Ks0428 keyestudio Mini Tank Robot V2

From Keyestudio Wiki
Jump to navigation Jump to search

Thanks for your support on our products, we will continue to provide you better quality and service!

*About keyestudio

Keyestudio is a best-selling brand owned by KEYES Corporation, our product lines range from controller boards, shields and sensor modules to smart car and complete starter kits for Arduino, Raspberry Pi and BBC micro:bit, which designed for customers of any level to learn electronics and programming knowledge. All of our products comply with international quality standards and are greatly appreciated in a variety of different markets throughout the world. You can obtain the details and the latest information through visiting the following web sites:http://www.keyestudio.com

*References and After-sales Service

1.Download Profile:https://fs.keyestudio.com/KS0428 2.Feel free to contact us please, if there is missing part or you encounter some troubles. Welcome to send email to us:service@keyestudio.com. We will update projects and products continuously based on your sincere advice.

*Warning

1.This product contains tiny parts(screws, copper pillars), keep it out of reach of children under 7 years old please. 2. This product contains conductive parts (control board and electronic module). Please operate according to the requirements of this tutorial. Improper operation may cause overheating and damage parts. Do not touch and immediately disconnect the circuit power.


*Copyright

The keyestudio trademark and logo are the copyright of KEYES DIY ROBOT co.,LTD. All products under keyestudio brand can’t be copied, sold and resold without authorization by anyone or company. If you’re interested in our items, please contact to our sales representatives: fennie@keyestudio.com


thumb



Introduction

Nowadays, technological education such as VR, kids programming, and artificial intelligence, has become mainstream in educational industry. Thereby, people attach importance to STEAM education. Arduino is pretty notable in Maker education.

So what is Arduino? Arduino is an open-source electronics platform based on easy-to-use hardware and software. Arduino boards are able to read inputs - light on a sensor, a finger on a button, or a Twitter message - and turn it into an output - activating a motor, turning on an LED, publishing something online. Based on this, Keyestudio team has designed a mini tank robot. The tank robot has a processor which is programmable using the Arduino IDE, to mapped its pins to sensors and actuators by a shield that plug in the processor, it reads sensors and controls the actuators and decides how to operate.

15 learning projects, from simple to complex, will guide you how to make a smart tank robot on you own and introduce the detailed knowledge about sensors and modules.
Simultaneously, it is the best choice if you intend to obtain a DIY robot for learning programming, entertainment and competition requirement.


Features

1.Multi-purpose: Obstacle avoidance, follow, IR remote control, Bluetooth control, light following, ultrasonic follow and displaying expressions.
2.Simple assembly: No soldering circuit required, complete assembly easily.
3. High Tenacity:Aluminum alloy bracket, metal motors, high quality wheels and tracks.
4. High extension: expand other sensors and modules through motor driver shield and sensor shield
5. Multiple controls: IR remote control, App control(IOS and Android system)
6.Basic programming:C language code of Arduino IDE.

Specification

  • Working voltage: 5v
  • Input voltage: 7-12V
  • Maximum output current: 2A
  • Maximum power dissipation: 25W (T=75℃)
  • Motor speed: 5V 200 rpm/min
  • Motor drive mode: dual H bridge drive (L298P)
  • Ultrasonic induction angle: <15 degrees
  • Ultrasonic detection distance: 2cm-400cm
  • Infrared remote control distance: 10 meters (measured)
  • Bluetooth remote control distance: 50 meters (measured)

Product List

Make sure no any parts missing please when you get this robot kit. And if it is, please feel free to contact us.


thumb

thumb

thumb

thumb

thumb

thumb

thumb

thumb

thumb

thumb

thumb

thumb

Assembly Guide

After making an inventory all the parts in this kit, then we need to mount the tank robot. Let’s install smart car in compliance with the following instructions.

Step 1: Install the tank bottom motor

Prepare the parts as follows:

  • M4 nut * 2
  • Metal motor *2
  • Metal holder *2
  • Copper coupler *2
  • Blue supporting parts *2
  • M4*12MM inner hex screw * 2
  • L-type M1.5 inner hex wrench *1
  • L-type M3 inner hex wrench *1
  • L-type M2.5 inner hex wrench *1
  • M3*8MM inner hex screw * 4


thumb

thumb

Step 2: Install the tank driver wheel

