Hummer Bot 1.0 Instruction Manual V.2.0
User Manual:
Open the PDF directly: View PDF .
Page Count: 113
Download | ![]() |
Open PDF In Browser | View PDF |
Hummer-Bot-1.0 Instruction Manual V.2.0 Data Version Description Author 2017/9/16 V-1.0 Create Baron.li 2017/9/23 V-1.1 modify Ken.chen 2017/10/18 V-1.2 Review Ken.chen 2017/11/15 V-1.3 Review Zach.zhou 2017/12/8 V-1.4 Review Baron.li 2018/3/11 V-1.5 2018/4/20 V-1.6 2018/5/3 V-1.7 2018/6/26 V-1.8 Modifyir/blutooth module Add device instructions Add installation details picture Ken.chen Baron.li Baron.li 1. Fix Servo lib conflict with pwm Luna/ken 2. Review and fix some error 2019/1/2 V-1.9 1. Installation modification Carl 2. Bom modification 2019/1/9 V-2.0 Install and modify the acrylic sheets Carl 1 Table Of Contents Chapter1 Introduction ........................................................................................................................................ 1 1.1 Writing Purpose ................................................................................................................................... 1 1.2 Product Introduction ............................................................................................................................ 1 Chapter2 Preparations ........................................................................................................................................ 3 About Arduino uno r3 ................................................................................................................................ 3 2.1 Development environment Arduino IDE ............................................................................................. 4 2.1.1 Install the IDE ........................................................................................................................... 4 Chapter3 Experiments ...................................................................................................................................... 13 3.1 Assembly of the Car........................................................................................................................... 13 3.1.1 Motor installation .................................................................................................................... 13 3.1.2 Wheel and drive module installation ...................................................................................... 16 3.1.3 Tracking module installation .................................................................................................. 19 3.1.4 Lower acrylic plate copper column installation and motor wiring ......................................... 21 3.1.5 Keywish Uno R3 board installation ....................................................................................... 23 3.1.6 Battery box installation ........................................................................................................... 24 3.1.7 Servo installation .................................................................................................................... 25 3.1.8 Infrared obstacle avoidance module installation..................................................................... 27 3.1.9 Voltage display module and DC head installation .................................................................. 28 3.1.10 Infrared remote control receiver installation......................................................................... 30 3.1.11 Overall assembly................................................................................................................... 31 3.1.12 Expansion board wiring diagram .......................................................................................... 32 3.2 Hummer Bot Module experiment ...................................................................................................... 34 3.2.1 Walking Principle of the Car .................................................................................................. 34 3.2.2 Infrared Obstacle Avoidance .................................................................................................. 41 3.2.3 Infrared Tracing ...................................................................................................................... 52 3.2.4 Ultrasonic Obstacle Avoidance............................................................................................... 62 3.2.5 Infrared Remote Control ......................................................................................................... 76 3.2.6 Mobile Phone Bluetooth Control ............................................................................................ 88 3.2.7 PS2 Handle (Optional) ............................................................................................................ 98 2 Chapter1 Introduction 1.1 Writing Purpose The purpose of this manual is to create a fast, practical and convenient development learning platform for the vast number of electronic enthusiasts and let them grasp the Arduino and its extended system design methods and design principles, as well as the corresponding hardware debugging methods. This manual will lead you to learn every function of "Hummer-Bot" step by step and open a new "Hummer-Bot" journey for you. It is divided into two parts: 1. Preparation chapter, which mainly introduces the use of common Arduino development software and some downloading and debugging skills. 2.Experiment chapter, which contains hardware and software. The hardware part mainly introduces the functions and principles of each module; the software part mainly introduces each part of the program. This manual is a specifications for "Hummer-Bot" , the file whose format is PDF which is in the CD along with our product requires the corresponding software to open. It contains detailed schematic diagrams and complete source codes for all instances, the codes won't have any mistake under our strict test. In addition, the library files used in the source codes are put into the corresponding path, you only need to see corresponding phenomenon of the car and personally experience the process of experiment by downloading the source codes to Arduino via the serial port emulator. This manual is very suitable for students and electronic enthusiasts to learn, all course videos will be synchronized to https://github.com/keywish/keywish-hummer-bot,please real-time synchronization of the latest information 1.2 Product Introduction "Hummer-Bot" is a multifunctional car based on the Arduino UNO and L298N motor. Compared with the traditional car, "Hummer-Bot" is also equipped with wireless control (Bluetooth, infrared, WIFI and so on); ultrasonic; infrared. It can trace and avoid obstacles automatically, of course, makers can also automatically control the car with wireless and make full use of each module, as well as integrate all kinds of related sensors to make the car more intelligent, which is more challenging. "Hummer-Bot" has various types of information, technical manuals, routines, etc., which can teach you step by step. Each electronic fan can use it easily to achieve their desired function. Product Features ◆ Three groups of black line infrared tracing module ◆ Two groups of infrared obstacle avoidance module ◆ Ultrasonic obstacle avoidance ◆ Four DC motor drive 1 ◆ Two 3000mZh, 3.7V rechargeable lithium battery with longer endurance ◆ Remaining capacity of battery real-time detection ◆ Infrared remote control ◆ Bluetooth app control ◆ PS2 handle control (optional) Product Device List 2 Chapter2 Preparations About Arduino uno r3 In "Hummer-bot", we used the Arduino uno r3 as the main control board, which has 14 digital input/output pins (6 of which can be used as PWM output), 6 analog inputs, and a 16 MHz ceramic resonator, 1 USB connection, 1 power socket, 1 ICSP head and 1 reset button. It contains everything that supports the microcontroller; You just need to connect it to a computer via a USB cable or start with an AC-DC adapter or battery. Technical specifications: Working voltage: 5V Input voltage: USB powered or external 7V~12V DC input Output voltage: 5V DC output and 3.3V DC output and external power input Microprocessor: ATmega328 (Chip data sheet is in the documentation) Bootloader:Arduino Uno Clock frequency: 16 MHz Support USB interface protocol and power supply (without external power supply) Support ISP download function Digital I/O port: 14 (4 PWM output ports) Analog input port: 6 DC Current I/O Port: 40mA DC Current 3.3V Port: 50mA Flash memory: 32 KB (ATmega328) (0.5 KB for bootloader) SRAM :2 KB (ATmega328) EEPROM:1 KB (ATmega328) Size:75x55x15mm 3 2.1 Development environment Arduino IDE 2.1.1 Install the IDE AduinoIDE is an open source software and hardware tool written by open source software such as Java, Processing, and avr-gcc. It is an integrated development environment that runs on a computer. It can write and transfer programs to the board. The major feature of the IDE is cross-platform compatibility for Windows, MaxOSX, and Linux. Only a simple code base is needed, and the creators can create personalized home internet solutions through the platform, such as remote home monitoring and constant temperature control and so on. In this tutorial, we use the version is 1.6.0, download address is:https://www.arduino.cc/en/Main/OldSoftwareReleases#previous,After opening the link, we can see the interface as shown in Figure 2.1.1. In this interface, we can see the different versions of the IDE and different operating environments. Everyone can download according to their own computer system, of course, There will be a downloaded installation package on our companion CD, but only the Windows version, because this tutorial is all running under Windows system. Figure 2.1.1 ArduinoIDE download interface After the downloading, we will get a compressed package as shown in Figure 2.1.2. The compressed package will be decompressed. After decompression, the files in Figure 2.1.3 are extracted. The “drivers” is the driver software. When the “Arduino.exe” is installed, it will be Install the driver automatically. Because the installation of "arduino.exe" is very simple, it will not be explained here. It is recommended to exit the anti-virus software during the installation process, otherwise it may affect the installation of the IDE. After 4 the installation is complete, click "arduino.exe" again to enter the IDE programming interface. Figure 2.1.2 Arduino IDE Installation Package Figure 2.1.3 Extracted files When finish the installation of the IDE,we need to connect to the Arduino mainboard,click“My Computer”→“Properties”→“Device Manager”→ “Viewing Ports (COM and LTP)”,If you can see as the Figure 2.1.4 Figure 2.1.4 Driver installation success interface That indicates the driver has been installed successfully. At this time we open the IDE, select the corresponding development board model and port in the toolbar to use normally. If you see Figure 2.1.5, it means that the computer does not recognize the development board and you need to install the driver yourself. 5 Figure 2.1.5 Driver is not successfully installed interface Note: 1)If you connect the controller board to the computer, the computer does not respond. Right-click "My Computer" and select Open Device Manager then find viewing port (com & lpt). If there is no com or lpt, or only an unknown device, there is a problem with the controller board or the USB cable. 2)Right-click "My Computer" and select Device Manager, find the viewing ports (COM and LPT). If there is a yellow Arduino UNO exclamation point, this means you need to install the driver yourself. 3)If you install the driver again and again, it eventually fails. Please uninstall the driver and re-install> install the driver automatically> restart the computer. 2.1.2 Install Driver 1、If your computer is a Windows 7 system 1)Right-click on "My Computer" and open the Device Manager, find viewing the ports (COM and LPT). At this point you will see a "USB Serial Port", right-click "USB Serial Port" and select the "Update Driver Software" option. 6 Figure 2.1.6 Updated Driver Interface 2)Next, select the "Browse my computer for driver software" option. Figure 2.1.7 Driver Update Selection Screen 7 3)Finally select the driver file named "FTDI USB Drivers" located in the "Drivers" folder of the Arduino software download. Figure 2.1.8 Driver file selection interface 4)If you have already installed, the following figure will automatically inform you that the driver was successful. 8 Figure 2.1.9 Driver Installation Successful Interface At this time, we return to the "Device Manager" interface, the computer has successfully identified Arduino, as shown in the below Figure 2.1.10 .then open the Arduino compilation environment, you can open the Arduino trip. Figure 2.1.10 Driver Success Recognition Interface Note: 9 In Win10 system, some Arduino are connected to the computer (non-genuine chips are difficult to identify), the system will automatically download the corresponding driver, no need to install the driver by yourself, but in Win7 system, you need to manually install driver according to the above steps. In addition, we can see that the USB serial port is identified as COM15 in the above figure, but it may be different with different computer, you may be COM4, COM5, etc., but USB-SERIAL CH340, this must be the same. If you do not find the USB serial port, you may have installed it incorrectly or the system is incompatible. 2、If your computer is a Windows 8 system: Before installing the driver, you should save the files you are editing because there will be several shutdowns during the operation. 1)Press "Windows key" + "R" 2)Iput shutdown.exe / r / o / f / t 00 3)Click the "OK" button. 4)The system will reboot to the "Select an option" screen 5)Select "Troubleshooting" from the "Select an option" screen 6)Select "Advanced Options" from the "Troubleshoot" screen 7)Select “Windows startup settings screen” from “Advanced Options” 8)Click the "Restart" button 9)The system will reboot to the “Advanced Boot Options” screen 10)Select "Disable Driver Signature Enforcement" 11)Once the system is booted, you can install Arduino driver the same as Windows7 3、If your computer is a Windows XP system: The installation steps are basically the same as for Windows 7, please refer to the above Windows 7 installation steps. 2.1.3 IDE Interface Introduction Nextly,we introduce the Arduino IDE interface, firstly enter the software directory. Then you can see the arduino.exe file and double-click to open the IDE. As shown in Figure 2.1.11. Figure 2.1.11 Software Catalog 1、The first thing you can see is the interface of the following figure. The functions of the toolbar buttons are "Compile" - "Upload" - "New Program" - "Open Program" - "Save Program" - "Serial Monitor" , as shown in Figure 2.1.12. 10 Figure 2.1.12 Arduino IDE Interface 2.There are 5 menus on the menu bar, but we mainly introduce File and Tools. Click File, the interface as shown in Figure 2.1.13 will be displayed, you can see the Examples and Preference options. The Examples are some of the Arduino's own programs, these are compiled without errors, the normal use of the program, a great help for beginners. The Preference option, It’s mainly about the parameter settings, such as language, fonts and so on. Figure 2.1.13 File Menu Bar Options 3、Click Tools, the interface shown in Figure 2.1.14 will pop up. Here we can see two options: Board and Port. In the board option, we can see the commonly used Arduino development board model, we only need to choose according to their own development board. In the Port option, the USB serial port is mainly selected, as shown in Figure 2.1.15. If you are not sure, you can check it in the "Device Manager" and select the corresponding COM port. 11 Figure 2.1.14 Tools interface Figure 2.1.15 USB serial port selection After the above steps, the Arduino IDE will work. You can open any program in Examples. First compile the program. If it is compiled correctly, it can be directly downloaded to the development board and the corresponding device of the connection number. With wires, you can see the corresponding phenomenon. 12 Chapter3 Experiments 3.1 Assembly of the Car 3.1.1 Motor installation Step1: You need to install the motor mount. Figure 3.1.1 Schematic diagram of motor mounting Note: You need to use the screw to pass through the front hole of the motor, the motor holder corresponds to the opposite position and use the nut to fix the motor holder. Figure 3.1.2 Effect diagram of motor mounting Step2: You need to solder the wire to the motor. 13 Figure 3.1.3 Effect diagram of solder the wire Step3: You need to fix the wire with a cable tie. Figure 3.1.4 Effect diagram of fixing the wire 14 Step4: You need to install motors. Figure 3.1.5 Schematic diagram of motor installation 15 Figure 3.1.6 Effect diagram of motor installation 3.1.2 Wheel and drive module installation Step1: You need to install hexagonal coupling. Figure 3.1.7 Schematic diagram of hexagonal coupling installation Figure 3.1.8 Effect diagram of hexagonal coupling installation 16 Step2: You need to install wheel. Figure 3.1.9 Schematic diagram of wheel installation Note: The black top wire position of the hexagonal coupling is tightened against the plane of the motor drive shaft. Figure 3.1.10 Effect diagram of wheel installation 17 Step3:You need to install motor driver module. Figure 3.1.11 Shematic diagram of fixing motor driver board Figure 3.1.12 Shematic diagram of fixing motor driver board 18 3.1.3 Tracking module installation Figure 3.1.15 Shematic diagram of copper column of tracking moduble installation Figure 3.1.16 Effect diagram of copper column of tracking moduble installation 19 Figure 3.1.17 Shematic diagram of tracking moduble installation Note: You need to screw the M3 nut to the bottom of the M3*10 screw and install it. Figure 3.1.18 Effect diagram of copper column of tracking moduble installation 20 3.1.4 Lower acrylic plate copper column installation and motor wiring Figure 3.1.19 Shematic diagram of motor wiring Note: You need to insert the 4Pin DuPont cable into the motor drive board input. Figure 3.1.20 Effect diagram of motor wiring 21 Figure 3.1.21 Shematic diagram of copper column installstion Figure 3.1.22 Effect diagram of copper column installstion 22 3.1.5 Keywish Uno R3 board installation Figure 3.1.23 Shematic diagram of Keywish Uno R3 board installation Figure 3.1.24 Effect diagram of Keywish Uno R3 board installation 23 3.1.6 Battery box installation Figure 3.1.25 Shematic diagram of battery box installation Figure 3.1.26 Effect diagram of battery box installation 24 3.1.7 Servo installation Figure 3.1.27 Shematic diagram of servo installation Figure 3.1.28 Effect diagram of servo installation In order to reduce the angle adjustment of the servo, we need to adjust the servo to 90 degrees. First, we should copy the following program (Lesson\ModuleDemo\Servo\ServoCorrect\ ServoCorrect.ino) into the compilation environment. Then, we need to make the signal line of servo(orange) be connected to port 13 of Arduino board. Finally, we need to fix rudder wing by screws, and fix the ultrasonic bracket on the rudder wing. 25 #includeServo myservo;// create servo object to control a servo int pos = 90; // variable to store the servo position void setup() { myservo.attach(13);// attaches the servo on pin 13 to the servo object } void loop() { myservo.write(pos);// tell servo to go to position in variable 'pos' delay(15);// waits 15ms for the servo to reach the position } Figure 3.1.29 Schematic diagram of rudder wing and ultrasonic bracket installation Figure 3.1.30 Effect diagram of rudder wing and ultrasonic bracket installation 26 3.1.8 Infrared obstacle avoidance module installation Figure 3.1.31 Shematic diagram of infrared obstacle module installation Figure 3.1.32 Effect diagram of infrared obstacle module installation 27 3.1.9 Voltage display module and DC head installation Figure 3.1.33 Shematic diagram of voltage display module and DC head installation We need to use two power cables (the same as the wires used by the motor, one red and one black), and connect the two wires to the DC power supply head. DC power supply head as shown in Figure 3.1.34. You need to remove the rubber ring at the "1" mark to open the caser and solder the wire to +12V and GND, as shown in Figure 3.19.3. Figure 3.1.34 Shematic diagram of solder DC power supply head 28 Figure 3.1.35 Effect diagram of solder DC power supply head Figure 3.1.36 Effect diagram of voltage display module and DC head installation 29 3.1.10 Infrared remote control receiver installation Figure 3.1.37 Shematic diagram of infrared remote control receiver installation Figure 3.1.38 Effect diagram of infrared remote control receiver installation 30 3.1.11 Overall assembly You should screw the battery box , the voltage display module and the DC head wire together (as shown in Figure 3.1.11.2), and connect the positive (red wire) to the +12V negative (black wire) to GND. Figure 3.1.39 Shematic diagram of Overall assembly Note: you need to take the infrared tracking wire and the driver board wire from the upper acrylic plate hole 1, plug the expansion board into the UNO R3 board and wire it. 31 Figure 3.1.40 Effect diagram of Overall assembly 3.1.12 Expansion board wiring diagram Figure 3.1.41 Expansion Board Connection Diagram The full installation of the car is as shown below: 32 Figure 3.1.42 Assembly Connection Diagram So far, the basic assembly of car has been completed. Then you can achieve the corresponding functions only by downloading the program to the development board, each function has a corresponding program in CD. Let's go to the software section! 33 3.2 Hummer Bot Module experiment 3.2.1 Walking Principle of the Car In the "Hummer-Bot" car, we choose the L298N as the motor driver chip for it is a high voltage and current full-bridge driver chip, the chip uses 15 pins package. It is a special motor driven integrated circuit (two H bridges) with high voltage and current full-bridge driver. And it contains 4 channel logic drive circuit, basically belongs to a kind of two-phase and four-phase special motor drive which contains two H bridges of high voltage large current. The output current is 2A, the maximum current is 4A, the maximum working voltage is 50V, which can drive the load under 46V and 2A, such as high power DC motor, stepper motor, solenoid valve and so on. The chip with two enable control terminals uses the standard logic level to control signals, allows or prohibits the device to work when the input signal is not interfered, it has a logic power input terminal which can enable the internal logic circuit to work under low voltage, and feedback the variation to the control circuit. Especially, the input can be connected directly with the MCU and easily controlled. When the DC motor is driven, the stepper motor can be directly controlled, and it can be turned forward and reversely, which only needs to change the logic level of the input. The pin arrangement is shown in Fig.3.2.1. The pin 1 and 15 can separately connect to the current sampling resistor and form the current sensing signal. Figure .3.2.1 Arrangement of Chip Pins L298N can drive 2 motors which are connected between OUTl, OUT2 and OUT3, OUT4. 5, 7, 10 and 12 pin are connected to input control level for controlling the positive and negative rotation of the motor, ENA, ENB are connected to control enable terminal for controlling the running and shutdown of the motor. Its characteristics: 34 ◆ Signal indicator ◆ The speed is adjustable ◆ The strong anti-interference ability with photoelectric isolation ◆ Overvoltage and overcurrent protection ◆ Controlling of two motors separately ◆ Controlling the stepper motor ◆ The speed control with PWM pulse width ◆ Positive and negative rotation ENA IN1 IN2 Motor status H H L Forward H L H Reversal H IN2 IN1 Quick stop L X X Stop Figure .3.2.2 Logic Function Chart Fig.3.2.3 Module Physical Map Detailed L298N chip data please refer to “hummer-bot\Document\L298N_datasheet.pdf” 35 Figure .3.2.4 Schematic Diagram of Motor Drive Four DC motors with high power L298N drive enable "Hummer-Bot" to run faster than conventional two-wheel car, the acceleration time is shorter and the structure is more stable. In addition, we use PWM to control the speed of the motor(Note: PWM is a way to simulate the simulation output via square waves with different duty cycles.), Arduino PWM port outputs a series of square waves with fixed frequency, the power and current of the motor can be amplified after receiving the signal, thereby changing the motor’s speed. The speed coordination of two motors on the right and left wheels can achieve the forward, backward, turning and other functions of the car. Figure 2.4.5 shows the sequence diagram of PWM duty cycles. Figure .3.2.5 Sequence Diagram of PWM Duty Cycles 36 In Arduino, analog voltage can’t be output, only 0 or 5V digital voltage value, we can use high resolution counter and the duty cycles of the square wave modulation method to encode a specific level of analog signal. The PWM signal is still digital, because at any given time, the full amplitude of DC power supply is either 5V (ON) or 0V (OFF). The voltage or current source is added to the analog load with a ON or OFF repetitive pulse sequence. When the DC power supply is added to the load, the power supply is on, otherwise the power supply is off. As long as the bandwidth is enough, any analog value can use PWM to encode. The output voltage value is calculated by the on and off time. Output voltage = (turn-on time / pulse time) * maximum voltage. Fig.2.4.6 shows the corresponding voltage to the pulse change. Figure .2.4.6 Relation between Pulse and Voltage Arduino UNO possess 6 PWM pins, namely digital interfaces 3, 5, 6, 9, 10, 11, and we select 5, 6, 9, 10 as the motor control IO, the connection is shown in Figure .2.4.7. The following table shows the correspondence between L298N and Uno board: L298N Arduino Uno IN1 D6 IN2 D10 IN3 D5 IN4 D9 37 Figure .2.4.7 Arduino and L298N driver board connection diagram and connection table The L298N and Arduino expansion board wiring is as follows: Figure.3.2.8 L298N and Arduino Expansion Board Connection Diagram After the wiring is completed, we need to do a simple test to check if the motor can run normally. So we need to copy the following code (You can also open the program in the CD directly.) into the IDE development environment and downloading to the development board. And turning on the power (power connection is introduced the tenth and eleventh steps in 3.1.2) to observe the wheels rotation, if "going forward 5s----stopping 1s---- going back 5s---- stopping 1s----turning left 3s----stop 1s----turning 38 right 3s" are normal, the connection is correct, otherwise the polarities of the motor may be reversed, then you need to adjust slightly. Program flow chart is as follows: Figure 3.2.9 Motor Test Flow Chart Note: This test and IO selection are only for reference, you can choose other IO ports or use other wiring methods according to your own ideas. 39 int E1 = 5; //PWMA int M1 = 9; //PWMA int E2 = 6; //PWMB int M2 = 10; //PWMB void setup() { } void loop() { analogWrite(M1, 0); analogWrite(E1, 150); //the speed value of motorA is 150 analogWrite(M2, 0); analogWrite(E2, 150); //the speed value of motorB is 150 delay(5000); //******** ******************************//forward analogWrite(M1, 0); analogWrite(E1, 0); //the speed value of motorA is 0 analogWrite(M2, 0); analogWrite(E2, 0); //the speed value of motorB is 0 delay(1000); 40 //********************************************//stop analogWrite(M1, 150);//the speed value of motorA is 150 analogWrite(E1, 0); analogWrite(M2, 150);//the speed value of motorA is 150 analogWrite(E2, 0); delay(5000);//*********************************************//back analogWrite(M1, 0); analogWrite(E1, 0); //the speed value of motorA is 0 analogWrite(M2, 0); analogWrite(E2, 0); //the speed value of motorB is 0 delay(1000); //******* ***************************************//stop analogWrite(M1, 0); analogWrite(E1, 180); //the speed value of motorA is 180 analogWrite(M2, 180);//the speed value of motorB is 180 analogWrite(E2, 0); delay(3000); //*******************************************//left analogWrite(M1, 0); analogWrite(E1, 0); //the speed value of motorA is 0 analogWrite(M2, 0); analogWrite(E2, 0); //the speed value of motorB is 0 delay(1000); //***** **************************************//stop analogWrite (M1, 200); //the speed value of motorA is 200 analogWrite(E1, 0); analogWrite (M2, 0); analogWrite(E2, 200); //the speed value of motorB is 200 delay(3000);//*** ***************************************//right } 3.2.2 Infrared Obstacle Avoidance 3.2.2.1 Introduction of Infrared Obstacle Avoidance Sensor Infrared obstacle avoidance module is a pair of infrared transmitting and receiving tubes, the former launches a certain frequency infrared, the receiving tube will receive the reflected infrared when the infrared detects the obstacles. After the signal is processed by the comparator circuit, the green LED lights, and the signal output port outputs digital signal at the same time (a low level signal). The detection distance can be adjusted through the potentiometer knob, the effective distance range is 2-30cm, the working voltage is 3.3V-5V. The sensor uses infrared, so the anti-interference ability is very strong, the measurement accuracy is very high when the distance is moderate. In addition, the module can be assembled easily and used 41 conveniently, it can be widely used in robot obstacle avoidance, car obstacle avoidance and the black&white line tracing and many other occasions. The sensor module possess strong anti-interference ability and wen the distance is moderate, the measurement accuracy is very high. It is widely used in many obstacles such as robot obstacle avoidance, pipeline counting and black and white line tracking. 3.2.2.2 Working Principle 1.The module output port OUT can be directly connected with the IO port of the microcontroller, and directly drive a 5V relay; the connection mode is: VCC-VCC; GND-GND; OUT-IO (A3 and A4), as shown in Fig.3.2.9 and Chart 3.2.1. 2. The module uses the 3-5V DC power as power supply. When the power is on, the indicator will light. 3. The diameter of installation hole is 3mm, you can use the same size screws (screws in the kit). Pin wiring definition (only for reference, you can define according to your own ideas): arduino Uno VCC GND A3 A4 Infrared Obstacle Avoidance Module VCC GND The left module The right module Chart 3.2.1 Pin Wiring Definition 3.2.2.3 Module Parameters The working principle of infrared obstacle avoidance sensor is very simple, that is the reflection property of objects. In a certain range, if there is no obstacle, the infrared ray emitted will gradually weaken because of the farther distance of transmission, and finally disappear. If there are obstacles, the infrared will be reflected to the receiving head. As soon as the sensor detects the signal, it can confirm that there are obstacles in front of the circuit board, the green indicator will light, the OUT port continuously outputs low level signal to MCU at the same time, the MCU conducts a series of analysis to ensure that the two wheels of car works properly and avoids the obstacle beautifully. The schematic diagram of the sensor is shown in Fig.3.2.8. 42 Figure .3.2.10 Infrared obstacle avoidance schematic diagram Figure .3.2.11 Connection of Arduino and Sensor Note: This module can adjust the detection distance by the potentiometer, the detection distance is 2-30cm, if it is found that the distance detection is not very sensitive, you can use the potentiometer to achieve the desired results (rotating the potentiometer clockwise will increase the detection distance; counterclockwise will decrease), it is shown in Fig.3.2.12. 43 Manual adjustment is shown in the following diagram: Adjustable Potentiometer Figure .3.2.12 Diagram of Distance Detection Adjustment 3.2.2.4 Wire connection As the figure shown below, the upper column is the "GND" interface, the middle column is the "VCC" interface, and the lower column is the "OUT" interface, where "A3" corresponds to the "OUT" of the left infrared obstacle avoidance, and "A4" corresponds to the "OUT" of right infrared obstacle avoidance. Figure 3.2.13 Wire connection diagram 44 3.2.2.5 Experimental Procedures 1. Fixing the two sensors on the car and connecting them to Arduino with wires.(Already done) 2. Testing the sensitivity of module, namely opening the switch on the battery box and the indicator will light, placing obstacles the 10cm away from the infrared tubes, adjusting the potentiometer until the output indicator lights up. 3. Module test. Copying the following code to the IDE compiler environment (you can also open the program directly in the CD), downloading it to the development board, opening the serial port monitor (baud rate is 9600) and observing the changes of data when there is an obstacle (Figure 3.2.14) and no obstacle (Figure 3.2.15). Note: Here we connect the infrared obstacle avoidance signal output port to the analog port on Arduino (A0-A5), so the serial port prints out analog value, you can connect it to digital port (2-13), and the serial port will only print out "0" and "1". Program flow chart is as follows: Test demo path:“hummer-bot\Lesson\ModuleDemo\InfraredAvoidance\ InfraredAvoidance.ino” 45 const int leftPin = A3; const int rightPin = A4; int dl; int dr; void setup() { Serial.begin(9600); pinMode(leftPin, INPUT); pinMode(rightPin, INPUT); delay(1000); } void loop() { dl = analogRead(leftPin); dr = analogRead(rightPin); Serial.print("left:"); Serial.print(dl); Serial.print(" "); Serial.print("right:"); Serial.println(dr); } Figure .3.2.14 Diagram of Data with Obstacles 46 Figure .3.2.15 Diagram of Data without Obstacles 47 3.2.2.5 Software Design 3.2.2.5.1 Program flow chart 3.2.2.5.2 Program code Next, we combined the above infrared obstacle avoidance module test program and the trolley motor driver program to complete the infrared obstacle avoidance experiment. The program of this experiment: “hummer-bot\Lesson\ModuleDemo\InfraredAvoidance\ InfraredAvoidance.ino” 48 int E1 = 5; //PWMA int M1 = 9; //DIRA****************************************left int E2 = 6; //PWMB int M2 = 10; //DIRB****************************************right /*Define 4 motor control terminals, connected to IN1-IN4 on the motor drive board。*/ const int leftPin = A3; const int rightPin = A4; // Define the two signal receiving ends of the sensor float dl; float dr;// Define two margins to store the values read by both sensors void setup() { Serial.begin(9600); // Set the serial port baud rate to 9600, pinMode(leftPin, INPUT); pinMode(rightPin, INPUT);// Set the working mode of two sensor pins, namely "input" delay(1000); } void loop() { dl = analogRead(leftPin); dr = analogRead(rightPin); // Read the values collected by both sensors and assign them to the defined variables。 if (dl >= 38 && dr <= 38) {/*If the value collected by the left sensor is greater than or equal to 38 and the right value is less than or equal to 38, the following program in {} is executed (dl> = 38, there is no obstacle on the left, dr<= 38 shows that there is an obstacle on the right, so at this time the car is turning to the side without obstacles (ie, turning to the left). From Figure 3.2.11, we know that the simulated value will drop below about 35 in the event of an obstacle , But in order to reduce the error, we set the threshold at 38 to prevent the car from judging the error because of the error. We can also customize other values. If we use the digital port to receive the value of the sensor, we only return "0" and "1" ", But the same way to judge. The reason why I did not use digital IO, because we use the digital IO port in other places.*/ analogWrite (M1, 0); analogWrite(E1, 180); //the speed value of motorA is 180 analogWrite (M2, 180); //the speed value of motorB is 180 analogWrite(E2, 0); /*Set a PWM value, the maximum PWM is 255, but the speed of the car should not be too fast when walking, otherwise it can not hit the obstacle in time when the obstacles are suddenly encountered.*/ 49 Serial.print(dl); Serial.print(" "); Serial.print(dr); Serial.print(" "); Serial.println("Turning left"); /*Through the "Serial Monitor" print the current status of the car and the value collected by the sensor*/ delay(300); analogWrite(M1,0); analogWrite(E1,0); analogWrite(M2,0); analogWrite(E2,0);/*As the car left after about 300ms stop, after measuring, 300ms time car just can rotate about 90 degrees, because the DC motor does not like the steering angle can be precisely controlled, so can only give a rough estimate, of course, different motor speed is not Similarly, the time used is not the same, so everyone in the experiment can be based on their own ideas, but the angle of 90, but also other values.*/ delay(1000);//************************************//Turning left } if (dl <= 38 && dr <= 38) {/*If the value collected by the left sensor is less than or equal to 38 and the right value is less than or equal to 38, the following program in {} is executed (dl <= 38, indicating that there is an obstacle on the left and dr<= 38 shows that there is an obstacle on the right, so at this time the car is rotated 180 degrees backwards. In the experiment, the car can just turn around 180 degrees after 500ms of rotation. Because the DC motor can not precisely control the angle like the steering gear, An approximate value, of course, different motor speed is not the same, the time used is not the same, so everyone in the experiment can be based on the circumstances may be.)*/ analogWrite(M1, 255); //the speed value of motorA is 255 analogWrite(E1, 0); analogWrite(M2, 0); analogWrite(E2, 255); //the speed value of motorB is 255 Serial.print(dl); Serial.print(" "); Serial.print(dr); Serial.print(" "); Serial.println("Turning around");/*Through the "Serial Monitor" print the current status of the car and the value collected by the sensor.*/ delay(500); analogWrite (M1, 0); analogWrite (E1, 0); analogWrite (M2, 0); analogWrite (E2, 0); /*Rotate 180 degrees and stop*/ delay(1000);//*********************************//Turning around } 50 if (dl <= 38 && dr >= 38) /*If the left sensor is less than or equal to 38 and the right value is greater than or equal to 38, the following program in {} is executed (dl <= 38, indicating that there is an obstacle on the left, dr> = 38 shows that there is no obstacle on the left, so at this moment the car is turning to the side without obstacle, that is, turning to the right)*/ { analogWrite(M1, 180);//the speed value of motorA is val analogWrite(E1, 0); analogWrite(M2, 0); analogWrite(E2, 180);//the speed value of motorA is val Serial.print(dl); Serial.print(" "); Serial.print(dr); Serial.print(" "); Serial.println("Turning right"); delay(300); analogWrite(M1, 0); analogWrite(E1, 0); analogWrite(M2, 0); analogWrite(E2, 0);/*Car must stop after each rotation, if you do not stop there will be the phenomenon of rotating around. */ delay(1000);//*********************************Turning right } if (dl >= 38 && dr >= 38) {/* Judge two values collected by the sensor. If the value collected by the left sensor is greater than or equal to 38 and the right value is greater than or equal to 38, execute the following program in {} (dl > = 38, indicating that there is no obstacle on the left and dr > = 38 that there is no obstacle on the left, so the car at this time straight */ intval = 150; /*When the straight line has a PWM value of 150, if the value is too large, the speed of the car will be very fast, which may lead to the car can not hit the obstacle in time when it encounters the obstacle. */ analogWrite (M1, 0); analogWrite(E1, val);//the speed value of motorA is val analogWrite (M2, 0); analogWrite(E2, val);//the speed value of motorB is val Serial.print(dl); Serial.print(" "); Serial.print(dr); Serial.print(" "); Serial.println("go");//**********************************/ / forward } } 51 3.2.3 Infrared Tracing 3.2.3.1 Introduction of Infrared Tracing Sensor After infrared obstacle avoidance, let us learn the infrared tracing, their nature of work is the same, using basically the same module, just in different ways, to achieve different functions. In this section when we study, we have to pay attention to the color of the line we trace (the black line or white line), if your floor is black, you should trace the white line (pasting white line on the floor); if it is white, then you should trace the black line (pasting black line on the floor); you just need to make a distinct difference between the track and the ground environment. In the "Hummer-Bot" car, we use the TCRT5000 sensor as tracing module, which consists of an infrared emitting diode and an NPN infrared photoelectric transistor. The physical map is shown in Fig.3.2.16. Figure .3.2.16 Physical Map of the Module 3.2.3.2 Working Principle In the above, we talked about two patterns of tracing-the white line and the black line. In fact, either the black line or the white line, we usually adopt the infrared detection method. Infrared detection method means that different objects with different colors have the different infrared reflection characteristics. The car launches the infrared to the ground continually during driving process, the infrared receiving tube will be in a shutdown state and the output of the module is low level when the emitted infrared is not reflected or the reflected infrared is not strong enough, and indicating diode will be off; when the diffuse reflection occurred on a white floor, the intense reflected infrared will be received by the receiving tube on the car, the photosensitive triode will be saturated, the output end of the module is high level and the indicating diode will light. 52 As is shown in the schematic diagram 3.2.17 (U1 is 74HC14D comparator), A and C are connected to the light emitting diode, C and E to the receiving diode. In the "Hummer-Bot" car, we use three modules, two in the left and right sides, one in the middle. Its installation is shown in Fig.3.2.18,the tracing sensors are in a straight line. Figure .3.2.17 Schematic Diagram of Tracing Module Figure. 3.2.18 Diagram of Tracing Module Installation The X1 and Y1 are the first direction control sensors, and the width of the two sensors on the same side of the black line must not be greater than the width of the black line. When the car is moving forward, the driving track is always between the two first level sensors X1 and Y1 (the black track as shown in Fig. 3.2.18), when the car deviates from the black line: If the left X1 detects the black line which can’t be detected by the right Y1 and intermediate sensors, the the car has shifted to the right, then the car will turn left slightly, and keeping intermediate sensor always detecting the black line; if the right Y1 detects the black line which can’t be detected by the left X1 and intermediate sensors, the the car has shifted to the left, then the car will turn right slightly, and keeping intermediate sensor always detecting the black line; if the car turns back on the track driving along the black line, X1 and Y1 can all detect the white line, and send high level to the microcontroller. 53 3.2.3.3 Module Parameters ◆ Using TCRT5000 infrared reflection sensor ◆ The detection distance: 1mm~25mm, the focal distance is 2.5mm ◆ The comparator output signal waveform is clean, good-shape and it has more than 15mA strong drive ability. ◆ The working voltage: 3.3V-5V ◆ Using wide voltage comparator 74HC14D, digital output (0 and 1) ◆ Easy-to-install fixed bolt holes Detailed parameters please refer to“hummer-bot\Document\ TCRT5000.pdf” Note: Correct wiring! The mainboard and electronic device may burn up if you have reverse connection between positive and negative poles. Connecting the VCC to 3.3V or 5V, the OUT output port to the microcontroller IO port directly. The I/O port on Arduino should be set for input mode / receiving mode, otherwise it can’t be used. As for other MCU, such as ARM or more advanced control boards, if the I/O ports need to be used as the input and output mode, they have to be set to the input mode / receiving mode. The 51 series microcontrollers can be used directly, there is no need to set the input and output mode. 3.2.3.4 Wire connection As shown in the below figure, the upper column is the "GND" interface, the middle column is the "VCC" interface, and the lower column is the "OUT" interface, where "A0" corresponds to the "OUT" of the left trace, and "A1" corresponds to the "OUT" of the intermediate trace. "A2" corresponds to the "OUT" of the right trarce. 54 Figure .3.2.19 Wire connection diagram 3.2.3.5 Experimental Procedures 1, We need to connect it to the Arduino as shown in Fig.3.2.19. 2, Making the track.If your floor is white, then you could stick a black tape to form a loop, otherwise stick a white tape, the shape of track is based on your own desires, the best width of the tape is 13-18mm. In this manual, we use the black track, as shown in Fig.3.2.20. 3, Module test. We should copy the following codes to the IDE compiler environment (you can also open the program in the CD directly) and downloading to the development board, and open the serial port monitor (baud rate is 9600) to observe the changes of data when there is the white line (Fig. 3.2.21) and is not the white line (Figure 3.2.22). Program flow chart is as follows: 55 Note: Here we connect the signal output port of infrared obstacle avoidance to the analog port on Arduino (A0-A5), so the serial port monitor prints analog values, you can connect it to the digital port (2-13), then the serial port monitor will print out only "0" and "1". Demo test code: “hummer-bot\Lesson\ModuleDemo\InfraredTracingTest\InfraredTracingTest.ino” 56 void setup() { Serial.begin(9600); } void loop() { int left, centre, right; left = analogRead(A0); centre = analogRead(A1); right = analogRead(A2); Serial.print("right:"); Serial.print(right); Serial.print(" "); Serial.print("centre:"); Serial.print(centre); Serial.print(" "); Serial.print("left:"); Serial.print(left); Serial.println(" "); } Figure .3.2.20 Example of the Black Track 57 Fig. 3.2.21 The Data When the Sensor Does Not Detect the Black Line Figure 3.2.22 The Data When the Sensor Detects the Black Line From Fig.3.2.21 and Fig.3.2.22 we can see that the output is high level when the sensor does not detect the black line, low level when detects the black line. We use the analog port to collect the sensor’s signal, so the printed value is analog that, the high level is reaching 1024, the low level is 0. 58 3.2.3.5 Software Design 3.2.3.5.1 Program flow chart When the car enters the tracing mode, it keeps scanning the I/O port of the MCU connected to the sensors, once detecting the changes in signal at the I/O port, the corresponding procedure will be implemented. If the left sensor detects the black line, the car should turn the left; If the right sensor detects the black line, the car should turn the right. After the direction adjustment, the car walks forward, and continues to detect the black line repeatedly. The tracing flow chart is shown in Fig.3.2.23. Figure .3.2.23 the Tracing Flow Chart 3.2.3.5.2 Program Code Code Path“hummer-bot\Lesson\ModuleDemo\InfraredTracing\ InfraredTracing.ino” 59 int E1 = 5; //PWMA int M1 = 9; //DIRA****************************************left int E2 = 6; //PWMB int M2 = 10; //DIRB****************************************right /*Define 4 motor control terminals, connected to IN1-IN4 on the motor drive board.*/ void setup() { Serial.begin(9600); /*Set the baud rate to 9600 */ } void loop() { int left1, centre, right1; /*Define 3 sensors */ left1 = analogRead(A0); centre = analogRead(A1); right1 = analogRead(A2); /*Read the value collected by 3 sensors */ if ((right1 >= 975) && (centre <= 8) && (left1 >= 975)) {/* Judge the collected value, if right1 > the sensor captures a value that is low and reads 0 after analog IO. However, to reduce the error, we set the threshold In 8, to prevent the error caused by the car to determine the wrong, we can 60 customize the other values, if the use of digital port to receive the value of the sensor returns only "0" and "1", but to determine the same way. The reason why I did not use digital IO, because we use the digital IO port in other places. */ intval = 150; /*Set a PWM value, the maximum value of PWM is 255, but the speed should not be too fast when tracing the car, otherwise the car will shake more in the tracing process.*/ analogWrite (M1, 0); analogWrite(E1, val); //the speed value of motorA is val analogWrite (M2, 0); analogWrite(E2, val); //the speed value of motorB is val } else if((right1 <= 8) && (centre >= 975) && (left1 >= 975)) {/* The value collected to judge, if the center > = 975 and left1 > = 975 are greater than 975, indicating that the middle and left sensors did not detect the black line, right1 <= 8 shows the right sensor detects a black line, then the car Has left to the left, or the black line has been turning to the right, so the car should turn to the right. */ intval = 150; analogWrite (E1, 0); analogWrite(M1, val); //the speed value of motorA is val analogWrite (M2, 0); analogWrite(E2, val); //the speed value of motorB is val } else if((right1 >= 975) && (centre >= 975) && (left1 <= 8)) {/* Judge the collected value, if center > = 975 and right1 > = 975 are greater than 975, indicating that the middle and right sensors did not detect the black line, left1 <= 8 shows that the left sensor detects the black line, then the car Has been to the right deviation, or the black line has turned to the left, so the car should turn left at this time. */ intval = 130; analogWrite (M1, 0); analogWrite(E1, val); //the speed value of motorA is val analogWrite (E2, 0); analogWrite(M2, val); //the speed value of motorB is val } if ((right1 <= 8) && (centre <= 8) && (left1 <= 8)) {/* The value collected to judge, if the center <= 8, left1 <= 8 and right1 <= 8 are greater than 8, indicating 3 sensors have detected a black line, then the car has reached the "ten" intersection, because We have only 3 sensors, no way to make more sophisticated judgments, so only let the car choose to go straight. */ intval = 130; analogWrite (M1, 0); analogWrite(E1, val); //the speed value of motorA is val analogWrite (M2, 0); analogWrite(E2, val); //the speed value of motorB is val } } 61 3.2.4 Ultrasonic Obstacle Avoidance In this product, we will integrate the ultrasonic module and steering engine together and make the two parts working at the same time, which greatly increases the effectiveness of the data and the flexibility of the car, the main working flow: When the power is on, steering engine will automatically rotates to 90 degrees, the MCU will read data from the reflected ultrasonic. If the data is greater than the security value, the car will continue to drive forward, otherwise the car will stop, then the steering engine will rotate 90 degrees to the right. After that, the MCU reads data from the reflected ultrasonic again, the steering engine rotates 180 degrees to the left, then reading data again, the steering engine rotate 90 degrees, the MCU will contrast the two detected data, if the left data is greater than the right data, the car will turn left, otherwise turn right, if the two data are both less than the safety value, the car will turn around. 3.2.4.1 Suite Introduction 1. The steering gear The steering gear is mainly composed of the following parts in general, steering wheels, gear group, position feedback potentiometer, DC motor and control circuit (shown in Fig.3.2.24). Fig.3.2.25 shows the most commonly used 9G steering gear now. Figure .3.2.24 Diagram of Steering Gear 62 Figure .3.2.25 Physical Map of Steering Gear 2. The ultrasonic An ultrasonic sensor is a device that transforms other forms of energies into ultrasonic energy with desired frequency or transforms the ultrasonic energy into other forms of energy with the same frequency. The ultrasonic sensors are commonly classified into two categories, the acoustic type and the hydrodynamic type. Acoustic type mainly has: 1, piezoelectric sensor; 2, magneto strictive sensor sensor; 3, electrostatic sensor. The hydrodynamic type includes the gas whistle and the liquid whistle. At present most of the ultrasonic sensors are working using piezoelectric sensors. Distance measurement with the ultrasonic is also a hot spot. In the "Hummer-Bot" car, we use HC-SR04 ultrasonic module which has the 2cm-400cm non-contact distance sensing function, the measurement accuracy can achieve to 3mm; the temperature sensor can correct the measured results using the GPIO communication mode, the module has a stable and reliable watchdog. The module includes an ultrasonic transmitter, receiver and control circuit, which can measure distance and steer like in some projects. The smart car can detect obstacles in front of itself, so that the smart car can change direction in time, avoid obstacles. A common ultrasonic sensor is shown in Fig.3.2.26. 63 Figure 3.2.26 Physical Map of Ultrasonic Module 3.2.4.2 Suite Parameters 1. Steering gear The steering gear has three input wires as shown in Fig.3.2.25, the red is power wire, while the brown is the ground, which guarantee the basic energy supply for the steering gear. The power supply has two kinds of specifications (one is 4.8V, the other is 6.0V)which are corresponding to different torque standards, the 6.0V torque is higher than the 4.8V torque; and the another one is the signal control wire, which is generally white in Futaba, orange in JR. Noticing that some of the SANWA's power wires are on the edge rather than the middle which need to be identified, so you need to remember that the red is power wire, the brown is ground wire. 2. Ultrasonic wave 1, Working voltage: 4.5V~5.5V. In particular, voltage above 5.5V is not allowed definitely 2, Power consumption current: the minimum is 1mA, the maximum is 20mA 3, Resonant frequency: 40KHz; 4, Detection range: 4 mm to 4 meters. Error: 4%. In particular, the nearest distance is 4mm, the longest distance is 4 meters, and the data outputs continuously without setting anything. 5, Temperature measurement range: 0℃to +100℃; precision: 1℃ 6, Illumination measurement range: bright and dark; 7, Data output mode: icc and uart (57600bps), users can choose any of them; UART mode uses 7 bytes as a group, and the 3 data stared with 0x55 are the distance values; the 2 data started with 0x66 are the temperature value; the 2 data started with 0x77 are the illumination values. 0x55\0x66\0x77 are the data headers in order to distinguish the 3 data; 64 8, Supporting the following 2 detection methods: 1, continuous detection; 2, controlled intermittent detection; 9, Distance data format: using mm as the smallest data unit, double byte 16 hexadecimal transmission; 10, Temperature data format: using Celsius degree as the smallest unit, single byte hexadecimal transmission; 11, Light data format: single byte 16 hexadecimal transmission; the value is big when it is dark, small when it is bright; 12, Working temperature: 0℃~+100℃ 13, storage temperature: -40 to +120 degrees Celsius 14, Size: 48mm*39mm*22mm (H) 15, The size of fixing holes: 3*Φ3mm; Gap:10mm 3.2.4.3 Working Principle 1. Steering gear The control signal enters the signal modulation chip by the receiver channel, gets the DC bias voltage. The steering gear has a reference circuit which generates a reference signal with a period of 20ms and a width of 1.5ms. Comparing the obtained DC bias voltage with the voltage of the potentiometer and obtaining the output voltage difference. Finally, the positive and negative output voltage difference in the motor driver chip decide the positive and negative rotation of motor. When the speed of motor is certain, the cascade reducer gear will drive potentiometer to rotate so that the voltage difference is reducing to 0, the motor will stop rotating. When the control circuit receives the control signal, the motor will rotate and drive a series of gear sets, the signal will move to the output steering wheel when the motor decelerates. The the output shaft of steering gear is connected with the position feedback potentiometer, the potentiometer will output a voltage signal to the control circuit board to feedback when the steering gear rotates, then the control circuit board decides the rotation direction and speed of the motor according to the position, so as to achieve the goal. The working process is as follows: control signal→control circuit board→motor rotation→gear sets deceleration →steering wheel rotation→position feedback potentiometer→control circuit board feedback. The control signal is 20MS pulse width modulation (PWM), in which the pulse width varies linearly from 0.5-2.5MS, the corresponding steering wheel position varies from 0-180 degrees, which means the output shaft will maintain certain corresponding degrees if providing the steering gear with certain pulse width. No matter how the external torque changes, it only changes position until a signal with different is provided as shown in Fig.3.2.27. The steering gear has an internal reference circuit which can produce reference signal with 20MS period and 1.5MS width, there is a comparator which can detect the magnitude and direction of the external signal and the reference signal, thereby produce the motor rotation signal. 65 Figure .3.2.27 Relationship between the Motor Output Angle and Input Pulse 2. The ultrasonic The most commonly used method of ultrasonic distance measurement is echo detection method, the ultrasonic transmitter launches ultrasonic toward a direction and starting the time counter at the same time, the ultrasonic will reflect back immediately when encountering a blocking obstacle and stopping the counter immediately as soon as the reflected ultrasonic is received by the receiver. The working sequence diagram is shown in Fig.3.2.28. The velocity of the ultrasonic in the air is 340m/s, we can calculate the distance between the transmitting position and the blocking obstacle according to the time t recorded by the time counters, that is: s=340*t/2. Figure .3.2.28 the Ultrasonic Working Sequence Let us analyze the working sequence, first the trigger signal starts the HC-RS04 distance measurement module, which means the MCU sends an at least 10us high level to trigger the HC-RS04,the signal sent inside of the module is responded automatically by the module, so we do not have to manage it, the output signal is what we need to pay attention to. The output high level of the signal is the transmitting and 66 receiving time interval of the ultrasonic, which can be recorded with the time counter, and don't forget to divided it with 2. The ultrasonic is a sound wave which will be influenced by temperature. If the temperature changes little, it can be approximately considered that the ultrasonic velocity is almost unchanged in the transmission process. If the required accuracy of measurement is very high, the measurement results should be to corrected with the temperature compensation. Once the velocity is determined, the distance can be obtained. This is the basic principle of ultrasonic distance measurement module which is shown in Fig.3.2.29: Figure .3.2.29 the Principle of Ultrasonic Distance Measurement Module The ultrasonic is mainly divided into two parts, one is the transmitting circuit and the other is the receiving circuit, as shown in Fig.3.2.30. The transmitting circuit is mainly composed of by the inverter 74LS04 and ultrasonic transducer T40, the first 40kHz square wave from the Arduino port is transmitted through the reverser to the one electrode on the ultrasonic transducer, the second wave is transmitted to another electrode on ultrasonic transducer, this will enhance the ultrasonic emission intensity. The output end adopts two parallel inverters in order to improve the driving ability. the resistance R1 and R2 on the one hand can improve the drive ability of the 74LS04 outputting high level, on the other hand, it can increase the damping effect of the ultrasonic transducer and shorten the free oscillation time. The receiving circuit is composed of the ultrasonic sensor, two-stage amplifier circuit and a PLL circuit. The reflected signal received by the ultrasonic sensor is very weak, which can be and amplified by the two-stage amplifier. PLL circuit will send the interrupt request to the microcontroller when receiving the signal with required frequency. The center frequency of internal VCO in the PLL LM567 is f 0 = 1 /(1.1RP 1C 2) , the locking bandwidth is associated with C3. Because the transmitted ultrasonic frequency is 40kHz, the center frequency of the PLL is 40kHz, which only respond to the frequency of the signal, so that the interference of other frequency signals can be avoided. The ultrasonic sensor will send the received the signal to the two-stage amplifier, the amplified signal will be sent into the PLL for demodulation, if the frequency is 40kHz, then the 8 pins will send low level interrupt request signal to the microcontroller P3.3, the Arduino will stop the time counter when detecting low level. 67 Figure .3.2.30 Schematic Diagram of Ultrasonic Transmitting and Receiving 3.2.4.4 Experimental Procedures 1, Installing the steering gear, ultrasonic module to the car which has been completed in fourth step to the seventh step in 3.1.2) as shown in Fig.3.2.31. 2. Connecting the steering gear and ultrasonic module to the Arduino motherboard as shown in Fig.3.2.32. (you can choose other IO ports according to your own ideas). 68 Figure .3.2.31 Installation Diagram of the Steering Gear and Ultrasonic Module Figure .3.2.32 Wiring of the Steering Gear and Ultrasonic Module 69 3.2.4.5 Wire connection As shown in the below figure, the servo's "S" is connected to pin 13, the ultrasonic "Trlg" is connected to pin 2, the "Echo" is connected to pin 3, the "VCC" pin is connected to VCC, and the "GND" pin is connected to GND. Figure 3.2.33 Wiring diagram of steering gear, ultrasonic wave and expansion board 3.2.4.6 Software design 70 3.2.4.6.1 Program flow chart 3.2.4.6.2 Program Code Code path “hummer-bot\Lesson\ModuleDemo\UltrasonicAvoidance\UltrasonicAvoidance” 71 #include /* In this section, we use the steering gear, so we need to call the steering gear library file. As for what is in the library file, we will not study it. Interested friends can drive for research. We have put this library files on the CD-ROM, we need to copy this folder to the Arduino IDE installation path "libraries" folder, otherwise the program can not compile. */ Servo head; int E1 = 5; //PWMA int M1 = 9; //DIRA****************************************left int E2 = 6; //PWMB int M2 = 10; //DIRB****************************************right /*Define 4 motor control terminals, connected to IN1-IN4 on the motor drive board. */ const int TrigPin = 2; const int EchoPin = 3; /* Define the sensor's 2 control pins to connect to pins 2 and 3 on the Arduino.*/ const int leftPin = A3; const int rightPin = A4; float da; float dl; float dr;/* Define three variables, used to store the servo at 0,90,180 degrees, the value collected by the ultrasonic module, da is the value collected by the ultrasonic 90 degrees servo, dl is the steering servo 180 degrees ultrasonic acquisition To the value, at this point the steering gear has turned to the left of the car. da for the servo 0 degrees ultrasonic collected value, then the steering gear has turned to the right side of the car. */ float left; float right; void setup() { Serial.begin(9600);/*Set the baud rate to 9600,use "Serial Monitor" to check the data during debugging*/ head.attach(13);/* Define the control pin of the servo as pin 13*/ pinMode(E2, OUTPUT); pinMode(E1, OUTPUT); pinMode(M1, OUTPUT); pinMode(M2, OUTPUT); pinMode(leftPin, INPUT); pinMode(rightPin, INPUT); pinMode(TrigPin, OUTPUT); pinMode(EchoPin, INPUT);/* Define two ultrasonic working mode. */ head.write(90);/* The servos swivel to 90 (center) during initialization, because some servos may have errors, so they are not necessarily centered at 90 degrees, so be fine - tuned where the servos are centered at 90 degrees. */ delay(1000); } void loop() { left = analogRead(leftPin); 72 right = analogRead(rightPin); analogWrite(TrigPin, 0); // Low high and low send a short pulse to TrigPin) delayMicroseconds(2); analogWrite(TrigPin, 255); delayMicroseconds(10); analogWrite(TrigPin, 0); da = pulseIn(EchoPin, HIGH) / 58.0; // Convert the echo time to cm if (da >= 50 && da <= 2000 && (left >= 38) && (right >= 38)) {/* Judge the collected value, da> = 50 && da <= 2000, meaning that when the distance between the current obstacle and the car is greater than or equal to 50, and less than or equal to 2000cm, execute the following program in {} */ int val = 150;/* When the straight line has a PWM value of 150, if the value is too high, the speed of the car will be very fast, which may lead to the car can not hit the obstacle in time when it encounters the obstacle. */ digitalWrite(M1, 0); analogWrite(E1, val); //the speed value of motorA is val digitalWrite(M2, 0); analogWrite(E2, val); //the speed value of motorB is val Serial.print("Distance = "); Serial.print(da); Serial.print(" "); Serial.println("Moving advance 50"); //delay(500);/* If the distance is more than 50cm, move forward and output "Moving advance 50", indicating that the obstacle is more than 50cm from the car*/ } if (da < 40 && da > 30 && (left >= 38) && (right >= 38)) {/* Judge the collected value, da < 50 && da > 30, meaning that when the distance between the frontal obstacle and the car is greater than 30, and less than 40cm, execute the following program in {} */ int val = 130; digitalWrite(M1, 0); analogWrite(E1, val); //the speed value of motorA is val digitalWrite(M2, 0); analogWrite(E2, val); //the speed value of motorB is val Serial.print("Distance = "); Serial.print(da); Serial.print(" "); Serial.println("Moving advance40"); //delay(500);/* If the distance is more than 40cm, move forward and output "Moving advance 40", indicating that the obstacle is more than 40cm from the car*/ } if ((left <= 38) && (right >= 38) && (da >= 30 && da <= 1000)) { digitalWrite(M1, HIGH); analogWrite(E1, 0); //the speed value of motorA is val analogWrite(M2, 0); analogWrite(E2, 250); //the speed value of motorA is val 73 Serial.println("Turning right"); delay(200); analogWrite(M1, 0); analogWrite(E1, 0); analogWrite(M2, 0); analogWrite(E2, 0); //delay(1000); //********************************************//Turning right } if ((left >= 38) && (right <= 38) && (da >= 30 && da <= 1000)) { analogWrite(M1, 0); analogWrite(E1, 250); //the speed value of motorA is 180 digitalWrite(M2, HIGH); analogWrite(E2, 0); //the speed value of motorB is 180 Serial.println("Turning left"); delay(200); analogWrite(M1, 0); analogWrite(E1, 0); analogWrite(M2, 0); analogWrite(E2, 0); // delay(1000); //********************************************//Turning left } else if (da <= 25) {/* The collected value is judged, da <= 25, meaning that when the current obstacle and the car is less than 20cm, execute the following program in {}, the distance between the car and the obstacle has exceeded the safety value, So the car stopped forward */ int val = 0; digitalWrite(M1, 0); analogWrite(E1, val); //the speed value of motorA is 0 digitalWrite(M2, 0); analogWrite(E2, val); //the speed value of motorB is 0 Serial.print("Distance = "); Serial.print(da); Serial.print(" "); Serial.println("Stopped");// If the distance is less than 20cm, the car will stop and output "Stopped" delay(500); head.write(180);/* Servo rotated 90 degrees from the original to 180 degrees, the left side of the car */ delay(1000); analogWrite(TrigPin, 0); // Low high and low send a short pulse to TrigPin delayMicroseconds(2); analogWrite(TrigPin, 255); delayMicroseconds(10); analogWrite(TrigPin, 0); dl = pulseIn(EchoPin, HIGH) / 58.0; // Convert the echo time to cm 74 Serial.print("Left distance = "); Serial.print(dl); Serial.print(" ");/* Ultrasonic acquisition of the left side of the car and obstacles distance, and then assigned to dl, then print on the "Serial Monitor" */ head.write(0);/* Servo steering from the original 180 degrees to 0 degrees, the right side of the car */ delay(1000); analogWrite(TrigPin, 0); // Low high and low send a short pulse to TrigPin delayMicroseconds(2); analogWrite(TrigPin, 255); delayMicroseconds(10); analogWrite(TrigPin, 0); dr = pulseIn(EchoPin, HIGH) / 58.0; // Convert the echo time to cm Serial.print("Right distance = "); Serial.print(dr); Serial.print(" "); Serial.println();/*Ultrasonic acquisition of the distance between the right side of the car and the obstacle, and then assigned to dr, and then print the distance on the "Serial Monitor" */ head.write(80);// head steering back, that is, when the initialization 80 degrees position if (dl >= 20 && dl <= 1000 && dl > dr) { digitalWrite(M1, 0); analogWrite(E1, 180); //the speed value of motorA is 180 digitalWrite(M2, 180); //the speed value of motorB is 180 analogWrite(E2, 0); Serial.println("Turning left1"); delay(200);// determine the left and right distance if the left is larger than the left } else if (dl >= 1000) { digitalWrite(M1, 180); //the speed value of motorA is 180 analogWrite(E1, 0); digitalWrite(M2, 0); analogWrite(E2, 180); //the speed value of motorB is 180 Serial.println("Turning right1"); delay(200); // Special case If the left return distance is greater than 1000, the probe is blocked and turn right at this moment } else if (dr >= 20 && dr <= 1000 && dr > dl) { digitalWrite(M1, 180); //the speed value of motorA is 180 analogWrite(E1, 0); digitalWrite(M2, 0); analogWrite(E2, 180); //the speed value of motorB is 180 Serial.println("Turning right2"); delay(200);// Judge about the distance if the right side then turn right } 75 else if (dr >= 1000) { digitalWrite(M1, 0); analogWrite(E1, 180); //the speed value of motorA is 180 digitalWrite(M2, 180); //the speed value of motorB is 180 analogWrite(E2, 0); Serial.println("Turning left2"); delay(200); // Special case If the return distance on the right is more than 1000, then the probe is blocked and turn left at this moment } else if (dr <= 20 && dl <= 20) { digitalWrite(M1, 255); //the speed value of motorA is 255 analogWrite(E1, 0); digitalWrite(M2, 0); analogWrite(E2, 255); //the speed value of motorB is 255 Serial.println("Turning around"); delay(700); // turn around if both sides are less than 20cm in distance } } } In front the sections, we focus on the "automatic driving", and they are obstacle avoidance experiments. We didn't seem to have relationship with the car, it is lack of fun. Now in the next few sections, we will develop the car from other aspects to make sure that we are able to control the car personally, then we will start from the "infrared remote control", followed by "2.4G handle remote control" and the last is "mobile phone Bluetooth control". 3.2.5 Infrared Remote Control 3.2.5.1 Suite Introduction Infrared remote control is widely used in every field which is known to everyone, since it can control other electrical appliances, naturally it can control the Hummer-Bot car. Let us take a look at the infrared remote control first: Infrared wireless remote control kit consists of Mini ultra-thin infrared remote controller and 38KHz infrared receiver module, the remote controller has 17 function keys, the transmission distance is up to 8 meters which is very suitable for controlling equipment indoor. The infrared receiving module can receive 38KHz modulation remote control signal. Through the Arduino programming, the decoding operation of Infrared wireless remote control signal can be realized so as to produce all kinds of remote control robot and interactive works. The suite is shown in Fig.3.2.34. 76 Figure .3.2.34 Physical Map of Remote Control Suite Infrared remote control system is mainly divided into modulation, transmitting and receiving parts. The transmitting part is mainly composed of keyboard, remote control specific integrated circuit, exciter and infrared light emitting diode. The integrated circuit is the core part of the launch system which consists internal oscillation circuit, timing circuit, scanning signal generator, key input encoder, instruction decoder, user code converter, digital modulation circuit and buffer amplifier and so on. It can produce a key scanning pulse signal, translate the key code, then obtain remote control commands of the keys by telecommand encoder (remote control encoding pulse). Through pulse amplitude modulation of the 38KHZ carrier signal, the infrared diode can transmit infrared remote control signal. In the infrared receiver, photoelectric converter (usually a photodiode or photoelectric triode, here we use PIN photodiode) converts the received infrared light instruction signal into a corresponding electrical signal. The received signal is very weak and interference is particularly large, in order to achieve the accurate detection and signal conversion, in addition to the infrared photoelectric conversion device with high performance, choosing the reasonable circuit design with good performance is also required. The most common photoelectric conversion device is a photodiode. When the photosensitive surface of the PN junction is irradiated by light, the semiconductor material of PN junction absorbs light energy and converts the light energy into electric energy. When the reverse voltage is added to the photodiode, the reverse current in the diode will change with the change of the incident light intensity. The larger the radiation intensity is, the larger the reverse current will be, the reverse current of the photoelectric varies with the incident light pulse. 77 In the Hummer-Bot car, the integrated infrared receiving head has three pins, including the power supply pin, grounding and signal output pin. The circuit is shown in Fig.3.2.35. Ceramic capacitors is a decoupling capacitor which can filter the output signal interference. The 1 end is the output of the demodulation signal which is directly connected to the number 12 port on the Arduino. When the infrared coded signal is transmitted, it will be processed by the infrared joint, then outputs the square wave signal, and directly supplied to the Arduino, and the corresponding operation is carried out to control the motor. Figure .3.2.35 Circuit Diagram and Physical Map of Infrared Receiving Head 3.2.5.2 Working Principle The remote control system in general composed of the remote controller (transmitter), and receiver, when you press any button on the remote control, it will generate the corresponding encoding pulse and output various control pulse signals based on the infrared, infrared monitor diode sends the signal to the the amplifier and the pulse amplitude limiter, the limiter controls the pulse amplitude at a certain level, regardless of the distance of infrared transmitter and receiver. AC signal enters the band-pass filter which can pass the 30KHZ to the load wave 60KHZ and enters the comparator through the demodulation circuit. The comparator outputs high or low level and restores the output signal waveform. The system procedure diagram is shown in Fig.3.2.36. 78 3.2.5.3 Experimental Procedures 1, Installing the infrared receiving head on the development board (if it has been installed in the the eighth step in "3.1.2", please ignore. The complete installation is shown in Fig.3.1.37. 2, Referring to Fig.3.2.37 and connecting the infrared receiving module to the Arduino board (you can choose other IO ports according to your own ideas) Note: Do not reverse power line, otherwise the receiving head will burn up. Figure .3.1.37 Infrared Module Connection Diagram 3, Copying the following program to IDE (you can also directly open the matching program in the CD), and downloading to the development board, pulled out the transparent plastic sheet marked as "1" in the Fig.3.2.33. Then opening the serial port monitor, observing and recording the values on it while pressing keys on the remote control towards the receiving head as shown in Fig.3.2.38. Program flow chart is as follows: 79 Test code Path : “hummer-bot\Lesson\ModuleDemo\IrkeyPressed\ IrkeyPressed.ino” 80 #include "IRremote.h" IRremote ir(12); unsigned char keycode; char str[128]; void setup() { Serial.begin(9600); ir.begin(); } void loop() { if (keycode = ir.getCode()) { String key_name = ir.getKeyMap(keycode); sprintf(str, "Get ir code: 0x%x key name: %s \n", keycode, (char *)key_name.c_str()); Serial.println(str); } else { // Serial.println("no key"); } delay(110); } Figure .3.2.38 Remote Encoding Query In Figure 3.2.38, we can see two values of Ir Code "0x45" and keyname "1", where "0x45" is the code of a key of the remote controller, and "1" is the name of the key function of the remote controller. 81 The key mapping table is as follows: ST_KEY_MAP irkeymap[KEY_MAX] = { {"1", 0x45}, {"2", 0x46}, {"3", 0x47}, {"4", 0x44}, {"5", 0x40}, {"6", 0x43}, {"7", 0x07}, {"8", 0x15}, {"9", 0x09}, {"0", 0x19}, {"*", 0x16}, {"#", 0x0D}, {"up", 0x18}, {"down", 0x52}, {"ok", 0x1C}, {"left", 0x08}, {"right", 0x5A} }; 3.2.5.4 Wire connection As shown in the below figure, the infrared receiver's “s” pin is connected to “12” pin, the “-” pin is connected to “GND”, and the middle pin is connected to “VCC”. 82 3.2.5.5 Software Design 3.2.5.5.1 Program flow chart 3.2.5.5.2 Program code Code Path : “hummer-bot\Lesson\ModuleDemo\ IRremote\ IRremote.ino” 83 #include */In this section, we use infrared remote control, so we need to call the corresponding library file, as for what is in the library file, we will not study, and interested friends can drive research. We have put this library files on the CD-ROM, we need to copy this folder to the Arduino IDE installation path "libraries" folder, otherwise the program can not compile. */ int E1 = 5;//PWMA int M1 = 9;//DIRA****************************************left int E2 = 6;//PWMB int M2 = 10;//DIRB****************************************right int RECV_PIN = 12; long expedite1 = 0xFF6897;/* Define a long integer expedite1 variable, and assign this variable 0xFF689, FF689 is the infrared remote control button encoding */ long expedite2 = 0xFFB04F; long advance = 0xFF18E7; long back = 0xFF4AB5; long stop = 0xFF38C7; long left = 0xFF10EF; long right = 0xFF5AA5; IRrecvirrecv(RECV_PIN); decode_results results; void setup() { Serial.begin(9600); irrecv.enableIRIn();// Initialize the infrared receiver } 84 void loop() { if (irrecv.decode ( &results) ) {/* Read the value received by the infrared */ if (results.value == advence) {/* Judgment on the received value, if this value is advence, execute the following {} command, here is the forward instruction. */ int val = 150; analogWrite (M1, 0); analogWrite(E1, val);//the speed value of motorA is val analogWrite (M2, 0); analogWrite(E2, val);//the speed value of motorB is val delay(500);irrecv.resume();// Receive the next value } if (results.value == expedite1) {/*Judgment on the value received, if this value is expedite1, execute the command in {} below, here is the acceleration 1 command. */ int val = 200; analogWrite (M1, 0); analogWrite(E1, val);//the speed value of motorA is val analogWrite (M2, 0); analogWrite(E2, val);//the speed value of motorB is val delay(500);irrecv.resume(); } if (results.value == expedite2) {/*Judgment on the received value, if the value is expedite2,execute the command {} below,here for the acceleration 2 command. */ int val = 255; analogWrite (M1, 0); analogWrite(E1, val);//the speed value of motorA is val analogWrite (M2, 0); analogWrite(E2, val);//the speed value of motorB is val delay(500); irrecv.resume(); } if (results.value== stop) {/* To judge the value received, if this value is stop, execute the command in the following {}, here is the stop instruction. */ 85 int val = 0; analogWrite (M1, 0); analogWrite(E1, val);//the speed value of motorA is val analogWrite (M2, 0); analogWrite(E2, val);//the speed value of motorB is val delay(500); irrecv.resume(); } if (results.value == left) {/* Judgment on the received value, if the value is left, execute the command in the following {}, here is the instruction to the left. */ int val = 150; analogWrite (M1, 0); analogWrite(E1, val);//the speed value of motorA is val analogWrite (E2, 0); analogWrite(M2, val);//the speed value of motorB is val delay(500);/* Rotate 500ms to the left and stop, otherwise the car will always be spinning around. */ analogWrite (M1, 0); analogWrite(E1, 0);//the speed value of motorA is 0 analogWrite (M2 ,0); analogWrite(E2, 0);//the speed value of motorB is 0 analogWrite(A1, 180); irrecv.resume(); } if (results.value == right) {/* Judgment on the received value, if the value is right, execute the command in the following {}, here is the command to the right. */ int val = 150; analogWrite (E1, 0); analogWrite(M1, val);//the speed value of motorA is val analogWrite (M2, 0); analogWrite(E2, val);//the speed value of motorA is val delay(500); analogWrite (M1, 0); analogWrite(E1, 0);//the speed value of motorA is 0 analogWrite (M2, 0); 86 analogWrite(E2, 0);//the speed value of motorB is 0 analogWrite(A2, 180); irrecv.resume(); } if (results.value == back) {/* Judgment on the received value, if the value is back, execute the command {} below, here for the back instruction. */ int val = 150; analogWrite (E1, 0); analogWrite(M1, val);//the speed value of motorA is val analogWrite (E2, 0); analogWrite(M2, val);//the speed value of motorA is val delay(500); irrecv.resume();// 接收下一个值 } Serial.println(results.value, HEX);// Output the receive code in hexadecimal Serial.println();// Add a blank line for easy viewing of the output irrecv.resume(); } } The above is the infrared remote reference program, you can open it in the CD and download to the development board, the instructions of remote control in shown in Fig.3.2.39. Fig.3.2.39. Infrared Remote Control Instructions 87 3.2.6 Mobile Phone Bluetooth Control 3.2.6.1 Suite Introduction Hummer-Bot supports Bluetooth mobile phone Bluetooth remote control function is JDY-16 BLE (Bluetooth Low Energy).JDY-16 transparent transmission module is based on the Bluetooth 4.2 protocol standard, operating frequency range is 2.4GHZ range, modulation mode is GFSK, maximum transmission power is 0db, maximum transmission distance is 80 meters, adopts original imported chip design, and supports users to modify device by AT command. Names, service UUIDs, transmit power, pairing passwords, and other instructions are convenient and quick to use. For module information, see “Hummer-bot\Document\JDY-16-V1.2(English manual).pdf” The physical diagram of module is shown in Fig.3.2.40. Fig.3.2.40 JDY-16 Module ◆ JDY-16 function introduction ◆ BLE high speed transparent transmission supports 8K Bytes rate communication. ◆ Send and receive data without byte limit, support 115200 baud rate continuously send and receive data. ◆ Support 3 modes of work (see the description of AT+STARTEN instruction function). ◆ Support (serial port, IO, APP) sleep wake up. ◆ Support WeChat Airsync, WeChat applet and APP communication. ◆ Support 4 channel IO port control. ◆ Support high precision RTC clock. ◆ Support PWM function (can be controlled by UART, IIC, APP, etc.). ◆ Support UART and IIC communication mode, default to UART communication. ◆ iBeacon mode (support WeChat shake protocol and Apple iBeacon protocol). ◆ Host transparent transmission mode (transmission of data between application modules, host and slave communication). 88 3.2.6.2 Bluetooth module test JDY-16 module test method see “hummer-bot\JDY-16\JDY-16 Module Test.pdf” 3.2.6.3 Bluetooth protocol Using Bluetooth to control the car means we use the Android app to control the Bluetooth sending instructions to the Arduino serial port, so as to control the motor's forwarding, reversing, speed and so on. Since the wireless communication is involved, one of the essential issues is the communication problem between the two terminals. But there is no common "language" between them, so designing communication protocols are required to ensure a perfect interaction between Android and Arduino. The main process is: the Android identification terminal packs the detected commands into the corresponding data packets, and then sends them to the Bluetooth module (JDY-16). When JDY-16 receives the packets, it will transmit them to Arduino through the serial port, then Arduino to analyze the data packets and execute the corresponding actions. The data format sent by the upper computer end (Android) is as follows, which mainly contains 8 fields, we use a structure to represent it. Protocol Header Data Length Device Type Device Address Function Code Control Data Check Protocol Sum End Code In the 8 fields above, we use a structural body to represent. typedef struct { unsigned char start_code; // 8bit 0xAA unsigned char len; unsigned char type; unsigned char addr; unsigned short int function; unsigned char *data; // 16 bit // n bit unsigned short int sum; // check sum unsigned char end_code; // 8bit 0x55 }ST_protocol; “Protocol Header” means the beginning of the packet, such as the uniform designation of 0xAA. Data length” means except the valid data length of the start and end codes of the data. “Device type” means the type of device equipment “Device address” means the address that is set for control “Function code” means the type of equipment functions that need to be controlled, the function types we currently support is as follows: 89 typedef enum { E_BATTERY = 1, E_LED = 2, E_BUZZER = 3, E_INFO = 4, E_ROBOT_CONTROL = 5, E_ROBOT_CONTROL_SPEED = 6, E_TEMPERATURE = 7, E_IR_TRACKING = 8, E_ULTRASONIC = 9, E_VERSION = 10, E_UPGRADE = 11, }E_CONTOROL_FUNC ; The data means the specific control value of a car, such as speed, angle. “Checksum” is the result of different or calculated data bits of the control instruction. “Protocol end code ” is the end part of the data bag when receiving this data ,it means that the data pack has been sent, and is ready for receiving the next data pack, here we specified it as 0x55. For example, a complete packet can be such as "AA 070101065000 5F55", in which: "07" is Transmission Data Length 7 bytes. "01" is device type "01" is device address. "06" is the transmission data, such as motor, LED, buzzer and so on. The 06 here refers to the transmission speed, and the 05 refers to the transmission direction. "50 (or 0050)" is the controlling data, 0x50 in hexadecimal is 80 when converted to binary, which means the speed value is 80. "005F" is the check sum, that is, 0x01+0x01+0x06+0x50=0x5F. "55" is the tail of the protocol, indicating the end of data transmission. 90 Fig.3.2.50 the Interface of Android APP In the above Figure.3.2.50: The "A, B" sections are the acceleration and deceleration buttons. The "C" section includes the dashboard and the digital display area, and the two parts displaying synchronously. They represent the current speed. The "D" section is a gravity remote sensing switch which can be switched to the gravity remote sensing mode. The "E" section represents the Bluetooth name that is currently connected. The "F" section indicates Bluetooth connection state. If the Bluetooth is not connected, the "disconnected" is displayed here. The "G" section is a manual rocker, and sliding it allows the car to rotate. The "I" section is a data return area, such as the current state, speed of the car, etc. The "H" section is the data packet, for example, the data is "AA 01 01 06 23 00 2B 55". At this time, the speed is 35 (23 is 16 hexadecimal data, which means 35 when converted to 10 hexadecimal). If the transmitted data is "AA 08 01 01 05 00 5B 00 79 55", it means that the car is moving forward (05 is the direction control instruction, and the 005B means 91 when converted to binary number. By the Figure.3.2.48 we can know that 91 degree means the car is moving forward). 3.2.6.4 Experimental Procedures Connect the Bluetooth module of the wire to "1" marked in Fig.3.2.51 Connection mode: JDY-16 VCC port on Bluetooth module is connected to Arduino 3.6V~6V DC power anode, GND port is connected to the 91 cathode of the DC power, the RXD port is connected to the TXD port on Arduino extended board, TXD port is connected to RXD port on the board, as shown in Fig.3.2.52. Note: Since Arduino UNO has only one serial port, the Bluetooth must be disconnected from the serial port when downloading the program, otherwise the download will fail. Figure .3.2.51 Wiring Positions of Bluetooth 92 Figure .3.2.52 Installation of Bluetooth Module 2, Open the mobile phone Bluetooth and the APP (There is a software installation package on the CD, latter we will launch the IOS version.) You will see that the flashing of the Bluetooth module indicator slows down after successful connection. If you have downloaded the program to the development board before, you can use the phone to control the car directly, as shown in Fig.3.2.53. 93 Figure .3.2.53. Diagram of APP Control In Fig.3.2.53, we can see the logo "1" and "2". When the Bluetooth connection is successful, sliding green dot marked as "1" in any direction, the car will move towards the corresponding direction. Switching on the gravity sensor marked in "2", the APP is switched to the gravity induction mode, and you can control the movement direction of the car by shaking the mobile phone. 3.2.6.5 Wire connection Bluetooth wire connection location as shown below: 94 3.2.6.6 Software Design 3.2.6.6.1 Program flow chart 3.2.6.6.2 Program Code Code Path “hummer-bot\Lesson\Advanced Experiment\Buletooth\ Buletooth.ino” 95 #include "protocol.h" #include "hummerbot.h" #include "process.h" int E1 = 5; //PWMA int M1 = 9; //DIRA --- left int E2 = 6; //PWMB int M2 = 10; //DIRB --- right byte readbuff[32] = {}; int readlen = 0; ST_protocol recv; hummerbot hbot(E1, M1, E2, M2, 13, A0); void setup() { Serial.begin(9600); hbot.init(); } void read_data (void) { unsigned char avilable; byte *p = readbuff ; memset(p, 0, 32); readlen = 0; while (Serial.available() > 0) { if ( !avilable && Serial.peek() == START_CODE) { avilable = 1; } if (avilable) { if (( *p = Serial.read()) == END_CODE) { avilable = 0; readlen++; //Serial.print(*p,HEX); break; } //Serial.print(*p,HEX); p++; readlen++; } } // Serial.print("\n"); } void loop() { read_data(); 96 if ( !protocol_prase(readbuff, readlen, &recv)) { switch (recv.function) { case E_BATTERY: break; case E_LED: break; case E_INFO: break; case E_ROBOT_CONTROL: hbot.drive(protocol_prase_degree( &recv)); break; case E_ROBOT_CONTROL_SPEED: hbot.setSpeed(protocol_prase_speed( &recv)); break; case E_VERSION: break; } } } 97 3.2.7 PS2 Handle (Optional) 3.2.7.1 Suite Introduction PS2 handle is SONY game remote control handle, SONY series game host is very popular in the world. Someone has come up with the idea of the PS2 handle, cracked the communication protocol, so that the handle can be connected to other devices for remote control, such as remote control of our familiar four wheeled vehicles and robots. Its outstanding features are cost-effective, rich buttons and easy to extend to other applications, Fig.3.2.54 shows a commonly used PS2 wireless handle. Figure .3.2.54 PS2 Wireless Handle The PS2 handle is composed of the handle and the receiver, the handle uses two AAA batteries as power supply. The controller and receiver use the same power supply whose voltage range is 3~5V, overvoltage, reverse connection will cause the receiver to burn out. There is a power switch on the handle, ON /OFF, when you switch it to ON, the light on handle will not stop flashing until the receiver is searched. In a certain period of time, if the receiver can’t be find, the handle will enter the standby mode and the light will burn out, you can press "START" button to wake up the handle. The receiver is powered by the Arduino as shown in Fig.3.2.55, in the absence of pairing, the green light flashes. When the handle switch is opened, the handle and receiver will pair automatically, and the light will be always on, and the handle is matched successfully. Button "MODE" (The above logo may be 98 "ANALOG" in different handles, but it will not affect the usefulness), you can choose "red light mode" or "green light mode". Some users see that the handle and receiver cannot match properly! Most of the problems are the incorrect wiring of the receiver and the program problems. Solution: The receiver should only be connected with power supply (power line must be connected correctly), not any data lines and clock lines. The handle light will be always on when pairing is successful. Then checking whether the wiring and program transplantation are correct again. Figure .3.2.55 Remote Control Receiver Module There are 9 interfaces at the end of the receiving head, each of which is shown in the following table: 1 2 3 4 DI/DAT DO/CMD NC GND 5 VDD 6 7 8 9 CS/SEL CLK NC ACK Note: The appearance of the receiver will be different due to different batches, some with a power light, some without, but the use and definition of the pins are the same. DI/DAT: The signal flows from the handle to the host. This signal is a serial 8-bit data which is transmitted synchronously to the falling edge of the clock. The read of the signal is completed in the process of clock changing from high to low; DO/CMD: The signal flows from the host to the handle. The signal is similar to the DI, a serial 8-bit data, which is transmitted synchronously to the falling edge of the clock; NC: Empty port; . GND: Ground; VDD: The 3~5V power supply; CS/SEL: Providing trigger signals for handles, the level is low during communication; CLK: The clock signal is sent by the host to maintain data synchronization; NC: Empty port; ACK: The response signal from the handle to the host. This signal changes to low in the last cycle of each 8-bit data sending, and the CS remains low. If the CS signal do not remain low, the PS host will try another device in about 60 microseconds. The ACK port is not used in programming. 99 3.2.6.2 Experimental Procedure 1、In order to wire simply, we use the PS2 receiver head adapter board and Arduino connection as follows: As shown in the below figure, the six lines of the receiving head are connected to the following places respectively. “CLK” is connected to 11 pins, “CS” is connected to 8 pins, “CMD” is connected to pin 7, “DAT” is connected to 4 pins, and “VCC” is connected to 5V. , "GND" is grounded. Ps2 DAT CMD CS CLK Arduino Uno 4 7 8 11 100 Fix the receiver head to the cart with a cable tie (red frame area in Figure 3.2.55), as shown in Figure 2.3.56. Figure 3.2.55 Receive Head Fixed Bit Figure 3.2.56 Receiving head fixing diagram 101 3、Lead the wire according to the hole marked “1” in Figure 3.2.57, and connect the wire to the Aruino expansion board with reference to Figure 2.3.58. After the completion, as shown as Figure 2.3.57. Figure 3.2.57 Wire Connection Diagram Figure 3.2.58 Connection of Arduino and Receiving Head Wires 4、Open Lesson\ModuleDemo\PS2X\PS2X.ino on the CD Finally, download the program to the Arduino development board and turn on the PS2 remote control. If the receiver head is connected to the remote controller (or the pairing is successful), the indicator light on the 102 receiver head is long, and the LED light is blinking. Finally, we open the "serial monitor", press any button on the remote control, you can see the corresponding data on the "serial monitor", as shown in Figure 3.2.59. Figure 3.2.59 "serial monitor" data display Test code path “hummer-bot\Lesson\ModuleDemo\PS2X\ PS2X.ino” 103 3.2.6.3 Software Design #include "PS2X_lib.h" //for v1.6 /****************************************************************** * set pins connected to PS2 controller: * - 1e column: original * - 2e colmun: Stef? * replace pin numbers by the ones you use ******************************************************************/ #define PS2_DAT 4 #define PS2_CMD 7 #define PS2_SEL 8 #define PS2_CLK 11 /****************************************************************** * select modes of PS2 controller: * - pressures = analog reading of push-butttons * - rumble = motor rumbling * uncomment 1 of the lines for each mode selection ******************************************************************/ //#define pressures #define pressures //#define rumble #define rumble true false true false PS2X ps2x; // create PS2 Controller Class //right now, the library does NOT support hot pluggable controllers, meaning //you must always either restart your Arduino after you connect the controller, //or call config_gamepad(pins) again after connecting the controller. int error = 0; byte type = 0; byte vibrate = 0; // Reset func void (* resetFunc) (void) = 0; 104 void setup() { Serial.begin(9600); delay(500); //added delay to give wireless ps2 module some time to startup, before configuring it //CHANGES for v1.6 HERE!!! **************PAY ATTENTION************* //setup pins and settings: GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error error = ps2x.config_gamepad(PS2_CLK, PS2_CMD, PS2_SEL, PS2_DAT, pressures, rumble); if(error == 0){ Serial.print("Found Controller, configured successful "); Serial.print("pressures = "); if (pressures) Serial.println("true "); else Serial.println("false"); Serial.print("rumble = "); if (rumble) Serial.println("true)"); else Serial.println("false"); Serial.println("Try out all the buttons, X will vibrate the controller, faster as you press harder;"); Serial.println("holding L1 or R1 will print out the analog stick values."); Serial.println("Note: Go to www.billporter.info for updates and to report bugs."); } else if(error == 1) Serial.println("No controller found, check wiring, see readme.txt to enable debug. visit www.billporter.info for troubleshooting tips"); else if(error == 2) Serial.println("Controller found but not accepting commands. see readme.txt to enable debug. Visit www.billporter.info for troubleshooting tips"); else if(error == 3) Serial.println("Controller refusing to enter Pressures mode, may not support it. "); type = ps2x.readType(); 105 switch(type) { case 0: Serial.println("Unknown Controller type found "); break; case 1: Serial.println("DualShock Controller found "); break; case 2: Serial.println("GuitarHero Controller found "); break; case 3: Serial.println("Wireless Sony DualShock Controller found "); break; } } void loop() { /* You must Read Gamepad to get new values and set vibration values ps2x.read_gamepad(small motor on/off, larger motor strenght from 0-255) if you don't enable the rumble, use ps2x.read_gamepad(); with no values You should call this at least once a second */ if(error == 1){ //skip loop if no controller found resetFunc(); } if(type == 2){ //Guitar Hero Controller ps2x.read_gamepad(); //read controller if(ps2x.ButtonPressed(GREEN_FRET)) Serial.println("Green Fret Pressed"); if(ps2x.ButtonPressed(RED_FRET)) Serial.println("Red Fret Pressed"); if(ps2x.ButtonPressed(YELLOW_FRET)) Serial.println("Yellow Fret Pressed"); if(ps2x.ButtonPressed(BLUE_FRET)) Serial.println("Blue Fret Pressed"); if(ps2x.ButtonPressed(ORANGE_FRET)) Serial.println("Orange Fret Pressed"); if(ps2x.ButtonPressed(STAR_POWER)) Serial.println("Star Power Command"); 106 if(ps2x.Button(UP_STRUM)) //will be TRUE as long as button is pressed Serial.println("Up Strum"); if(ps2x.Button(DOWN_STRUM)) Serial.println("DOWN Strum"); if(ps2x.Button(PSB_START)) //will be TRUE as long as button is pressed Serial.println("Start is being held"); if(ps2x.Button(PSB_SELECT)) Serial.println("Select is being held"); if(ps2x.Button(ORANGE_FRET)) { // print stick value IF TRUE Serial.print("Wammy Bar Position:"); Serial.println(ps2x.Analog(WHAMMY_BAR), DEC); } } else { //DualShock Controller ps2x.read_gamepad(false, vibrate); //read controller and set large motor to spin at 'vibrate' speed if(ps2x.Button(PSB_START)) //will be TRUE as long as button is pressed Serial.println("Start is being held"); if(ps2x.Button(PSB_SELECT)) Serial.println("Select is being held"); if(ps2x.Button(PSB_PAD_UP)) { //will be TRUE as long as button is pressed Serial.print("Up held this hard: "); Serial.println(ps2x.Analog(PSAB_PAD_UP), DEC); } if(ps2x.Button(PSB_PAD_RIGHT)){ Serial.print("Right held this hard: "); Serial.println(ps2x.Analog(PSAB_PAD_RIGHT), DEC); } if(ps2x.Button(PSB_PAD_LEFT)){ Serial.print("LEFT held this hard: "); Serial.println(ps2x.Analog(PSAB_PAD_LEFT), DEC); } if(ps2x.Button(PSB_PAD_DOWN)){ Serial.print("DOWN held this hard: "); Serial.println(ps2x.Analog(PSAB_PAD_DOWN), DEC); } 107 vibrate = ps2x.Analog(PSAB_CROSS); //this will set the large motor vibrate speed based on how hard you press the blue (X) button if (ps2x.NewButtonState()) { //will be TRUE if any button changes state (on to off, or off to on) if(ps2x.Button(PSB_L3)) Serial.println("L3 pressed"); if(ps2x.Button(PSB_R3)) Serial.println("R3 pressed"); if(ps2x.Button(PSB_L2)) Serial.println("L2 pressed"); if(ps2x.Button(PSB_R2)) Serial.println("R2 pressed"); if(ps2x.Button(PSB_TRIANGLE)) Serial.println("Triangle pressed"); } if(ps2x.ButtonPressed(PSB_CIRCLE)) //will be TRUE if button was JUST pressed Serial.println("Circle just pressed"); if(ps2x.NewButtonState(PSB_CROSS)) //will be TRUE if button was JUST pressed OR released Serial.println("X just changed"); if(ps2x.ButtonReleased(PSB_SQUARE)) //will be TRUE if button was JUST released Serial.println("Square just released"); if(ps2x.Button(PSB_L1) || ps2x.Button(PSB_R1)) { //print stick values if either is TRUE Serial.print("Stick Values:"); Serial.print(ps2x.Analog(PSS_LY), DEC); //Left stick, Y axis. Other options: LX, RY, RX Serial.print(","); Serial.print(ps2x.Analog(PSS_LX), DEC); Serial.print(","); Serial.print(ps2x.Analog(PSS_RY), DEC); Serial.print(","); Serial.println(ps2x.Analog(PSS_RX), DEC); } } delay(50); } 108 In the above program, we instructed to read the test button. In this experiment we want to implement the PS2 remote control car function. We firstly define all the button functions as follows: Figure .3.2.60 Functions of PS2 Handle Buttons Mark UP: move forward Mark DOWN: move backward Mark LEFT: turn left Mark RIGHT: right Mark A: speed up Mark B: servo turns left Mark C: slow down Mark D: servo turns right Mark 3: Right joystick (mark 5) control key, only when you press R1, the Right joystick will work. Mark 4: Left joystick (mark 6) control key, only when you press L1, the Left joystick will work. Joystick left: joystick remotes control direction Joystick Right:joystick remotes control speed Ps2 Control program in Lesson\Advanced Experiment\PS2XControl\PS2XControl.ino 109 The program flow chart is as follows: Code path “hummer-bot-new\hummer-bot\Lesson\Advanced Experiment\PS2XControl\ PS2XControl.ino” 110
Source Exif Data:
File Type : PDF File Type Extension : pdf MIME Type : application/pdf PDF Version : 1.7 Linearized : No Page Count : 113 Language : zh-CN Tagged PDF : Yes XMP Toolkit : 3.1-701 Producer : Microsoft® Word 2016 Creator : 灯昏酒满 Creator Tool : Microsoft® Word 2016 Create Date : 2019:01:10 09:22:46+08:00 Modify Date : 2019:01:10 09:22:46+08:00 Document ID : uuid:7AB6C360-EA0B-44A8-A28A-DB7388D0C8BE Instance ID : uuid:7AB6C360-EA0B-44A8-A28A-DB7388D0C8BE Author : 灯昏酒满EXIF Metadata provided by EXIF.tools