KS0507 Keyestudio Smart RV Kit: Difference between revisions
Keyestudio (talk | contribs) |
Keyestudio (talk | contribs) |
||
Line 1,596: | Line 1,596: | ||
(1)Description:<br> | (1)Description:<br> | ||
<br>[[File:0507--图片16.png|500px|frameless|thumb]]<br> | <br>[[File:0507--图片16.png|500px|frameless|thumb]]<br> | ||
With I2C communication module, this is a display module that can show 2 lines with 16 characters per line.<br> | |||
It shows blue background and white word and connects to I2C interface of MCU, which highly save the MCU resources.<br> | |||
On the back of LCD display, there is a blue potentiometer for adjusting the backlight. The communication address defaults to 0x27.<br> | |||
The original 1602 LCD can start and run with 7 IO ports, but ours is built with ARDUINOIIC/I2C interface, saving 5 IO ports. Alternatively, the module comes with 4 positioning holes with a diameter of 3mm, which is convenient for you to fix on other devices.<br> | |||
Notice that when the screen gets brighter or darker, the characters will become more visible or less visible.<br> | |||
(2) Specification:<br> | |||
* I2C address: 0x27 | |||
* Backlight (blue, white) | |||
* Power supply voltage: 5V | |||
* Adjustable contrast | |||
* GND: A pin that connects to ground | |||
* VCC: A pin that connects to a +5V power supply | |||
* SDA: A pin that connects to analog port 20 for IIC communication | |||
* SCL: A pin that connects to analog port 21 for IIC communication |
Revision as of 11:45, 17 March 2021
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 can help customers at any level learn electronics and programming knowledge. Likewise, 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/KS0507
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 from 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 tutorial. Improper operation may cause parts to overheat damage. 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
Description:
When it comes to programming, many think it difficult. However, KEYES group issues a smart RV kit to cope with this problem.
This is low cost, easy-to-build and open source programming kit-----smart RV.
It integrates smart home and robot car. In addition, it helps you absorb the knowledge of programming like electronics, control logic and computing and science.
In compliance with the tutorial, you can create your own robot by boards, slot connection and wiring. In the assembly process, the detailed projects will guide you to learn the working principle of sensors and modules.
What’s more, it a has temperature humidity sensor and an LCD display except LED, line tracking sensor, ultrasonic sensor, Bluetooth module and motor driving modules.
Should you are interested in STEM and code programming, you can customize your RV by altering code and adding extra modules.
That sounds entertaining, right? Let’s get started1
Features
- Multi-purpose function:obstacle avoidance, line tracking, Bluetooth control, ultrasonic follow, smart sensation and so on.
- Easy to build:Slot connection and without soldering circuit
- Novel style:Adopt strong wood board, acrylic board, RGB and lcd1602 modules.
- High extension:configure motor driving chip, preserve IIC, UART and SPI port and expand other sensor and module.
- Basic programming learning:use C language and code
Specification:
- Working voltage: 5v
- Input voltage: 7-12V
- Maximum output current: 3A
- Maximum power dissipation: 15W
- Motor speed: 200 rpm (4.5V)
- Motor driving form: TB6612 chip drive
- Ultrasonic sensing angle: <15 degrees
- Ultrasonic detection distance: 2cm-400cm
- Bluetooth remote control distance: 50 meters (measured)
- Bluetooth APP control: support Android and iOS system
Kit
Remember to check if the components received are in line with the following product list when you getting this kit.
Getting Started with Arduino
Installing Arduino IDE
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:
You can download either Windows win7 and newer or Windows ZIP file.
The first one doesn’t require
There are two versions of IDE for WINDOWS system, you can choose from the Installer (.exe) and the Zip packages. We suggest you use the first one that installs directly everything you need to use the Arduino Software (IDE), including the drivers.
With the Zip package you need to install the drivers manually. The Zip file is also useful if you want to create a portable installation.
You just need to click JUST DOWNLOAD.
Keyestudio MEGA 2560 Smart Development Board
We need to know keyestudio MEGA 2560 development board, as a core of this smart car.
The processor core of MEGA 2560 board is ATMEGA2560-16AU, with the cp2102 chip.
It has 54 digital input/output pins (of which 15 can be used as PWM outputs), 16 analog inputs, 4 UARTs (hardware serial ports), a 16 MHz crystal oscillator, a USB connection, a power jack, 1 ICSP header, and a reset button.
It can be interfaced computer with external power with a USB cable.
Install Driver on Windows System
Let’s install the driver of keyestudio MEGA 2560 smart development board. The USB-TTL chip on this board adopts CP2102 serial chip. The driver program of this chip is included in Arduino 1.8 version and above, which is convenient. Plugged in USB port, 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.
There is a yellow exclamation mark on the page, which implies installing unsuccessfully. Then we double click the hardware and update the driver.
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:
There is a DRIVERS folder in Arduino software installed package. Just 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 can follow my way)
Open device manager, we will find the yellow exclamation mark disappear. The driver of CP2102 is installed successfully.
Install Driver on MAC System
The USB to serial chip of control board is CP2102. We install driver on MAC as follows: https://wiki.keyestudio.com/How_to_Install_the_Driver_of_CP2102_on_MAC_System
Arduino IDE Setting
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)
Then select the correct COM port (you can see the corresponding COM port after the driver is successfully installed)
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.
Note: the setting method on Mac system is same as on Windows system except different COM port, as shown below:
Start First Program
We’ve known how to download and install the driver of development board , next, we will burn a code to show“Hello World!”in the monitor.
Test Code
void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } void loop() { // print out "Hello world!" Serial.println("Hello world!"); delay(1000);// delay 1 second }
Open Arduino IDE, and set board as follows:
Set COM port, as shown below:
Click to start compiling the program, and check errors.
Click to upload the program, upload successfully.
Upload the program successfully, open serial monitor and set baud rate to 9600. Monitor will print“Hello World!”each 1s.
Congratulation, you finish the first program.
Projects
For detailed projects, nevigated the website https://fs.keyestudio.com/KS0507
The whole project begins with basic program. Starting from simple to complex, the lessons will guide you to assemble smart RV and absorb the knowledge of electronic and machinery step by step. I reckon that you might hardly sit still and itch to have a go, let’s get started.
Note: (G), marked on each sensor and module, is negative pole and connected to“G”,“-”or“GND”on the sensor shield or control board ; (V) is positive pole and interfaced with“V”,“VCC”,“+”or“5V”on the sensor shield or control board.
Project 1: LED Blink
(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. It is often applied to numbers and text display as an indicator in the circuit.
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) Parameter:
- Control interface: digital port
- Working voltage: DC 3.3-5V
- Pin spacing: 2.54mm
- LED display color: red
(3) Component:
(4)Connection Diagram:
From the above diagram, pin -, + and S of LED module are respectively connected to pin G, 5V and D13 of expansion board. Then we compile the code as follows:
(5)Test Code:
/* keyestudio smart RV lesson 1.1 Blink http://www.keyestudio.com */ #define LED 13 //define the pin of LED as D13 void setup() { pinMode(LED, OUTPUT);// initialize digital pin LED as an output. } void loop() // the loop function runs over and over again forever { digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level delay(1000); // wait for a second digitalWrite(LED, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } //*******************************************************************
(6)Test Result:
Upload the program, LED blinks with the interval of 1s.
(7)Code Explanation:
pinMode(LED,OUTPUT) - This function can denote that the pin is INPUT or OUTPUT.
digitalWrite(LED,HIGH) - When pin is OUTPUT, we can set it to HIGH(output 5V) or LOW(output 0V).
(8)Extension Practice:
The LED flashes for 1s through the test result, therefore, pins and delay time affect flash frequency.
/* keyestudio smart RV lesson 1.2 Blink http://www.keyestudio.com */ #define LED 13 //Define the pin of LED as D13 void setup() { pinMode(LED, OUTPUT);// initialize digital pin LED as an output. } void loop() // the loop function runs over and over again forever { digitalWrite(LED, HIGH); // turn LED on (HIGH is the voltage level delay(100); // wait for a second digitalWrite(LED, LOW); // turn LED off by making the voltage LOW delay(100); // wait for a second } //****************************************************************
The LED flashes faster through the lesson 1.2 test.
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.
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)Component:
(3)Connection Diagram:
We keep connection diagram unchanged.
(4)Test Code:
/* keyestudio smart RV lesson 2.1 PWM http://www.keyestudio.com */ #define LED 13 //Define the pin of LED as D13 int value; void setup() { pinMode(LED, OUTPUT);// initialize digital pin LED as an output. } void loop () { for (value = 0; value < 255; value = value + 1) { analogWrite (LED, value); // LED lights gradually light up delay (5); // delay 5MS } for (value = 255; value > 0; value = value - 1) { analogWrite (LED, value); // LED gradually goes out delay (5); // delay 5MS } }
(5) Test Result:
Upload test code successfully, LED gradually becomes brighter then darker, like human breath.
(6) Code Explanation
When we need to repeat some statements, we could use FOR statement.
FOR statement format is shown below:
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.
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.
(7) Extension Practice:
Let’s keep pins unchanged and change the delay value, then observe how LED changes.
/* keyestudio smart RV lesson 2.2 PWM http://www.keyestudio.com */ #define LED 13 //Define the pin of LED as D13 int value; void setup() { pinMode(LED, OUTPUT);// initialize digital pin LED as an output. } void loop () { for (value = 0; value < 255; value = value + 1) { analogWrite (LED, value); // LED lights gradually light up delay (20); // delay 30MS } for (value = 255; value > 0; value = value - 1) { analogWrite (LED, value); // LED gradually goes out delay (20); // delay 30MS } } //**********************************************************
Upload code to development board, the LED’s blink frequency is slower, isn’t it?
Project 3: Button Module
(1)Description: In this project, we control LED brightness by button module. The low level(0) is output when the button is pressed; however, high level(1) is output when button is released.
(2)Specification:
- Operating Voltage: 3.3-5V (DC)
- Control Signal: Digital signal
- Detection Height: 0-3 cm
- Weight: 3.8g
- Dimension: 34*22*15mm
(3)Component:
(4)Connection Diagram:
Note: the pin G, V and S of button sensor are interfaced with pin G, V and
D2 of expansion board, and connect pin G, V and S of LED module to G, V
and D13 of expansion board.
(5)Test Code:read the signal of button
/* keyestudio smart RV lesson 3.1 button http://www.keyestudio.com */ #define button 2 //Define the pin of LED as D12 volatile int buttonState; //The output level state of button module void setup() { Serial.begin(9600);//set baud rate to 9600 pinMode(button, INPUT);// initialize digital pin button as an input. } void loop () { buttonState = digitalRead(button); Serial.println(buttonState); //auto wrap and output the digital signals from digital 2 delay(100);//delay in 100ms }
(6)Test Result:
Upload code, open serial monitor to set baud rate to 9600. The number “1”shows up then“0”appears on the monitor.
(7)Code Explanation:
Serial.begin(9600)- Initialize serial port, set baud rate to 9600
pinMode(pin, INPUT)-This function can denote that the pin is INPUT or OUTPUT
digitalRead(pin)-Read the state of pin, which are generally HIGH and LOW level. Function digitalRead() will come back to HIGH or LOW level if pins are not connected.
(8) Extension Practice:button-controlled LED
/* keyestudio smart RV lesson 3.2 button http://www.keyestudio.com */ #define LED 13 //Define the pin of LED as D13 #define button 2 //Define the pin of button module as D2 volatile int buttonState; //the state of button void setup() { Serial.begin(9600); //set baud rate to 9600 pinMode(button, INPUT); // initialize digital pin button as an input. pinMode(LED, OUTPUT); // initialize digital pin LED as an output. } void loop () { buttonState = digitalRead(button); //read the status of button if (buttonState == 0) //if the button is pressed { digitalWrite(LED, HIGH); //Turn on LED } else { digitalWrite(LED, LOW); //turn off LED } delay(100); //dealy in 100ms
It turns out that LED is on when the button is pressed, and LED off when button is released.
Project 4: Line Tracking Sensor
(1)Description:
The tracking sensor is actually an infrared sensor. The component used here is the TCRT5000 infrared tube.
Its working principle is to use the different reflectivity of infrared light to the color, then convert the strength of the reflected signal into a current signal.
During the process of detection, black is active at HIGH level, but white is active at LOW level. The detection height is 0-3 cm.
Keyestudio 3-channel line tracking module has integrated 3 sets of TCRT5000 infrared tube on a single board, which is more convenient for wiring and control.
By rotating the adjustable potentiometer on the sensor, it can adjust the detection sensitivity of the sensor.The tracking sensor is actually an infrared sensor.
(2) Specification:
- Operating Voltage: 3.3-5V (DC)
- Interface: 5PIN
- Output Signal: Digital signal
- Detection Height: 0-3 cm
Note: Adjust the sensitivity by rotating the potentiometer before the test. The sensitivity is best when LED is at on and off state.
(3) Component:
(4)Connection Diagram:
(5)Test Code:
/* keyestudio smart RV lesson 4.1 Line Track sensor http://www.keyestudio.com */ //Line Tracking Sensor #define L_pin 50 #define M_pin 51 #define R_pin 52 void setup() { Serial.begin(9600); //Set baud rate to 9600 pinMode(L_pin, INPUT); //set pins of line tracking sensor to INPUT pinMode(M_pin, INPUT); pinMode(R_pin, INPUT); } void loop () { int L_val = digitalRead(L_pin); //read the value of left sensor int M_val = digitalRead(M_pin); //read the value of middle sensor int R_val = digitalRead(R_pin); //read the value of right sensor Serial.print(L_val); Serial.print(" "); Serial.print(M_val); Serial.print(" "); Serial.print(R_val); Serial.println(" "); delay(100); //delay in 100ms }//****************************************************************************
(6)Test Result:
Upload code to development board, open serial monitor to check the state of three line tracking sensors. When no signals are received, they are in high level state and“1”shows up ; however, 1 changes into 0 when covering sensor with white paper.
(7) Code Explanation:
Serial.begin(9600)-initialize the serial port, set serial baud rate to 9600
pinMode- define the PIN state(input and output) of MCU
digitalRead- read the level status of pin(HIGH, LOW)
(8)Extension Practice:
We’ve known how line tracking sensor works, next, we connect an LED at pin 13. We will control LED on and off by line tracking sensor, as shown below
Test Code
/* keyestudio smart RV lesson 4.2 Line Track sensor http://www.keyestudio.com */ //LED pin #define LED 13 //Line Tracking Sensor #define L_pin 50 #define M_pin 51 #define R_pin 52 void setup() { Serial.begin(9600); //set baud rate to 9600 pinMode(LED, OUTPUT); //set LED to OUTPUT pinMode(L_pin, INPUT); //set the pin of line tracking sensor to INPUT pinMode(M_pin, INPUT); pinMode(R_pin, INPUT); } void loop () { int L_val = digitalRead(L_pin); //read the value of left sensor int M_val = digitalRead(M_pin); //read the value of middle sensor int R_val = digitalRead(R_pin); //read the value of right sensor Serial.print(L_val); Serial.print(" "); Serial.print(M_val); Serial.print(" "); Serial.print(R_val); Serial.println(" "); delay(100); //delay in 100ms if (L_val == 0 || M_val == 0 || R_val == 0) { digitalWrite(LED, HIGH); } else { digitalWrite(LED, LOW); } } //****************************************************************************
Upload the code to development board, we observe LED get brighter when covering the line tracking sensor by hand.
Project 5: PIR Motion Sensor
(1)Description:
The Pyroelectric infrared motion sensor can detect infrared signals from a moving person or animal, and output switching signals. It can be applied to a variety of occasions to detect the movement of human body. Conventional pyroelectric infrared sensors are much more bigger, with complex circuit and lower reliability. Now we launch this new pyroelectric infrared motion sensor, specially designed for ARDUINO. This sensor integrates a digital pyroelectric infrared sensor and connecting pins. It features higher sensibility and reliability, lower power consumption, light weight, small size, lower voltage working mode and simpler peripheral circuit.
(2)Specification:
- Input voltage: DC 3.3V ~ 5V
- Working current: 15uA
- Working temperature: -20 ~ 85 degrees Celsius
- Output voltage: high 3 V, low 0 V
- Output delay time (high level): about 2.3 to 3 seconds
- Detection angle: about 100 °
- Detection distance: 3-4 meters
- Output indicator LED (high-level )
- Pin limit current: 100mA
Note:
1. The maximum distance is 3-4 meters during testing.
2. When testing, firstly open the white lens, you can see the rectangular sensing part. When the long line of the rectangular sensing part is parallel to the ground, the distance is the best.
3. When testing, need to cover the sensor with white lens, otherwise it will affect the distance.
4. The distance is best at 25℃, and the detection distance is shortened when it exceeds 30℃.
5. Done powering up and uploading the code, you need to wait 5-10 seconds then start testing, otherwise it is not sensitive.
(3)Component:
(4)Connection Diagram
Note: on expansion board, the pin G, V and S of PIR motion sensor are connected to G, V and 47; pin G, V and S of LED module are connected to G, V and 13.
(5)Test Code:
/* keyestudio smart RV lesson 5.1 PIR http://www.keyestudio.com */ //PIR Motion Sensor #define PIR 47 //PIR pin to D47 void setup() { Serial.begin(9600); //set baud rate to 9600 pinMode(PIR, INPUT); //set the pin of PIR motion sensor to INPUT } void loop () { int val = digitalRead(PIR); //set the variable val to the value read Serial.println(val); delay(100); //delay in 100ms }
(6)Test Result:
Upload code, open serial monitor and set baud rate to 9600. The serial monitor will show“1”when PIR motion sensor detects people around; on the contrary, number“0”will appear on the monitor when nobody is detected.
/* keyestudio smart RV lesson 5.2 PIR http://www.keyestudio.com */ //PIR Motion Sensor #define PIR 47 //PIR pin to D47 #define LED 13 //LED pin to D13 void setup() { pinMode(LED, OUTPUT); //set LED to OUTPUT pinMode(PIR, INPUT); //set PIR motion sensor to INPUT } void loop () { int val = digitalRead(PIR); //set val to the value read by sensor if (val == 1) { //People is detected digitalWrite(LED, HIGH); //turn on LED } else { digitalWrite(LED, LOW); //otherwise, lED will be off } }
The LED connected to digital 13 will be on when the sensor detects people moving, otherwise, LED will be off.
Project 6: 4*4 Membrane Keypad
(1)Description:
To save I/O ports of MCU, we make a Membrane Keypad. In this project, we will make an experiment; serial monitor will display the corresponding character when the membrane keypad is pressed.
Schematic Diagram:
(2)Specification:
- Working Voltage: 3.3V~5V
- Port:digital port
(5)Test Code:
/* keyestudio smart RV lesson 6.1 Keypad http://www.keyestudio.com */ #include <Keypad.h> const byte ROWS = 4; //four rows const byte COLS = 4; //four columns char keypressed; //define the cymbols on the buttons of the keypads char keyMap[ROWS][COLS] = { {'1', '2', '3', 'A'}, {'4', '5', '6', 'B'}, {'7', '8', '9', 'C'}, {'*', '0', '#', 'D'} }; byte rowPins[ROWS] = {14, 15, 16, 17}; //Row pinouts of the keypad byte colPins[COLS] = {36, 37, 38, 39}; //Column pinouts of the keypad Keypad myKeypad = Keypad( makeKeymap(keyMap), rowPins, colPins, ROWS, COLS); void setup() { Serial.begin(9600); //set baud rate to 9600 } void loop () { keypressed = myKeypad.getKey(); //read key value if (keypressed != NO_KEY) { //read key value Serial.print("key:"); Serial.println(keypressed); //print key value } }
(6)Test Result:
Download code, open serial monitor and set baud rate to 9600. The serial monitor will show the corresponding key value when the key of membrane keypad is pressed, as shown below;
Project 7: Power Amplifier Module
(1)Description:
We can use Arduino to make many interactive works of which the most commonly used is acoustic-optic display.
All the previous experiment has something to do with LED. However, the experiment of this chapter is related to produce sound. Normally, the experiment is done with a buzzer or a speaker.
In this lesson, we will replace buzzer with power amplifier module, input different frequencies square wave to emit different sound like“do re mi fa so la si do”.
(2) Specification:
- Control interface: digital port
- Working voltage: DC 3.3-5V
(3) Component:
(4) Connection Diagram:
Note: the pin G, V and S of passive buzzer are connected to pin G, V and D49 of expansion board
(5)Test Code:
//************************************************************************* /* keyestudio smart car lesson 7.1 buzzer http://www.keyestudio.com */ #define buzzer 49 //buzzer pin to D49 void setup() { pinMode(buzzer, OUTPUT);//set digital 49 to OUTPUT } void loop () { tone(buzzer, 262); //buzzer emits the sound with 262Hz delay(250); //delay in 250ms tone(buzzer, 294);; //buzzer emits the sound with 294Hz delay(250); //delay in 250ms tone(buzzer, 330); delay(250); tone(buzzer, 349); delay(250); tone(buzzer, 392); delay(250); tone(buzzer, 440); delay(250); tone(buzzer, 494); delay(250); tone(buzzer, 532); delay(250); noTone(buzzer); //buzzer turns off sound output delay(1000); } //*************************************************************************************
(6) Test Result:
Upload code to MEGA 2560 smart development board, power amplifier module will emit“do re mi fa so la si do”.
(7)Project Extension:Playing Music
/* keyestudio smart RV lesson 7.2 buzzer http://www.keyestudio.com */ #define buzzer 49 //buzzer pin to D49 void setup() { pinMode(buzzer, OUTPUT);//set digital 3 to OUTPUT } void loop () { birthday(); } ////////////////////////set "Happy Birthday" Song////////////////////////////////// void birthday() { tone(buzzer, 294); //buzzer emits sound with 294Hz delay(250);//delay in 250ms tone(buzzer, 440); delay(250); tone(buzzer, 392); delay(250); tone(buzzer, 532); delay(250); tone(buzzer, 494); delay(500); tone(buzzer, 392); delay(250); tone(buzzer, 440); delay(250); tone(buzzer, 392); delay(250); tone(buzzer, 587); delay(250); tone(buzzer, 532); delay(500); tone(buzzer, 392); delay(250); tone(buzzer, 784); delay(250); tone(buzzer, 659); delay(250); tone(buzzer, 532); delay(250); tone(buzzer, 494); delay(250); tone(buzzer, 440); delay(250); tone(buzzer, 698); delay(375); tone(buzzer, 659); delay(250); tone(buzzer, 532); delay(250); tone(buzzer, 587); delay(250); tone(buzzer, 532); delay(500); }
Project 8: RGB Module
(1)Description:
In the previous project, we know how to control the LED brightness.Yet, in this chapter, we will learn a special LED---- RGB. RGB LED is divided into
Common cathode means that all the cathodes are connected to a single pin. Common anode means that all the anodes are connected to a single pin. We use common anode RGB.
Common anode RGB LED has 4 pins and its anodes are interfaced with +5V. The rest of LEDs need a 220Ω resistor in cascade series to prevent circuit from burning.
We need to interface R, G and B signal ends of RGB with PWM ports of MCU. In addition, the color proportion of LED can be controlled by adjusting three PWM values, that is, LED can display different colors.
The larger corresponding color proportion is, the larger the PWM value we set.
(2)Specification:
- Working voltage: DC 5V
- Working current: 0.6A (maximum)
- Maximum power: 0.3W
- Working temperature: -25~+65℃
- Interface: 4pin header (spacing 2.54mm)
- Positioning hole: 3mm in diameter
- Size: 30*20mm
- Environmental protection attributes: ROHS
(5)Test Code:
/* keyestudio smart RV lesson 8.1 RGB http://www.keyestudio.com */ #define RGB_R 3 //define pin R of RGB as D3 #define RGB_B 4 // define pin B of RGB as D4 #define RGB_G 5 //define pin B of RGB as D5 void setup() { pinMode(RGB_R, OUTPUT); //set the digital ports to OUTPUT pinMode(RGB_G, OUTPUT); pinMode(RGB_B, OUTPUT); } void loop () { set_RGBColor(0,255,255); //red delay(500); set_RGBColor(255,0,255); //green delay(500); set_RGBColor(255,255,0); //blue delay(500); } //set color void set_RGBColor(int red, int green, int blue) { analogWrite(RGB_R, red); analogWrite(RGB_G, green); analogWrite(RGB_B, blue); }
(6)Test Result:
After uploading code, RGB module shows red, green and blue colors.
(7)Project Extension:display random color
/* keyestudio smart RV lesson 8.2 RGB http://www.keyestudio.com */ #define RGB_R 3 //define the pin R of RGB as D3 #define RGB_B 4 //set pin B of RGB to D4 #define RGB_G 5 //set pin g of RGB to D5 int r, g, b; void setup() { pinMode(RGB_R, OUTPUT); // set digital ports of RGB to OUTPUT pinMode(RGB_G, OUTPUT); pinMode(RGB_B, OUTPUT); } void loop () { //choose a random number from 0 to 255 r = random(255); g = random(255); b = random(255); set_RGBColor(r, g, b); //random colors delay(500); } //set color void set_RGBColor(int red, int green, int blue) { analogWrite(RGB_R, red); analogWrite(RGB_G, green); analogWrite(RGB_B, blue); }
Project 9: Adjustable Rotary Potentiomete
(1)Description:
There is a rotary potentiometer module which uses a 10K adjustable resistor in this kit. By rotating the potentiometer, we can change the value of the resistor and then build the circuit to convert the resistance change into the voltage change. In addition, its voltage can be divided into 1025 parts and can be easily connected to 2560 control board.
In this chapter, we will adjust LED brightness by potentiometer.
(2)Specification:
- Operating voltage: 3.3V to 5V
- Interface: analog interface
(4)Connection Diagram:
(5) Test Code:
/* keyestudio smart motorhome lesson 9.1 Adjustable potentiometer http://www.keyestudio.com */ #define RES A3 //potentiometer pin to A3 volatile int value=0; void setup() { Serial.begin(9600);//set baud rate } void loop () { value = analogRead(RES); //read the value of potentiometer Serial.println(value); //print value delay(100); //delay in 100MS }
(6) Code Explanation:
1. In the project,we set pins to A3.
2. Set a integer to variable value and assign the detected result to value.
3. Serial monitor shows the value of variable value, and set baud rate to 9600.
analogRead(pin)-read the analog value of pin, mega2560 control board had 16 analog ports (A0-A15), in the range of 0~1023,that is, the accuracy is 5V/1024=0.0049V.
map(value, fromLow, fromHigh, toLow, toHigh)-value is mapped value,fromLow- current value range lower limit,fromHigh- current value range upper limit,toLow- target value range lower limit,toHigh-target value range upper limit.
(7) Test Result:
Upload code, power on with USB cable, open serial monitor and set baud rate to 9600. The serial monitor shows the corresponding analog value.
In the project, rotate the potentiometer clockwise, and the analog value increases; yet, the analog value(0-1023) decreases if rotating anticlockwise, as shown below,
(8)Project Extension:control LED brightness by potentiometer
/* keyestudio smart motorhome lesson 9.2 Adjustable potentiometer http://www.keyestudio.com */ #define RES A3 //set potentiometer pin to A3 #define LED 13 //define the pin of LED as D13 volatile int value = 0; void setup() { pinMode(LED, OUTPUT);// initialize digital pin LED as an output. } void loop () { value = analogRead(RES); //read the value of potentiometer int light = map(value, 0, 1023, 0, 255); //map the analog value 0~1023 of potentiometer to 0~255 analogWrite(LED, light); //set LED brightness to light delay(100); //delay in 100MS }
Project10: Ambient Light Sensor
(1)Description:
Ambient light sensor adopts TEMT6000 element which is a high sensitivity and visible photo sensitive (NPN type) triode. It can catch tiny light ray, amplify for 100 times and be recognized by MCU. What’s more, the reaction to light is similar to human eyes, which can determine light intensity and help create interactive appliances.
(2) Specification:
- Working voltage: 3.3V-5V (DC)
- Interface: 3PIN interface
- Output signal: analog signal
- Weight: 2.3g
(4) Connection Diagram:
Note: pin G,V and S of ambient light sensor are separately interfaced with G, V and A4; pin G, V and S of LED module are connected to G, V and 13.
(5) Test Code:
//**************************************************************************** /* keyestudio smart motorhome lesson 10.1 photovaristor http://www.keyestudio.com */ #define photos A4 //set photoresistance pin to A4 #define LED 13 //define the pin of LED as D13 volatile int value = 0; void setup() { Serial.begin(9600); pinMode(LED, OUTPUT);// initialize digital pin LED as an output. } void loop () { value = analogRead(photos); //read the value of photoresistor Serial.println(value); if (value < 300) { //when the analog vlaue is les than 300 digitalWrite(LED, HIGH); //turn on LED } else { //when the analog value is higher than 300 digitalWrite(LED, LOW); //turn off LED } delay(100); //delay in 100MS } //***************************************************************************
(6) Test Result:
Wire up, upload code and set baud rate to 9600. We see the value detected by ambient light sensor.
The value reduces when covering ambient sensor, however, LED will be on when the value is less than 300; on the contrary, LED will be off.
Project 11:Steam Sensor
(1)Description:
This is a commonly used steam sensor. Its principle is to detect the amount of water by bare printed parallel lines on the circuit board. The more the water is, the more wires will be connected. As the conductive contact area increases, the output voltage will gradually rise. It can detect water vapor in the air as well. The steam sensor can be used as a rain water detector and level switch. When the humidity on the sensor surface surges, the output voltage will increase.
The sensor is compatible with various microcontroller control boards, such as Arduino series microcontrollers. When using it, we provide the guide to operate steam sensor and Arduino control board. Connect the signal end of the sensor to the analog port of the microcontroller, sense the change of the analog value, and display the corresponding analog value on the serial monitor.
Note: the connect part is not waterproof, don’t immerse it in the water please.
(7)Specification:
Working voltage: DC 3.3-5V
Working current: <20mA
Operating temperature range: -10℃~+70℃;
Control signal: analog signal output
Interface: 2.54mm 3pin pin interface
Size: 35*20*8mm
Weight: 2.2g
3. Pin Description:
S:signal pin output
V(+):Power(VCC)
G(-):Ground(GND)
(3) Component:
(4) Connection Diagram:
Note: on expansion board, pin G, V and S of steam sensor are connected to G, V and A2.
(6)Test Code:
//************************************************************************* /* keyestudio smart motorhome lesson 11.1 water sensor http://www.keyestudio.com */ #define waterpin A5 //water sensor pin to A5 volatile int water = 0; void setup() { Serial.begin(9600); } void loop () { water = analogRead(waterpin); //read the analog value of water sensor Serial.println(water); delay(100); } //******************************************************************************
(7)Test Result:
Upload code, power on according to connection diagram, open serial monitor and set baud rate to 9600. The value on monitor increases when the water is on steam sensor; whereas, the value decreases when the water is wiped off.
(8)Project Extension:
Power amplifier module will alarm when the water content exceeds 300
/* keyestudio smart motorhome lesson 11.2 water sensor http://www.keyestudio.com */ #define waterpin A5 //define the pin of water sensor as A5 #define buzzer 49 //define the pin of buzzer as D49 volatile int water = 0; void setup() { Serial.begin(9600); pinMode(buzzer, OUTPUT);//set buzzer to OUTPUT } void loop () { water = analogRead(waterpin); //read the analog value of water sensor Serial.println(water); if (water > 300) { //when the analog value is more than 300 tone(buzzer,2000); //buzzer emits the sound with 2000Hz } else { //when the analog value is less than 300 noTone(buzzer); //turn off buzzer } }
Project 12 Analog Gas(MQ-2)Sensor
(1)Description:
This gas sensor is used for household gas leak alarms, industrial combustible gas alarms and portable gas detection instruments. And it is suitable for the detection of liquefied gas, benzene, alkane, alcohol, hydrogen, etc., and widely used in various fire alarm systems. The MQ-2 smoke sensor can be accurately a multi-gas detector, and has the advantages of high sensitivity, fast response, good stability, long life, and simple drive circuit.
It can detect the concentration of flammable gas and smoke in the range of 300~10000ppm.Meanwhile, it has high sensitivity to natural gas, liquefied petroleum gas and other smoke, especially to alkanes smoke.
It must be heated for a period of time before using the smoke sensor, otherwise the output resistance and voltage are not accurate. However, the heating voltage should not be too high, otherwise it will cause my internal signal line to blow.
It is belongs to the tin dioxide semiconductor gas-sensitive material, and belongs to the surface ion type N-type semiconductor. At a certain temperature, tin dioxide adsorbs oxygen in the air and forms negative ion adsorption of oxygen, reducing the electron density in the semiconductor, thereby increasing its resistance value. When in contact with flammable gas in the air and smog, if the potential barrier at the grain boundary is adjusted by the smog, it will cause the surface conductivity to change. With this, information about the presence of smoke or flammable gas can be obtained. The greater the concentration of smoke or flammable gas in the air, the greater the conductivity, and the lower the output resistance, the larger the analog signal output. The sensor comes with a positioning hole, which is convenient for you to fix the sensor to other devices. In addition, the sensitivity can be adjusted by rotating the potentiometer.
(2) Specification:
- Working voltage: 3.3-5V (DC)
- Interface: 4 pins (GND, VCC, D0, A0)
- Output signal: digital signal and analog signal
- Weight: 7.5g
(3) Component:
(4) Connection Diagram:
Note: on expansion board, the pin GND, VCC, D0 and A0 of analog gas (MQ-2)sensor are interfaced with G,V, A1 and A0.
(5) Test Code:
//******************************************************************************** /* keyestudio smart motorhome lesson 12.1 MQ2 http://www.keyestudio.com */ #define MQ2_A A0 //define the pin mq2 as A0 #define MQ2_D A1 //define the pin mq2 as A1 volatile int analogVal,digitalVal; void setup() { Serial.begin(9600); } void loop () { digitalVal = digitalRead(MQ2_D); //read the digital value analogVal = analogRead(MQ2_A); //read the analog value Serial.print("digitalVal:"); Serial.print(digitalVal); Serial.print(" analogVal:"); Serial.println(analogVal); delay(100); } //******************************************************************************
(6) Test Result:
Wire up, upload code and open serial monitor to set baud rate to 9600.
The analog value increases and digital level varies from 1 to 0 when the combustible gas is detected.
(7) Project Extension:
Power amplifier module will alarm when the detected combustible gas is leaked.
/* keyestudio smart motorhome lesson 12.2 MQ2 http://www.keyestudio.com */ #define MQ2_A A0 // define MQ2_A as A0 #define MQ2_D A1 //define MQ2_A as A1 #define buzzer 49 //buzzer pin to D49 volatile int analogVal, digitalVal; void setup() { Serial.begin(9600); } void loop () { analogVal = analogRead(MQ2_A); //read the analog value Serial.println(analogVal); //print the value of sensor if (analogVal > 150) { //when analog value exceeds 150, the buzzer will alarm tone(buzzer, 1000); } else { noTone(buzzer); //turn off buzzer } delay(100); }
Project 13 DHT11 Temperature and Humidity Sensor
This DHT11 Temperature and Humidity Sensor is a composite sensor which contains a calibrated digital signal output of the temperature and humidity.Its technology ensures high reliability and excellent long-term stability. A high-performance 8-bit microcontroller is connected.This sensor includes a resistive element and a sense of wet NTC temperature measuring devices. It has excellent quality, fast response, anti-interference ability and high cost performance advantages.Each DHT11 sensor features extremely accurate calibration data of humidity calibration chamber. The calibration coefficients stored in the OTP program memory, internal sensors detect signals in the process, and we should call these calibration coefficients.The single-wire serial interface system is integrated to make it quick and easy. Qualities of small size, low power, and 20-meter signal transmission distance make it a wide applied application or even the most demanding one.
(2) Specification:
- Supply Voltage: +5 V
- Temperature range: 0-50 ℃ error of ± 2 ℃
- Humidity: 20-90% RH ± 5% RH error
- Interface: Digital
(3) Component:
(8)Connection Diagram:
In the project, we need to import the library of DHT11.
(9)Test Code:
/* keyestudio smart motorhome lesson 13.1 DHT11 http://www.keyestudio.com */ #include <dht11.h> //include the library code: dht11 DHT; #define DHT11_PIN 47 //define DHT11 as 48 void setup() { Serial.begin(9600); } void loop () { int chk; chk = DHT.read(DHT11_PIN); // READ DATA switch (chk) { case DHTLIB_OK: break; case DHTLIB_ERROR_CHECKSUM: break; case DHTLIB_ERROR_TIMEOUT: break; default: break; } // DISPLAT DATA Serial.print("humidity:"); Serial.print(DHT.humidity); Serial.print(" temperature:"); Serial.println(DHT.temperature); delay(100); }
(10)Test Result:
Upload code, power on with USB cable,open serial monitor and the temperature and humidity data is shown below:
Project 15 Ultrasonic Sensor
(1)Description:
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:
Project 14 Servo Control
(1)Description
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.
In general, servo has three line in brown, red and orange. Brown wire is grounded, red one is positive pole line and orange one is signal line.
The corresponding servo angles are shown below:
(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) Component:
(4) Connection Diagram:
Note: The servo is connected to G (GND), V (VCC),8. The brown wire of the servo is connected to Gnd (G), the red wire is linked with 5v (V), and the orange wire is connected to digital pin 8.
Remember to connect external power due to the high current of driving motor.
(6)Test Code1:
/* keyestudio smart motorhome lesson 14.1 servo http://www.keyestudio.com */ int servoPin = 8; //pin of servo void setup() { pinMode(servoPin, OUTPUT);//set the pin of servo to OUTPUT } void loop() { servopulse(servoPin, 0);//rotate to 0° delay(1000);//delay 1s servopulse(servoPin, 90);//rotate to 900° delay(1000); servopulse(servoPin, 180);//rotate to 180° delay(1000); } void servopulse(int pin, int myangle) { //output function int pulsewidth = map(myangle, 0, 180, 500, 2500); //map angle to pulsewidth for (int i = 0; i < 10; i++) { //output pulse digitalWrite(pin, HIGH);//set level of servo port to HIGH delayMicroseconds(pulsewidth);//delay the time of pulsewidth digitalWrite(pin, LOW);//set the level of servo port to LOW delay(20 - pulsewidth / 1000); } } //**********************************************************************************
Upload code successfully, servo swings forth and back in the range of 0° 90° and 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
(7)Test Code2:
/* keyestudio smart motorhome lesson 14.2 servo http://www.keyestudio.com */ #include <Servo.h> //include the library code: Servo myservo; void setup() { myservo.attach(8); //connect servo to digital 8 } void loop () { //rotate 0° to 180° for (int i = 0; i < 180; i++) { myservo.write(i); delay(20); } delay(1000); //delay in 1s //rotate from 180° to 0° for (int i = 180; i > 0; i--) { myservo.write(i); delay(20); } delay(1000); //delay in 1s } //********************************************************************************
(8)Test Result:
Upload code successfully and power on, servo swings in the range of 0° to 180°.
(9)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 the pin of servo.
2. 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. attached()——Judge if the parameter of servo is sent to its interface
Note: The above written format is“servo variable name, specific statement()”, for instance: myservo.attach(8)
Project 15 Ultrasonic Sensor
(1)Description:
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:
(3) Component:
(4) The principle of ultrasonic sensor
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.
Circuit diagram of ultrasonic sensor:
(5) Connection Diagram:
Wiring guide:
Ultrasonic sensor keyestudio V5 Sensor Shield
VCC → 5v(V)
Trig → 22(S)
Echo → 23(S)
Gnd → Gnd(G)
(6) Test Code:
/* keyestudio smart motorhome lesson 15.1 Ultrasonic sensor http://www.keyestudio.com */ //Ultrasonic Sensor #define EchoPin 23 //ECHO to D23 #define TrigPin 22 //TRIG to D22 float dis; void setup() { Serial.begin(9600); pinMode(EchoPin, INPUT); // set pin ECHO to INPUT pinMode(TrigPin, OUTPUT); //set pin TRIG to OUTPUT } void loop () { digitalWrite(TrigPin, LOW); delayMicroseconds(2); digitalWrite(TrigPin, HIGH); //trigger TrigPin at least 10us high level delayMicroseconds(10); digitalWrite(TrigPin, LOW); dis = pulseIn(EchoPin, HIGH) / 2 / 29.1; //calculate distance delay(50); //delay in 50ms Serial.print("distance: "); Serial.print(dis); Serial.println("cm"); } //**************************************************************************
(7) Test Result:
Upload code to development board, open serial monitor and set baud rate to 9600. The serial monitor shows the distance, and unit is cm. The value reduces when covering the ultrasonic sensor.
(8) Code Explanation:
int trigPin- this pin is defined to transmit ultrasonic waves, generally output.
int echoPin - this is defined as the pin of reception, generally input
cm = (duration/2) / 29.1
inches = (duration/2) / 74
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’ve known how to detect the distance, next, let’s try to control an LED with detected distance
Value.
Connect an LED module at D13
/* keyestudio smart motorhome lesson 15.2 Ultrasonic sensor http://www.keyestudio.com */ //Ultrasonic Sensor #define EchoPin 23 //ECHO to D23 #define TrigPin 22 //TRIG to D22 const int LED = 13; //led pin to D13 volatile int distance; void setup() { Serial.begin(9600); pinMode(EchoPin, INPUT); //set pin ECHO to INPUT pinMode(TrigPin, OUTPUT); //set pin TRIG to OUTPUT pinMode(LED, OUTPUT); } void loop () { distance = get_distance(); //set distance to variable distance Serial.println(distance); if (distance < 10) { digitalWrite(LED, HIGH); } else { digitalWrite(LED, LOW); } } int get_distance() { //detect distance by ultrasonic sensor int dis; digitalWrite(TrigPin, LOW); delayMicroseconds(2); digitalWrite(TrigPin, HIGH); //trigger TRIG at least 10us high level delayMicroseconds(10); digitalWrite(TrigPin, LOW); dis = pulseIn(EchoPin, HIGH) / 58; //calculate distance delay(10); //delay in 50ms return dis; } //****************************************************************************
Upload the above code to development board. Do you find LED on when covering ultrasonic sensor by hand?
Project 16: 1602 LCD Display
(1)Description:
With I2C communication module, this is a display module that can show 2 lines with 16 characters per line.
It shows blue background and white word and connects to I2C interface of MCU, which highly save the MCU resources.
On the back of LCD display, there is a blue potentiometer for adjusting the backlight. The communication address defaults to 0x27.
The original 1602 LCD can start and run with 7 IO ports, but ours is built with ARDUINOIIC/I2C interface, saving 5 IO ports. Alternatively, the module comes with 4 positioning holes with a diameter of 3mm, which is convenient for you to fix on other devices.
Notice that when the screen gets brighter or darker, the characters will become more visible or less visible.
(2) Specification:
- I2C address: 0x27
- Backlight (blue, white)
- Power supply voltage: 5V
- Adjustable contrast
- GND: A pin that connects to ground
- VCC: A pin that connects to a +5V power supply
- SDA: A pin that connects to analog port 20 for IIC communication
- SCL: A pin that connects to analog port 21 for IIC communication