Prepare the parts as follows:

  • M4*12MM inner hex screw * 2
  • M4*50MM inner hex screw * 2
  • Tank Load-bearing wheel * 2
  • Flange Bearing * 4
  • Copper bush *2
  • Caterpillar Band *2
  • M4 self-locking nut * 2
  • L-type M3 inner hex wrench *1


thumb

thumb

thumb


Step 3: Install the battery holder

Prepare the parts as follows:


thumb


  • Battery holder *1
  • M3 nut * 2
  • Blue Metal holder *2
  • M4 nut *8
  • M3*10MM flat-head screw * 2
  • M4*40MM inner hex screw *4
  • L-type M2.5 inner hex wrench *1
  • L-type M3 inner hex wrench *1
  • M3*25MM inner hex screw *4

Finish the above part. Go to fix the metal holder on the motor wheel with four M4*40MM inner hex screws and four M4 nuts.
thumb

thumb

thumb

Step 4: Mount the sensor module

  • Install Acrylic board and sensor modules:
  • Acrylic Board * 2
  • L- type black bracket *1
  • Photocell Sensor *2
  • IR Receiver Module *1
  • 8X16 LED Panel *1
  • M2 Nut *4
  • M3 Nut *10
  • M3*8MM inner hex screw * 4
  • L-type M2.5 inner hex wrench *1
  • M3*12MM Round-head screw *7
  • M2*11MM dual-pass copper pillar *4
  • M2*10MM Round-head screw * 8


thumb

thumb

thumb

thumb

Step 5: Install the servo platform

Prepare the parts as follows:

  • Servo *1
  • Black gimbal *1
  • Cable tie *2
  • M2x8 Round head cross tapping screw *2
  • Ultrasonic *1
  • M2*4 screw *1
  • M1.2*5 screw *4

Note: For convenient debugging, make sure that the ultrasonic module is in front of tank robot, and the angle of servo motor is 90°. Therefore, we need to set servo to 90° before installing the servo platform.


thumb

thumb


Step 6: Install all parts of Acrylic plate

Prepare the parts as follows:

  • M2*5MM round head screw *4
  • M3*6MM round head screw *8
  • M3*12MM round head screw *2
  • M3 nickel plating nut *2
  • L298P Shield *1
  • V4.0 Board *1
  • V5 Sensor Shield *1
  • Screwdriver *1
  • Bluetooth *1


thumb

thumb

thumb

thumb

Step 7: Hook-up Guide


thumb

thumb

Step 8: Wire up LED panel


thumb

thumb


Step 9: Install all parts of Acrylic plate


thumb

thumb

thumb

thumb

thumb

thumb

thumb

thumb

Step 10: Final Renderings


thumb

Install Arduino IDE and Driver

Download software

When we get control board, we need to download Arduino IDE and driver firstly. You could download Arduino IDE from the official website: https://www.arduino.cc/, click the SOFTWARE on the browse bar, click “DOWNLOADS” to enter download page, as shown below:


thumb

There are various versions for Arduino, just download a suitable version for your system, we will take WINDOWS system as an example to show you how to download and install.


thumb

There are two versions for WINDOWS system, one is installed version, another one is download version, you just need to download file to computer directly and unzip it. These two versions can be used normally. Choose one and download on your computer.


thumb

You just need to click JUST DOWNLOAD, then click the downloaded file to install it. And when the ZIP file is downloaded, you can directly unzip and start it.






































Installing driver

Let’s install the driver of keyestudio PLUS control board. The USB-TTL chip on PLUS board adopts CP2102 serial chip. The driver program of this chip is included in Arduino 1.8 version and above, which is convenient. Plug on USB port of board, the computer can recognize the hardware and automatically install the driver of CP2102.

If install unsuccessfully, or you intend to install manually, open the device manager of computer. Right click Computer----- Properties----- Device Manager.


thumb

There is a yellow exclamation mark on the page, which implies installing the driver of CP2102 unsuccessfully. Then we double click the hardware and update the driver.


thumb

Click “OK” to enter the following page, click “browse my computer for updated driver software”, find out the installed or downloaded ARDUINO software. As shown below:


thumb

There is a DRIVERS folder in Arduino software installed package(thumb), open driver folder and you can see the driver of CP210X series chips.


We click “Browse”, then find out the driver folder, or you could enter “driver” to search in rectangular box, then click “next”, the driver will be installed successfully. (I place Arduino software folder on the desktop, you could follow my way)


thumb


