Wi-Fi remote controlled RC car commanded by a C# application & esp32 Arduino Wi-Fi module
Abstract
En aquest treball es pretén construir un robot a partir d’un cotxe teledirigit que serà controlat mitjançant Wi-Fi. El robot es controlarà des d’una aplicació Windows programada en llenguatge C#, que es connectarà amb el mòdul Wi-Fi ESP32 programat en llenguatge Arduino, per tal de donar instruccions al robot. El robot conté una càmera IP per la qual el seu operador pot accedir en directe a la visió del robot i el pot controlar des del seu PC mitjançant un controlador Xbox.
Full text
Universitat Polit` ecnica de Catalunya Bachelor’s degree in Industrial Electronics and Automatic Control Engineering Bachelor’s Thesis WIFI REMOTE CONTROLLED RC CAR COMMANDED BY A C# APPLICATION & ESP32 ARDUINO WI-FI MODULE Author: Guillem Cornella Barba Eudald Sangen ´ ıs Rafart Supervisor: Leslie Tekamp Ra´ul Ben ´ ıtez Iglesias June 22, 2020
Wi-Fi Robot Eudald Sangen´ıs Summary English: In this project, it is expected to build a robot from an RC car that will be controlled through Wi-Fi. The robot will be controlled from a Windows application programmed in the C# language, that will be connected to the ESP32 Wi-Fi module, programmed in Arduino language, to give instructions to the robot. The robot contains an IP camera whereupon its operator can access live to the robot’s vision and he can control it from his PC through an Xbox controller. Key words: Windows application, C#, Arduino, ESP32 Wi-Fi module, IP camera & Xbox controller. Catal`a: En aquest treball es pret´en construir un robot a partir d’un cotxe teledirigit que ser`a controlat mitjan¸cant Wi-Fi. El robot es controlar`a des d’una aplicaci´o Windows programada en llenguatge C#, que es connectar`a amb el m`odul Wi-Fi ESP32 programat en llenguatge Arduino, per tal de donar instruccions al robot. El robot cont´e una c`amera IP per la qual el seu operador pot accedir en directe a la visi´o del robot i el pot controlar des del seu PC mitjan¸cant un controlador Xbox. Paraules clau: aplicaci´o Windows, C#, Arduino, m`odul Wi-Fi ESP32, c`amera IP & controlador Xbox. Castellano: En este trabajo se pretende construir un robot a partir de un coche teledirigido que ser´a controlado mediante Wi-Fi. El robot se controlar´a desde una aplicaci´on Windows programada en lenguaje C#, que se conectar´a con el m´odulo Wi-Fi ESP32 programado en lenguaje Arduino, para dar instrucciones al robot. El robot contiene una c´amara IP con lo cual su operador puede acceder en directo a la visi´on del robot y lo puede controlar desde su PC mediante un controlador Xbox. Palabras clave: aplicaci´on Windows, C#, Arduino, m´odulo Wi-Fi ESP32, c´amara IP & controlador Xbox. 1
Wi-Fi Robot Eudald Sangen´ıs Acknowledgements This project was made possible thanks to the collaboration between Universitat Polit`ecnica de Catalunya (UPC), the University of Colorado Colorado Srings (UCCS) and the funding of the Balsells Foundation. We would like to thank our advisor Leslie Tekamp from the electrical and computer engineering department for his weekly supervision and for his advice. Last but not least, we would like to thank the UCCS IT department for their readiness at all times. This project has been challenging and multidisciplinary. Without your help achieving the end results would not have been possible. We thank you all for giving us the opportunity of learning as much as we have learned. 2
Wi-Fi Robot Eudald Sangen´ıs Scope Project Justification: Among all the proposals provided from Prof. Tekamps, this project was chosen because of our interest in designing and coding an interface that could be able to control a robot through Wi-Fi. Project Scope: This project consists of creating a remote-controlled robot using a Windows application written in C# that sends data to the robot through Wi-Fi. The microcontroller of the robot is an ESP32 module and it receives the data from the computer in order to control the robot. Project Deliverables: At the beginning of the project, a schedule was elaborated in order to know when to deliver the sections that were being done: MONTH WEEK WORK JANUARY 19 - 25 Create a list of materials and do research 26 - 1 Buy materials and plan the project FEBRUARY 2 - 8 Dissemble RC car, understand its functionality and draw the electrical scheme draft 9 - 15 Create the interface ‘PC-camera’ using C# 16 - 22 Create the interface ‘PC-robot’ using C# 23 - 29 Test the ESP32 Wi-Fi module and control lights, servos and the motors of the robot MARCH 1 - 7 Design and 3D print all support Assemble and weld all the components of the robot 8 - 14 Spring Brake 15 - 21 Code the behavior of the Xbox controller with C# 22 - 28 Control the robot with the PC using the ESP32 29 - 4 Test the robot and resolve errors APRIL 5 - 11 Write the report 15 - 21 19 - 25 Deliver the report 26 - 2 - MAY 3 - 9 - 10 -16 - Table 1: Schedule of the project. Project Success: The project will be determined successfully if the robot runs perfectly using the designed application. 3
Wi-Fi Robot Eudald Sangen´ıs Contents 1 Introduction 8 2 List of materials 9 3 Hardware 10 3.1 MotorDriverL298N ............................ 10 3.2 Servomotors................................. 13 3.2.1 Camera control - MG996R . . . . . . . . . . . . . . . . . . . . . 13 3.2.2 Steer control - SG90 . . . . . . . . . . . . . . . . . . . . . . . . 14 3.3 Powersupply-Battery........................... 15 3.4 ESP32 DEVKITV1 Wi-Fi Module . . . . . . . . . . . . . . . . . . . . . 16 4 Telecommunications 17 4.1 NetworkSystems .............................. 17 4.2 Wi-Fiprotocols............................... 20 4.2.1 TCP................................. 20 4.2.2 UDP................................. 21 4.3 Network’ssecurity ............................. 22 4.4 Deviceconnection.............................. 24 5 Application Code 25 5.1 Libraries................................... 26 5.1.1 NuGetlibraries ........................... 26 5.1.2 Systemlibraries........................... 27 5.2 Camera characteristics & code . . . . . . . . . . . . . . . . . . . . . . . 28 5.3 Controllercode ............................... 32 5.3.1 Keyboard .............................. 32 5.3.2 XboxController........................... 34 6 Arduino Code 38 6.1 Setup..................................... 39 6.2 Loop..................................... 40 7 Building the robot 43 7.1 Research and material acquisition . . . . . . . . . . . . . . . . . . . . . 43 7.2 Disassemble the RC car . . . . . . . . . . . . . . . . . . . . . . . . . . 44 7.3 Designofa3Dsupport........................... 44 7.4 Initial connections in the breadboard and first test of the code . . . . . 45 7.5 Weld the components to the PCB circuit board . . . . . . . . . . . . . 45 7.6 Final base design and 3D supports . . . . . . . . . . . . . . . . . . . . 46 7.7 Assembling ................................. 48 7.8 Electricaldiagram.............................. 49 4
Wi-Fi Robot Eudald Sangen´ıs 7.8.1 Analysis of the servo motors . . . . . . . . . . . . . . . . . . . . 49 7.8.1.1 Servo’s current consumption without load: . . . . . . . 50 7.8.1.2 Servo’s current consumption with load: . . . . . . . . . 52 7.8.2 Current analysis of the DC motors . . . . . . . . . . . . . . . . 53 7.8.2.1 Current analysis of the DC without friction: . . . . . . 53 7.8.2.2 Current analysis of the DC with friction: . . . . . . . . 54 7.8.3 Current consumption . . . . . . . . . . . . . . . . . . . . . . . . 54 7.9 Finaltesting................................. 55 8 Problems faced & solutions 56 9 Conclusion 57 A C# Code 60 A.AMainWindow.xaml.cs............................ 60 A.BMainWindow.xaml ............................. 70 A.CIpWindow.xaml.cs ............................. 74 A.DIpWindow.xaml............................... 75 A.EGlobalVariables.cs ............................. 79 B Arduino Code 80 C Electrical Diagram 87 5
Wi-Fi Robot Eudald Sangen´ıs List of Figures 1 Spot Boston Dynamics’ robot [1]. . . . . . . . . . . . . . . . . . . . . . 8 2 RoverNASA’srobot[2]. .......................... 8 3 Pulse Width Modulation explanation [7]. . . . . . . . . . . . . . . . . . 10 4 H-Bridge schema using switches to control the rotation direction. [7]. . 11 5 This is the module L298N with two terminal blocks for the motors A and B, and one terminal block for the GND pin, the VCC to power the motor and a 5V pin (input or output). . . . . . . . . . . . . . . . . . . 11 6 Input pins from left to right: ENA, IN1, IN2, IN3, IN4, ENB. . . . . . 12 7 Angle position depends on the length of the pulse [8]. . . . . . . . . . . 13 8 MG996RServomotor............................. 13 9 SG90Servomotor............................... 14 10 LG-ZJ04Servomotor............................. 14 11 SG90 Servomotor inside the LG-ZJ04. . . . . . . . . . . . . . . . . . . 14 12 1600 mAh 7.4V 2S 25C LI-PO Rechargeable Battery [12]. . . . . . . . . 15 13 Block diagram ESP32 [14]. . . . . . . . . . . . . . . . . . . . . . . . . . 16 14 ESP32 DEVKIT V1 - DOIT, version with 30 GPIOs, PINOUT scheme [15]. ..................................... 16 15 Networkstructure. ............................. 18 16 TCP/IPstack[16]. ............................. 18 17 TCP/IP protocol [17]. . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 18 UDPprotocol[18]. ............................. 21 19 Network structure with protocol communication. . . . . . . . . . . . . . 22 20 Structurecode. ............................... 25 21 Camera AMCREST IP2M-841B . . . . . . . . . . . . . . . . . . . . . . 28 22 Cisco Surveillance IP Camera 2500 . . . . . . . . . . . . . . . . . . . . 28 23 Keyboard Controller application interface. . . . . . . . . . . . . . . . . 32 24 IPWindowinterface............................. 34 25 Xbox Controller application interface. . . . . . . . . . . . . . . . . . . . 35 26 Acquisition of the materials. . . . . . . . . . . . . . . . . . . . . . . . . 43 27 Disassemble of the RC car. . . . . . . . . . . . . . . . . . . . . . . . . . 44 28 Design of a support base using SketchUp 3D Software. ......... 44 29 First testing of the code using a breadboard. . . . . . . . . . . . . . . . 45 30 PCBcircuitboard ............................. 46 31 Battery support design. . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 32 Smartphone support design. . . . . . . . . . . . . . . . . . . . . . . . . 47 33 Servo motor support design. . . . . . . . . . . . . . . . . . . . . . . . . 47 34 Usage of a methacrylate plastic base. . . . . . . . . . . . . . . . . . . . 48 35 Assemblingprocess.............................. 48 36 Electricaldiagram. ............................. 49 37 Servo’s current consumption without load. . . . . . . . . . . . . . . . . 51 38 Servo’s current consumption with loads. . . . . . . . . . . . . . . . . . 52 6
Wi-Fi Robot Eudald Sangen´ıs 39 Motor’s current consumption without friction. . . . . . . . . . . . . . . 54 40 Upper picture of the final testing. . . . . . . . . . . . . . . . . . . . . . 55 41 Frontal picture of the final testing. . . . . . . . . . . . . . . . . . . . . 55 42 Xbox Controller application interface. . . . . . . . . . . . . . . . . . . . 73 43 IPWindowinterface............................. 78 List of Tables 1 Scheduleoftheproject............................ 3 2 Listofmaterials. .............................. 9 3 How to configured the motor rotation with the pins IN1, IN2, IN3, IN4. 12 4 Wi-Fi router properties depending on which band is working on. . . . . 17 5 The existing types of Wi-Fi and the ability to connect of the devices. . 24 6 Power study of the robot. . . . . . . . . . . . . . . . . . . . . . . . . . 54 7
Wi-Fi Robot Eudald Sangen´ıs 1 Introduction Robots are remotely controlled from their beginnings. They have infinity applications in several different camps. In the industry they are usually used to do repetitive tasks and help carrying weights but also they are used for avoiding the direct manipulation of toxic components, in the health field there are robots that help to make surgeries like the appendicitis operation. . . All these robots have in common two things. The first one is that there is a person who makes the decisions for the robot and order what the robot has to do. The second one is that since the operator has to make a decision, they have to be able to see the vision of the robot. Like Spot [1] a Boston Dynamics robot which is mainly used to carry weight for avoiding causing injuries to workers, which is remotely controlled with a controller where the user can see the vision of the robot in a live feed and it connects to a wireless network to communicate. This robot also has an autonomous mode that records in a video all his activity. However, there are also robots that are autonomous and send afterwards images to the user to make a report. For example, Rovers [2] (NASA’s robot which is working in Mars) is able to send images to Earth. On the other hand, rescue robots [3] also have remote-control system but also have an autonomous system because when natural disasters happen, usually the communications also fall down. Even though, it is to important to note that there is always a record of images of the rescue mission. Figure 1: Spot Boston Dynamics’ robot [1]. Figure 2: Rover NASA’s robot [2]. The purpose of this report is to explain how it was created a remote-control robot through Wi-Fi from an RC car and be able to reproduce creation in a project class of the University of Colorado Colorado Springs. This will ensure that the students learn about Wi-Fi communications, and the importance of creating robots that can see the environment. The robot was controlled from a Windows application programmed in the C# language. The application sent the datagrams needed to give instructions to the ESP32 Wi-Fi module program in the Arduino language. The robot also contains an IP camera whereupon its operator can access live to the robot’s vision and control it from their PC. To maneuver the robot, an Xbox controller is connected to a PC through an USB input. The C# application can read the data from the Xbox controller, process it and send the data packages back to the robot. 8
Wi-Fi Robot Eudald Sangen´ıs 3.3 Power supply - Battery Two Li-Po batteries LG-DJ02 [12] with 1600 mAh, 7.4 V were used. The first one was meant to supply the DC motors and the ESP32 Wi-Fi module and the second one was used to supply the servos. These batteries are the originals from the Laegendary RC car. One external battery to supply the servomotors was used since the ESP32 does not supply the necessary current to power the servomotors. Thus, only one battery is used to feed two servos. In the first prototype a power bank of 2000 mAh, 5 V was used to supply the servomotors but it did not work because, the power bank does not allow low currents. Therefore, when the servo is stopped it uses 6 mA to maintain the torque, and when the servo is turning, it uses 150 mA. The reason for this bad functioning was because a power bank has an internal battery of 3.7 V and in order to get 5 V from an output there is a step-up converter. Such a circuit draws current even when not loaded with anything and it drains the battery even when not charging anything. To try to fix the problem of the low current when the servomotor is stopped, to cut the power supply a relay was used. This solution worked well because the consumption was null but also, the response was slow. Also, it was tried to put a resistor in series with the servo to increase the current to 6 mA to 20 mA but when the servo was turning, it did not have sufficient torque to move it. So finally, the LG-DJ02 Li-Po battery was used. Figure 12: 1600 mAh 7.4V 2S 25C LI-PO Rechargeable Battery [12]. •Peak performance: Increase the runtime. •Stable performance: A LiPo will hold a steady voltage for most of your run. •More energy density: LiPo battery have about four times the energy of density of nickel-cadmium or nickel-metal hydride batteries 15
Wi-Fi Robot Eudald Sangen´ıs 3.4 ESP32 DEVKITV1 Wi-Fi Module To communicate the laptop with the robot the ESP32 DEVKITV1 module [13] was used. The communication via Wi-Fi was established but also, this module has Bluetooth. The ESP32 was chosen because it is easy to implement it with Arduino and have more pins than the ESP8266 Wi-Fi module. According to the datasheet, the ESP32 overview specifications are the following ones: Figure 13: Block diagram ESP32 [14]. •Dual Core •RAM of 512 KB •Frequency of 240 MHz •Admitted peripherals see figure 13. •Admit Wi-Fi and Bluetooth communication. •30 pins Figure 14: ESP32 DEVKIT V1 - DOIT, version with 30 GPIOs, PINOUT scheme [15]. 16
Wi-Fi Robot Eudald Sangen´ıs 4 Telecommunications The purpose of this section is to explain how the module ESP32 and the camera interact via wireless communication with the computer. 4.1 Network Systems The wireless communication is one in which the ends of the communication (sender/receiver) are not linked by a physical means of propagation, but rather that, the modulation of electromagnetic waves through space is used. In this sense, the physical devices are only present in the signal transmitters and receivers. Wi-Fi is a technology that enables the wireless interconnection of electronic devices. The enabled devices (such as personal computers, telephones, televisions ...) can connect to each other or to the internet through a wireless network access point. This communication can be produced in short distances, normally, a Wi-Fi router working on the traditional 2.4 GHz band reach up to 150 feet (46 m) indoors and 300 feet (92 m) outdoors unless there are used repeaters to maximizes the range. But the routers that use the 5.0 GHz band, reach up approximately one-third of these distances. The range is lower in the 5 GHz band because higher frequencies cannot penetrate solid objects, such as walls and floors. However, higher frequencies allow data to be transmitted faster than lower frequencies, so the 5 GHz band allows you to upload and download files faster. Frequency Theoretical Speed Indoor distance Outdoor distance 2.4 GHz 300 Mpbs 150 feet - 46 m 300 feet - 92 m 5.0 GHz 900 Mbps 50 feet - 15 m 100 feet - 30 m Table 4: Wi-Fi router properties depending on which band is working on. So, to communicate the computer to the robot a 2.4 GHz band was used because long distances were needed to run. Thanks to using the 2.4 GHz band, the computer was inside the house and the robot was outside about 100 feet and the communication was fluid. The router created a LAN1to be able to interconnect the applications without needed to connect to the internet as it is illustrated in figure 15. A WAN2network is not used because there is no need to cover more space than a campus. 1Local Area Network: is a computer network that interconnects computers within a limited area. 2Wide Area Network: is a telecommunications network that extends over a large geographical area for the primary purpose of computer networking. 17
Wi-Fi Robot Eudald Sangen´ıs Figure 15: Network structure. This communication was possible due to how the packet of the data was structured. Those packets were layered as illustrated in figure 16. Figure 16: TCP/IP stack [16]. 18
Wi-Fi Robot Eudald Sangen´ıs The following example pretends to explain how the stack of the message that the camera sends to the laptop to be able to reproduce the video would be: The video is the user data. The camera send the video through a HTTP3protocol to distribute the video. ————————————————————————————————— 1. The application data is the video plus the protocol to distribute it. ————————————————————————————————— The camera has a port (origin port). The laptop has a port (destination port). The user data has to be sent it to another device by TCP or UDP. ————————————————————————————————— 2. The TCP Header is the protocol that indicates how the devices have to communicate, in this case UDP, plus the origin and destined ports. ————————————————————————————————— The camera has an IP (origin IP). The laptop has an IP (destination IP). ————————————————————————————————— 3. The IP Header is the origin IP plus the destination IP. ————————————————————————————————— 4. The Ethernet Header is how the data can be linked, in that case is used a PPP 4 protocol. ————————————————————————————————— 3Hypertext Transfer Protocol: is an application protocol for distributed, collaborative, hypermedia information systems.. 4Point-to-Point Protocol: is a data link layer communications protocol between two applications directly without any host or any other networking in between. 19
Wi-Fi Robot Eudald Sangen´ıs 4.2 Wi-Fi protocols 4.2.1 TCP The Transmission Control Protocol (TCP) is one of the main protocols of the Internet protocol suite. Therefore, the entire suite is commonly referred to as TCP/IP. TCP provides reliable, ordered, and error-checked delivery of a stream of bytes between applications running on hosts communicating via an IP network. TCP is connectionoriented, and a connection between client and server is established before data can be sent (see figure 17). The Transmission Control Protocol provides a communication service at an intermediate level between an application program and the Network Protocol (see figure 16). It provides host-to-host connectivity at the transport layer of the Internet model. At the transport layer, TCP handles all handshaking and transmission details and presents an abstraction of the network connection to the application typically through a network socket interface. A TCP connection is managed by an operating system through a resource that represents the local end-point for communications, the Internet socket. During the lifetime of a TCP connection, the local end-point undergoes a series of state changes as illustrated in figure 17: Figure 17: TCP/IP protocol [17]. TCP is used for organizing data in a way that ensures the secure transmission between the server and the client. It guarantees the integrity of data sent over the network, regardless of the amount. 20
Wi-Fi Robot Eudald Sangen´ıs 4.2.2 UDP User Datagram Protocol is mainly used for establishing loss-tolerating and low-latency connections between applications on the internet. It is used as an alternative to TCP protocol. UDP provides checksums for data integrity, and port numbers for addressing different functions at the source and destination of the datagram. It has no dialogues between the server and the client (see figure 18), and thus there is no guarantee of delivery, ordering, or duplicate protection. UDP sends data packets (datagrams) to recipients without checking for missed packets. It is used when error correction is not necessary, and speed is desirable. UDP is often used for online games and live broadcasts. Figure 18: UDP protocol [18]. That properties make the User Datagram Protocol ideal to the project because it is sent two types of data, the camera sends video and the computer sends strings to the ESP32 module. When the video is sent it is interesting to have a low-latency connection and if a frame of the video is lost is not a big deal. And about the datagrams that the computer sends every 40 ms if a package is lost it makes no difference because the robot has inertia and there is no effect if the interval is upped at 80 ms. So, in that case, it was more important the velocity than the security of receiving the data. 21
Wi-Fi Robot Eudald Sangen´ıs Figure 19: Network structure with protocol communication. 4.3 Network’s security At the university there were three networks, each one with its security: •UCCS-Guest [19] ”is an open (unsecure) network which does not require any username or password to join - similar to your experience at a place such as a coffee shop. This network does not provide full access. It offers basic http and https access (for general web browsing), but no access to on-campus resources such as network drives. Advanced functionality is limited (some ports and applications are blocked). Should you need access to on-campus resources such as shared network drives, you will need to utilize the UCCS-Wireless network.” •UCCS-Wireless [19] ”is the full-access secure network intended to be used by all students, faculty, and staff. This network uses WPA2 Enterprise encryption to ensure security. This network provides full access to the Internet. This network requires a username and password to join.” •Eduroam [19] ”is the secure, world-wide roaming access service developed for the international research and education community. Eduroam allows students, researchers, faculty and staff from participating institutions to obtain Internet connectivity across campuses and when visiting other participating institutions. In other words, if you visit another participating campus, you would connect to the Eduroam wireless network there and enter your UCCS username and password as your credentials in order to gain wireless internet access at that location.” This network uses WPA2 Enterprise encryption to ensure security. Finally, due to the COVID-19, the project has to be finished with the home’s network with a WPA2 personal encryption to ensure security. This network provides full 22
Wi-Fi Robot Eudald Sangen´ıs access to the Internet and there are no limits in advance functionalities. This network requires a password to join. To sum up, these are the differences in the security’s types: •WPA2 personal: requires a password •WPA2 enterprise: requires a username an a password •Unsecure: no requisites but with university restrictions. 23
Wi-Fi Robot Eudald Sangen´ıs 4.4 Device connection UCCS-Guest Unsecure UCCS-Wireless WPA2 enter. Eduroam WPA2 enter. Home Network WPA2 per. Amcrest No connect No connect No connect Connect Cisco No connect Connect No connect Connect Cell Phone Connect Connect Connect Connect ESP32 Connect No connect No connect Connect Table 5: The existing types of Wi-Fi and the ability to connect of the devices. After evaluating the options, the cell phone’s camera was the best option to connect to the UCCS-Guest and therefore it was chosen but it was not able to visualise the images on the application. Seeing that, the IT department was asked and said that to send video with this network was not possible due to the university policies. The university does not want the students to install cameras on campus so, the ports of the network were blocked. Therefore, the IT department proposed to create a network only for this project with WPA2 personal security but owing to the emergency sanitary of COVID-19 the university had to be closed. Hence, the project was required to be finished at home. Finally, due to the AMCREST and Cisco camera had been returned it was chosen to use the cell phone camera to lower the cost of the project. 24
Wi-Fi Robot Eudald Sangen´ıs Finally, the fourth one is used to record a video of the robot’s view and save it to the indicated folder. This function is similar to the ”Connect” function but it has to be added the video format, the type of video and the way how to save it. Also, this function has to have into account if the connection is already set up to close it and restart it. ///number of record button c l i c k s count btn recd++; /// i f the streaming i s enable i t c l o s e i f (videoCapture1 .IsEnabled )videoCapture1 .Stop() ; /// Create a new videoCapture1 object l i k e the connect func . . . . ///Audio S etti n gs l i k e the connect func tion . . . /// save the video to myvideos f o l d e r videoCapture1 .Output Filename = Environment .GetFolderPath(Environment .SpecialFolder .MyVideos) + $”\\ vid {count btn recd }.mp4” ; ///Output video format videoCapture1 .Output Format =new VFWMVOutput() ; ///Type of video videoCapture1 .Mode =VisioForge .Types . VFVideoCaptureMode .IPCapture ; ///Method to s t a r t connection videoCapture1 .Start( ) ; Listing 10: Fragment of the ”Record function”. 31
Wi-Fi Robot Eudald Sangen´ıs 5.3 Controller code To be able to control the robot two applications were designed. The first one was a prototype because a platform was needed to try to send data to the robot. In this prototype the robot was controlled through the laptop’s keyboard. The second one was the final application controlled with the Xbox controller. 5.3.1 Keyboard Firstly, an application to be able to send data to the ESP32 module and see how it responded was designed. The main problem that was faced was the maneuverability of the robot. To pilot the car the velocity and the steer are needed to be controlled. Hence, a packet of data (datagram) sent via UDP protocol to the ESP32 every 40 ms. This packages contained the information to say to move forward ”x” distance when the event of the key ”w” was key up and the velocity. So, to control the steer four buttons were created, and to manipulate the velocity a slicer was designed As illustrated in figure 23. This type of control created two problems. The first one was that the robot did not change the direction unless the ”x” distance had finished and if the robot wanted to continue to keep forward, the ”w” key was needed to press again. The second one occurred when the velocity was tried to be set up because it was not very intuitive and dynamic. Figure 23: Keyboard Controller application interface. 32
Wi-Fi Robot Eudald Sangen´ıs The following fragment of code illustrates how to declare a private function to raise buttons events when a keyboard key is pressed. /// Keyboard co ntro l pr ivate void key event(object sender ,KeyEventArgs e) { switch (e.Key) { case Key .A: BtnA .RaiseEvent (new RoutedEventArgs(Button .ClickEvent) ) ; break ; /// Changing the Key .A, the keyword key i s changed . . . } } Listing 11: Fragment of the function to raise buttons events when a keyboard key is press. The next fragment of code is an example of how the application is able to send the datagrams via UDP protocol to the ESP32 when button Ais pressed. ///Text to send to the arduino Global Variables .cmd = ”A” ; ///Connect to the ip & port of the ESP32 udpSender .Connect (Global Variables .ip rob , Global Variables .port rob ) ; ///Transform to codi ASCII the ”A” Byte [ ] sendBytes = Encoding .ASCII .GetBytes(Global Variables .cmd) ; ///send ”A” in codi ASCII udpSender .Send (sendBytes ,sendBytes .Length) ; Listing 12: Fragment of the ”A function” From this example is easy to extrapolate how functions should be programmed to go forward, backward, and rightward. To connect to the IP and the port of the ESP32 device, the IP Window (see in figure 43) was designed. This interface asks for the camera’s and the robot’s IP number and the camera’s and robot’s port number to be set up. Those values had to be entered manually and saved clicking to the ”Apply” button. 33
Wi-Fi Robot Eudald Sangen´ıs Figure 24: IP Window interface. 5.3.2 Xbox Controller Once the robot had been driven, improve the maneuverability of the car buying an Xbox controller was decided. So, another interface (see figure 42) was decided to be built but maintaining the IP Window interface (see figure 43). The Xbox commander is constituted by two joysticks with two-axis each one (jx0, jy0, jx1, jy1) and 14 buttons (four arrows, back, start, X, A, B, Y, RB, LB, RT, and LT ). It is only used ten commands over eighteen possible to control the robot: •X- Connect camera •Y- Disconnect camera •A- Available start driving •RB - Film video •LB - Take snapshot •jx0 - Camera tilt •jx1 - Steer •jy1 - Speed •Left arrow - Turn off light •Down arrow - Turn on light 34
Wi-Fi Robot Eudald Sangen´ıs Figure 25: Xbox Controller application interface. In order to read the joysticks values, a timer object that raises his event every 40 ms and set it up when the main window interface is initialized was required. /// creat e a new timer ob ject pr ivate s t a t i c Timer timer ; public MainWindow () { InitializeComponent( ) ; /// Set timer up timer =new Timer() ; /// I n t e r v a l 40ms timer .Interval = 40; /// Call the fun ction when the event r a i s e . timer .Elapsed += new ElapsedEventHandler(t h i s .timer Tick) ; ///Enable the timer timer .Enabled =true ; } Listing 13: Create a timer object and set it up. Every 40 ms was called the timer Tick function. This one calls the m CJoy.Update function to update the data from the joystick and from the Joystick Check Data function to read the data, processed and send it to the ESP32 module. 35
Wi-Fi Robot Eudald Sangen´ıs /// Joystic k Declaration private Ojw .CJoystick m CJoy =new Ojw .CJoystick(Ojw .CJoystick .ID 0 ) ; public void timer Tick(object sender ,EventArgs e) { // update j o y s t i c k information m CJoy .Update() ; // Joystick Data Check Joystick Check Data( ) ; } Listing 14: timerTickfunction. As was said before, to read the data, processed, and send it to the ESP32 module the Joystick Check Data function was used. So, the function is divided by regions (arrows, buttons, RB and LB buttons, joystick values, and send and print data to the text boxes of the interface). The following fragment of code is just a few lines of the function Joystick Check Data, just to give an idea of how to program this function. This example shows how to call the function Connect if the X button from the Xbox controller is pressed, how to obtain the joysticks information, and finally, how to send the information through the UDP protocol. ///BUTTON X i f (m CJoy .IsDown Event(Ojw .CJoystick .PadKey .Button3) == true && XBOX X == false) { t h i s .Dispatcher .Invoke ( ( ) => { BtnConnect .RaiseEvent (new RoutedEventArgs(Button .ClickEvent) ) ; }) ; XBOX X =true ; } //DATA FROM JOYSTICK ///camera servo jx0 =Math .Round(m CJoy .dX0 , 1) . ToString() ; /// s t e e r servo jx1 =Math .Round(m CJoy .dX1 , 1) . ToString() ; /// v e l o c i t y jy1 = (1−Math .Round(m CJoy .dY1 , 1) ) . ToString( ) ; 36
Wi-Fi Robot Eudald Sangen´ıs //SEND DATA TO ESP32 /// information to send var joystick values = ” jx0 ” + jx0 + ” jx1 ” + jx1 + ” jy1 ” + jy1 + ”LED” + l e d s ; /// Establish the connection with the ip & port udpClient .Connect(Global Variables .ip rob , Global Variables .port rob ) ; ///Transform the information to ASCII Byte [ ] sendBytes jx0 =Encoding .ASCII . GetBytes(joystick values) ; ///Send the information udpClient .Send(sendBytes jx0 ,sendBytes jx0 .Length) ; Listing 15: Joystick Check Data function. Finally, to see the full code implementation is possible to access in the following GitHub [21]. 37
Wi-Fi Robot Eudald Sangen´ıs 6 Arduino Code The purpose of this section is to explain how the Arduino code works step by step. In other words, how the ESP32 receives the data from the laptop, how it processed and which is the response. Firstly, the ESP32 board was installed in the Arduino program. 1. In your Arduino IDE, go to File – Preferences. 2. Enter https://dl.espressif.com/dl/package esp32 index.json into the “Additional Board Manager URLs” field. Then, click the “OK” button. 3. Open the Boards Manager. Go to Tools ¿ Board ¿ Boards Manager. . . 4. Search for ESP32 and press install button for the “ESP32 by Espressif Systems“. 5. It should be installed after a few seconds. Secondly, the ESP32 libraries were installed and declared. #include <WiFiUdp . h> #include <WiFi . h> #include <ESP32Servo . h> #include <MapFloat . h> Listing 16: Libraries necessary for Arduino code. •WiFiUdp.h: This library is used to create the instances necessary to send and receive UDP packets. •WiFi.h: This library does not support the WPA2-Enterprise security, only allow to connect to the networks with WPA2-Personal security (SSID & password). •ESP32Servo.h: This library permits the ESP32 board to control the servomotors using the ESP32 PWM timers programming with Arduino. •MapFloat.h: This library contains the mapFloat function which re-maps a floating-point number from one range to another. The next step after declaring the libraries was to define the variables that were used during the program. In the following fragment of code is possible to see how the name of the router and the password can be declared. const char ∗s s i d = ” name of router ” ; const char ∗password = ”password goes here”; Listing 17: Defining the router variables. 38
Wi-Fi Robot Eudald Sangen´ıs 6.1 Setup The connection between the WiFi module and the network needed to be completed. The begin method was called on the WiFi object, passing as arguments the SSID and the password variables. This line started the connection to the network: WiFi . begin( ssid , password ) ; Listing 18: Start to try to connect to the network specified. After beginning the connection it was necessary to wait until the ESP32 was connected. To do so, a while loop was created to print in the serial window a list of points every 100 ms to show that the program is waiting to connect to the network. while (WiFi . statu s () != WL CONNECTED) { Serial .print(”.”) ; delay(100) ; } Listing 19: Waiting the connection to be established. Once the connection was done, the serial monitor printed the IP of the module and the port. These values in the IP Window of the C# application were uploaded to establish a connection between the PC with the ESP32. Serial .println(WiFi . loca l I P () ) ; udp . begin( udpPort ) ; Serial .println( udpPort ) ; Listing 20: Print the IP and the Port in wich the ESP32 module is connect. Now the program was ready to run its main loop to control the outputs of the robot (lights, servo motors and DC motors). 39
Wi-Fi Robot Eudald Sangen´ıs 6.2 Loop The C# application every 40 ms was sending the data received by the Xbox controller to the Arduino module through an UDP protocol. This protocol was basically sending a packet of information in ASCII format using the IP and port of the module. This packet of data is a String type of 22 characters. Every character uses 1 byte (8 bits), then the packet in total uses 8*22 = 176 bits or 22 bytes from a maximum capacity of 255 bits. int packetSize = udp . parsePacket () ; i f (packetSize) { IPAddress remoteIp = udp . remoteIP () ; int len = udp . read ( packetBuffer , 255) ; i f ( len >0) packetBuffer [ len ] = 0; String udp packet sent = packetBuffer ; } Listing 21: Transform the ASCII packet information to string. This String was named “udp packet sent” and it contained 4 sub-packages of information which needed to be separated in order to obtain the information needed for each output. For instance, as for the servo controls, a substring was created in order to obtain information regarding the tilt value expressed as “jx0—“. The program then converted these Strings into ‘int’ variables. String v a l t i l t c a m e r a = udp packet sent . substring(0 ,6) ; val tilt camera = val tilt camera .substring(3 ,6) ; float v a l t i l t c a m e r a f = v a l t i l t c a m e r a . toFloat val tilt camera f = val tilt camera f −0.5; float servo cam angle = mapFloat ( v a l t i l t c a m e r a f , −0.5 , 0 .5 , 170.0 , 10.0) ; int servo cam angle int = (i nt )servo cam angle ; Listing 22: Processing the tilt data from the string udp packedt sent. The same structure was used for the Servo that is controlling the steer. To light on the lights of the robot a substring was also used in order to obtain just the information needed. Then, the program analyzed the String and compared it with the 3 different options available. If it had received “LED1” for example, it would create a Boolean variable called ‘led’ and then the light could turn on. 40
Wi-Fi Robot Eudald Sangen´ıs Figure 32: Smartphone support design. The servomotor needed also a cavity. In order to guarantee its locomotion, the next image is the same support from figure 32 from the bottom. Figure 33: Servo motor support design. Once the project evolved, it was found experimentally that the printed base support was not that stable as was thought. A new idea popped up where a methacrylate plastic base with more rigidity was able to sustain all the components using only once a structural piece instead of two. At this stage, the final shape of the robot was the following: 47
Wi-Fi Robot Eudald Sangen´ıs Figure 34: Usage of a methacrylate plastic base. 7.7 Assembling When every part was properly designed and tested, the assembly took place. After checking there was no short-circuits problems in the electrical system, the robot was finally tested. At this point, the robot had the next appearance: Figure 35: Assembling process. 48
Wi-Fi Robot Eudald Sangen´ıs 7.8 Electrical diagram The scheme that summarize the electrical diagram was done: Figure 36: Electrical diagram. 7.8.1 Analysis of the servo motors At this stage of the project, an analysis of the current that flowed across the servos was done. For obtaining its values, an Arduino program was coded using the analog pins. The servos were connected to them and a voltage fall was detected in four resistors of value 10 Ω. Always bearing in mind whenever the domain of degrees of the servo motors, some test programs were used. As an example, the following code shows an iterative loop that increased the servo’s degrees and after calculated the mean current consumption. In a physical way, the next conversion was applied for converting an analog value into current: Resistance =1 1 R1+1 R2+1 R3+1 R4 =10 4(1) As it is already known: R1 = R2 = R3 = R4 = 10Ω 49
Wi-Fi Robot Eudald Sangen´ıs Therefore, the current is: I=5V 1023(analog)·V(analog)·4 10(1 Ω)·1000mA 1A(2) The following code was written: for (int servo1Position = 20; servo1Position < 160; servo1Position += 2){ t++; servo1.write(servo1Position); delay(200); voltageVal1 = analogRead(analogPin0); currentVal1=((5.0*voltageVal1)/1023.0)* (4.0/10.0)*1000.0; c1+=currentVal1; mean1=c1/(t*2); servo2Position+=1; servo2.write(servo2Position); delay(200); voltageVal2 = analogRead(analogPin1); currentVal1=((5.0*voltageVal1)/1023.0)* (4.0/10.0)*1000.0; c2+=currentVal2; mean2=c2/t; sum=mean1+mean2; Listing 26: how to convert from an analog value into current) For understanding the current consumption of the servos, two plots were obtained: with and without a load in the servo that controlled the audiovisual devices. 7.8.1.1 Servo’s current consumption without load: Because of the presence of an excessive number of pikes, an average value was also plotted by the program meansum. It can be seen that the mean current consumption had a value of around 150 mA in the case of both servos when they were running at the same time. Once they stopped, the current consumption reduced at an approximate value of 6 mA. Another important value to analyze is the 600 mA peak, which was nothing that the LI-PO battery could not supply. Nonetheless, the mean value was required for obtaining consumption. 50
Wi-Fi Robot Eudald Sangen´ıs With detail in the first part of the graph, an initial current peak can be observed when powering occurs for the first time. The reason why this happens is because of inertia reasons when starting. In a stationary state, only its armature resistance limits the current flow. Once the motor starts functioning, an opposite power supply is generated. This fact explains that when a servo makes small movements, higher peaks can be observed in contrast with moving the servos a larger distance. In the latter case, the effective voltage is less and current drops. Figure 37: Servo’s current consumption without load. 51
Wi-Fi Robot Eudald Sangen´ıs 7.8.1.2 Servo’s current consumption with load: Once the cameras were added to the system, some changes were detected: Figure 38: Servo’s current consumption with loads. The current consumption was detected to increase up to a 175 mA. Although, the steering servo was not tested with load because of difficulties moving the wheels in a stationary state, it was estimated to reach 200 mA values. 52
Wi-Fi Robot Eudald Sangen´ıs 7.8.2 Current analysis of the DC motors Due to the incapability of obtaining the DC motors current consumption, the Arduino Serial Plotter was used again with the following current estimation using analog values: I= AnalogV alue 1024 ·5000mV −OffsetV alue(mV ) Sensitivity(mV/A)(3) For this purpose, the following code was made to print the values in the Serial Plotter: // Variables used and declaration of values const int currentPin = A0; int sensitivity = 100; //it is a 20A type sensor int adcValue= 0; int offsetVoltage = 2500; double adcVoltage = 0; double currentValue = 0; // Then the calculations adcValue = analogRead(currentPin); adcVoltage = (adcValue / 1024.0) *5000; currentValue = ((adcVoltage-offsetVoltage)/sensitivity); Serial.println(currentValue); Listing 27: Program to calculate the current from DC motors. 7.8.2.1 Current analysis of the DC without friction: An overheat of the sink in the first prototype was detected. Doing a consummation study it was seen that the motors when were stopped it consumes about 1000 mA. To sort out this problem, in the final project a relay was added. This relay cut the power supply of the motor driver L982N when the motors were stopped. As illustrated in figure 39 there are four relevant aspect to discuss. •When the joystick of the Xbox Controller is in the center, the current is 0 mA so the motors are stopped. •When the motors turn on for the first time it makes a 5 A pick. That is another reason that produces a heat of the sink because the L982N sink allows a great dissipation until 3 A. So, to improve this project is recommended to use the L923D motor driver. •When the motors turn on for the second time due to the wheels’ inertia because there is no friction the current necessary to start is less than 5 A, specifically 3 A. 53
Wi-Fi Robot Eudald Sangen´ıs •The mean value of the current drawn when the motors are running at maximum speed is 1100 mA. Figure 39: Motor’s current consumption without friction. 7.8.2.2 Current analysis of the DC with friction: Unlikely for the analysis, there is no data obtained with the DC motors with load. Because the robot could not be in touch with the floor during the serial data measurement with Arduino, this study was not possible. However, it is estimated that this consumption is higher if the terrain and the elevation are modified. 7.8.3 Current consumption The total consumption of the robot was 1.34 A when the robot had no friction but when it comes to the friction, the current estimation was about 2.79 A but it depended on the type of the terrain and the slop. No friction/ No load Friction/ load Servomotors 150 mA 175-200 mA DC motors 1100 mA 2000-2500 mA LED 20 mA x 2 LEDS 20 mA x 2 LEDS ESP32 50 mA 50 mA TOTAL MAX 1340 mA 2790 mA Table 6: Power study of the robot. 54
Wi-Fi Robot Eudald Sangen´ıs 7.9 Final testing Figure 40: Upper picture of the final testing. Figure 41: Frontal picture of the final testing. 55
Wi-Fi Robot Eudald Sangen´ıs 8 Problems faced & solutions •Steer’s servo: To control the steer of the robot the SG90 servomotor was used. The servo originally from the RC car LG-ZJ04 could not be implemented because it has five wires and the ”servo.h” Arduino’s library can only control a servo with three wires. So, it was opted to disassemble the original servo and fit the i inside the casing of the LG-ZJ04 (see page 14). •Power supply: In order to power the robot a power bank of 5V and 2000 mAh was chosen. The main problem was that the power bank can not supply low currents and when the servomotors stop, the servos consume 6 mA and while they are turning they consume 150 mA. So, when the power bank had to provide only 6 mA, due to the internal circuit it could not supply it (see pag. 15). •Wi-Fi module: Firstly, the ESP8266 module was used. Seeing that this module did not have sufficient pins to control all the outputs, the ESP32 Wi-Fi module was bought. The ESP8266 has seven outputs otherwise the ESP32 has more than twenty output pins and the project needed nine outputs to control the robot (see page 16). •University’s Wi-Fi: The biggest problem of the project was how to connect to the university network with the Wi-Fi module and the camera. None of the three networks could suit the project. The security of Eudoram and UCCS-Wireless was WPA2 enterprise and the ESP32 can not connect to it. In regard to the UCCS- Guest, the camera can not send the video through the router ports because of the university’s policies not allow it. To sort out the problem, the IT department offered to integrate another wireless network only for the project but due to the COVID-19, the project had to be finished at home (see page 23). •Cameras: A few cameras were tested before chose the camera of the cell phone. The AMCREST IP camera was bought, nevertheless, it did not connect to the university’s Wi-Fi since it did not support WPA2-Enterprise. After that, the Cisco Surveillance IP Camera 2500 was bought but when it arrived some pieces were missing. Seeing that, it was returned. So finally because all the people have a cell phone and it connects to the university network, the camera of the cell phone was used. This change allowed to reduce the cost of the project. (see page 27) •Overheating of the sink: A high heat of the sink of the motor driver L982N was experimented. This heat was due to the initialize current when the motors turn on because a 5 A peak of current was produced and the motor driver only allows 3 A. So, the L923D motor driver is recommended to replace the L982N (see page 53). 56
Wi-Fi Robot Eudald Sangen´ıs } /// Create a new videoCapture1 o bje ct videoCapture1 .IP Camera Source =new VisioForge . Types .Sources .IPCameraSourceSettings() { URL = ” http :/” + Global Variables .ip cam + ”:” +Global Variables .port cam .ToString() + ”/ video” , Type =VisioForge .Types .VFIPSource . HTTP MJPEG LowLatency }; ///Audio Se ttin g s videoCapture1 .Audio PlayAudio =videoCapture1 . Audio RecordAudio =false ; /// save the video to myvideos f o l d e r with the name /// of vid {count btn recd }.mp4 videoCapture1 .Output Filename =Environment . GetFolderPath(Environment .SpecialFolder . MyVideos) + $”\\ vid {count btn recd }.mp4” ; ///Output video format videoCapture1 .Output Format =new VFWMVOutput() ; ///Type of video videoCapture1 .Mode =VisioForge .Types . VFVideoCaptureMode .IPCapture ; videoCapture1 .Start( ) ; } } ///Camara snapshoot pr ivate void Snapshot(object sender ,RoutedEventArgs e) { i f (connect cam == false) { MessageBox .Show(” F i r s t Connect the Camera ”) ; } e l s e { ///number of snapshot button c l i c k s count btn snap++; /// save the snapshot to mypictures f o l d e r with the ///name of frame {count btn snap }. jpg videoCapture1 .Frame Save(Environment .GetFolderPath (Environment .SpecialFolder .MyPictures) + $”\\ frame 63
Wi-Fi Robot Eudald Sangen´ıs {count btn snap }.jpg” , VisioForge .Types . VFImageFormat .JPEG, 85) ; } } #endregion CAMARA'S CONTROLS //−−−−−−−−−−−−−−−−−−−−−−−−−− // IP CONFING WINDOW //−−−−−−−−−−−−−−−−−−−−−−−−−− #region IP CONFING WINDOW pr ivate void Ip config Click(object sender , RoutedEventArgs e) { IP Window iP Window =new IP Window () ; iP Window .Show ( ) ; } #endregion IP CONFING WINDOW //−−−−−−−−−−−−−−−−−−−−−−−−−− // Joystick //−−−−−−−−−−−−−−−−−−−−−−−−−− #region Joystick /// Joystic k Declaration private Ojw .CJoystick m CJoy =new Ojw .CJoystick( Ojw .CJoystick .ID 0 ) ; ///Timer to p e r i o d i c a l l y check j oy s ti ck connection private Ojw .CTimer m CTmr Joystick =new Ojw .CTimer ( ) ; // a n a l i z e data and send i t #region Joystick data pr ivate void FJoystick Check Data() { #region Joystick Check Data #region arrows /// l eds o f f −arrow l e f t i f (m CJoy .IsDown(Ojw .CJoystick .PadKey .POVLeft) ) { leds = ”2”; } 64
Wi-Fi Robot Eudald Sangen´ıs /// leds on −arrow down e l s e i f (m CJoy .IsDown(Ojw .CJoystick .PadKey .POVDown) == true) { leds = ”1”; } /// maintain the l ed st at us e l s e { leds = ”0”; } #endregion arrows #region buttons // Button A i f (m CJoy .IsDown(Ojw .CJoystick .PadKey .Button1) == true) { /// Error −Null values ip rob or port rob i f (Global Variables .ip rob == null | | Global Variables .port rob == 0) { MessageBox .Show(” IP Robot or Port Robot isn 't fulfilled . ” ) ; } /// Error −Port number overflow e l s e i f (Global Variables .port rob >65536) { MessageBox .Show(” Robot 's Port number i s overflowed . ” + ”\n”+”I t has to be smaller than 65536”) ; } /// Error −IP number overflow e l s e i f (Global Variables .ip rob .Length >15) { MessageBox .Show(” Robot 's IP number i s overflowed . ” + ”\n”+”I t has to be smaller than 15 digits”) ; } /// Error −F i r s t f i l l the Ip Configuration : e l s e { ///To be able to send the j o y s i t c k s /// value data to the robot start pilot =true ; } 65
Wi-Fi Robot Eudald Sangen´ıs } // Button X i f (m CJoy .IsDown Event(Ojw .CJoystick .PadKey .Button3) == true && XBOX X == false) { t h i s .Dispatcher .Invoke ( ( ) => { BtnConnect .RaiseEvent (new RoutedEventArgs( Button .ClickEvent) ) ; }) ; XBOX X =true ; } // Button Y i f (m CJoy .IsDown Event(Ojw .CJoystick .PadKey .Button4) == true) { t h i s .Dispatcher .Invoke ( ( ) => { BtnDisconnect .RaiseEvent (new RoutedEventArgs( Button .ClickEvent) ) ; }) ; } #endregion buttons #region R &L buttons //Button LB −− Photo i f (m CJoy .IsDown Event(Ojw .CJoystick .PadKey .Button5) == true) { t h i s .Dispatcher .Invoke ( ( ) => { BtnSnap .RaiseEvent (new RoutedEventArgs(Button . ClickEvent) ) ; }) ; } //Button RB −− Record i f (m CJoy .IsDown Event(Ojw .CJoystick .PadKey .Button6) == true) { t h i s .Dispatcher .Invoke ( ( ) => { BtnRecord .RaiseEvent (new RoutedEventArgs(Button . ClickEvent) ) ; }) ; } 66
Wi-Fi Robot Eudald Sangen´ıs #endregion R &L buttons #region J o yst icks values //DATA TO SEND: //camera servo jx0 =Math .Round(m CJoy .dX0 , 1) . ToString() ; // s t e e r servo jx1 =Math .Round(m CJoy .dX1 , 1) . ToString() ; // v e l o c i t y and d i r e c t i o n jy1 = (1−Math .Round(m CJoy .dY1 , 1) ) . ToString( ) ; jx0 =jx0 .Replace( ” ,” , ” . ” ) ; jx1 =jx1 .Replace( ” ,” , ” . ” ) ; jy1 =jy1 .Replace( ” ,” , ” . ” ) ; i f (jx0 == ”0”) jx0 = ”0.0”; i f (jx1 == ”0”) jx1 = ”0.0”; i f (jy1 == ”0”) jy1 = ”0.0”; i f (jx0 == ”1”) jx0 = ”1.0”; i f (jx1 == ”1”) jx1 = ”1.0”; i f (jy1 == ”1”) jy1 = ”1.0”; //DATA TO SHOW TO THE SCREEN var c a m e r a t i l t = (Math .Round(m CJoy .dX0 , 1) −0) ∗ (170 −10) / (1 −0) + 10; var s t e e r = (Math .Round(m CJoy .dX1 , 1) −0) ∗(110 −70) / (1 −0) + 70; var velocity = 0.0; var l i g h t s = ”” ; var drive = ””; i f ((1 −Math .Round(m CJoy .dY1 , 1) ) >= 0.5) velocity = ((1 −Math .Round(m CJoy .dY1 , 1) ) −0.5 −0) ∗(100 −0) / ( 0 .5 −0) + 0; e l s e velocity = ((1 −Math .Round(m CJoy .dY1 , 1) ) −0.5 −0) ∗(100 −0) / ( 0 .5 −0) + 0; i f (l e d s == ”1”) { lights = ”on ” ; l i g h t s b o o l =true ; } 67
Wi-Fi Robot Eudald Sangen´ıs i f (l e d s == ”2”) { lights = ” off ” ; l i g h t s b o o l =f a l s e ; } i f (l e d s == ”0”) { i f (l i g h t s b o o l == true)lights = ”on ” ; e l s e lights = ” o f f ” ; } i f (start pilot == true)drive = ” Available ” ; e l s e drive = ” Disable ” ; #endregion J oys tick s values //SEND DATA & RECIVE #region Send &p ri nt data t h i s .Dispatcher .Invoke ( ( ) => { i f (start pilot == true) { // send data to arduino var joystick values = ” jx0 ” + jx0 + ” jx1 ” + jx1 + ” jy1 ” + jy1 + ”LED” + l eds ; udpClient .Connect(Global Variables .ip rob , Global Variables .port rob ) ; Byte [ ] sendBytes jx0 =Encoding .ASCII .GetBytes( joystick values) ; udpClient .Send(sendBytes jx0 ,sendBytes jx0 . Length) ; } // pri nt data lb joysticks .Text = ” Camera : ” + c a m e r a t i l t + ”degrees” + ”\n\n”+” Steer : ” + steer + ”degrees \n\n” + ” Velocity : ” + velocity ; lb buttons .Text = ” Drive : ” + drive + ”\n\n” + ”Lights : ” + lights ; }) ; #endregion Send &pr in t data #endregion Joys tick Check Data 68
Wi-Fi Robot Eudald Sangen´ıs } #endregion Joys tick data // timer event #region timer event public void timer1 Tick 1 (object sender ,EventArgs e ) { // update j o y s t i c k information m CJoy .Update() ; // Joystick Data Check FJoystick Check Data( ) ; } #endregion timer event #endregion Joystick } } 69
Wi-Fi Robot Eudald Sangen´ıs A.B MainWindow.xaml <Window xmlns=”http ://schemas . microsoft . com/ winfx /2006/xaml/ presentation” xmlns :x=”http :// schemas . m icr os oft . com/ winfx /2006/ xaml” xmlns :d=”http :// schemas . microsoft . com/ ex pr es si on / blend /2008” xmlns :mc=”http :// schemas . openxmlformats . org /markup− com pat ibil ity /2006” xmlns :l o c a l=”clr −namespace :WIFI Robot Controlled Xbox” xmlns :WPF=”cl r −namespace :VisioForge .Controls .UI .WPF; assembly=VisioForge .Controls .UI” x:Class=”WIFI Robot Controlled Xbox .MainWindow” mc:Ignorable=”d” Title=”WIFI RC ROBOT”Height =”515” Width=”1000” ResizeMode =”NoResize”Background=”Gainsboro”> <!−−Outside Grid−−> <Grid x:Name=”OutsideGrid”> <!−−Work Space Defin itio n −−> <Grid .ColumnDefinitions> <ColumnDefinition Width=”15”/> <ColumnDefinition Width=”450”/> <ColumnDefinition Width=”∗”/> <ColumnDefinition Width=”15”/> </Grid .ColumnDefinitions> <Grid .RowDefinitions> <RowDefinition Height=”10”/> <RowDefinition Height=”336”/> <RowDefinition Height=”∗”/> <RowDefinition Height=”10”/> </Grid .RowDefinitions> <!−−Camara Grid−−> <Grid x:Name=”InnerCameraGrid”Grid .Column=”1” Grid .Row =”2”> <Grid .ColumnDefinitions> <ColumnDefinition Width=”20”/> <ColumnDefinition Width=”∗”/> <ColumnDefinition Width=”∗”/> <ColumnDefinition Width=”20”/> </Grid .ColumnDefinitions> <Grid .RowDefinitions> <RowDefinition Height=”20”/> <RowDefinition Height=”50”/> 70
Wi-Fi Robot Eudald Sangen´ıs <RowDefinition Height=”50”/> <RowDefinition Height=”∗”/> </Grid .RowDefinitions> <!−−Buttons Camara−−> <Button x:Name=”BtnConnect”Click=”Connect”Content=” Connect” Height=”35” Width=”140” Grid .Column=”1” Grid .Row=”1”> </Button> <Button x:Name=”BtnDisconnect”Click=”Disconnect” Content=”Disconnect” Height=”35” Width=”140” Grid .Column=”2” Grid .Row=”1”> </Button> <Button x:Name=”BtnRecord”Click=”Record”Content=” Record” Height=”35” Width=”140” Grid .Column=”1” Grid .Row=”2”> <Button .ContentTemplate> <DataTemplate> <Image Source=”C:\Users\carle\Documents\ GitHub\WIFI Robot Controlled Xbox\rec .png”VerticalAlignment=” Center”Height=”50”/> </DataTemplate> </Button .ContentTemplate> </Button> <Button x:Name=”BtnSnap”Click=”Snapshot”Content=” Snapshot” Height=”35” Width=”140” Grid .Column=”2” Grid .Row=”2”> <Button .ContentTemplate> <DataTemplate> <Image Source=”C:\Users\carle\Documents\ GitHub\WIFI Robot Controlled Xbox\snap .png”VerticalAlignment=” Center”Height=”20”/> </DataTemplate> </Button .ContentTemplate> </Button> </Grid> <!−−Controls Robot &Camara Grid−−> <Grid x:Name=”ControlsGrid”Grid .Column=”2” Grid .Row=”1”> <Grid .RowDefinitions> <RowDefinition Height=”15”/> <RowDefinition Height=”∗”/> 71
Wi-Fi Robot Eudald Sangen´ıs </Grid .RowDefinitions> <!−− Image −−> <Image Source=”C:\Users\carle\Documents\GitHub\ WIFI Robot Controlled Xbox\xbox controls .png”Stretch=” F i l l ” Grid .Row=”1”/> <Label Content=”Xbox Contr oll er Commands”Grid .Row=”1” FontSize=”25” VerticalAlignment=”Top”HorizontalAlignment=” Center”FontWeight=”Bold”Foreground=”#333333”/> <!−−IP c o n f igura t i o n Btn−−> <Button x:Name=”BtnIP”Height =”15” Width=”15” Grid . Column=”0” Grid .Row=”0” Click=” Ip config Click” VerticalAlignment=”Top”HorizontalAlignment=” Left ”Margin =”5 ,0 ,0 ,0” ToolTipService .InitialShowDelay=”500” ToolTipService .ShowDuration=”3000” ToolTipService . BetweenShowDelay=”10000” ToolTip=”Configurate IP.”> <Button .Template> <ControlTemplate> <Image Source=”C:\Users\carle\Documents\ GitHub\WIFI Robot Controlled Xbox\gear .png”/> </ControlTemplate> </Button .Template> </Button> </Grid> <!−− Sensoring Grid +Leds−−> <Grid x:Name=”Sensoring ”Grid .Column=”2” Grid .Row=”2”> <Label Content=”J oyst ick s information : ” HorizontalAlignment=”Left”VerticalAlignment=”Top”FontStyle=” Normal”FontSize=”14” Margin =”65 ,0 ,10 ,0” FontWeight=”Bold”/> <Label Content=”Buttons information : ” HorizontalAlignment=”Right”VerticalAlignment=”Top”FontStyle=” Normal”FontSize=”14” Margin =”10 ,0 ,65 ,0” FontWeight=”Bold”/> <TextBox x :Name=” lb joysticks”VerticalAlignment=”Top” HorizontalAlignment=”Left”Margin =”40 ,30 ,40 ,0” Height=”90” Width=”200” Background=”White”/> <TextBox x :Name=”lb buttons ”VerticalAlignment=”Top” HorizontalAlignment=”Right”Margin =”40,30,40,0” Height=”90” Width=”200” Background=”White”/> </Grid> <!−−Camara Vision−−> <Frame Grid .Column=”1” Grid .Row=”1” Height =”336” Width 72
Wi-Fi Robot Eudald Sangen´ıs A.E Global Variables.cs public c l a s s Global Variables { //ip variables pu bl ic s t a t i c s t r i n g ip cam ; pu bl ic s t a t i c s t r i n g ip rob ; // port v a r i a b l e s public s t a t i c int port cam ; public s t a t i c int port rob ; } 79
Wi-Fi Robot Eudald Sangen´ıs B Arduino Code // UDP WIFI TRANSMISSION BETWEEN ARDUINO AND VISUAL STUDIO // WIFI ROBOT CONTROLLED USING A XBOX CONTROLLER // EUDALD SANGEN S & GUILLEM CORNELLA // Include a l l the l i b r a r i e s #include <WiFiUdp . h>// f o r programming UDP r o ut i n es #include <ESP32Servo . h>// to c o ntr ol the servo motors #include <WiFi . h>// to connect to the WIFI module #include <MapFloat . h>// to be able to do Maps using f l o a t variables // Define the pins o f the motor s h i e l d module #define enA 14 // enable the motor A #define enB 32 // enable the motor B // Pins that act as a switch , to c o nt ro l the d i r e c t i o n of the motor : #define in1 27 #define in2 26 #define in3 25 #define in4 33 // Define the speed o f the motors , s t a r t i n g at 0 int motorSpeedA = 0; int motorSpeedB = 0; // Defining the servo motors Servo servo cam ; // The name of the servo that we are using f o r the camera co n tr o l Servo s e r v o s t e e r ; // The name of the servo that we are using f o r robot s t e e r i n g // Define the i n i t i a l p o s i t i o n degree o f the se rv os int initial pos cam = 90; // The i n i t i a l p o s i t i o n o f the camera w i l l centered at 90 degrees int i n i t i a l p o s s t e e r = 115; // The i n i t i a l p o s i t i o n o f the se rvo s t e e r w i l l be at 115 degr ees to have the robot s t r a i g h t int s erv o cam angl e int y = 0; // The past value of the var i a b l e that the servo had be fo re the new loop int servo steer angle int y = 0; // Define the PWM pins of the servos int servo cam pin = 4; 80
Wi-Fi Robot Eudald Sangen´ıs int s e r v o s t e e r p i n = 5 ; // Define the pins of the servos connected to the rel ay int servo cam relay = 18; int s e r v o s t e e r r e l a y = 19; // Define the router const char ∗s s i d = ”EBG3808 2.4 ” ;// The name of your WIFI router const char ∗password = ”ventana2 .4”;// The password of your router // Define v a r i a b l e s o f the incoming packets from the C# a p p li c a t io n WiFiUDP udp ; // Create a udp obj ec t unsigned int udpPort = 2000; // The port to l i s t e n to incoming packets char packetBuffer [50]; // Set up a b u f f e r f o r incoming packets ( abans era [ 5 0 ] ) // Other d e f i n i t i o n s #define LED 2 // Defining a LED connected to the GPIO 2 bool led ; // Define the variab l e ” led ” as a bool // Write the code to i n i t i a l i z e the board , c rea te the SETUP void setup() { Serial .begin(115200) ; // Sets the data r at e in b i t s per second ( baud ) f o r s e r i a l data transmission . delay(500) ; // Wait f o r 500ms pinMode(enA , OUTPUT) ; // Define the pins o f the motor s h i e l d as outputs pinMode(enB , OUTPUT) ; pinMode( in1 , OUTPUT) ; pinMode( in2 , OUTPUT) ; pinMode( in3 , OUTPUT) ; pinMode( in4 , OUTPUT) ; pinMode(LED, OUTPUT) ; // Define the LED that w i l l act as the robot 's lights pinMode( servo cam pin ,OUTPUT) ; pinMode(servo steer pin ,OUTPUT) ; pinMode( servo cam relay ,OUTPUT) ; pinMode(servo steer relay ,OUTPUT) ; 81
Wi-Fi Robot Eudald Sangen´ıs servo cam . attach ( servo cam pin ) ; // Attach the servo to the pin GPIO 4 , the same as D2 f o r the ESP8266 module s e r v o s t e e r . attach ( s e r v o s t e e r p i n ) ; // Attach the servo to the pin GPIO 5 , the same as D1 f o r the ESP8266 module servo cam . w rite ( i n i t i a l p o s c a m ) ; // Set the i n i t i a l position to 0 s e r v o s t e e r . write ( i n i t i a l p o s s t e e r ) ; // Set the i n i t i a l position to 45 digi t a lWri t e (LED, LOW) ; // Turn o f f the Led On Board // Wifi con f i g urati o n and connection : WiFi . begin( ssid , password ) ; // Connect to your WiFi router Serial .println(”” ) ; // Print a blank space Serial .print(”Connecting”) ; // Print ” Connecting ” to the S e r i a l Monitor while (WiFi . statu s () != WL CONNECTED) // Make the Led Flash while connecting to the w i f i router { Serial .print(”.”) ; // Print a dot ” .” while trying to connect digi t a lWri t e (LED, LOW) ; // Turn o f f the LED on board delay(250) ; // Wait f o r 250ms digi t a lWri t e (LED, HIGH) ; // Turn on the LED on board delay(250) ; // Wait f o r 250ms } // I f s u c c e s s f u l l y connected to the w i f i router , the IP Address and port are displayed in the s e r i a l monitor Serial .println(”” ) ; Serial .print(” S u c c e s s f u l l y connected to : ” ) ; Serial .println( s s i d ) ; Serial .print(”NodeMCU IP address : ” ) ; Serial .println(WiFi . loca l I P () ) ; udp . begin( udpPort ) ; // Once connection i s es tablish ed , you can s t ar t l i s t e n i n g to incoming packets . Serial .print(” Local Port : ” ) ; Serial .println( udpPort ) ; // Print the number of the port that 's going to be used } // Write the loop code to run the program void loop () { receive packet();} 82
Wi-Fi Robot Eudald Sangen´ıs // Waiting to r e c e i v e incoming UDP packets void receive packet() { int packetSize = udp . parsePacket () ; i f (packetSize) { IPAddress remoteIp = udp . remoteIP () ; int len = udp . read ( packetBuffer , 255) ; i f ( len >0) packetBuffer [ len ] = 0; String udp packet sent = packetBuffer ; // String that contains a l l the data sent by C#. Serial .print(”UDP packet sent by PC: ” ) ; Serial .println(udp packet sent); // Print in the s e r i a l monitor the long s t r i n g co nt ai ni ng a l l the information // SERVO CAMERA MOVEMENT String v a l t i l t c a m e r a = udp packet sent . substring(0 ,6) ; // Creating a substri ng from the packet sent to obtain information regarding the t i l t value ” jx0−−−” val tilt camera = val tilt camera .substring(3 ,6) ; // Creating a s ub st ri ng again to obtain the numeric v a r i a b l e s and removing the l e t t e r s ” jx0 ” float v a l t i l t c a m e r a f = v a l t i l t c a m e r a . toFloat ( ) ; // Converting the String into a f l o a t varia bl e val tilt camera f = val tilt camera f −0.5; // Substracting 0.5 to the value so we can have 0 in the the center ,−0.5 the minimum , and 0.5 the maximum Serial .print(”Value of the camera sent by c#:” ) ; Serial .println(val tilt camera f); float servo cam angle = mapFloat ( v a l t i l t c a m e r a f , −0.5 , 0 .5 , 170.0 , 1 0. 0) ; // Maping the value obtained , −0.5 in the j o y s t i c k equals 170 and 0.5 equals 10 int servo cam angle int = (i nt )servo cam angle ; // Converting the value in degrees into an <int >variable i f ( s er vo ca m a ng le in t == s er vo c am an gl e in t y ) { digi t a lWri t e ( servo cam relay ,LOW) ; servo cam . detach () ; Serial .println(” Servo camera OFF” ) ; delay(200) ; } e l s e i f ( s erv o c am a ng le in t != s er vo c am a ng le i nt y ) { digi t a lWri t e ( servo cam relay ,HIGH) ; servo cam . attach ( servo cam pin ) ; servo cam . write ( servo cam angle int ) ; // 83
Wi-Fi Robot Eudald Sangen´ıs Move the servo according to the degrees maped Serial .println(” Servo camera ON” ) ; Serial .print(”Angle of the camera 's servo : ” ) ; Serial .println(servo cam angle int); Serial .print(” Antique angle of the camera 's servo : ” ) ; Serial .println( se rvo cam a ngl e int y ) ; delay(200) ; } se rvo c am an gle int y=servo cam angle int ; // STEER OF THE ROBOT String v a l s t e e r = udp packet sent . substring(6 ,12) ; // Creating a substri ng from the packet sent to obtain information regardi ng the s t e e r value ” jx1−−−” val steer = val steer .substring(3 ,6) ; // String sent by the PC to c ont r ol the robot and go r i g h t and l e f t float v a l s t e e r f = v a l s t e e r . toFloat () ; // Converting the String into a f l o a t varia bl e v a l s t e e r f = v a l s t e e r f −0.5; // Substracting 0.5 to the value so we can have 0 in the the center ,−0.5 the minimum , and 0.5 the maximum Serial .println(” v a l s t e e r f : ” ) ; Serial .println( v a l s t e e r f ) ; float s e r v o s t e e r a n g l e = mapFloat ( v a l s t e e r f , −0.5 , 0.5 , 85.0 , 145.0) ; // Maping the value obtained , −0.5 in the j o y s t i c k equals 85 −l e f t and 0.5 equals 145 −right . Serial .println(servo steer angle); int servo steer angle int = (i n t )servo steer angle ; // Converting the value in degrees into an <int >variable i f ( s e r v o s t e e r a n g l e i n t == s e r v o s t e e r a n g l e i n t y ) { digi t a lWri t e (servo steer relay ,LOW) ; s e r v o s t e e r . detach ( ) ; delay(200) ; } e l s e i f ( s e r v o s t e e r a n g l e i n t != s e r v o s t e e r a n g l e i n t y ) { digi t a lWri t e (servo steer relay ,HIGH) ; s e r v o s t e e r . attach ( s e r v o s t e e r p i n ) ; s e r v o s t ee r . write ( s e r v o s t e e r a n g l e i n t ) ; // Move the servo according to the degrees maped Serial .println(” Servo s t e e r ON” ) ; Serial .print(” Angle of the s t e e r : ” ) ; Serial .println(servo steer angle int); Serial .print(” Antique angle o f the s t e e r servo : ” ) ; Serial .println(servo steer angle int y); delay(200) ; 84
Wi-Fi Robot Eudald Sangen´ıs } s e r v o s t e e r a n g l e i n t y = s e r v o s t e e r a n g l e i n t ; // ROBOT FORWARD AND BACKWARDS String v a l v e l = udp packet sent . substring(12,18) ; // Creating a substri ng from the packet sent to obtain information regardi ng the s t e e r value ” jy1−−−” v a l v e l = v a l v e l . substring(3 ,6) ; // String sent by the PC to con tro l the robot and go forward and backwards float v a l v e l f = v al v e l . toFloat ( ) ; // Converting the String into a f l o a t varia bl e val vel f = val vel f −0.5; // Substracting 0.5 to the value so we can have 0 in the the center ,−0.5 the minimum , and 0.5 the maximum Serial .print(” Value of the v e l o c i t y : ” ) ; Serial .println( v a l v e l f ) ; //LEDS ON −LEDS OFF String l i g h t = udp packet sent . substring(18,22) ; // Creating a substri ng from the packet sent to obtain information regarding the LED value ”LED−” i f ( l i g h t==”LED1” ){// When the su bs tring analyzed i s ”LED1” then l i g h t on the LED led = true ; digi t a lWri t e (LED,HIGH) ; } e l s e i f ( l i g h t==”LED2” ){// When the su bs tring analyzed i s ”LED2” then l i g h t o f f the LED led = false ; digi t a lWri t e (LED, LOW) ; } e l s e i f ( l i g h t==”LED0” ){// When the su bs tring analyzed i s ”LED0” , i f the LED was on , turn i t off , and v ice versa . digi t a lWri t e (LED,LOW) ; i f ( led==true )dig i t alWr i t e (LED,HIGH) ; e l s e di g i talW r i te (LED,LOW) ; } // Y−a xi s used f o r forward and backward c o nt r ol // to go BACKWARDS i f ( v a l v e l f <−0.1) { // Set Motor A backward digi t a lWri t e ( in1 , HIGH) ; digi t a lWri t e ( in2 , LOW) ; // Set Motor B backward 85
Wi-Fi Robot Eudald Sangen´ıs digi t a lWri t e ( in3 , HIGH) ; digi t a lWri t e ( in4 , LOW) ; // Convert the d e c l i n i n g Y−a x is re ad in gs f o r going backwards , −0.1 equals 400 and −0.5 equals 1000. The PWM s i g n a l i s i n c r e a s i n g the motor speed . float motorSpeedA f = mapFloat ( v a l v e l f , −0.1 , −0.5 , 400.0 , 1000.0) ; float motorSpeedB f = mapFloat ( v a l v e l f , −0.1 , −0.5 , 400.0 , 1000.0) ; motorSpeedA = ( i nt )motorSpeedA f ; // convert the f l o a t variab l e of the speed of the motor A to an int motorSpeedB = ( i n t )motorSpeedB f ; // convert the f l o a t variab l e of the speed of the motor B to an i nt } // to go FORWARD e l s e i f ( v a l v e l f >0.1) { // Set Motor A forward digi t a lWri t e ( in1 , LOW) ; digi t a lWri t e ( in2 , HIGH) ; // Set Motor B forward digi t a lWri t e ( in3 , LOW) ; digi t a lWri t e ( in4 , HIGH) ; // Convert the growing Y−ax is r ea di ngs f o r going forward , 0 .1 equa ls 400 and 0.5 e qu al s 1000. The PWM s i g n a l i s i n c r e a s i n g the motor speed . float motorSpeedA f = mapFloat ( v a l v e l f , 0.1 , 0. 5 , 400.0 , 1000.0) ; float motorSpeedB f = mapFloat ( v a l v e l f , 0. 1 , 0.5 , 400.0 , 1000.0) ; motorSpeedA = ( i nt )motorSpeedA f ; // convert the f l o a t variab l e of the speed of the motor A to an int motorSpeedB = ( i n t )motorSpeedB f ; // convert the f l o a t variab l e of the speed of the motor B to an i nt } // I f j o y s t i c k stays in middle the motors are not moving ( to avoid warming the motors ) e l s e { motorSpeedA = 0 ; motorSpeedB = 0; } } analogWrite(enA , motorSpeedA ) ; // Send PWM s i g n a l to motor A analogWrite(enB , motorSpeedB ) ; // Send PWM s i g n a l to motor B } 86
Wi-Fi Robot Eudald Sangen´ıs C Electrical Diagram 87