Open device manager, we will find the yellow exclamation mark disappear. The driver of CP2102 is installed successfully.
thumb

thumb















Arduino IDE Setting

Click0486-12.png icon,open Arduino IDE.
0085=14.png

To avoid the errors when uploading the program to the board, you need to select the correct Arduino board that matches the board connected to your computer. Then come back to the Arduino software, you should click Tools→Board, select the board. (as shown below)
0085=15.png


Then select the correct COM port (you can see the corresponding COM port after the driver is successfully installed)


0085=16.png

0085=17.png


Start your first program

Open the file to select Example, choose BLINK from BASIC, as shown below:



048610png.png


048611png.png

Set board and COM port, the corresponding board and COM port are shown on the lower right of IDE.


048612png.png

Click 0486-20.png to start compiling the program, check errors.


048613png.png

Click 0486-23.pngto upload the program, upload successfully.


048614png.png

Upload the program successfully, the onboard LED lights on for 1s, lights off for 1s. Congratulation, you finish the first program.







Before uploading the program to the board, let’s demonstrate the function of each symbol in the Arduino IDE toolbar.

A- Used to verify whether there is any compiling mistakes or not.
B- Used to upload the sketch to your Arduino board.
C- Used to create shortcut window of a new sketch.
D- Used to directly open an example sketch.
E- Used to save the sketch.
F- Used to send the serial data received from board to the serial monitor.

Projects

Project 1: LED Blink


thumb

(1)Description

For the starter and enthusiast, this is a fundamental program---LED Blink.
LED, the abbreviation of light emitting diodes, consist of Ga, As, P, N chemical compound and so on. The LED can flash diverse color by altering the delay time in the test code. When in control, power on GND and VCC, the LED will be on if S end is high level; nevertheless, it will go off.

(2)Specification


thumb

Control interface: digital port Working voltage: DC 3.3-5V Pin spacing: 2.54mm LED display color: red (3)Equipment


thumb

(4) V5 Sensor Shield
There will be troublesome when we combine Arduino development boards with numerous sensors. However, the V5 sensor shield, compatible with Arduino development board, address this problem perfectly. Just stack V5 board on it. This sensor shield can be inserted into 3pin sensor modules and breaks out some some communication pins, like serial, IIC, and SPI communication as well.

Pins Description


thumb

Connection Diagram:


thumb

Seen from the above diagram, LED is linked with D2

(5) Test Code

/*
 keyestudio Mini Tank Robot V2
 lesson 1.1
 Blink
 http://www.keyestudio.com
*/
void setup()
 { 
    pinMode(2, OUTPUT);// initialize digital pin 2 as an output.
}
void loop() // the loop function runs over and over again forever

{
   digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
   delay(1000); // wait for a second
   digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
   delay(1000); // wait for a second
}
//****************************************************************

(6) Test Result

(There will be contradict about serial communication between code and Bluetooth when uploading code, therefore, don’t link with Bluetooth module before uploading code.) Upload the program on the development board, LED flicker with the interval of 1s.


thumb

(7)Code Explanation

pinMode(2,OUTPUT) - Set pin2 to OUTPUT

digitalWrite(2,HIGH) - When set pin2 to HIGH level(output 5V) or to LOW level(output 0V)

(8)Extension Practice We succeed to blink LED. Next, let’s observe what LED will change if we modify pins and delay time.


Connection Diagram


thumb

We’ve altered pins and connected LED to D10.

Test Code:


/*
 keyestudio Mini Tank Robot V2
 lesson 1.2
 delay
 http://www.keyestudio.com
*/
void setup() {  // initialize digital pin 10 as an output.
   pinMode(10, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
   digitalWrite(10, HIGH); // turn the LED on (HIGH is the voltage level)
   delay(100); // wait for 0.1 second
   digitalWrite(10, LOW); // turn the LED off by making the voltage LOW
   delay(100); // wait for 0.1 second
}
//****************************************************************

The LED flickers faster than before through the test result, therefore, pins and delay time affect flash frequency.

Project 2: Adjust LED Brightness

(1)Description In previous lesson, we control LED on and off and make it blink. In this project, we will control LED brightness through PWM to simulate breathing effect. Similarly, you can change the step length and delay time in the code so as to demonstrate different breathing effect. PWM is a means of controlling the analog output via digital means. Digital control is used to generate square waves with different duty cycles (a signal that constantly switches between high and low levels) to control the analog output.In general, the input voltage of port are 0V and 5V. What if the 3V is required? Or what if switch among 1V, 3V and 3.5V? We can’t change resistor constantly. For this situation, we need to control by PWM.


thumb

For the Arduino digital port voltage output, there are only LOW and HIGH, which correspond to the voltage output of 0V and 5V. You can define LOW as 0 and HIGH as 1, and let the Arduino output five hundred 0 or 1 signals within 1 second. If output five hundred 1, that is 5V; if all of which is 1, that is 0V. If output 010101010101 in this way then the output port is 2.5V, which is like showing movie. The movie we watch are not completely continuous. It actually outputs 25 pictures per second. In this case, the human can’t tell it, neither does PWM. If want different voltage, need to control the ratio of 0 and 1. The more 0,1 signals output per unit time, the more accurately control.


(2) Specification

  • Control interface: digital port
  • Working voltage: DC 3.3-5V
  • Pin spacing: 2.54mm
  • Display color: red


(3) Equipment
thumb

(4) Connection Diagram
thumb

(5) Test Code

/*
 keyestudio Mini Tank Robot V2
 lesson 2.1
 pwm
 http://www.keyestudio.com
*/
int ledPin = 10; // Define the LED pin at D10
int value;
void setup () 
{
pinMode (ledPin, OUTPUT); // initialize ledpin as an output.
}
void loop () 
{
for (value = 0; value <255; value = value + 1)
{
analogWrite (ledPin, value); // LED lights gradually light up
delay (5); // delay 5MS
}
for (value = 255; value> 0; value = value-1)
{
analogWrite (ledPin, value); // LED gradually goes out
delay (5); // delay 5MS
}}//**********************************************************

(6)Test Result

Upload test code successfully, LED gradually becomes brighter then darker, like human breath, rather than light on and off immediately.

(7)Code Explanation

When we need to repeat some statements, we could use FOR statement.
FOR statement format is shown below:


thumb


FOR cyclic sequence: Round 1:1 → 2 → 3 → 4 Round 2:2 → 3 → 4 … Until number 2 is not established, “for”loop is over, After knowing this order, go back to code: for (int value = 0; value < 255; value=value+1){

       ...

} for (int value = 255; value >0; value=value-1){

      ...

} The two“for”statements make value increase from 0 to 255, then reduce from 255 to 0, then increase to 255,....infinitely loop There is a new function in the following ----- analogWrite() We know that digital port only has two state of 0 and 1. So how to send an analog value to a digital value? Here,this function is needed. Let’s observe the Arduino board and find 6 pins marked“~”which can output PWM signals. Function format as follows: analogWrite(pin,value) analogWrite() is used to write an analog value from 0~255 for PWM port, so the value is in the range of 0~255. Attention that you only write the digital pins with PWM function, such as pin 3, 5, 6, 9, 10, 11. PWM is a technology to obtain analog quantity through digital method. Digital control forms a square wave, and the square wave signal only has two states of turning on and off (that is, high or low levels). By controlling the ratio of the duration of turning on and off, a voltage varying from 0 to 5V can be simulated. The time turning on(academically referred to as high level) is called pulse width, so PWM is also called pulse width modulation. Through the following five square waves, let’s acknowledge more about PWM.


thumb

In the above figure, the green line represents a period, and value of analogWrite() corresponds to a percentage which is called Duty Cycle as well. Duty cycle implies that high-level duration is divided by low-level duration in a cycle. From top to bottom, the duty cycle of first square wave is 0% and its corresponding value is 0. The LED brightness is lowest, that is, turn off. The more time high level lasts, the brighter the LED. Therefore, the last duty cycle is 100%, which correspond to 255, LED is brightest. 25% means darker. PWM mostly is used for adjusting the LED brightness or rotation speed of motor. It plays vital role in controlling smart robot car. I believe that you can’t wait to enter next project.


(8) Extension Practice:

Let’s modify the value of delay and remain the pin unchanged, then observe how LED changes.

/*
 keyestudio Mini Tank Robot V2
 lesson 2.2
 pwm-slow
 http://www.keyestudio.com
*/
int ledPin = 10; // Define the LED pin at D10
int value;
void setup () 
{
pinMode (ledPin, OUTPUT); // initialize ledpin as an output.
}
void loop () 
{
for (value = 0; value <255; value = value + 1)
{
analogWrite (ledPin, value); // LED lights gradually light up
delay (30); // delay 30MS
}
for (value = 255; value> 0; value = value-1)
{
analogWrite (ledPin, value); // LED gradually goes out
delay (30); // delay 30MS
}}//**********************************************************

Upload code on the development board and LED gradually get brighter then darker.

Project 3: Photoresistor Sensor


thumb

(1)Description

The photoresistor is a special resistor made of semiconductor materials such as CdS or Selenide septum. The surface is also coated with moisture-proof resin, which has a photoconductive effect. It is sensitive to ambient light. Its resistance varies from different light intensities.

We use the characteristics of the photo-resistor to design the circuit and generate the photo-resistor module.
Connecting the signal pin of photocell module to Analog port, when the stronger the light intensity, the greater the voltage of analog port, the greater the analog value is.
On the contrary, the weaker the light intensity, the smaller the voltage of analog port, the smaller the analog value is. Based on that, we can use the photocell module to read the analog value, so get the ambient light intensity.

(2)Specification


thumb

  • Resistance:5K ohm-0.5Mohm
  • Interface Type: analog
  • Working Voltage: 3.3V-5V
  • Easy installation: with screw fixing holes
  • Pin spacing: 2.54mm

(3)Equipment


thumb

Connection Diagram:


thumb
The two photoresistor sensors are linked with A1 and A2, then finish the experiment via photoresistor connected to A1. Then finish the following experiment via photoresistor connected A1. Let’s read its analog value.


(4)Test Code


/*
 keyestudio Mini Tank Robot V2
 lesson 3.1
 photocell
 http://www.keyestudio.com
*/
int sensorPin = A1;    // select the input pin for the photocell
int sensorValue = 0;  // variable to store the value coming from the sensor
void setup() {
Serial.begin(9600);
}
void loop() {
sensorValue = analogRead(sensorPin);  // read the value from the sensor:
Serial.println(sensorValue);  //Serial port prints the resistance value
delay(500);
}
//******************************************************

(5)Test Result


thumb


Upload code on development board, open serial monitor, check if its value diminishes when covering photoresistor. However, the value increases when uncovered.

(6)Code Explanation analogRead(sensorPin):read the analog value of photoresistor via analog ports. Serial.begin(9600): Initialize the serial port, baud rate of serial communication is 9600 Serial.println : Serial port prints and word wrap.


(7)Extension Practice We’ve known how to read the value of photoresistor. Let’s combine photoresistor with LED and view the status of LED.


thumb
PWM restrains the brightness, so LED is linked with PWM pins, connect LED to pin 10, keep pin of photoresistor unchanged, then design the code:

/*keyestudio Mini Tank Robot V2
lesson 3.2
photocell-analog output
http://www.keyestudio.com
*/
int analogInPin = A1;  // Analog input pin that the photocell is attached to
int analogOutPin = 10; // Analog output pin that the LED is attached to
int sensorValue = 0;        // value read from the pot
int outputValue = 0;        // value output to the PWM (analog out)
void setup() {
Serial.begin(9600);
 }
void loop() {
  // read the analog in value:
  sensorValue = analogRead(analogInPin);
  // map it to the range of the analog out:
  outputValue = map(sensorValue, 0, 1023, 0, 255);
  // change the analog out value:
  analogWrite(analogOutPin, outputValue);
  // wait 2 milliseconds before the next loop for the analog-to-digital
  // converter to settle after the last reading:
 Serial.println(sensorValue);  //serial port prints the value of photoresistor
delay(2);
}
//***************************************************************

Upload code, press it by hand and see the the LED brightness.


Project 4: Servo Control

(1)Description


thumb

Servo motor is a position control rotary actuator. It mainly consists of housing, circuit board, core-less motor, gear and position sensor. Its working principle is that the servo receives the signal sent by MCU or receiver and produces a reference signal with a period of 20ms and width of 1.5ms, then compares the acquired DC bias voltage to the voltage of the potentiometer and obtain the voltage difference output.

When the motor speed is constant, the potentiometer is driven to rotate through the cascade reduction gear, which leads that the voltage difference is 0, and the motor stops rotating. Generally, the angle range of servo rotation is 0° --180 °

The rotation angle of servo motor is controlled by regulating the duty cycle of PWM (Pulse-Width Modulation) signal. The standard cycle of PWM signal is 20ms (50Hz). Theoretically, the width is distributed between 1ms-2ms, but in fact, it's between 0.5ms-2.5ms. The width corresponds the rotation angle from 0° to 180°. But note that for different brand motor, the same signal may have different rotation angle. 


thumb

The corresponding servo angles are shown below:
thumb


(2)Specification

  • Working voltage: DC 4.8V ~ 6V
  • Operating angle range: about 180 ° (at 500 → 2500 μsec)
  • Pulse width range: 500 → 2500 μsec
  • No-load speed: 0.12 ± 0.01 sec / 60 (DC 4.8V) 0.1 ± 0.01 sec / 60 (DC 6V)
  • No-load current: 200 ± 20mA (DC 4.8V) 220 ± 20mA (DC 6V)
  • Stopping torque: 1.3 ± 0.01kg · cm (DC 4.8V) 1.5 ± 0.1kg · cm (DC 6V)
  • Stop current: ≦ 850mA (DC 4.8V) ≦ 1000mA (DC 6V)
  • Standby current: 3 ± 1mA (DC 4.8V) 4 ± 1mA (DC 6V)


(3)Equipment


thumb

(4)Connection Diagram:


thumb

Wiring note: the brown line of servo is linked with Gnd(G), the red line is connected to 5v(V) and orange line is attached to digital 9.

The servo have to be connected to external power, due to its high demand for driving servo current. Generally, the current of development board is not enough. If without connected power, the development board could be burnt.


(5)Test Code1

/*
keyestudio Mini Tank Robot V2
lesson 4.1
Servo
http://www.keyestudio.com
*/
#define servoPin 9  //servo Pin
int pos; //angle variable of servo
int pulsewidth; // pulse width variable of servo
void setup() {
  pinMode(servoPin, OUTPUT);  //set servo pin to OUTPUT
  procedure(0); //set the angle of servo to 0°
}
void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    procedure(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                   //control the rotation speed of servo
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    procedure(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                    
  }
}
// function to control servo
void procedure(int myangle) {
  pulsewidth = myangle * 11 + 500;  //calculate the value of pulse width
  digitalWrite(servoPin,HIGH);
  delayMicroseconds(pulsewidth);   //The duration of high level is pulse width
  digitalWrite(servoPin,LOW);
  delay((20 - pulsewidth / 1000));  // the cycle is 20ms, the low level last for the rest of time
}
//********************************************************************

Upload code successfully, servo swings back in the range of 0° to 180°

There is another guide for restraining servo---- servo library file, the following link of official website is for your reference. https://www.arduino.cc/en/Reference/Servo

Servo library file

(6)Test Code2

/*
 keyestudio Mini Tank Robot V2
 lesson 4.2
 servo
 http://www.keyestudio.com
*/
#include <Servo.h>
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position
void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}
void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}
//****************************************************************

(7)Test Result

Upload code successfully and power on, servo rotates in the range of 0° to 180°. The result is same. We usually control it by library file.

(8)Code Explanation

Arduino comes with #include <Servo.h> (servo function and statement) The following are some common statements of the servo function: 1. attach(interface)——Set servo interface, port 9 and 10 are available

3.write(angle)——The statement to set rotation angle of servo, the angle range is from 0° to 180° 3. read()——The statement to read angle of servo, read the command value of “write()” 4. Note: The above written format is “servo variable name, specific statement()”, for instance: myservo.attach(9)

Project 5: Ultrasonic Sensor

(1)Description


thumb

The HC-SR04 ultrasonic sensor uses sonar to determine distance to an object like bats do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package. It comes complete with ultrasonic transmitter and receiver modules. The HC-SR04 or the ultrasonic sensor is being used in a wide range of electronics projects for creating obstacle detection and distance measuring application as well as various other applications. Here we have brought the simple method to measure the distance with arduino and ultrasonic sensor and how to use ultrasonic sensor with arduino.

(2)Specification


thumb


  • Power Supply :+5V DC
  • Quiescent Current : <2mA
  • Working Current: 15mA
  • Effectual Angle: <15°
  • Ranging Distance : 2cm – 400 cm
  • Resolution : 0.3 cm
  • Measuring Angle: 30 degree
  • Trigger Input Pulse width: 10uS


(3)Equipment


thumb

(4)The principle of ultrasonic sensor

As the above picture shown, it is like two eyes. One is transmitting end, the other is receiving end.

The ultrasonic module will emit the ultrasonic waves after trigger signal. When the ultrasonic waves encounter the object and are reflected back, the module outputs an echo signal, so it can determine the distance of object from the time difference between trigger signal and echo signal. The t is the time that emitting signal meets obstacle and returns. and the propagation speed of sound in the air is about 343m/s, therefore, distance = speed * time, because the ultrasonic wave emits and comes back, which is 2 times of distance, so it needs to be divided by 2, the distance measured by ultrasonic wave = (speed * time)/2

1.Use method and timing chart of ultrasonic module: Setting the delay time of Trig pin of SR04 to 10μs at least, which can trigger it to detect distance. 2. After triggering, the module will automatically send eight 40KHz ultrasonic pulses and detect whether there is a signal return. This step will be completed automatically by the module. 3. If the signal returns, the Echo pin will output a high level, and the duration of the high level is the time from the transmission of the ultrasonic wave to the return.



thumb

Circuit diagram of ultrasonic sensor:


thumb

(5)Connection Diagram


thumb



thumb


(6)Test Code


/*

keyestudio Mini Tank Robot V2
lesson 5
Ultrasonic sensor
http://www.keyestudio.com
  • /

int trigPin = 5; // Trigger int echoPin = 4; // Echo long duration, cm, inches; void setup() {

 //Serial Port begin
 Serial.begin (9600);
 //Define inputs and outputs
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);

} void loop() {

 // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
 // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(trigPin, LOW);
  // Read the signal from the sensor: a HIGH pulse whose
 // duration is the time (in microseconds) from the sending
 // of the ping to the reception of its echo off of an object.
 duration = pulseIn(echoPin, HIGH);
  // Convert the time into a distance
 cm = (duration/2) / 29.1;     // Divide by 29.1 or multiply by 0.0343
 inches = (duration/2) / 74;   // Divide by 74 or multiply by 0.0135
 Serial.print(inches);
 Serial.print("in, ");
 Serial.print(cm);
 Serial.print("cm");
 Serial.println();
 delay(250);

} //****************************************************************


(7)Test Result Upload test code on the development board, open serial monitor and set baud rate to 9600. The detected distance will be displayed, unit is cm and inch. Hinder the ultrasonic sensor by hand, the displayed distance value is smaller.



thumb


(8)Code Explanation int trigPin = 5; this pin is defined pin to transmit ultrasonic waves, generally output. int echoPin = 4; this is defined as the pin of reception, generally input cm = (duration/2) / 29.1; inches = (duration/2) / 74; by 0.0135 We can calculate the distance by using the following formula: distance = (traveltime/2) x speed of sound The speed of sound is: 343m/s = 0.0343 cm/uS = 1/29.1 cm/uS Or in inches: 13503.9in/s = 0.0135in/uS = 1/74in/uS We need to divide the traveltime by 2 because we have to take into account that the wave was sent, hit the object, and then returned back to the sensor. (9)Extension Practice: We have just measured the distance displayed by the ultrasonic. How about controlling the LED with the measured distance? Let's try it, connect an LED light module to the D10 pin.


thumb

/*
 keyestudio Mini Tank Robot V2
 lesson 5
 Ultrasonic LED
 http://www.keyestudio.com
*/ 
int trigPin = 5;    // Trigger
int echoPin = 4;    // Echo
long duration, cm, inches;
void setup() {
  //Serial Port begin
  Serial.begin (9600);
  //Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}
 void loop() 
{
  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Read the signal from the sensor: a HIGH pulse whose
  // duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  duration = pulseIn(echoPin, HIGH);
  // Convert the time into a distance
  cm = (duration/2) / 29.1;     // Divide by 29.1 or multiply by 0.0343
  inches = (duration/2) / 74;   // Divide by 74 or multiply by 0.0135
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  delay(250);
if (cm>=2 && cm<=10)
digitalWrite(10, HIGH);
delay(1000);
digitalWrite(10, LOW);
delay(1000);
}
//****************************************************************

Upload test code to development board and block ultrasonic sensor by hand, then check if LED is on

Project 6: IR Reception

(1)Description There is no doubt that infrared remote control is ubiquitous in daily life. It is used to control various household appliances, such as TVs, stereos, video recorders and satellite signal receivers. Infrared remote control is composed of infrared transmitting and infrared receiving systems, that is, an infrared remote control and infrared receiving module and a single-chip microcomputer capable of decoding.​     The 38K infrared carrier signal emitted by remote controller is encoded by the encoding chip in the remote controller. It is composed of a section of pilot code, user code, user inverse code, data code, and data inverse code. The time interval of the pulse is used to distinguish whether it is a 0 or 1 signal and the encoding is made up of these 0, 1 signals. The user code of the same remote control is unchanged. The data code can distinguish the key. When the remote control button is pressed, the remote control sends out an infrared carrier signal. When the IR receiver receives the signal, the program will decode the carrier signal and determines which key is pressed. The MCU decodes the received 01 signal, thereby judging what key is pressed by the remote control. Infrared receiver we use is an infrared receiver module. Mainly composed of an infrared receiver head, it is a device that integrates reception, amplification, and demodulation. Its internal IC has completed demodulation, and can achieve from infrared reception to output and be compatible with TTL signals. Additionally, it is suitable for infrared remote control and infrared data transmission. The infrared receiving module made by the receiver has only three pins, signal line, VCC and GND. It is very convenient to communicate with arduino and other microcontrollers.


thumb


(2)Specification


  • Operating Voltage: 3.3-5V(DC)
  • Interface: 3PIN
  • Output Signal: Digital signal
  • Receiving Angle: 90 degrees
  • Frequency: 38khz
  • Receiving Distance: 10m


(3)Equipment


thumb

(4)Connection Diagram



thumb

Respectively link “-”、“+” and S of IR receiver module with G(GND), V(VCC)and A0 of keyestudio development board. Attention: On the condition that digital ports are not available, analog ports can be regarded as digital ports. A0 equals to D14, A1 is equivalent to digital 15.


(5)Test Code

Firstly import library file of IR receiver module(refer to how to import Arduino library file) before designing code.

/*
keyestudio Mini Tank Robot V2
lesson 6
IRremote
http://www.keyestudio.com
*/ 
#include <IRremote.h>     // IRremote library statement
int RECV_PIN = A0;        //define the pins of IR receiver as A0
IRrecv irrecv(RECV_PIN);   
decode_results results;   // decode results exist in the “result” of “decode results”
void setup()  
	{  
      Serial.begin(9600);  
      irrecv.enableIRIn(); //Enable receiver
	}  
 void loop() {  
	  if (irrecv.decode(&results))//decode successfully, receive a set of infrared signals
	  {  
	    Serial.println(results.value, HEX);//Wrap word in 16 HEX to output and receive code 
	    irrecv.resume(); // Receive the next value
	  }  
	  delay(100);  
	}  
//*******************************************************


(6)Test Result

Upload test code, open serial monitor and set baud rate to 9600, point remote control to IR receiver and the corresponding value will be shown, if pressing so long, the error codes will appear.


thumb

Below we have listed out each button value of keyestudio remote control. So you can keep it for reference.


(7)Code Explanation irrecv.enableIRIn(): after enabling IR decoding, the IR signals will be received, then function“decode()”will check continuously if decode successfully.

irrecv.decode(&results): after decoding successfully, this function will come back to “true”, and keep result in “results”. After decoding a IR signals, run the resume()function and receive the next signal (8)Extension Practice We decoded the key value of IR remote control. How about restrain LED by the measured value? We could operate an experiment to affirm. Attach a LED to D10. When keep the pin of IR receiver unchanged, LED will be on when pressing the key of remote control; press again, LED will be off.


thumb

/* keyestudio Mini Tank Robot V2
lesson 6.2
IRremote
http://www.keyestudio.com
*/ 
#include <IRremote.h>
int RECV_PIN = A0;//define the pin of IR receiver as A0
int LED_PIN=10;//define the pin of LED
int a=0;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Initialize the IR receiver 
  pinMode(LED_PIN,OUTPUT);//set LED_pin to OUTPUT
}
void loop() {
  if (irrecv.decode(&results)) {
if(results.value==0xFF02FD &a==0) // according to the above key value, press“OK”on remote control , LED will be controlled
{
    digitalWrite(LED_PIN,HIGH);//LED will be on
a=1;
}
else if(results.value==0xFF02FD &a==1) //press again
{
digitalWrite(LED_PIN,LOW);//LED will go off
a=0;
}
    irrecv.resume(); //receive the next value
  }
}
//*******************************************************

Upload code to development board, press“OK”key on remote control to make LED on and off.


Project 7: Bluetooth Remote Control