circuitdigestDetail2

Must Watch!



MustWatch



RS-485 MODBUS Serial Communication with Arduino as Master

RS-485 Serial Communication

is needed as it allows serial communication over long distance of 1200 meters. It is bidirectional and half duplex and has data transfer rate of 2.5 Mbps. This module requires a voltage of 5V.
Pin NameUse
VCC5V
ANon-inverting Receiver Input Non-Inverting Driver Output
BInverting Receiver Input Inverting Driver Output
GNDGND (0V)
R0Receiver Out (RX pin)
REReceiver Output (LOW-Enable)
DEDriver Output (HIGH-Enable)
DIDriver Input (TX pin)

Modbus Slave Software

Each slave in a network is assigned a unique unit address from 1 to 127. When the masterrequests data, the first byte it sends is the Slave address. This way each slave knows afterthe first byte whether or not to ignore the message. It is a 1-bit register and they are used to control discrete outputs and can be read or written. They have register numbers from (1 to 9999). Discrete Input: It is a 1-bit register and used as inputs and can only be read. They have register numbers from (10001 to 19999). It is a 16-bit register used for input and can only be read. They have register numbers from (30001 to 39999). It is a 16-bit register and can be read or written. They have register numbers from (40001 to 49999).
Function CodeActionTable Name
04 (04hex)ReadAnalog Input Registers
03 (03hex)ReadAnalog Output Holding Registers
06 (06hex)Write singleAnalog Output Holding Register
16 (10hex)Write multipleAnalog Output Holding Registers
Supported Coil Function codes:
Function CodeActionTable Name
02 (02hex)ReadDiscrete Input Contacts
01 (01hex)ReadDiscrete Output Coils
05 (05hex)Write singleDiscrete Output Coil
15 (0Fhex)Write multipleDiscrete Output Coils
CRC: CRC stands for Cyclic Redundancy check. It is two bytes added to the end of everyModbus message for error detection.

Components Required

Arduino UNO MAX-485 TTL to RS-485 Converter Module USB to RS-485 Converter Module Push Buttons (2) 10k-Resistor (2) 16x2 LCD display 10k Potentiometer Modbus Slave

Circuit Diagram

0(RX)RO
1(TX)DI
3DE
2RE
+5VVCC
GNDGND
AA
BB
VSSGND
VDD+5V
V0To potentiometer centre pin for contrast control of LCD
RS8
RWGND
E9
D410
D511
D612
D713
A+5V
KGND
is used to provide Analog input value to the Arduino pin A0. After the circuit connections the complete setup looks like this.

Programming Arduino Uno as MODBUS Master

library. Here Arduino Uno has two push buttons and a potentiometer to send the values from Modbus Master Arduino to Modbus Slave software. is given at the end. Here we have explained has some major steps below. First, include the ModbusMaster and Liquid Crystal Library: #include <ModbusMaster.h> #include <LiquidCrystal.h> Next define the Pin names that are connected between the MAX485 TTL to RS-485 converter module and Arduino UNO. #define MAX485_DE 3 #define MAX485_RE_NEG 2 ModbusMaster node; high or low to Transmit or Receive data. void preTransmission() { digitalWrite(MAX485_RE_NEG, 1); digitalWrite(MAX485_DE, 1); } void postTransmission() { digitalWrite(MAX485_RE_NEG, 0); digitalWrite(MAX485_DE, 0); } , the LCD is set in 16x2 mode and a welcome message is displayed and cleared. lcd.begin(16,2); lcd.print("CIRCUIT DIGEST"); delay(3000); lcd.clear(); lcd.print("Arduino"); lcd.setCursor(0,1); lcd.print("Modbus Master"); delay(3000); lcd.clear(); Then RE and DE pins are set as OUTPUT pins and the pins 4 & 5 are set as INPUT pins (Push Buttons). pinMode(MAX485_RE_NEG, OUTPUT); pinMode(MAX485_DE, OUTPUT); pinMode(4,INPUT); pinMode(5,INPUT); Initially the DE and RE pins of the MAX-485 TTL to RS-485 Converter Module is set LOW digitalWrite(MAX485_RE_NEG, 0); digitalWrite(MAX485_DE, 0); Set the baud rate at 115200 and inform the Modbus Master with the slave ID 1. Serial.begin(115200); node.begin(1, Serial); After that call back statements are used so that the RS-485 Transceiver is configured properly. node.preTransmission(preTransmission); node.postTransmission(postTransmission); First the Analog value is read from the pin A0 that is connected with potentiometer. float value = analogRead(A0); Then ADC value of (0 to 1023) is written to the 0x40000 register for sending it to Modbus Slave by using the following statement. node.writeSingleRegister(0x40000,value); Then the value is also displayed in the 16x2 LCD display lcd.setCursor(0,0); lcd.print("POT Val :"); lcd.print(value); Next the state of the two-push buttons is read. int a= digitalRead(4); int b= digitalRead(5); And depending upon the state of the push button, the value 0x40001 for button 1 and 0x40002 for button 2 is written to the Modbus Slave and also displayed on LCD display. if (a == 1) { node.writeSingleRegister(0x40001,1); lcd.setCursor(0,1); lcd.print("S1: 1"); } else { node.writeSingleRegister(0x40001,0); lcd.setCursor(0,1); lcd.print("S1: 0"); } if (b == 1) { node.writeSingleRegister(0x40002,1); lcd.setCursor(8,1); lcd.print("S2: 1"); } else { node.writeSingleRegister(0x40002,0); lcd.setCursor(8,1); lcd.print("S2: 0"); }

Testing the Arduino UNO as RS485 MODBUS Master

After the circuit connections are completed and the code is uploaded to Arduino Uno now its time to connect the USB to RS-485 Module to the PC where the Modbus Slave Software is installed. : Open the device manager and check the COM port according to your PC where the USB to RS-485 Module is connected and then open the Modbus Slave software. and it appears as below. 4. This trial software only runs for 10 minutes after opening it. and Mode as RTU and then click OK. and then click OK. 8. After that verify the ID as 1 and F as 03. In this tutorial first three registers are used (0-Potentiomter ADC value,1-Push button value,2-Push button value). 9. Now when Push button 2 is pressed. Note the value 1 in the third row. As push button 1 is not pressed it remains 0 in second row and in first row some pot value is displayed. 10. When Push button 1 is pressed. Note the value 1 in the second row. And as push button 2 is not pressed so it remains 0 in third row and in first row some pot value is displayed. 11. Now when both the Push Buttons are Pressed, there are value 1 in both rows second and third and also note the potentiometer value. 12. When potentiometer is varied, the Row 1 also varies in the Modbus Slave software. .Check the previous tutorial to see Arduino Uno as slave in MODBUS commination. Code #include <ModbusMaster.h> //Library for using ModbusMaster #include <LiquidCrystal.h> //Library for using LCD display #define MAX485_DE 3 #define MAX485_RE_NEG 2 ModbusMaster node; //object node for class ModbusMaster LiquidCrystal lcd(8,9,10,11,12,13); //Object lcd for class Liquidcrystal with LCD pins (RS, E, D4, D5, D6, D7) that are connected with Arduino UNO. void preTransmission() //Function for setting stste of Pins DE & RE of RS-485 { digitalWrite(MAX485_RE_NEG, 1); digitalWrite(MAX485_DE, 1); } void postTransmission() { digitalWrite(MAX485_RE_NEG, 0); digitalWrite(MAX485_DE, 0); } void setup() { lcd.begin(16,2); lcd.print("CIRCUIT DIGEST"); delay(3000); lcd.clear(); lcd.print("Arduino"); lcd.setCursor(0,1); lcd.print("Modbus Master"); delay(3000); lcd.clear(); pinMode(MAX485_RE_NEG, OUTPUT); pinMode(MAX485_DE, OUTPUT); pinMode(4,INPUT); pinMode(5,INPUT); digitalWrite(MAX485_RE_NEG, 0); digitalWrite(MAX485_DE, 0); Serial.begin(115200); //Baud Rate as 115200 node.begin(1, Serial); //Slave ID as 1 node.preTransmission(preTransmission); //Callback for configuring RS-485 Transreceiver correctly node.postTransmission(postTransmission); } void loop() { float value = analogRead(A0); node.writeSingleRegister(0x40000,value); //Writes value to 0x40000 holding register lcd.setCursor(0,0); lcd.print("POT Val :"); lcd.print(value); int a= digitalRead(4); //Reads state of push button int b= digitalRead(5); if (a == 1) { node.writeSingleRegister(0x40001,1); //Writes 1 to 0x40001 holding register lcd.setCursor(0,1); lcd.print("S1: 1"); } else { node.writeSingleRegister(0x40001,0); //Writes 0 to 0x40001 holding register lcd.setCursor(0,1); lcd.print("S1: 0"); } if (b == 1) { node.writeSingleRegister(0x40002,1); //Writes 1 to 0x40002 holding register lcd.setCursor(8,1); lcd.print("S2: 1"); } else { node.writeSingleRegister(0x40002,0); //Writes 0 to 0x40002 holding register lcd.setCursor(8,1); lcd.print("S2: 0"); } } Video microcontroller-projects/how-to-use-arduino-and-hm-10-ble-module-to-control-led-with-android-app

How to Use HM-10 BLE Module with Arduino to Control an LED using Android App

What is HM10 BLE 4.0 Module?

.

Difference between HM10 and other Bluetooth Module

in open space. Compare to other Bluetooth modules such as HC-05 which is a Bluetooth 2.0 based module, the HM10 certainly performs better than the HC-05. The HC-05 only offers 3 Mbps compared to HM10 which is quite less. are still very popular among makers and hobbyists as they are cheap and easy to interface. We also made many projects using HC-05/06 and interfaced them with many other microcontrollers: Bluetooth Module Interfacing with ESP8266: Controlling an LED Interfacing Bluetooth HC-05 with STM32F103C8 Blue Pill: Controlling LED Interfacing HC-05 Bluetooth module with AVR Microcontroller Interfacing Bluetooth Module HC-06 with PIC Microcontroller Voice Controlled LEDs using Arduino and Bluetooth Voice Controlled Lights using Raspberry Pi can be found at this link. The On/Off commands will be sent by Smartphone.

Components Required

Arduino UNO HM10 Bluetooth Module Resistors(1 kΩ, 470 Ω) Jumper Wires Arduino IDE Arduino Bluetooth Controller(HM-10 Module) Android App Android Smart phone

Circuit Diagram

is very simple as shown below.

Arduino Bluetooth Controller (HM-10 Module) Android Application

Download the app from Google Play Store. The Home page of the app will look like below where you can find features like, connect Device, Search Icon, Delete Icon, Device Status, Send Text, Add Template etc. Start with searching the Device either by clicking on Search Icon or by clicking to three dots on the upper right corner and choose connect Device. All available devices will be shown in the screen. Choose the correct HM-10 Module. Now the HM-10 will be successfully connected and you will be able to see the status of HM-10 in the Top of Screen. Now either you can directly send a text or String by writing on the text section and hit arrow to send or you can create a custom template. To create a custom template to save time. Click on the ᾼstrong>+ᾠicon on upper right corner and fill the details. The ᾼstrong>Nameᾠis button name, the ᾼstrong>Textᾠfield is for texts or string which will be sent to HM-10 and ᾼstrong>Descriptionᾠis just the button description that how the button will function. Firstly, create a button for turn LED ON and give it a Green Color. The Button will send “Nᾠletter to HM-10 which will turn on the LED connected to Arduino. Similarly create a button for LED OFF and give it a Red Color. The Button will send “Fᾠletter to HM-10 which will turn off the LED connected to Arduino. Now you can see the two buttons created just below the Text Field. Now if you want to control LED then just click on the Buttons. Now we will start with the programming Arduino Uno to get the characters from Android App.

Programming Arduino UNO to Control LED using HM-10 Bluetooth Module

The pins Rx and Tx are connected at 2 and 3 Pins of Arduino. #include <SoftwareSerial.h> SoftwareSerial HM10(2, 3); // RX = 2, TX = 3 The two variables are used to store the data received from HM10 and android app. char appData; String inData = ""; and print some debugging statements. The LED pin is set as output and initially it is off. Serial.begin(9600); Serial.println("HM10 serial started at 9600"); HM10.begin(9600); // set HM10 serial at 9600 baud rate pinMode(13, OUTPUT); // onboard LED digitalWrite(13, LOW); // switch OFF LED and read the string until the HM10 is available and sends the data. Save the data in string. HM10.listen(); // listen the HM10 port while (HM10.available() > 0) { // if HM10 sends something then read appData = HM10.read(); inData = String(appData); // save the data in string format Serial.write(appData); } just write the below code line which will send the string to HM10. if (Serial.available()) { // Read user input if available. delay(10); HM10.write(Serial.read()); } If the received string is “Fᾠthen print a message on serial monitor and turn OFF the led else if the received string is “Nᾠthen print a message on serial monitor and Blink led with a delay of 500ms. if ( inData == "F") { Serial.println("LED OFF"); digitalWrite(13, LOW); // switch OFF LED delay(500); } if ( inData == "N") { Serial.println("LED ON"); digitalWrite(13, HIGH); // switch OFF LED delay(500); digitalWrite(13, LOW); // switch OFF LED delay(500); } Code #include <SoftwareSerial.h> SoftwareSerial HM10(2, 3); // RX = 2, TX = 3 char appData; String inData = ""; void setup() { Serial.begin(9600); Serial.println("HM10 serial started at 9600"); HM10.begin(9600); // set HM10 serial at 9600 baud rate pinMode(13, OUTPUT); // onboard LED digitalWrite(13, LOW); // switch OFF LED } void loop() { HM10.listen(); // listen the HM10 port while (HM10.available() > 0) { // if HM10 sends something then read appData = HM10.read(); inData = String(appData); // save the data in string format Serial.write(appData); } if (Serial.available()) { // Read user input if available. delay(10); HM10.write(Serial.read()); } if ( inData == "F") { Serial.println("LED OFF"); digitalWrite(13, LOW); // switch OFF LED delay(500); } if ( inData == "N") { Serial.println("LED ON"); digitalWrite(13, HIGH); // switch OFF LED delay(500); digitalWrite(13, LOW); // switch OFF LED delay(500); } } Video microcontroller-projects/joystick-game-controller-using-arduino-leonardo

Joystick Game Controller using Arduino Leonardo

Arduino Leonardo has advantage over Uno that we can install USB drivers on it and it can be detected as mouse, keyboard or joystick by computer when connected.

Components Required

Arduino Leonardo Dual Axis XY Joystick Module Arduino IDE Connecting wires

Arduino Leonardo

For this project we are using the Arduino Leonardo, it is a microcontroller board based on the ATmega32u4. It has 20 digital input/output pins (out of which 7 can be used as PWM outputs and 12 as Analog inputs), a 16 MHz crystal oscillator, a micro USB connection, a power jack, an ICSP header and a reset button. It contains everything needed to support the microcontroller; simply connect it to a computer with a USB cable or power it with a AC-to-DC adapter or battery to get started. The Leonardo is different from all preceding boards in that the ATmega32u4 has built-in USB communication, eliminating the need for a secondary processor. This allows the Leonardo to appear to a connected computer as a mouse and keyboard, in addition to a virtual (CDC) serial / COM port.
MicrocontrollerATmega32u4
Operating Voltage5V
Input Voltage (Recommended)7-12V
Input Voltage (limits)6-20V
Digital I/O Pins20
PWM Channels7
Analog Input Channels12
DC Current per I/O Pin40 mA
DC Current for 3.3V Pin50 mA
Flash Memory32 KB (ATmega32u4) of which 4 KB used by bootloader
SRAM2.5 KB (ATmega32u4)
EEPROM1 KB (ATmega32u4)
Clock Speed16 MHz
Length68.6 mm
Width53.3 mm
Weight20 g

Dual Axis XY Joystick Module

is shown in the figure below. This Joystick module typically provides Analog Outputs and the output voltages provided by this module keep changing according to the direction in which we move it. And we can get the direction of movement by interpreting these voltage changes using some microcontroller. Previously we interfaced joy stick with different microcontrollers: Interfacing Joystick with Arduino Interfacing Joystick with Raspberry Pi Interfacing Joystick with PIC Microcontroller Joystick Interfacing with AVR Microcontroller This joystick module has two axes as you can see. They are X-axis and Y-axis. Each axis of JOY STICK is mounted to a potentiometer or pot. The mid points of these pots are driven out as Rx and Ry. So Rx and Ry are variable points to these pots. When the Joystick is in standby, Rx and Ry act as voltage divider. When the stick is moved, the voltage on each pin goes high or low depending on direction.

Circuit Diagram

requires connections between the Arduino and the Joystick as follows:

Code and Working Explanation

video is given at the end; here we are explaining few important part of it. Firstly, we need to initialize the keyboard library #include<Keyboard.h> Next in below code, we have initialised X and Y axis of the Joystick module for Analog pin A0 and A1 respectively. const int X_pin and const int Y_pin respectively The analog value of the VRX pin is read and if the value is 1023 then the command for “upᾠis given and if the value is 0 then the command for “downᾠis given. Similarly, the analog value of the VRY pin is read and if the value is 1023 then the command for “rightᾠis given and if the value is 0 then the command for “leftᾠis given. Joystick also has a push button on top so this button (SW) is also read and if the button is pressed the value will be 0 then the command for “enterᾠis given. Finally burn the code into Arduino and connect the Arduino with computer. under devices section as shown in below image. Now you are ready to play with the joystick. We can control the any game controls using this Joystick. The Joystick has two potentiometers inside it, one is for X-axis movement and another is for Y-axis movement. Each potentiometer gets 5v from the Arduino. So as we move the joystick, the voltage value will change and the analog value at Analog pins A0 and A1 will also change. So the joystick will act as a gamepad. and can be used to play games having all the controls to move left, right, up and down. As told earliar more than one Joystickcan be interfaced to get more controls other than these basic four functions. Code #include<Keyboard.h> const int SW_pin = 2; // digital pin connected to switch output const int X_pin = A0; // analog pin connected to X output const int Y_pin = A1; // analog pin connected to Y output int x, y; void setup() { pinMode(SW_pin, INPUT); // SW pin set as input digitalWrite(SW_pin, HIGH); // A high value is written to SW pin Serial.begin(115200); Keyboard.begin(); } void loop() { x = analogRead(X_pin); // output of X_pin is read if (x == 1023) // check whether the value of x = 1023 { Serial.println("Up:"); Keyboard.press(218); // key moves up } else { Keyboard.release(218); // release the key } x = analogRead(X_pin); // output of X_pin is read if (x == 0) // check whether the value of x = 0 { Serial.println("Down:"); Keyboard.press(217); // key moves down } else { Keyboard.release(217); // release the key } y = analogRead(Y_pin); // output of Y_pin is read if (y == 1023) // check whether the value of y = 1023 { Serial.println("Right:"); Keyboard.press(216); // key moves right } else { Keyboard.release(216); // release the key } y = analogRead(Y_pin); // output of Y_pin is read if (y == 0) // check whether the value of y = 0 { Serial.println("Left:"); Keyboard.press(215); // key moves left } else { Keyboard.release(215); // release the key } int z = digitalRead(SW_pin); // read the value of SW pin if (z == 0) //check whether the value of z = 0 { Serial.println("Enter:"); Keyboard.println(); //enter key is pressed } delay(500); } Video microcontroller-projects/arduino-color-sorter-machine-using-tcs3200-color-sensor

DIY Arduino Based Color Sorter Machine using TCS3200 Color Sensor

As the name suggests, color sorting is simply to sort the things according to their color. It can be easily done by seeing it but when there are too many things to be sorted and it is a repetitive task then automatic color sorting machines are very useful. These machines have color sensor to sense the color of any objects and after detecting the color servo motor grab the thing and put it into respective box. They can be used in different application areas where color identification, color distinction and color sorting is important. Some of the application areas include Agriculture Industry (Grain Sorting on the basis of color), Food Industry, Diamond and Mining Industry, Recycling etc. The applications are not limited to this and can be further applied to different industries. The box will be in the fixed position and the servo motor will be used to move the sorter hand to keep the ball in the relevant box.

Components Required

Arduino UNO TCS3200 Color Sensor Servo Motors Jumpers Breadboard

How to make the chassis for Color Sorting Robotic Arm

of 2mm thickness. It is easily available in the stationary stores. We have used paper cutter to cut the Sunboard Sheet and FlexKwik or FeviKwik for joining the different parts. Below are some steps build the Color sorting Arm: 1) Take the Sunboard Sheet. 2) Cut the sunboard sheet into pieces after measuring all sides with scale and marker as shown in the figure. 3) Now hold the two pieces of sunboard together and pour a drop of FeviKwik on it to stick the pieces together. Keep joining the pieces by following the figure. 4) After joining all the pieces together, this color sorting machine will look something like this:

TCS3200 Color Sensor

As shown in figure on microscopic level one can see the square boxes inside the eye on sensor. These square boxes are arrays of RGB matrix. Each of these boxes contain three sensors, One is for sensing RED light intensity, One is for sensing GREEN light intensity and the last in for sensing BLUE light intensity. in which the sensor detects white light.

Arduino Color Sorter Circuit Diagram

is pretty easy to make and doesn’t require much connections. The schematic is given below. This is the circuitry behind the setup of color sorting machine:

Programming Arduino Uno for sorting colourful balls

is given at the end. given at the end. The first step will be all library inclusion and define the servo variables. #include <Servo.h> Servo pickServo; Servo dropServo; #define S0 4 #define S1 5 #define S2 7 #define S3 6 #define sensorOut 8 int frequency = 0; int color=0; The OUT pin will provide frequency. Select the scaling of frequency as 20% initially. pinMode(S0, OUTPUT); pinMode(S1, OUTPUT); pinMode(S2, OUTPUT); pinMode(S3, OUTPUT); pinMode(sensorOut, INPUT); digitalWrite(S0, LOW); digitalWrite(S1, HIGH); which will drop the color balls according to the color is connected at Pin10. pickServo.attach(9); dropServo.attach(10); Initially the pick servo motor is set in the initially position which in this case is 115 degrees. It may differ and can be customized accordingly. The motor moves after some delay to the detector region and waits for the detection. pickServo.write(115); delay(600); for(int i = 115; i > 65; i--) { pickServo.write(i); delay(2); } delay(500); color = detectColor(); delay(1000); Depending Upon the color detected, the drop servo motor moves with particular angle and drops the color ball to its respective box. switch (color) { case 1: dropServo.write(50); break; case 2: dropServo.write(80); break; case 3: dropServo.write(110); break; case 4: dropServo.write(140); break; case 5: dropServo.write(170); break; case 0: break; } delay(500); The servo motor returns to the initial position for the next ball to pick. for(int i = 65; i > 29; i--) { pickServo.write(i); delay(2); } delay(300); for(int i = 29; i < 115; i++) { pickServo.write(i); delay(2); } is used to measure frequency and compares the color frequency to make the conclusion of color. The result is printed on the serial monitor. Then it returns the color value for cases to move the drop servo motor angle. int detectColor() { to take the readings for red color density. digitalWrite(S2, LOW); digitalWrite(S3, LOW); frequency = pulseIn(sensorOut, LOW); int R = frequency; Serial.print("Red = "); Serial.print(frequency);//printing RED color frequency Serial.print(" "); delay(50); to take the readings for blue color density. digitalWrite(S2, LOW); digitalWrite(S3, HIGH); frequency = pulseIn(sensorOut, LOW); int B = frequency; Serial.print("Blue = "); Serial.print(frequency); Serial.println(" "); to take the readings for green color density. digitalWrite(S2, HIGH); digitalWrite(S3, HIGH); // Reading the output frequency frequency = pulseIn(sensorOut, LOW); int G = frequency; Serial.print("Green = "); Serial.print(frequency); Serial.print(" "); delay(50); Then the values are compared to make the color decision. The readings are different for different experimental setup as the detection distance varies for everyone when making the setup. if(R<22 & R>20 & G<29 & G>27){ color = 1; // Red Serial.print("Detected Color is = "); Serial.println("RED"); } if(G<25 & G>22 & B<22 &B>19){ color = 2; // Orange Serial.println("Orange "); } if(R<21 & R>20 & G<28 & G>25){ color = 3; // Green Serial.print("Detected Color is = "); Serial.println("GREEN"); } if(R<38 & R>24 & G<44 & G>30){ color = 4; // Yellow Serial.print("Detected Color is = "); Serial.println("YELLOW"); } if (G<29 & G>27 & B<22 &B>19){ color = 5; // Blue Serial.print("Detected Color is = "); Serial.println("BLUE"); } return color; } or comment below. Also check the video given below. Code #include <Servo.h> Servo pickServo; Servo dropServo; #define S0 4 #define S1 5 #define S2 7 #define S3 6 #define sensorOut 8 int frequency = 0; int color=0; int detectColor() { // activating red photodiodes to read digitalWrite(S2, LOW); digitalWrite(S3, LOW); frequency = pulseIn(sensorOut, LOW); int R = frequency; Serial.print("Red = "); Serial.print(frequency);//printing RED color frequency Serial.print(" "); delay(50); // activating blue photodiodes to read digitalWrite(S2, LOW); digitalWrite(S3, HIGH); frequency = pulseIn(sensorOut, LOW); int B = frequency; Serial.print("Blue = "); Serial.print(frequency); Serial.println(" "); // activating green photodiodes to read digitalWrite(S2, HIGH); digitalWrite(S3, HIGH); // Reading the output frequency frequency = pulseIn(sensorOut, LOW); int G = frequency; Serial.print("Green = "); Serial.print(frequency); Serial.print(" "); delay(50); delay(50); //Readings are different for different setup //change the readings according your project and readings detected if(R<22 & R>20 & G<29 & G>27){ color = 1; // Red Serial.print("Detected Color is = "); Serial.println("RED"); } if(G<25 & G>22 & B<22 &B>19){ color = 2; // Orange Serial.println("Orange "); } if(R<21 & R>20 & G<28 & G>25){ color = 3; // Green Serial.print("Detected Color is = "); Serial.println("GREEN"); } if(R<38 & R>24 & G<44 & G>30){ color = 4; // Yellow Serial.print("Detected Color is = "); Serial.println("YELLOW"); } if (G<29 & G>27 & B<22 &B>19){ color = 5; // Blue Serial.print("Detected Color is = "); Serial.println("BLUE"); } return color; } void setup() { pinMode(S0, OUTPUT); pinMode(S1, OUTPUT); pinMode(S2, OUTPUT); pinMode(S3, OUTPUT); pinMode(sensorOut, INPUT); //frequency-scaling to 20% selected digitalWrite(S0, LOW); digitalWrite(S1, HIGH); pickServo.attach(9); dropServo.attach(10); Serial.begin(9600); } void loop() { //initial position of servo motor pickServo.write(115); delay(600); for(int i = 115; i > 65; i--) { pickServo.write(i); delay(2); } delay(500); //read color values by calling function. save the values for conclusion in variable color = detectColor(); delay(1000); switch (color) { case 1: dropServo.write(50); break; case 2: dropServo.write(80); break; case 3: dropServo.write(110); break; case 4: dropServo.write(140); break; case 5: dropServo.write(170); break; case 0: break; } delay(500); for(int i = 65; i > 29; i--) { pickServo.write(i); delay(2); } delay(300); for(int i = 29; i < 115; i++) { pickServo.write(i); delay(2); } color=0; } Video microcontroller-projects/iot-based-biometric-attendance-system-using-arduino-and-thingsboard

IoT Based Biometric Attendance system using Arduino and Thingsboard

Few years back if you were to tell someone that the Geyser and bedroom lights in your home are connected to internet, they would be baffled and might even criticize it as over-engineered products. But today with the advent of IoT, Smart cities etc the idea no longer sounds strange, we have devices around us that have become smarter by being able to communicate with the internet. etc.

Hardware Required

Arduino UNO 16x2 LCD Display Arduino WiFi Shield ESP8266-01 GT511C3 Finger print sensor (FPS) 12V Adapter

Pre-requisites

to update them on Thingsboard Dashboard. tutorial before you proceed with this to understand how to enroll and detect finger prints using the GT511C3 module.

Preparing your Thingsboard account

video. You can think of assets as buildings, warehouses, industry, farmland etc and devices as the sensor or devices present in that particular asset. So every asset will have one or more devices in it based on the project, here we will have one asset and one device in our asset.

Creating an Asset on Thingsboard

You can give any name and type, I have given the following and your asset will be created. Note that I have named by asset as , remember this for we will need it later. Once the asset is created you can notice it appearing on the window as shown below.

Adding a Device to the Asset

To do so click on the device tab on the left panel and then click on add icon on the bottom right corner of the screen. You will get a similar pop up in which you to name the device I have name mine as FPS main gate and device type as default. Click on add and then you will find the device being created on the panel, click on the device that we just created and you will notice a new panel sliding in from the right. This panel will have all the information about the device, just click on copy access token as shown below to get the token value of our device, we will need this value in our Arduino program to send or receive values to this device.

Creating Device Relation for Asset

ᾮ This will slide in a pop-up from the right, now select relations tab in the new pop-up and over outbound relations click on add (+) symbol to get the following pop-up button to add the device relationship to asset.

Preparing the ESP8266-01

for powering the ESP8266 module and connect the Tx Rx pins to FTDI board as shown below. on it. , later we will replace the FTDI board with Arduino UNO in our final set-up.

Programming ESP8266 with Arduino IDE for sending data to ThingsBoard

Just search for the required library and click on install. PubSubClient by Nick O’Leary. WiFiEsp by bportaluri with the Token value that we obtained earlier. Then create a Wi-Fi client that connects to the Thingsboard demo page. The code for the same is shown below. #include <PubSubClient.h> //http://pubsubclient.knolleary.net/ #include <ESP8266WiFi.h> //https://github.com/bportaluri/WiFiEsp #define WIFI_AP "CircuitLoop" #define WIFI_PASSWORD "pasword14785" #define TOKEN "IFhm5ggJVsEpokiIoQ" char thingsboardServer[] = "demo.thingsboard.io"; WiFiClient wifiClient; Make sure you change the TOKEN and Wi-Fi credentials according to your device. we will begin the serial communication at 9600 baud rate and initialize the Wi-Fi module to connect to the Wi-Fi router. Finally we will connect our Wi-Fi client to the ThingsBoard server. void setup() { Serial.begin(9600); delay(10); InitWiFi(); client.setServer( thingsboardServer, 1883 ); lastSend = 0; } void loop() { if ( !client.connected() ) { reconnect(); } if ( Serial.available() ) { // Update and send only after 1 seconds char a = Serial.read(); Name = Name + String(a); if (a == 13) //check for new line { Name.trim(); //Remove /n or /r from the incomind data Serial.println(Name); Send_to_Thingsboard(); Name =""; //clear the string if new line is detected } } client.loop(); } should not be changed. void Send_to_Thingsboard() { Serial.println("Collecting temperature data."); String Employee_Name = Name; // Prepare a JSON payload string String payload = "{"; payload += "\"Name\":"; payload += Employee_Name; payload += "}"; // Send payload char attributes[100]; payload.toCharArray( attributes, 100 ); client.publish( "v1/devices/me/telemetry", attributes ); Serial.println( attributes ); }

Testing ESP8266 connection with ThingsBoard

Once your IDE and hardware is ready, we can check if the ESP8266 Part is working well. Using the FTDI module in the above discussed circuit upload the code to ESP8266 by keeping it in programming mode. Once the code is uploaded connect it back to AT command mode and press the reset button. Then open serial monitor and you should see the following r. At this stage the ESP is waiting for input through its Serial monitor, when it receives something it will send that data to the server. So, now it’s time to connect the ESP with Arduino to provide the values to ESP.

Circuit diagram for IoT based Attendance System

For the final circuit, we will port the existing circuit and replace the FTDI module with Arduino UNO with the GT511C3 FPS and LCD screen connected to it. The final circuit diagram is shown below. is connected to display the name of the person who has been identified. This is to turn off the FPS when not in use. As we know the FPS needs a blue LED to be turned on to take optical images of fingerprints and recognize them. But if this light is always kept on the sensor tends to get hot which might reduce its life. Luckily I found a method mentioned in its datasheet to overcome this problem, which is to use the metal casing of the sensor as a touch sensor. When a person have to use the FPS he has to touch the metal frame, so if we can sense his body capacitance we will be able to say if a person has touched the FPS or not.

Programming Arduino UNO for Biometric Attendance System

, the explanation of code is as follows. I have used a string array for 5 employees including Admin. Hence the person with ID number 0 will be Admin and 1 will be Steve and so on. Thus for five employees ID number from 0 to 4 will be used. If the admin enroll a new finger print of a new employee he will have id number 5 which can be related to his name. char *Name_List[]= {"Admin", "Steve", "Tony", "Natasha", "Bruce"}; GT511C3 FPS library One pin capacitive touch sensor library allows us to check if someone has touched the metal casing on the FPS. Once the libraries are added to Arduino include them in the program as shown below #include "FPS_GT511C3.h" //Get library from https://github.com/sparkfun/Fingerprint_Scanner-TTL #include "SoftwareSerial.h" //Software serial library #include <LiquidCrystal.h> //Library for LCD #include "OnePinCapSense.h" //Librarey to sensor capacitive touch https://github.com/MrYsLab/OnePinCapSense Softwareserial ESP(12, 13); // RX, TX FPS_GT511C3 fps(9, 8); //FPS connected to D9 and D8 const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7);//Initialize LCD method int capSensePin10 = 10; //Pin to which casing of sensor is connected we initialize the Serial communication at 9600 baud rate and display a small intro message on the LCD. We have also opened communication with FPS and have turned its blue LED off if it has been left on earlier. void setup() { Serial.begin(9600); ESP.begin (9600); lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print("GT511C3 FPS"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print("with Arduino"); //Intro Message line 2 delay(2000); lcd.clear(); fps.Open(); //send serial command to initialize fps fps.SetLED(false); //turn on LED so fps can see fingerprint } option. For our set-up I found that the read value exceeds 50 all times when the casing is not touched and goes below 50 when someone touches it. So we can use to it check if the sensor is being touched. If the sensor is touched we just have to turn on the blue LED. int capSense10 = opcs.readCapacitivePin(capSensePin10) ; if( capSense10 < 50) { fps.SetLED(true); delay(500);} If the ID number is 200 it means that the identified finger print has not been enrolled yet. So we will display unknown, if the ID is 0 then it means the identified fingerprint is of the admin so we proceed with enrolling a new finger print. If the identified number is within our name list then we can proceed with displaying their name on LCD and also sending the information to ESP. After the process we can finally turn off the blue LED until a new finger touch is detected. if (fps.IsPressFinger()) { fps.CaptureFinger(false); id = fps.Identify1_N(); lcd.clear(); if (id==200) { lcd.print("Unkown"); lcd.setCursor(0,1); lcd.print("Try Again!!");//If not recognised } else if (id==0) { lcd.print("Welcome"); lcd.setCursor(0,1); lcd.print("***ADMIN***");//If not recognised delay(2000); Enroll(); } else { lcd.print("Thank You"); lcd.setCursor(0,1); lcd.print(Name_List[id]); ESP.println(Name_List[id]); Serial.println("Sent Value to ESP"); } delay(1000); fps.SetLED(false); }

Testing the complete IoT based Arduino Attendance System

Finally it’s time to get the system into action, upload the Arduino code to the UNO board and connect it with ESP which already has our code running using the circuit diagram given above. Power up the module and if everything goes good you should notice the LCd display saying “Press Fingerᾠas shown below. Now make sure that the fingerprints are enrolled in the FPS by following the previous tutorial and then touch the sensor with a enrolled finger. If detected the LCD will say Thank you followed by the name of that person and will also send the name of the person to ESP which will then send to the thingsboard device that we created earlier.

Checking if ThingsBoard is receiving the Attendance Data

If the LCD displays Thank you it means that it has sent the name of the person to the ESP which should have sent it to the Thingsboard device that we created earlier. To ensure it is working as expected, get into the deice tab and click on the device that we created earlier, mine is named as “FPS Main Gateᾠhere. This will slide in a pop-up window from the right, in this window click on Latest Telemetry and you should see the last entry the device received as shown below. In previous step our FPS sensor detected Steve and hence the same name has been sent to thingsboard as you can see here. If you do not get anything here, make sure your ESP is connected and powered properly and is able to get information from Arduino though serial and send it to client.

Creating a Dashboard on ThingsBoard for IoT Attendance System

The final step is to create a dashboard in which we can view all the names sent by the ESP module against time and date. The good thing with ThingsBoard is that you have many widgets to visualize the data based on usage. It is also possible to use the rule chain option to logically analyze these data and take required actions like triggering an alarm sending E-mail etc. To create a dashboard click on dashboard in the left panel, then click on add new dashboard (+) icon on the bottom left of the screen. And select create new dashboard. In the pop-up give a name to your dashboard and click on add. as device and mention the name of the device from which we need the data on the dashboard as shown below and click on add and then save button. Click on add new widget and then under the current bundle select cards and then select time series table. This will open a window and ask for the alias name that we just created, you can select the type as entity and provide the alias name as shown in the below picture. Click on add and you should see a new widget on your dashboard with the name of all the employees that have been sent by the ESP so far. You can also sort the data name vise or use the history option to view the data in a particular date or time. My sample dataset is shown below that updates all data on our dashboard which can be visualized, analyzed and reported online without the need of physical contact with the hardware. Once the project is ready hand it over to Nick Furry and ask him assemble the Avengers on time, the next time when someone decides to wipe out half the population. Hope you understood the project and enjoyed building something useful. If you have any questions regarding this project leave them in the comment section below or use our forums for other technical queries. Code /* * Arduino with GT511C2 FingerPrint Sensor (FPS) * Code to enroll and Detect Fingers * For: www.circuitdigest.com * Dated: 6-5-19 * Code By: Aswinth * * Connect Tx of FPS to Arduino Pin D4 and Rx of FPS to D5 */ char *Name_List[]= {"ADMIN", "Mahesh", "Aswinth", "Munna", "Pankaj", "Sandeep", "Ashok", "Gust 1", "Gust 2", "Gust 3", "Gust 4"}; #include "SoftwareSerial.h" //Software serial library #include <LiquidCrystal.h> //Library for LCD #include "OnePinCapSense.h" //Librarey to sensor capacitive touch https://github.com/MrYsLab/OnePinCapSense SoftwareSerial ESP(12, 13); // RX, TX FPS_GT511C3 fps(9, 8); //FPS connected to D9 and D8 const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7);//Initialize LCD method int capSensePin10 = 10; //Pin to which casing of sensor is connected int id = 200; OnePinCapSense opcs = OnePinCapSense(); void setup() { Serial.begin(9600); ESP.begin (9600); lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print("GT511C3 FPS"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print("with Arduino"); //Intro Message line 2 delay(2000); lcd.clear(); fps.Open(); //send serial command to initialize fps fps.SetLED(false); //turn on LED so fps can see fingerprint } void loop() { int capSense10 = opcs.readCapacitivePin(capSensePin10) ; if( capSense10 < 100) { fps.SetLED(true); delay(500);} Serial.println(capSense10); // Identify fingerprint test if (fps.IsPressFinger()) { fps.CaptureFinger(false); id = fps.Identify1_N(); lcd.clear(); if (id==200) { lcd.print("Unkown"); lcd.setCursor(0,1); lcd.print("Try Again!!");//If not recognised } else if (id==0) { lcd.print("Welcome"); lcd.setCursor(0,1); lcd.print("***ADMIN***");//If not recognised delay(2000); Enroll(); } else { lcd.print("Thank You"); lcd.setCursor(0,1); lcd.print(Name_List[id]); ESP.println(Name_List[id]); Serial.println("Sent Value to ESP"); } delay(1000); fps.SetLED(false); } else { fps.SetLED(false); lcd.clear(); lcd.print("CircuitDigest"); //Display intro text lcd.setCursor(0,1); lcd.print("Press Finger"); } } void Enroll() //Enrol function from library exmaple program { int enrollid = 0; bool usedid = true; while (usedid == true) { usedid = fps.CheckEnrolled(enrollid); if (usedid==true) enrollid++; } fps.EnrollStart(enrollid); // enroll lcd.clear(); lcd.print("Enroll #"); lcd.print(enrollid); while(fps.IsPressFinger() == false) delay(100); bool bret = fps.CaptureFinger(true); int iret = 0; if (bret != false) { lcd.clear(); lcd.print("Remove finger"); fps.Enroll1(); while(fps.IsPressFinger() == true) delay(100); lcd.clear(); lcd.print("Press again"); while(fps.IsPressFinger() == false) delay(100); bret = fps.CaptureFinger(true); if (bret != false) { lcd.clear(); lcd.print("Remove finger"); fps.Enroll2(); while(fps.IsPressFinger() == true) delay(100); lcd.clear(); lcd.print("Press yet again"); while(fps.IsPressFinger() == false) delay(100); bret = fps.CaptureFinger(true); if (bret != false) { lcd.clear(); lcd.print("Remove finger"); iret = fps.Enroll3(); if (iret == 0) { lcd.clear(); lcd.print("Enrolling Success"); } else { lcd.clear(); lcd.print("Enroll Failed:"); lcd.print(iret); } } else lcd.print("Failed 1"); } else lcd.print("Failed 2"); } else lcd.print("Failed 3"); } /*Program to connect ESP8266 to thingsboard and sent the value received through serial input * For IoT Attendance Project * Author: B.Aswinth Raj * Dated: 11-5-2019 * Website: www.circuitdigest.com */ #include <PubSubClient.h> //http://pubsubclient.knolleary.net/ #include <ESP8266WiFi.h> //https://github.com/bportaluri/WiFiEsp #define WIFI_AP "CircuitLoop" #define WIFI_PASSWORD "circuitdigest101" #define TOKEN "lrmsUz2M4cA9wN3dVmUX" char thingsboardServer[] = "demo.thingsboard.io"; WiFiClient wifiClient; PubSubClient client(wifiClient); int status = WL_IDLE_STATUS; unsigned long lastSend; void setup() { Serial.begin(9600); delay(10); InitWiFi(); client.setServer( thingsboardServer, 1883 ); lastSend = 0; } String Name =""; void loop() { if ( !client.connected() ) { reconnect(); } if ( Serial.available() ) { // Update and send only after 1 seconds char a = Serial.read(); Name = Name + String(a); if (a == 13) //check for new line { Name.trim(); //Remove /n or /r from the incomind data Serial.println(Name); Send_to_Thingsboard(); Name =""; //clear the string if new line is detected } } client.loop(); } void Send_to_Thingsboard() { Serial.println("Collecting temperature data."); String Employee_Name = Name; // Prepare a JSON payload string String payload = "{"; payload += "\"Name\":"; payload += Employee_Name; payload += "}"; // Send payload char attributes[100]; payload.toCharArray( attributes, 100 ); client.publish( "v1/devices/me/telemetry", attributes ); Serial.println( attributes ); } void InitWiFi() { Serial.println("Connecting to AP ..."); // attempt to connect to WiFi network WiFi.begin(WIFI_AP, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("Connected to AP"); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { status = WiFi.status(); if ( status != WL_CONNECTED) { WiFi.begin(WIFI_AP, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("Connected to AP"); } Serial.print("Connecting to ThingsBoard node ..."); // Attempt to connect (clientId, username, password) if ( client.connect("ESP8266 Device", TOKEN, NULL) ) { Serial.println( "[DONE]" ); } else { Serial.print( "[FAILED] [ rc = " ); Serial.print( client.state() ); Serial.println( " : retrying in 5 seconds]" ); // Wait 5 seconds before retrying delay( 5000 ); } } } Video microcontroller-projects/programming-arduino-using-platform-io-to-blink-an-led

Programming Arduino using Platform IO

which is easy to use and has added features compare to Arduino environment.

What is PlatformIO?

The PlatformIO is a Python based open source ecosystem for IoT development and a cross platform IDE with a unified debugger runs on Windows, Mac and Linux. PlatformIO comes with library manager for platforms like Arduino or MBED support along with unit testing and firmware updates. The PlatformIO supports a number of Platforms, Frameworks, Boards like Arduino, ESP32, ESP8266 and comes with number of examples and libraries. It is independent of the platform in which it is running and it requires only Python Installed on the computer. The core features include the Multi-platform Build System, Library Manager, Serial Port Monitor etc. with a support for the multiple architectures and development platforms allows to debug multiple embedded boards with Zero-Configuration. The PlatformIO Unified Debugger has features like Conditional Breakpoints, Expressions and Watchpoints, Memory Viewer, A hot restart of an active debugging session. The PlatformIO Core is written in Python 2.7 and works on Windows, macOS, Linux, FreeBSD and even ARM-based credit card sized computers like Raspberry Pi, BeagleBone, CubieBoard, Samsung ARTIK, etc. Apart from this the PlatformIO has File Explorer which helps organizing the files when the project grows to a certain level and organizing becomes necessary.

Setting up PlatformIO for Arduino Uno

and then proceed for setting up PlatformIO IDE. The PlatformIO is an IDE plus it provides official packages (plugins, extensions) for the most popular IDEs and text editors. The VS Code is a well-known text editor with number of extensions allowing us to develop in different programming languages. There are steps involved which are explained below: Firstly install the Visual Studio Code from its official website. The installation steps of Visual Studio Code will not be explained here but you can find it on VS Code website. There are general steps involved just like installing any other software on Windows OS. The Visual Studio Code will look like following when it is successfully installed. Next Step includes installing the PlatformIO using VS Code Extensions. For this you need go to Extensions Icon on the top left corner of the VS Code. There is square Box Icon which is the 5th icon on the top left corner. Just click on that and one search box will appear just beside that where you can find many extension for different programming languages like C/C++, C#, Python, PHP, Go, JavaScript, TypeScript and Node.js etc. Search For “PlatformIOᾠin the extension search box and you will see PlatformIO Icon with Name and Description. Just click on it and Install it. It may take some time installing toolchains and other dependencies. Dependencies include C/C++ environment as Arduino development is mostly done on C/C++. When the installation is completed, you will see the following interface. The Interface includes all the necessary navigation such as creating New Project, Import Arduino Project, Open Project, Project Examples etc. It is recommended to restart the VS Code Editor after the installation of PlatformIO. This finishes the installation steps of PlatformIO. Now the PlatformIO is installed and ready to use. Just like Arduino IDE, we will start with the Blink Program and try to upload the Blink Program in the Arduino UNO.

Programming Arduino UNO using the PlatformIO IDE

Follow the below steps below to create a new project for blinking LED. Select “New Projectᾠtab from the quick access menu. Name the project (Here it is ‘Blinkᾩ. Search and Select the board which is Arduino UNO. Since we are working in Arduino framework, so the framework selected will be Arduino. After filling all details just click on Finish. The Project will start getting created by collecting resources and other dependencies. When project is successfully created, you will get the prompt message as “Project has been successfully initializedᾠwith all filled details. To open the created project, just scroll down the Home Menu of PlatformIO and you will see all list of the projects created from beginning. At the right corner of created project click on ‘Openᾠto open the project and start editing. When the project is opened, initially it will look like its hidden, but don’t worry, the PlatformIO has file explorer feature where all the files of current project will be found. Just go to the top left corner and open the ‘Untitled (Workplace)ᾮ When click on it, all files will appear as dropdown menu. To find the text editor to edit the ‘Codeᾬ select ‘srcᾠand the open ‘main.cppᾮ The text editor mode will appear on the Home Screen with opening a new Tab. Here you can write all codes of Current Ongoing Project. Simply write the Blink Code for Arduino UNO. Note that, the PlatformIO doesn’t have the default access to Arduino libraries, so everytime you write the code for Arduino, always include Arduino library i.e. ᾣinclude <Arduino.h>ᾼ/strong> at the beginning of program. The next step would be compiling and uploading the code. To do so, let’s look at the functions provided by the PlatformIO. Also the PlatformIO selects the COM Port by default. But you can also change the Port if it is not the desired COM port. The change of COM port will be explained later in this tutorial. PlatformIO has functions like Build, Upload, Upload to Remote Device, Clean, Test, Run Task, Serial Monitor, New Terminal. All the functions can be found in the left bottom corner of the Editor. When you Hover over the icons, the functions will be shown. To Build the Sketch, click on ‘Buildᾠand to upload the sketch click on the ‘UploadᾠIcon. When the upload is done, you will be able to see the time taken to upload with all other details and a message saying “Successᾮ The code is uploaded successfully and you will be able to see the Blinking of LED in the Arduino Board. , just go to the PlatformIO Home Screen and then go to the Devices, here you can see all the available devices connected. Select appropriate COM port and follow the same procedure to Upload the sketch.

Programming STM32 Board using the PlatformIO IDE

Proceed with following steps to program it with PlatformIO. Just name the Project (Here it is ‘Blink STM32ᾩ. Then select the board for STM32 i.e. ᾼstrong>BluePill F103C8(Generic)ᾮ Then select Framework as Arduino. Click on Finish and wait for some time as initially it will take time to download the packages and dependencies for board STM32. Once Set Up, the next project creation time will be less compare to first. Now Simply go to Untitled(Workspace) -> src -> main.cpp in the left file explorer. Now the upcoming steps will be important as it needs to be decided that which programmer we should use for programming the STM32 Board. There are many programmers available such as JTAG, STLink, JLink, Serial etc. All will work but you need to configure the ‘platformio.iniᾠconfiguration page or file. In this Project, we are using Serial Programmer CP210x USB to UART Bridge. We already have done Programming STM32F103C8 Board using USB Port, o most of steps will be taken from there only. You can visit the link and find more about this. Firstly, Connect Serial Programmer to STM32 Board with following pin mapping and connect it to PC.
Now go to the project explorer and open ‘platformio.iniᾠpage and change the statement as shown in the picture. The upload_protocol will tell that which programmer should use (STLink, JLink, Serial etc). The upload_port selects the COM port. You can find by going to ‘Devicesᾠin Home Page. Change the COM port according to your COM port. Go to the ‘main.cppᾼ/em> and change the program to Blink program. Now just upload the program and it will show success message and time taken to upload. Now the LED will start blinking connected at PC13 pin of STM32 board. or comment below. Code #include <Arduino.h> void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(100); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(100); // wait for a second } Video microcontroller-projects/arduino-fingerprint-sensor-gt511c3-interfacing

Interfacing GT511C3 Finger Print Sensor (FPS) with Arduino

, Iris scanning and Finger print Scanning. Out of which the finger print recognition is the most widely used method, we can find it from a simple attendance system to smart phones to Security checks and much more. So let’s get started.

Materials Required

Arduino Nano/UNO GT511C3 Finger Print Sensor 16x2 LCD screen Pot ᾠ10k and 1k,10k,22k resistors Push button Connecting Wires Bread board

GT511C3 Fingerprint Sensor (FPS) Module

, meaning it relies on images of your fingerprint to recognize its pattern. Yes you read that right, the sensor actually has a camera inside it which takes pictures of your fingerprint and then processes these images using powerful in-built ARM Cortex M3 IC. The below image shows the front and back side of the sensor with pinouts. at 9600. The communication pins (Rx and Tx) is said to be only 3.3V tolerant, however the datasheet does not specify much about it. The pin-out of a GT511C3 FPS is shown below. application which can be downloaded from the link. This application allows the user to enroll/verify/delete fingerprints and also to recognize fingerprints. The software can also help you to read the image captured by the sensor which is worth giving it a try. Alternatively you can also use this Software even if the sensor is connected with Arduino, we will discuss on this later in this article. If yes the LED can be turned on and the sensing process can be started. This method is not demonstrated here as it is outside the scope of this article. from ADH-Tech who is the official manufacturer of the module.

Connecting GT511C3 Finger Print Sensor with Arduino

can be found below. where the user can enroll new finger. After enrolling the program will remain in scanning mode to scan for any finger touching the sensor.

ArduinoGT511C3 Finterprint Sensor Library

has already created a library which can be used directly with Arduino to Enroll and detect finger prints. The Github library for GT511C3 FPS can be downloaded from the link below as shown below You should see four example programs, the blink program will blink the blue led on the FPS, the enroll and ID finger program can be used to enroll and identify the fingers accordingly. Note that a finger once enrolled will always be remembered by the module even if it is powered off. application that we discussed earlier in this article. To delete any fingerprint template or to save a copy on your computer this SDK application can be used.

ArduinoFinger Print Sensor Code

Here I am breaking the same into small snippets to help you understand better. , here we will need the FPS_GT511C3 library for our FPS module, Software serial to use D4 and D5 on serial communication and Liquid crystal for LCD interfacing. Then we need to mention to which pins the FPS and LCD is connected to. If you had followed the circuit diagram as such then it is 4 and 5 for FPS and D6 to D11 for LCD. The code for the same is shown below #include "FPS_GT511C3.h" //Get library from https://github.com/sparkfun/Fingerprint_Scanner-TTL #include "SoftwareSerial.h" //Software serial library #include <LiquidCrystal.h> //Library for LCD FPS_GT511C3 fps(4, 5); //FPS connected to D4 and D5 const int rs = 6, en = 7, d4 = 8, d5 = 9, d6 = 10, d7 = 11; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7);//Initialize LCD method The command fps.SetLED(true) will turn on the blue LED on the sensor, you can turn it off by fps.SetLED(false) when not required as it would heat up the sensor if left on continuously. We have also made the pin D2 as input pin and connected it to internal pull-up resistor so as to connect a push button to the pin. void setup() { Serial.begin(9600); lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print("GT511C3 FPS"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print("with Arduino"); //Intro Message line 2 delay(2000); lcd.clear(); fps.Open(); //send serial command to initialize fp fps.SetLED(true); //turn on LED so fps can see fingerprint pinMode(2,INPUT_PULLUP); //Connect to internal pull up resistor as input pin } with an ID number by using the enroll function. If not we will keep waiting for a finger to be pressed in the sensor. If pressed we will indentify the fingerprint by comparing it to all enrolled fingerprints template using the 1:N method. Once the ID number is discovered we will display welcome followed by the ID number. If the finger print did not match with any of the enrolled fingers the id count will be 200, in that case we will display welcome unknown. if (digitalRead(2))//If button pressed { Enroll(); //Enroll a fingerprint } // Identify fingerprint test if (fps.IsPressFinger()) { fps.CaptureFinger(false); int id = fps.Identify1_N(); lcd.clear(); lcd.print("Welcome:"); if (id==200) lcd.print("Unkown "); //If not recognised lcd.print(id); delay(1000); } and then finally Enroll1, Enroll2 and Enroll3 is used for three different samples to successfully enroll one finger. The LCD displays the ID number of the finger if enrolled successfully else it would display a failure message with code. Code 1 means the finger print was not captured clearly and hence you have to try again. Code 2 is a memory fail indication and code 3 is to indicate that the finger has already been enrolled. void Enroll() //Enrol function from library exmaple program { int enrollid = 0; bool usedid = true; while (usedid == true) { usedid = fps.CheckEnrolled(enrollid); if (usedid==true) enrollid++; } fps.EnrollStart(enrollid); // enroll lcd.print("Enroll #"); lcd.print(enrollid); while(fps.IsPressFinger() == false) delay(100); bool bret = fps.CaptureFinger(true); int iret = 0; if (bret != false) { lcd.clear(); lcd.print("Remove finger"); fps.Enroll1(); while(fps.IsPressFinger() == true) delay(100); lcd.clear(); lcd.print("Press again"); while(fps.IsPressFinger() == false) delay(100); bret = fps.CaptureFinger(true); if (bret != false) { lcd.clear(); lcd.print("Remove finger"); fps.Enroll2(); while(fps.IsPressFinger() == true) delay(100); lcd.clear(); lcd.print("Press yet again"); while(fps.IsPressFinger() == false) delay(100); bret = fps.CaptureFinger(true); if (bret != false) { lcd.clear(); lcd.print("Remove finger"); iret = fps.Enroll3(); if (iret == 0) { lcd.clear(); lcd.print("Enrolling Success"); } else { lcd.clear(); lcd.print("Enroll Failed:"); lcd.print(iret); } } else lcd.print("Failed 1"); } else lcd.print("Failed 2"); } else lcd.print("Failed 3"); }

Working ofGT511C3Finger Print Sensor with Arduino

Now that our hardware and code is ready it is time to test our project. Upload the code to Arduino and power it up, I am just using the micro-usb port to power the project. On booting we should see the intro message on the LCD and then it should display “Hi!..ᾮ This means that FPS is ready to scan for finger, if any enrolled finger is pressed it would say “Welcomeᾠfollowed by the ID number of that finger as shown below. for other technical questions. Code /* * Arduino with GT511C2 FingerPrint Sensor (FPS) * Code to enroll and Detect Fingers * For: www.circuitdigest.com * Dated: 6-5-19 * Code By: Aswinth * * Connect Tx of FPS to Arduino Pin D4 and Rx of FPS to D5 */ #include "SoftwareSerial.h" //Software serial library #include <LiquidCrystal.h> //Library for LCD FPS_GT511C3 fps(4, 5); //FPS connected to D4 and D5 const int rs = 6, en = 7, d4 = 8, d5 = 9, d6 = 10, d7 = 11; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7);//Initialize LCD method void setup() { Serial.begin(9600); lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print("GT511C3 FPS"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print("with Arduino"); //Intro Message line 2 delay(2000); lcd.clear(); fps.Open(); //send serial command to initialize fps fps.SetLED(true); //turn on LED so fps can see fingerprint pinMode(2,INPUT_PULLUP); //Connect to internal pull up resistor as input pin } void loop() { if (digitalRead(2)==0)//If button pressed { Enroll(); //Enroll a fingerprint } // Identify fingerprint test if (fps.IsPressFinger()) { fps.CaptureFinger(false); int id = fps.Identify1_N(); lcd.clear(); lcd.print("Welcome:"); if (id==200) lcd.print("Unkown "); //If not recognised lcd.print(id); delay(1000); } else { lcd.clear(); lcd.print("Hi!....."); //Display hi when ready to scan } } void Enroll() //Enrol function from library exmaple program { int enrollid = 0; bool usedid = true; while (usedid == true) { usedid = fps.CheckEnrolled(enrollid); if (usedid==true) enrollid++; } fps.EnrollStart(enrollid); // enroll lcd.clear(); lcd.print("Enroll #"); lcd.print(enrollid); while(fps.IsPressFinger() == false) delay(100); bool bret = fps.CaptureFinger(true); int iret = 0; if (bret != false) { lcd.clear(); lcd.print("Remove finger"); fps.Enroll1(); while(fps.IsPressFinger() == true) delay(100); lcd.clear(); lcd.print("Press again"); while(fps.IsPressFinger() == false) delay(100); bret = fps.CaptureFinger(true); if (bret != false) { lcd.clear(); lcd.print("Remove finger"); fps.Enroll2(); while(fps.IsPressFinger() == true) delay(100); lcd.clear(); lcd.print("Press yet again"); while(fps.IsPressFinger() == false) delay(100); bret = fps.CaptureFinger(true); if (bret != false) { lcd.clear(); lcd.print("Remove finger"); iret = fps.Enroll3(); if (iret == 0) { lcd.clear(); lcd.print("Enrolling Success"); } else { lcd.clear(); lcd.print("Enroll Failed:"); lcd.print(iret); } } else lcd.print("Failed 1"); } else lcd.print("Failed 2"); } else lcd.print("Failed 3"); } Video microcontroller-projects/arduino-multitasking-using-millis-in-arduino

Arduino Multitasking Tutorial - How to use millis() in Arduino Code

has led the computers to a revolution where one or more programs can run simultaneously which increases efficiency, flexibility, adaptability and productivity. In embedded systems, microcontrollers can also handle Multitasking and performs two or more tasks simultaneously without halting the current instructions. Before going into detail let’s start with understating Multitasking.

What is Multitasking?

Multitasking simply means executing more than one task or program simultaneously at the same time. Almost all operating systems feature multitasking. This kind of operating systems are known as MOS (multitasking operating system). The MOS can be mobile or desktop PC Operating System. The good example of multitasking in computers are when users run the email application, internet browser, media player, games, at the same time and if users don’t want use the application it runs in the background if not closed. The end user use all these applications at the same time but OS takes this concept a bit different. Let’s discuss how OS manages multitasking.

Why to skip delay() in Arduino?

then the delay will be of 1000 microseconds i.e. 1 milliseconds. , both functions pause the program for the amount of time passed in delay function. So if we are giving a delay of 1 second then the processor cannot go to next instruction until 1 second passed. Similarly if the delay is 10 seconds then program will stop for 10 seconds and processor will not allow to go for the next instructions until the 10 seconds passed. This hampers the performance of the microcontroller in terms of speed and executing the instructions. is using two push buttons. Consider we want to toggle two LEDs using two push buttons. So if one push button is pushed then the corresponding LED should glow for 2 seconds, similarly if second is pushed then LED should glow for 4 seconds. But when we use delay(), if the user is pressing the first button then the program will stop for 2 seconds and if the user presses the second button before 2 seconds delay, then the microcontroller won’t accept the input as the program is in halt stage. You can go through and check this out to make it more clear.

Why to use millis() ?

is a function that just returns the amount of milliseconds that have elapsed since the Arduino board began running the current program without freezing the program. This time number will overflow (i.e go back to zero), after approximately 50 days. The difference between micros and millis is that, the micros() will overflow after approximately 70 minutes, compared to millis() which is 50 days. So depending upon the application you can use millis() or micros(). Using millis() instead of delay(): To use the millis() for timing and delay, you need to record and store the time at which the action took place to start the time and then check at intervals whether the defined time has passed. So as stated, store the current time in a variable. unsigned long currentMillis = millis(); is declared. The interval will tell us the time delay and previosMillis will store the last time the event has occurred. unsigned long previousMillis; unsigned long period = 1000; To understand this, let's take an example of a simple blinking LED. The period = 1000 will tell us that the LED will blink for 1 second or 1000ms. const int ledPin = 4; // the LED pin number connected int ledState = LOW; // used to set the LED state unsigned long previousMillis = 0; //will store last time LED was blinked const long period = 1000; // period at which to blink in ms void setup() { pinMode(ledPin, OUTPUT); // set ledpin as output } void loop() { unsigned long currentMillis = millis(); // store the current time if (currentMillis - previousMillis >= period) { // check if 1000ms passed previousMillis = currentMillis; // save the last time you blinked the LED if (ledState == LOW) { // if the LED is off turn it on and vice-versa ledState = HIGH; } else { ledState = LOW; } digitalWrite(ledPin, ledState);//set LED with ledState to blink again } } checks if the 1000ms has passed. If 1000ms has passed, then the LED blink and again comes to same state. And this goes on. That's it, we have learnt to use millis instead of delay. This way it won’t halt the program for particular interval. , where you can learn more about Interrupts and how to use them. So three tasks will be performed simultaneously.

Components Required

Arduino UNO Three LEDs(Any Color) Resistances (470, 10k) Jumpers Breadboard

Circuit Diagram

is very easy and doesn't have much components to attach as shown below.

Programming Arduino UNO for Multitasking

Programming Arduino UNO for multitasking will only require the logic behind how millis() work which is explained above. It is recommended to practice blink LED using millis again and again to make the logic clear and make yourself comfortable with millis() before starting to program Arduino UNO for multitasking. In this tutorial the interrupt is also used with millis() simultaneously for multitasking. The button will be an interrupt. So whenever an interrupt is generated i.e. push button is pressed, the LED will switch to ON or OFF state. The programming starts with declaring pin numbers where LEDs and Push Button are connected. int led1 = 6; int led2 = 7; int toggleLed = 5; int pushButton = 2; Next we write a variable to store the status of LEDs for future use. int ledState1 = LOW; int ledState2 = LOW; The first LED blinks at after every 1 second and another LED blinks at after 200ms. unsigned long previousMillis1 = 0; const long period1 = 1000; unsigned long previousMillis2 = 0; const long period2 = 200; to avoid the multiple presses of push button. There will be similar approach as above. int debouncePeriod = 20; int debounceMillis = 0; , toggle LED and push button state. bool buttonPushed = false; int ledChange = LOW; int lastState = HIGH; Define the action of pin that which pin will work as INPUT or OUTPUT. pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(toggleLed, OUTPUT); pinMode(pushButton, INPUT); function to translate the actual digital pin to the specific interrupt number. attachInterrupt(digitalPinToInterrupt(pushButton), pushButton_ISR, CHANGE); should be as short as possible, so try to write it and minimize the extra instructions. void pushButton_ISR() { buttonPushed = true; } Loop starts with storing the millis value in a currentMillis variable which will store the value of time elapsed every time the loop iterates. unsigned long currentMillis = millis(); So we will write three parts to do this task. is toggles LED state after every 1 second by comparing the millis elapsed. if (currentMillis - previousMillis1 >= period1) { previousMillis1 = currentMillis; if (ledState1 == LOW) { ledState1 = HIGH; } else { ledState1 = LOW; } digitalWrite(led1, ledState1); } it toggles the LED after every 200ms by comparing the elapsed millis. The explanation is already explained earlier in this article. if (currentMillis - previousMillis2 >= period2) { previousMillis2 = currentMillis; if (ledState2 == LOW) { ledState2 = HIGH; } else { ledState2 = LOW; } digitalWrite(led2, ledState2); } flag is monitored and after generating a debounce delay of 20ms it just toggles the state of LED corresponds to push button attached as interrupt. if (buttonPushed = true) // check if ISR is called { if ((currentMillis - debounceMillis) > debouncePeriod && buttonPushed) // generate 20ms debounce delay to avoid multiple presses { debounceMillis = currentMillis; // save the last debounce delay time if (digitalRead(pushButton) == LOW && lastState == HIGH) // change the led after push button is pressed { ledChange = ! ledChange; digitalWrite(toggleLed, ledChange); lastState = LOW; } else if (digitalRead(pushButton) == HIGH && lastState == LOW) { lastState = HIGH; } buttonPushed = false; } } or comment below. is providedbelow. Code /* Multitasking using Arduino millis() function Author : CircuitDigest (circuitdigest.com) */ int led1 = 6; // led1 connected at pin 6 int led2 = 7; // led1 connected at pin 7 int toggleLed = 5; // push button controlled led connected at pin 5 int pushButton = 2; // push butoon connected at pin 2 which is also interrupt pin int ledState1 = LOW; // to determine the states of led1 and led2 int ledState2 = LOW; unsigned long previousMillis1 = 0; //store last time LED1 was blinked const long period1 = 1000; // period at which led1 blinks in ms unsigned long previousMillis2 = 0; //store last time LED2 was blinked const long period2 = 200; // period at which led1 blinks in ms int debouncePeriod = 20; // debounce delay of 20ms int debounceMillis = 0; // similar to previousMillis bool buttonPushed = false; // interrupt routine button status int ledChange = LOW; // to track the led status last int lastState = HIGH; // to track last button state void setup() { pinMode(led1, OUTPUT); // define pins as input or output pinMode(led2, OUTPUT); pinMode(toggleLed, OUTPUT); pinMode(pushButton, INPUT); attachInterrupt(digitalPinToInterrupt(pushButton), pushButton_ISR, CHANGE); // use interrupt pin2 } void pushButton_ISR() { buttonPushed = true; // ISR should be as short as possible } void loop() { unsigned long currentMillis = millis(); // store the current time if (currentMillis - previousMillis1 >= period1) { // check if 1000ms passed previousMillis1 = currentMillis; // save the last time you blinked the LED if (ledState1 == LOW) { // if the LED is off turn it on and vice-versa ledState1 = HIGH; //change led state for next iteration } else { ledState1 = LOW; } digitalWrite(led1, ledState1); //set LED with ledState to blink again } if (currentMillis - previousMillis2 >= period2) { // check if 1000ms passed previousMillis2 = currentMillis; // save the last time you blinked the LED if (ledState2 == LOW) { // if the LED is off turn it on and vice-versa ledState2 = HIGH; } else { ledState2 = LOW; } digitalWrite(led2, ledState2);//set LED with ledState to blink again } if (buttonPushed = true) // check if ISR is called { if ((currentMillis - debounceMillis) > debouncePeriod && buttonPushed) // generate 20ms debounce delay to avoid multiple presses { debounceMillis = currentMillis; // save the last debounce delay time if (digitalRead(pushButton) == LOW && lastState == HIGH) // change the led after push button is pressed { ledChange = ! ledChange; digitalWrite(toggleLed, ledChange); lastState = LOW; } else if (digitalRead(pushButton) == HIGH && lastState == LOW) { lastState = HIGH; } buttonPushed = false; } } } Video microcontroller-projects/arduino-nodejs-tutorial-control-led-brightness-with-web-interface

Node.js with Arduino: Controlling Brightness of LED through Web Interface

where the LED can be controlled from anywhere.

What is Node.js?

is a widely used JavaScript-based framework built on Google Chrome’s JavaScript V8 Engine and applied in developing I/O intensive web applications such as single-page applications, video streaming sites etc. In this tutorial, we will follow the similar approach i.e. the LED will be controlled using two methods such as: Simple LED blink by writing a JavaScript code in the Node.js framework. LED Brightness Control Using Node.js framework and a web interface from any browser: The Arduino UNO will act as a webserver and HTML web page will be hosted on a PC or Laptop.

Components Required

Arduino UNO Board Led Resistor Arduino IDE: For uploading sketch to Arduino UNO Board. Firmata: It is a protocol for communicating with different microcontrollers from software on a computer, smartphone, etc. The Firmata firmware can be loaded in any microcontroller board (like Arduino, Teensy) and is able to talk to any laptop, PC or smartphone. Firmata Library comes with Arduino IDE, so no need to download from anywhere. We have done a tutorial on controlling Arduino with Raspberry Pi using pyFirmata. Johnny-Five: Johnny-Five is the JavaScript Based Robotics and IoT platform used to write codes in JavaScript and Used to make a bridge between the Arduino Boards and Computer. Johnny-Five have been tested with a variety of Arduino-compatible Boards such as Arduino UNO, NANO, Promini, etc. In this tutorial, the Johnny-Five library has to be downloaded in order to use all its features. The installation guide will be explained later-on in this tutorial.

Circuit Diagram

Circuit diagram is very basic, we just need to connect an LED with Arduino.

Setting Up Node.js Framework

Before starting the coding and development, the Node.js has to be downloaded and set up. For downloading the Node.js environment just follow simple steps. from its official website. Run the .exe and follow the given instructions in the installer. Restart your computer as it is recommended in the Node.js Document and also to use all the features of Node.js The Node.js version will be displayed indicating the Node.js is installed.

Installing Johnny-Five Library

ᾠfolder. To download, follow steps below: Open Command Prompt ᾠcommand. This will install all dependencies of Johnny-Five. Also install necessary libraries used in this tutorial for controlling brightness of LED. There are three libraries used here: express: HTTP server wrapper socket.io: WebSockets library serialport: Serial port wrapper Run the below commands one by one to install these three libraries. npm install express npm install socket.io npm install serialport Firstly, Arduino Blinking LED with Node.js Secondly, Controlling LED Brightness from web interface using Arduino and Node.js.

Blinking LED with Arduino and Node.js

To blink LED, the Arduino has to be Set up to communicate with Computer. , just follow these simple steps: Connect the Arduino UNO using USB cable Open Arduino IDE and select Arduino UNO board (If using other board then select respective one) from Tools. Select the Respective COM port of connected Arduino UNO Now find the Firmata Sketch using Menu -> File -> Examples -> Firmata -> StandardFirmata. Upload the “StandardFirmataᾼ/strong> sketch by going to File -> Upload. This will load the Firmata Sketch onto Arduino UNO and now the Arduino UNO is ready to accept any command from computer. code file. Initially define the Pin of microcontroller where led is connected. In this example, the LED is connected to Pin 5 of Arduino UNO. The ‘varᾠin Node.js represents variable declaration. var led_pin=5; ᾠwill access the module. var johnny_five=require("johnny-five"); var arduino_board=new johnny_five.Board(); statement is similar to print statement and it will print message. And the LED pin is set to output mode and the defined delay is given to blink led. console.log("LED has Started Blinking!"); var led = new johnny_five.Led(led_pin); led.blink(100); Now to run the program follow steps below: Open Command Prompt Locate “LED_Controlᾼ/strong> folder by following ‘cdᾼ/strong> command Run ‘Node led_blink.jsᾠcommand. If successfully executed it will show "LED has Started Blinking!" as shown in the image below. The led will start blinking in the Arduino UNO Pin 5. And this finishes the first part of our tutorial i.e. Blinking LED with Node.js

Controlling LED Brightness using Arduino and Node.js Webserver

, this section will also have some parts i.e. Setting up Arduino UNO, Setting up Web Interface and Writing a Node.js program. code has following important steps involved. Initially the baud rate is set at 9600. Serial.begin(9600); The serial port always looks for incoming byte and the byte is written to Pin 5 which is a PWM Pin. while(!Serial.available()); analogWrite(5, Serial.read()); pin and will change the brightness of LED. To have interface follow simple steps below: Create a new folder named “publicᾼ/strong> inside the “LED_Controlᾼ/strong> folder created before. Now download the “index.htmlᾼ/strong> and “style.cssᾠfiles and move both files inside the “publicᾠfolder created in first step above. Files can be downloaded from here. to control the brightness of LED using Node.js and Arduino. . Similar to Blink Led Node.js program, this section will also use modules (library). Include the ‘expressᾬ ‘httpᾠand ‘serial portᾠmodule. var express = require('express'); app = express(); server = require('http').createServer(app); io = require('socket.io').listen(server); var SerialPort = require("serialport")//.SerialPort Now set the COM port and baudrate. Note that in windows, it will always be COM with extension of number (COM6, COM4, COM24 etc.), so set below as required after ᾯᾮ Also set buadrate. var serialPort = new SerialPort("/COM4", { baudRate: 9600 }); Start to listen the server at port 8080. server.listen(8080); Set the brightness at 0 initially. Then latch the brightness data to IO with sockets module, which is a websocket module. The data will receive by Web Interface using socket protocol. io.sockets.on('connection', function (socket) { socket.on('led', function (data) { brightness = data.value; var buf = new Buffer(1); buf.writeUInt8(brightness, 0); serialPort.write(buf); Now emit the LED brightness value got from socket to LED pin. io.sockets.emit('led', {value: brightness}); }); socket.emit('led', {value: brightness}); }); in Node.js. console.log("Web Server Started go to 'http://localhost:8080' in your Browser."); Now to run the program by following the steps below: Open Command Prompt Locate “LED_Controlᾼ/strong> folder by following ‘cdᾼ/strong> command Run ‘Node brightness_control.jsᾠcommand. If successfully executed it will show "Web Server Started go to "http://localhost:8080" in your Browser." just below the command. Now go to your browser and type “localhost:8080ᾠin the url. To change the brightness just move the slider from 0-255 values. Code var led_pin=5; var johnny_five=require("johnny-five"); var arduino_board=new johnny_five.Board(); arduino_board.on("ready", function() { console.log("LED has Started Blinking!"); var led = new johnny_five.Led(led_pin); led.blink(100); }); void setup() { Serial.begin(9600); } void loop() { while(!Serial.available()); //wait until a byte was received analogWrite(5, Serial.read());//output received byte } var express = require('express'); app = express(); server = require('http').createServer(app); io = require('socket.io').listen(server); var SerialPort = require("serialport")//.SerialPort var serialPort = new SerialPort("/COM4", { baudRate: 9600 }); server.listen(8080); app.use(express.static('public')); var brightness = 0; io.sockets.on('connection', function (socket) { socket.on('led', function (data) { brightness = data.value; var buf = new Buffer(1); buf.writeUInt8(brightness, 0); serialPort.write(buf); io.sockets.emit('led', {value: brightness}); }); socket.emit('led', {value: brightness}); }); console.log("Web Server Started go to 'http://localhost:8080' in your Browser."); Video microcontroller-projects/raspberry-pi-with-lora-peer-to-peer-communication-with-arduino

LoRa with Raspberry Pi ᾠPeer to Peer Communication with Arduino

LoRa is getting increasingly popular with the advent of IoT, Connected Cars, M2M, Industry 4.0 etc. Because of its ability to communicate to long distances with very less power it is preferably used by designers to send/receive data from a battery powered Thing. We have already discussed the basics of LoRa and how to use LoRa with Arduino. Although the technology is originally intended for a LoRa Node to communicate with a LoRa gateway, there are many scenarios in which a LoRa Node has to communicate with another LoRa Node to exchange information over long distance. So, in this tutorial we will learn how to use a LoRa module SX1278 with Raspberry pi to communicate with another SX1278 connected to a microcontroller like Arduino. This method can come in handy at many places since the Arduino could act as a Server to fetch data from sensors and send it to Pi over a long distance through LoRa and then the Pi acting as a Client can receive these information and upload it to the could since it has access to internet. Sounds interesting right? So, let’s get started.

Materials Required

SX1278 433MHz LoRa Module ᾠ2 Nos 433MHz LoRa antenna ᾠ2Nos Arduino UNO- or other version Raspberry Pi 3 : Always use your SX1278 LoRa module with 433 MHz antennas; else the module might get damaged.

Connecting Raspberry Pi with LoRa

Before we get into the software packages, let’s get the hardware ready. The SX1278 is a 16-pin Lora module that communicates using SPI on 3.3V Logic. The Raspberry pi also operates in 3.3V logic level and also has in-built SPI port and 3.3V regulator. So we can directly connect the LoRa module with the Raspberry Pi. The connection table is shown below
Raspberry PiLora ᾼU+393C>SX1278 Module
3.3V3.3V
GroundGround
GPIO 10MOSI
GPIO 9MISO
GPIO 11SCK
GPIO 8Nss / Enable
GPIO 4DIO 0
GPIO 17DIO 1
GPIO 18DIO 2
GPIO 27DIO 3
GPIO 22RST
, hence appearance might differ in the below image. looks something like this below

Connecting Arduino with LoRa

we will use the Rspreal library based on Radio head which we will discuss later in this project. The circuit is give below Again you can use the 3.3V pin on Arduino Uno or use a separate 3.3V regulator. In this project I have used the on-board voltage regulator. The pin connection table is given below to help you to make the connections easily.
LoRa SX1278 ModuleArduino UNO Board
3.3V3.3V
GndGnd
En/NssD10
G0/DIO0D2
SCKD13
MISOD12
MOSID11
RSTD9
setup will look something like this below

pyLoRa for Raspberry Pi

modules which can be used on the Arduino and the Raspberry Pi environment. For now, let’s focus on the Raspberry Pi environment.

Configuring the Raspberry Pi for LoRa module

Follow the below steps to do the same, after opening the terminal window of Pi. Again, I am using putty to connect to my Pi you can use your convenient method. using the following command. To get the below window sudo raspi-config because as we discussed the LCD and PI communicates through SPI protocol using the following command. pip install RPi.GPIO This package class will help us control the GPIO pin on the Pi. If successfully installed your screen will look like this using the following command. Spidev is a python binding for Linux which can be used to perform SPI communication on Raspberry Pi. pip install spidev If the installation is successful the terminal should look something like this below. using the following pip command. This package installs the Radio models associated with LoRa. pip install pyLoRa If the installation is successful you will see the following screen. The PyLoRa package also supports encrypted communication which can be used with Arduino and Raspberry Pi seamlessly. This will improve the data security in your communication. But you have to install separate package after this step which I am not doing since encryption is not in the scope of this tutorial. You can follow the above github links for more details. But I was not able to add the path successfully and hence had to manually download library and use the same directly for my programs. So I had to proceed with the following steps using the below command. sudo apt-get install python-rpi.gpio python3-rpi.gpio sudo apt-get install python-spidev python3-spidev The terminal window should display something like this after both the installations. Also install git and then use it to clone the python directory for our Raspberry Pi. You can do that using the following commands. sudo apt-get install git sudo git clone https://github.com/rpsreal/pySX127x This will have all the required files associated with the library.

Programming Raspberry Pi for LoRa

Here I will try to explain the important lines in the program. Make sure the program file is in the same directory where the SX127x library folder is present. You can copy this folder and use it anywhere if you wish to port the project. If we receive anything we simple print them on the console. As always we begin the program by importing the required the python libraries. from time import sleep from SX127x.LoRa import * from SX127x.board_config import BOARD BOARD.setup() # Medium Range Defaults after init are 434.0MHz, Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on 13 dBm lora.set_pa_config(pa_select=1) def __init__(self, verbose=False): super(LoRaRcvCont, self).__init__(verbose) self.set_mode(MODE.SLEEP) self.set_dio_mapping([0] * 6) We set the module to work in continuous receiver mode (RXCONT) from sleep mode and then use a while loop to read values like RSSI and modem status. We also flush the data in the serial buffer onto the terminal. def start(self): self.reset_ptr_rx() self.set_mode(MODE.RXCONT) while True: sleep(.5) rssi_value = self.get_rssi_value() status = self.get_modem_status() sys.stdout.flush() In this function the received values is moved into a variable called payload from the Rx buffer after setting the receiving flag high. Then the received values are decoded with utf-8 to print a user readable data on the shell. We also put the module back in sleep mode till another value is received. def on_rx_done(self): print("\nReceived: ") self.clear_irq_flags(RxDone=1) payload = self.read_payload(nocheck=True) print(bytes(payload).decode("utf-8",'ignore')) self.set_mode(MODE.SLEEP) self.reset_ptr_rx() self.set_mode(MODE.RXCONT) We again set the board in sleep mode even after termination of the program to save power. try: lora.start() except KeyboardInterrupt: sys.stdout.flush() print("") sys.stderr.write("KeyboardInterrupt\n") finally: sys.stdout.flush() print("") lora.set_mode(MODE.SLEEP) BOARD.teardown()

Arduino Code for LoRa to communicate with Raspberry Pi

of this page as always. Here, I will explain few important lines in the program. We begin the program by importing the SPI library (installed by default) to use SPI protocol and then the RH_RF95 library from Radio head to perform LoRa communication. Then we define to which pin of Arduino we have connected the Chip select (CS), Reset (RST) and Interrupt (INT) pin of the LoRa with Arduino. Finally we also define that the module should work in 434MHz Frequency and initialize the LoRa module. #include <SPI.h> //Import SPI librarey #include <RH_RF95.h> // RF95 from RadioHead Librarey #define RFM95_CS 10 //CS if Lora connected to pin 10 #define RFM95_RST 9 //RST of Lora connected to pin 9 #define RFM95_INT 2 //INT of Lora connected to pin 2 // Change to 434.0 or other frequency, must match RX's freq! #define RF95_FREQ 434.0 // Singleton instance of the radio driver RH_RF95 rf95(RFM95_CS, RFM95_INT); Higher the transmission more distance your packets will travel but will consume more power. void setup() { //Initialize Serial Monitor Serial.begin(9600); // Reset LoRa Module pinMode(RFM95_RST, OUTPUT); digitalWrite(RFM95_RST, LOW); delay(10); digitalWrite(RFM95_RST, HIGH); delay(10); //Initialize LoRa Module while (!rf95.init()) { Serial.println("LoRa radio init failed"); while (1); } //Set the default frequency 434.0MHz if (!rf95.setFrequency(RF95_FREQ)) { Serial.println("setFrequency failed"); while (1); } rf95.setTxPower(18); //Transmission power of the Lora Module } This data can be anything like sensor value of user command. But for simplicity we will send char value 0 to 9 for every 1 second interval and then initialize the value back to 0 after reaching 9. Note that the values can be sent only in a char array format and the type of data should be unit8_t that is 1 byte at a time. The code to do the same is shown below void loop() { Serial.print("Send: "); char radiopacket[1] = char(value)}; rf95.send((uint8_t *)radiopacket, 1); delay(1000); value++; if (value > '9') value = 48; }

Testing LoRa Communication between Raspberry Pi and Arduino

Now, that we got both our hardware and program ready we simply have to upload the Arduino code to the UNO board and the python sketch should be launched on pi. My test set-up with both the hardware connected, looks something like this below You should notice “Received: 0ᾠto 9 like shown in the image below. between Arduino and Raspberry pi we can proceed with adding sensor on Arduino side and cloud platform on Pi side to make a complete IoT package. for other technical quires. Code ) from time import sleep from SX127x.LoRa import * from SX127x.board_config import BOARD BOARD.setup() class LoRaRcvCont(LoRa): def __init__(self, verbose=False): super(LoRaRcvCont, self).__init__(verbose) self.set_mode(MODE.SLEEP) self.set_dio_mapping([0] * 6) def start(self): self.reset_ptr_rx() self.set_mode(MODE.RXCONT) while True: sleep(.5) rssi_value = self.get_rssi_value() status = self.get_modem_status() sys.stdout.flush() def on_rx_done(self): print("\nReceived: ") self.clear_irq_flags(RxDone=1) payload = self.read_payload(nocheck=True) print(bytes(payload).decode("utf-8",'ignore')) self.set_mode(MODE.SLEEP) self.reset_ptr_rx() self.set_mode(MODE.RXCONT) lora = LoRaRcvCont(verbose=False) lora.set_mode(MODE.STDBY) # Medium Range Defaults after init are 434.0MHz, Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on 13 dBm lora.set_pa_config(pa_select=1) try: lora.start() except KeyboardInterrupt: sys.stdout.flush() print("") sys.stderr.write("KeyboardInterrupt\n") finally: sys.stdout.flush() print("") lora.set_mode(MODE.SLEEP) BOARD.teardown() //Arduino Raspberry Pi wireless Comunnication through LoRa - SX1278 //Send 0 to 9 from Arduino through Radio head LoRa without ACK //Code for: www.circuitdigest.com //Dated: 19-4-20198 #include <SPI.h> //Import SPI librarey #include <RH_RF95.h> // RF95 from RadioHead Librarey #define RFM95_CS 10 //CS if Lora connected to pin 10 #define RFM95_RST 9 //RST of Lora connected to pin 9 #define RFM95_INT 2 //INT of Lora connected to pin 2 // Change to 434.0 or other frequency, must match RX's freq! #define RF95_FREQ 434.0 // Singleton instance of the radio driver RH_RF95 rf95(RFM95_CS, RFM95_INT); void setup() { //Initialize Serial Monitor Serial.begin(9600); // Reset LoRa Module pinMode(RFM95_RST, OUTPUT); digitalWrite(RFM95_RST, LOW); delay(10); digitalWrite(RFM95_RST, HIGH); delay(10); //Initialize LoRa Module while (!rf95.init()) { Serial.println("LoRa radio init failed"); while (1); } //Set the default frequency 434.0MHz if (!rf95.setFrequency(RF95_FREQ)) { Serial.println("setFrequency failed"); while (1); } rf95.setTxPower(18); //Transmission power of the Lora Module } char value = 48; void loop() { Serial.print("Send: "); char radiopacket[1] = char(value)}; rf95.send((uint8_t *)radiopacket, 1); delay(1000); value++; if (value > '9') value = 48; } Video microcontroller-projects/diy-location-tracker-using-gsm-sim800-and-arduino

DIY Location Tracker using GSM SIM800 and Arduino

Self-driving cars and connected vehicles, is sure to change the way we commute in the future. Today companies like Tesla are encouraging its owners to lend out their cars as robot taxis when not used, recently its CEO Elon Musk took it to twitter to state that there will be more than 1 million robot taxis on road by 2020. This will not only impact general transportation but also change the way how logistics operate today. It works in such a way that when a phone call is made to the GSM module, the module will check the location and sends it back as a text message with Google map link to the number from which the phone call is made. This link when opened on phone will pin the location of modem on Google Maps. Sounds Interesting enough!!? So, let’s get started.

Arduino GSM Based CarTracker Circuit Diagram

This GSM car tracker system will use GPRS of SIM800 GSM module which will be connected with a microcontroller like Arduino. Although both the GSM module and the Arduino boards are available as separate packages I decided to make my own circuit combining both of them on a single board to save cost and space. The board can be powered by a 12V adapter or from the 12V battery in the cars/trucks, the on board buck converter will step down the 12V to 4V for GSM module and as 3.3V for the microcontroller to work. The complete circuit diagram is given below. Further below I will split this circuit diagram into blocks and explain them to make sure you can use them or modify them according to your application needs.

LM2596 Power module

to provide 4V to the SIM800 module from the input 12V. The SIM800 module requires around 2A peak current when initialized and searching for network, hence the power supply should be able to source that current, else the module will enter shutdown mode, and hence the LM2596 IC is selected which can supply upto 3A. The power supply regulator circuit is shown below. , which is then passed through an LC filter of value 100uH and 470uF respectively to filter output switching noise. The output voltage can be set by using the resistors R30 and R29 forming the potential divider circuit and connected to feedback pin as shown above. The formulae to calculate the output voltage for LM2596 is given below Vout = 1.23 * ((R1+R2)/R1)

Powering and Communicating with SIM800 IC

The SIM800 GSM modem is commonly available as modem, but we have used the bare IC package to reduce board space and cost. Using the SIM800 modem is pretty much straight forward, we simply have to power the IC though the VBAT and GND pins and then use the PWR KEY pin to enable the modem by pulling the pin down for 1 second. By default the pin is pulled high internally to VBAT through a resistor. , so if you are using it on portable devices then you can skip the LM2596 circuit and connect it directly to a lithium polymer battery. Then we have the network pins connected to a 6-pin SIM card colder to connect with our SIM card. The NETLIGHT pin is connected to a LED, this LED will act as a status LED to indicate the network status, though it is optional. Similarly the BT_ANT pin can be used to connect the module to an antenna to find network connection easily, which is again optional. Finally we have the TxD and RxD pins pulled out to a header pin, these two pins will be used to communicate with a microcontroller like Arduino through the standard USART protocol at 9600 baud rate. The other connections shown in the circuit above is optional and does not hood any significant importance for this project.

Microcontroller Side of GSM Locator

itself since it also supports both 3.3V and 5V operating voltages. similar to what we do with Arduino Pro mini in 3.3V mode.

Fabricating PCB for GSM Location Tracker

Now that we have a circuit that combines the GSM module with a microcontroller we have to fabricate it on a PCB. Again to save board space I decided to use a double side board with SMD components, so I opened my PCB designing software and assigned the packages and the components used in above circuit and began designing my PCB. Once the Design was complete itlooked something like this. You can also download the design files in GERBER format and fabricate it to get your boards. The Gerber file link is given below Now, that our Design is ready it is time to get them fabricated. To get thePCB done is quite easy, simply follow the steps below , sign up if this is your first time. Then, in the PCB Prototype tab enter the dimensions of your PCB, the number of layers and the number of PCB you require. Assuming the PCB is 80cm×80cm you can set the dimensions as shown below. button. You will be taken to a page where to set few additional parameters if required like the material used track spacing etc. But mostly the default values will work fine. The only thing that we have to consider here is the price and time. As you can see the Build Time is only 2-3 days and it just costs only $5 for our PSB. You can then select a preferred shipping method based on your requirement. and proceed with the payment. To make sure the process is smooth PCBGOGOverifies if your Gerber file is valid before proceeding with the payment. This way you can sure that your PCB is fabrication friendly and will reach you as committed.

Assembling the PCB

After the board was ordered, it reached me after some days though courier in a neatly labeled well packed box and like always the quality of the PCB was awesome. I turned on my soldering rod and started assembling the Board. Since the Footprints, pads, vias and silkscreen are perfectly of the right shape and size I had no problem assembling the board. For example the SMD pads of my 68 pin SIM800 module were of great quality and looked perfect like shown below after soldering the SIM800. are shown below. As you can see I have not used the microcontroller side of the board as it is still in testing stage, so for this tutorial I will hook up the GSM module with an external Arduino nano through the header pins. I will provide an update once the microcontrller part is also tested.

Connecting the Board to Arduino Nano

The external header on the board labeled as P2 can be connected to the Arduino Nano directly. Here I have connected the pins according to the table below
Pin D12PWR_KY
Pin D11TxD
Pin D10RxD
GndGND
The power key connected to pin D12 is used to enable/disabling the module after power up, this helps in saving power when the module is not used. Pin D11 and D12 is connected to Tx and Rx pins respectively, we will program the Arduino to used these pins as software serial to communicate with the board. The set-up looks like this below once the connections are made.

Programming Arduino for GPRS Vehicle Tracking System

we will not discuss much about that in this article. is easy compared to GSM. The following AT commands will be used to obtain the location information in DD format from the SIM800 module
AT+CGATT=1Connect SIM to GPROS
AT+SAPBR=3,1,"CONTYPE","GPRS"Activate bearer profile with connection type GPRS
AT+SAPBR=3,1,"APN","RCMNET"Set VPN for bearer Profile
AT+SAPBR=1,1Open Bearer profile
AT+SAPBR=2,1Get the IP address of the bearer profile
AT+CIPGSMLOC=1,1Request for location Pincode, latitude and longitude
Note: Make sure the SIM supports 2G and GPRS plan before proceeding with the above steps. The commands when executed directly over serial communication will respond like this shown below will be something like this +CIPGSMLOC: 0,75.802460,26.848892,2019/04/23,08:32:35 Where 0 is the location Pin code (fails to fetch in India), 26.8488832 is Latitude and 75.802460 is longitude. So we have to crop these values out from this result and append it to a Google Map link to point the place and address on a map. The link will be something like this , but I have explained the program into small snippets below to help you understand it. println command and then use the SIM800.read() function to get the result back from the SIM800 module and return it. The function is shown below String SIM800_send(String incoming) //Function to communicate with SIM800 module { SIM800.println(incoming); delay(100); //Print what is being sent to GSM module String result = ""; while (SIM800.available()) //Wait for result { char letter = SIM800.read(); result = result + String(letter); //combine char to string to get result } return result; //return the result } , we initialize the serial monitor and SIM800 communication and 9600 baud rate and also make the pin 12 (PWR_KY) low for 1 second to enable the GSM module. Then we use the above created function to communicate with the GSM module. We first enable echo by using “ATE1ᾠand then start following the commands listed above to get co-ordinates from GSM module. After each AT command we print the response on the serial monitor for debugging purpose, the code for the same is given below void setup() { //PWRKY pin of GSM module has to be pulled low for 1sec to enable the module pinMode(12,OUTPUT); digitalWrite(12, LOW); //Pull-down delay(1000); digitalWrite(12, HIGH); //Release Serial.begin(9600); //Serial COM for debugging SIM800.begin(9600); //Software serial called SIM800 to speak with SIM800 Module delay(1000); //wait for serial COM to get ready responce = SIM800_send("ATE1"); //Enable Echo if not enabled by default Serial.print ("Responce:"); Serial.println(responce); delay(1000); responce = SIM800_send("AT+CGATT=1"); //Set the SIM800 in GPRS mode Serial.print ("Responce:"); Serial.println(responce); delay(1000); responce = SIM800_send("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\" "); //Activate Bearer profile Serial.print ("Responce:"); Serial.println(responce); delay(1000); responce = SIM800_send("AT+SAPBR=3,1,\"APN\",\"RCMNET\" "); //Set VPN options => 'RCMNET' 'www' Serial.print ("Responce:"); Serial.println(responce); delay(2000); responce = SIM800_send("AT+SAPBR=1,1"); //Open bearer Profile Serial.print ("Responce:"); Serial.println(responce); //Open bearer Profile delay(2000); responce = SIM800_send("AT+SAPBR=2,1"); //Get the IP address of the bearer profile Serial.print ("Responce:"); Serial.println(responce); delay(1000); } function, we check if the Module is saying anything. If the module receives a call it will print out “RINGᾮ So, we make out program to check for RING buy combining all the output char to string and compare it directly to “RINGᾮ The code for the same is shown below. if (SIM800.available()) { //Check if the SIM800 Module is telling anything char a = SIM800.read(); Serial.write(a); //print what the module tells on serial monitor incoming = incoming + String(a); if (a == 13) //check for new line incoming =""; //clear the string if new line is detected incoming.trim(); //Remove /n or /r from the incomind data if (incoming=="RING") //If an incoming call is detected the SIM800 module will say "RING" check for it { ᾠcommand to get the location data from the internet. Serial.println ("Sending sms"); delay(1000); responce = SIM800_send("ATH"); //Hand up the incoming call using ATH delay (1000); responce = SIM800_send("ATE0"); //Disable Echo delay (1000); responce = ""; Latitude=""; Longitude=""; //initialise all string to null SIM800.println("AT+CIPGSMLOC=1,1"); delay(5000); //Request for location data function to trim the value of latitude and longitude. As you can see in the below sample message +CIPGSMLOC: 0,75.802460,26.848892,2019/04/23,08:32:35 The value of longitude is followed by the first command and ends with second command. Similarly the value of latitude starts with second command and ends with third comma. We can make use of these characteristics to fetch the latitude and longitude values form the program. Using the below code void prepare_message() { //Sample Output for AT+CIPGSMLOC=1,1 ==> +CIPGSMLOC: 0,75.802460,26.848892,2019/04/23,08:32:35 //where 26.8488832 is Lattitude and 75.802460 is longitute int first_comma = responce.indexOf(','); //Find the position of 1st comma int second_comma = responce.indexOf(',', first_comma+1); //Find the position of 2nd comma int third_comma = responce.indexOf(',', second_comma+1); //Find the position of 3rd comma for(int i=first_comma+1; i<second_comma; i++) //Values form 1st comma to 2nd comma is Longitude Longitude = Longitude + responce.charAt(i); for(int i=second_comma+1; i<third_comma; i++) //Values form 2nd comma to 3rd comma is Latitude Latitude = Latitude + responce.charAt(i); The code for the same is given below. Serial.println(Latitude); Serial.println(Longitude); Link = Link + Latitude + "," + Longitude; //Update the Link with latitude and Logitude values Here I have hardcoded the mobile number with the command AT+CMGS="907923XXXX", make sure you replace the command with your phone number. SIM800.println("AT+CMGF=1"); //Set the module in SMS mode delay(1000); SIM800.println("AT+CMGS=\"907923XXXX\""); //Send SMS to this number delay(1000); SIM800.println(Link); // we have send the string in variable Link delay(1000); SIM800.println((char)26);// ASCII code of CTRL+Z - used to terminate the text message delay(1000);

Testing the GPRS Tracking Device

Make the connections as discussed and upload the code to your Arduino Nano board. Insert the SIM card and make sure your network signal is established. One way to do this by monitoring the LED on your GSM module, which should flash once in every 3 seconds. Now open the serial monitor and you should see the following messages in your screen Click on the link and you phone will automatically take you to Google maps and plot the received location on your phone with a red color pin. You can then navigate to the location or get the address of that location. The above link when opened appears like this then follow the link. for other technical discussions. Code /*Program to send Latitude and Logitute Information from SIM800 to Phone via SMS on call request * Code by: B.Aswinth Raj * For: www.circuitdigest.com * Dated:23-04-2019 * Sample Output for AT+CIPGSMLOC=1,1 ==> +CIPGSMLOC: 0,75.802460,26.848892,2019/04/23,08:32:35 //where 26.8488832 is Lattitude and 75.802460 is longitute * Link to send: https://www.google.com/maps/place/26.8488892,75.802460 //where 26.8488832 is Lattitude and 75.802460 is longitute */ #include <SoftwareSerial.h> //Software Serial header to communicate with GSM module SoftwareSerial SIM800(10, 11); // RX, TX String Link = "The current Location is https://www.google.com/maps/place/"; //we will append the Lattitude and longitude value later int the program String responce = ""; String Longitude = ""; String Latitude = ""; String SIM800_send(String incoming) //Function to communicate with SIM800 module { SIM800.println(incoming); delay(100); //Print what is being sent to GSM module String result = ""; while (SIM800.available()) //Wait for result { char letter = SIM800.read(); result = result + String(letter); //combine char to string to get result } return result; //return the result } void setup() { //PWRKY pin of GSM module has to be pulled low for 1sec to enable the module pinMode(12,OUTPUT); digitalWrite(12, LOW); //Pull-down delay(1000); digitalWrite(12, HIGH); //Release Serial.begin(9600); //Serial COM for debugging SIM800.begin(9600); //Software serial called SIM800 to speak with SIM800 Module delay(1000); //wait for serial COM to get ready responce = SIM800_send("ATE1"); //Enable Echo if not enabled by default Serial.print ("Responce:"); Serial.println(responce); delay(1000); responce = SIM800_send("AT+CGATT=1"); //Set the SIM800 in GPRS mode Serial.print ("Responce:"); Serial.println(responce); delay(1000); responce = SIM800_send("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\" "); //Activate Bearer profile Serial.print ("Responce:"); Serial.println(responce); delay(1000); responce = SIM800_send("AT+SAPBR=3,1,\"APN\",\"RCMNET\" "); //Set VPN options => 'RCMNET' 'www' Serial.print ("Responce:"); Serial.println(responce); delay(2000); responce = SIM800_send("AT+SAPBR=1,1"); //Open bearer Profile Serial.print ("Responce:"); Serial.println(responce); //Open bearer Profile delay(2000); responce = SIM800_send("AT+SAPBR=2,1"); //Get the IP address of the bearer profile Serial.print ("Responce:"); Serial.println(responce); delay(1000); } void prepare_message() { //Sample Output for AT+CIPGSMLOC=1,1 ==> +CIPGSMLOC: 0,75.802460,26.848892,2019/04/23,08:32:35 //where 26.8488832 is Lattitude and 75.802460 is longitute int first_comma = responce.indexOf(','); //Find the position of 1st comma int second_comma = responce.indexOf(',', first_comma+1); //Find the position of 2nd comma int third_comma = responce.indexOf(',', second_comma+1); //Find the position of 3rd comma for(int i=first_comma+1; i<second_comma; i++) //Values form 1st comma to 2nd comma is Longitude Longitude = Longitude + responce.charAt(i); for(int i=second_comma+1; i<third_comma; i++) //Values form 2nd comma to 3rd comma is Latitude Latitude = Latitude + responce.charAt(i); Serial.println(Latitude); Serial.println(Longitude); Link = Link + Latitude + "," + Longitude; //Update the Link with latitude and Logitude values Serial.println(Link); } String incoming = ""; void loop() { if (SIM800.available()) { //Check if the SIM800 Module is telling anything char a = SIM800.read(); Serial.write(a); //print what the module tells on serial monitor incoming = incoming + String(a); if (a == 13) //check for new line incoming =""; //clear the string if new line is detected incoming.trim(); //Remove /n or /r from the incomind data if (incoming=="RING") //If an incoming call is detected the SIM800 module will say "RING" check for it { Serial.println ("Sending sms"); delay(1000); responce = SIM800_send("ATH"); //Hand up the incoming call using ATH delay (1000); responce = SIM800_send("ATE0"); //Disable Echo delay (1000); responce = ""; Latitude=""; Longitude=""; //initialise all string to null SIM800.println("AT+CIPGSMLOC=1,1"); delay(5000); //Request for location data while (SIM800.available()) { char letter = SIM800.read(); responce = responce + String(letter); //Store the location information in string responce } Serial.print("Result Obtained as:"); Serial.print(responce); Serial.println("*******"); prepare_message(); delay(1000); //use prepare_message funtion to prepare the link with the obtained LAT and LONG co-ordinates SIM800.println("AT+CMGF=1"); //Set the module in SMS mode delay(1000); SIM800.println("AT+CMGS=\"9612345678\""); //Send SMS to this number delay(1000); SIM800.println(Link); // we have send the string in variable Link delay(1000); SIM800.println((char)26);// ASCII code of CTRL+Z - used to terminate the text message delay(1000); } } if (Serial.available()) { //For debugging SIM800.write(Serial.read()); } } Video microcontroller-projects/rs485-modbus-serial-communication-using-arduino-uno-as-slave

RS-485 MODBUS Serial Communication using Arduino UNO as Slave

project, we will use Arduino Uno as Slave for serial communication. etc. Modbus has 255 function codes and there are mainly three popular versions of Modbus: MODBUS RTU MODBUS ASCII MODBUS/TCP RS485 can also be used with other controllers for serial communication: RS-485 Serial Communication between Raspberry Pi & Arduino UNO Serial Communication Between STM32F103C8 and Arduino UNO using RS-485 here.

RS-485 Serial Communication

to transfer binary data from one device to another. RS-485 supports higher data transfer rate of 30Mbps maximum. It also provides maximum data transfer distance compared to RS-232 protocol. It transfers data up to 1200-meter maximum. The main advantage of RS-485 over RS-232 is the multiple slave with single Master while RS-232 supports only single slave. Can have a maximum of 32 devices connected to RS-485 protocol. Another advantage of the RS-485 is immune to the noise as they use differential signal method to transfer. RS-485 is faster compared to I2C protocol.

Connecting RS-485 with Arduino

is needed as it allows serial communication over long distance of 1200 meters. It is bidirectional and half duplex and has data transfer rate of 2.5 Mbps. This module requires a voltage of 5V.
VCC5V
ANon-inverting Receiver Input Non-Inverting Driver Output
BInverting Receiver Input Inverting Driver Output
GNDGND (0V)
R0Receiver Out (RX pin)
REReceiver Output (LOW-Enable)
DEDriver Output (HIGH-Enable)
DIDriver Input (TX pin)

USB to RS-485 Converter Module

To use this device there are various Modbus Software available in the internet. In this tutorial a software called Simply Modbus Software is used.

Simply Modbus Master Software

. Before using the software, it is important to get familiar with the following terminologies. Each slave in a network is assigned a unique unit address from 1 to 127. When the masterrequests data, the first byte it sends is the Slave address. This way each slave knows afterthe first byte whether or not to ignore the message. The second byte sent by the Master is the Function code. This number tells the slave whichtable to access and whether to read from or write to the table.
04 (04hex)ReadAnalog Input Registers
03 (03hex)ReadAnalog Output Holding Registers
06 (06hex)Write singleAnalog Output Holding Register
16 (10hex)Write multipleAnalog Output Holding Registers
02 (02hex)ReadDiscrete Input Contacts
01 (01hex)ReadDiscrete Output Coils
05 (05hex)Write singleDiscrete Output Coil
15 (0Fhex)Write multipleDiscrete Output Coils
CRC stands for Cyclic Redundancy check. It is two bytes added to the end of everyModbus message for error detection.

Tools Required

Arduino UNO MAX-485 TTL to RS-485 Converter Module USB to RS-485 Converter Module LED (2) 1k-Resistor (2) 16x2 LCD display 10k Potentiometer Servo Motor SG-90 Simply Modbus Master

Circuit Diagram

0(RX)RO
1(TX)DI
4DE & RE
+5VVCC
GNDGND
AA
BB
VSSGND
VDD+5V
V0To control pin of potentiometer for contrast/brightness control of 16x2 LCD
RS8
RWGND
E9
D410
D511
D612
D713
A+5V
KGND
2Anode through 1k resistor--
5-Anode through 1k resistor-
6--PWM pin (Orange)
+5V--+5V (RED)
GNDCathode GNDCathode GNDGND (Brown)

Programming Arduino UNO for RS-485 MODBUS Slave

converter module, the whole setup will look file follows: Programming has some major steps which will be explained below. Initially, include the required library. ModbusRTU library is for using RS-485 Modbus communication, and the liquid crystal library is for using LCD with Arduino UNO, and the servo library is for using Servo motor with Arduino UNO. #include<ModbusRtu.h> #include<LiquidCrystal.h> #include <Servo.h> Now the LED anode pins that are connected with Arduino pins 2 and 5 are defined as LED1 and LED2. #define led1 2 #define led2 5 Next the object for accessing Liquid Crystal class is declared with the LCD pins (RS, E, D4, D5, D6, D7) that are connected with Arduino UNO. LiquidCrystal lcd(8,9,10,11,12,13); When LCD is done, Initialize servo object for class Servo. Also Initialize bus object for class Modbus. Servo servo; Modbus bus; Next for storing values for Modbus communication an array is declared with the three values initialized with zero. uint16_t modbus_array[] = {0,0,0}; function, firstly the LCD is set in 16x2 mode and a welcome message is displayed and cleared. lcd.begin(16,2); //Lcd set in 16x2 mode lcd.print("RS-485 Modbus"); //Welcome Message lcd.setCursor(0,1); lcd.print("Arduino Slave"); delay(5000); lcd.clear(); After this, LED1 and LED2 pins are set as output pins. pinMode(led1,OUTPUT); pinMode(led2,OUTPUT); The servo pulse pin connected to PWM pin 6 of Arduino is attached. servo.attach(6); Now for the Modbus communication the following parameters are set. First ᾱᾠrepresents Slave ID, second ᾱᾠrepresents that it uses RS-485 to transfer data and ᾴᾠrepresents RS-485 DE&RE pin connected to Arduino UNO. bus = Modbus(1,1,4); The Modbus slave is set at 9600 baudrate. is used to write and receive value from the master Modbus. bus.poll(modbus_array,sizeof(modbus_array)/sizeof(modbus_array[0])); This method is used to check if there is any data available at the serial port. If there is any data available at serial port the Modbus RTU library will check the message (check the device address, data length, and CRC) and perform the required action. to write or read any value from master, the ModbusRTU must receive an unsigned 16-bit integer array and its length from the Master Modbus. This array carries the data that is written from the master. is used. if (modbus_array[0] == 0) //Depends upon value in modubus_array[0] written by Master Modbus { digitalWrite(led1,LOW); //LED OFF if 0 lcd.setCursor(0,0); lcd.print("L1:OFF"); } else { digitalWrite(led1,HIGH); //LED ON if value other than 0 lcd.setCursor(0,0); lcd.print("L1:ON"); } is used. if (modbus_array[1] == 0) //Depends upon value in modbus_array[1] written by Master Modbus { digitalWrite(led2,LOW); //LED OFF if 0 lcd.setCursor(8,0); lcd.print("L2:OFF"); } else { digitalWrite(led2,HIGH); //LED ON if value other than 0 lcd.setCursor(9,0); lcd.print("L2:ON"); } used and value is printed in the 16x2 LCD display. int pwm = modbus_array[2]; servo.write(pwm); lcd.setCursor(0,1); lcd.print("Servo angle:"); lcd.print(pwm); delay(200); lcd.clear(); This finishes programming Arduino UNO for working it as MODBUS Slave. The next step will be testing it as Modbus Slave.

Testing the Arduino UNO as Rs485 Modbus Slave

software is installed. Open the device manager and check the COM port according to your PC where the USB to RS-485 Module is connected and after that open the Simply Modbus Master 8.1.1 software. is opened now open the Write option. Write is opened. Set the parameters Mode in RTU, COM port according to your PC (mine was COM6), Baud at 9600, Data Bits 8, Stop bit 1, Parity None and Slave ID as 1. 3. After that set first register as 40001 and values to write is 3 and the function code as 16 (Write Holding Register). After that write 1 to 40001 (For LED1 on) and 1 to 40002 (For LED2 on) and 90 to 40003 (For Servo Motor Angle) and then click SEND button. 4. After that enter 40001 as 1 and 40002 as 0 and 40003 as 180 and click SEND button. 5. Now writing 135 to 40003 and 40001 as 0 and 40002 as 1. In next tutorial we will use the Arduino Uno as master in MODBUS commination. Code //RS-485 Modbus Slave (Arduino UNO) //Circuit Digest #include<ModbusRtu.h> //Library for using Modbus in Arduino #include<LiquidCrystal.h> //Library for using 16x2 LCD display #include <Servo.h> //Library for using Servo Motor #define led1 2 //Define as 2 led1 #define led2 5 //Define as 5 led2 LiquidCrystal lcd(8,9,10,11,12,13); //initizlize lcd object with pins (RS,E,D4,D5,D6,D7) for class liquid crystal Servo servo; //Initilize servo object for class Servo Modbus bus; //Define Object bus for class modbus uint16_t modbus_array[] = {0,0,0}; //Array initilized with three 0 values void setup() { lcd.begin(16,2); //Lcd set in 16x2 mode lcd.print("RS-485 Modbus"); //Welcome Message lcd.setCursor(0,1); lcd.print("Arduino Slave"); delay(5000); lcd.clear(); pinMode(led1,OUTPUT); //Led1 set as OUTPUT pinMode(led2,OUTPUT); //Led2 set as OUTPUT servo.attach(6); //Servo PWM pin 6 bus = Modbus(1,1,4); //Modbus slave ID as 1 and 1 connected via RS-485 and 4 connected to DE & RE pin of RS-485 Module bus.begin(9600); //Modbus slave baudrate at 9600 } void loop() { bus.poll(modbus_array,sizeof(modbus_array)/sizeof(modbus_array[0])); //Used to receive or write value from Master if (modbus_array[0] == 0) //Depends upon value in modubus_array[0] written by Master Modbus { digitalWrite(led1,LOW); //LED OFF if 0 lcd.setCursor(0,0); lcd.print("L1:OFF"); } else { digitalWrite(led1,HIGH); //LED ON if value other than 0 lcd.setCursor(0,0); lcd.print("L1:ON"); } if (modbus_array[1] == 0) //Depends upon value in modbus_array[1] written by Master Modbus { digitalWrite(led2,LOW); //LED OFF if 0 lcd.setCursor(8,0); lcd.print("L2:OFF"); } else { digitalWrite(led2,HIGH); //LED ON if value other than 0 lcd.setCursor(9,0); lcd.print("L2:ON"); } int pwm = modbus_array[2]; //Depends upon value in modbus_array[1] written by Master Modbus servo.write(pwm); //Write Received value (0 to 180) from Modbus Master lcd.setCursor(0,1); lcd.print("Servo angle:"); lcd.print(pwm); //Prints Angle in 16x2 LCD display. delay(200); lcd.clear(); } Video microcontroller-projects/arduino-sw-420-vibration-sensor-module-interfacing

Interfacing Vibration Sensor Module with Arduino

But, there are few dedicated and cheap sensors are also available to detect the vibrations only, one such vibration sensor is SW-420 which we are going to interface with Arduino Uno. and whenever the vibration sensor detects any vibration or jerk an LED will start blinking.

Vibration Sensor Module SW-420

There are three peripherals available in the module, two LEDs, one for the Power state and other for the sensor’s output. Additionally, a potentiometer is available which can be further used to control the threshold point of the vibration. In this project, we will use 5V to power the module.

Components Required

Arduino UNO SW-420 Vibration Sensor Module 5mm LED (Any Color) Jumper Wires(Hookup Wires) USB Cable for Uploading Program

Arduino Vibration Sensor Circuit Diagram

is given below. The LED is connected in the D13 pin. The module is powered using the available 5V pin in the Arduino. The Ground and the 5V pin are used to power up the Arduino whereas the A5 pin is used to get the data from the vibration sensor. The circuit is constructed where the SW-420 module and LED are connected with Arduino Uno.

Arduino UnoVibration Sensor Programming

Initially the Header Files are included. The arduino header is included since this tutorial was written in Eclipse IDE with Arduino extension. This sketch will also work for Arduino IDE and while using this sketch in Arduino IDE, there is no need to include <Arduino.h> header. #include <Arduino.h> Here two macros are defined for ON and OFF. #define ON 1 #define OFF 0 The below statement is used for integrating the LEDs and the Vibration Sensor. The vibration sensor is connected to pin A5. The inbuilt LED is also used which is directly connected in the board to pin 13. The 5mm LED is also connected to the pin 13. /* * Pin Description */ int vibration_Sensor = A5; int LED = 13; Two integers are declared where the sensors present output and previous output will be stored, which will further used to detect whether the vibration is happening or not. /* * Programme flow Description */ int present_condition = 0; int previous_condition = 0; The same pin which is declared as the peripheral connection, the direction of the pins are configured. The sensor pin as input and the LED pin as an output. /* * Pin mode setup */ void setup() { pinMode(vibration_Sensor, INPUT); pinMode(LED, OUTPUT); } One function is written to blink the led twice. The delay can be configured by chaging the delay value. void led_blink(void) { digitalWrite(LED, ON); delay(250); digitalWrite(LED, OFF); delay(250); digitalWrite(LED, ON); delay(250); digitalWrite(LED, OFF); delay(250); } variable becomes 1 and led start to blink. And again when vibrations stops both the vaiables becomes 0 and LED stops blinking. void loop() { previous_condition = present_condition; present_condition = digitalRead(A5); // Reading digital data from the A5 Pin of the Arduino. if (previous_condition != present_condition) { led_blink(); } else { digitalWrite(LED, OFF); } } This finishes the programming the arduino UNO with Vibration sensor. The final step will be testing the whole setup.

Testing the Arduino Vibration Sensor Circuit

The circuit doesn’t require additional breadboard. It can be simply tested using the Arduino UNO Board. The led is monitored when the vibration sensor is hit or if it changes its state. The led will blink connected to Pin 13 of Arduino UNO when there is some vibrations. If the vibration sensor doesn’t work then please check the connection and power. Avoid any loose connection between sensor and microcontroller. or you can also comment below. Code /*//==============================================================================// * Vibration Sensor interfacing with Arduino * Date: - 15-04-2019 * Author:- Sourav Gupta * For:- circuitdigest.com */ //=============================================================================// #include <Arduino.h> #include <stdio.h> #define ON 1 #define OFF 0 /* * Pin Description */ int vibration_Sensor = A5; int LED = 13; /* * Programme flow Description */ int present_condition = 0; int previous_condition = 0; /* * Pin mode setup */ void setup() { pinMode(vibration_Sensor, INPUT); pinMode(LED, OUTPUT); } /* * Led blink */ void led_blink(void); /* * main_loop */ void loop() { previous_condition = present_condition; present_condition = digitalRead(A5); // Reading digital data from the A5 Pin of the Arduino. if (previous_condition != present_condition) { led_blink(); } else { digitalWrite(LED, OFF); } } void led_blink(void) { digitalWrite(LED, ON); delay(250); digitalWrite(LED, OFF); delay(250); digitalWrite(LED, ON); delay(250); digitalWrite(LED, OFF); delay(250); } Video microcontroller-projects/rs485-serial-communication-between-arduino-and-raspberry-pi

RS-485 Serial Communication between Raspberry Pi and Arduino Uno

It is important because the overall performance of any embedded application depends on communication means as it is related to cost reduction, faster data transfer, long distance coverage etc.

RS485 Serial Communication Protocol

to transfer binary data from one device to another. Differential signal method works by creating a differential voltage by using a positive and negative 5V. It provides a Half-Duplex communication when using two wires and Full-Duplex requires 4 fours wires. to show the angle value that is received from Raspberry Pi.

Components Required

Raspberry Pi 3 B+ (With Raspbian OS installed) Arduino UNO MAX485 TTL to RS485 Converter Module (2) SG-90 Servo Motor 16x2 LCD 10K Potentiometer Bread Board Connecting Wires

Pin-Out & Features of MAX-485 TTL to RS-485 converter module

Pin NamePin Description
VCC5V
ANon-inverting Receiver Input Non-Inverting Driver Output
BInverting Receiver Input Inverting Driver Output
GNDGND (0V)
R0Receiver Out (RX pin)
REReceiver Output (LOW-Enable)
DEDriver Output (HIGH-Enable)
DIDriver Input (TX pin)
MAX-485 TTL to RS-485 converter module has following features: Operating voltage: 5V On-board MAX485 chip A low power consumption for the RS485 communication Slew-rate limited transceiver 5.08mm pitch 2P terminal Convenient RS-485 communication wiring Board size: 44 x 14mm It allows serial communication over long distance of 1200 meters

Connecting RS-485 Module with Raspberry Pi 3 B+

pins of Pi is used (GPIO14, GPIO15).

Connecting RS-485 Module with Arduino UNO

To connect the MAX485 TTL to RS-485 ConverterModule to Arduino UNO the following UART pins of UNO is used (0,1).
DIGPIO14 (TX)
DE REGPIO4
R0GPIO15(RX)
VCC5V
GNDGND
ATo A of Slave RS-485
BTo B of Slave RS-485
DI1 (TX)
DE RE2
R00 (RX)
VCC5V
GNDGND
ATo A of Master RS-485
BTo B of Master RS-485
RED+5V
ORANGE (PWM)3
BROWNGND
VSSGND
VDD+5V
V0To potentiometer centre pin for contrast control of LCD
RS8
RWGND
E9
D410
D511
D612
D713
A+5V
KGND
This finishes all the necessary circuit connections between all components. Now start programming the Raspberry Pi and Arduino UNO with the Master and Slave code.

Programming Raspberry Pi as Master using Python

In the Master Raspberry Pi, the angle value of range (0,10,45,90,135,180,135,90,45,10,0) is sent to the RS-485 module via serial port of Pi that sends value to the Arduino UNO and controls the servo motor according to that. So, for using Serial port in Raspberry Pi the UART Serial port must be enabled. Before using UART pins in Raspberry Pi, it needs to be enabled. Follow the steps below to enable the UART (Serial) Pins in Raspberry Pi board. 2. Select Interfacing options 3. And then select serial 4. Then click on ‘Noᾠ(This is used to disable Linux UART console) 5. After that exit the raspi-config 6. Reboot the Pi Now Serial port is ready to be used. So, let’s see in detail about Python coding at master side now. Initially, all the libraries are imported for peripherals used. The libraries which are important here are time, serial(for serial communication), GPIO for accessing GPIO and sleep. import time import serial import RPi.GPIO as GPIO from time import sleep option specifies that you are referring to the pins by the number of pin in the board. GPIO.setmode(GPIO.BOARD) The GPIO pin number 7 on the Raspberry Pi is made HIGH because the pin 7 of Pi is connected to DE & RE of RS-485.It is made HIGH because it makes RPi to send values to RS-485. GPIO.setup(7, GPIO.OUT, initial=GPIO.HIGH) Initiate the serial class at the pins GPIO14 & GPIO 15 (Serial0 Port) with various information like which serial port, baud rate, parity and stop bits. send = serial.Serial( port='/dev/serial0', baudrate = 9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1 ) The variable ‘iᾠwith array of angle values is defined, these values will be sent via serial communication. i = [0,10,45,90,135,180,135,90,45,10,0] The function send.write(str(x)) sends the values to serial port to the RS-485 one by one written inside the while loop as it executes continuously. The values are sent with a delay of 1.5 seconds. while True: for x in i: send.write(str(x)) print(x) time.sleep(1.5) This finishes the code for Raspberry Pi which is acting as master in RS485 based serial communication.

Programming Arduino UNO (Slave)

is rotated according to the value received, and also the value is displayed in LCD display. So, in Arduino programming LCD display library and Servo motor library used. is used for programming Arduino UNO. Just like for master we had several peripherals and included necessary libraries, similarly the slave side has peripherals such as servo motor and 16X2 LCD display, so start with including libraries for these peripherals. #include <LiquidCrystal.h> #include <Servo.h> Next the 16X2 LCD display pins that are to be used with the Arduino UNO are defined and then the Servo object is also created. LiquidCrystal lcd(8,9,10,11,12,13); // Define LCD display pins RS,E,D4,D5,D6,D7 Servo servo; Initially a display message is displayed which can be changed according to the project and then it is cleared for next message. lcd.begin(16,2); lcd.print("CIRCUIT DIGEST"); lcd.setCursor(0,1); lcd.print("RS_485"); delay(3000); lcd.clear(); The serial communication is started at baud rate of 9600. Serial.begin(9600); As Arduino RS-485 receives value from master, so the pin 2 of (EnablePin) is made LOW to make it in input mode and also to make pin DE & RE of RS-485 LOW to read value from Master Raspberry Pi. digitalWrite(enablePin, LOW); pin 3. servo.attach(3); loop executes when there is a value available at serial port where RS485 module is connected. function is used to receive the integer value (Angle) from serial port that is sent from Raspberry Pi int angle = Serial.parseInt(); Write the received angle value to servo motor to rotate the servo motor shaft from (0 to 180). servo.write(angle); And finally, the angle value is displayed in LCD display using the respective LCD functions. lcd.setCursor(0,0); lcd.print("Angle From RPi "); lcd.setCursor(0,1); lcd.print(angle); is given at the end of this tutorial.

Testing the RS 485 Serial communication with Raspberry Pi and Arduino UNO

When circuit connections are complete and code is uploaded to Arduino UNO, then use terminal to run the python code in Raspberry Pi. The Angle value is sent from Raspberry Pi to Arduino Uno to control the Servo Motor angle via RS-485 Serial Communication. 1. At Angle: 0 2. At Angle: 90 3. At Angle:135 4. At Angle:180 If you have any doubt or suggestions then please comment below. Code import time import serial import RPi.GPIO as GPIO from time import sleep GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT, initial=GPIO.HIGH) send = serial.Serial( port='/dev/serial0', baudrate = 9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1 ) i = [0,10,45,90,135,180,135,90,45,10,0] while True: for x in i: send.write(str(x)) print(x) time.sleep(1.5) #include <LiquidCrystal.h> //Include LCD library for using LCD display functions #include <Servo.h> //For using Servo functions int enablePin = 2; LiquidCrystal lcd(8,9,10,11,12,13); // Define LCD display pins RS,E,D4,D5,D6,D7 Servo servo; void setup() { lcd.begin(16,2); lcd.print("CIRCUIT DIGEST"); lcd.setCursor(0,1); lcd.print("RS_485"); delay(3000); lcd.clear(); Serial.begin(9600); // initialize serial at baudrate 9600: pinMode(enablePin, OUTPUT); delay(10); digitalWrite(enablePin, LOW); // (Pin 2 always LOW to receive value from Master) servo.attach(3); // (Servo PWM pin connected to Pin 3 PWM pin of Arduino) } void loop() { while (Serial.available()) //While have data at Serial port this loop executes { lcd.clear(); int angle = Serial.parseInt(); //Receive INTEGER value from Master throught RS-485 servo.write(angle); //Write received value to Servo PWM pin (Setting Angle) lcd.setCursor(0,0); lcd.print("Angle From RPi "); lcd.setCursor(0,1); lcd.print(angle); //Displays the Angle value } } Video microcontroller-projects/arduino-7-segment-display-clock

Arduino 7 Segment Display Clock by Multiplexing Four 7 Segment Displays

and displaying the time in HH:MM format.

Components Required

4-Digit 7 Segment Display 74HC595 IC DS3231 RTC Module Arduino UNO Breadboard Connecting wires

4-Digit 7 Segment Display

4-digit 7 Segment display has four seven segment display joined together or we can say multiplexed together. They are used to display numerical values and also some alphabets with decimals and colon. The display can be used in both direction. Four digits are useful for making digital clocks or like counting numbers from 0 to 9999. Below is the internal diagram for 4-Digit 7 Segment display. The above image shows the common anode type 7 segment display. In Common Anode, all the positive terminals (Anodes) of all the 8 LEDs are connected together, named as COM. And all the negative terminals are left alone or connected to the microcontroller pins. By using microcontroller, if logic LOW is set to illuminate the particular LED segment and set logic High to turn OFF LED. In Common Cathode, all the Negative terminals (cathode) of all the 8 LEDs are connected together, named as COM. And all the positive terminals are left alone or connected to the microcontroller pins. By using microcontroller, if set logic HIGH to illuminate the LED and set LOW to turn OFF LED. Learn more about 7 segment displays here and check how it can be interfaced with other microcontrollers: 7 Segment Display Interfacing with Arduino 7 Segment Display Interfacing with Raspberry Pi Interfacing Seven Segment Display with ARM7-LPC2148 7 Segment Display Interfacing with PIC Microcontroller 7 Segment Display Interfacing with 8051 Microcontroller

74HC595 Shift Register IC

This IC uses three pins such as Clock, Data & Latch with the microcontroller to control the 8 output pins of the IC. The clock is used to provide continuously pulses from microcontroller and data pin is used to send the data like which output needs to be turned ON or OFF at the respective clock time.
1,2,3,4,5,6,7Output Pins (Q1 to Q7)The 74HC595 has 8 output pins out of which 7 are these pins. They can be controlled serially
8GroundConnected to the Groundof microcontroller
9(Q7) Serial OutputThis pin is used to connect more than one 74HC595 as cascading
10(MR) Master ResetResets all outputs as low. Must be held high for normal operation
11(SH_CP) ClockThis is the clock pin to which the clock signal has to be provided from MCU/MPU
12(ST_CP) LatchThe Latch pin is used to update the data to the output pins. It is active high
13(OE) Output EnableThe Output Enable is used to turn off the outputs. Must be held low for normal operation
14(DS) Serial DataThis is the pin to which data is sent, based on which the 8 outputs are controlled
15(Q0) OutputThe first output pin.
16VccThis pin powers the IC, typically +5V is used.

DS3231 RTC Module

etc. Here are some useful projects using it: Automatic Pet Feeder using Arduino Interfacing RTC Module (DS3231) with PIC Microcontroller: Digital Clock Interfacing RTC module (DS3231) with MSP430: Digital Clock ESP32 Real Time Clock using DS3231 Module Digital Wall Clock on PCB using AVR Microcontroller Atmega16 and DS3231 RTC
VCCConnected to positive of power source
GNDConnected to ground
SDASerial data pin (I2C)
SCLSerial clock pin (I2C)
SQWSquare Wave output pin
32K32K oscillator output
RTC counts seconds, minutes, hours and year Digital temperature sensor with ±3oC accuracy Register for Aging trim 400Khz I2C interface Low power consumption CR2032 battery backup with two to three-year life Operating Voltage: 2.3 to 5.5V

Circuit Diagram

VCC5V
GNDGND
SDAA4
SCLA4
11-SH_CP (SRCLK)6
12-ST_CP (RCLK)5
14-DS (Data)4
13-OE(Latch)GND
8-GNDGND
10-MR(SRCLR)+5V
16-VCC+5V
AQ0-
BQ1-
CQ2-
DQ3-
EQ4-
FQ5-
GQ6-
D1-10
D2-11
D3-12
D4-9

Programming Arduino UNO for Multiplexing Seven Segment Display

are attached at the end of this tutorial. In the programming section, how the time (hour and minute) is taken from the RTC module in 24hr format and then it is converted into respective format for displaying them in the 4-digit 7 Segment display will be explained. library is also used in the program. and then from the shift register to the seven-segment, successfully displaying the Digit 0 in seven segment display. This way, the four digits are multiplexed and hour and minute is displayed. and Wire library(I2C library). #include <Wire.h> #include<DS3231.h> #define latchPin 5 #define clockPin 6 #define dataPin 4 #define dot 2 The variables are declared to store the converted or raw result taken from the RTC. int h; //Variable declared for hour int m; //Variable declared for minute int thousands; int hundreds; int tens; int unit; bool h24; bool PM; Next the object for the class DS3231 is declared as RTC to simplify the use in further lines. DS3231 RTC; As RTC module is interfaced with Arduino by using I2C communication. So, wire.begin() is used to start I2C communication in default address of RTC as there are no other I2C modules. Wire.begin(); , whether the GPIO will behave as output or input. pinMode(9,OUTPUT); pinMode(10,OUTPUT); pinMode(11,OUTPUT); pinMode(12,OUTPUT); pinMode(latchPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(dataPin, OUTPUT); pinMode(dot,OUTPUT); The loop runs infinitely and it takes the time in hour and minute from the RTC DS3231 module. ‘h24ᾠindicates the 24hr format variable. int h= RTC.getHour(h24, PM); int m = RTC.getMinute(); Then the hour and minute is combined as one number (example if hour is 10 and min is 60 then number is 10*100=1000+60 =1060). int number = h*100+m; (example 1060- 1 is thousand,0 is hundered,1 is tenth and 0 is last digit). To separate the digits, modulus operator is used. For example, in 1060 to get 1 then 1060/1000=1.06%10=1). So separate digits are stored in separate variables. int thousands = number/1000%10; int hundreds = number/100%10; int tens = number/10%10; int unit = number%10; After that a switch case statement for each individual digit is defined for converting them into respective format (binary format) and sending out via shift register to display in 7-segment. For example (For 1 digit it is changed into 06 (0000 0110)). So that it is sent out via shift and 1 digit is displayed in 7-segment (0 for LOW, 1 for HIGH). switch (t) { case 0: unit = 63; break; case 1: unit = 06; break; case 2: unit =91; break; case 3: unit=79; break; case 4: unit=102; break; case 5: unit = 109; break; case 6: unit =125; case 7: unit = 07; break; case 8: unit = 127; break; case 9: unit =103; break; } Then the individual digit in binary format is sent out via ‘shiftoutᾠfunction with MSB first and the respective digit pin is made HIGH and latch pin is made HIGH. digitalWrite(9, LOW); digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST,thousands); digitalWrite(latchPin, HIGH); digitalWrite(9, HIGH); delay(5); This finishes the complete code. Most of the function explanation are given in the code comment section just beside the code line. The frequency of the clock will decide the view of Time and quality of multiplexing I.e. if low clock is used then the flickering can be seen where as if the clock speed is high then there won’t be such flickering and a steady time can be seen. Note that to access the RTC module, the I2C bus voltage has to be maintained. In order to give any suggestion or if you have any doubt then please comment below. Code //Four-Digit 7 Segments Multiplexing using Arduino: Display time in HH:MM //CIRCUIT DIGEST #include <Wire.h> //Library for SPI communication #include <DS3231.h> //Library for RTC module #define latchPin 5 #define clockPin 6 #define dataPin 4 #define dot 2 DS3231 RTC; //Declare object RTC for class DS3231 int h; //Variable declared for hour int m; //Variable declared for minute int thousands; int hundreds; int tens; int unit; bool h24; bool PM; void setup () { Wire.begin(); pinMode(9,OUTPUT); pinMode(10,OUTPUT); pinMode(11,OUTPUT); pinMode(12,OUTPUT); pinMode(latchPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(dataPin, OUTPUT); pinMode(dot,OUTPUT); } void loop () { digitalWrite(dot,HIGH); int h= RTC.getHour(h24, PM); //To get the Hour int m = RTC.getMinute(); //TO get the minute int number = h*100+m; //Converts hour and minute in 4-digit int thousands = number/1000%10; //Getting thousands digit from the 4 digit int hundreds = number/100%10; //Getting hundreds digit from 4 digit int tens = number/10%10; //Getting tens digit from 4-digit int unit = number%10; //Getting last digit from 4-digit int t= unit; int u= tens; int v= hundreds; int w= thousands; //Converting the individual digits into corresponding number for passing it through the shift register so LEDs are turned ON or OFF in seven segment switch (t) { case 0: unit = 63; break; case 1: unit = 06; break; case 2: unit =91; break; case 3: unit=79; break; case 4: unit=102; break; case 5: unit = 109; break; case 6: unit =125; case 7: unit = 07; break; case 8: unit = 127; break; case 9: unit =103; break; } switch (u) { case 0: tens = 63; break; case 1: tens = 06; break; case 2: tens =91; break; case 3: tens=79; break; case 4: tens=102; break; case 5: tens= 109; break; case 6: tens =125; case 7: tens = 07; break; case 8: tens = 127; break; case 9: tens =103; break; } switch (v) { case 0: hundreds = 63; break; case 1: hundreds = 06; break; case 2: hundreds =91; break; case 3: hundreds=79; break; case 4: hundreds=102; break; case 5: hundreds = 109; break; case 6: hundreds =125; case 7: hundreds = 07; break; case 8: hundreds = 127; break; case 9: hundreds =103; break; } switch (w) { case 0: thousands = 63; break; case 1: thousands = 06; break; case 2: thousands =91; break; case 3: thousands=79; break; case 4: thousands=102; break; case 5: thousands = 109; break; case 6: thousands =125; case 7: thousands = 07; break; case 8: thousands= 127; break; case 9: thousands =103; break; } digitalWrite(9, LOW); digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST,thousands); // The thousand digit is sent digitalWrite(latchPin, HIGH); // Set latch pin HIGH to store the inputs digitalWrite(9, HIGH); // Turinig on that thousands digit delay(5); // delay for multiplexing digitalWrite(10, LOW); digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST,hundreds ); // The hundered digit is sent digitalWrite(latchPin, HIGH); digitalWrite(10, HIGH); delay(5); digitalWrite(11, LOW); digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST,tens); // The tens digit is sent digitalWrite(latchPin, HIGH); digitalWrite(11, HIGH); delay(5); digitalWrite(12, LOW); digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST,unit); // The last digit is sent digitalWrite(latchPin, HIGH); digitalWrite(12, HIGH); delay(5); } Video microcontroller-projects/arduino-ttp223-touch-sensor-interfacing-to-turn-on-lights-with-touch

Control Home Lights with Touch using TTP223 Touch Sensor and Arduino UNO

is the widely used type in touch sensor segment. The Arduino is a widely popular and easily available development board. with different microcontrollers such as: Touch Keypad Interfacing with ATmega32 Microcontroller Capacitive Touch Pad with Raspberry Pi

Touch Sensor

The operating voltage of the TTP223 IC is from the 2 V to 5.5 V and the current consumption of the touch sensor is very low. Due to the inexpensive, low current consumption, and easy to integrate support, the touch sensor with TTP223 becomes popular in the capacitive touch sensor segment. which will be very useful. Below chart is showing different outputs at different jumper settings-
Jumper AJumper BOutput Lock StateOutput TTL level
OpenOpenNo-lockHigh
OpenCloseSelf-lockHigh
CloseOpenNo-LockLow
CloseCloseSelf-LockLow
For this project, the sensor will be used as the default configuration which is available on the factory release condition.

Get to know about Relay

, it is important to have a fair idea about the relay’s pin description. The pinout of the relay can be seen in the below image- before the application. The relay has an operating voltage across the L1 and L2. Some relay works with 12V, some with the 6V and some with the 5V. Not only has this, the NO, NC and POLE also had a voltage and current rating. For our application, we are using 5V Relay with a 250V, 6A rating on the switching side.

Components Required

Arduino UNO The USB cable for programming and power Standard Cubic Relay - 5V 2k resistor -1 pc 4.7k resistor - 1 pc BC549B transistor TTP223 Sensor module 1N4007 Diode Light Bulb With Bulb Holder A breadboard A phone charger to connect the Arduino via USB cable. Lots of hookup wires or berg wires. Arduino programming platform. 2k resistor, BC549B, 1N4007, and the Relay can be replaced with a Relay Module.

Circuit Diagram

is simple and can be seen below, The touch sensor is connected with the Arduino UNO board. The circuit is constructed on a breadboard with the Arduino as below. The proper breadboard connection can be seen in the below schematic.

Programming Arduino UNO to Control Light Bulb using Touch Sensor

is given at the end. Here we are explaining few important parts of the code. The Arduino UNO will be programmed using Arduino IDE. Firstly, the Arduino library is included to access all default functions of Arduino. #include <Arduino.h> Define all the pin numbers where relay and touch sensor will be connected. Here, the touch sensor is connected to pin A5. The inbuilt LED is also used which is directly connected in the board to pin 13. The relay is connected to pin A4. /* * Pin Description */ int Touch_Sensor = A5; int LED = 13; int Relay = A4; i.e. what should be the pin function whether as input or output. Here touch sensor is made input. Relay and LED pins are output. /* * Pin mode setup */ void setup() { pinMode(Touch_Sensor, INPUT); pinMode(LED, OUTPUT); pinMode(Relay, OUTPUT); } Two integers are declared where the ‘conditionᾠis used to hold the sensor’s condition whether it is touched or not. The ‘stateᾠis used for holding the state of the LED and Relay, on or off. /* * Programme flow Description */ int condition = 0; int state = 0; //To hold the switch state. is used to confirm the single touch. void loop() { condition = digitalRead(A5); // Reading digital data from the A5 Pin of the Arduino. if(condition == 1){ delay(250); // de-bounce delay. if(condition == 1){ state = ~state; // Changing the state of the switch. digitalWrite(LED, state); digitalWrite(Relay, state); } } }

Testing the Working of Touch Sensor TTP223

The circuit is tested in the breadboard with a low power bulb connected to it. this project uses 230-240V AC voltage, so it is advised to be careful while using bulb. If you have any doubt or suggestion, then please comment below. Code /*//==============================================================================// * TTP223 interfacing with Arduino * Date: - 3-04-2019 * Author:- Sourav Gupta * For:- circuitdigest.com *///=============================================================================// #include <Arduino.h> //#define ON 1 //#define OFF 0 /* * Pin Description */ int Touch_Sensor = A5; int LED = 13; int Relay = A4; /* * Programme flow Description */ int condition = 0; int state = 0; //To hold the switch state. /* * Pin mode setup */ void setup() { pinMode(Touch_Sensor, INPUT); pinMode(LED, OUTPUT); pinMode(Relay, OUTPUT); } void loop() { condition = digitalRead(A5); // Reading digital data from the A5 Pin of the Arduino. if(condition == 1){ delay(250); // de-bounce delay. if(condition == 1){ state = ~state; // Changing the state of the switch. digitalWrite(LED, state); digitalWrite(Relay, state); } } } Video microcontroller-projects/how-to-use-ov7670-camera-module-with-arduino

How to Use OV7670 Camera Module with Arduino

etc. with same pin configuration, code and steps. The camera module is hard to interface because it has large number of pins and jumbled wiring to carry out. Also the wire becomes very important when using camera modules as the choice of the wire and length of the wire can significantly affect the picture quality and can bring noise. We have already done ample projects on Cameras with different kind of Microcontrollers and IoT Devices such as: Visitor Monitoring System with Raspberry Pi and Pi Camera IOT based Raspberry Pi Home Security System with Email Alert Raspberry Pi Surveillance Camera with Motion Capture

Components Required

Arduino UNO OV7670 Camera Module Resistors(10k, 4.7k) Jumpers Arduino IDE Serial Port Reader (To analyze Output Image)

Things to Remember about Camera Module OV7670

OV7670 Camera Module is a FIFO camera Module available from different Manufacturers with different pin Configurations. TheOV7670 provides full frame, windowed 8-bit images in a wide range of formats. The image array is capable of operating at up to 30 frames per second (fps) in VGA. The OV7670 includes Image Sensor Array(of about 656 x 488 pixels) Timing Generator Analog Signal Processor A/D Converters Test Pattern Generator Digital Signal Processor(DSP) Image Scaler Digital Video Port LED and Strobe Flash Control Output (SIOC, SIOD) with a maximum clock frequency of 400KHz. The Camera comes with handshaking signals such as: VSYNC: Vertical Sync Output ᾠLow during frame HREF: Horizontal Reference ᾠHigh during active pixels of row PCLK: Pixel Clock Output ᾠFree running clock. Data is valid on rising edge In addition to this, it has several more signals such as D0-D7: 8-bit YUV/RGB Video Component Digital Output PWDN: Power Down Mode Selection ᾠNormal Modeand Power Down Mode XCLK: System Clock Input Reset: Reset Signal The OV7670 is clocked from a 24MHz oscillator. This gives a Pixel Clock(PCLK) output of 24MHz. The FIFO provides 3Mbps of video frame buffer memory. The test pattern generator features 8-bar color bar pattern, fade-to-gray color bar patter. Now let’s start programming the Arduino UNO for testing Camera OV7670 and grabbing frames using serial port reader.

Circuit Diagram

Programming Arduino UNO

The programming starts with including required library necessary for OV7670. Since OV7670 runs on I2C interface, it includes <util/twi.h> library. The libraries used in this project are built-in libraries of ArduinoIDE. We just have to include the libraries to get the job done. After this, the registers need to be modified for OV7670. The program is divided into small functions for better understanding. clock, selection of interrupt pins, presclaer selection, adding parity and stop bits. arduinoUnoInut(); After configuring the Arduino, the camera has to be configured. To initialise the camera, we only have the options to change the register values. The register values need to be changed from the default to the custom. Also add required delay depending upon the microcontroller frequency we are using. As, slow microcontrollers have less processing time adding more delay between capturing frames. void camInit(void){ writeReg(0x12, 0x80); _delay_ms(100); wrSensorRegs8_8(ov7670_default_regs); writeReg(REG_COM10, 32);//PCLK does not toggle on HBLANK. } The camera is set to take a QVGA image so the resolution need to be selected. The function configures the register to take a QVGA image. setResolution(); In this tutorial, the images are taken in monochrome, so the register value is set to output a monochrome image. The function sets the register values from register list which is predefined in the program. setColor(); If you get the scrambled images then try to change the second term i.e. 10 to 9/11/12. But most of the time this value works fine so no need to change it. writeReg(0x11, 10); This function is used to get the image resolution size. In this project we are taking pictures in the size of 320 x 240 pixels. captureImg(320, 240); at the end of this tutorial. Just Upload the code and open the Serial Port Reader and grab the frames.

How to Use Serial Port Reader for reading Images

Serial Port Reader is a simple GUI, download it from here. This captures the base64 encode and decodes it to form an image. Just follow these simple steps to use Serial Port Reader Connect Your Arduino to any USB Port of your PC Click on “Checkᾠto find your Arduino COM Port Finally click on “Startᾠbutton to start reading serially. One can also save this pictures by just clicking on “Save Pictureᾮ

Below are Sample Images Taken from the OV7670

Precautions when using OV7670

Try to use wires or jumpers as short as possible Avoid any loose contact to any pins on Arduino or OV7670 Be careful about connecting as large number of wiring can lead short circuit If the UNO gives 5V output to GPIO then use Level Shifter. Use 3.3V Input for OV7670 as exceeding voltage than this can damage the OV7670 module. This project is created to give overview of using a camera module with Arduino. Since Arduino has less memory, so the processing may not be as expected. You can use different controllers which has more memory for processing. Code #include <stdint.h> #include <avr/io.h> #include <util/twi.h> #include <util/delay.h> #include <avr/pgmspace.h> #define F_CPU 16000000UL #define vga 0 #define qvga 1 #define qqvga 2 #define yuv422 0 #define rgb565 1 #define bayerRGB 2 #define camAddr_WR 0x42 #define camAddr_RD 0x43 /* Registers */ #define REG_GAIN 0x00 /* Gain lower 8 bits (rest in vref) */ #define REG_BLUE 0x01 /* blue gain */ #define REG_RED 0x02 /* red gain */ #define REG_VREF 0x03 /* Pieces of GAIN, VSTART, VSTOP */ #define REG_COM1 0x04 /* Control 1 */ #define COM1_CCIR656 0x40 /* CCIR656 enable */ #define REG_BAVE 0x05 /* U/B Average level */ #define REG_GbAVE 0x06 /* Y/Gb Average level */ #define REG_AECHH 0x07 /* AEC MS 5 bits */ #define REG_RAVE 0x08 /* V/R Average level */ #define REG_COM2 0x09 /* Control 2 */ #define COM2_SSLEEP 0x10 /* Soft sleep mode */ #define REG_PID 0x0a /* Product ID MSB */ #define REG_VER 0x0b /* Product ID LSB */ #define REG_COM3 0x0c /* Control 3 */ #define COM3_SWAP 0x40 /* Byte swap */ #define COM3_SCALEEN 0x08 /* Enable scaling */ #define COM3_DCWEN 0x04 /* Enable downsamp/crop/window */ #define REG_COM4 0x0d /* Control 4 */ #define REG_COM5 0x0e /* All "reserved" */ #define REG_COM6 0x0f /* Control 6 */ #define REG_AECH 0x10 /* More bits of AEC value */ #define REG_CLKRC 0x11 /* Clocl control */ #define CLK_EXT 0x40 /* Use external clock directly */ #define CLK_SCALE 0x3f /* Mask for internal clock scale */ #define REG_COM7 0x12 /* Control 7 */ //REG mean address. #define COM7_RESET 0x80 /* Register reset */ #define COM7_FMT_MASK 0x38 #define COM7_FMT_VGA 0x00 #define COM7_FMT_CIF 0x20 /* CIF format */ #define COM7_FMT_QVGA 0x10 /* QVGA format */ #define COM7_FMT_QCIF 0x08 /* QCIF format */ #define COM7_RGB 0x04 /* bits 0 and 2 - RGB format */ #define COM7_YUV 0x00 /* YUV */ #define COM7_BAYER 0x01 /* Bayer format */ #define COM7_PBAYER 0x05 /* "Processed bayer" */ #define REG_COM8 0x13 /* Control 8 */ #define COM8_FASTAEC 0x80 /* Enable fast AGC/AEC */ #define COM8_AECSTEP 0x40 /* Unlimited AEC step size */ #define COM8_BFILT 0x20 /* Band filter enable */ #define COM8_AGC 0x04 /* Auto gain enable */ #define COM8_AWB 0x02 /* White balance enable */ #define COM8_AEC 0x01 /* Auto exposure enable */ #define REG_COM9 0x14 /* Control 9- gain ceiling */ #define REG_COM10 0x15 /* Control 10 */ #define COM10_HSYNC 0x40 /* HSYNC instead of HREF */ #define COM10_PCLK_HB 0x20 /* Suppress PCLK on horiz blank */ #define COM10_HREF_REV 0x08 /* Reverse HREF */ #define COM10_VS_LEAD 0x04 /* VSYNC on clock leading edge */ #define COM10_VS_NEG 0x02 /* VSYNC negative */ #define COM10_HS_NEG 0x01 /* HSYNC negative */ #define REG_HSTART 0x17 /* Horiz start high bits */ #define REG_HSTOP 0x18 /* Horiz stop high bits */ #define REG_VSTART 0x19 /* Vert start high bits */ #define REG_VSTOP 0x1a /* Vert stop high bits */ #define REG_PSHFT 0x1b /* Pixel delay after HREF */ #define REG_MIDH 0x1c /* Manuf. ID high */ #define REG_MIDL 0x1d /* Manuf. ID low */ #define REG_MVFP 0x1e /* Mirror / vflip */ #define MVFP_MIRROR 0x20 /* Mirror image */ #define MVFP_FLIP 0x10 /* Vertical flip */ #define REG_AEW 0x24 /* AGC upper limit */ #define REG_AEB 0x25 /* AGC lower limit */ #define REG_VPT 0x26 /* AGC/AEC fast mode op region */ #define REG_HSYST 0x30 /* HSYNC rising edge delay */ #define REG_HSYEN 0x31 /* HSYNC falling edge delay */ #define REG_HREF 0x32 /* HREF pieces */ #define REG_TSLB 0x3a /* lots of stuff */ #define TSLB_YLAST 0x04 /* UYVY or VYUY - see com13 */ #define REG_COM11 0x3b /* Control 11 */ #define COM11_NIGHT 0x80 /* NIght mode enable */ #define COM11_NMFR 0x60 /* Two bit NM frame rate */ #define COM11_HZAUTO 0x10 /* Auto detect 50/60 Hz */ #define COM11_50HZ 0x08 /* Manual 50Hz select */ #define COM11_EXP 0x02 #define REG_COM12 0x3c /* Control 12 */ #define COM12_HREF 0x80 /* HREF always */ #define REG_COM13 0x3d /* Control 13 */ #define COM13_GAMMA 0x80 /* Gamma enable */ #define COM13_UVSAT 0x40 /* UV saturation auto adjustment */ #define COM13_UVSWAP 0x01 /* V before U - w/TSLB */ #define REG_COM14 0x3e /* Control 14 */ #define COM14_DCWEN 0x10 /* DCW/PCLK-scale enable */ #define REG_EDGE 0x3f /* Edge enhancement factor */ #define REG_COM15 0x40 /* Control 15 */ #define COM15_R10F0 0x00 /* Data range 10 to F0 */ #define COM15_R01FE 0x80 /* 01 to FE */ #define COM15_R00FF 0xc0 /* 00 to FF */ #define COM15_RGB565 0x10 /* RGB565 output */ #define COM15_RGB555 0x30 /* RGB555 output */ #define REG_COM16 0x41 /* Control 16 */ #define COM16_AWBGAIN 0x08 /* AWB gain enable */ #define REG_COM17 0x42 /* Control 17 */ #define COM17_AECWIN 0xc0 /* AEC window - must match COM4 */ #define COM17_CBAR 0x08 /* DSP Color bar */ /* * This matrix defines how the colors are generated, must be * tweaked to adjust hue and saturation. * * Order: v-red, v-green, v-blue, u-red, u-green, u-blue * They are nine-bit signed quantities, with the sign bit * stored in0x58.Sign for v-red is bit 0, and up from there. */ #define REG_CMATRIX_BASE 0x4f #define CMATRIX_LEN 6 #define REG_CMATRIX_SIGN 0x58 #define REG_BRIGHT 0x55 /* Brightness */ #define REG_CONTRAS 0x56 /* Contrast control */ #define REG_GFIX 0x69 /* Fix gain control */ #define REG_REG76 0x76 /* OV's name */ #define R76_BLKPCOR 0x80 /* Black pixel correction enable */ #define R76_WHTPCOR 0x40 /* White pixel correction enable */ #define REG_RGB444 0x8c /* RGB 444 control */ #define R444_ENABLE 0x02 /* Turn on RGB444, overrides 5x5 */ #define R444_RGBX 0x01 /* Empty nibble at end */ #define REG_HAECC1 0x9f /* Hist AEC/AGC control 1 */ #define REG_HAECC2 0xa0 /* Hist AEC/AGC control 2 */ #define REG_BD50MAX 0xa5 /* 50hz banding step limit */ #define REG_HAECC3 0xa6 /* Hist AEC/AGC control 3 */ #define REG_HAECC4 0xa7 /* Hist AEC/AGC control 4 */ #define REG_HAECC5 0xa8 /* Hist AEC/AGC control 5 */ #define REG_HAECC6 0xa9 /* Hist AEC/AGC control 6 */ #define REG_HAECC7 0xaa /* Hist AEC/AGC control 7 */ #define REG_BD60MAX 0xab /* 60hz banding step limit */ #define REG_GAIN 0x00 /* Gain lower 8 bits (rest in vref) */ #define REG_BLUE 0x01 /* blue gain */ #define REG_RED 0x02 /* red gain */ #define REG_VREF 0x03 /* Pieces of GAIN, VSTART, VSTOP */ #define REG_COM1 0x04 /* Control 1 */ #define COM1_CCIR656 0x40 /* CCIR656 enable */ #define REG_BAVE 0x05 /* U/B Average level */ #define REG_GbAVE 0x06 /* Y/Gb Average level */ #define REG_AECHH 0x07 /* AEC MS 5 bits */ #define REG_RAVE 0x08 /* V/R Average level */ #define REG_COM2 0x09 /* Control 2 */ #define COM2_SSLEEP 0x10 /* Soft sleep mode */ #define REG_PID 0x0a /* Product ID MSB */ #define REG_VER 0x0b /* Product ID LSB */ #define REG_COM3 0x0c /* Control 3 */ #define COM3_SWAP 0x40 /* Byte swap */ #define COM3_SCALEEN 0x08 /* Enable scaling */ #define COM3_DCWEN 0x04 /* Enable downsamp/crop/window */ #define REG_COM4 0x0d /* Control 4 */ #define REG_COM5 0x0e /* All "reserved" */ #define REG_COM6 0x0f /* Control 6 */ #define REG_AECH 0x10 /* More bits of AEC value */ #define REG_CLKRC 0x11 /* Clocl control */ #define CLK_EXT 0x40 /* Use external clock directly */ #define CLK_SCALE 0x3f /* Mask for internal clock scale */ #define REG_COM7 0x12 /* Control 7 */ #define COM7_RESET 0x80 /* Register reset */ #define COM7_FMT_MASK 0x38 #define COM7_FMT_VGA 0x00 #define COM7_FMT_CIF 0x20 /* CIF format */ #define COM7_FMT_QVGA 0x10 /* QVGA format */ #define COM7_FMT_QCIF 0x08 /* QCIF format */ #define COM7_RGB 0x04 /* bits 0 and 2 - RGB format */ #define COM7_YUV 0x00 /* YUV */ #define COM7_BAYER 0x01 /* Bayer format */ #define COM7_PBAYER 0x05 /* "Processed bayer" */ #define REG_COM8 0x13 /* Control 8 */ #define COM8_FASTAEC 0x80 /* Enable fast AGC/AEC */ #define COM8_AECSTEP 0x40 /* Unlimited AEC step size */ #define COM8_BFILT 0x20 /* Band filter enable */ #define COM8_AGC 0x04 /* Auto gain enable */ #define COM8_AWB 0x02 /* White balance enable */ #define COM8_AEC 0x01 /* Auto exposure enable */ #define REG_COM9 0x14 /* Control 9- gain ceiling */ #define REG_COM10 0x15 /* Control 10 */ #define COM10_HSYNC 0x40 /* HSYNC instead of HREF */ #define COM10_PCLK_HB 0x20 /* Suppress PCLK on horiz blank */ #define COM10_HREF_REV 0x08 /* Reverse HREF */ #define COM10_VS_LEAD 0x04 /* VSYNC on clock leading edge */ #define COM10_VS_NEG 0x02 /* VSYNC negative */ #define COM10_HS_NEG 0x01 /* HSYNC negative */ #define REG_HSTART 0x17 /* Horiz start high bits */ #define REG_HSTOP 0x18 /* Horiz stop high bits */ #define REG_VSTART 0x19 /* Vert start high bits */ #define REG_VSTOP 0x1a /* Vert stop high bits */ #define REG_PSHFT 0x1b /* Pixel delay after HREF */ #define REG_MIDH 0x1c /* Manuf. ID high */ #define REG_MIDL 0x1d /* Manuf. ID low */ #define REG_MVFP 0x1e /* Mirror / vflip */ #define MVFP_MIRROR 0x20 /* Mirror image */ #define MVFP_FLIP 0x10 /* Vertical flip */ #define REG_AEW 0x24 /* AGC upper limit */ #define REG_AEB 0x25 /* AGC lower limit */ #define REG_VPT 0x26 /* AGC/AEC fast mode op region */ #define REG_HSYST 0x30 /* HSYNC rising edge delay */ #define REG_HSYEN 0x31 /* HSYNC falling edge delay */ #define REG_HREF 0x32 /* HREF pieces */ #define REG_TSLB 0x3a /* lots of stuff */ #define TSLB_YLAST 0x04 /* UYVY or VYUY - see com13 */ #define REG_COM11 0x3b /* Control 11 */ #define COM11_NIGHT 0x80 /* NIght mode enable */ #define COM11_NMFR 0x60 /* Two bit NM frame rate */ #define COM11_HZAUTO 0x10 /* Auto detect 50/60 Hz */ #define COM11_50HZ 0x08 /* Manual 50Hz select */ #define COM11_EXP 0x02 #define REG_COM12 0x3c /* Control 12 */ #define COM12_HREF 0x80 /* HREF always */ #define REG_COM13 0x3d /* Control 13 */ #define COM13_GAMMA 0x80 /* Gamma enable */ #define COM13_UVSAT 0x40 /* UV saturation auto adjustment */ #define COM13_UVSWAP 0x01 /* V before U - w/TSLB */ #define REG_COM14 0x3e /* Control 14 */ #define COM14_DCWEN 0x10 /* DCW/PCLK-scale enable */ #define REG_EDGE 0x3f /* Edge enhancement factor */ #define REG_COM15 0x40 /* Control 15 */ #define COM15_R10F0 0x00 /* Data range 10 to F0 */ #define COM15_R01FE 0x80 /* 01 to FE */ #define COM15_R00FF 0xc0 /* 00 to FF */ #define COM15_RGB565 0x10 /* RGB565 output */ #define COM15_RGB555 0x30 /* RGB555 output */ #define REG_COM16 0x41 /* Control 16 */ #define COM16_AWBGAIN 0x08 /* AWB gain enable */ #define REG_COM17 0x42 /* Control 17 */ #define COM17_AECWIN 0xc0 /* AEC window - must match COM4 */ #define COM17_CBAR 0x08 /* DSP Color bar */ #define CMATRIX_LEN 6 #define REG_BRIGHT 0x55 /* Brightness */ #define REG_REG76 0x76 /* OV's name */ #define R76_BLKPCOR 0x80 /* Black pixel correction enable */ #define R76_WHTPCOR 0x40 /* White pixel correction enable */ #define REG_RGB444 0x8c /* RGB 444 control */ #define R444_ENABLE 0x02 /* Turn on RGB444, overrides 5x5 */ #define R444_RGBX 0x01 /* Empty nibble at end */ #define REG_HAECC1 0x9f /* Hist AEC/AGC control 1 */ #define REG_HAECC2 0xa0 /* Hist AEC/AGC control 2 */ #define REG_BD50MAX 0xa5 /* 50hz banding step limit */ #define REG_HAECC3 0xa6 /* Hist AEC/AGC control 3 */ #define REG_HAECC4 0xa7 /* Hist AEC/AGC control 4 */ #define REG_HAECC5 0xa8 /* Hist AEC/AGC control 5 */ #define REG_HAECC6 0xa9 /* Hist AEC/AGC control 6 */ #define REG_HAECC7 0xaa /* Hist AEC/AGC control 7 */ #define REG_BD60MAX 0xab /* 60hz banding step limit */ #define MTX1 0x4f /* Matrix Coefficient 1 */ #define MTX2 0x50 /* Matrix Coefficient 2 */ #define MTX3 0x51 /* Matrix Coefficient 3 */ #define MTX4 0x52 /* Matrix Coefficient 4 */ #define MTX5 0x53 /* Matrix Coefficient 5 */ #define MTX6 0x54 /* Matrix Coefficient 6 */ #define REG_CONTRAS 0x56 /* Contrast control */ #define MTXS 0x58 /* Matrix Coefficient Sign */ #define AWBC7 0x59 /* AWB Control 7 */ #define AWBC8 0x5a /* AWB Control 8 */ #define AWBC9 0x5b /* AWB Control 9 */ #define AWBC10 0x5c /* AWB Control 10 */ #define AWBC11 0x5d /* AWB Control 11 */ #define AWBC12 0x5e /* AWB Control 12 */ #define REG_GFI 0x69 /* Fix gain control */ #define GGAIN 0x6a /* G Channel AWB Gain */ #define DBLV 0x6b #define AWBCTR3 0x6c /* AWB Control 3 */ #define AWBCTR2 0x6d /* AWB Control 2 */ #define AWBCTR1 0x6e /* AWB Control 1 */ #define AWBCTR0 0x6f /* AWB Control 0 */ struct regval_list{ uint8_t reg_num; uint16_t value; }; const struct regval_list qvga_ov7670[] PROGMEM = { { REG_COM14, 0x19 }, { 0x72, 0x11 }, { 0x73, 0xf1 }, { REG_HSTART, 0x16 }, { REG_HSTOP, 0x04 }, { REG_HREF, 0xa4 }, { REG_VSTART, 0x02 }, { REG_VSTOP, 0x7a }, { REG_VREF, 0x0a }, { 0xff, 0xff }, /* END MARKER */ }; const struct regval_list yuv422_ov7670[] PROGMEM = { { REG_COM7, 0x0 }, /* Selects YUV mode */ { REG_RGB444, 0 }, /* No RGB444 please */ { REG_COM1, 0 }, { REG_COM15, COM15_R00FF }, { REG_COM9, 0x6A }, /* 128x gain ceiling; 0x8 is reserved bit */ { 0x4f, 0x80 }, /* "matrix coefficient 1" */ { 0x50, 0x80 }, /* "matrix coefficient 2" */ { 0x51, 0 }, /* vb */ { 0x52, 0x22 }, /* "matrix coefficient 4" */ { 0x53, 0x5e }, /* "matrix coefficient 5" */ { 0x54, 0x80 }, /* "matrix coefficient 6" */ { REG_COM13, COM13_UVSAT }, { 0xff, 0xff }, /* END MARKER */ }; const struct regval_list ov7670_default_regs[] PROGMEM = {//from the linux driver { REG_COM7, COM7_RESET }, { REG_TSLB, 0x04 }, /* OV */ { REG_COM7, 0 }, /* VGA */ /* * Set the hardware window. These values from OV don't entirely * make sense - hstop is less than hstart. But they work... */ { REG_HSTART, 0x13 }, { REG_HSTOP, 0x01 }, { REG_HREF, 0xb6 }, { REG_VSTART, 0x02 }, { REG_VSTOP, 0x7a }, { REG_VREF, 0x0a }, { REG_COM3, 0 }, { REG_COM14, 0 }, /* Mystery scaling numbers */ { 0x70, 0x3a }, { 0x71, 0x35 }, { 0x72, 0x11 }, { 0x73, 0xf0 }, { 0xa2,/* 0x02 changed to 1*/1 }, { REG_COM10, 0x0 }, /* Gamma curve values */ { 0x7a, 0x20 }, { 0x7b, 0x10 }, { 0x7c, 0x1e }, { 0x7d, 0x35 }, { 0x7e, 0x5a }, { 0x7f, 0x69 }, { 0x80, 0x76 }, { 0x81, 0x80 }, { 0x82, 0x88 }, { 0x83, 0x8f }, { 0x84, 0x96 }, { 0x85, 0xa3 }, { 0x86, 0xaf }, { 0x87, 0xc4 }, { 0x88, 0xd7 }, { 0x89, 0xe8 }, /* AGC and AEC parameters. Note we start by disabling those features, then turn them only after tweaking the values. */ { REG_COM8, COM8_FASTAEC | COM8_AECSTEP }, { REG_GAIN, 0 }, { REG_AECH, 0 }, { REG_COM4, 0x40 }, /* magic reserved bit */ { REG_COM9, 0x18 }, /* 4x gain + magic rsvd bit */ { REG_BD50MAX, 0x05 }, { REG_BD60MAX, 0x07 }, { REG_AEW, 0x95 }, { REG_AEB, 0x33 }, { REG_VPT, 0xe3 }, { REG_HAECC1, 0x78 }, { REG_HAECC2, 0x68 }, { 0xa1, 0x03 }, /* magic */ { REG_HAECC3, 0xd8 }, { REG_HAECC4, 0xd8 }, { REG_HAECC5, 0xf0 }, { REG_HAECC6, 0x90 }, { REG_HAECC7, 0x94 }, { REG_COM8, COM8_FASTAEC | COM8_AECSTEP | COM8_AGC | COM8_AEC }, { 0x30, 0 }, { 0x31, 0 },//disable some delays /* Almost all of these are magic "reserved" values. */ { REG_COM5, 0x61 }, { REG_COM6, 0x4b }, { 0x16, 0x02 }, { REG_MVFP, 0x07 }, { 0x21, 0x02 }, { 0x22, 0x91 }, { 0x29, 0x07 }, { 0x33, 0x0b }, { 0x35, 0x0b }, { 0x37, 0x1d }, { 0x38, 0x71 }, { 0x39, 0x2a }, { REG_COM12, 0x78 }, { 0x4d, 0x40 }, { 0x4e, 0x20 }, { REG_GFIX, 0 }, /*{0x6b, 0x4a},*/{ 0x74, 0x10 }, { 0x8d, 0x4f }, { 0x8e, 0 }, { 0x8f, 0 }, { 0x90, 0 }, { 0x91, 0 }, { 0x96, 0 }, { 0x9a, 0 }, { 0xb0, 0x84 }, { 0xb1, 0x0c }, { 0xb2, 0x0e }, { 0xb3, 0x82 }, { 0xb8, 0x0a }, /* More reserved magic, some of which tweaks white balance */ { 0x43, 0x0a }, { 0x44, 0xf0 }, { 0x45, 0x34 }, { 0x46, 0x58 }, { 0x47, 0x28 }, { 0x48, 0x3a }, { 0x59, 0x88 }, { 0x5a, 0x88 }, { 0x5b, 0x44 }, { 0x5c, 0x67 }, { 0x5d, 0x49 }, { 0x5e, 0x0e }, { 0x6c, 0x0a }, { 0x6d, 0x55 }, { 0x6e, 0x11 }, { 0x6f, 0x9e }, /* it was 0x9F "9e for advance AWB" */ { 0x6a, 0x40 }, { REG_BLUE, 0x40 }, { REG_RED, 0x60 }, { REG_COM8, COM8_FASTAEC | COM8_AECSTEP | COM8_AGC | COM8_AEC | COM8_AWB }, /* Matrix coefficients */ { 0x4f, 0x80 }, { 0x50, 0x80 }, { 0x51, 0 }, { 0x52, 0x22 }, { 0x53, 0x5e }, { 0x54, 0x80 }, { 0x58, 0x9e }, { REG_COM16, COM16_AWBGAIN }, { REG_EDGE, 0 }, { 0x75, 0x05 }, { REG_REG76, 0xe1 }, { 0x4c, 0 }, { 0x77, 0x01 }, { REG_COM13, /*0xc3*/0x48 }, { 0x4b, 0x09 }, { 0xc9, 0x60 }, /*{REG_COM16, 0x38},*/ { 0x56, 0x40 }, { 0x34, 0x11 }, { REG_COM11, COM11_EXP | COM11_HZAUTO }, { 0xa4, 0x82/*Was 0x88*/ }, { 0x96, 0 }, { 0x97, 0x30 }, { 0x98, 0x20 }, { 0x99, 0x30 }, { 0x9a, 0x84 }, { 0x9b, 0x29 }, { 0x9c, 0x03 }, { 0x9d, 0x4c }, { 0x9e, 0x3f }, { 0x78, 0x04 }, /* Extra-weird stuff. Some sort of multiplexor register */ { 0x79, 0x01 }, { 0xc8, 0xf0 }, { 0x79, 0x0f }, { 0xc8, 0x00 }, { 0x79, 0x10 }, { 0xc8, 0x7e }, { 0x79, 0x0a }, { 0xc8, 0x80 }, { 0x79, 0x0b }, { 0xc8, 0x01 }, { 0x79, 0x0c }, { 0xc8, 0x0f }, { 0x79, 0x0d }, { 0xc8, 0x20 }, { 0x79, 0x09 }, { 0xc8, 0x80 }, { 0x79, 0x02 }, { 0xc8, 0xc0 }, { 0x79, 0x03 }, { 0xc8, 0x40 }, { 0x79, 0x05 }, { 0xc8, 0x30 }, { 0x79, 0x26 }, { 0xff, 0xff }, /* END MARKER */ }; void error_led(void){ DDRB |= 32;//make sure led is output while (1){//wait for reset PORTB ^= 32;// toggle led _delay_ms(100); } } void twiStart(void){ TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN);//send start while (!(TWCR & (1 << TWINT)));//wait for start to be transmitted if ((TWSR & 0xF8) != TW_START) error_led(); } void twiWriteByte(uint8_t DATA, uint8_t type){ TWDR = DATA; TWCR = _BV(TWINT) | _BV(TWEN); while (!(TWCR & (1 << TWINT))) {} if ((TWSR & 0xF8) != type) error_led(); } void twiAddr(uint8_t addr, uint8_t typeTWI){ TWDR = addr;//send address TWCR = _BV(TWINT) | _BV(TWEN); /* clear interrupt to start transmission */ while ((TWCR & _BV(TWINT)) == 0); /* wait for transmission */ if ((TWSR & 0xF8) != typeTWI) error_led(); } voidwriteReg(uint8_t reg, uint8_t dat){ //send start condition twiStart(); twiAddr(camAddr_WR, TW_MT_SLA_ACK); twiWriteByte(reg, TW_MT_DATA_ACK); twiWriteByte(dat, TW_MT_DATA_ACK); TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);//send stop _delay_ms(1); } static uint8_t twiRd(uint8_t nack){ if (nack){ TWCR = _BV(TWINT) | _BV(TWEN); while ((TWCR & _BV(TWINT)) == 0); /* wait for transmission */ if ((TWSR & 0xF8) != TW_MR_DATA_NACK) error_led(); return TWDR; } else{ TWCR = _BV(TWINT) | _BV(TWEN) | _BV(TWEA); while ((TWCR & _BV(TWINT)) == 0); /* wait for transmission */ if ((TWSR & 0xF8) != TW_MR_DATA_ACK) error_led(); return TWDR; } } uint8_t rdReg(uint8_t reg){ uint8_t dat; twiStart(); twiAddr(camAddr_WR, TW_MT_SLA_ACK); twiWriteByte(reg, TW_MT_DATA_ACK); TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);//send stop _delay_ms(1); twiStart(); twiAddr(camAddr_RD, TW_MR_SLA_ACK); dat = twiRd(1); TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);//send stop _delay_ms(1); return dat; } void wrSensorRegs8_8(const struct regval_list reglist[]){ uint8_t reg_addr, reg_val; const struct regval_list *next = reglist; while ((reg_addr != 0xff) | (reg_val != 0xff)){ reg_addr = pgm_read_byte(&next->reg_num); reg_val = pgm_read_byte(&next->value); writeReg(reg_addr, reg_val); next++; } } void setColor(void){ wrSensorRegs8_8(yuv422_ov7670); // wrSensorRegs8_8(qvga_ov7670); } void setResolution(void){ writeReg(REG_COM3, 4); // REG_COM3 enable scaling wrSensorRegs8_8(qvga_ov7670); } void camInit(void){ writeReg(0x12, 0x80); _delay_ms(100); wrSensorRegs8_8(ov7670_default_regs); writeReg(REG_COM10, 32);//PCLK does not toggle on HBLANK. } void arduinoUnoInut(void) { cli();//disable interrupts /* Setup the 8mhz PWM clock * This will be on pin 11*/ DDRB |= (1 << 3);//pin 11 ASSR &= ~(_BV(EXCLK) | _BV(AS2)); TCCR2A = (1 << COM2A0) | (1 << WGM21) | (1 << WGM20); TCCR2B = (1 << WGM22) | (1 << CS20); OCR2A = 0;//(F_CPU)/(2*(X+1)) DDRC &= ~15;//low d0-d3 camera DDRD &= ~252;//d7-d4 and interrupt pins _delay_ms(3000); //set up twi for 100khz TWSR &= ~3;//disable prescaler for TWI TWBR = 72;//set to 100khz //enable serial UBRR0H = 0; UBRR0L = 1;//0 = 2M baud rate. 1 = 1M baud. 3 = 0.5M. 7 = 250k 207 is 9600 baud rate. UCSR0A |= 2;//double speed aysnc UCSR0B = (1 << RXEN0) | (1 << TXEN0);//Enable receiver and transmitter UCSR0C = 6;//async 1 stop bit 8bit char no parity bits } void StringPgm(const char * str){ do{ while (!(UCSR0A & (1 << UDRE0)));//wait for byte to transmit UDR0 = pgm_read_byte_near(str); while (!(UCSR0A & (1 << UDRE0)));//wait for byte to transmit } while (pgm_read_byte_near(++str)); } static void captureImg(uint16_t wg, uint16_t hg){ uint16_t y, x; StringPgm(PSTR("*RDY*")); while (!(PIND & 8));//wait for high while ((PIND & 8));//wait for low y = hg; while (y--){ x = wg; //while (!(PIND & 256));//wait for high while (x--){ while ((PIND & 4));//wait for low UDR0 = (PINC & 15) | (PIND & 240); while (!(UCSR0A & (1 << UDRE0)));//wait for byte to transmit while (!(PIND & 4));//wait for high while ((PIND & 4));//wait for low while (!(PIND & 4));//wait for high } // while ((PIND & 256));//wait for low } _delay_ms(100); } void setup(){ arduinoUnoInut(); camInit(); setResolution(); setColor(); writeReg(0x11, 10); //Earlier it had the value:writeReg(0x11, 12); New version works better for me :) !!!! } void loop(){ captureImg(320, 240); } Video microcontroller-projects/arduino-obstacle-avoding-robot

Obstacle Avoiding Robot using Arduino and Ultrasonic Sensor

is an intelligent device that can automatically sense the obstacle in front of it and avoid them by turning itself in another direction. This design allows the robot to navigate in an unknown environment by avoiding collisions, which is a primary requirement for any autonomous mobile robot. The application of the Obstacle Avoiding robot is not limited and it is used in most of the military organizations now which helps carry out many risky jobs that cannot be done by any soldiers. Here an Ultrasonic sensor is used to sense the obstacles in the path by calculating the distance between the robot and obstacle. If robot finds any obstacle it changes the direction and continue moving.

How to build obstacle avoiding robot using Ultrasonic Sensor

is used. To use this sensor, similar approach will be followed explained above. So, the Trig pin of HC-SR04 is made high for at least 10 us. A sonic beam is transmitted with 8 pulses of 40KHz each. The signal then hits the surface and return back and captured by the receiver Echo pin of HC-SR04. The Echo pin had already made high at the time sending high. The time taken by beam to return back is saved in variable and converted to distance using appropriate calculations like below Distance= (Time x Speed of Sound in Air (343 m/s))/2 The components for this obstacle avoiding robot can be found easily. In order to make chassis, any toy chassis can be used or can be custom made.

Components Required

Arduino NANO or Uno (any version) HC-SR04 Ultrasonic Sensor LM298N Motor Driver Module 5V DC Motors Battery Wheels Chassis Jumper Wires

Circuit Diagram

with the same circuit (follow the same pinout) and code. by assembling the circuit on top of a robotic chassis as shown below.

Obstacle Avoiding Robot using Arduino - Code

The complete program with a demonstration video is given at the end of this project. The program will include setting up HC-SR04 module and outputting the signals to Motor Pins to move motor direction accordingly. No libraries will be used in this project. in the program. In this project the trig pin is connected to GPIO9 and echo pin is connected to GPIO10 of Arduino NANO. int trigPin = 9; // trig pin of HC-SR04 int echoPin = 10; // Echo pin of HC-SR04 The LM298N has 4 data input pins used to control the direction of motor connected to it. int revleft4 = 4; //REVerse motion of Left motor int fwdleft5 = 5; //ForWarD motion of Left motor int revright6 = 6; //REVerse motion of Right motor int fwdright7 = 7; //ForWarD motion of Right motor The four Motor pins and Trig pin is set as OUTPUT and Echo Pin is set as Input. pinMode(revleft4, OUTPUT); // set Motor pins as output pinMode(fwdleft5, OUTPUT); pinMode(revright6, OUTPUT); pinMode(fwdright7, OUTPUT); pinMode(trigPin, OUTPUT); // set trig pin as output pinMode(echoPin, INPUT); //set echo pin as input to capture reflected waves , follow the link. digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); // send waves for 10 us delayMicroseconds(10); duration = pulseIn(echoPin, HIGH); // receive reflected waves distance = duration / 58.2; // convert to distance delay(10); If the distance is greater than the defined distance means there is not obstacle in its path and it will moving in forward direction. if (distance > 19) { digitalWrite(fwdright7, HIGH); // move forward digitalWrite(revright6, LOW); digitalWrite(fwdleft5, HIGH); digitalWrite(revleft4, LOW); } if (distance < 18) { digitalWrite(fwdright7, LOW); //Stop digitalWrite(revright6, LOW); digitalWrite(fwdleft5, LOW); digitalWrite(revleft4, LOW); delay(500); digitalWrite(fwdright7, LOW); //movebackword digitalWrite(revright6, HIGH); digitalWrite(fwdleft5, LOW); digitalWrite(revleft4, HIGH); delay(500); digitalWrite(fwdright7, LOW); //Stop digitalWrite(revright6, LOW); digitalWrite(fwdleft5, LOW); digitalWrite(revleft4, LOW); delay(100); digitalWrite(fwdright7, HIGH); digitalWrite(revright6, LOW); digitalWrite(revleft4, LOW); digitalWrite(fwdleft5, LOW); delay(500); } Code /* Obstacle Avoiding Robot Using Ultrasonic Sensor and Arduino NANO * Circuit Digest(www.circuitdigest.com) */ int trigPin = 9; // trig pin of HC-SR04 int echoPin = 10; // Echo pin of HC-SR04 int revleft4 = 4; //REVerse motion of Left motor int fwdleft5 = 5; //ForWarD motion of Left motor int revright6 = 6; //REVerse motion of Right motor int fwdright7 = 7; //ForWarD motion of Right motor long duration, distance; void setup() { delay(random(500,2000)); // delay for random time Serial.begin(9600); pinMode(revleft4, OUTPUT); // set Motor pins as output pinMode(fwdleft5, OUTPUT); pinMode(revright6, OUTPUT); pinMode(fwdright7, OUTPUT); pinMode(trigPin, OUTPUT); // set trig pin as output pinMode(echoPin, INPUT); //set echo pin as input to capture reflected waves } void loop() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); // send waves for 10 us delayMicroseconds(10); duration = pulseIn(echoPin, HIGH); // receive reflected waves distance = duration / 58.2; // convert to distance delay(10); // If you dont get proper movements of your robot then alter the pin numbers if (distance > 19) { digitalWrite(fwdright7, HIGH); // move forward digitalWrite(revright6, LOW); digitalWrite(fwdleft5, HIGH); digitalWrite(revleft4, LOW); } if (distance < 18) { digitalWrite(fwdright7, LOW); //Stop digitalWrite(revright6, LOW); digitalWrite(fwdleft5, LOW); digitalWrite(revleft4, LOW); delay(500); digitalWrite(fwdright7, LOW); //movebackword digitalWrite(revright6, HIGH); digitalWrite(fwdleft5, LOW); digitalWrite(revleft4, HIGH); delay(500); digitalWrite(fwdright7, LOW); //Stop digitalWrite(revright6, LOW); digitalWrite(fwdleft5, LOW); digitalWrite(revleft4, LOW); delay(100); digitalWrite(fwdright7, HIGH); digitalWrite(revright6, LOW); digitalWrite(revleft4, LOW); digitalWrite(fwdleft5, LOW); delay(500); } } Video microcontroller-projects/google-assistant-based-home-automation-using-diy-arduino-wifi-shield

Google Assistant Based Voice Controlled Home Automation using DIY Arduino Wi-Fi Shield

Humans and machines interact and communicate with one other in many possible ways, computers have monitor, keyboard and mouse, while smart phones have touch screen, gesture control etc and even AR and VR is on its way. But the most basic tool used by humans to communicate is vocal communication, we have the capability to listen and speak and if the machines could somehow do the same then communicating with them could not get any simpler. It is not that we are super lazy to toggle loads with switches, but at the end of the day it is the sheer joy of getting things done just with our voice commands. So let’s get started.

Google Assistant controlled Home Automation Project Overview

to keep the cost down and not to over engineer anything. which require internet connection. comes in. Basically the voice command given to Google assistant changes the value of a field in our ThingSpeak channel accordingly. While the ESP8266 periodically checks the value of this field using API calls and sends this value to Arduino using serial communication. The Arduino then performs required action like toggling a relay based on the value received.

Arduino Uno Wi-Fi Shield using ESP8266

before proceeding any further. Do remember that the ESP8266 when purchased comes with a default firmware which is capable of communicating with AT commands. But if the module has been directly programmed with Arduino, then the default firmware will be erased and it has to be flashed again if AT commands are to be used. Details on how to use flash will be explained later. The circuit diagram for the Wi-Fi shield is shown below as a 3.3V voltage regulator. This 3.3V is used to power the ESP8266 module because the 3.3V from Arduino UNO will not be able to source enough current for the ESP module. The LM317 input pin can be powered by the DC input barrel jack of the Vin pin of the Arduino UNO board. The GPIO0 pin of the ESP module is connected to a jumper pin which can be toggled to connect the pin to ground. This allows the user to set the ESP module to work either in AT command mode or Programming mode (Arduino IDE). Both the GPIO0 and GPIO2 is connected to a external connector so that these GPIO pins can also be utilized. is also provided, so that it can be mounted directly on top of the shield. The LCD is powered by the 5V pin of the Arduino.

Fabricating PCB for ESP8266 Wi-Fi Module using EasyEDA

is getting the footprint right. If the dimensions go wrong then the shield will not fit properly into the Arduino UNO board. But, lucky enough, EasyEDA provides footprint for almost all components in the market. This is because of its vast user community where users create footprint and makes it available for public to use it their projects. where they have a large stock of electronic components and users can order their required components along with the PCB order. While designing your circuits and PCBs, you can also make your circuit and PCB designs public so that other users can copy or edit them and can take benefit from your work, we have also made our whole Circuit and PCB layouts public for thiscircuit,check the below link: (Top, Bottom, Topsilk, bottomsilk etc) of the PCB by selecting the layer form the ‘LayersᾠWindow. Apart from this they also provide a 3D model view of the PCB on how it would appear after fabrication. The snapshot of the top layer and bottom layer of the Wi-Fi shield would appear something like this

Calculating and Ordering PCB Samples online using EasyEDA

page, then download the Gerber file from there oryou can click onOrder at JLCPCBas shown in below image.This will redirect you to JLCPCB.com, whereyou can select the number of PCBs you want to order, how manycopper layers you need, the PCB thickness, copper weight, and even the PCB color, like the snapshot shown below: After clicking on order at JLCPCB button, it will take you to JLCPCB website where you can order the PCB inverylow rate which is $2. Theirbuild time is also verylesswhichis 48 hours with DHL delivery of 3-5 days,basicallyyou will get your PCBs within a week of ordering. with date and time. You can check it by going on Account page and click on "Production Progress" link under the PCB like, shown in below image. After few days of orderingPCB’sI got thePCB samples in nice packagingas shown in below pictures. looks like this below

Arduino Wi-Fi Shield Programming mode and AT mode

When the ESP8266 is programmed directly using the Arduino IDE or when it is to be flashed, the GPIO 0 pin should be connected to ground and Reset pin has to be momentarily connected to ground every time before the uploading process. Similarly when the ESP8266 is working with AT commands the GPIO pin should be left free and again the Reset pin should be momentarily connected to ground to reset it. To make things easier the Wi-Fi shield that we designed has a toggle pin which can shift between Programming mode and AT command mode as shown in the below images. Also the Reset pin can be connected to ground by simply pressing the reset button (red color) everytime before uploading the code. from the given link. Then open the software and browse for the bin file using Bin button, then type in the right COM port and leave the address to be 0x00000 as default. Finally click on the Download button to flash the ESP8266 module. The software is also shown in the image below, but remember that you have to flash it only if default firmware on ESP8266 is overwritten.

Setting up the ThingSpeak channel for Google Assistant

You can pick any name for your channel and give it a description. Since we are toggling only one light I have used only one field and named it as Light but again you can use as many as you want. My channel settings looks something like this, make note of the Channel ID which is 683739 in my case and field number which is 1 in my case, we will need it in future. , here you will be provided with two API keys one for Write function and the other for read function. You can read or write values to the filed only using these keys respectively. Every key will be unique, mine is shown below yours will be different for sure. Never share your keys as it can give permission to write or read to your channel. They keys shown below were destroyed after usage. Now let us look at the API GET calls using which we can write and read data to the field that we just created. api.thingspeak.com/channels/683739/fields/1/last.json?api_key=7EK8DHQDV3M0EJ6S&results=2 api.thingspeak.com/update?api_key=UEI3D4YTWX9OQQ4B&field1=7 These are my API you have to replace the key value with your keys and also change the channel ID according to your ThingSpeak channel. If you have selected the first field as shown in the image then the field value need not be changed. we are writing 7 (appended at the last) to the channel. You can load this on your browser and check if the value is being reflected on your ThingSpeak account. Similarly the read from Thing Field API call when loaded in browser should give you the value that you have sent to field previously, in this case 7.

Setting up IFTTT Applets

and the following image will also help you.

Programming the Arduino for Google Assistant Home Automation

Both the IFTTT and the ThingSpeak account should be set by now. So, based on the command given to our Google assistant the IFTTT will send a value (0 or 1) to our ThingSpeak account. Now, on our Arduino side we have to write a program to check if the value of field is 0 or 1. If 0 we have to turn off the light and if 1 we have to turn it on. , I am breaking the program into meaningful snippets and explaining them below. We begin by defining the pins to which the ESP and the LCD is connected to Arduino. You can refer the circuit diagram to verify the same. SoftwareSerial ESP(12,13); //ESP is connected to 12 and 13 pin of Arduino const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7); Then we have to feed in few critical parameters, like the name of the Wi-Fi to which the ESP should connect to its password and then finally the API call request that we obtained from our ThingSpeak. Be sure that you have changed these credentials according to your applications. Verify the API key and load it in browser to make sure. String WiFi_SSID = "Oneplus"; String WiFi_Pass = "nightfury"; String sendData = "GET /channels/683739/fields/1/last.json?api_key=7EK8DHQDV3M0EJ6S&results=2"; String output = ""; //Initialize a null string variable , we declare pin 10 as output this is where we connect our load thorough a relay. Then we display a small intro text on the LCD and initialize serial monitor using the below lines of code. pinMode(10,OUTPUT); lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print(" Arduino WiFi"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print(" Shield "); //Intro Message line 2 delay(2000); Serial.begin (9600); as shown below. After changing the baud rate we can re-initialize the software serial to work with 9600 baud rate. ESP.begin(115200); ESP.println("AT+CIOBAUD=9600"); delay(100); ESP.begin(9600); They include turning off the Echo option (ATE0) then setting the ESP to work in station mode (AT+CWMODE=1) and then connecting it to the router using (AT+CWJAP) etc. Once it is executed the ESP will remember these details and will connect to our Router as a station every time we power it on. So you can comment these lines after first time usage (optional though). ESP_talk("ATE0", 1000); //Turn off Echo ESP_talk("AT+CWMODE=1", 1000); //Set ESP as station ESP_talk("AT+CWJAP=\""+ WiFi_SSID +"\",\""+ WiFi_Pass +"\"", 5000); //Connect to WiFi delay(1000); ESP_talk("AT+CIPMUX=1",1000); delay(1000); This can be done by first starting a TCP connection to the ThingSpeak network by the following command. ESP_talk("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",80",1000); In my case it is 76. Because the below command that we will send, we have 74 characters and with that we have to add 2 for ᾯnᾠwhich gives 76. GET /channels/683739/fields/1/last.json?api_key=7EK8DHQDV3M0EJ6S&results=2 These commands are sent with a delay of 100ms for stability but it is not mandatory. The program for the same is shown below. ESP_talk("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",80",1000); //AT+CIPSTART="TCP","api.thingspeak.com",80 delay(100); ESP_talk("AT+CIPSEND=76",1000); delay(100); ESP_talk(sendData,1000); delay(100); The above code will fetch the field data as a string value from the ThingSpeak website and store it in the variable “outputᾠwhich will look something like this. +IPD,64:{"created_at":"2019-01-22T12:13:32Z","entry_id":15,"field1":"0"}CLOSED The location of the value is 11 steps behind from the last value. So the code looks like int light_value = int (output.charAt(output.length()-11))-48; Then toggle the light on if it is a 1 and turn it off if it is a 0. The LCD is also made to display the result, based on the field value. lcd.clear(); lcd.print("Listning...."); //Intro Message line 1 lcd.setCursor(0, 1); if (light_value == 0) //light should be off { lcd.print("Light is OFF :-(" ); digitalWrite(10,LOW); } if (light_value == 1) //light should be off { lcd.print(":-) Light is ON"); digitalWrite(10,HIGH); } being used extensively throughout the program. This function basically has two parameters one is the actual command which is sent to the ESP module and other is the time out value within which the ESP should respond back for the sent command. The response from the ESP is then stored in the variable output. This comes in very handy when debugging the ESP module. The function definition is shown below. void ESP_talk(String AT_cmd, const int timeout) { Serial.print("Sent: "); Serial.print(AT_cmd); ESP.println(AT_cmd); //print to ESP through software serial Serial.println("");//Move to next line long int time = millis(); output=""; //clear the string while ( (time + timeout) > millis()) { while (ESP.available()) { char i = ESP.read(); // read one char output += i; //Combine char to string } } Serial.print("Received: "); Serial.print(output); }

Using Google Assistant to Toggle Lights

from anywhere using Google Assistant. As explained the above program is used to toggle the pin 10. So you can add a relay to the pin 10 and connect any AC load within relay rating as required. My setup with the Relay and the Arduino board with Wi-Fi shield is shown below. I have used a small reading lamp as a demo load but you can use anything of your choice. Power up the set-up and speak out the command to your Google assistant and you should see the Light getting controlled accordingly. You can also see the ThingSpeak channel values getting changed as you issue command to your Google assistant. For debugging you can open your Serial monitor to check if everything is working fine. If yes your serial monitor should display something like this. for other technical questions. Code /*Home automation using Google assistant and thingspeak using Arduino Shield *Shield details: https://easyeda.com/CircuitDigest/Arduino-WiFi-shield *Author: B.Aswinth Raj *Website: www.circuitdigest.com *Dated: 21-1-2019 */ //Use the new flah tool ad bin file to get the latest firmware and then use AT+CIOBAUD=9600 to change the baud, // AT+UART_DEF=9600,8,1,0,0 (for old firmware) #include <LiquidCrystal.h> //Librarey for LCD display #include <SoftwareSerial.h> //Librarey for serial connection with ESP SoftwareSerial ESP(12,13); //ESP is connected to 12 and 13 pin of Arduino const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7); String WiFi_SSID = "Oneplus"; String WiFi_Pass = "nightfury"; String sendData = "GET /channels/683739/fields/1/last.json?api_key=7EK8DHQDV3M0EJ6S&results=2"; String output = ""; //Initialize a null string variable void setup() { pinMode(10,OUTPUT); lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print(" Arduino WiFi"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print(" Shield "); //Intro Message line 2 delay(2000); Serial.begin (9600); ESP.begin(115200); ESP.println("AT+CIOBAUD=9600"); delay(100); ESP.begin(9600); ESP_talk("ATE0", 1000); //Turn off Echo /*ESP_talk("AT+CWMODE=1", 1000); //Set ESP as station ESP_talk("AT+CWJAP=\""+ WiFi_SSID +"\",\""+ WiFi_Pass +"\"", 5000); //Connect to WiFi delay(1000); ESP_talk("AT+CIPMUX=1",1000); delay(1000); */ } void loop() { ESP_talk("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",80",1000); //AT+CIPSTART="TCP","api.thingspeak.com",80 delay(100); ESP_talk("AT+CIPSEND=76",1000); delay(100); ESP_talk(sendData,1000); delay(100); int light_value = int (output.charAt(output.length()-11))-48; //read the required value form string and convert it to int Serial.println(light_value); lcd.clear(); lcd.print("Listning...."); //Intro Message line 1 lcd.setCursor(0, 1); if (light_value == 0) //light should be off { lcd.print("Light is OFF :-(" ); digitalWrite(10,LOW); } if (light_value == 1) //light should be off { lcd.print(":-) Light is ON"); digitalWrite(10,HIGH); } delay(500); } void ESP_talk(String AT_cmd, const int timeout) { Serial.print("Sent: "); Serial.print(AT_cmd); ESP.println(AT_cmd); //print to ESP through software serial Serial.println("");//Move to next line long int time = millis(); output=""; //clear the string while ( (time + timeout) > millis()) { while (ESP.available()) { char i = ESP.read(); // read one char output += i; //Combine char to string } } Serial.print("Received: "); Serial.print(output); } Video microcontroller-projects/two-step-lithium-battery-charger-circuit-with-cc-cv-mode

7.4V Two Step Lithium Battery Charger Circuit - CC and CV mode

or Lithium Polymer Batteries. While these Batteries have a very good charge density they are chemically unstable under harsh conditions hence care should be taken while charging them and using them. Also, what’s more fun than building your own gadget and learning in it’s process.

CC and CV mode for Battery Charger:

By combining these two modes we will be able to charge the battery faster than usual. The first mode to get into operation will be the CC mode. Here the amount of charging current that should enter the battery is fixed. To maintain this current the voltage will be varied accordingly. Once the CC mode is completed the CV mode will kick in. Here the Voltage will be kept fixed and the current will be allowed to vary as per the charging requirement of the battery. Hence these values are already fixed for our battery pack. So initially when the battery is connected for charging the charger should get into CC mode and push in 800mA into the battery by varying the charging voltage according. This will charge the battery and the battery voltage will start to increase slowly. Since we are pushing a heavy current into the battery with higher voltage values we cannot leave it in CC till the battery gets fully charged. We have to shift the charger from CC mode to CV mode when the battery voltage has reached a considerable value. Our battery pack here should be 8.4V when fully charged so we can shift it from CC mode to CV mode at 8.2V. in our case. The battery will drain a considerably less current in CV mode than CC mode since the battery is almost charged in CC mode itself. Hence at a fixed 8.6V the battery will consume less current and this current will go reduce as the battery gets charged. So we have to monitor the current when it reaches a very low value say less than 50mA we assume that the battery is fully charged and disconnect the battery from the charger automatically using a relay. Enter CC mode and charge the battery with a fixed 800mA Regulated current. Monitor the battery voltage and when it reaches 8.2V shift to CV Mode. In CV mode charge the battery with a fixed 8.6V Regulated Voltage. Monitor the charging current as it gets reduced. When the current reaches 50mA disconnect the battery from charger automatically. should actually work, let’s get into the Circuit Diagram.

Circuit Diagram

can be found below. The circuit was made using EasyEDA and the PCB will also be fabricated using the same. , one to regulate Current and the other to regulate Voltage. The first relay is used to switch between CC and CV mode and the second relay is used to connect or disconnect the battery to the charger. Let’s break the circuit into segments and understand its design.

LM317 Current Regulator

The LM317 IC can act as a current regulator with the help of a single resistor. The circuit for the same is shown below For our charger we need to regulate a current of 800mA as discussed above. The formula for calculating the value of resistor for the required current is given in datasheet as Resistor (Ohms) = 1.25 / Current (Amps) In our case the value of current is 0.8A and for that we get a value of 1.56 Ohms as the resistor value. But the closest value we could use is 1.5 Ohms which is mentioned in the circuit diagram above.

LM317 Voltage Regulator

For the CV mode of lithium battey charger we have to regulate the voltage to 8.6V as discussed earlier. Again LM317 can do this with the help of just two resistors. The circuit for the same is shown below. The formula to calculate the output voltage for a LM317 Regulator is give as

Relay Arrangement to toggle between CC and CV mode

Both the Relay arrangement is shown below , this Relay is triggered by the Arduino pin labeled as “Modeᾮ By default the relay is in CC mode when it is triggered it changes from CC mode to CV mode. ; this Relay is triggered by the Arduino pin labeled as “Chargeᾮ By default the relay disconnects the battery from the charger, when triggered it connects the charger to the battery. Apart from this the two diodes D1 and D2 are used for protecting the circuit from reverse current and the 1K Resistors R4 and R5 are used to limit the current flowing through the base of the transistor.

Measuring Lithium Battery Voltage

The one used here is shown below. ᾠlabel. We can later retrieve the original value while programming the Arduino.

Measuring Charging Current

Another vital parameter to be measured is the charging current. During the CV mode the battery will be disconnected to the charger when the charging current goes below 50mA indicating charge completion. There are many methods to measure current, the most commonly used method is by using a shunt resistor. The circuit for the same is shown below R we can calculate the Resistance value and Power value of the Resistor.

Arduino and LCD

to display the charging Process to the user and control the charging by measuring the voltage, current and then triggering the Relays accordingly. The Voltage and Current can be measured by the Analog pins A0 and A1 respectively using the labels “B_Voltageᾠand “B_Currentᾮ The Relay can be triggered by toggling the GPIO pin D8 and D9 which are connected through the labels “Modeᾠand “Chargeᾮ Once the schematics are ready we can proceed with PCB fabrication.

PCB Design and Fabrication using EasyEDA

where they have a large stock of electronic components and users can order their required components along with the PCB order. While designing your circuits and PCBs, you can also make your circuit and PCB designs public so that other users can copy or edit them and can take benefit from your work, we have also made our whole Circuit and PCB layouts public for thiscircuit,check the below link: button in EasyEDA:

Calculating and Ordering Samples online

page, then download the Gerber file from there oryou can click onOrder at JLCPCBas shown in below image.This will redirect you to JLCPCB.com, whereyou can select the number of PCBs you want to order, how manycopper layers you need, the PCB thickness, copper weight, and even the PCB color, like the snapshot shown below: After clicking on order at JLCPCB button, it will take you to JLCPCB website where you can order the PCB inverylow rate which is $2. Theirbuild time is also verylesswhichis 48 hours with DHL delivery of 3-5 days,basicallyyou will get your PCBs within a week of ordering. with date and time. You check it by going on Account page and click on "Production Progress" link under the PCB like, shown in below image. After few days of orderingPCB’sI got thePCB samples in nice packagingas shown in below pictures. looks like this below

Programming the Arduino for two step Lithium Battery Charging

for this project is provided at the bottom of the page, you can upload it directly to your Arduino. Now, let’s break the program into small snippets and understand what the code actually does. As we know from our hardware the pins A0 and A2 is used to measure Voltage and current respectively and the pin D8 and D9 is used the control the Mode relay and Charge relay. The code to define the same is shown below const int rs = 2, en = 3, d4 = 4, d5 = 5, d6 = 6, d7 = 7; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7); int Charge = 9; //Pin to connect or disconnect the battery to the circuit int Mode = 8; //Pin to toggle between CC mode and CV mode int Voltage_divider = A0; //To measure battery Voltage int Shunt_resistor = A1; //To measure charging current float Charge_Voltage; float Charge_current; We also define the relay pins as output pins. Then trigger the charge relay connect the battery to the charger and by default the charger stays in CC mode. void setup() { lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print("7.4V Li+ charger"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print("-CircuitDigest "); //Intro Message line 2 lcd.clear(); pinMode (Charge, OUTPUT); pinMode (Mode, OUTPUT); digitalWrite(Charge,HIGH); //Begin Chargig Initially by connecting the battery digitalWrite(Mode,LOW); //HIGH for CV mode and LOW of CC mode, initally CC mode delay(1000); } The value 0.0095 and 1.78 is multiplied with Analog value to convert 0 to 1024 to actual voltage and current value you can use a multimeter and a clamp meter to measure the real value and then calculate the multiplier value. It is also theoretically calculate the multiplier values based on the resistors we have used but it was not as accurate as I expected it to be. //Measure voltage and current initially Charge_Voltage = analogRead(Voltage_divider) * 0.0092; //Measure Battery Voltage Charge_current = analogRead(Shunt_resistor) * 1.78; //Measure charging current loop. Inside the CC mode loop we keep the Mode pin as LOW to stay in CC mode and then keep monitoring the voltage and current. If the voltage exceeds the 8.2V threshold voltage we break the CC loop using a break statement. The status of charge voltage is also displayed on the LCD inside the CC loop. //If the battery voltage is less than 8.2V enter CC mode while(Charge_Voltage<8.2) //CC MODE Loop { digitalWrite(Mode,LOW); //Stay in CC mode //Measure Voltage and Current Charge_Voltage = analogRead(Voltage_divider) * 0.0095; //Measure Battery Voltage Charge_current = analogRead(Shunt_resistor) * 1.78; //Measure charging current //print detials on LCD lcd.print("V="); lcd.print(Charge_Voltage); lcd.setCursor(0, 1); lcd.print("In CC mode"); delay(1000); lcd.clear(); //Check if we have to exit CC mode if(Charge_Voltage>=8.2) // If yes { digitalWrite(Mode,HIGH); //Change to CV mode break; } } This applies a constant 8.6V across the battery and the charging current is allowed to vary based on battery requirement. This charging current is then monitored and when it reaches below 50mA we can terminate the charging process by disconnecting the battery from the charger. To do this we simply have to turn off the Charge relay as show in the code below //If the battery voltage is greater than 8.2V enter CV mode while (Charge_Voltage>=8.2) //CV MODE Loop { digitalWrite(Mode,HIGH); //Stay in CV mode //Measure Voltage and Current Charge_Voltage = analogRead(Voltage_divider) * 0.0092; //Measure Battery Voltage Charge_current = analogRead(Shunt_resistor) * 1.78; //Measure charging current //Display details to user in LCD lcd.print("V="); lcd.print(Charge_Voltage); lcd.print(" I="); lcd.print(Charge_current); lcd.setCursor(0, 1); lcd.print("In CV mode"); delay(1000); lcd.clear(); //Check if the battery is charged by monitoring charging current if(Charge_current<50) //If yes { digitalWrite(Charge,LOW); //Turn off charging while(1) //Keep the charger off until restart { lcd.setCursor(0, 1); lcd.print("Charge Complete."); delay(1000); lcd.clear(); } } } }

Working of 7.4V Two Step Lithium Battery Charger

and your LCD will display something like this below. and now it will display both Voltage and current as shown below. From here slowly the current consumption of the battery will go down as it gets charged. When current reaches to 50mA or less the charger assumes the battery to be fully charged and then disconnects the battery from charger using the relay and displays the following screen. After which you can disconnect the battery from the charger and use it in your applications. for other technical queries. Again the circuit is only for educational purpose so use it with responsibility since lithium batteries are not stable under harsh conditions. Code /* * 7.4V Lithium Two step Charger Code * By: Aswinth Raj * For: www.circuitdigest.com * Dated: 11-1-2019 */ #include <LiquidCrystal.h> //Librarey to use 16*2 LCD display const int rs = 2, en = 3, d4 = 4, d5 = 5, d6 = 6, d7 = 7; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7); int Charge = 9; //Pin to connect or disconnect the battery to the circuit int Mode = 8; //Pin to toggle between CC mode and CV mode int Voltage_divider = A0; //To measure battery Voltage int Shunt_resistor = A1; //To measure charging current float Charge_Voltage; float Charge_current; void setup() { lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print("7.4V Li+ charger"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print("-CircuitDigest "); //Intro Message line 2 lcd.clear(); pinMode (Charge, OUTPUT); pinMode (Mode, OUTPUT); digitalWrite(Charge,HIGH); //Begin Chargig Initially by connecting the battery digitalWrite(Mode,LOW); //HIGH for CV mode and LOW of CC mode, initally CC mode delay(1000); } void loop() { //Measure voltage and current initially Charge_Voltage = analogRead(Voltage_divider) * 0.0092; //Measure Battery Voltage Charge_current = analogRead(Shunt_resistor) * 1.78; //Measure charging current //If the battery voltage is less than 8.2V enter CC mode while(Charge_Voltage<8.2) //CC MODE Loop { digitalWrite(Mode,LOW); //Stay in CC mode //Measure Voltage and Current Charge_Voltage = analogRead(Voltage_divider) * 0.0095; //Measure Battery Voltage Charge_current = analogRead(Shunt_resistor) * 1.78; //Measure charging current //print detials on LCD lcd.print("V="); lcd.print(Charge_Voltage); lcd.setCursor(0, 1); lcd.print("In CC mode"); delay(1000); lcd.clear(); //Check if we have to exit CC mode if(Charge_Voltage>=8.2) // If yes { digitalWrite(Mode,HIGH); //Change to CV mode break; } } //If the battery voltage is greater than 8.2V enter CV mode while (Charge_Voltage>=8.2) //CV MODE Loop { digitalWrite(Mode,HIGH); //Stay in CV mode //Measure Voltage and Current Charge_Voltage = analogRead(Voltage_divider) * 0.0092; //Measure Battery Voltage Charge_current = analogRead(Shunt_resistor) * 1.78; //Measure charging current //Display details to user in LCD lcd.print("V="); lcd.print(Charge_Voltage); lcd.print(" I="); lcd.print(Charge_current); lcd.setCursor(0, 1); lcd.print("In CV mode"); delay(1000); lcd.clear(); //Check if the battery is charged by monitoring charging current if(Charge_current<50) //If yes { digitalWrite(Charge,LOW); //Turn off charging while(1) //Keep the charger off until restart { lcd.setCursor(0, 1); lcd.print("Charge Complete."); delay(1000); lcd.clear(); } } } } //**Happy Charging**// Video microcontroller-projects/arduino-lora-sx1278-interfacing-tutorial

Interfacing SX1278 (Ra-02) LoRa Module with Arduino

, which can perform very-long range transmission with low power consumption.

What is LoRa?

This LoRa technology can be used to transmit bi-directional information to long distance without consuming much power. This property can be used by remote sensors which have to transmit its data by just operating on a small battery. (will talk more on this later) and can work on battery for years. Remember that LoRa, LoRaWAN and LPWAN are three different terminologies and should not be confused with one another. We will discuss them briefly later in this article.

Understanding LoRa Technology

provided for warehouse management or field monitoring, there will hundreds of Sensors nodes deployed on the field which will monitor the vital parameters and send it to the could for processing. But these sensors should be wireless and should operate on a small battery so that it is portable. Wireless solutions like RF can send data to long distance but requires more power to do so thus cannot be battery operated, while BLE on the other hand can work with very little power but cannot send data to long distance. So this is what brings in the need for LoRa. , thus overcoming the drawback of Wi-Fi and BLE communication. But how is it possible? If that is the case why do BLE and RF still exist? Many people compare LoRa with Wi-Fi or Bluetooth, but these two do not stand anywhere near LoRa. Bluetooth is used to transfer information between two Bluetooth devices and Wi-Fi is used to transfer information between an Access Point (Router) and Station (Mobile). But LoRa technology was primarily not invented to transmit data between two LoRa modules. as shown in the image below. It is not just LoRa that can operate on LPWAN, but we also have other technologies like Narrow Band IoT (NB-IOT), Sigfox etc. which are capable of operating in the same LPWAN. Once the technology of LoRa was introduced, it needed certain set of protocols to be followed by all manufactures, so the LoRa alliance was formed which then introduced the LoRaWAN. LoRaWAN is a modified form of LPWAN which specifies the protocol on how LoRa in a physical layer should be used to send and receive data among the nodes, gateways and to the internet. That is when there is no obstacle between the Node and Gateway. Few people have even practically achieved communication between 212km Ground to Ground and even upto 702km using weather Balloon.

LoRa SX1278 with Arduino

at receiving side. I have both the Module and Chip version soldered with wires as shown below. Remember that it is mandatory to operate the LoRa module only with an antenna, else the output transmitting power will damage the Module. I am using a 433Mhz Lora module so my antennas are also rated for 433MHz, you have to select your antenna accordingly. My LoRa module along with antenna is shown below.

Transmitting Side- Connecting LoRa SX1278 with Arduino UNO

The circuit diagram to connect the Arduino UNO with LoRa is shown below as shown above. You can also use the table below to make sure the connection is done correctly
3.3V3.3V
GndGnd
En/NssD10
G0/DIO0D2
SCKD13
MISOD12
MOSID11
RSTD9
to make it portable to test the range.

Receiving Side- Connecting LoRa SX1278 with Arduino Nano

is shown below This is because the on-board regulator on Arduino Nano cannot provide enough current for the LoRa module to operate. Other than this the connections remain the same. I am also pasting a similar table below for your reference.
3.3V-
GndGnd
En/NssD10
G0/DIO0D2
SCKD13
MISOD12
MOSID11
RSTD9
that we built earlier. Also note that the LoRa modules that I used are not breadboard friendly hence I have used two small breadboard to make the connections as shown below.

Preparing the Arduino IDE for LoRa Wireless Communication

In this article we will just include the Library to our Arduino IDE and use the example sketches with slight modifications to make our LoRa modules communicate between them. and look for the library that was made by Sandeep Mistry and click on install. Wait for the installation to complete and you should see something like this in the end and then open both LoRa Receiver and LoRa Sender Program as shown below. The complete program is self explanatory. The Sender program sends a “helloᾠfor every 5 seconds with a value of counter being incremented. The receiver then receives this and prints on the Serial monitor with the RSSI value. as I told earlier, so you have to change it as shown below LoRa.begin(433E6) to know what each function in the Library means and how to change it. Once the program is ready upload the program on the respective boards after making sure the connections are correct and the antenna is connected to the LoRa module.

LoRa Wireless Communication with Arduino

Once the program is uploaded, open the Serial monitor of both the Arduino boards. The Serial monitor of Sender should show the value that is being sent while the receiver will receive it display it on its serial monitor. The screen should look something like this. For instance if I move both the devices far apart the signal strength will go down. Hope you understood the project and enjoyed building something out of it, if you have any problem in getting it to work leave your questions in the comment section and I will try my best answering them. Code #include <SPI.h> #include <LoRa.h> int counter = 0; void setup() { Serial.begin(9600); while (!Serial); Serial.println("LoRa Sender"); if (!LoRa.begin(433E6)) { Serial.println("Starting LoRa failed!"); while (1); } LoRa.setTxPower(20); } void loop() { Serial.print("Sending packet: "); Serial.println(counter); // send packet LoRa.beginPacket(); LoRa.print("hello "); LoRa.print(counter); LoRa.endPacket(); counter++; delay(5000); } #include <SPI.h> #include <LoRa.h> void setup() { Serial.begin(9600); while (!Serial); Serial.println("LoRa Receiver"); if (!LoRa.begin(433E6)) { Serial.println("Starting LoRa failed!"); while (1); } } void loop() { // try to parse packet int packetSize = LoRa.parsePacket(); if (packetSize) { // received a packet Serial.print("Received packet '"); // read packet while (LoRa.available()) { Serial.print((char)LoRa.read()); } // print RSSI of packet Serial.print("' with RSSI "); Serial.println(LoRa.packetRssi()); } } Video microcontroller-projects/rs485-serial-communication-between-arduino-uno-and-arduino-nano

RS485 Serial Communication between Arduino Uno and Arduino Nano

Choosing a communication protocol for communication between microcontrollers and peripheral devices is an important part of embedded system. It is important because the overall performance of any embedded application depends on communication means as it is related to cost reduction, faster data transfer, long distance coverage etc. .This Protocol uses an asynchronous serial communication. The main advantage of RS-485 is the long distance data transfer between two devices. And they are most commonly used in electrically noisy industrial environment. and then demonstrate it by controlling the brightness of the LED connected to a Slave Arduino from Master Arduino by sending ADC values through RS-485 Module. A 10k potentiometer is used to vary the ADC values at Master Arduino. Let’s start by understanding the working of RS-485 Serial communication.

RS-485 Serial Communication Protocol

to transfer binary data from one device to another. By using this method RS-485 supports higher data transfer rate of 30Mbps maximum. It also provides maximum data transfer distance compared to RS-232 protocol. It transfers data up to 1200 meters maximum. The main advantage of RS-485 over RS-232 is the multiple slave with single Master while RS-232 supports only single slave. It can have a maximum of 32 devices connected to RS-485 protocol. Another advantage of the RS-485 is that it is immune to the noise as they use differential signal method to transfer. RS-485 is faster compared to I2C protocol.

RS-485 in Arduino

is needed as it allows serial communication over long distance of 1200 meters and it is bidirectional. In half duplex mode it has a data transfer rate of 2. 5Mbps. requires a voltage of 5V and uses 5V logic levels so that it can be interfaced with hardware serial ports of microcontrollers like Arduino. It has following features: Operating voltage: 5V On-board MAX485 chip A low power consumption for the RS485 communication Slew-rate limited transceiver 5.08mm pitch 2P terminal Convenient RS-485 communication wiring All pins of chip have been lead to can be controlled through the microcontroller Board size: 44 x 14mm
VCC5V
ANon-inverting Receiver Input Non-Inverting Driver Output
BInverting Receiver Input Inverting Driver Output
GNDGND (0V)
R0Receiver Out (RX pin)
REReceiver Output (LOW-Enable)
DEDriver Output (HIGH-Enable)
DIDriver Input (TX pin)
Programming part is explained later in detail but first lets check the required components and circuit diagram.

Components Required

Arduino UNO or Arduino NANO (2) MAX485 TTL to RS485 Converter Module -(2) 10K Potentiometer 16x2 LCD Display LED Breadboard Connecting Wires Two Arduino Boards are used here so two RS-485 Modules are required.

Circuit Diagram

DI1 (TX)
DE RE8
R00 (RX)
VCC5V
GNDGND
ATo A of Slave RS-485
BTo B of Slave RS-485
DID1 (TX)
DE RED8
R0D0 (RX)
VCC5V
GNDGND
ATo A of Master RS-485
BTo B of Master RS-485
VSSGND
VDD+5V
V0To potentiometer centre pin for contrast control of LCD
RSD2
RWGND
ED3
D4D4
D5D5
D6D6
D7D7
A+5V
KGND
A 10K potentiometer is connected to the Analog Pin A0 of the Arduino UNO for providing Analog input and a LED is connected to pin D10 of Arduino Nano.

Programming Arduino UNO & Arduino Nano for RS485 Serial Communication

Here we are explaining important part of the code. There are two programs in this tutorial, one for Arduino UNO (Master) and other for Arduino Nano (Slave). those values to the RS-485 bus through the Hardware Serial Ports (0,1) of Arduino UNO. To Begin Serial Communication at Hardware Serial Pins (0,1) use: Serial.begin(9600); use: int potval = analogRead(pushval); that is connected to the pin 8 of Arduino UNO so to Make pin 8 HIGH: digitalWrite(enablePin, HIGH); Next to put those values in the Serial Port connected with the RS-485 module, use the following statement Serial.println(potval); In the Slave side an integer value is received from the Master RS-485 that is available at the Hardware Serial port of the Arduino Nano (Pins -0,1). Simply read those value and store in a variable. The values are in form of (0 -1023). So it is converted into (0-255) as PWM technique is used to control LED brightness. So the pin D8 (enablePin) of Arduino NANO is made LOW. digitalWrite(enablePin, LOW); And to read the integer data available at Serial Port and store them in a variable use int pwmval = Serial.parseInt(); Next convert value from (0-1023 to 0-255) and store them in a variable: int convert = map(pwmval,0,1023,0,255); Next write the analog value (PWM) to pin D10 where LED anode is connected: analogWrite(ledpin,convert); To print those PWM value in 16x2 LCD display use lcd.setCursor(0,0); lcd.print("PWM FROM MASTER"); lcd.setCursor(0,1); lcd.print(convert);

Controlling LED Brightness with Serial Communication RS485

When the PWM value is set at 0 using potentiometer, the LED is turned OFF. And when PWM value is set at 251 using potentiometer: The LED is turned ON with full brightness as shown in below picture: Code //Master code (Arduino UNO) //Serial Communication Between Arduino using RS-485 int enablePin = 8; int pushval = A0; int potval =0 ; void setup() { Serial.begin(9600); // initialize serial at baudrate 9600: pinMode(enablePin, OUTPUT); pinMode(pushval,INPUT); delay(10); digitalWrite(enablePin, HIGH); // (always high as Master Writes data to Slave) } void loop() { int potval = analogRead(pushval); Serial.println(potval); //Serial Write POTval to RS-485 Bus delay(100); } //Slave code (Arduino NANO) //Serial Communication Between Two Arduinos using RS-485 //Circuit Digest #include <LiquidCrystal.h> //Include LCD library for using LCD display functions int enablePin = 8; int ledpin = 10; LiquidCrystal lcd(2,3,4,5,6,7); // Define LCD display pins RS,E,D4,D5,D6,D7 void setup() { lcd.begin(16,2); lcd.print("CIRCUIT DIGEST"); lcd.setCursor(0,1); lcd.print("RS485 ARDUINO"); delay(3000); lcd.clear(); Serial.begin(9600); // initialize serial at baudrate 9600: pinMode(ledpin,OUTPUT); pinMode(enablePin, OUTPUT); delay(10); digitalWrite(enablePin, LOW); // (Pin 8 always LOW to receive value from Master) } void loop() { while (Serial.available()) //While have data at Serial port this loop executes { lcd.clear(); int pwmval = Serial.parseInt(); //Receive INTEGER value from Master throught RS-485 int convert = map(pwmval,0,1023,0,255); //Map those value from (0-1023) to (0-255) analogWrite(ledpin,convert); //PWM write to LED lcd.setCursor(0,0); lcd.print("PWM FROM MASTER"); lcd.setCursor(0,1); lcd.print(convert); //Displays the PWM value delay(100); } } Video microcontroller-projects/arduino-xbee-module-interfacing-tutorial

XBee Module Interfacing with Arduino

Hardware Requirements

1 x Arduino Uno 2 x XBee Pro S2C modules (any other model can be used) 1 x Xbee explorer board (optional) 1 x Xbee Breakout board (optional) USB cables LEDs

Configuring XBee Modules using XCTU

, we have to configure these modules using XCTU software. To connect XBee module with the laptop, a USB to serial converter or specifically designed explorer board is used. Just hook up the XBee module to the Explorer board and plug it with the laptop using USB cable. which can easily communicate with the XBee and laptop. Just upload blank sketch in Arduino board and now it can behave like a USB to Serial converter. are shown in the circuit diagram. Connections: Tx (pin2)of XBee -> Tx of Arduino board Rx(pin3) of Xbee -> Rx of Arduino board Gnd(pin10) of Xbee -> GND of Arduino board Vcc (Pin1) of Xbee -> 3.3v of Arduino board and install it. After downloading and installing the XCTU software, open it and make sure your XBee module is properly connected. Check the COM port of the Arduino board in device manager. Now, click on the search button. This will show you all the RF devices connected with your laptop. In our case, it will show only one XBee module. Select the Serial port of the Explorer board/Arduino board and click on Next. In the next window, set the USB port parameters as shown below and click on Finish. This process will add your XBee module to XCTU dashboard. First, update the Firmware by clicking on the Update firmware. button. As shown below.
Then give commands to the receiver part using laptop. Connections: Tx (pin2)of XBee -> Rx of Arduino board Rx(pin3) of Xbee -> Tx of Arduino board Gnd(pin10) of Xbee -> GND of Arduino board Vcc (Pin1) of Xbee -> 3.3v of Arduino board If you are using the Arduino board to connect the transmitter ZigBee with the laptop, connections will be same as for the programming the ZigBee.

Programming and Testing XBee communication using Arduino

, for other characters LED will remain OFF. Upload the code in the Receiver part Arduino. Remove the Tx and Rx wires of XBee before uploading. To give command to the transmitter part, we will use XCTU’s console terminal. Click on the Console icon near the settings option. Then, click on Open button to connect the XBee to the laptop. Enter ‘aᾠin Console log. You will see that LED will turn ON for 2 seconds and after that enter ‘bᾠto make the led blink for 5 times. You can also connect the transmitter XBee to the Arduino board, just change the receiver code little bit. In place of Serial.read() function, use Serial.println() function to send the characters. given below. can be used to make many useful wireless applications like Home automation system, chatting room etc. Code int led = 13; int received = 0; int i; void setup() { Serial.begin(9600); pinMode(led, OUTPUT); } void loop() { if (Serial.available() > 0) { received = Serial.read(); if (received == 'a'){ digitalWrite(led, HIGH); delay(2000); digitalWrite(led, LOW); } else if (received == 'b'){ for(i=0;i<5;i++){ digitalWrite(led, HIGH); delay(1000); digitalWrite(led, LOW); delay(1000); } } } } Video microcontroller-projects/arduino-interrupt-tutorial-with-examples

Arduino Interrupts Tutorial

is used here which has the highest priority of all. of Interrupts is touch screen mobile phones which have the highest priority to the “Touchᾠsense. Almost every electronic device has some kind to interrupts to ‘interruptᾠthe regular process and do some higher priority things on a particular event. The regular process is resumed after serving the Interrupt. For example, a processor doing a normal execution can be interrupted by some sensor to execute a particular process that is present in ISR (Interrupt Service Routine). After executing the ISR processor can again resume the normal execution.

Types of Interrupts

There are two types of interrupts: It happens when an external event occurslike an external interrupt pin changes its state from LOW to HIGH or HIGH to LOW.

Interrupts in Arduino

Board. It has two types of interrupts: External Interrupt Pin Change Interrupt These interrupt are interpreted by hardware and are very fast. These interrupts can be set to trigger on the event of RISING or FALLING or LOW levels.
UNO , NANO2,3
Mega2,3,18,19,20,21
interrupts. In ATmega168/328 based Arduino boards any pins or all the 20 signal pins can be used as interrupt pins. They can also be triggered using RISING or FALLING edges.

Using Interrupts in Arduino

In order to use interrupts in Arduino the following concepts are need to be understood. Interrupt Service Routine or an Interrupt handler is an event that has small set of instructions in it. When an external interrupt occurs, the processor first executes these code that is present in ISR and returns back to state where it left the normal execution. attachInterrupt(digitalPinToInterrupt(pin), ISR, mode); In Arduino Uno, NANO the pins used for interrupt are 2,3 & in mega 2,3,18,19,20,21. Specify the input pin that is used for external interrupt here. It is a function that is called when an external interrupt is done. Type of transition to trigger on, e.g. falling, rising, etc. RISING: To trigger an interrupt when the pin transits from LOW to HIGH. FALLING: To trigger an interrupt when the pin transits from HIGH to LOW. CHANGE: To trigger an interrupt when the pin transits from LOW to HIGH or HIGH to LOW (i.e., when the pin state changes ). Interrupt Service Routine function (ISR) must be as short as possible. Delay () function doesn’t work inside ISR and should be avoided. the led goes OFF and the display shows interrupt1 and goes off.

Components Required

Arduino Board (In this tutorial Arduino NANO is used) Push button - 2 LED - 1 Resistor (10K) - 2 LCD (16x2) - 1 Bread Board Connecting Wires

Circuit Diagram

LCDArduino Nano
VSSGND
VDD+5V
V0To Potentiometer Centre PIN For Controlling Contrast of the LCD
RSD7
RWGND
ED8
D4D9
D5D10
D6D11
D7D12
A+5V
KGND
of 10k connected to ground. So when push button is pressed it is logic HIGH (1) and when not pressed it is logic LOW (0). A Pull down resistor is compulsory otherwise there will be floating values at the input pin D2 & D3. is also used to indicate that a Interrupt has been triggered or a button has been pressed.

Arduino Interrupt Programming

In this tutorial a number is incremented from 0 which displays continuously in (16x2) LCD connected to the Arduino Nano, whenever the left push button (interrupt pin D3) is pressed the LED goes ON and display shows Interrupt2, and when the right push button (interrupt pin D2) is pressed the LED goes OFF and display shows Interrupt1. for the LCD display is included and then the LCD pins that are used in connecting with the Arduino Nano are defined. #include<LiquidCrystal.h> LiquidCrystal lcd (7,8,9,10,11,12); // Define LCD display pins RS, E, D4, D5, D6, D7 lcd.begin(16,2); lcd.setCursor(0,0); lcd.print("CIRCUIT DIGEST"); lcd.setCursor(0,1); lcd.print("ArduinoInterrupt"); delay(3000); lcd.clear(); 3. Then in same void setup () function the input and output pins must be specified. The pin D13 is connected to LED’s Anode, so this pin must be defined as output. pinMode(13,OUTPUT); , it is also included inside the void setup(). attachInterrupt(digitalPinToInterrupt(2),buttonPressed1,RISING); attachInterrupt(digitalPinToInterrupt(3),buttonPressed2,RISING); function is called when there is RISING (LOW to HIGH) at D2 pin. And pin 3 is also for external interrupt and buttonPressed2 function is called when there is RISING at D3 pin. a number (i) is incremented from zero and printed on LCD(16x2). lcd.clear(); lcd.print("COUNTER:"); lcd.print(i); ++i; delay(1000); LED will turn on or off digitalWrite(13,output); function. As two interrupt pins are used 2 and 3 so two ISR are required. Here in this programming following ISR are used void buttonPressed1() { output = LOW; lcd.setCursor(0,1); lcd.print("Interrupt 1"); } This function executes when push button on the pin D2 is pressed (RISING EDGE). This function changes the state of the output to LOW causing LED to turn OFF and prints the “interrupt1ᾠon the LCD display. void buttonPressed2() { output = HIGH; lcd.setCursor(0,1); lcd.print("Interrupt2"); } This function executes when push button on the pin D3 is pressed. This function changes the state of the output to HIGH causing LED to turn ON and prints the “interrupt2ᾠon the LCD display.

Arduino Interrupt Demonstration

1. When PUSH BUTTON on the leftside is pressed the LED goes ON and the LCD displays Interrupt2. 2. When the PUSH BUTTON on the right side is pressed the LED goes OFF and the LCD displays Interrupt1 This is how an Interrupt can be useful to trigger any important task in between of normal execution. Code //Interrupts using Arduino //Circuit Digest #include<LiquidCrystal.h> // Including lcd display library LiquidCrystal lcd (7,8,9,10,11,12); // Define LCD display pins RS,E,D4,D5,D6,D7 volatile int output = LOW; int i = 0; void setup() { lcd.begin(16,2); // setting LCD as 16x2 type lcd.setCursor(0,0); lcd.print("CIRCUIT DIGEST"); lcd.setCursor(0,1); lcd.print("ArduinoInterrupt"); delay(3000); lcd.clear(); pinMode(13,OUTPUT); attachInterrupt(digitalPinToInterrupt(2),buttonPressed1,RISING); // function for creating external interrupts at pin2 on Rising (LOW to HIGH) attachInterrupt(digitalPinToInterrupt(3),buttonPressed2,RISING); // function for creating external interrupts at pin3 on Rising (LOW to HIGH) } void loop() { lcd.clear(); lcd.print("COUNTER:"); lcd.print(i); ++i; delay(1000); digitalWrite(13,output); //Turns LED ON or OFF depending upon output value } void buttonPressed1() //ISR function excutes when push button at pinD2 is pressed { output = LOW; //Change Output value to LOW lcd.setCursor(0,1); lcd.print("Interrupt 1"); } void buttonPressed2() //ISR function excutes when push button at pinD3 is pressed { output = HIGH; //Change Output value to HIGH lcd.setCursor(0,1); lcd.print("Interrupt2"); } Video microcontroller-projects/arduino-dac-tutorial-interfacing-mcp4725-dac

Arduino DAC Tutorial: Interfacing MCP4725 12-Bit Digital-to-Analog Converter with Arduino

is recording a song in studio where an artist singer is using microphone and singing a song. These analog sound waves are converted into digital form and then stored in a digital format file and when the song is played using the stored digital file those digital values are converted into analog signals for speaker output. So in this system DAC is used. , Video Encoders, Data Acquisition Systems etc.

MCP4725 DAC Module (Digital to Analog Converter)

It also comes with on board nonvolatile memory EEPROM. This IC has 12-Bit resolution. This means we use (0 to 4096) as input to provide the voltage output with respect to reference voltage. Maximum reference voltage is 5V. O/P Voltage = (Reference Voltage / Resolution) x Digital Value if we use 5V as reference voltage and let’s assume that digital value is 2048. So to calculate the DAC output. O/P Voltage = (5/ 4096) x 2048 = 2.5V Below is the image of MCP4725 with clearly indicating pin names.
OUTOutputs Analog Voltage
GNDGND for Output
SCLI2C Serial Clock line
SDAI2C Serial Data line
VCCInput Reference Voltage 5V or 3.3V
GNDGND for input

I2C Communication in MCP4725 DAC

is already explained in detail in previous tutorial.

Components Required

Arduino Nano / ArduinoUno 16x2 LCD display module MCP4725 DAC IC 10k Potentiometer Breadboard Jumper Wires

Circuit Diagram

SDAA4NC
SCLA5NC
A0 or OUTA1+ve terminal
GNDGND-ve terminal
VCC5VNC
VSSGND
VDD+5V
V0From Potentiometer Centre Pin to adjust contrast of LCD
RSD2
RWGND
ED3
D4D4
D5D5
D6D6
D7D7
A+5V
KGND
is used with center pin connected to A0 analog input of Arduino Nano, Left pin connected to GND and right most pin connected to 5V of Arduino.

DAC Arduino Programming

with a demonstration video. Here we have explained the code line by line. library. #include<Wire.h> #include <LiquidCrystal.h> Next define and initialize the LCD pins according to pins we have connected with the Arduino Nano LiquidCrystal lcd(2,3,4,5,6,7); //Define LCD display pins RS,E,D4,D5,D6,D7 Next define the I2C address of the MCP4725 DAC IC #define MCP4725 0x61 First begin the I2C communication at the pins A4 (SDA) and A5 (SCL) of Arduino Nano Wire.begin(); //Begins the I2C communication Next set the LCD display in the 16x2 mode and display a welcome message. lcd.begin(16,2); //Sets LCD in 16X2 Mode lcd.print("CIRCUIT DIGEST"); delay(1000); lcd.clear(); lcd.setCursor(0,0); lcd.print("Arduino"); lcd.setCursor(0,1); lcd.print("DAC with MCP4725"); delay(2000); lcd.clear(); First in buffer[0] put the control byte value (0b01000000) (010-Sets MCP4725 in Write mode) buffer[0] = 0b01000000; 2. The following statement reads the analog value from pin A0 and converts it into digital values (0-1023). Arduino ADC is 10-bit resolution so multiply it with 4 gives: 0-4096, as the DAC is 12-bit resolution. adc = analogRead(A0) * 4; 3. This statement is to find the voltage from the ADC input value (0 to 4096) and the reference voltage as 5V float ipvolt = (5.0/4096.0)* adc; 4. Below first line puts the Most significant bit values in buffer[1] by shifting 4 bits to right in ADC variable, and second line puts the least significant bit values in buffer[2] by shifting 4 bits to left in ADC variable. buffer[1] = adc >> 4; buffer[2] = adc << 4; unsigned int analogread = analogRead(A1)*4 ; is calculated using the formula below float opvolt = (5.0/4096.0)* analogread; 7. Following statement is used to begins the transmission with MCP4725 Wire.beginTransmission(MCP4725); Sends the control byte to I2C Wire.write(buffer[0]); Sends the MSB to I2C Wire.write(buffer[1]); Sends the LSB to I2C Wire.write(buffer[2]); Ends the transmission Wire.endTransmission(); lcd.setCursor(0,0); lcd.print("A IP:"); lcd.print(adc); lcd.setCursor(10,0); lcd.print("V:"); lcd.print(ipvolt); lcd.setCursor(0,1); lcd.print("D OP:"); lcd.print(analogread); lcd.setCursor(10,1); lcd.print("V:"); lcd.print(opvolt); delay(500); lcd.clear();

Digital to Analog Conversion using MCP4725 and Arduino

You can also check the output voltage by connecting a multimeter to the OUT and GND pin of MCP4725. Code #include<Wire.h> //Include Wire library for using I2C functions #include <LiquidCrystal.h> //Include LCD library for using LCD display functions #define MCP4725 0x61 //MCP4725 address as 0x61 Change yours accordingly LiquidCrystal lcd(2,3,4,5,6,7); //Define LCD display pins RS,E,D4,D5,D6,D7 unsigned int adc; byte buffer[3]; void setup() { Wire.begin(); //Begins the I2C communication lcd.begin(16,2); //Sets LCD in 16X2 Mode lcd.print("CIRCUIT DIGEST"); delay(1000); lcd.clear(); lcd.setCursor(0,0); lcd.print("Arduino"); lcd.setCursor(0,1); lcd.print("DAC with MCP4725"); delay(2000); lcd.clear(); } void loop() { buffer[0] = 0b01000000; //Sets the buffer0 with control byte (010-Sets in Write mode) adc = analogRead(A0) * 4; //Read Analog value from pin A0 and convert into digital (0-1023) multiply with 4 gives (0-4096) float ipvolt = (5.0/4096.0)* adc; //Finding voltage formula (A0) buffer[1] = adc >> 4; //Puts the most significant bit values buffer[2] = adc << 4; //Puts the Least significant bit values unsigned int analogread = analogRead(A1)*4 ; //Reads analog voltage from A1 float opvolt = (5.0/4096.0)* analogread; //Finding Voltage Formula (A1) Wire.beginTransmission(MCP4725); //Joins I2C bus with MCP4725 with 0x61 address Wire.write(buffer[0]); //Sends the control byte to I2C Wire.write(buffer[1]); //Sends the MSB to I2C Wire.write(buffer[2]); //Sends the LSB to I2C Wire.endTransmission(); //Ends the transmission lcd.setCursor(0,0); lcd.print("A IP:"); lcd.print(adc); //Prints the ADC value from A0 lcd.setCursor(10,0); lcd.print("V:"); //Prints the Input Voltage at A0 lcd.print(ipvolt); lcd.setCursor(0,1); lcd.print("D OP:"); lcd.print(analogread); //Prints the ADC value from A1 (From DAC) lcd.setCursor(10,1); lcd.print("V:"); lcd.print(opvolt); //Prints the Input Voltage at A1 (From DAC) delay(500); lcd.clear(); } Video microcontroller-projects/digital-taxi-fare-meter-using-arduino

Digital Taxi Fare Meter using Arduino

are replacing analog meters in every sector whether its electricity meter or taxi fare meter. The main reason for that is analog meters have mechanical parts that tend to wear when used for long time and they are not as accurate as digital Meters. arrangement in which a cable is used to rotate speedometer’s pin when wheel is rotated. This will wear out when using for long period and also needs replacement and maintenance. In digital meter, instead of using mechanical parts, some sensors like optical interrupter or hall sensor is used to calculate the speed and distance. This is more accurate than the analog meters and doesn’t require any maintenance for long period of time. We previously built many digital speedometer projects using different sensors: DIY Speedometer using Arduino and Processing Android App Digital Speedometer and Odometer Circuit using PIC Microcontroller Speed, Distance and Angle Measurement for Mobile Robots using LM393 Sensor (H206) And based on distance travelled it generates fare amount when we press push button. , follow the link. Let’s see a short introduction of Speed sensor module.

Infrared Slotted Optical LM-393 Speed Sensor Module

This is a slot type module that can be used for measuring speed of rotation of encoder wheels. This Speed sensor module works based on slot type optical interrupter also known as optical source sensor. This module requires a voltage of 3.3V to 5V and produces digital output. So it can be interfaced with any microcontroller. consists consists of light source (IR-LED) and a phototransistor sensor. Both are placed with a small gap in-between them. When an object is placed in between the gap of IR LED and phototransistor it will interrupt the light beam causing phototransistor to stop passing current. Thus with this sensor a slotted disc (Encoder Wheel) is used that can be attached to a motor and when the wheel rotates with motor it interrupts the light beam between IR LED and phototransistor that makes output On and Off (Creating Pulses). when there is no object placed. In the module we have an LED to indicated the optical interrupt caused.

Measuring Speed and Distance Travelled to Calculate Fare

To measure the speed of rotation we need to know the number of slots present in encoder wheel. I have an encoder wheel with 20 slots in it. When they rotate one complete rotation we have 20 pulses at the output. So to calculate speed we need number of pulses produced per second. If there are 40 pulses in one second, then Speed = Noo. Of pulses / No. of slots = 40/20 = 2RPS (Revolution per second) For calculating speed in RPM (Revolutions per Minute) multiply with 60. Speed in RPM = 2 X 60 = 120 RPM (Revolutions per Minute) Measuring distance travelled by the wheel is so simple. Before calculating distance, the circumference of the wheel should be known. Circumference of the wheel = π*d Where d is the diameter of the wheel. Value of π is 3.14. I have a wheel (RC car wheel) of diameter 6.60 cm so the circumference is (20.7 cm). So to calculate the distance travelled, just multiply the no of pulses detected with the circumference. Distance Travelled = Circumference of Wheel x (No. of Pulses / No. of slots) So when a wheel of Circumference 20.7cm takes 20 pulses that is one rotation of encoder wheel then the distance travelled by wheel is calculated by Distance travelled = 20.7 x (20/20) = 20.7cm In order to calculate the distance in meter divide the distance in cm value by 100. To get the total fare amount, multiply the distance travelled with the fare rate (amount/meter). In this tutorial I’m assuming that Rs 5 is charged per meter. So now let’s get the components and build the circuit.

Components Required

Arduino UNO LCD (16x2) Push Button Potentiometer -10k ULN2003 Motor Driver IC LM393 Speed Sensor Module (FC-03) RC Smart Car Chassis with Speed encoder Battery 9V Breadboard Connecting Wires

Circuit Diagram

is given below: Speed sensor is mounted with the encoder wheel present in between the gap of sensor. In my chassis I have a special hole for placing the sensor. See the image below
VCC5V
GNDGND
D02
VSSGND
VDD+5V
V0From potentiometer output for contrast of LCD
RS12
RWGND
EN13
D48
D59
D610
D711
A+5V
KGND
5IN1
GNDGND
I have used a 9V battery and ULN2003 IC to externally power the motor.
OUT1-Ve Motor-
COM+Ve Motor+Ve
GND--Ve
A push button with pull down resistor is connected to the pin 3 of Arduino for generating fare amount when pressed. A potentiometer is used to give analog input voltage to the pin A0 of the Arduino for varying speed of the motor wheel.

Programming Arduino for Digital Taxi Meter

is given at the end of this tutorial. Here we understand few important parts of the code. as they are used in the code. is used here because we need to constantly check the output detected at the speed sensor module as the high priority. So ISR is used in the code. ISR is interrupt service routine that is called when an interrupt is occurred at the interrupt pins 2 & 3. Arduino UNO has two interrupt pins 2 and 3. is used in this code to check how many rotations (how many pulses) are detected for one second and from that we can calculate the speed per second and display them at the output. This ISR function executes for every second So let’s see our code in detail: 1. First of all, include libraries for the functions are going to be used in programme. #include "TimerOne.h" #include <LiquidCrystal.h> 2. Next declare the global variables as they will be used throughout the program. volatile unsigned int counter=0; volatile unsigned int rotation=0; float rotationinm=0; unsigned int speed=0; 3. Next define and initialize the LCD pins that are connected to Arduino. const int rs = 12, en = 13, d4 = 8, d5 = 9, d6 = 10, d7 = 11; LiquidCrystal lcd(rs, en, d4, d5, d6, d7); Define the pin mode, here PIN A0 is used for taking Analog input from potentiometer and pin 5 to write analog output which is connected to IN1 pin of ULN2003 IC. pinMode(A0,INPUT); pinMode(5,OUTPUT); Next display some welcome message and clear them. lcd.begin(16,2); //Sets LCD as 16x2 type lcd.setCursor(0,0); lcd.print("CIRCUIT DIGEST"); lcd.setCursor(0,1); lcd.print("WELCOME TO TAXI"); delay(3000); lcd.clear(); lcd.print("LETS START :)"); delay(1000); lcd.clear(); part is to set the Interrupt pin and the ISR to be called when interrupt happens Timer1.initialize(1000000); Timer1.attachInterrupt( timerIsr ); Next attach two external interrupts. First interrupt makes the Arduino pin 2 as interrupt pin and calls ISR (count) when there is RISING (LOW TO HIGH) detected at the pin 2. This pin 2 is connected to the D0 output of the speed sensor module. And second one makes the Arduino pin 3 as interrupt pin and calls ISR (generatefare) when HIGH is detected at the pin3. This pin is connected to the push button with a pull down resistor. attachInterrupt(digitalPinToInterrupt(2), count, RISING); attachInterrupt(digitalPinToInterrupt(3), generatefare, HIGH); we used here: ISR is called when an RISING (LOW TO HIGH) is happened at the pin 2 (connected to speed sensor). void count() // ISR for counts from the speed sensor { counter++; // increase the counter value by one rotation++; //Increase the rotation value by one delay(10); } ISR is called every one second and execute those lines present inside the ISR. void timerIsr() { detachInterrupt(digitalPinToInterrupt(2)); Timer1.detachInterrupt(); lcd.clear(); float speed = (counter / 20.0)* 60.0; float rotations = 230*( rotation / 20); rotationinm = rotations/100; lcd.setCursor(0,0); lcd.print("Dist(m):"); lcd.print(rotationinm); lcd.setCursor(0,1); lcd.print("Speed(RPM):"); lcd.print(speed); counter=0; int analogip = analogRead(A0); int motorspeed = map(analogip,0,1023,0,255); analogWrite(5,motorspeed); Timer1.attachInterrupt( timerIsr ); attachInterrupt(digitalPinToInterrupt(2), count, RISING); } This function contains the lines that actually first detach the Timer1 and Interrupt pin2 first because we have LCD print statements inside the ISR. we use below code where 20.0 is the no of slots preset in the encoder wheel. float speed = (counter / 20.0) * 60.0; And for calculating distance below code is used: float rotations = 230*( rotation / 20); Here the circumference of wheel is assumed as 230cm (as this is normal for real time cars) Next convert the distance in m by dividing the distance by 100 rotationinm = rotations/100; After that we display the SPEED and DISTANCE on LCD display lcd.setCursor(0,0); lcd.print("Dist(m):"); lcd.print(rotationinm); lcd.setCursor(0,1); lcd.print("Speed(RPM):"); lcd.print(speed); We have to reset the counter to 0 because we need to get number of pluses detected for per second so we use this line counter=0; function that is connected to the ULN2003 Motor IC. int analogip = analogRead(A0); int motorspeed = map(analogip,0,1023,0,255); analogWrite(5,motorspeed); ISR is used to generate the fare amount based on the distance travelled. This ISR is called when interrupt pin 3 is detected HIGH (When push button pressed). This function detaches the interrupt at pin 2 and the timer interrupt and then clears the LCD. void generatefare() { detachInterrupt(digitalPinToInterrupt(2)); pin at 2 Timer1.detachInterrupt(); lcd.clear(); lcd.setCursor(0,0); lcd.print("FARE Rs: "); float rupees = rotationinm*5; lcd.print(rupees); lcd.setCursor(0,1); lcd.print("Rs 5 per metre"); } After that distance travelled is multiplied with 5 (I have used 5 for the rate INR 5/meter). You can change according to your wish. float rupees = rotationinm*5; After calculating the amount value display it on the LCD display connected to Arduino. lcd.setCursor(0,0); lcd.print("FARE Rs: "); lcd.print(rupees); lcd.setCursor(0,1); lcd.print("Rs 5 per metre"); is given below. You can further improve this prototype by increasing accuracy, robustness and adding more features like android app, digital payment etc and develop it as a product. Code #include "TimerOne.h" //Include Timer1 library for using Timer1 functions #include <LiquidCrystal.h> //Include LCD library for using LCD display functions const int rs = 12, en = 13, d4 = 8, d5 = 9, d6 = 10, d7 = 11; //Define the LCD pins LiquidCrystal lcd(rs, en, d4, d5, d6, d7); volatile unsigned int counter=0; volatile unsigned int rotation=0; float rotationinm=0; unsigned int speed=0; void count() // ISR for counts from the speed sensor { counter++; //increase the counter value by one rotation++; //Increase the rotation value by one delay(10); } void timerIsr() { detachInterrupt(digitalPinToInterrupt(2)); //Stops the interrupt pin 2 Timer1.detachInterrupt(); //Stops the timer1 interrupt lcd.clear(); float speed = (counter / 20.0)* 60.0; //Calcukate speed in minute (20-No of slots in Encoder Wheel) float rotations = 230*( rotation / 20); //Calculate distance in cm (230-Circumference of the wheel assumed 20- No of slots) rotationinm = rotations/100; lcd.setCursor(0,0); lcd.print("Dist(m):"); lcd.print(rotationinm); //Display rotationinm at LCD lcd.setCursor(0,1); lcd.print("Speed(RPM):"); lcd.print(speed); //Dsiplay speed in RPM counter=0; //Reset counter to 0 int analogip = analogRead(A0); // Analog read from pin A0 int motorspeed = map(analogip,0,1023,0,255); //convert digital vales 0-1023 to 0-255 analogWrite(5,motorspeed); //Sets PWM value at pin 5 Timer1.attachInterrupt( timerIsr ); //Starts timer1 again attachInterrupt(digitalPinToInterrupt(2), count, RISING); //Attaches interrupt at pin2 again } void generatefare() //ISR to generate the fareamount { detachInterrupt(digitalPinToInterrupt(2)); //Disables the Interrupt pin at 2 Timer1.detachInterrupt(); //Disables the Timer1 interrupt float rupees = rotationinm*5; //Muliply 5 with distance travelled (Rs 5 per meter ) lcd.clear(); //Clears LCD lcd.setCursor(0,0); lcd.print("FARE Rs: "); lcd.print(rupees); //Display fare amount lcd.setCursor(0,1); lcd.print("Rs 5 per metre"); } void setup() { pinMode(A0,INPUT); //Sets pin A0 as INPUT pinMode(5,OUTPUT); //Sets pin 5 as OUTPUT lcd.begin(16,2); //Sets LCD as 16x2 type lcd.setCursor(0,0); //The following code displays welcome messages lcd.print("CIRCUIT DIGEST"); lcd.setCursor(0,1); lcd.print("WELCOME TO TAXI"); delay(3000); lcd.clear(); lcd.print("LETS START :)"); delay(1000); lcd.clear(); Timer1.initialize(1000000); //Initilize timer1 for 1 second Timer1.attachInterrupt( timerIsr ); //ISR routine to be called for every one second attachInterrupt(digitalPinToInterrupt(2), count, RISING); // Pin 2 as Interrupt pin with count ISR is called when LOW to RIGH happens. attachInterrupt(digitalPinToInterrupt(3), generatefare, HIGH); //Pin 3 as Interrupt pin with generatefare ISR is called when HIGH is detected. } void loop() { } Video microcontroller-projects/arduino-medicine-reminder

Automatic Medicine Reminder Using Arduino

is very wide and can be used by patients at home, doctors at hospitals, and at many other places. When it comes to reminding, there can be many ways to remind it: Show it on a display Send notification on email or Phone Using mobile apps Buzz alarm Using Bluetooth/ Wi-Fi Get a call Remind for next medicine time while reminding current time

Components Required for Automatic Medicine reminder using Arduino

Arduino Uno (We can use other Arduino boards also, like Pro mini, Nano) RTC DS3231 module 16x2 LCD Display Buzzer Led(any color) Breadboard Push Buttons 10K Potentiometer 10K,1K Resistors Jumper Wires

ArduinoMedicine Reminder using Arduino Circuit

is shown below of Arduino with different peripherals 2 -----------------------------> D7 of 16x2 LCD Display 3 -----------------------------> D6 of 16x2 LCD Display 4 -----------------------------> D5 of 16x2 LCD Display 5 -----------------------------> D4 of 16x2 LCD Display 7 -----------------------------> 3rd push button 8 -----------------------------> 2nd push button 9 -----------------------------> 1st push button 11 -----------------------------> EN pin of 16x2 LCD Display 12 -----------------------------> RS pin of 16x2 LCD Display 13 -----------------------------> +Ve Pin of Buzzer and Led A0 -----------------------------> Stop Push Button A4 -----------------------------> SDA of DS3231 A5 -----------------------------> SCL of DS3231 3.3V -----------------------------> Vcc of DS3231 Gnd -----------------------------> Gnd are used where each has distinct select feature. The first push button is used for reminding to take medicine once per day. The second push button is used to remind twice per day and the third push button is used to remind thrice per day. The fourth push button is used to stop the buzzer when user has heard the alert.

Working of Automatic Medicine Reminder System

ᾮ The second screen is a help screen which tells to press select push button to select any one time-slot to remind (once/twice/thrice in a day). The time slot is changeable in program and can be configured accordingly. Right now we have fixed this into three durations i.e. 8am, 2pm, and 8pm. push button. given at the end of this aricle.

Programming Arduino UNO for Medicine Reminder

It is very easy to write program once you have thought of the ways to remind taking the pills. Here it will show the reminder on display, buzz a buzzer and indicate it using LED. It also have option to select three time slots (once/twice/thrice per day) and when time will reach it start alerting the patient by buzzing the buzzer. Then the whole system will look like following: We can change the program and hardware if we want to add more features. To understand in much simpler way, we have broken down program into small functions. The functions are easy to understand and implement. The complete program is given at the end of this project. Let’s start with the program. or that. Library required are as following: <LiquidCrystal.h> <RTClib.h> (https://github.com/adafruit/RTClib) <EEPROM.h> <Wire.h> The EEPROM library is used to keep the track of user select input if Arduino is not turned on. And when user power on the Arduino it gets the previous state of push buttons using EEPROM library. The Wire.h library is used since the RTC DS3231 module is communicated using I2C. , since RTC will play an important role in time keeping of the whole reminder system. if (! rtc.begin()) { // check if rtc is connected Serial.println("Couldn't find RTC"); while (1); } if (rtc.lostPower()) { Serial.println("RTC lost power, lets set the time!"); } The time adjustment can be done in two ways, either automatically using system compile time or by entering it manually. Once we have set the time, comment the below lines unless you want to change the RTC time again. rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); //rtc.adjust(DateTime(2019, 1, 10, 7, 59, 52)); and resuming the state for appropriate and accurate reminder time. val2 = EEPROM.read(addr); // read previosuly saved value of push button to start from where it was left previously switch (val2) { case 1: Serial.println("Set for 1/day"); push1state = 1; push2state = 0; push3state = 0; pushVal = 01; break; case 2: Serial.println("Set for 2/day"); push1state = 0; push2state = 1; push3state = 0; pushVal = 10; break; case 3: Serial.println("Set for 3/day"); push1state = 0; push2state = 0; push3state = 1; pushVal = 11; break; } This statement is used to get the millis to use for timing and control of the defined interval screen cycling. currentMillisLCD = millis(); // start millis for LCD screen switching at defined interval of time Start reading the digital pins connected to push buttons. push1state = digitalRead(push1pin); push2state = digitalRead(push2pin); push3state = digitalRead(push3pin); stopinState = digitalRead(stopPin); is used. void push1() { // function to set reminder once/day if (push1state == 1) { push1state = 0; push2state = 0; push3state = 0; // pushPressed = true; EEPROM.write(addr, 1); Serial.print("Push1 Written : "); Serial.println(EEPROM.read(addr)); // for debugging pushVal = 1; //save the state of push button-1 lcd.clear(); lcd.setCursor(0, 0); lcd.print("Reminder set "); lcd.setCursor(0, 1); lcd.print("for Once/day !"); delay(1200); lcd.clear(); } } It is always good to give suggestions. Print a suggestion message on display “Take medicine with warm waterᾮ void stopPins() { //function to stop buzzing when user pushes stop push button if (stopinState == 1) { // stopinState = 0; // pushPressed = true; pushpressed = 1; lcd.clear(); lcd.setCursor(0, 0); lcd.print("Take Medicine "); lcd.setCursor(0, 1); lcd.print("with Warm Water"); delay(1200); lcd.clear(); } } void changeScreen() { //function for Screen Cycling // Start switching screen every defined intervalLCD if (currentMillisLCD - previousMillisLCD > intervalLCD) // save the last time you changed the display { previousMillisLCD = currentMillisLCD; screens++; if (screens > maxScreen) { screens = 0; // all screens over -> start from 1st } isScreenChanged = true; } // Start displaying current screen if (isScreenChanged) // only update the screen if the screen is changed. { isScreenChanged = false; // reset for next iteration switch (screens) { case getWellsoon: gwsMessege(); // get well soon message break; case HELP_SCREEN: helpScreen(); // instruction screen break; case TIME_SCREEN: timeScreen(); // to print date and time break; default: //NOT SET. break; } } } simultaneously if the selected time has reached. void startBuzz() { // function to start buzzing when time reaches to defined interval // if (pushPressed == false) { if (pushpressed == 0) { Serial.println("pushpressed is false in blink"); unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; // save the last time you blinked the LED Serial.println("Start Buzzing"); if (ledState == LOW) { // if the LED is off turn it on and vice-versa: ledState = HIGH; } else { ledState = LOW; } digitalWrite(ledPin, ledState); } } else if (pushpressed == 1) { Serial.println("pushpressed is true"); ledState = LOW; digitalWrite(ledPin, ledState); } } is used to start buzzer and led at 2pm and 8pm. void at8am() { // function to start buzzing at 8am DateTime now = rtc.now(); if (int(now.hour()) >= buzz8amHH) { if (int(now.minute()) >= buzz8amMM) { if (int(now.second()) > buzz8amSS) { ///////////////////////////////////////////////////// startBuzz(); ///////////////////////////////////////////////////// } } } } to make it an IoT project which will be able to send email alert to the user. is given below. Code //Medicine Reminder using Arduino Uno // Reminds to take medicine at 8am, 2pm, 8pm /* The circuit: LCD RS pin to digital pin 12 LCD Enable pin to digital pin 11 LCD D4 pin to digital pin 5 LCD D5 pin to digital pin 4 LCD D6 pin to digital pin 3 LCD D7 pin to digital pin 2 LCD R/W pin to ground LCD VSS pin to ground LCD VCC pin to 5V 10K resistor: ends to +5V and ground wiper to LCD VO pin (pin 3)*/ #include <LiquidCrystal.h> #include <Wire.h> #include <RTClib.h> #include <EEPROM.h> int pushVal = 0; int val; int val2; int addr = 0; RTC_DS3231 rtc; const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // lcd pins LiquidCrystal lcd(rs, en, d4, d5, d6, d7); #define getWellsoon 0 #define HELP_SCREEN 1 #define TIME_SCREEN 2 //bool pushPressed; //flag to keep track of push button state int pushpressed = 0; const int ledPin = LED_BUILTIN; // buzzer and led pin int ledState = LOW; int Signal = 0; int buzz = 13; int push1state, push2state, push3state, stopinState = 0; // int push1Flag, push2Flag, Push3Flag = false; // push button flags int push1pin = 9; int push2pin = 8; int push3pin = 7; int stopPin = A0; int screens = 0; // screen to show int maxScreen = 2; // screen count bool isScreenChanged = true; long previousMillis = 0; long interval = 500; // buzzing interval unsigned long currentMillis; long previousMillisLCD = 0; // for LCD screen update long intervalLCD = 2000; // Screen cycling interval unsigned long currentMillisLCD; // Set Reminder Change Time int buzz8amHH = 8; // HH - hours ##Set these for reminder time in 24hr Format int buzz8amMM = 00; // MM - Minute int buzz8amSS = 00; // SS - Seconds int buzz2pmHH = 14; // HH - hours int buzz2pmMM = 00; // MM - Minute int buzz2pmSS = 00; // SS - Seconds int buzz8pmHH = 20; // HH - hours int buzz8pmMM = 00; // MM - Minute int buzz8pmSS = 00; // SS - Seconds int nowHr, nowMin, nowSec; // to show current mm,hh,ss // All messeges void gwsMessege(){ // print get well soon messege lcd.clear(); lcd.setCursor(0, 0); lcd.print("Stay Healthy :)"); // Give some cheers lcd.setCursor(0, 1); lcd.print("Get Well Soon :)"); // wish } void helpScreen() { // function to display 1st screen in LCD lcd.clear(); lcd.setCursor(0, 0); lcd.print("Press Buttons"); lcd.setCursor(0, 1); lcd.print("for Reminder...!"); } void timeScreen() { // function to display Date and time in LCD screen DateTime now = rtc.now(); // take rtc time and print in display lcd.clear(); lcd.setCursor(0, 0); lcd.print("Time:"); lcd.setCursor(6, 0); lcd.print(nowHr = now.hour(), DEC); lcd.print(":"); lcd.print(nowMin = now.minute(), DEC); lcd.print(":"); lcd.print(nowSec = now.second(), DEC); lcd.setCursor(0, 1); lcd.print("Date: "); lcd.print(now.day(), DEC); lcd.print("/"); lcd.print(now.month(), DEC); lcd.print("/"); lcd.print(now.year(), DEC); } void setup() { Serial.begin(9600); // start serial debugging if (! rtc.begin()) { // check if rtc is connected Serial.println("Couldn't find RTC"); while (1); } if (rtc.lostPower()) { Serial.println("RTC lost power, lets set the time!"); } // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // uncomment this to set the current time and then comment in next upload when u set the time rtc.adjust(DateTime(2019, 1, 10, 7, 59, 30)); // manual time set lcd.begin(16, 2); lcd.clear(); lcd.setCursor(0, 0); lcd.print("Welcome To"); // print a messege at startup lcd.setCursor(0, 1); lcd.print("Circuit Digest"); delay(1000); pinMode(push1pin, INPUT); // define push button pins type pinMode(push2pin, INPUT); pinMode(push3pin, INPUT); pinMode(stopPin, INPUT); pinMode(ledPin, OUTPUT); delay(200); Serial.println(EEPROM.read(addr)); val2 = EEPROM.read(addr); // read previosuly saved value of push button to start from where it was left previously switch (val2) { case 1: Serial.println("Set for 1/day"); push1state = 1; push2state = 0; push3state = 0; pushVal = 1; break; case 2: Serial.println("Set for 2/day"); push1state = 0; push2state = 1; push3state = 0; pushVal = 2; break; case 3: Serial.println("Set for 3/day"); push1state = 0; push2state = 0; push3state = 1; pushVal = 3; break; } } void loop() { push1(); //call to set once/day push2(); //call to set twice/day push3(); //call to set thrice/day if (pushVal == 1) { // if push button 1 pressed then remind at 8am at8am(); //function to start uzzing at 8am } else if (pushVal == 2) { // if push button 2 pressed then remind at 8am and 8pm at8am(); at8pm(); //function to start uzzing at 8mm } else if (pushVal == 3) { // if push button 3 pressed then remind at 8am and 8pm at8am(); at2pm(); //function to start uzzing at 8mm at8pm(); } currentMillisLCD = millis(); // start millis for LCD screen switching at defined interval of time push1state = digitalRead(push1pin); // start reading all push button pins push2state = digitalRead(push2pin); push3state = digitalRead(push3pin); stopinState = digitalRead(stopPin); stopPins(); // call to stop buzzing changeScreen(); // screen cycle function } // push buttons void push1() { // function to set reminder once/day if (push1state == 1) { push1state = 0; push2state = 0; push3state = 0; // pushPressed = true; EEPROM.write(addr, 1); Serial.print("Push1 Written : "); Serial.println(EEPROM.read(addr)); // for debugging pushVal = 1; //save the state of push button-1 lcd.clear(); lcd.setCursor(0, 0); lcd.print("Reminder set "); lcd.setCursor(0, 1); lcd.print("for Once/day !"); delay(1200); lcd.clear(); } } void push2() { //function to set reminder twice/day if (push2state == 1) { push2state = 0; push1state = 0; push3state = 0; // pushPressed = true; EEPROM.write(addr, 2); Serial.print("Push2 Written : "); Serial.println(EEPROM.read(addr)); pushVal = 2; lcd.clear(); lcd.setCursor(0, 0); lcd.print("Reminder set "); lcd.setCursor(0, 1); lcd.print("for Twice/day !"); delay(1200); lcd.clear(); } } void push3() { //function to set reminder thrice/day if (push3state == 1) { push3state = 0; push1state = 0; push2state = 0; // pushPressed = true; EEPROM.write(addr, 3); Serial.print("Push3 Written : "); Serial.println(EEPROM.read(addr)); pushVal = 3; lcd.clear(); lcd.setCursor(0, 0); lcd.print("Reminder set "); lcd.setCursor(0, 1); lcd.print("for Thrice/day !"); delay(1200); lcd.clear(); } } void stopPins() { //function to stop buzzing when user pushes stop push button if (stopinState == 1) { // stopinState = 0; // pushPressed = true; pushpressed = 1; lcd.clear(); lcd.setCursor(0, 0); lcd.print("Take Medicine "); lcd.setCursor(0, 1); lcd.print("with Warm Water"); delay(1200); lcd.clear(); } } void startBuzz() { // function to start buzzing when time reaches to defined interval // if (pushPressed == false) { if (pushpressed == 0) { Serial.println("pushpressed is false in blink"); unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; // save the last time you blinked the LED Serial.println("Start Buzzing"); if (ledState == LOW) { // if the LED is off turn it on and vice-versa: ledState = HIGH; } else { ledState = LOW; } digitalWrite(ledPin, ledState); } } else if (pushpressed == 1) { Serial.println("pushpressed is true"); ledState = LOW; digitalWrite(ledPin, ledState); } } void at8am() { // function to start buzzing at 8am DateTime now = rtc.now(); if (int(now.hour()) >= buzz8amHH) { if (int(now.minute()) >= buzz8amMM) { if (int(now.second()) > buzz8amSS) { ///////////////////////////////////////////////////// startBuzz(); ///////////////////////////////////////////////////// } } } } void at2pm() { // function to start buzzing at 2pm DateTime now = rtc.now(); if (int(now.hour()) >= buzz2pmHH) { if (int(now.minute()) >= buzz2pmMM) { if (int(now.second()) > buzz2pmSS) { /////////////////////////////////////////////////// startBuzz(); ////////////////////////////////////////////////// } } } } void at8pm() { // function to start buzzing at 8pm DateTime now = rtc.now(); if (int(now.hour()) >= buzz8pmHH) { if (int(now.minute()) >= buzz8pmMM) { if (int(now.second()) > buzz8pmSS) { ///////////////////////////////////////////////////// startBuzz(); ///////////////////////////////////////////////////// } } } } //Screen Cycling void changeScreen() { //function for Screen Cycling // Start switching screen every defined intervalLCD if (currentMillisLCD - previousMillisLCD > intervalLCD) // save the last time you changed the display { previousMillisLCD = currentMillisLCD; screens++; if (screens > maxScreen) { screens = 0; // all screens over -> start from 1st } isScreenChanged = true; } // Start displaying current screen if (isScreenChanged) // only update the screen if the screen is changed. { isScreenChanged = false; // reset for next iteration switch (screens) { case getWellsoon: gwsMessege(); // get well soon message break; case HELP_SCREEN: helpScreen(); // instruction screen break; case TIME_SCREEN: timeScreen(); // to print date and time break; default: //NOT SET. break; } } } Video microcontroller-projects/speed-distance-and-angle-measurement-for-mobile-robots-using-arduino-and-lm393-h206

Speed, Distance and Angle Measurement for Mobile Robots using Arduino and LM393 Speed Sensor (H206)

to measure some vital parameters like Speed, Distance travelled and Angle of the robot using Arduino. With these parameters the robot will be able to know its real world status and can use it to navigate safely. display connected to Arduino. This projectjust helps you with measuring these parameters, once you are done with this you can use these parameters to operate your bot autonomously as required. Sounds interesting right? So let’s get started.

LM393 Speed Sensor Module (H206)

consists of an Infrared Light sensor integrated with a LM393 Voltage comparator IC hence the name LM393 Speed sensor. The module also consists of a grid plate which has to be mounted to the rotating shaft of the motor. All the components are labeled in below image. consists of an IR LED and a photo-transistor separated by a small gab. The entire sensor arrangement is placed in a black housing as shown above. The Grid plate consist of slots, the plate is arranged in between the gap of the Infrared Light Sensor in such a manner that the sensor can sense the gaps in grid plate. Each gap in the grid plate triggers the IR sensor when passing through the gap; these triggers are then converted into voltage signals using the comparator. The comparator is nothing but an LM393 IC from ON semiconductors. The module has three pins, two of which is used to power the module and one output pin is used to count the number of triggers.

H206 Sensor Mounting Arrangement

is a bit tricky. It can be mounted only to motors that have shaft protruded on both the side. One side of the shaft is connected to the wheel while the other side is used to mount the grid plate as shown above. to guide the robot about the obstacles. and give a try to measure rotational angle using them.

DIY Arduino LM393 Speed SensorRobotCircuit Diagram

The potentiometer connected to the LCD can be used to adjust the contrast of the LCD and the resistor is used to limit the current flowing to the backlight of the LCD. This 7.4V is supplied to the 12V pin of the Motor driver module. The voltage regulator on the motor driver module then converters the 7.4V to regulated +5V which is used to power the Arduino, LCD, Sensors and Joystick. to positive terminal of the motor. Hence we have pin 9 and 10 which are both PWM capable pins. The X and Y values form the joystick is read using the Analog pins A2 and A3 respectively. at the end of this page to know how the sensor was mounted. Now that the hardware part is completed let us get into the logics of how we will be measuring the speed, distance and single of the bot and then proceed to the programming section.

Logic behind Measuring Speed with LM393 speed sensormodule

From the sensor mounting set-up you should be aware that the LM393 speed sensormodule (H206)measures only the gaps present in the grid plate. While mounting it should made sure that the wheel (whose speed should be measured) and the grid plate rotates in the same speed. Like here, since we have mounted both the wheel and the plate on the same shaft they will both rotate with the same speed obviously. In our set-up we have mounted two sensors for each wheel to measure the angle of the bot. But if your aim is to measure only the speed and distance we can mount the sensor on any one wheel. The output of the sensor (trigger signals) will be most commonly connected to an external interrupt pin of a microcontroller. Every time the gap in the grid plate is detected an interrupt will be trigger and the code in the ISR (Interrupt service Routine) will be executed. If we are able to calculate the time interval between two such triggers we can calculate the speed of the wheel. value form the millis(). Time taken = current time – previous time timetaken = millis()-pevtime; //timetaken in millisec using the below formulae, where (1000/timetaken) gives the RPS (Revolutions per second) and it is multiplied by 60 to convert RPS to RPM (Revolutions per minute). rpm=(1000/timetaken)*60; using the below formulae provided we know the radius of the wheel. Velocity = 2π × RPS × radius of wheel. v = radius_of_wheel * rpm * 0.104 Note, the above formula is for calculating the velocity in m/s, if you want to calculate in km/hr then replace 0.0104 with 0.376. If you are curious to know how the value 0.104 was obtained then try simplifying the formula V = 2π × RPS × radius of wheel. So we wait for 40 interrupts before we actually calculate the speed of the wheel. The code for the same is shown below if(rotation>=40) { timetaken = millis()-pevtime; //timetaken in millisec rpm=(1000/timetaken)*60; //formulae to calculate rpm pevtime = millis(); rotation=0; } to check the difference in time and if it exceeds 500 milli seconds the value of velocity and rpm is forced to be zero. /*To drop to zero if vehicle stopped*/ if(millis()-dtime>500) //no inetrrupt found for 500ms { rpm= v = 0; // make rpm and velocity as zero dtime=millis(); }

Logic behind measuring the distance travelled by the wheel

Since we already know the radius of the wheel we can easily calculate the distance covered using the below formula Distance = 2πr * number of rotations distance = (2*3.141*radius_of_wheel) * (left_intr/40) Where the circumference of the wheel is calculated using the formula 2πr and then it is multiplied by the number of rotations made by the wheel.

Logic behind measuring the angle of the bot

There are many ways to determine the angel of the robot. Accelerometers and Gyroscopes are normally used to determine these values. But another cheap approach is to use the H206 sensor on both the wheels. This way we would know how many turns has each wheel made. The below figure illustrates how the angle is calculated. For instance if the Left wheel makes one complete rotation (80 interrupts) then the bot will turn 90° towards the left and similarly if the Right wheel makes one complete rotation (80 interrupts) then the bot will turn -90° towards the right. Now we know that if the Arduino detects 80 interrupts on one wheel then the bot has turned by 90° and based on which wheel we can tell if the bot has turned by positive (right) or negative (left). So the left and right angle can be calculated using the below formulae int angle_left = (left_intr % 360) * (90/80) ; int angle_right = (right_intr % 360) * (90/80) ; Where 90 is the angle covered when making an interrupt of 80. The resulting value is multiplied number interrupts. We have also used a modulus of 360 so that the resulting value never exceeds 36. Once we have calculated both the left and right angle the effective angle at which the bot is facing can be simply obtained by subtracting the left angle form the right angle. angle = angle_right - angle_left;

Arduino Robot Code

Do note that we also have to control the sped of the motor and hence we have to use the PWM pins on Arduino to control the motors. Here we have used the pin 8,9,10 and 11. #define LM_pos 9 // left motor #define LM_neg 8 // left motor #define RM_pos 10 // right motor #define RM_neg 11 // right motor #define joyX A2 #define joyY A3 , measure the value and enter it in meters as shown below. For my bot the radius was 0.033 meters but it could differ for you based on your bot. float radius_of_wheel = 0.033; //Measure the radius of your wheel and enter it here in cm will be executed accordingly. void setup() { rotation = rpm = pevtime = 0; //Initialize all variable to zero Serial.begin(9600); lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print("Bot Monitor"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print("-CircuitDigest "); //Intro Message line 2 delay(2000); lcd.clear(); lcd.print("Lt: Rt: "); lcd.setCursor(0, 1); lcd.print("S: D: A: "); pinMode(LM_pos, OUTPUT); pinMode(LM_neg, OUTPUT); pinMode(RM_pos, OUTPUT); pinMode(RM_neg, OUTPUT); digitalWrite(LM_neg, LOW); digitalWrite(RM_neg, LOW); attachInterrupt(digitalPinToInterrupt(2), Left_ISR, CHANGE); //Left_ISR is called when left wheel sensor is triggered attachInterrupt(digitalPinToInterrupt(3), Right_ISR, CHANGE);//Right_ISR is called when right wheel sensor is triggered } The variable rotation is incremented for every interrupt and then the above logic is used to calculate the speed. void Left_ISR() { left_intr++;delay(10); } void Right_ISR() { right_intr++; delay(10); rotation++; dtime=millis(); if(rotation>=40) { timetaken = millis()-pevtime; //timetaken in millisec rpm=(1000/timetaken)*60; //formulae to calculate rpm pevtime = millis(); rotation=0; } } Based on the value if joystick is moved we control the bot accordingly. The speed of the bot depends on how far the joystick is pushed. int xValue = analogRead(joyX); int yValue = analogRead(joyY); int acceleration = map (xValue, 500, 0, 0, 200); if (xValue<500) { analogWrite(LM_pos, acceleration); analogWrite(RM_pos, acceleration); } else { analogWrite(LM_pos, 0); analogWrite(RM_pos, 0); } if (yValue>550) analogWrite(RM_pos, 80); if (yValue<500) analogWrite(LM_pos, 100); and display it on the LCD using the below code. v = radius_of_wheel * rpm * 0.104; //0.033 is the radius of the wheel in meter distance = (2*3.141*radius_of_wheel) * (left_intr/40); int angle_left = (left_intr % 360) * (90/80) ; int angle_right = (right_intr % 360) * (90/80) ; angle = angle_right - angle_left; lcd.setCursor(3, 0); lcd.print(" "); lcd.setCursor(3, 0); lcd.print(left_intr); lcd.setCursor(11, 0); lcd.print(" "); lcd.setCursor(11, 0);lcd.print(right_intr); lcd.setCursor(2, 1); lcd.print(" "); lcd.setCursor(2, 1);lcd.print(v); lcd.setCursor(9, 1); lcd.print(" "); lcd.setCursor(9, 1);lcd.print(distance); lcd.setCursor(13, 1); lcd.print(" "); lcd.setCursor(13, 1);lcd.print(angle);

Testing the Arduino Robot for measuring Distance, Speed and Angle

Once your hardware is ready upload the code into your Arduino and use the joystick to move your bot. the speed of the bot, distance covered by it and the angle will be displayed in the LCD as shown below. The Angle of the bot is displayed at the end where 0° is for straight and it goes negative for anti-clockwise rotation and positive for clockwise rotation. for quick technical help. Code /* * Arduino Vehicle Speed, Distance and angle calculator */ /*-------defining pins------*/ #define LM_pos 9 // left motor #define LM_neg 8 // left motor #define RM_pos 10 // right motor #define RM_neg 11 // right motor #define joyX A2 #define joyY A3 #include <LiquidCrystal.h> const int rs = 14, en = 15, d4 = 4, d5 = 5, d6 = 6, d7 = 7; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7); int left_intr = 0; int right_intr = 0; int angle = 0; /*Hardware details*/ float radius_of_wheel = 0.033; //Measure the radius of your wheel and enter it here in cm volatile byte rotation; // variale for interrupt fun must be volatile float timetaken,rpm,dtime; float v; int distance; unsigned long pevtime; void setup() { rotation = rpm = pevtime = 0; //Initialize all variable to zero Serial.begin(9600); lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print("Vechile Monitor"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print("-CircuitDigest "); //Intro Message line 2 delay(2000); lcd.clear(); lcd.print("Lt: Rt: "); lcd.setCursor(0, 1); lcd.print("S: D: A: "); pinMode(LM_pos, OUTPUT); pinMode(LM_neg, OUTPUT); pinMode(RM_pos, OUTPUT); pinMode(RM_neg, OUTPUT); digitalWrite(LM_neg, LOW); digitalWrite(RM_neg, LOW); attachInterrupt(digitalPinToInterrupt(2), Left_ISR, CHANGE); //Left_ISR is called when left wheel sensor is triggered attachInterrupt(digitalPinToInterrupt(3), Right_ISR, CHANGE);//Right_ISR is called when right wheel sensor is triggered } void loop() { int xValue = analogRead(joyX); int yValue = analogRead(joyY); int acceleration = map (xValue, 500, 0, 0, 200); if (xValue<500) { analogWrite(LM_pos, acceleration); analogWrite(RM_pos, acceleration); } else { analogWrite(LM_pos, 0); analogWrite(RM_pos, 0); } if (yValue>550) analogWrite(RM_pos, 80); if (yValue<500) analogWrite(LM_pos, 100); /*To drop to zero if vehicle stopped*/ if(millis()-dtime>500) //no inetrrupt found for 500ms { rpm= v = 0; // make rpm and velocity as zero dtime=millis(); } v = radius_of_wheel * rpm * 0.104; //0.033 is the radius of the wheel in meter distance = (2*3.141*radius_of_wheel) * (left_intr/40); int angle_left = (left_intr % 360) * (90/80) ; int angle_right = (right_intr % 360) * (90/80) ; angle = angle_right - angle_left; lcd.setCursor(3, 0); lcd.print(" "); lcd.setCursor(3, 0); lcd.print(left_intr); lcd.setCursor(11, 0); lcd.print(" "); lcd.setCursor(11, 0);lcd.print(right_intr); lcd.setCursor(2, 1); lcd.print(" "); lcd.setCursor(2, 1);lcd.print(v); lcd.setCursor(9, 1); lcd.print(" "); lcd.setCursor(9, 1);lcd.print(distance); lcd.setCursor(13, 1); lcd.print(" "); lcd.setCursor(13, 1);lcd.print(angle); delay(100); } void Left_ISR() { left_intr++;delay(10); } void Right_ISR() { right_intr++; delay(10); rotation++; dtime=millis(); if(rotation>=40) { timetaken = millis()-pevtime; //timetaken in millisec rpm=(1000/timetaken)*60; //formulae to calculate rpm pevtime = millis(); rotation=0; } } Video microcontroller-projects/stm32-stm32f103c8-i2c-communication-tutorial

How to use I2C Communication in STM32 Microcontroller

and will communicate with the Arduino board using I2C bus.

STM32F103C8I2COverview

and STM32 is faster than Arduino. To learn more about I2C communication, refer our previous articles How to use I2C in Arduino: Communication between two Arduino Boards I2C Communication with PIC Microcontroller PIC16F877 Interfacing 16X2 LCD with ESP32 using I2C I2C communication with MSP430 Launchpad Interfacing LCD with NodeMCU without using I2C How to handle multi communications (I2C SPI UART) in single program of arduino

I2C pins in STM32F103C8

PB7 or PB9, PB11. : PB6 or PB8, PB10.

I2C pins in Arduino

A4 pin A5 pin

Components Required

STM32F103C8 Arduino Uno LED (2-Nos) Push Button (2-Nos) Resistors (4-Nos [10k-2 & 2.2k-2]) Breadboard Connecting Wires

Circuit Diagram and Connections

It requires only two wires.
B7A4SDA
B6A5SCL
GNDGNDGround
Don’t forget to connect the Arduino GND and STM32F103C8 GND together. Then connect a Pull down resistor of 10k to the push button pins of both the board separately. we will configure the STM32F103C8 as Master and Arduino as Slave. Both boards are attached with an LED & a push button separately. To demonstrate I2C communication in STM32, we control the master STM32 LED by using slave Arduino push button value and control slave Arduino LED by using master STM32F103C8 push button value. These values are sent via I2C communication bus.

I2C Programming in STM32

follow the link.

Master STM32 Programming Explanation

In Master STM32 let’s see what’s happening: 1. First of all we need to include the Wire library and softwire library for using I2C communication functions in STM32F103C8. #include<Wire.h> #include<SoftWire.h> We Start Serial Communication at Baud Rate 9600. Serial.begin(9600); Next we start the I2C communication at pin (B6,B7) Wire.begin(); First we get the data from the Slave Arduino so we use requestFrom() with the slave address 8 and we request one byte. Wire.requestFrom(8,1); byte a = Wire.read(); Depending upon the received value from slave the Master LED is turned ON or OFF by using digitalwrite at pin PA1 and also serial print is used to print value in serial monitor if (a==1) { digitalWrite(LED,HIGH); Serial.println("Master LED ON"); } else { digitalWrite(LED,LOW); Serial.println("Master LED OFF"); } Next we need to read the status of the pin PA0 that is the master STM32 push button. int pinvalue = digitalRead(buttonpin); Next send the pin value according to the logic, so we use if condition and then begin the transmission with slave arduino with 8 as address and then write the value according to the push button input value. if(pinvalue==HIGH) { x=1; } else { x=0; } Wire.beginTransmission(8); Wire.write(x); Wire.endTransmission();

Slave Arduino Programming Explanation

1. First of all we need to include the Wire library for using I2C communication functions. #include<Wire.h> We Start Serial Communication at Baud Rate 9600. Serial.begin(9600); Next start the I2C communication at pin (A4, A5) with slave address as 8. Here it is important to specify the slave address. Wire.begin(8); function call when Master request value from Slave. Wire.onReceive(receiveEvent); Wire.onRequest(requestEvent); 3. Next we have two functions one for request event and one for receive event void requestEvent() { int value = digitalRead(buttonpin); if (value == HIGH) { x=1; } else { x=0; } Wire.write(x); } logic to turn slave LED ON or OFF depending upon the value received. If received value is 1 then LED turns ON and for 0 LED turns OFF. void receiveEvent (int howMany) { byte a = Wire.read(); if (a == 1) { digitalWrite(LED,HIGH); Serial.println("Slave LED ON"); } else { digitalWrite(LED,LOW); Serial.println("Slave LED OFF"); } delay(500); } When we press the push button at Master STM32, the LED connected to Slave Ardiono turns ON (White). Now when we press the push button at Slave side, the LED connected to Master turns ON (Red) and when button is released LED turns OFF. When both the push buttons pressed simultanewolsy, then both the LEDs glow at the same time, and remains ON until the buttons are pressed Now you can interface any I2C sensor with STM32 board. Code

MasterSTM32Code

//I2C Master Code (STM32F103C8) //I2C Communication between STM32 and Arduino //Circuit Digest #include<Wire.h> #include<SoftWire.h> //Library for I2C Communication functions #define LED PA1 #define buttonpin PA0 int x = 0; void setup() { Serial.begin(9600); //Begins Serial Communication at 9600 baud rate pinMode(buttonpin,INPUT); //Sets pin PA0 as input pinMode(LED,OUTPUT); //Sets PA1 as Output Wire.begin(); //Begins I2C communication at pin (B6,B7) } void loop() { Wire.requestFrom(8,1); // request bytes from slave arduino(8) byte a = Wire.read(); // receive a byte from the slave arduino and store in variable a if (a==1) //Logic to turn Master LED ON (if received value is 1) or OFF (if received value is 0) { digitalWrite(LED,HIGH); Serial.println("Master LED ON"); } else { digitalWrite(LED,LOW); Serial.println("Master LED OFF"); } { int pinvalue = digitalRead(buttonpin); //Reads the status of the pin PA0 if(pinvalue==HIGH) //Logic for Setting x value (To be sent to slave Arduino) depending upon inuput from pin PA0 { x=1; } else { x=0; } Wire.beginTransmission(8); // starts transmit to device (8-Slave Arduino Address) Wire.write(x); // sends the value x to Slave Wire.endTransmission(); // stop transmitting delay(500); } }

SlaveArduinoCode

//I2C Slave Code (Arduino) //I2C Communication between STM32 and Arduino //Circuit Digest #include<Wire.h> //Library for I2C Communication functions #define LED 7 #define buttonpin 2 byte x =0; void setup() { Serial.begin(9600); //Begins Serial Communication at 9600 baud rate pinMode(LED,OUTPUT); //Sets pin 7 as output Wire.begin(8); // join i2c bus with its slave Address as 8 at pin (A4,A5) Wire.onReceive(receiveEvent); //Function call when Slave Arduino receives value from master STM32 Wire.onRequest(requestEvent); //Function call when Master STM32 request value from Slave Arduino } void loop() { delay(100); } void receiveEvent (int howMany) //This Function is called when Slave Arduino receives value from master STM32 { byte a = Wire.read(); //Used to read value received from master STM32 and store in variable a if (a == 1) //Logic to turn Slave LED ON (if received value is 1) or OFF (if received value is 0) { digitalWrite(LED,HIGH); Serial.println("Slave LED ON"); } else { digitalWrite(LED,LOW); Serial.println("Slave LED OFF"); } delay(500); } void requestEvent() //This Function is called when Master STM32 wants value from slave Arduino { int value = digitalRead(buttonpin); //Reads the status of the pin 2 if (value == HIGH) //Logic to set the value of x to send to master depending upon input at pin 2 { x=1; } else { x=0; } Wire.write(x); // sends one byte of x value to master STM32 } } Video microcontroller-projects/arduino-i2c-tutorial-communication-between-two-arduino

How to use I2C in Arduino: Communication between two Arduino Boards

Comparing I2C with SPI, I2C has only two wires while SPI uses four and I2C can have Multiple Master and Slave, while SPI can have only one master and multiple slaves. So there are more than one microcontroller in a project that need to be masters then I2C is used. I2C communication is generally used to communicate with Gyroscope, accelerometer, barometric pressure sensors, LED displays etc. connected to each of the Arduino. Here one Arduino will act as Master and another one will act as Slave. So let’s start with the introduction about I2C communication.

What is I2C Communication Protocol?

ᾮ It is normally denoted as I2C or I squared C or even as 2-wire interface protocol (TWI) at some places but it all means the same. I2C is a synchronous communication protocol meaning, both the devices that are sharing the information must share a common clock signal. It has only two wires to share information out of which one is used for the cock signal and the other is used for sending and receiving data.

How I2C Communication works?

The advantage of I2C communication is that more than one slave can be connected to a Master. The complete communication takes place through these two wires namely, Serial Clock (SCL) and Serial Data (SDA). Shares the clock signal generated by the master with the slave Sends the data to and from between the Master and slave. At any given time only the master will be able to initiate the communication. Since there is more than one slave in the bus, the master has to refer to each slave using a different address. When addressed only the slave with that particular address will reply back with the information while the others keep quit. This way we can use the same bus to communicate with multiple devices. In this case voltage shifters are used to match the voltage levels between two I2C buses. There are some set of conditions which frame a transaction. Initialization of transmission begins with a falling edge of SDA, which is defined as ‘STARTᾠcondition in below diagram where master leaves SCL high while setting SDA low. As shown in the above diagram below, The falling edge of SDA is the hardware trigger for the START condition. After this all devices on the same bus go into listening mode. In the same manner, rising edge of SDA stops the transmission which is shown as ‘STOPᾠcondition in above diagram, where the master leaves SCL high and also releases SDA to go HIGH. So rising edge of SDA stops the transmission. R/W bit indicates the direction of transmission of following bytes, if it is HIGH means the slave will transmit and if it is low means the master will transmit. clock cycle. So it is low it considered as ACK otherwise NACK.

Where to use I2C communication?

It is certainly reliable to an extent since it has a synchronised clock pulse to make it smart. This protocol is mainly used to communicate with sensor or other devices which has to send information to a master. It is very handy when a microcontroller has to communicate with many other slave modules using a minimum of only wires. If you are looking for a long range communication you should try RS232 and if you are looking for more reliable communication you should try the SPI protocol.

I2C in Arduino

The image below shows the I2C pins present in Arduino UNO.
I2C LinePin in Arduino
SDAA4
SCLA5
used in Arduino IDE. is included in the program for using the following functions for I2C communication. This library is used for making communication with I2C devices. This Initiate the Wire library and join theI2Cbus as a master or slave. Address: The 7-bit slave address is optional and if the address is not specified, it joins the bus as a master like this [Wire.begin()]. or was transmitted from a master to a slave. This function is used to write data to a slave or master device. is used in master. can be written as: Wire.write(value) value: a value to send as a single byte. Wire.write(string): string: a string to send as a series of bytes. Wire.write(data, length): data: an array of data to send as bytes length: the number of bytes to transmit. function. 7-bit address of the device is transmitted. function to send data to the master. 7. Wire.onReceive(); function to read the data sent from master. is used to read the data sent from the slave device. address: the 7-bit address of the device to request bytes from quantity: the number of bytes to request

Components Required

Arduino Uno (2-Nos) 16X2 LCD display module 10K Potentiometer (4-Nos) Breadboard Connecting Wires

Circuit Diagram

Working Explanation

attached to each other and use two potentiometers at both arduino to determine the sending values (0 to 127) from master to slave and slave to master by varying the potentiometer. (0 to 1023). Then these ADC values are further converted into (0 to 127) as we can send only 7-bit data through I2C communication. The I2C communication takes place through two wires at pin A4 & A5 of both arduino.

I2C Programming in Arduino

Master Arduino Programming Explanation

here. #include<Wire.h> #include<LiquidCrystal.h> LiquidCrystal lcd(2, 7, 8, 9, 10, 11); We Start Serial Communication at Baud Rate 9600. Serial.begin(9600); Next we start the I2C communication at pin (A4,A5) Wire.begin(); //Begins I2C communication at pin (A4,A5) Next we initialize LCD display module in 16X2 mode and display the welcome message and clear after five seconds. lcd.begin(16,2); //Initilize LCD display lcd.setCursor(0,0); //Sets Cursor at first line of Display lcd.print("Circuit Digest"); //Prints CIRCUIT DIGEST in LCD lcd.setCursor(0,1); //Sets Cursor at second line of Display lcd.print("I2C 2 ARDUINO"); //Prints I2C ARDUINO in LCD delay(5000); //Delay for 5 seconds lcd.clear(); //Clears LCD display First we need to get data from the Slave so we use requestFrom() with the slave address 8 and we request one byte Wire.requestFrom(8,1); The received value is read using Wire.read() byte MasterReceive = Wire.read(); Next we need to read the analog value from the master arduino POT attached to pin A0 int potvalue = analogRead(A0); We convert that value in terms of one byte as 0 to 127. byte MasterSend = map(potvalue,0,1023,0,127); Next we need to send those converted values so we begin the transmission with slave arduino with 8 address Wire.beginTransmission(8); Wire.write(MasterSend); Wire.endTransmission(); Next we display those received values from the slave arduino with a delay of 500 microseconds and we continuously receive and display those value. lcd.setCursor(0,0); //Sets Currsor at line one of LCD lcd.print(">> Master <<"); //Prints >> Master << at LCD lcd.setCursor(0,1); //Sets Cursor at line two of LCD lcd.print("SlaveVal:"); //Prints SlaveVal: in LCD lcd.print(MasterReceive); //Prints MasterReceive in LCD received from Slave Serial.println("Master Received From Slave"); //Prints in Serial Monitor Serial.println(MasterReceive); delay(500); lcd.clear();

Slave Arduino Programming Explanation

for using I2C communication functions and LCD library for using LCD functions. Also define LCD pins for 16x2 LCD. #include<Wire.h> #include<LiquidCrystal.h> LiquidCrystal lcd(2, 7, 8, 9, 10, 11); We Start Serial Communication at Baud Rate 9600. Serial.begin(9600); Next we start the I2C communication at pin (A4, A5) with slave address as 8. Here it is important to specify the slave address. Wire.begin(8); Next we need to call the function when Slave receives value from master and when Master request value from Slave Wire.onReceive(receiveEvent); Wire.onRequest(requestEvent); Next we initialize LCD display module in 16X2 mode and display the welcome message and clear after five seconds. lcd.begin(16,2); //Initilize LCD display lcd.setCursor(0,0); //Sets Cursor at first line of Display lcd.print("Circuit Digest"); //Prints CIRCUIT DIGEST in LCD lcd.setCursor(0,1); //Sets Cursor at second line of Display lcd.print("I2C 2 ARDUINO"); //Prints I2C ARDUINO in LCD delay(5000); //Delay for 5 seconds lcd.clear(); //Clears LCD display Next we have two functions one for request event and one for receive event When Master request value from slave this function will be executed. This function does take input value from the Slave POT and convert it in terms of 7-bit and send that value to master. void requestEvent() { int potvalue = analogRead(A0); byte SlaveSend = map(potvalue,0,1023,0,127); Wire.write(SlaveSend); } void receiveEvent (int howMany { SlaveReceived = Wire.read(); } We display the received value from master continuously in the LCD display module. void loop(void) { lcd.setCursor(0,0); //Sets Currsor at line one of LCD lcd.print(">> Slave <<"); //Prints >> Slave << at LCD lcd.setCursor(0,1); //Sets Cursor at line two of LCD lcd.print("MasterVal:"); //Prints MasterVal: in LCD lcd.print(SlaveReceived); //Prints SlaveReceived value in LCD received from Master Serial.println("Slave Received From Master:"); //Prints in Serial Monitor Serial.println(SlaveReceived); delay(500); lcd.clear(); } , here we have use two Arduinos to demonstrate not only sending of data but also receiving the data using I2C communication. So now you can interface any I2C sensor to Arduino. Code //I2C MASTER CODE //I2C Communication between Two Arduino //Circuit Digest //Pramoth.T #include<Wire.h> //Library for I2C Communication functions #include<LiquidCrystal.h> //Library for LCD display function LiquidCrystal lcd(2, 7, 8, 9, 10, 11); //Define LCD Module Pins (RS,EN,D4,D5,D6,D7) void setup() { lcd.begin(16,2); //Initilize LCD display lcd.setCursor(0,0); //Sets Cursor at first line of Display lcd.print("Circuit Digest"); //Prints CIRCUIT DIGEST in LCD lcd.setCursor(0,1); //Sets Cursor at second line of Display lcd.print("I2C 2 ARDUINO"); //Prints I2C ARDUINO in LCD delay(5000); //Delay for 5 seconds lcd.clear(); //Clears LCD display Serial.begin(9600); //Begins Serial Communication at 9600 baud rate Wire.begin(); //Begins I2C communication at pin (A4,A5) } void loop() { Wire.requestFrom(8,1); // request 1 byte from slave arduino (8) byte MasterReceive = Wire.read(); // receive a byte from the slave arduino and store in MasterReceive int potvalue = analogRead(A0); // Reads analog value from POT (0-5V) byte MasterSend = map(potvalue,0,1023,0,127); //Convert digital value (0 to 1023) to (0 to 127) Wire.beginTransmission(8); // start transmit to slave arduino (8) Wire.write(MasterSend); // sends one byte converted POT value to slave Wire.endTransmission(); // stop transmitting lcd.setCursor(0,0); //Sets Currsor at line one of LCD lcd.print(">> Master <<"); //Prints >> Master << at LCD lcd.setCursor(0,1); //Sets Cursor at line two of LCD lcd.print("SlaveVal:"); //Prints SlaveVal: in LCD lcd.print(MasterReceive); //Prints MasterReceive in LCD received from Slave Serial.println("Master Received From Slave"); //Prints in Serial Monitor Serial.println(MasterReceive); delay(500); lcd.clear(); } //I2C SLAVE CODE //I2C Communication between Two Arduino //CircuitDigest //Pramoth.T #include<Wire.h> //Library for I2C Communication functions #include<LiquidCrystal.h> //Library for LCD display function LiquidCrystal lcd(2, 7, 8, 9, 10, 11); //Define LCD Module Pins (RS,EN,D4,D5,D6,D7) byte SlaveReceived = 0; void setup() { lcd.begin(16,2); //Initilize LCD display lcd.setCursor(0,0); //Sets Cursor at first line of Display lcd.print("Circuit Digest"); //Prints CIRCUIT DIGEST in LCD lcd.setCursor(0,1); //Sets Cursor at second line of Display lcd.print("I2C 2 ARDUINO"); //Prints I2C ARDUINO in LCD delay(5000); //Delay for 5 seconds lcd.clear(); //Clears LCD display Serial.begin(9600); //Begins Serial Communication at 9600 baud rate Wire.begin(8); //Begins I2C communication with Slave Address as 8 at pin (A4,A5) Wire.onReceive(receiveEvent); //Function call when Slave receives value from master Wire.onRequest(requestEvent); //Function call when Master request value from Slave } void loop(void) { lcd.setCursor(0,0); //Sets Currsor at line one of LCD lcd.print(">> Slave <<"); //Prints >> Slave << at LCD lcd.setCursor(0,1); //Sets Cursor at line two of LCD lcd.print("MasterVal:"); //Prints MasterVal: in LCD lcd.print(SlaveReceived); //Prints SlaveReceived value in LCD received from Master Serial.println("Slave Received From Master:"); //Prints in Serial Monitor Serial.println(SlaveReceived); delay(500); lcd.clear(); } void receiveEvent (int howMany) //This Function is called when Slave receives value from master { SlaveReceived = Wire.read(); //Used to read value received from master and store in variable SlaveReceived } void requestEvent() //This Function is called when Master wants value from slave { int potvalue = analogRead(A0); // Reads analog value from POT (0-5V) byte SlaveSend = map(potvalue,0,1023,0,127); // Convert potvalue digital value (0 to 1023) to (0 to 127) Wire.write(SlaveSend); // sends one byte converted POT value to master } Video microcontroller-projects/arduino-spi-communication-tutorial

How to use SPI (Serial Peripheral Interface) in Arduino to Communication between two Arduino Boards

Serial communicationis the process of sendingdataonebitat a time, sequentially, over acommunication channelorbus. There are many types of serial communication like UART, CAN, USB, I2C, and SPI communication.

What is SPI?

is a serial communication protocol. SPI interface was found by Motorola in 1970. SPI has a full-duplex connection, which means that the data is sent and received simultaneously. That is a master can send data to a slave and a slave can send data to the master simultaneously. SPI is synchronous serial communication means the clock is required for communication purposes. SPI communication is previously explained in other microcontrollers: SPI Communication with PIC Microcontroller PIC16F877A Interfacing 3.5 inch Touch Screen TFT LCD with Raspberry Pi Programming AVR microcontroller with SPI pins Interfacing Nokia 5110 Graphical LCD with Arduino

Working of SPI

A SPI has a master/Slave communication by using four lines. A SPI can have only one master and can have multiple slaves. A master is usually a microcontroller and the slaves can be a microcontroller, sensors, ADC, DAC, LCD etc. MISO(Master in Slave Out) - The Slave line for sending data to the master. MOSI(Master Out Slave In) - The Master line for sending data to the peripherals. SCK(Serial Clock) - The clock pulses which synchronize data transmission generated by the master. SS(Slave Select) –Master can use this pin to enable and disable specific devices. we need to set the required device's Slave Select (SS) pin to LOW, so that it can communicate with the master. When it's high, it ignores the master. This allows you to have multiple SPI devices sharing the same MISO, MOSI, and CLK lines of master. As you can see in the above image there are four slaves in which the SCLK, MISO, MOSI are common connected to master and the SS of each slave is connected separately to individual SS pins (SS1, SS2, SS3) of master. By setting the required SS pin LOW a master can communicate with that slave.

SPI Pins in Arduino UNO

The image below shows the SPI pins present Arduino UNO (in red box).
MOSI11 or ICSP-4
MISO12 or ICSP-1
SCK13 or ICSP-3
SS10

Using SPI in Arduino

used in Arduino IDE. is included in the program for using the following functions for SPI communication. To Initialize the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high. To Set the SPI clock divider relative to the system clock. The available dividers are 2, 4, 8, 16, 32, 64 or 128. Dividers: SPI_CLOCK_DIV2 SPI_CLOCK_DIV4 SPI_CLOCK_DIV8 SPI_CLOCK_DIV16 SPI_CLOCK_DIV32 SPI_CLOCK_DIV64 SPI_CLOCK_DIV128 This function is called when a slave device receives data from the master. This function is used to simultaneous send and receive the data between master and slave. So now let’s start with practical demonstration of SPI protocol in Arduino. In this tutorial we will use two arduino one as master and other as slave. Both Arduino are attached with a LED & a push button separately. Master LED can be controlled by using slave Arduino’s push button and slave Arduino’s LED can be controlled by master Arduino’s push button using SPI communication protocol present in arduino.

Components Required for Arduino SPI communication

Arduino UNO (2) LED (2) Push Button (2) Resistor 10k (2) Resistor 2.2k (2) Breadboard Connecting Wires

ArduinoSPI Communication Circuit Diagram

The below circuit diagram shows how to use SPI on Arduino UNO, but you can follow the same procedure for Arduino Mega SPI Communication or Arduino nano SPI communication. Almost everything will remain the same except for the pin number. You have to check the pinout of Arduino nano or mega to find the Arduino nano SPI pins and Arduino Mega pins, once you have done that everything else will be the same. I have built the above-shown circuit over a breadboard, you can see the circuit set-up that I used for testing below.

How to Program Arduino for SPI Communication:

This tutorial has two programs one for master Arduino and other for slave Arduino. Complete programs for both sides are given at the end of this project.

Arduino SPIMasterProgramming Explanation

1. First of all we need to include the SPI library for using SPI communication functions. #include<SPI.h> 2. In void setup() We Start Serial Communication at Baud Rate 115200. Serial.begin(115200); Attach LED to pin 7 and Push button to pin 2 and set those pins OUTPUT and INPUT respectively. pinMode(ipbutton,INPUT); pinMode(LED,OUTPUT); Next we begin the SPI communication SPI.begin(); Next we set the Clockdivider for SPI communication. Here we have set divider 8. SPI.setClockDivider(SPI_CLOCK_DIV8); Then set the SS pin HIGH since we didn’t start any transfer to slave arduino. digitalWrite(SS,HIGH); 3. In void loop(): We read the status of the pushbutton pin connected to pin2 (Master Arduino) for sending those value to the slave Arduino. buttonvalue = digitalRead(ipbutton); Set Logic for Setting x value (To be sent to slave) depending upon input from pin 2 if(buttonvalue == HIGH) { x = 1; } else { x = 0; } Before sending the value we need to LOW the slave select value to begin the transfer to slave from master. digitalWrite(SS, LOW); Here comes the important step, in the following statement we send the push button value stored in Mastersend variable to the slave arduino and also receive value from slave that will be store in Mastereceive variable. Mastereceive=SPI.transfer(Mastersend); After that depending upon the Mastereceive value we will turn the Master Arduino LED ON or OFF. if(Mastereceive == 1) { digitalWrite(LED,HIGH); //Sets pin 7 HIGH Serial.println("Master LED ON"); } else { digitalWrite(LED,LOW); //Sets pin 7 LOW Serial.println("Master LED OFF"); } to view the result in Serial Motor of Arduino IDE. Check the Video at the end.

Arduino SPI Slave Programming Explanation

1. First of all we need to include the SPI library for using SPI communication functions. #include<SPI.h> 2. In void setup() We Start Serial Communication at Baud Rate 115200. Serial.begin(115200); Attach LED to pin 7 and Push button to pin2 and set those pins OUTPUT and INPUT respectively. pinMode(ipbutton,INPUT); pinMode(LED,OUTPUT); The important step here is the following statements pinMode(MISO,OUTPUT); The above statement sets MISO as OUTPUT (Have to Send data to Master IN). So data is sent via MISO of Slave Arduino. Now Turn on SPI in Slave Mode by using SPI Control Register SPCR |= _BV(SPE); Then turn ON interrupt for SPI communication. If a data is received from master the Interrupt Routine is called and the received value is taken from SPDR (SPI data Register) SPI.attachInterrupt(); The value from master is taken from SPDR and stored in Slavereceived variable. This takes place in following Interrupt Routine function. ISR (SPI_STC_vect) { Slavereceived = SPDR; received = true; } 3. Next in void loop () we set the Slave arduino LED to turn ON or OFF depending upon the Slavereceived value. if (Slavereceived==1) { digitalWrite(LEDpin,HIGH); //Sets pin 7 as HIGH LED ON Serial.println("Slave LED ON"); } else { digitalWrite(LEDpin,LOW); //Sets pin 7 as LOW LED OFF Serial.println("Slave LED OFF"); } Next we read the status of the Slave Arduino Push button and store the value in Slavesend to send the value to Master Arduino by giving value to SPDR register. buttonvalue = digitalRead(buttonpin); if (buttonvalue == HIGH) { x=1; } else { x=0; } Slavesend=x; SPDR = Slavesend; to view the result in Serial Motor of Arduino IDE. Check the Video at the end.

How does SPI work on Arduino? - Let's test it!

When push button at Master side is pressed, white LED at slave side turns ON. And when the push button at Slave side is pressed, Red LED at Master side turns ON. You can check out the video below to see the demonstration of Arduino SPI communication. If you have any questions please leave them in the comment section our use our forums. Code //SPI MASTER (ARDUINO) //SPI COMMUNICATION BETWEEN TWO ARDUINO //CIRCUIT DIGEST #include<SPI.h> //Library for SPI #define LED 7 #define ipbutton 2 int buttonvalue; int x; void setup (void) { Serial.begin(115200); //Starts Serial Communication at Baud Rate 115200 pinMode(ipbutton,INPUT); //Sets pin 2 as input pinMode(LED,OUTPUT); //Sets pin 7 as Output SPI.begin(); //Begins the SPI commnuication SPI.setClockDivider(SPI_CLOCK_DIV8); //Sets clock for SPI communication at 8 (16/8=2Mhz) digitalWrite(SS,HIGH); // Setting SlaveSelect as HIGH (So master doesnt connnect with slave) } void loop(void) { byte Mastersend,Mastereceive; buttonvalue = digitalRead(ipbutton); //Reads the status of the pin 2 if(buttonvalue == HIGH) //Logic for Setting x value (To be sent to slave) depending upon input from pin 2 { x = 1; } else { x = 0; } digitalWrite(SS, LOW); //Starts communication with Slave connected to master Mastersend = x; Mastereceive=SPI.transfer(Mastersend); //Send the mastersend value to slave also receives value from slave if(Mastereceive == 1) //Logic for setting the LED output depending upon value received from slave { digitalWrite(LED,HIGH); //Sets pin 7 HIGH Serial.println("Master LED ON"); } else { digitalWrite(LED,LOW); //Sets pin 7 LOW Serial.println("Master LED OFF"); } delay(1000); } //SPI SLAVE (ARDUINO) //SPI COMMUNICATION BETWEEN TWO ARDUINO //CIRCUIT DIGEST //Pramoth.T #include<SPI.h> #define LEDpin 7 #define buttonpin 2 volatile boolean received; volatile byte Slavereceived,Slavesend; int buttonvalue; int x; void setup() { Serial.begin(115200); pinMode(buttonpin,INPUT); // Setting pin 2 as INPUT pinMode(LEDpin,OUTPUT); // Setting pin 7 as OUTPUT pinMode(MISO,OUTPUT); //Sets MISO as OUTPUT (Have to Send data to Master IN SPCR |= _BV(SPE); //Turn on SPI in Slave Mode received = false; SPI.attachInterrupt(); //Interuupt ON is set for SPI commnucation } ISR (SPI_STC_vect) //Inerrrput routine function { Slavereceived = SPDR; // Value received from master if store in variable slavereceived received = true; //Sets received as True } void loop() { if(received) //Logic to SET LED ON OR OFF depending upon the value recerived from master { if (Slavereceived==1) { digitalWrite(LEDpin,HIGH); //Sets pin 7 as HIGH LED ON Serial.println("Slave LED ON"); }else { digitalWrite(LEDpin,LOW); //Sets pin 7 as LOW LED OFF Serial.println("Slave LED OFF"); } buttonvalue = digitalRead(buttonpin); // Reads the status of the pin 2 if (buttonvalue == HIGH) //Logic to set the value of x to send to master { x=1; }else { x=0; } Slavesend=x; SPDR = Slavesend; //Sends the x value to master via SPDR delay(1000); } } Video microcontroller-projects/build-an-arduino-smart-watch-by-interfacing-oled-display-with-android-phone

Build a Smart Watch by Interfacing OLED Display with Android Phone using Arduino

and can be further extended to display incoming calls, messages and many more on OLED display. Bluetooth module HC-05 can also be used in place of HC-06.

Hardware Required

128×64 OLED display Module (SSD1306) Arduino ( we have used Arduino Pro Mini. But we can use any Arduino Board) Bluetooth HC05/HC06 Connecting Wires 3.7v Li-On Battery Jumper

Getting to know about OLED Displays

This Display can only work with the I2C mode. VCC -> 3.3v GND -> GND SDA -> SDA (Physical pin 3) SCL -> SCL (Physical pin 5 OLED looks very cool and can be easily interfaced with other microcontrollers to build some interesting projects: Interfacing SSD1306 OLED Display with Raspberry Pi Interfacing SSD1306 OLED Display with Arduino Internet Clock using ESP32 and OLED Display Automatic AC Temperature Controller using Arduino, DHT11 and IR Blaster

Circuit Diagram

is simple and is shown below is the compact and light weight battery, and is the perfect choice for wearable devices. And here we also make something wearable in this project like a simple smartwatch, which can be synced with your smartphone. Now one question arises about power supply is that here all the modules are working on 3.3v but li-ion battery is giving 3.7v which may damage the modules. So to solve this problem we have applied battery’s 3.7v supply to a raw pin of Arduino pro mini which can convert that voltage to 3.3v.

Android App for sending data to Arduino over Bluetooth

So just download and install this app in your Android Smart phone and then enable the Bluetooth and pair the HC-06 module with your phone. It may ask for passcode to pair the HC-06 bluetooth module, default passcode is 1234 or 0000. Now open the OLED app and select paired Bluetooth device HC-06, as shown in the below image: will display the data fetched from the android phone as shown below:

Programming Arduino for OLED Smart Watch

is given at the end of this project here we have explained few parts of code. First download and the Adafruit Library and the GFX library from Github using the links below Adafruit Library GFX Graphics Library Then start with including all the required libraries #include<SoftwareSerial.h> SoftwareSerial Serial1(10, 11); #include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include "Adafruit_SSD1306.h" #define OLED_RESET 4 Adafruit_SSD1306 display(OLED_RESET); After this we have defined some macros and variables for different operations. #define NUMFLAKES 10 #define XPOS 0 #define YPOS 1 #define DELTAY 2 #define LOGO16_GLCD_HEIGHT 16 #define LOGO16_GLCD_WIDTH 16 String str = ""; byte h = 0; byte m = 0; byte S = 0; String dmy, time, network, battery, inNumber, s; byte centerX = 24; byte centerY = 39; byte Radius = 24; double RAD = 3.141592 / 180; double LR = 89.99; void showTimeAnalog(int center_x, int center_y, double pl1, double pl2, double pl3) { double x1, x2, y1, y2; x1 = center_x + (Radius * pl1) * cos((6 * pl3 + LR) * RAD); y1 = center_y + (Radius * pl1) * sin((6 * pl3 + LR) * RAD); x2 = center_x + (Radius * pl2) * cos((6 * pl3 - LR) * RAD); y2 = center_y + (Radius * pl2) * sin((6 * pl3 - LR) * RAD); display.drawLine((int)x1, (int)y1, (int)x2, (int)y2, WHITE); } void digitalClock() { display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(60, 20); display.println(dmy); display.setTextSize(2); display.setCursor(60, 30); display.println(time); display.display(); delay(2000); } using the function below. void Battery() { display.clearDisplay(); display.setTextSize(2); display.setTextColor(WHITE); display.setCursor(20, 0); display.print("Bat:"); display.print(battery); display.print("%"); display.drawRect(14, 20, 80, 40, WHITE); display.drawRect(94, 30, 10, 20, WHITE); display.fillRect(14, 20, (int)(8 * (battery.toInt()) / 10), 40, WHITE); display.display(); delay(2000); } as well. void Network() { display.clearDisplay(); display.drawLine(5, 15, 25, 15, WHITE); display.drawLine(5, 15, 14, 30, WHITE); display.drawLine(25, 15, 17, 30, WHITE); display.fillRect(14, 15, 4, 40, WHITE); int net = network.toInt() / 20; int x1 = 24, y1 = 50, x2 = 4, y2 = 5; ....... ..... function, we have initialiase all communications and modules that we have used in this project. void setup() { Serial.begin(9600); display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3D (for the 128x64) display.clearDisplay(); Serial1.begin(9600); Serial1.println("System Ready"); } function, we have received data from android mobile and decoded that data and sent them to OLED display. void loop(){ Serial1.println("1234"); delay(1000); while (Serial1.available() > 0){ char ch = Serial1.read(); str += ch; if (ch == '$'){ dmy = str.substring(str.indexOf("#") + 1, str.indexOf(" ")); time = str.substring(str.indexOf(" ") + 1, str.indexOf(",") - 3); network = str.substring(str.indexOf(",") + 1, str.indexOf(",,")); battery = str.substring(str.indexOf(",,") + 2, str.indexOf(",,,")); inNumber = str.substring(str.indexOf(",,,") + 3, str.indexOf("$")); s = time.substring(time.indexOf(" ") + 1, time.indexOf(" ") + 3); h = s.toInt(); s = time.substring(time.indexOf(" ") + 4, time.indexOf(" ") + 6); m = s.toInt(); s = time.substring(time.indexOf(" ") + 7, time.indexOf(" ") + 9); S = s.toInt(); str = "";} } display.clearDisplay(); display.drawCircle(centerX, centerY, Radius, WHITE); showTimeAnalog(centerX, centerY, 0.1, 0.5, h * 5 + (int)(m * 5 / 60)); showTimeAnalog(centerX, centerY, 0.1, 0.78, m); // showTimePin(centerX, centerY, 0.1, 0.9, S); digitalClock(); Battery(); Network(); } wirelessly and can send or sync whatever data we want from the smart phone to OLED. Code #include<SoftwareSerial.h> SoftwareSerial Serial1(10, 11); #include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include "Adafruit_SSD1306.h" #define OLED_RESET 4 Adafruit_SSD1306 display(OLED_RESET); #define NUMFLAKES 10 #define XPOS 0 #define YPOS 1 #define DELTAY 2 #define LOGO16_GLCD_HEIGHT 16 #define LOGO16_GLCD_WIDTH 16 String str = ""; byte h = 0; byte m = 0; byte S = 0; String dmy, time, network, battery, inNumber, s; byte centerX = 24; byte centerY = 39; byte Radius = 24; double RAD = 3.141592 / 180; double LR = 89.99; void showTimeAnalog(int center_x, int center_y, double pl1, double pl2, double pl3) { double x1, x2, y1, y2; x1 = center_x + (Radius * pl1) * cos((6 * pl3 + LR) * RAD); y1 = center_y + (Radius * pl1) * sin((6 * pl3 + LR) * RAD); x2 = center_x + (Radius * pl2) * cos((6 * pl3 - LR) * RAD); y2 = center_y + (Radius * pl2) * sin((6 * pl3 - LR) * RAD); display.drawLine((int)x1, (int)y1, (int)x2, (int)y2, WHITE); } void digitalClock() { display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(60, 20); display.println(dmy); display.setTextSize(2); display.setCursor(60, 30); display.println(time); display.display(); delay(2000); } void Battery() { display.clearDisplay(); display.setTextSize(2); display.setTextColor(WHITE); display.setCursor(20, 0); display.print("Bat:"); display.print(battery); display.print("%"); display.drawRect(14, 20, 80, 40, WHITE); display.drawRect(94, 30, 10, 20, WHITE); display.fillRect(14, 20, (int)(8 * (battery.toInt()) / 10), 40, WHITE); display.display(); delay(2000); } void Network() { display.clearDisplay(); display.drawLine(5, 15, 25, 15, WHITE); display.drawLine(5, 15, 14, 30, WHITE); display.drawLine(25, 15, 17, 30, WHITE); display.fillRect(14, 15, 4, 40, WHITE); int net = network.toInt() / 20; int x1 = 24, y1 = 50, x2 = 4, y2 = 5; for (int i = 1; i <= net; i++) { display.fillRect(x1, y1, x2, y2, WHITE); x1 += 10; y1 -= 5; y2 += 10; y2 -= 5; } display.setTextSize(3); display.setTextColor(WHITE); display.setCursor(80, 34); display.print(network); display.setTextSize(1); display.setCursor(117, 44); display.println("%"); display.display(); delay(2000); } void setup() { Serial.begin(9600); display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3D (for the 128x64) display.clearDisplay(); Serial1.begin(9600); Serial1.println("System Ready"); } void loop(){ Serial1.println("1234"); delay(1000); while (Serial1.available() > 0){ char ch = Serial1.read(); str += ch; if (ch == '$'){ dmy = str.substring(str.indexOf("#") + 1, str.indexOf(" ")); time = str.substring(str.indexOf(" ") + 1, str.indexOf(",") - 3); network = str.substring(str.indexOf(",") + 1, str.indexOf(",,")); battery = str.substring(str.indexOf(",,") + 2, str.indexOf(",,,")); inNumber = str.substring(str.indexOf(",,,") + 3, str.indexOf("$")); s = time.substring(time.indexOf(" ") + 1, time.indexOf(" ") + 3); h = s.toInt(); s = time.substring(time.indexOf(" ") + 4, time.indexOf(" ") + 6); m = s.toInt(); s = time.substring(time.indexOf(" ") + 7, time.indexOf(" ") + 9); S = s.toInt(); str = "";} } display.clearDisplay(); display.drawCircle(centerX, centerY, Radius, WHITE); showTimeAnalog(centerX, centerY, 0.1, 0.5, h * 5 + (int)(m * 5 / 60)); showTimeAnalog(centerX, centerY, 0.1, 0.78, m); // showTimePin(centerX, centerY, 0.1, 0.9, S); digitalClock(); Battery(); Network(); } Video microcontroller-projects/arduino-waveform-generator

DIY Waveform Generator using Arduino

and the Dual mode power supply. Do note that this generator is not of industrial grade and cannot be used for serious testing. But other than that it will come in handy for all hobby projects and you need not wait in weeks for the shipment to arrive. Also what’s more fun than using a device, that we built on our own.

Materials Required

Arduino Nano 16*2 Alphanumeric LCD display Rotary Encoder Resistor(5.6K,10K) Capacitor (0.1uF) Perf board, Bergstik Soldering Kit

Circuit Diagram

which will help us to set the frequency. The complete set-up is powered by the USB port of the Arduino itself. The connections which I used previously didn’t turn out to work dues to some reasons which we will discuss later in this article. Hence I had to mess up with the wiring a bit by changing the pin order. Anyhow, you will not have any such issues as it is all sorted out, just follow the circuit carefully to know which pin is connect to what. You can also refer the below table to verify your connections.
Arduino PinConnected to
D14Connected to RS of LCD
D15Connected to RN of LCD
D4Connected to D4 of LCD
D3Connected to D5 of LCD
D6Connected to D6 of LCD
D7Connected to D7 of LCD
D10Connect to Rotary Encoder 2
D11Connect to Rotary Encoder 3
D12Connect to Rotary Encoder 4
D9Outputs square wave
D2Connect to D9 of Arduino
D5Outputs SPWM then converted to sine
, the frequency of this has to be related with PWM frequency so we provide this PWM signal to pin D2 to act as an interrupt and then use the ISR to control the frequency of the since wave. You can build the circuit on a breadboard or even get a PCB for it. But I decided to solder it on a Perf board to get the work done fast and make it reliable for long term use. My board looks like this once all the connections are complete. If you want to know more on how the PWM and Sine wave is produced with Arduino read the following paragraphs, else you can scroll down directly to the Programming Arduino section.

Producing Square Wave with Variable Frequency

We will discuss more about this library in the coding section. There are some drawbacks with this library as well, because the library alters the default Timer 1 and Timer 2 settings in Arduino. Hence you will no longer be able to use servo library or any other timer related library with your Arduino. Also the analog write function on pins 9,10,11 & 13 uses Timer 1 and Timer 2 hence you will not be able to produce SPWM on those pins. on those pins. Initially it took some time for me to figure this out and that is why the wiring is messed up a bit. , but to change the frequency of waveform you have to replace Resistor or capacitor, and it will hard to get the required frequency.

Producing Sine Wave using Arduino

As we know microcontrollers are Digital devices and they cannot produce Sine wave by mere coding. But there two popular ways of obtaining a sine wave from a microcontroller one is by utilizing a DAC and the other is by creating a SPWM. Unfortunately Arduino boards (except Due) does not come with a built-in DAC to produce sine wave, but you can always build your own DAC using the simple R2R method and then use it to produce a decent sine wave. But to reduce the hardware work I decided to use the later method of creating a SPWM signal and then converting it to Sine wave. This signal is very much similar to the PWM, but for an SPWM signal the duty cycle is controlled in such a manner to obtain an average voltage similar to that of a sine wave. For example, with 100% duty cycle the average output voltage will be 5V and for 25% we will have 1.25V thus controlling the duty cycle we can get pre-defined variable average voltage which is nothing but a sine wave. This technique is commonly used in Inverters. In the above image, the blue signal is the SPWM signal. Notice that the duty cycle of the wave is varied from 0% to 100% and then back to 0%. The graph is plotted for -1.0 to +1.0V but in our case, since we are using an Arduino the scale will be form 0V to 5V. We will learn how to produce SPWM with Arduino in the programming section below. r which comprises of an Inductor and Capacitor. However in our circuit, we will not be using the sine wave to power anything. I simply wanted to create from the generated SPWM signal so I went with a simple RC-Filter. You can also try a LC-Filter for better results but I chose RC for simplicity. The value of my resistor is 620 Ohms and the capacitor is 10uF. The above image shows the SPWM signal (Yellow) from the pin 5 and the sine wave (Blue) which was obtained after passing it through a RC-Filter.

Adding the Arduino PWM Frequency Library

The Arduino Frequency Library can be downloaded by clicking on the link below. Arduino PWM Frequency Library Paste the PWM folder into the libraries folder. Sometimes you might already have a PWM folder in there, in that case make sure you replace the old one with this new one.

Programming Arduino for Waveform Generator

for this project can be found at the bottom of this page. You can use the code as such, but make sure you have added the variable frequency library for Arduino IDE as discussed above else you will get compile time error. In this section let’s look in to the code to understand what is happening. This frequency should be set using the rotary encoder and the value should also be displayed in the 16*2 LCD. Once the PWM signal is created on pin 9 it will create an interrupt on pin 2 since we have shorted both the pins. Using this interrupt we can control the frequency of the SPWM signal which is generated on pin 5. The liquid crystal library is in-built in Arduino and we just installed the PWM library. #include <PWM.h> //PWM librarey for controlling freq. of PWM signal #include <LiquidCrystal.h> You can leave this undisturbed if you have followed the circuit diagram above. const int rs = 14, en = 15, d4 = 4, d5 = 3, d6 = 6, d7 = 7; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7); const int Encoder_OuputA = 11; const int Encoder_OuputB = 12; const int Encoder_Switch = 10; const int signal_pin = 9; const int Sine_pin = 5; const int POT_pin = A2; int Previous_Output; int multiplier = 1; double angle = 0; double increment = 0.2; int32_t frequency; //frequency to be set int32_t lower_level_freq = 1; //Lowest possible freq value is 1Hz int32_t upper_level_freq = 100000; //Maximum possible freq is 100KHz We also display an intro message during the boot just to make sure things are working. lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print("Signal Generator"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print("-CircuitDigest "); //Intro Message line 2 delay(2000); lcd.clear(); lcd.print("Freq:00000Hz"); lcd.setCursor(0, 1); lcd.print("Inc. by: 1 "); Serial.begin(9600); //Serial for debugging //pin Mode declaration pinMode (Encoder_OuputA, INPUT); pinMode (Encoder_OuputB, INPUT); pinMode (Encoder_Switch, INPUT); Once this function is called the default timer settings of Arduino will be altered. InitTimersSafe(); //Initialize timers without disturbing timer 0 attachInterrupt(0,generate_sine,CHANGE); If you are new here I would recommend you to fall back to that tutorial and then get back here. is used to set the frequency of our signal pin that is pin 9. pwmWriteHR(signal_pin, 32768); //Set duty cycle to 50% by default -> for 16-bit 65536/2 = 32768 SetPinFrequencySafe(signal_pin, frequency); You can also try with the lookup table method if you are interested. The sin() returns a variable value (decimal) between -1 to +1 and this when plotted against time will give us a sine wave. Now all we have to do is convert this value of -1 to +1 into 0 to 255 and feed it to our analog Write function. For which I have multiplied it with 255 just to ignore the decimal point and then used the map function to convert the value from -255 to +255 into 0 to +255. Finally this value is written to pin 5 using the analog write function. The value of angle is incremented by 0.2 every time the ISR is called this help us in controlling the frequency of the sine wave double sineValue = sin(angle); sineValue *= 255; int plot = map(sineValue, -255, +255, 0, 255); Serial.println(plot); analogWrite(Sine_pin,plot); angle += increment;

Testing the Arduino Function Generator on Hardware

Build your hardware as per the circuit diagram and upload the code given at the bottom of this page. Now, you are all set to test your project. It would be a lot easier if you have a DSO (Oscilloscope) but you can also test it with an LED since the frequency range is very high. Connect the probe to the Square wave and sine wave pin of the circuit. Use two LEDs on these two pins if you do not have a scope. Power up the circuit and you should be greeted with the introductory message on the LCD. Then vary the Rotary encoder and set the required frequency you should be able to observe the square wave and sine wave on your scope as shown below. If you are using an LED you should notice the LED blinking at different intervals based on the frequency you have set. for other technical help. Code #include <PWM.h> //PWM librarey for controlling freq. of PWM signal #include <LiquidCrystal.h> const int rs = 14, en = 15, d4 = 4, d5 = 3, d6 = 6, d7 = 7; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7); int Encoder_OuputA = 11; int Encoder_OuputB = 12; int Encoder_Switch = 10; int Previous_Output; int multiplier = 1; double angle = 0; double increment = 0.2; const int signal_pin = 9; const int Sine_pin = 5; const int POT_pin = A2; int32_t frequency; //frequency to be set int32_t lower_level_freq = 1; //Lowest possible freq value is 1Hz int32_t upper_level_freq = 100000; //Maximum possible freq is 100KHz void setup() { lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print("Signal Generator"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print("-CircuitDigest "); //Intro Message line 2 delay(2000); lcd.clear(); lcd.print("Freq:00000Hz"); lcd.setCursor(0, 1); lcd.print("Inc. by: 1 "); Serial.begin(9600); //Serial for debugging InitTimersSafe(); //Initialize timers without disturbing timer 0 //pin Mode declaration pinMode (Encoder_OuputA, INPUT); pinMode (Encoder_OuputB, INPUT); pinMode (Encoder_Switch, INPUT); Previous_Output = digitalRead(Encoder_OuputA); //Read the inital value of Output A attachInterrupt(0,generate_sine,CHANGE); } void loop() { if (digitalRead(Encoder_OuputA) != Previous_Output) { if (digitalRead(Encoder_OuputB) != Previous_Output) { frequency = frequency + multiplier; // Serial.println(frequency); pwmWriteHR(signal_pin, 32768); //Set duty cycle to 50% by default -> for 16-bit 65536/2 = 32768 SetPinFrequencySafe(signal_pin, frequency); lcd.setCursor(0, 0); lcd.print("Freq: Hz"); lcd.setCursor(5, 0); lcd.print(frequency); } else { frequency = frequency - multiplier; // Serial.println(frequency); pwmWriteHR(signal_pin, 32768); //Set duty cycle to 50% by default -> for 16-bit 65536/2 = 32768 SetPinFrequencySafe(signal_pin, frequency); lcd.setCursor(0, 0); lcd.print("Freq: Hz"); lcd.setCursor(5, 0); lcd.print(frequency); } } if (digitalRead(Encoder_Switch) == 0) { multiplier = multiplier * 10; if (multiplier>1000) multiplier=1; // Serial.println(multiplier); lcd.setCursor(0, 1); lcd.print("Cng. by: "); lcd.setCursor(8, 1); lcd.print(multiplier); delay(500); while(digitalRead(Encoder_Switch) == 0); } Previous_Output = digitalRead(Encoder_OuputA); } void generate_sine() { double sineValue = sin(angle); sineValue *= 255; int plot = map(sineValue, -255, +255, 0, 255); Serial.println(plot); analogWrite(Sine_pin,plot); angle += increment; if (angle > 180) angle =0; } Video microcontroller-projects/how-to-use-bluetooth-with-matlab-for-wireless-communication

How to use Bluetooth with MATLAB for Wireless Communication

Bluetooth is the simplest and most popular protocol for short range wireless communication in embedded systems. Bluetooth is not only used for transferring the data from one device to another but also used to control the devices wirelessly. Almost every electronic gadget has Bluetooth support now days so it is wise choice to have Bluetooth control option in your embedded application. You can further explore more MATLAB Projects: Serial Communication between MATLAB and Arduino DC Motor Control Using MATLAB and Arduino Stepper Motor Control using MATLAB and Arduino Getting Started with Image Processing using MATLAB

Components Required

MATLAB installed Laptop (Preference: R2016a or above versions) Arduino UNO Bluetooth Module (HC-05) LED (any color) Resistor (330 ohm) Jumper Wires , check the following articles. Bluetooth Controlled Servo Motor using Arduino Voice Controlled LEDs using Arduino and Bluetooth Cell Phone Controlled AC using Arduino and Bluetooth

Circuit Diagram

is given below:

Bluetooth Communication using MATLAB Command Window

to connect HC-05 connected with Arduino. First we have to code the Arduino to read the serial incoming data coming from the MATLAB (using Laptop’s Bluetooth). that can be controlled from the LAPTOP using MATLAB. and then start coding in MATLAB Command Window. #include <SoftwareSerial.h> int TxD; int RxD; int data; SoftwareSerial bluetooth(TxD, RxD); void setup() { Serial.begin(9600); bluetooth.begin(9600); } void loop() { if(bluetooth.available() > 0) { data = bluetooth.read(); Serial.print(data); Serial.print("\n"); if(data == '1') { digitalWrite(11, HIGH); } else if(data == '0') { digitalWrite(11, LOW); } } } Then, copy and paste the below MATLAB code in the Command window for Bluetooth communication between MATLAB and Arduino. instrhwinfo('Bluetooth','HC-05'); bt = Bluetooth('HC-05', 1); fopen(bt); is used to turn OFF the LED by sending ᾰᾠto the Arduino. Now, if you want to turn ON the LED just send ᾱᾠinstead of ᾰᾠusing the below command. fprintf(bt,'1'); To check the information about the available hardware, use below command instrhwinfo('type','Name of device'); To open the bluetooth port, below command in used fopen(bt);

Bluetooth Communication using MATLAB GUI

to turn on, turn off and blink the LED connected to the Arduino. Data will be sent via bluetooth from MATLAB to HC-05 on clicking on those graphical buttons. Arduino contains the code to receive the Bluetooth transmitted data from MATLAB to HC-05 and controlling the LED according to data received. Arduino code will remain same as previous one, only difference is that, previously we were sending data ᾱᾠand ᾰᾠthrough command window of MATLAB, and now the same data will be sent on clicking on three graphical buttons. guide as shown in below image, as shown below, To resize or to change the shape of the pushbuttons, just click on it and you will be able to drag the corners of the button. By double-clicking on pushbutton you can change the color, string and tag of that particular button. We have customized three pushbuttons as shown in below picture. , using which you cancustomize the buttons as per your requirement. Below are some tweaks we did for controlling the LED connected with Arduino. Copy and paste the below code on line no. 74 to setup or connect the MATLAB to the Laptop’s Bluetooth. clear All; global bt; instrhwinfo('Bluetooth','HC-05'); bt = Bluetooth('HC-05', 1); fopen(bt); is used to open the Bluetooth port for transmitting data. Now, when you scroll down, you will see that there are three functions created for three pushbuttons in the GUI. Now write the code in the functions according to the task you want to perform on click. pin HIGH. global bt; fprintf(bt,'1'); pin LOW. global bt; fprintf(bt,'0'); loop is used to blink the LED 10 times. global bt; for i = 1:10 fprintf(bt,'1'); pause(0.5); fprintf(bt,'0'); pause(0.5); end After completing with MATLAB GUI coding and setup the hardware according to circuit diagram, just click on the run button to run the edited code in .m file. MATLAB may take few seconds to respond, do not click on any GUI button until MATLABshows BUSY indication, which you can see at the left bottom corner of the screen as shown below, or you can use the code given below. Code #include <SoftwareSerial.h> int TxD; int RxD; int data; SoftwareSerial bluetooth(TxD, RxD); void setup() { Serial.begin(9600); bluetooth.begin(9600); } void loop() { if(bluetooth.available() > 0) { data = bluetooth.read(); if(data == '1') digitalWrite(11, HIGH); else if(data == '0') digitalWrite(11, LOW); } } instrhwinfo('Bluetooth','HC-05'); bt = Bluetooth('HC-05', 1); fopen(bt); fprintf(bt,'1'); fprintf(bt,'0'); gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @bluetooth_with_MATLAB_OpeningFcn, ... 'gui_OutputFcn', @bluetooth_with_MATLAB_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end function bluetooth_with_MATLAB_OpeningFcn(hObject, eventdata, handles, varargin) function varargout = bluetooth_with_MATLAB_OutputFcn(hObject, eventdata, handles) varargout{1} = handles.output; clear All; global bt; instrhwinfo('Bluetooth','HC-05'); bt = Bluetooth('HC-05', 1); fopen(bt); function led_on_Callback(hObject, eventdata, handles) global bt; fprintf(bt,'1'); function led_off_Callback(hObject, eventdata, handles) global bt; fprintf(bt,'0'); function blink_Callback(hObject, eventdata, handles) global bt; for i = 1:10 fprintf(bt,'1'); pause(0.5); fprintf(bt,'0'); pause(0.5); end Video microcontroller-projects/how-to-burn-bootloader-in-atmega328p-and-program-using-arduino-ide

How to Burn Arduino Bootloader in Atemga328 IC and Program it using Arduino IDE

But in industrial or consumer products its not good idea to use the complete Arduino board, so we can use standalone Atmega328 IC, which can be programmed with Arduino IDE but without using Arduino board. by replicating it on PCB.

Components Required

Atmega 328 IC Breadboard LM7805 16 MHz Crystal 22pF ceramic capacitors (2) 10uF capacitor(2) 10 K resistor 1k resistor Jumper wires Optionally, you can also use 3.3v voltage regulator LM1117-3.3v to include 3.3v rail in your circuit.

Pin Diagram of Atmega328

Circuit Diagram

Circuit Diagram for replicating Arduinoon Breadboard is given below:

Component Descriptions

5V voltage regulator: Atmega 328 IC runs on 5V power supply. So here, we are using LM7805 to get 5v output, it can handle upto 30V as input. If you have a separate 5V supply then You can leave this step. Capacitors: 10uF capacitor is used at the input and output part of 7805 to bypass any AC component to ground. LED: This will show you that your 5V output is coming. Atmega 328: This is our main component on the breadboard. Its pin diagram is given above. Crystal oscillator: A 16MHz external crystal is connected between Pin 9 and Pin 10 of the ATmega328.This crystal is used to give clock to the microcontroller to execute the tasks faster. Push Button: To reset the the microcontroller a push button is connected between pin 1 and GND. Normally, it is connected with 5v using a 10k resistor. LED: A led is connected with digital pin 13. Building the Arduino Circuit on Breadboard Burning the Bootloader into Atmega328 IC How to Program Arduino Bootloader uploaded Atmega 328 IC on breadboard. Now we will explain each part one by one.

Part-1: Building the Arduino Circuit on Breadboard

as shown in circuit diagram and test it using external power supply to LM7805. It will looks like this. as shown in circuit diagram. Make the connections carefully. Now, connect the power supply and microcontroller part using jumpers. Your final circuit will looks something like this. You can implement the same circuit on PCB using simple tools like EasyEDA, etc. Now, we have to upload the bootloader to the new Atmega 328 IC so that we can start to program the IC.

Part-2: Burning the Bootloader into Atmega328 IC

Bootloader is small piece of executable code that permanently stored in the microcontroller’s memory. This occupies less than 1Kb of memory. Bootloader allows the IC to accept the code from the computer and place it in the memory of the microcontroller. So to program your Atmega328 using Arduino IDE you have to first upload the bootloader. To upload the Bootloader, we have two methods: Using USBasp programmer Using Arduino UNO board Second method is easier compared to first one. Because it requires less connections and also latest version of Arduino IDE not supports the fancy USBasp programmers. Than choose ArduinoISP. As shown below. Now, you have to upload this code to your Arduino board. Choose the com port and board from the tool menu and hit the upload button. , disconnect the Arduino board from the computer and make the connections of Arduino board with Atmega 328 as shown in below diagram. Now, connect the Arduino board with the computer. Open Arduino IDE. Don’t confuse it with ArduinoISP. Both are different. just below the Programmer option. After few seconds, bootloader is uploaded successfully. If there is any error in uploading, check the connections. ? That we will discuss in our next section.

Part-3: How to Program Arduino Bootloader uploaded Atmega 328 IC

Standalone Arduino Atmega328 Chip can be programmed in many ways. Using blank Arduino board i.e. Arduino board without Atmega 328 IC in it. Using USB to Serial TTL converter module (FTDI module). Using USBasp programmer (involve many connections). Here, we will program it using two methods: USB to serial converter and Arduino board.

Programming Atmega328 Chip using Arduino board

as shown in this diagram. , Programmer as USBasp and correct com port of the board. We will start by uploading the Blink program. So choose the blink program from Examples and hit Upload button. Now, you can see led on the breadboard will start blinking.

Programming Arduino Atmega328 Chip using USB to Serial converter

RXD pin of FTDI -> Tx pin of Atmega328(pin 3) TXD pin of FTDI -> Rx pin of Atmega328 (pin 2) GND -> GND(pin 8) 5v -> Vcc (pin 7) Some FTDI modules has Reset pin also known as DTR pin, which needs to be connected with the Reset pin of Atmega328 (pin 1). If there is no reset pin in the module, don’t worry I’ll give the solution when we program the chip. in control panel. You will see Port section, Expand it. If there is an yellow mark in front of the driver then you have to update your module driver. the com that you have noted. Choose Arduino Uno from Board menu in tools, Programmer as USBasp and correct com port of the board. Then hit upload button. Now, the program will be successfully uploaded into Arduino Bootloader Atmega328 chip. : You can design this circuit on PCB to make it more compact. microcontroller-projects/thermal-printer-interfacing-with-arduino-uno

Thermal Printer Interfacing with Arduino Uno

Thermal printer is the readily available and cost effective solution to print small bills or receipts. This easy to integrate solution is available everywhere. The printer uses thermochromic paper, a special type of paper which transforms into black color when it is exposed to a certain amount of heat. Thermal printer uses a special heating process to print on this paper. The printer head is heated in a special electrical to maintain a certain temperature. When the thermal paper passes through its head, its thermal coating turns into black where the head is heated. This project will work like this:- The printer will be connected with Arduino Uno. A tactile switch is being connected with the Arduino board to provide the ᾼem>push to printᾼ/em> option when pressed. Onboard Arduino LED will notify the printing status. It will glow only when the printing activity is going on.

Printer Specification and connections

from Cashino, which is available easily and the price is not too high. If we see the specification on its official website, we will see a table which provides the detailed specifications- On the back side of the printer, we will see the following connection- to communicate with the printer. The power connector is for powering the printer and the button is used for printer testing purpose. When the printer is being powered, if we push the self-test button the printer, will print a sheet where specifications and sample lines will be printed. Here is the self-test sheet- As we can see the printer use 9600 baud rate to communicate with the microcontroller unit. The printer can print ASCII characters. The communication is very easy, we can print anything by simply using UART, transmitting string or character. The printer works from 5-9V, we will use a 9V 2A power supply which can power both the printer and the Arduino Uno. The printer needs more than 1.5A of current for heating the printer head. This is the drawback of the thermal printer as it takes huge load current during the printing process.

Prerequisites

To make the following project, we need the following things:- Breadboard Hook up wires Arduino UNO board with USB Cable. A computer with Arduino interface setup ready with the Arduino IDE. 10k resistor Tactile switch Thermal Printer CSN A1 with paper roll 9V 2A rated power supply unit.

Circuit Diagram and Explanation

is given below: The circuit is simple. We are using a resistor to provide default state across the Switch input pin D2. When the button is pressed, D2 will become HIGH and this condition is used to trigger the printing. Single power supply of 9V 2A power supply is used to power the thermal printer and Arduino board. It is important to check the power supply polarity before connecting it to the Arduino UNO board. It has a barrel jack input with center positive polarity.

Arduino Program

is at the end of the project. Here we are explaining few important part of the code. At first, we declared the pins for pushbutton (Pin 2) and on board LED (Pin13) int led = 13; int SW = 2; int is_switch_press = 0; // For detecting the switch press status int debounce_delay = 300; //Debounce delay We also configured the UART with 9600 baud rate. void setup() { /* * This function is used to set the pin configuration */ pinMode(led, OUTPUT); pinMode(SW, INPUT); Serial.begin(9600); } , then again we wait for sometime and again check to identify that the switch is truly pressed or not, if the switch is still pressed even after the delay, we print custom lines in the UART, so in the Thermal printer. At the start of printing we set the onboard LED high and after printing, we turned it off by making it low. void loop() { is_switch_press = digitalRead(SW); // Reading the Switch press status if (is_switch_press == HIGH){ delay(debounce_delay); // debounce delay for button press if(is_switch_press == HIGH){ digitalWrite(led, HIGH); Serial.println("Hello"); delay(100); Serial.println("This is a Thermal printer interface"); Serial.println("with Arduino UNO."); delay(100); Serial.println("Circuitdigest.com"); Serial.println ("\n\r"); Serial.println ("\n\r"); Serial.println ("\n\r"); Serial.println ("---------------------------- \n \r"); Serial.println ("Thank You."); Serial.println ("\n\r"); Serial.println ("\n\r"); Serial.println ("\n\r"); digitalWrite(led, LOW); } } else{ digitalWrite(led, LOW); } } below. Code /* * This code is to use in Arduino UNO for interfacing the Thermal Printer. * By:- Sourav Gupta * Date:- 14.11.2018 * Circuitdigest.com */ //Pin declaration int led = 13; int SW = 2; // Programe flow related operations int is_switch_press = 0; // For detecting the switch press status int debounce_delay = 300; //Debounce delay void setup() { /* * This function is used to set the pin configuration */ pinMode(led, OUTPUT); pinMode(SW, INPUT); Serial.begin(9600); } void loop() { is_switch_press = digitalRead(SW); // Reading the Switch press status if (is_switch_press == HIGH){ delay(debounce_delay); // debounce delay for button press if(is_switch_press == HIGH){ digitalWrite(led, HIGH); Serial.println("Hello"); delay(100); Serial.println("This is a Thermal printer interface"); Serial.println("with Arduino UNO."); delay(100); Serial.println("Circuitdigest.com"); Serial.println ("\n\r"); Serial.println ("\n\r"); Serial.println ("\n\r"); Serial.println ("---------------------------- \n \r"); Serial.println ("Thank You."); Serial.println ("\n\r"); Serial.println ("\n\r"); Serial.println ("\n\r"); digitalWrite(led, LOW); } } else{ digitalWrite(led, LOW); } } Video microcontroller-projects/digital-compass-with-arduino-and-hmc5883l-magnetometer

Digital Compass using Arduino and HMC5883L Magnetometer

use different types of sensors to accomplish this, but the commonly used one is a magnetometer, which could inform the robot in which geo-graphic direction it is currently facing at. This will not only help the robot to sense direction but also to take turns in a pre-defined direction and angel. , so that I can carry it next time when I go out in the wild and wish that I would get lost just to use this thing for finding my way back home. Let’s get started.

Materials Required for Arduino Compass Project

Arduino Pro mini HMC5883L Magnetometer sensor LED lights - 8Nos 470Ohm Resistor ᾠ8Nos Barrel Jack A reliable PCB manufacturer like PCBgogo FTDI Programmer for mini PC/Laptop

What is a Magnetometer and How does it Work?

Before we dive into the circuit, let’s understand a bit about magnetometer and how they work. As the name suggests the term Magneto does not refer to that crazy mutant in marvel who could control metals by just playing piano in the air. Ohh! But I like that guy he is cool. and point the direction according to that. We all know that Earth is huge piece of spherical magnet with North Pole and South Pole. And there is magnetic field because of it. A Magnetometer senses this magnetic field and based on the direction of the magnetic field it can detect the direction we are facing.

How the HMC5883L Sensor Module Works

also. Care should be taken not to bring magnets near this sensor since the strong magnetic field from a magnet might trigger false values on the sensor. the commonly available sensor module. then it is the QMC5883L IC. Both the modules are shown in picture below for easy understating.

ArduinoDigital Compass Circuit Diagram

The complete circuit diagram is shown below that are connected to the A4 and A5 I2C pins of the Arduino Pro mini respectively. Since the module itself has a pull high resistor on the lines, there is no need to add them externally. all of which are connected to the GPIO pins of the Arduino through a current limiting resistor of 470 Ohms. The Complete circuit is powered by a 9V battery through the barrel Jack. This 9V is provided directly to the Vin pin of the Arduino where it is regulated to 5V using the on-board regulator on Arduino. This 5V is then used to power the sensor and the Arduino as well.

Fabricating the PCBs for the Digital Compass

The idea of the circuit is place the 8 LEDs in a circular fashion so that each Led points all the 8 directions namely North, North-East, East, South-East, South, South-West, West and North West respectively. So it is not easy to arrange them neatly on a breadboard or even on a perf board for that matter. Developing a PCB for this circuit will make it look more neat and easy to use. So I opened my PCB designing software and placed the LEDs and resistor in a neat circular pattern and connected the tracks to form the connections. My Design looked something like this below when completed. You can also download the Gerber file from the link given below. Download Gerber file for Digital Compass PCB I have designed it to be a double side board since I want the Arduino to be in the bottom side of my PCB so that it does not spoil the look on top of my PCB. If you are worrying that you have to pay high for a double side PCB then hold on I got good new coming. Now, that our Design is ready it is time to get them fabricated. To get thePCB done is quite easy, simply follow the steps below , sign up if this is your first time. Then, in the PCB Prototype tab enter the dimensions of your PCB, the number of layers and the number of PCB you require. My PCB is 80cm×80cm so the tab looks like this below button. You will be taken to a page where to set few additional parameters if required like the material used track spacing etc. But mostly the default values will work fine. The only thing that we have to consider here is the price and time. As you can see the Build Time is only 2-3 days and it just costs only $5 for our PSB. You can then select a preferred shipping method based on your requirement. and proceed with the payment. To make sure the process is smooth PCBGOGOverifies if your Gerber file is valid before proceeding with the payment. This way you can sure that your PCB is fabrication friendly and will reach you as committed.

Assembling the PCB

After the board was ordered, it reached me after some days though courier in a neatly labeled well packed box and like always the quality of the PCB was awesome. I am sharing few pictures of the boards below for you to judge. I turned on my soldering rod and started assembling the Board. Since the Footprints, pads, vias and silkscreen are perfectly of the right shape and size I had no problem assembling the board. The board was ready in just 10 minutes from the time of unpacking the box. are shown below.

Programming the Arduino

Once could later calculate the other direction is one direction is known. can be found at the end of this page. You can directly upload it on your board after including the library and you are ready to go. But, if you want to know more on what is actually happening in the code read further. as shown below. The wire library is used to enable I2C communication and the MechaQMC5883 is the one that we just added to Arduino. This library holds all the information on how to talk with the EMC5883L sensor. #include <Wire.h> //Wire Librarey for I2C communication #include <MechaQMC5883.h> //QMC5883 Librarey is added since mine is QMC583 and not HMC5883 but it can be anything you like. MechaQMC5883 qmc; //Create an object name for the snsor, I have named it as qmc is the number of led we have. It starts with 0. int ledPins[] = {2,3,4,5,6,7,8,9}; //Array of output pin to which the LED is connected to char led_count = 7; //Total number of LED pins loop as shown below. void setup() { Wire.begin(); //Begin I2C communication Serial.begin(9600); //Begin Serial Communication qmc.init(); //Initialise the QMC5883 Sensor for (int thisPin=0; thisPin <= led_count; thisPin++){ //Navigate through all the pins in array pinMode(ledPins[thisPin],OUTPUT); //Declare them as output } } sensor and calculate the degree the sensor is currently facing. To read the values of x,y and z use the following line int x,y,z; qmc.read(&x,&y,&z); //Get the values of X,Y and Z from sensor is shown below. Since we are not going to rotate the compass along the z axis we do not take that value into account. This formulae can be used only if the IC flat surface is facing up like it is in our set-up. Once heading is calculated, the value will be in range -180 to 180 which we have to convert to 0 to 360 like we would find in all digital compasses. int heading=atan2(x, y)/0.0174532925; //Calculate the degree using X and Y parameters with this formulae //Convert result into 0 to 360 if(heading < 0) heading+=360; heading = 360-heading; To do that we have series of if conditions statements where we check in what range the degree is currently in and turn on the LED according to that. The code is show below //Based on the value of heading print the result for debugging and glow the respective LED. if (heading > 338 || heading < 22) { Serial.println("NORTH"); digitalWrite(ledPins[0],HIGH); } if (heading > 22 && heading < 68) { Serial.println("NORTH-EAST"); digitalWrite(ledPins[7],HIGH); } if (heading > 68 && heading < 113) { Serial.println("EAST"); digitalWrite(ledPins[6],HIGH); } if (heading > 113 && heading < 158) { Serial.println("SOUTH-EAST"); digitalWrite(ledPins[5],HIGH); } if (heading > 158 && heading < 203) { Serial.println("SOUTH"); digitalWrite(ledPins[4],HIGH); } if (heading > 203 && heading < 248) { Serial.println("SOTUH-WEST"); digitalWrite(ledPins[3],HIGH); } if (heading > 248 && heading < 293) { Serial.println("WEST"); digitalWrite(ledPins[2],HIGH); } if (heading > 293 && heading < 338) { Serial.println("NORTH-WEST"); digitalWrite(ledPins[1],HIGH); } Basically we calculate which direction we are facing and predict the north direction and glow the respective LED.
NORTH0° / 360°>338° or < 22°
NORTH-EAST45°22° to 68°
EAST90°68° to 113°
SOTUH-EAST135°113° to 158°
SOUTH180°158° to 203°
SOUTH-WEST225°203° to 248°
WEST170°248° to 293°
NORTH-WEST315°293° to 338°
I have create a delay for 500 milli seconds and then made all the LED to turn off to start again form the first inside the void loop. But if you need faster updates you can reduce the delay further down. delay(500); // update position of LED for every alf seconds //Turn off the all the LED for (int thisPin=0; thisPin <= led_count; thisPin++){ digitalWrite(ledPins[thisPin],LOW); }

Testing the Digital Compass

You may note that the values will get wrong when there is a heavy metal piece near your board or even if you rotate the board along the Z axis. There are ways to overcome this problem and that is for another tutorial. Hope you have enjoyed the tutorial and learned something useful out of it. If yes, then the credits go to PCBGOGOwho have sponsored this post, so do give them a try for your PCB’s. Like always post your thoughts on the comment section below. Code /* * Program for Arduino Digital Compass using QMC5883 * Project by: Aswinth Raj * Dated: 1-11-2018 * Website: www.circuitdigest.com * Lib. from https://github.com/keepworking/Mecha_QMC5883L * WARNING: This code works only for QMC5883 Sensor which is commonly being sold as HMC5883 read article to find the actual name of the sensor you have. */ #include <Wire.h> //Wire Librarey for I2C communication #include <MechaQMC5883.h> //QMC5883 Librarey is added since mine is QMC583 and not HMC5883 MechaQMC5883 qmc; //Create an object name for the snsor, I have named it as qmc int ledPins[] = {2,3,4,5,6,7,8,9}; //Array of output pin to which the LED is connected to char led_count = 7; //Total number of LED pins void setup() { Wire.begin(); //Begin I2C communication Serial.begin(9600); //Begin Serial Communication qmc.init(); //Initialise the QMC5883 Sensor for (int thisPin=0; thisPin <= led_count; thisPin++){ //Navigate through all the pins in array pinMode(ledPins[thisPin],OUTPUT); //Declare them as output } } void loop() { //Infinite Loop int x,y,z; qmc.read(&x,&y,&z); //Get the values of X,Y and Z from sensor int heading=atan2(x, y)/0.0174532925; //Calculate the degree using X and Y parameters with this formulae //Convert result into 0 to 360 if(heading < 0) heading+=360; heading = 360-heading; Serial.println(heading); //Print the value of heading in degree for debugging //Based on the value of heading print the result for debugging and glow the respective LED. if (heading > 338 || heading < 22) { Serial.println("NORTH"); digitalWrite(ledPins[0],HIGH); } if (heading > 22 && heading < 68) { Serial.println("NORTH-EAST"); digitalWrite(ledPins[7],HIGH); } if (heading > 68 && heading < 113) { Serial.println("EAST"); digitalWrite(ledPins[6],HIGH); } if (heading > 113 && heading < 158) { Serial.println("SOUTH-EAST"); digitalWrite(ledPins[5],HIGH); } if (heading > 158 && heading < 203) { Serial.println("SOUTH"); digitalWrite(ledPins[4],HIGH); } if (heading > 203 && heading < 248) { Serial.println("SOTUH-WEST"); digitalWrite(ledPins[3],HIGH); } if (heading > 248 && heading < 293) { Serial.println("WEST"); digitalWrite(ledPins[2],HIGH); } if (heading > 293 && heading < 338) { Serial.println("NORTH-WEST"); digitalWrite(ledPins[1],HIGH); } delay(500); // update position of LED for every alf seconds //Turn off the all the LED for (int thisPin=0; thisPin <= led_count; thisPin++){ digitalWrite(ledPins[thisPin],LOW); } } Video microcontroller-projects/how-to-plot-real-time-temperature-graph-using-matlab

How to Plot Real Time Temperature Graph using MATLAB

Arduino Uno is used here to get temperature data from LM35 temperature sensor. Before proceeding further, if you are new to MATLAB you can check our previous MATLAB tutorials for better understating: Getting started with MATLAB: A Quick Introduction Interfacing Arduino with MATLAB - Blinking LED Serial Communication between MATLAB and Arduino DC Motor Control Using MATLAB and Arduino Stepper Motor Control using MATLAB and Arduino

Creating MATLAB Graphical User Interface for Plotting Graph

guide as shown in below image, Push button will be used for start the temperature sensing, two axes for plotting the graph and Text box to show the current value of temperature. To resize or to change the shape of the button, Axes or edit text button, just click on it and you will be able to drag the corners of the button. By double-clicking on any of these you will be able to change the color, string and tag of that particular button. After customization it will look like this

MATLAB Code for Plotting the Graph

, is given at the end of this project. Further we are including the GUI file (.fig) and code file(.m)here for download, using which you cancustomize the buttons or Axes size as per your requirement. We have edited the generated code as explained below. clear all; global a; a = arduino(); in the GUI, no function will be created for Axes. Now write the code in the Pushbutton (start button) function according to the task you want to perform. of 1 second after every iteration so temperature value will be updated every second. x = 0; go = true; global a; while go value = readVoltage(a,'A1'); temp = (value*100); disp(temp); x = [x temp]; plot(handles.axes1,x); grid on; xlabel('Time(seconds)') ylabel('Temperature(°C)'); title('Real-Time Temperature Graph'); drawnow set(handles.edit1,'String',num2str(temp)); pause(1); end for calling the Arduino in the function. x = 0; go = true; global a; which is connected to the ‘OUTᾠpin of the LM35 Temperature Sensor. The output will be the voltage value not the analog value. value = readVoltage(a,'A1'); (degree Celsius), by multiplying it by 10 temp = (value*100); ᾠare used for naming the x-axis, y-axis and title. plot(handles.axes1,x); grid on; xlabel('Time(seconds)') ylabel('Temperature(°C)'); title('Real-Time Temperature Graph'); is used to update the graphical representation in real-time. drawnow at every second below command is used, set(handles.edit1,'String',num2str(temp));

Material Required

MATLAB installed Laptop (Preference: R2016a or above versions) Arduino UNO LM35 ᾠTemperature Sensor Connecting Wires Breadboard

Circuit Diagram

Plot the Graph with MATLAB

After setting the hardware according to circuit diagram, just click on the run button to run the edited code in .m file MATLAB may take few seconds to respond, do not click on any GUI buttons until MATLAB is showing busy message in the lower left corner as shown below, The value will automatically update in every one second. This interval of one second you can change in the MATLAB code accordingly. The output will look like the image shown below, This is how you can plot the graph for any incoming value from the Arduino using MATLAB. below for proper understanding. Code function varargout = Temperature(varargin) gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Temperature_OpeningFcn, ... 'gui_OutputFcn', @Temperature_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end function Temperature_OpeningFcn(hObject, eventdata, handles, varargin) handles.output = hObject; guidata(hObject, handles); function varargout = Temperature_OutputFcn(hObject, eventdata, handles) varargout{1} = handles.output; clear all; global a; a = arduino; function start_Callback(hObject, eventdata, handles) x = 0; go = true; global a; while go value = readVoltage(a,'A1'); temp = (value*100); disp(temp); x = [x temp]; plot(handles.axes1,x); grid on; xlabel('Time(seconds)') ylabel('Temperature(°C)'); title('Real-Time Temperature Graph'); drawnow set(handles.edit1,'String',num2str(temp)); pause(1); end function edit1_Callback(hObject, eventdata, handles) function edit1_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end Video microcontroller-projects/serial-communication-between-matlab-and-arduino

Serial Communication between MATLAB and Arduino

Components Required

MATLAB installed Laptop (Preference: R2016a or above versions) Arduino UNO LED (any color) Resistor (330 ohm)

Circuit Diagram

The above circuit diagram will remain same for both the ways to establish serial communication between MATLAB and Arduino.

Serial Communication using MATLAB Command Window

This is the simple method to setup serial communication between Arduino and MATLAB. Here we will simply send the data from MATLAB to the Arduino serially using command window and then Arduino read the incoming serial data. Then this serially transmitted data can be used to control anything connected to the Arduino. Here we have connected an LED to Arduino, that will be turned on and off according to the serially received data by the Arduino. as shown in below image: Then, copy and paste the below complete MATLAB code in the editor window for serial communication between MATLAB and Arduino. %MATLAB Code for Serial Communication between Arduino and MATLAB x=serial('COM18','BAUD', 9600); fopen(x); go = true; while go a= input('Press 1 to turn ON LED & 0 to turn OFF:'); fprintf(x,a); if (a == 2) go=false; end end x=serial('COM18','BAUD', 9600); To open serial port use the below command, fopen(x); and a is the value entered by the user. fprintf(x,a); function for creating an infinite loop and whenever the user input the number ᾲᾠthe loop will break. while go a= input('Press 1 to turn ON LED & 0 to turn OFF:'); fprintf(x,a); if (a == 2) go=false; end end ᾠto run your program as shown in below image, MATLAB takes few seconds for processing the code and start the serial communication, wait until MATLAB shows ‘BUSYᾠmessage at the bottom left corner of the software screen, as shown in below image. Now, you will see the command window for sending the user input, we have set the default message, 'Press 1 to turn ON LED & 0 to turn OFF:' is given at the end.

Serial Communication using MATLAB GUI

to turn on and off the LED connected to the Arduino. Data will be sent serially from MATLAB to Arduino on clicking on these buttons to turn on and off the LED. Arduino will contain the code for receiving serial data from MATLAB and controlling the LED according to serial data received. Arduino code will remain same as previous one, only difference is that, previously we were sending serial data ᾱᾠand ᾰᾠthrough command window of MATLAB, and now the same data will be sent on clinking on two graphical buttons. guide as shown in below image, as shown below, To resize or to change the shape of the buttons, just click on it and you will be able to drag the corners of the button. By double-clicking on pushbutton you can change the color, string and tag of that particular button. We have customized two buttons as shown in below picture. (right click on link then select 'Save link as...'), using which you cancustomize the buttons as per your requirement. Below are some tweaks we did for controlling the LED connected with Arduino. Copy and paste the below code on line no. 74 to setup the serial port and baud rate. clear all; global x; x=serial('COM18','BAUD', 9600); % Make sure the baud rate and COM port is % same as in Arduino IDE fopen(x); is used to open the serial port for serial communication. When you scroll down, you will see that there are two functions created for both the Buttons in the GUI. Now write the code in both the functions according to the task you want to perform on click. pin HIGH, when it receives ᾱᾠon its serial port. global x; fprintf(x,1); pin LOW, when it receives ᾰᾠon its serial port. global x; fprintf(x,0); After completing with MATLAB GUI coding and setup the hardware according to circuit diagram, just click on the run button to run the edited code in .m file. MATLAB may take few seconds to respond, do not click on any GUI button until MATLABshows BUSY indication, which you can see at the left bottom corner of the screen as shown below, pin of Arduino goes LOW which makes the LED to turn off. Code int value; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } void loop() { if(Serial.available()>0) { value=Serial.read(); if (value == 1) { digitalWrite(13, HIGH); } if(value == 0) { digitalWrite(13, LOW); } } } function varargout = final(varargin) gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @final_OpeningFcn, ... 'gui_OutputFcn', @final_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end handles.output = hObject; guidata(hObject, handles); function varargout = final_OutputFcn(hObject, eventdata, handles) varargout{1} = handles.output; clear all; global x; x=serial('COM18','BAUD', 9600); % Make sure the baud rate and COM port is % same as in Arduino IDE fopen(x); function turnonled_Callback(hObject, eventdata, handles) global x; fprintf(x,1); function turnoffled_Callback(hObject, eventdata, handles) global x; fprintf(x,0); Video microcontroller-projects/stepper-motor-control-using-matlab-and-arduino

Stepper Motor Control using MATLAB and Arduino

is a brushless DC motor that rotates in discrete steps, and are the best choice for many precision motion control applications. Also, stepper motors are good for positioning, speed control and applications which require high torque at low speed.

Modes of operation in Stepper Motor

Before you start coding for stepper motor you should understand the working or rotating concept of a stepper motor. Since the stator of the stepper mode is built of different pairs of coils, each coil pair can be excited in many different methods, this enabling the modes to be driven in many different modes. The following are the broad classifications In this mode only one terminal (phase) of the motor will be energised at any given time. This has less number of steps and hence can achieve a full 360° rotation. Since the number of steps is less the current consumed by this method is also very low. The following table shows the wave stepping sequence for a 4 phase stepper motor
StepPhase 1 (Blue)Phase 2 (Pink)Phase 3 (Yellow)Phase 4 (Orange)
11000
20100
30010
40001
As the name states in this method two phases will be one. It has the same number of steps as Wave stepping, but since two coils are energised at a time it can provide better torque and speed compared to the previous method. Although one down side is that this method also consumes more power.
StepPhase 1 (Blue)Phase 2 (Pink)Phase 3 (Yellow)Phase 4 (Orange)
11100
20110
30011
41001
The Half Step mode is the combination of one phase-on and two-phase on modes. This combination will help us to get over the above mentioned disadvantage of the both the modes. in this method to get a complete rotation. The switching sequence for a 4-phase stepper motor shown below
StepPhase 1 (Blue)Phase 2 (Pink)Phase 3 (Yellow)Phase 4 (Orange)
11000
21100
30100
40110
50011
60001
71001
81000
Hence, it is your choice to program your stepper motor in any mode, but I prefer Two Phase-on stepping Full Step Mode. Because this method deliver faster speed then the one phase method and in compare to half mode the coding part is less due to less number of steps in two-phase method.

Creating MATLAB Graphical User Interface for controlling Stepper Motor

guide as shown in below image, as shown below, To resize or to change the shape of the button, just click on it and you will be able to drag the corners of the button. By double-clicking on toggle button you can change the color, string and tag of that particular button. We have customized two buttons as shown in below picture.

MATLAB Code for controlling Stepper Motor with Arduino

(right click on link then select 'Save link as...')), using which you cancustomize the buttons as per your requirement. Below are some tweaks we did for rotating the Stepper Motorclockwise and anticlockwise using two toggle buttons. Copy and paste the below code on line no. 74 to make sure that the Arduino is talking with MATLAB every time you run the m-file. clear all; global a; a = arduino(); When you scroll down, you will see that there are two functions created for both the Buttons in the GUI. Now write the code in both the functions according to the task you want to perform on click. to repeat the two phase-on stepping full mode steps for clockwise direction. while get(hObject,'Value') global a; writeDigitalPin(a, 'D8', 1); writeDigitalPin(a, 'D9', 0); writeDigitalPin(a, 'D10', 0); writeDigitalPin(a, 'D11', 1); pause(0.0002); writeDigitalPin(a, 'D8', 0); writeDigitalPin(a, 'D9', 0); writeDigitalPin(a, 'D10', 1); writeDigitalPin(a, 'D11', 1); pause(0.0002); writeDigitalPin(a, 'D8', 0); writeDigitalPin(a, 'D9', 1); writeDigitalPin(a, 'D10', 1); writeDigitalPin(a, 'D11', 0); pause(0.0002); writeDigitalPin(a, 'D8', 1); writeDigitalPin(a, 'D9', 1); writeDigitalPin(a, 'D10', 0); writeDigitalPin(a, 'D11', 0); pause(0.0002); end to repeat the two phase-on stepping full mode steps for anti-clockwise direction. while get(hObject,'Value') global a; writeDigitalPin(a, 'D8', 1); writeDigitalPin(a, 'D9', 1); writeDigitalPin(a, 'D10', 0); writeDigitalPin(a, 'D11', 0); pause(0.0002); writeDigitalPin(a, 'D8', 0); writeDigitalPin(a, 'D9', 1); writeDigitalPin(a, 'D10', 1); writeDigitalPin(a, 'D11', 0); pause(0.0002); writeDigitalPin(a, 'D8', 0); writeDigitalPin(a, 'D9', 0); writeDigitalPin(a, 'D10', 1); writeDigitalPin(a, 'D11', 1); pause(0.0002); writeDigitalPin(a, 'D8', 1); writeDigitalPin(a, 'D9', 0); writeDigitalPin(a, 'D10', 0); writeDigitalPin(a, 'D11', 1); pause(0.0002); end

Material Required

MATLAB installed Laptop (Preference: R2016a or above versions) Arduino UNO Stepper Motor (28BYJ-48, 5VDC) ULN2003 - Stepper motor driver

Circuit Diagram

Controlling Stepper Motor with MATLAB

After setup the hardware according to circuit diagram, just click on the run button to run the edited code in .m file MATLAB may take few seconds to respond, do not click on any GUI buttons until MATLAB is showing busy message in the lower side of left corner as shown below, When everything is ready, click on clockwise or anticlockwise button to rotate the motor. As we are using toggle button, the stepper motor will continuously move in clockwise direction until we press the button again. Similarly, by pressing the anti-clockwise toggle button, motor starts rotating in anti-clockwise direction until we press the button again. Code function varargout = untitled1(varargin) gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @untitled1_OpeningFcn, ... 'gui_OutputFcn', @untitled1_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end function untitled1_OpeningFcn(hObject, eventdata, handles, varargin) function varargout = untitled1_OutputFcn(hObject, eventdata, handles) varargout{1} = handles.output; clear all; global a; a = arduino(); function clockwise_Callback(hObject, eventdata, handles) while get(hObject,'Value') global a; writeDigitalPin(a, 'D8', 1); writeDigitalPin(a, 'D9', 0); writeDigitalPin(a, 'D10', 0); writeDigitalPin(a, 'D11', 1); pause(0.0002); writeDigitalPin(a, 'D8', 0); writeDigitalPin(a, 'D9', 0); writeDigitalPin(a, 'D10', 1); writeDigitalPin(a, 'D11', 1); pause(0.0002); writeDigitalPin(a, 'D8', 0); writeDigitalPin(a, 'D9', 1); writeDigitalPin(a, 'D10', 1); writeDigitalPin(a, 'D11', 0); pause(0.0002); writeDigitalPin(a, 'D8', 1); writeDigitalPin(a, 'D9', 1); writeDigitalPin(a, 'D10', 0); writeDigitalPin(a, 'D11', 0); pause(0.0002); end function anticlockwise_Callback(hObject, eventdata, handles) while get(hObject,'Value') global a; writeDigitalPin(a, 'D8', 1); writeDigitalPin(a, 'D9', 1); writeDigitalPin(a, 'D10', 0); writeDigitalPin(a, 'D11', 0); pause(0.0002); writeDigitalPin(a, 'D8', 0); writeDigitalPin(a, 'D9', 1); writeDigitalPin(a, 'D10', 1); writeDigitalPin(a, 'D11', 0); pause(0.0002); writeDigitalPin(a, 'D8', 0); writeDigitalPin(a, 'D9', 0); writeDigitalPin(a, 'D10', 1); writeDigitalPin(a, 'D11', 1); pause(0.0002); writeDigitalPin(a, 'D8', 1); writeDigitalPin(a, 'D9', 0); writeDigitalPin(a, 'D10', 0); writeDigitalPin(a, 'D11', 1); pause(0.0002); end Video microcontroller-projects/matlab-dc-motor-control-using-arduino

DC Motor Control Using MATLAB and Arduino

Creating MATLAB Graphical User Interface for controlling DC Motor

guide as shown in below image, , as shown below, To resize or to change the shape of the button, just click on it and you will be able to drag the corners of the button. By double-clicking on pushbutton you can change the color, string and tag of that particular button. We have customized three buttons as shown in below picture. of MATLAB. To code your Arduino for performing any task related to your project, you always have to edit this generated code. So below we have edited the MATLAB code.

MATLAB Code for controlling DC Motor with Arduino

, using which you cancustomize the buttons as per your requirement. Below are some tweaks we did for rotating the DC Motorclockwise, anticlockwise and stop using three push buttons. Copy and paste the below code on line no. 74 to make sure that the Arduino is talking with MATLAB every time you run the m-file. clear all; global a; a = arduino(); When you scroll down, you will see that there are three functions for every Button in the GUI. Now write the code in every function according to task you want to perform on click. button’s function, copy and paste the below code just before the ending braces of the function to rotate the motor in clockwise direction. Here we are giving HIGH at pin 6 and LOW at pin 5 to rotate the motor in clockwise direction. global a; writeDigitalPin(a, 'D5', 0); writeDigitalPin(a, 'D6', 1); pause(0.5); button’s function, paste the below code at the end of the function to rotate the motor in anti-clockwise direction. Here we are giving HIGH at pin 5 and LOW at pin 6 to rotate the motor in Anti-clockwise direction. global a; writeDigitalPin(a, 'D5', 1); writeDigitalPin(a, 'D6', 0); pause(0.5); button’s function, paste the below code at the end, to stop the rotation of motor. Here we are giving LOW at both pin 5 and 6 to stop the motor. global a; writeDigitalPin(a, 'D5', 0); writeDigitalPin(a, 'D6', 0); pause(0.5);

Material Required

MATLAB installed Laptop (Preference: R2016a or above versions) Arduino UNO DC Motor L293D- motor driver

Circuit Diagram

Controlling DC Motor with MATLAB

After setup the hardware according to circuit diagram, just click on the run button to run the edited code in .m file MATLAB may take few seconds to respond, do not click on any GUI button until MATLABshows BUSY indication, which you can see at the left bottom corner of the screen as shown below, using the Arduino. Code function varargout = DCmotor(varargin) gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @DCmotor_OpeningFcn, ... 'gui_OutputFcn', @DCmotor_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end function DCmotor_OpeningFcn(hObject, eventdata, handles, varargin) guidata(hObject, handles); function varargout = DCmotor_OutputFcn(hObject, eventdata, handles) varargout{1} = handles.output; clear all; global a; a = arduino(); function clockwise_Callback(hObject, eventdata, handles) global a; writeDigitalPin(a, 'D5', 0); writeDigitalPin(a, 'D6', 1); pause(0.5); function anticlockwise_Callback(hObject, eventdata, handles) global a; writeDigitalPin(a, 'D5', 1); writeDigitalPin(a, 'D6', 0); pause(0.5); function stop_Callback(hObject, eventdata, handles) global a; writeDigitalPin(a, 'D5', 0); writeDigitalPin(a, 'D6', 0); pause(0.5); Video microcontroller-projects/smart-phone-controlled-arduino-mood-based-lights

Smart Phone Controlled Arduino Mood Light with Alarm

strip and was quite impressed by the way it works. The tiny LED’s have an inbuilt driver IC which helps us to control each LED individually and can produce a wide spectrum of colors. Being a garish person who is obsessed with colours I really loved watching these tiny LED’s changing colors so I decided to build something on my own and leave it coloring my bedroom during night times. which will wake you up with a bright orange colour (sunshine) and another alarm that puts the LED’s in sleep mode with mild purple (night sky) color to doze you into sleep. Sounds interesting right? So let’s get building.

Chromotherapy ᾠMood Lamp

But there are lots of so called DIY mood lamps out there which just randomly change colour without any purpose behind it. After a bit of searching I found that a mood lamp should have a minimum of certain lumens brightness and should also change colours gradually with varying intensity. Each colour has a different impact on both mental and physical level. I have tabulated the impact against each colour in the below table.
RedGives more Energy, Boosts Sexual DesiresKidney, Backbone, sense of smell
YellowImproves Digestion, Kills DepressionStomach, Liver, Intestine
BlueLowers Blood Pressure, Calm Down PeopleMigraine headache, throat, ears and mouth
GreenStimulates Growth and strengthens muscleBones, tissues, immune system
PurpleSleep Inducer Emotional and Mental Balance Decreases Sexual desiresNervous system, eyes
OrangeStimulates creativityBreathing, Brest feeding
PinkPurifies BloodBlood, arteries, veins
So based on this data I have designed the mood Lamp to change its colours based on what time of the day it is. Of course I have added some personal flavour, so feel free to edit the program accordingly.

Materials Required

Enough science we are supposed to be working with electronics, so let’s gather the required components. Neo Pixel LEDs Arduino DS3231 RTC module HC-05 Bluetooth Module LDR 100K resistor 12V Power supply.

Circuit Diagram

is given below. This module works with the help of I2C communication and can be powered directly with 5V pin of the Arduino. The SDA and SCL pins are connected to the I2C pins A4 and A5 respectively. Through this Bluetooth connection we can set the required colour on the LED and also set a sleep time and wake up time for the LED. The Bluetooth module is powered with the 5V pin as well and the Tx and Rx pins are connected to Arduino through pins 11 and 10 respectively. for my project since it is smaller and would be handy while packing it inside an enclosure. You can use any board of your choice. The complete set-up is powered by a 12V adapter which is connected to the RAW pin of the Arduino. The on board voltage regulator on Arduino converts this 12V to 5V which is then used to supply 5V to power all the modules through the vcc pin.

Neo Pixel LEDs and How They Work

The primary and cool component of this project is the neo Pixel LED. The idea for the Neo pixel LEDs were originally by the Adafruit industries in which they use an LED driver IC WS2812 inside an RBG LED. This driver IC can receive a control signal from a controller like Arduino and based on the control signal it can control the intensity of the RBG color thus helping us to achieve the required color. The Vcc and ground pin is used to power the Led which can range from 3.3V to 5V and the data pin is used to send the control signal which decide that which Led should glow in which color.

Programming Arduino for Mood Light

can be found at the end of this article. for the project in this case the following libraries are needed. #include <SoftwareSerial.h> //Bluetooth module works with software serial #include <Adafruit_NeoPixel.h> //Library for Neo Pixel (Download from Link in article) #include <DS3231.h> //Library for RTC module (Download from Link in article) #include <EEPROM.h> //Library for EEPROM (Pre-Loaded into Arduino) The Bluetooth module works though serial communication; I do not prefer using the hardware serial pin (0 and 1) for that since I will be using the serial monitor to debug the program, so we include the software serial library into our program. This library will be present in your IDE by default. option to add this ZIP file into your Arduino IDE. for the RTC module and add it the same way. Finally we have EEPROM library which are already pre-loaded into the Arduino library. We just have to add the library to store the wake up alarm and sleep alarm time in EEPROM so that when the Arduino re-boots after a power failure it remembers when to go to sleep and when to wake up. as shown below. #define Red 1 #define Orange 20 #define Yellow 30 #define Green 70 #define Cyan 100 #define Blue 130 #define Purple 200 #define Pink 240 In my case I have connected the Neo pixel to pin 6 as shown in the circuit diagram above and I have a total of 5 LEDs on my strip so my code looks like Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, 6, NEO_GRB + NEO_KHZ800); //5 LEDs on PIN-6 each consisting of 4 colours. I have selected Red, Orange, Green and Pink to be the morning colours and Yellow, Cyan, Blue and Purple to be the evening colours based on the chromo therapy table that we discussed above you can change it as you wish //array declarations char current_rainbow[8] = {}; //the main array char morning_rainbow[4] = {Red, Orange, Green, Pink}; //colours to show during day time char evening_rainbow[4] = {Yellow, Cyan, Blue, Purple}; //colours to show during night time char all_rainbow[8] = {Red, Orange, Yellow, Green, Cyan, Blue, Purple, Pink}; //colours that can be controlled thorugh Bluetooth previously and store them in the respective variables void setup(){//Execute once during the launch of program Initialize_RTC(); Bluetooth.begin(9600); Serial.begin (9600); //for debugging strip.begin(); strip.show(); // Initialize all pixels to 'off' Bluetooth.println("Mood Lamp Alarm -CircuitDigest"); Serial.println("Mood Lamp Alarm -CircuitDigest"); //If anything was stored previously in EEPROM copy it to the alarm variables sleep_alarm_hour = EEPROM.read(0); sleep_alarm_minute = EEPROM.read(1); wake_alarm_hour = EEPROM.read(2); wake_alarm_minute = EEPROM.read(3); } is also checked when the room is bright so that the user can still force the lights to turn on from the mobile phone. Here I have select 800 as the threshold value but if you want to lamp to work even in bright day light you can simply increase the value of 800. Then range is form 0-1024. while (lightvalue>800) //IF the room is very brigt (you can increase this values to make it glow even duringf day) { for (int i=0; i<=5; i++) //turn of all LED { strip.setBrightness(0); //by setting brightness to zero strip.show(); } lightvalue = analogRead(A0); //kepp checking if the room is getting darker Serial.print("Too bright to glow: "); Serial.println(lightvalue); //for debugging Interactive_BT(); //Also check if the user is trying to access through bluetooth delay(100); } or Iphone store and still can interact with it. respectively. t = rtc.getTime(); //get the current time current_time_hour = t.hour; //get hour value current_time_minute = t.min; //get minute value as shown below. if (sleeping == false) //If we are not sleeping glow_rainbow(colour_count); //dsplay the colours if (sleeping == true) //if we are sleeping night_lamp(); //display the night lamp effect if (t.hour>=17) //During evening time { for (int i=0; i<=3; i++) { current_rainbow[i] = evening_rainbow[i]; delay(100);} //copy evening raninbow into current_rainbow } else //During Morning { for (int i=0; i<=3; i++) { current_rainbow[i] = morning_rainbow[i]; delay(100);} //copy mornign rainboe into current rainbow } can be fiddled around between 0-255 according to how much ever brightness you want to reduce void glow_rainbow(int count) { for (int j=150; j>=10; j--) //decrease the brightness to create dim effect { for (int i=0; i<=5; i++) //do it for all 5 leds { strip.setBrightness(j); strip.show(); } 1 delay(2); } for (int j=0; j<=255; j++) //increase the brightness { for (int i=0; i<=5; i++) //do it for all 5 leds { strip.setPixelColor(i,Wheel(current_rainbow[count]));//select the colour based on count value strip.setBrightness(j); strip.show(); } delay(10); } } macros. The function is shown below. // Input a value 0 to 255 to get a color value. // The colours are a transition r - g - b - back to r. uint32_t Wheel(byte WheelPos) { WheelPos = 255 - WheelPos; if(WheelPos < 85) { return strip.Color( (255 - WheelPos * 3), 0, (WheelPos * 3) ); } if(WheelPos < 170) { WheelPos -= 85; return strip.Color(0, (WheelPos * 3) , (255 - WheelPos * 3) ); } WheelPos -= 170; return strip.Color((WheelPos * 3), (255 - WheelPos) * 3, 0); } is an important line which decides the colour of the LED. The variables x,y and z each take a value from 0-255 and based on the value it decides the amount of Red, Green and Blue light the LED should emit. So x,y ad z directly controls the Red, Green and Blue light intensity of the LED pixels.

Controlling and Setting Alarm through Smart Phone

Once you have made the connection as per the circuit diagram and have uploaded the code given below you can test the circuit. I would also recommend opening the serial monitor to check how the hardware is responding to the program. Once you are done with that you can open your Bluetooth application on the mobile phone. but you can use any Bluetooth application which helps you to read and write data through Bluetooth connection. Make sure you have paired the Bluetooth module with your phone using the password ᾱ234ᾠbefore launching the application. Once the application is launched connect to your Bluetooth device which should be normal named as “HC-05ᾮ To begin communications just send a random variable from the phone, in this case I have sent ‘gᾮ This will initiate Interactive Bluetooth communication mode in the program and you will get the following screen. linked at the end of this project.

3D Printing the Enclosure for Arduino Mood Light

As I said I made this project to be left working in my office or in my living room so it requires a good enclosure for housing all the electronics. Also it hurts our eyes to look at the pixel directly when they glow. So I decide to 3D print my enclosure using my Tevo tarantula printer and hence went on to design my enclosures. You can also print your own if you have 3D printer or simply can use wood or acrylic to build an enclosure of our own. My print setting is show in the image below. After printing you can push the LDR into the small hole provided and the LED strip can be slide into the top case. After assembling, my hardware looked something like this as shown below. All that is left to do is power the set-up using a 12V adapter and set the alarm using the Bluetooth option as discussed above and leave in illuminating your room. Hope you liked the project and enjoyed building it. If you have faced any problem in the build process you can post it in the comment section below or use the forums for quick help. Code /* * Mood light using Arduino * Interactive Bluetooth Programming using Terminal * Alarm function for wake up and sleep. * Program by: B.Aswinth Raj https://circuitdigest.com/users/baswinth-raj * For: Circuitdigest.com * Dated: 24-9-2018 */ /*PIN CONNECTIONS * Bluetooth (HC-05) * #Tx -> 11 * Rx ->10 * #DS3231 (RTC) * SDA ->A4 * SCL ->A5 * #Neo Pixel * Data -> pin 6 */ #include <SoftwareSerial.h> //Bluetooth module works with software serial #include <Adafruit_NeoPixel.h> //Library for Neo Pixel (Download from Link in article) #include <DS3231.h> //Library for RTC module (Download from Link in article) #include <SPI.h> //Library for SPI communication (Pre-Loaded into Arduino) #include <EEPROM.h> //Library for EEPROM (Pre-Loaded into Arduino) //Define the value of colours #define Red 1 #define Orange 20 #define Yellow 30 #define Green 70 #define Cyan 100 #define Blue 130 #define Purple 200 #define Pink 240 Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, 6, NEO_GRB + NEO_KHZ800); //5 LEDs on PIN-6 DS3231 rtc(SDA, SCL); //object for RTC module Time t; //element t SoftwareSerial Bluetooth(11, 10); // TX, RX //GLOBAL variables char incoming; //to store value form Bluetooth int lightvalue=0; //LDR output vale int colour_count = 0; //to increment array //variable to store hour and minute values int wake_alarm_hour; int sleep_alarm_hour; int wake_alarm_minute; int sleep_alarm_minute; int current_time_hour; int current_time_minute; //flag variables boolean settings = false; boolean sleeping = false; //array declarations char current_rainbow[8] = {}; //the main array char morning_rainbow[4] = {Red, Orange, Green, Pink}; //colours to show during day time char evening_rainbow[4] = {Yellow, Cyan, Blue, Purple}; //colours to show during night time char all_rainbow[8] = {Red, Orange, Yellow, Green, Cyan, Blue, Purple, Pink}; //colours that can be controlled thorugh bluetooth void wait_for_reply() //Function to wait for user to enter value for BT { Bluetooth.flush(); while (!Bluetooth.available()); } void Initialize_RTC() { rtc.begin(); // Initialize the rtc object //#### The following lines can be uncommented to set the date and time for the first time### //rtc.setDOW(TUESDAY); // Set Day-of-Week to SUNDAY //rtc.setTime(13, 01, 00); // Set the time to 12:00:00 (24hr format) //rtc.setDate(9, 25, 2018); // Set the date to January 1st, 2014 } int get_hour() //get the hour value for setting alarm { char UD; char LD; //upper digit and lower digit Bluetooth.println("Enter hours"); wait_for_reply(); //wait for user to enter something UD = Bluetooth.read(); delay (100); //Read the first digit wait_for_reply(); //wait for user to enter something LD = Bluetooth.read(); //Read the lower digit UD= int(UD)-48; LD= int(LD)-48; //convert the char to int by subtracting 48 from it return (UD*10)+ LD; // Comine the uper digit and lowe digit to form the number which is hours } int get_minute() //get the minute value for setting alarm { char UD; char LD; //upper digit and lower digit Bluetooth.println("Enter minutes"); wait_for_reply();//wait for user to enter something UD = Bluetooth.read(); delay (100); //Read the first digit wait_for_reply();//wait for user to enter something LD = Bluetooth.read(); //Read the first digit UD= int(UD)-48; LD= int(LD)-48; //convert the char to int by subtracting 48 from it return (UD*10)+ LD; // Comine the uper digit and lowe digit to form the number which is hours } void setup(){//Execute once during the launch of program Initialize_RTC(); Bluetooth.begin(9600); Serial.begin (9600); //for debugging strip.begin(); strip.show(); // Initialize all pixels to 'off' Bluetooth.println("Mood Lamp Alarm -CircuitDigest"); Serial.println("Mood Lamp Alarm -CircuitDigest"); //If anything was stored previously in EEPROM copy it to the alarm variables sleep_alarm_hour = EEPROM.read(0); sleep_alarm_minute = EEPROM.read(1); wake_alarm_hour = EEPROM.read(2); wake_alarm_minute = EEPROM.read(3); } void loop(){ lightvalue = analogRead(A0); //Read the value form LDR while (lightvalue>800) //IF the room is very brigt (you can increase this values to make it glow even duringf day) { for (int i=0; i<=5; i++) //turn of all LED { strip.setBrightness(0); //by setting brightness to zero strip.show(); } lightvalue = analogRead(A0); //kepp checking if the room is getting darker Serial.print("Too bright to glow: "); Serial.println(lightvalue); //for debugging Interactive_BT(); //Also check if the user is trying to access through bluetooth delay(100); } settings=true; //if setting is true it means we have are ready to get into bluetooth control Interactive_BT(); //Also check if the user is trying to access through bluetooth t = rtc.getTime(); //get the current time current_time_hour = t.hour; //get hour value current_time_minute = t.min; //get minute value if (t.sec%5 == 0) //For every 5 seconds { colour_count++; //change the colour if (colour_count>=4) //if we exceed array count colour_count = 0; //initialise the count while(t.sec%5==0) //wait till the 5th secound is over t = rtc.getTime(); //update t.sec //For Debugging Serial.print ("Glowing clour: ");Serial.println(colour_count); Serial.print("At time: "); Serial.print(t.hour); Serial.print (" : "); Serial.println (t.min); Serial.print("Enviroment Brightness: "); Serial.println(lightvalue); Serial.print("Wake up at :"); Serial.print(wake_alarm_hour); Serial.print (" : "); Serial.println (wake_alarm_minute); Serial.print("Sleep at :"); Serial.print(sleep_alarm_hour); Serial.print (" : "); Serial.println (sleep_alarm_minute); Serial.print ("Is Lamp sleeping? : "); Serial.println (sleeping); Serial.println(" ****** "); //End of debugging lines if (sleeping == false) //If we are not sleeping glow_rainbow(colour_count); //dsplay the colours if (sleeping == true) //if we are sleeping night_lamp(); //display the night lamp effect if (t.hour>=17) //During evening time { for (int i=0; i<=3; i++) { current_rainbow[i] = evening_rainbow[i]; delay(100);} //copy evening raninbow into current_rainbow } else //During Morning { for (int i=0; i<=3; i++) { current_rainbow[i] = morning_rainbow[i]; delay(100);} //copy mornign rainboe into current rainbow } } if(t.hour == sleep_alarm_hour && t.min == sleep_alarm_minute) //If the sleep time is meat { sleeping = true; Serial.println("Lamp getting into Sleep Mode");}//get into sleeping mode if(t.hour == wake_alarm_hour && t.min == wake_alarm_minute)// If wake up time is meat { sleeping = false; Serial.println("Lamp is up and ready"); }// get out of sleeping mode. } void Interactive_BT() //using this funciton the user cna control LED colour and set alarm time. { if (Bluetooth.available() > 0 && settings == true) { //if the user has sent something incoming = Bluetooth.read(); //read and clear the stack Bluetooth.println("0-> Set Alarm "); Bluetooth.println("1 -> Control Lamp"); Bluetooth.println("x -> Exit Anytime"); //Display the options wait_for_reply(); incoming = Bluetooth.read(); //read what the user has sent //Based on user request if (incoming == '0') //if user sent 0 { Bluetooth.println("Setting Alarm"); Bluetooth.println("0-> Sleep alarm"); Bluetooth.println("1 -> Wake up Alarm"); //give alarm options wait_for_reply(); incoming = Bluetooth.read(); if (incoming == '0') { Bluetooth.println("Go to sleep at:"); sleep_alarm_hour = get_hour(); sleep_alarm_minute = get_minute(); Bluetooth.print("Sleep alarm set at: "); Bluetooth.print(sleep_alarm_hour); Bluetooth.print(" : "); Bluetooth.println(sleep_alarm_minute); EEPROM.write(0, sleep_alarm_hour); EEPROM.write(1, sleep_alarm_minute); } if (incoming == '1') { Bluetooth.println("Wake me at:"); wake_alarm_hour = get_hour(); wake_alarm_minute = get_minute(); Bluetooth.print("Wake up alarm set at: "); Bluetooth.print(wake_alarm_hour); Bluetooth.print(" : "); Bluetooth.println(wake_alarm_minute); EEPROM.write(2, wake_alarm_hour); EEPROM.write(3, wake_alarm_minute); } incoming = 'x'; } if (incoming == '1') { Bluetooth.println("Select the colour you like"); Bluetooth.println("0-> Red"); Bluetooth.println("1-> Orange"); Bluetooth.println("2-> Yellow"); Bluetooth.println("3-> Green"); Bluetooth.println("4-> Cyan"); Bluetooth.println("5-> Blue"); Bluetooth.println("6-> Purple"); Bluetooth.println("7-> Pink"); do{ wait_for_reply(); incoming = Bluetooth.read(); memcpy(current_rainbow, all_rainbow, 8); glow_rainbow(incoming-48); Serial.println(incoming-48); }while (incoming!='x'); Bluetooth.println("Exiting control mode"); } if (incoming == 'x') //exit from Bluetooth mode { Bluetooth.flush(); incoming = Bluetooth.read(); incoming = 0; settings= false; Bluetooth.println("Back to main"); } } } // Input a value 0 to 255 to get a color value. // The colours are a transition r - g - b - back to r. uint32_t Wheel(byte WheelPos) { WheelPos = 255 - WheelPos; if(WheelPos < 85) { return strip.Color( (255 - WheelPos * 3), 0, (WheelPos * 3) ); } if(WheelPos < 170) { WheelPos -= 85; return strip.Color(0, (WheelPos * 3) , (255 - WheelPos * 3) ); } WheelPos -= 170; return strip.Color((WheelPos * 3), (255 - WheelPos) * 3, 0); } void glow_rainbow(int count) { for (int j=150; j>=10; j--) //decrease the brightness to create dim effect { for (int i=0; i<=5; i++) //do it for all 5 leds { strip.setBrightness(j); strip.show(); } delay(2); } for (int j=0; j<=255; j++) //increase the brightness { for (int i=0; i<=5; i++) //do it for all 5 leds { strip.setPixelColor(i,Wheel(current_rainbow[count]));//select the colour based on count value strip.setBrightness(j); strip.show(); } delay(10); } } void night_lamp() { for (int j=240; j<=254; j++) //decrease the brightness to create dim effect { for (int i=0; i<=5; i++)//do it for all 5 leds { strip.setPixelColor(i, 255-j, 0, 255-j); strip.show(); } delay(300); } for (int j=254; j>=240; j--)//decrease the brightness to create dim effect { { for (int i=0; i<=5; i++)//do it for all 5 leds { strip.setPixelColor(i, 255-j, 0, 255-j); strip.show(); } delay(300); } } } Video microcontroller-projects/interfacing-nrf24l01-with-arduino-transmitter-and-receiver-tutorial

Interfacing nRF24L01 with Arduino: Controlling Servo Motor

While Internet of things (IoT), Industry 4.0, Machine to Machine communication etc are getting increasingly popular the need for wireless communication has become incumbent, with more machines/devices to speak with one another on the cloud. Designers use many wireless communication systems like Bluetooth Low Energy (BLE 4.0), Zigbee, ESP43 Wi-Fi Modules, 433MHz RF Modules, Lora, nRF etc, and the selection of medium depends on the type of application it is being used in. We will also share some solutions for the commonly faced problems while using this module.

Getting to know the nRF24L01 RF Module

is shown below during normal operation which makes it battery efficient and hence can even run on coin cells. Even though the operating voltage is 3.3V most of the pins are 5V tolerant and hence can be directly interfaced with 5V microcontrollers like Arduino. Another advantage of using these modules is that, each module has 6 Pipelines. Meaning, each module can communicate with 6 other modules to transmit or receive data. This makes the module suitable for creating star or mesh networks in IoT applications. Also they have a wide address range of 125 unique ID’s, hence in a closed area we can use 125 of these modules without interfering with each other.

Interfacing nRF24L01 with Arduino

by controlling the servo motor connected with one Arduino by varying the potentiometer on the other Arduino. For the sake of simplicity we have used one nRF24L01 module as transmitter and the other is receiver, but each module can be programmed to send and receive data individually. for the transmitter side. But the logic for connection remains the same for other Arduino boards like mini, mega as well.

Receiver side: ArduinoUno nRF24L01 module connections

On Arduino Nano and UNO the pins 11, 12 and 13 are used for SPI communication. Hence we connect the MOSI, MISO and SCK pins from nRF to the pins 11, 12 and 13 respectively. The pins CE and CS are user configurable, I have used pin 7 and 8 here, but you can use any pin by altering the program. The nRF module is powered by the 3.3V pin on Arduino, which in most cases will work. If not, a separate power supply can be tried. Apart from interfacing the nRF I have also connected a servo motor to pin 7 and powered it through the 5V pin on Arduino. Similarly the transmitter circuit is shown below.

Transmitter side: ArduinoNanonRF24L01 module Connections

The connections for the transmitter is also the same, additionally I have used a potentiometer connected across the 5V ad Ground pin of Arduino. The output analog voltage which will vary from 0-5V is connected to the A7 pin of the Nano. Both the boards are powered through the USB port.

Working with nRF24L01+ Wireless Transceiver Module

which can help you from getting hit on a wall. You can try these when the modules did not work the normal way. 1. Most of the nRF24L01+ modules in the market are fake. The cheap ones that we can find on Ebay and Amazon are the worst (Don’t worry, with few tweaks we can make them work) 2. The main problem is the power supply, not your code. Most of the codes online will work properly, I myself have a working code which I personally tested, Let me know if you need them. 3. Pay attention because the modules which are printed as NRF24L01+ are actually Si24Ri (Yes a Chinese product). 4. The clone and fake modules will consume more power, hence do not develop your power circuit based on nRF24L01+ datasheet, because Si24Ri will have high current consumption about 250mA. 5. Beware of Voltage ripples and current surges, these modules are very sensitive and might easily burn up. (;-( fried up 2 modules so far) 6. Adding a couple capacitors (10uF and 0.1uF) across Vcc and Gnd of the module helps in making your supply pure and this works for most of the modules. , or ask your questions on our forum.

Programming nRF24L01 for Arduino

, in the transmitter code the receiver option will be commented out and in the receiver program the transmitter code will be commented out. You can use it if you are trying a project in which the module has to work as both. The working of the program is explained below. Since the nRF uses SPI protocol we have included the SPI header and also the library that we just downloaded. The servo library is used to control the servo motor. #include <SPI.h> #include "RF24.h" #include <Servo.h> In our circuit diagram we have connected CE to pin 7 and CS to pin 8 so we set the line as RF24 myRadio (7, 8); is used to send and receive data from the RF module. struct package { int msg; }; typedef struct package Package; Package data; but if you have multiple module you can set the ID to any unique 6 digit string. byte addresses[][6] = {"0"}; which is free from noise and also set the module to work in minimum power consumption mode with minimum speed of 250Kbps. void setup() { Serial.begin(9600); myRadio.begin(); myRadio.setChannel(115); //115 band above WIFI signals myRadio.setPALevel(RF24_PA_MIN); //MIN power low rage myRadio.setDataRate( RF24_250KBPS ) ; //Minimum speed myservo.attach(6); Serial.print("Setup Initialized"); delay(500); } function to receive the data that was written. void WriteData() { myRadio.stopListening(); //Stop Receiving and start transminitng myRadio.openWritingPipe(0xF0F0F0F066);//Sends data on this 40-bit address myRadio.write(&data, sizeof(data)); delay(300); } Again out of 6 different pipes using which we can read or write data here we have used 0xF0F0F0F0AA as address to read data. This means the transmitter of the other module has written something on this address and hence we are reading it from the same. void ReadData() { myRadio.openReadingPipe(1, 0xF0F0F0F0AA); //Which pipe to read, 40 bit Address myRadio.startListening(); //Stop Transminting and start Reveicing if ( myRadio.available()) { while (myRadio.available()) { myRadio.read( &data, sizeof(data) ); } Serial.println(data.text); } }

Controlling Servo Motor using nRF24L01 wirelessly

Once you are ready with the program upload the transmitter and receiver code (given below) on respective Arduino boards and power them up with USB port. You can also launch the serial monitor of both the boards to check what value is being transmitted and what is being received. If everything is working as expected when you turn the POT knob on transmitter side the servo on the other side should also turn accordingly. or in the comment section and I will try to resolve them. Code /*Transmit POT value through NRF24L01 using Arduino * * Pin Conections * CE - 7 MISO - 12 MOSI - 11 SCK - 13 CS - 8 POT-A7 */ #include <SPI.h> #include "RF24.h" RF24 myRadio (7, 8); struct package { int msg = 0; }; byte addresses[][6] = {"0"}; typedef struct package Package; Package data; void setup() { Serial.begin(9600); myRadio.begin(); myRadio.setChannel(115); //115 band above WIFI signals myRadio.setPALevel(RF24_PA_MIN); //MIN power low rage myRadio.setDataRate( RF24_250KBPS ) ; //Minimum speed delay(500); Serial.print("Setup Initialized"); } void loop() { int Read_ADC = analogRead(A7); char servo_value = map (Read_ADC, 0, 1024, 0,180); if (servo_value>1) data.msg = servo_value; WriteData(); delay(50); // ReadData(); //delay(200); } void WriteData() { myRadio.stopListening(); //Stop Receiving and start transminitng myRadio.openWritingPipe( 0xF0F0F0F0AA); //Sends data on this 40-bit address myRadio.write(&data, sizeof(data)); Serial.print("\nSent:"); Serial.println(data.msg); delay(300); } void ReadData() { myRadio.openReadingPipe(1, 0xF0F0F0F066); // Which pipe to read, 40 bit Address myRadio.startListening(); //Stop Transminting and start Reveicing if ( myRadio.available()) { while (myRadio.available()) { myRadio.read( &data, sizeof(data) ); } Serial.print("\nReceived:"); Serial.println(data.msg); } } /*CE - 7 MISO - 12 MOSI - 11 SCK - 13 CS - 8 Recently tested with nano */ #include <SPI.h> #include "RF24.h" #include <Servo.h> Servo myservo; RF24 myRadio (7, 8); struct package { int msg; }; typedef struct package Package; Package data; byte addresses[][6] = {"0"}; void setup() { Serial.begin(9600); myRadio.begin(); myRadio.setChannel(115); //115 band above WIFI signals myRadio.setPALevel(RF24_PA_MIN); //MIN power low rage myRadio.setDataRate( RF24_250KBPS ) ; //Minimum speed myservo.attach(6); Serial.print("Setup Initialized"); delay(500); } int Servo_value; int Pev_servo_value; void loop() { ReadData(); delay(50); Pev_servo_value = Servo_value; Servo_value = data.msg; while (Pev_servo_value< Servo_value) { myservo.write(Pev_servo_value); Pev_servo_value++; delay(2); } while (Pev_servo_value> Servo_value) { myservo.write(Pev_servo_value); Pev_servo_value--; delay(2); } //data.msg = "nothing to send"; //WriteData(); // delay(50); } void ReadData() { myRadio.openReadingPipe(1, 0xF0F0F0F0AA); //Which pipe to read, 40 bit Address myRadio.startListening(); //Stop Transminting and start Reveicing if ( myRadio.available()) { while (myRadio.available()) { myRadio.read( &data, sizeof(data) ); } Serial.print("\nReceived:"); Serial.println(data.msg); } } void WriteData() { myRadio.stopListening(); //Stop Receiving and start transminitng myRadio.openWritingPipe(0xF0F0F0F066);//Sends data on this 40-bit address myRadio.write(&data, sizeof(data)); Serial.print("\nSent:"); Serial.println(data.msg); delay(300); } Video microcontroller-projects/iot-based-patient-monitoring-system-using-esp8266-and-arduino

IoT Based Patient Health Monitoring System using ESP8266 and Arduino

is rapidly revolutionizing the healthcare industry. which records the patient heart beat rate and body temperature and also send an email/SMSalert whenever those readings goes beyond critical values. Pulse rate and body temperature readings are recorded over ThingSpeak and Google sheets so that patient health can be monitored from anywhere in the world over internet. A panic will also be attached so that patient can press it on emergency to send email/sms to their relatives.

Materials required

Arduino Unoand Programming Cable ESP8266 Wi-Fi module LM35 temperature sensor Pulse rate sensor Push button 10k Resistor Male-female wires Breadboard

Pulse Rate Sensor

Pulse Sensor is a well-designed plug-and-play heart-rate sensor for Arduino.The sensor clips onto a fingertip or earlobe and plugs right into Arduino. It also includes an open-source monitoring app that graphs your pulse in real time. The front of the sensor is the covered with the Heart shape logo. This is the side that makes contact with the skin. On the front you see a small round hole, which is where the LED shines through from the back, and there is also a little square just under the LED. The square is an ambient light sensor, exactly like the one used in cellphones, tablets, and laptops, to adjust the screen brightness in different light conditions. The LED shines light into the fingertip or earlobe, or other capillary tissue, and sensor reads the amount of light that bounces back. That’s how it calculates the heart rate. The other side of the sensor is where the rest of the parts are mounted.

Before we use this sensor, we need to protect the exposed side of the sensor so that we can get accurate readings and avoid the short circuit due to sweat. For this, you can use Velcro strip or black tape. As shown in the picture.

There are three wires coming out of the sensor, Signal(S), Vcc(3 - 5 V) and GND.

LM35 Temperature Sensor

C rise or fall in temperature. It can be operated from a 5V as well as 3.3 V supply and the stand by current is less than 60uA.

ESP8266-01

There are two of ways to work with your ESP8266 module. This tutorial will help you to get started with ESP8266.One way is by using the AT commands. The other way is by using the Arduino IDE. Here we will use AT commands to send data from Arduino to ESP.

Circuit Diagram

Below are the connections: Signal pin of pulse sensor -> A0 of arduino Vcc pin of pulse sensor -> 5V of arduino GND pin of pulse sensor -> GND of arduino Vout of LM35 -> A1 of Arduino Tx of ESP8266 -> pin 10 of arduino Rx of ESP8266 -> pin 11 of arduino CH_PD and Vcc of ESP8266 -> 3.3 V of arduino GND of ESP8266 -> GND of arduino Push button -> digital pin 8 of arduino

Configuring ThingSpeak to record Patient Data online

platform to connect ThingSpeak to email/message service so that alert message can be sent whenever the patient is in critical state. option on the same page for further process. , fill in the Name and Description as per your choice. Then fill ‘Pulse Rateᾬ ‘Temperatureᾠand ‘Panicᾠin Field 1, Field 2 and Field 3 labels, tick the checkboxes for the Fields. Also tick the check box for ‘Make Publicᾠoption below in the form and finally Save the Channel. Now your new channel has been created. , we will use this key in our code. To make New ThingHTTP, we will need URL for triggering which we will get from IFTTT.

Configuring IFTTT for triggering Mail/SMS based on ThingSpeak Values

and click on it. Type “Patient_Infoᾠin the event box and copy the URL. We will use this URL in ThingHTTP. Now let’s make Applet to link ThingHTTP to Google sheet and to send email/sms. After that we will jump to complete our ThingHTTP. option. Click on ᾫthisᾠand search for Webhooks and click on it. Choose trigger as “Receive a web requestᾮ Type the Event Name which is same as you write in the event box in webhooks URL. Click on Create Trigger. Click on ᾫthatᾠand search for Google Sheets and click on it. Give any name to your sheet. In formatted row box, you have date and time, event name, BPM value and body temperature which will be written as shown. Review your applet and click on finish. , then in event name enter “Panicᾮ In ᾫthatᾠsearch for Gmail and click on it. Now, click on Send an email. Type the email addresses on which you wish to receive email when there is a panic to the patient. Type the body content you wish to send in the email and click on create action. Review it and finish.

ThingHTTP for connecting ThingSpeak with IFTTT

Give any name and Paste the URL that you copied from the webhooks documentation. Fill Remaining information as shown below. In Body, we have to write the information that we want to send to the IFTTT applet. We are sending patient Pulse reading and temperature. So the format is { "value1" : "%%channel_channelID_field_fieldNumber%%","value2" : "%%channel_channelID_field_fieldNumber%%"} In the same manner, we have to make ThingHTTP for “Panicᾮ Follow the same steps. Body remains empty and All other information are same as in previous ThingHTTP. Save it. React works with ThingHTTPapp to perform actions when channel data meets a certain condition. Give name to your React. Condition type as Numeric and Test Freaquency as on Data Insertion. any value. I have used 60. As shown . as shown. Select “Run action each time condition is metᾠand click on Save React. We have done with Web based work. Now, we will see code for Arduino.

Arduino Code Explanation

Let’s jump to coding part‐󋈍 First, we include all the libraries. We are using software serial to communicate with esp8266. #include <SoftwareSerial.h> #include "Timer.h" #include <PulseSensorPlayground.h> //pulse sensor library Make instance for timer, SoftwareSerial and pulse sensor to use in our code. Timer t; PulseSensorPlayground pulseSensor; SoftwareSerial esp8266(10,11); //Rx,Tx Set-up low-level interrupts for most accurate BPM match and enable DEBUG to show ongoing commands on serial monitor. #define USE_ARDUINO_INTERRUPTS true #define DEBUG true Set your WiFi name , password and IP of thingspeak.com #define SSID "*********" // "your WiFiname" #define PASS "**********" // "wifi password" #define IP "184.106.153.149" // thingspeak.com ip and paste here. String msg = "GET /update?key=Your Api Key"; you defined. void setup() { Serial.begin(9600); esp8266.begin(115200); pulseSensor.analogInput(PulseWire); pulseSensor.blinkOnPulse(LED13); //auto-magically blink Arduino's LED with heartbeat. pulseSensor.setThreshold(Threshold); // Double-check the "pulseSensor" object was created and "began" seeing a signal. if (pulseSensor.begin()) { Serial.println("We created a pulseSensor Object !"); } Serial.println("AT"); esp8266.println("AT"); delay(3000); if(esp8266.find("OK")) { connectWiFi(); } t.every(10000, getReadings); t.every(10000, updateInfo); } command, used in this function, is to connect to your Access Point (your Wi-Fi router). boolean connectWiFi() { Serial.println("AT+CWMODE=1"); esp8266.println("AT+CWMODE=1"); delay(2000); String cmd="AT+CWJAP=\""; cmd+=SSID; cmd+="\",\""; cmd+=PASS; cmd+="\""; Serial.println(cmd); esp8266.println(cmd); …… ‐󬬼/strong> void getReadings(){ raw_myTemp = analogRead(A1); Voltage = (raw_myTemp / 1023.0) * 5000; // 5000 to get millivots. tempC = Voltage * 0.1; //in degree C myTemp = (tempC * 1.8) + 32; // conver to F Serial.println(myTemp); int myBPM = pulseSensor.getBeatsPerMinute(); // Calls function on our pulseSensor object that returns BPM as an "int". if (pulseSensor.sawStartOfBeat()) { // Constantly test to see if "a beat happened". Serial.println(myBPM); // Print the value inside of myBPM. } delay(20); char buffer1[10]; char buffer2[10]; BPM = dtostrf(myBPM, 4, 1, buffer1); temp = dtostrf(myTemp, 4, 1, buffer2); } Make function for updating sensor information on the ThingSpeak channel. AT Command will establish TCP command over port 80 void updateInfo() { String cmd = "AT+CIPSTART=\"TCP\",\""; cmd += IP; cmd += "\",80"; Serial.println(cmd); esp8266.println(cmd); delay(2000); if(esp8266.find("Error")) { return; } Attach the readings with the GET URL using "&field1="; for pulse readings and "&field2="; for temperature readings. Send this information using “AT+CIPSEND=ᾠcommand. cmd = msg ; cmd += "&field1="; //field 1 for BPM cmd += BPM; cmd += "&field2="; //field 2 for temperature cmd += temp; cmd += "\r\n"; Serial.print("AT+CIPSEND="); esp8266.print("AT+CIPSEND="); Serial.println(cmd.length()); esp8266.println(cmd.length()); if(esp8266.find(">")) { Serial.print(cmd); esp8266.print(cmd); } … ‐󺮳trong> When button goes to HIGH, esp8266 send the information to the server using AT+CIPSTART and AT+CIPSEND commands. void panic_button(){ panic = digitalRead(8); if(panic == HIGH){ Serial.println(panic); String cmd = "AT+CIPSTART=\"TCP\",\""; cmd += IP; cmd += "\",80"; Serial.println(cmd); esp8266.println(cmd); ….. .. Attach this information to "&field3=ᾮ cmd = msg ; cmd += "&field3="; function . void loop() { panic_button(); start: //label error=0; t.update(); …… …‐󺮳trong>

Patient Monitoring System in Action

Now, connect your hardware components according to the circuit diagram and upload the code to the Arduino. Open Serial monitor to see what’s going inside the code. You will see data is updated defined in the Google sheets on Google drive, after the interval you defined in the timer setting. Press panic button for 4-5 seconds, you will get email that patient is in problem, like shown below: given below. Code #define USE_ARDUINO_INTERRUPTS true #define DEBUG true #define SSID "********" // "SSID-WiFiname" #define PASS "************" // "password" #define IP "184.106.153.149" // thingspeak.com ip #include <SoftwareSerial.h> #include "Timer.h" #include <PulseSensorPlayground.h> // Includes the PulseSensorPlayground Library. Timer t; PulseSensorPlayground pulseSensor; String msg = "GET /update?key=your api key"; SoftwareSerial esp8266(10,11); //Variables const int PulseWire = A0; // PulseSensor PURPLE WIRE connected to ANALOG PIN 0 const int LED13 = 13; // The on-board Arduino LED, close to PIN 13. int Threshold = 550; //for heart rate sensor float myTemp; int myBPM; String BPM; String temp; int error; int panic; int raw_myTemp; float Voltage; float tempC; void setup() { Serial.begin(9600); esp8266.begin(115200); pulseSensor.analogInput(PulseWire); pulseSensor.blinkOnPulse(LED13); //auto-magically blink Arduino's LED with heartbeat. pulseSensor.setThreshold(Threshold); // Double-check the "pulseSensor" object was created and "began" seeing a signal. if (pulseSensor.begin()) { Serial.println("We created a pulseSensor Object !"); //This prints one time at Arduino power-up, or on Arduino reset. } Serial.println("AT"); esp8266.println("AT"); delay(3000); if(esp8266.find("OK")) { connectWiFi(); } t.every(10000, getReadings); t.every(10000, updateInfo); } void loop() { panic_button(); start: //label error=0; t.update(); //Resend if transmission is not completed if (error==1) { goto start; //go to label "start" } delay(4000); } void updateInfo() { String cmd = "AT+CIPSTART=\"TCP\",\""; cmd += IP; cmd += "\",80"; Serial.println(cmd); esp8266.println(cmd); delay(2000); if(esp8266.find("Error")) { return; } cmd = msg ; cmd += "&field1="; //field 1 for BPM cmd += BPM; cmd += "&field2="; //field 2 for temperature cmd += temp; cmd += "\r\n"; Serial.print("AT+CIPSEND="); esp8266.print("AT+CIPSEND="); Serial.println(cmd.length()); esp8266.println(cmd.length()); if(esp8266.find(">")) { Serial.print(cmd); esp8266.print(cmd); } else { Serial.println("AT+CIPCLOSE"); esp8266.println("AT+CIPCLOSE"); //Resend... error=1; } } boolean connectWiFi() { Serial.println("AT+CWMODE=1"); esp8266.println("AT+CWMODE=1"); delay(2000); String cmd="AT+CWJAP=\""; cmd+=SSID; cmd+="\",\""; cmd+=PASS; cmd+="\""; Serial.println(cmd); esp8266.println(cmd); delay(5000); if(esp8266.find("OK")) { return true; } else { return false; } } void getReadings(){ raw_myTemp = analogRead(A1); Voltage = (raw_myTemp / 1023.0) * 5000; // 5000 to get millivots. tempC = Voltage * 0.1; myTemp = (tempC * 1.8) + 32; // conver to F Serial.println(myTemp); int myBPM = pulseSensor.getBeatsPerMinute(); // Calls function on our pulseSensor object that returns BPM as an "int". // "myBPM" hold this BPM value now. if (pulseSensor.sawStartOfBeat()) { // Constantly test to see if "a beat happened". Serial.println(myBPM); // Print the value inside of myBPM. } delay(20); char buffer1[10]; char buffer2[10]; BPM = dtostrf(myBPM, 4, 1, buffer1); temp = dtostrf(myTemp, 4, 1, buffer2); } void panic_button(){ panic = digitalRead(8); if(panic == HIGH){ Serial.println(panic); String cmd = "AT+CIPSTART=\"TCP\",\""; cmd += IP; cmd += "\",80"; Serial.println(cmd); esp8266.println(cmd); delay(2000); if(esp8266.find("Error")) { return; } cmd = msg ; cmd += "&field3="; cmd += panic; cmd += "\r\n"; Serial.print("AT+CIPSEND="); esp8266.print("AT+CIPSEND="); Serial.println(cmd.length()); esp8266.println(cmd.length()); if(esp8266.find(">")) { Serial.print(cmd); esp8266.print(cmd); } else { Serial.println("AT+CIPCLOSE"); esp8266.println("AT+CIPCLOSE"); //Resend... error=1; } } } Video microcontroller-projects/arduino-uno-guitar-tuner

Arduino Based Guitar Tuner

How Guitar Tuner Works

is defined as the loudness or lowness of sound and its indicated by the frequency of that sound. Since the frequency of these notes are known, for us to determine if the guitar is tuned or not, we only need to compare the frequency of the note of particular string to the actual frequency of the note that the string represents. The frequencies of the 7 musical notes are: Each variation of these notes is always at a pitch equal to FxM where F is the frequency and M is a non-zero integer. Thus for the last A which as described earlier, is at an octave higher than the first A, the frequency is; The guitar (Lead/box guitar) usually has 6 strings denoted by the notes E, A, D, G, B, E on open string. As usual, last E will be at an octave higher than the first E. We will be designing our guitar tuner to help tune the guitar using the frequencies of these notes. According to the standard guitar tuning, the note and corresponding frequency of each string is shown in the table below.
StringsFrequencyNotation
1 (E)329.63HzE4
2 (B)246.94HzB3
3 (G)196.00HzG3
4 (D)146.83HzD3
5 (A)110.00HzA2
6 (E)82.41HzE2
is quite simple; we convert the sound signal generated by the guitar to a frequency then compare with the exact frequency value of the string being tuned. The guitarist is notified using an LED when the value correlates. The frequency detection/conversion involves 3 main stages; Amplifying Offsetting Analog to Digital conversion(sampling) and the frequency of that sound is obtained.

Required components

The following components are required to build this project; Arduino Uno x1 LM386 x1 Condenser Mic x1 Microphone / Audio jack x1 10k potentiometer x1 O.1uf capacitor x2 100ohms resistor x4 10ohms resistor x1 10uf capacitor x3 5mm yellow LED x2 5mm green LED x1 Normally Open Push Buttons x6 Jumper wires Breadboard

Schematics

below. The push buttons are connected without pull up/down resistors because the Arduino’s in built pullup resistors will be used. This is to ensure the circuit is as simple as possible.

Arduino Code for Guitar Tuner

is given at the end, here we have briefly explained the important parts of code. We start by creating an array to hold the switches. int buttonarray[] = {13, 12, 11, 10, 9, 8}; // [E2, A2, D3, G3, B3, E4] Next, we create an array to hold the corresponding frequency for each of the strings. float freqarray[] = {82.41, 110.00, 146.83, 196.00, 246.94, 329.63};//all in Hz With this done, we then declare the pins to which the LEDs are connected and other variables that will be used for obtaining the frequency from the ADC. int lowerLed = 7; int higherLed = 6; int justRight = 5; #define LENGTH 512 byte rawData[LENGTH]; int count; function. Here we start by enabling the internal pull up on the Arduino for each of the pins to which the switches is connected. After which we set the pins to which the LEDs are connected as outputs and launch the serial monitor to display the data. void setup() { for (int i=0; i<=5; i++) { pinMode(buttonarray[i], INPUT_PULLUP); } pinMode(lowerLed, OUTPUT); pinMode(higherLed, OUTPUT); pinMode(justRight, OUTPUT); Serial.begin(115200); } void loop(){ if (count < LENGTH) { count++; rawData[count] = analogRead(A0)>>2; } else { sum = 0; pd_state = 0; int period = 0; for(i=0; i < len; i++) { // Autocorrelation sum_old = sum; sum = 0; for(k=0; k < len-i; k++) sum += (rawData[k]-128)*(rawData[k+i]-128)/256; // Serial.println(sum); // Peak Detect State Machine if (pd_state == 2 && (sum-sum_old) <=0) { period = i; pd_state = 3; } if (pd_state == 1 && (sum > thresh) && (sum-sum_old) > 0) pd_state = 2; if (!i) { thresh = sum * 0.5; pd_state = 1; } } // Frequency identified in Hz if (thresh >100) { freq_per = sample_freq/period; Serial.println(freq_per); for (int s=0; s<=5; s++) { if (digitalRead(buttonarray[i])== HIGH) { if (freq_per - freqarray[i] < 0) { digitalWrite(lowerLed, HIGH); } else if(freq_per - freqarray[i] > 10) { digitalWrite(higherLed, HIGH); } else { digitalWrite(justRight, HIGH); } } } } count = 0; } } is given below. Upload the code to your Arduino board and strum away. Code int buttonarray[] = {13, 12, 11, 10, 9, 8}; // [E2, A2, D3, G3, B3, E4] // each pin represents a guitar string // next we create and array with frequencies matching each of the strings above // such that when 13 is selected the freq matching the note e is selected). float freqarray[] = {82.41, 110.00, 146.83, 196.00, 246.94, 329.63};//sll in Hz int lowerLed = 7; int higherLed = 6; int justRight = 5; #define LENGTH 512 byte rawData[LENGTH]; int count = 0; // Sample Frequency in kHz const float sample_freq = 8919; int len = sizeof(rawData); int i,k; long sum, sum_old; int thresh = 0; float freq_per = 0; byte pd_state = 0; void setup(){ for (int i=0; i<=5; i++) { pinMode(buttonarray[i], INPUT_PULLUP); } pinMode(lowerLed, OUTPUT); pinMode(higherLed, OUTPUT); pinMode(justRight, OUTPUT); Serial.begin(115200); } void loop(){ if (count < LENGTH) { count++; rawData[count] = analogRead(A0)>>2; } else { sum = 0; pd_state = 0; int period = 0; for(i=0; i < len; i++) { // Autocorrelation sum_old = sum; sum = 0; for(k=0; k < len-i; k++) sum += (rawData[k]-128)*(rawData[k+i]-128)/256; // Serial.println(sum); // Peak Detect State Machine if (pd_state == 2 && (sum-sum_old) <=0) { period = i; pd_state = 3; } if (pd_state == 1 && (sum > thresh) && (sum-sum_old) > 0) pd_state = 2; if (!i) { thresh = sum * 0.5; pd_state = 1; } } // Frequency identified in Hz if (thresh >100) { freq_per = sample_freq/period; Serial.println(freq_per); for (int s=0; s<=5; s++) { if (digitalRead(buttonarray[i])== HIGH) { if (freq_per - freqarray[i] < 0) { digitalWrite(lowerLed, HIGH); } else if(freq_per - freqarray[i] > 10) { digitalWrite(higherLed, HIGH); } else { digitalWrite(justRight, HIGH); } } } } count = 0; } } Video microcontroller-projects/arduino-analog-speedometer-using-ir-sensor

Analog Speedometer Using Arduino and IR Sensor

, but using an IR sensor is easy because IR sensor module is very common device and we can get it easily from the market and also it can be used on any type of motor/Vehicle.

Materials Required

Arduino A bipolar stepper motor (4 wire) Stepper motor driver (L298n Module) IR sensor module 16*2 LCD display 2.2k resistor Connecting wires Breadboard. Power supply Speedometer picture printout

Calculating Speed and Showing it on Analog Speedometer

is a device which can detect the presence of an object in front of it. We have used two blade rotor (fan) and placed the IR sensor near it in such a way that every time the blades rotate the IR sensor detects it. We then use the help of timers and Interrupts in Arduino to calculate the time taken for one complete rotation of the motor. will be executed. And as we have used two blade rotor, It means the function will be called 4 times in one revolution. Once the time taken is known we can calculate the RPM by using the below formulae, Where 1000/time taken will give us the RPS (revolution per second) and further multiplying it with 60 will give you the RPM (revolution per minute) rpm = (60/2)*(1000/(millis() - time))*REV/bladesInFan; After getting RPM, speed can be calculated by given formula: Speed = rpm * (2 * Pi * radius) / 1000 We know that Pi = 3.14 and radius is 4.7 inch But first we need to convert radius into meters from inches: radius = ((radius * 2.54)/100.0) meters Speed= rpm * 60.0 * (2.0 * 3.14 * radius)/ 1000.0) in kilometers per hour Here we have multiplied rpm by 60 to convert rpm to rph (revolution per hour) and divided by 1000 to convert meters/hour to Kilometers/hour. we need to do one more calculation to find out no. of steps, stepper motor should move to show speed on analog meter. Here we have used a 4 wire bipolar stepper motor for analog meter, which is having 1.8 degree means 200 steps per revolution. Now we have to show 280 Kmh on speedometer. So to show 280 Kmh stepper motor needs to move 280 degree So we have maxSpeed = 280 And maxSteps will be maxSteps = 280/1.8 = 155 steps which is used here to map speed into steps. Steps = map(speed,0,maxSpeed,0,maxSteps); So now we have steps=map(speed,0,280,0,155); After calculating steps we can directly apply these steps in stepper motor function to move stepper motor. We also need to take care of current steps or angle of the stepper motor by using given calculations currSteps=Steps steps= currSteps-preSteps preSteps=currSteps is last performed steps.

Circuit Diagram and Connections

to show speed in digital form and stepper motor to rotate the analog speedometer needle. 16x2 LCD is connected at following analog pins of Arduino. RS - A5 RW -GND EN - A4 D4 - A3 D5 - A2 D6 - A1 D7 - A0 A 2.2k resistor is used to set the brightness of LCD. An IR sensor module, which is used to detect fan’s blade to calculate the rpm, is connected to interrupt 0 means D2 pin of Arduino. IN1, IN2, IN3 and IN4 pin of stepper motor driver is directly connected to D8, D9, D10, and D11 of Arduino. Rest of connections are given in Circuit Diagram.

Programming Explanation

r is given at the end, here we are explaining few important part of it. like stepper motor library, LiquidCrystal LCD library and declared pins for them. #include<LiquidCrystal.h> LiquidCrystal lcd(A5,A4,A3,A2,A1,A0); #include <Stepper.h> const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); After this, we have taken some variables and macros for performing the calculations. Calculations are already explained in the previous section. volatile byte REV; unsigned long int rpm,RPM; unsigned long st=0; unsigned long time; int ledPin = 13; int led = 0,RPMlen , prevRPM; int flag = 0; int flag1=1; #define bladesInFan 2 float radius=4.7; // inch int preSteps=0; float stepAngle= 360.0/(float)stepsPerRevolution; float minSpeed=0; float maxSpeed=280.0; float minSteps=0; float maxSteps=maxSpeed/stepAngle; function void setup() { myStepper.setSpeed(60); Serial.begin(9600); pinMode(ledPin, OUTPUT); lcd.begin(16,2); lcd.print("Speedometer"); delay(2000); attachInterrupt(0, RPMCount, RISING); } function and perform a calculation to get speed and convert that into steps to run stepper motor to show speed in analog form. void loop() { readRPM(); radius=((radius * 2.54)/100.0); // convering in meter int Speed= ((float)RPM * 60.0 * (2.0 * 3.14 * radius)/1000.0); // RPM in 60 minute, diameter of tyre (2pi r) r is radius, 1000 to convert in km int Steps=map(Speed, minSpeed,maxSpeed,minSteps,maxSteps); if(flag1) { Serial.print(Speed); Serial.println("Kmh"); lcd.setCursor(0,0); lcd.print("RPM: "); lcd.print(RPM); lcd.print(" "); lcd.setCursor(0,1); lcd.print("Speed: "); lcd.print(Speed); lcd.print(" Km/h "); flag1=0; } int currSteps=Steps; int steps= currSteps-preSteps; preSteps=currSteps; myStepper.step(steps); } function to calculate RPM. int readRPM() { if(REV >= 10 or millis()>=st+1000) // IT WILL UPDATE AFETR EVERY 10 READINGS or 1 second in idle { if(flag==0) flag=1; rpm = (60/2)*(1000/(millis() - time))*REV/bladesInFan; time = millis(); REV = 0; int x= rpm; while(x!=0) { x = x/10; RPMlen++; } Serial.println(rpm,DEC); RPM=rpm; delay(500); st=millis(); flag1=1; } } Finally, we have interrupt routine which is responsible to measure revolution of object void RPMCount() { REV++; if (led == LOW) { led = HIGH; } else { led = LOW; } digitalWrite(ledPin, led); } for the same. Code #include<LiquidCrystal.h> LiquidCrystal lcd(A5,A4,A3,A2,A1,A0); #include <Stepper.h> const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); volatile byte REV; unsigned long int rpm,RPM; unsigned long st=0; unsigned long time; int ledPin = 13; int led = 0,RPMlen , prevRPM; int flag = 0; int flag1=1; #define bladesInFan 2 float radius=4.7; // inch int preSteps=0; float stepAngle= 360.0/(float)stepsPerRevolution; float minSpeed=0; float maxSpeed=280.0; float minSteps=0; float maxSteps=maxSpeed/stepAngle; void setup() { myStepper.setSpeed(60); Serial.begin(9600); pinMode(ledPin, OUTPUT); lcd.begin(16,2); lcd.print("Speedometer"); delay(2000); attachInterrupt(0, RPMCount, RISING); } void loop() { readRPM(); radius=((radius * 2.54)/100.0); // convering in meter int Speed= ((float)RPM * 60.0 * (2.0 * 3.14 * radius)/1000.0); // RPM in 60 minute, diameter of tyre (2pi r) r is radius, 1000 to convert in km int Steps=map(Speed, minSpeed,maxSpeed,minSteps,maxSteps); if(flag1) { Serial.print(Speed); Serial.println("Kmh"); lcd.setCursor(0,0); lcd.print("RPM: "); lcd.print(RPM); lcd.print(" "); lcd.setCursor(0,1); lcd.print("Speed: "); lcd.print(Speed); lcd.print(" Km/h "); flag1=0; } int currSteps=Steps; int steps= currSteps-preSteps; preSteps=currSteps; myStepper.step(steps); } int readRPM() { if(REV >= 10 or millis()>=st+1000) // IT WILL UPDATE AFETR EVERY 10 READINGS or 1 second in idle { if(flag==0) flag=1; rpm = (60/2)*(1000/(millis() - time))*REV/bladesInFan; time = millis(); REV = 0; int x= rpm; while(x!=0) { x = x/10; RPMlen++; } Serial.println(rpm,DEC); RPM=rpm; delay(500); st=millis(); flag1=1; } } void RPMCount() { REV++; if (led == LOW) { led = HIGH; } else { led = LOW; } digitalWrite(ledPin, led); } Video microcontroller-projects/arduino-lc-meter-measure-inductance

LC Meter using Arduino: Measuring Inductance and Frequency

A push button is given in the circuit, to switch between capacitance and inductance display.

Components Required

Arduino Uno 741 opamp IC 3v battery 100-ohm resistor Capacitors Inductors 1n4007 diode 10k resistor 10k pot Power supply Push button Breadboard or PCB Connecting wires

Calculating Frequency and Inductance

f=1/(2*time) function now we have LC circuit Frequency: f=1/2*Pi* square root of (LC) we can solve it to get inductance: f2 = 1/ (4Pi2LC) L= 1/ (4Pi2 f2C) L = 1/(4* Pi * Pi * f * f * C) function measure only one pulse, so now to get correct frequency we have to multiply it by to 2. Now we have a frequency which can be converted into inductance by using the above formula. while measuring inductance (L1), capacitor (C1) value should be 0.1uF and while measuring capacitance (C1), inductor (L1) value should be 10mH.

Circuit Diagram and Explanation

, we have used Arduino to control the project operation. In this, we have used an LC circuit. This LC circuit consists of an Inductor and a capacitor. To convert sinusoidal resonance frequency to digital or square wave we have used operational amplifier namely 741. Here we need to apply negative supply to op-amp to get accurate output frequency. So we have used a 3v battery connected in reverse polarity, means 741 negative pin is connected to battery negative terminal and positive pin of the battery is connected to the ground of the remaining circuit. For more clarification see the circuit diagram below. whether we are measuring inductance or capacitance. A 16x2 LCD is used to show inductance or capacitance with the frequency of LC circuit. A 10k pot is used for controlling the brightness of the LCD. Circuit is powered with the help of Arduino 5v supply and we can power the Arduino by 5v using USB or 12v adaptor.

Programming Explanation

code is given at the end of this article. First we have to include library for LCD and declare some pins and macros. #include<LiquidCrystal.h> LiquidCrystal lcd(A5, A4, A3, A2, A1, A0); #define serial #define charge 3 #define freqIn 2 #define mode 10 #define Delay 15 double frequency, capacitance, inductance; typedef struct { int flag: 1; }Flag; Flag Bit; to show measured values over the LCD and serial monitor. void setup() { #ifdef serial Serial.begin(9600); #endif lcd.begin(16, 2); pinMode(freqIn, INPUT); pinMode(charge, OUTPUT); pinMode(mode, INPUT_PULLUP); lcd.print(" LC Meter Using "); lcd.setCursor(0, 1); lcd.print(" Arduino "); delay(2000); lcd.clear(); lcd.print("Circuit Digest"); delay(2000); } : void loop() { for(int i=0;i<Delay;i++) { digitalWrite(charge, HIGH); delayMicroseconds(100); digitalWrite(charge, LOW); delayMicroseconds(50); double Pulse = pulseIn(freqIn, HIGH, 10000); if (Pulse > 0.1) frequency+= 1.E6 / (2 * Pulse); delay(20); } frequency/=Delay; #ifdef serial Serial.print("frequency:"); Serial.print( frequency ); Serial.print(" Hz "); #endif lcd.setCursor(0, 0); lcd.print("freq:"); lcd.print( frequency ); lcd.print(" Hz "); by using given piece of code capacitance = 0.1E-6; inductance = (1. / (capacitance * frequency * frequency * 4.*3.14159 * 3.14159)) * 1.E6; #ifdef serial Serial.print("Ind:"); if(inductance>=1000) { Serial.print( inductance/1000 ); Serial.println(" mH"); } else { Serial.print( inductance ); Serial.println(" uH"); } #endif lcd.setCursor(0, 1); lcd.print("Ind:"); if(inductance>=1000) { lcd.print( inductance/1000 ); lcd.print(" mH "); } else { lcd.print( inductance ); lcd.print(" uH "); } } if (Bit.flag) { inductance = 1.E-3; capacitance = ((1. / (inductance * frequency * frequency * 4.*3.14159 * 3.14159)) * 1.E9); if((int)capacitance < 0) capacitance=0; #ifdef serial Serial.print("Capacitance:"); Serial.print( capacitance,6); Serial.println(" uF "); #endif lcd.setCursor(0, 1); lcd.print("Cap: "); if(capacitance > 47) { lcd.print( (capacitance/1000)); lcd.print(" uF "); } else { lcd.print(capacitance); lcd.print(" nF "); } } and displayed it on 16x2 LCD. Code #include<LiquidCrystal.h> LiquidCrystal lcd(A5, A4, A3, A2, A1, A0); #define serial #define charge 3 #define freqIn 2 #define mode 10 #define Delay 15 double frequency, capacitance, inductance; typedef struct { int flag: 1; }Flag; Flag Bit; void setup() { #ifdef serial Serial.begin(9600); #endif lcd.begin(16, 2); pinMode(freqIn, INPUT); pinMode(charge, OUTPUT); pinMode(mode, INPUT_PULLUP); lcd.print(" LC Meter Using "); lcd.setCursor(0, 1); lcd.print(" Arduino "); delay(2000); lcd.clear(); lcd.print("Circuit Digest"); delay(2000); } void loop() { for(int i=0;i<Delay;i++) { digitalWrite(charge, HIGH); delayMicroseconds(100); digitalWrite(charge, LOW); delayMicroseconds(50); double Pulse = pulseIn(freqIn, HIGH, 10000); if (Pulse > 0.1) frequency+= 1.E6 / (2 * Pulse); delay(20); } frequency/=Delay; #ifdef serial Serial.print("frequency:"); Serial.print( frequency ); Serial.print(" Hz "); #endif lcd.setCursor(0, 0); lcd.print("freq:"); lcd.print( frequency ); lcd.print(" Hz "); if (Bit.flag) { inductance = 1.E-3; capacitance = ((1. / (inductance * frequency * frequency * 4.*3.14159 * 3.14159)) * 1.E9); if((int)capacitance < 0) capacitance=0; #ifdef serial Serial.print("Capacitance:"); Serial.print( capacitance,6); Serial.println(" uF "); #endif lcd.setCursor(0, 1); lcd.print("Cap: "); if(capacitance > 47) { lcd.print( (capacitance/1000)); lcd.print(" uF "); } else { lcd.print(capacitance); lcd.print(" nF "); } } else { capacitance = 0.1E-6; inductance = (1. / (capacitance * frequency * frequency * 4.*3.14159 * 3.14159)) * 1.E6; #ifdef serial Serial.print("Ind:"); if(inductance>=1000) { Serial.print( inductance/1000 ); Serial.println(" mH"); } else { Serial.print( inductance ); Serial.println(" uH"); } #endif lcd.setCursor(0, 1); lcd.print("Ind:"); if(inductance>=1000) { lcd.print( inductance/1000 ); lcd.print(" mH "); } else { lcd.print( inductance ); lcd.print(" uH "); } } if (digitalRead(mode) == LOW) { Bit.flag = !Bit.flag; delay(1000); while (digitalRead(mode) == LOW); } delay(50); } Video microcontroller-projects/arduino-wattmeter-to-measure-voltage-current-power-consumption

Arduino Wattmeter: Measure Voltage, Current and Power Consumption

As electronics engineers, we always depend upon meters/instruments to measure and analyse the working of a circuit. Starting with a simple multimeter to a complex power quality analysers or DSOs everything has their own unique applications. Most of these meters are readily available and can be purchased based on the parameters to be measured and their accuracy. But sometimes we might end up in a situation where we need to build our own meters. Say for instance you are working on a solar PV project and you would like to calculate the power consumption of your load, in such scenarios we can build our own Wattmeter using a simple microcontroller platform like Arduino. at pre-defined intervals. Sounds interesting right!? So let’s get started...

Materials Required

Arduino Nano LM358 Op-Amp 7805 Voltage regulator 16*2 LCD display 0.22 ohm 2Watt shunt resistor 10k Trimmer pot 10k,20k,2.2k,1k Resistors 0.1uF Capacitors Test Load Perf board or breadboard Soldering kit (optional)

Circuit Diagram

is given below. is split into two units. The upper part of the circuit is the measuring unit and the lower part of the circuit is the computation and display unit. For people who are new to this type of circuits followed the labels. Example +5V is label which means that all the pins to which label is connected to should be considered as they are connected together. Labels are normally used to make the circuit diagram look neat. The circuit is designed to fit into systems operating between 0-24V with a current range of 0-1A keeping in mind the specification of a Solar PV. But you can easily extend the range once you understand the working of the circuit. The underlying principle behind the circuit is to measure the voltage across the load and current through it to calculate the power consumes by it. All the measured values will be displayed in a 16*2 Alphanumeric LCD. Further below let’s split the circuit into small segments so that we can get a clear picture of how the circuit is indented to work.

Measuring Unit

The measuring unit consists of a potential divider to help us measure the voltage and a shut resistor with a Non-Inverting Op-amp is used to help us measure the current through the circuit. The potential divider part from the above circuit is shown below to calculate value of resistor if you are re-designing the circuit. Vout = (Vin × R2) / (R1 + R2) The mapped 0-5V can be obtained from the middle part which is labelled as Voltage. This mapped voltage can then be fed to the Arduino Analog pin later. Next we have to measure the current through the LOAD. As we know microcontrollers can read only analog voltage, so we need to somehow convert the value of current to voltage. It can be done by simply adding a resistor (shunt resistor) in the path which according to Ohm’s law will drop a value of voltage across it that is proportional to the current flowing through it. The value of this voltage drop will be very less so we use an op-amp to amplify it. The circuit for the same is shown below we can calculate the voltage drop across this resistor which will be around 0.2V when a maximum of 1A current is passing through the load. This voltage is very small for a microcontroller to read, we use an Op-Amp in Non-Inverting Amplifier mode to increase the voltage from 0.2V to higher level for the Arduino to read. The Op-Amp in Non-Inverting mode is shown above. The amplifier is designed to have a gain of 21, so that 0.2*21 = 4.2V. The formulae to calculate the gain of the Op-amp is given below, you can also use this online gain calculator to get the value of your resistor if you are re-designing the circuit. Gain = Vout / Vin = 1 + (Rf / Rin) Here in our case the value of Rf is 20k and the value of Rin is 1k which gives us a gian value of 21. The amplified voltage form the Op-amp is then given to a RC filter with resistor 1k and a capacitor 0.1uF to filter any noise that is coupled. Finally the voltage is then fed to the Arduino analog pin. The last part that is left in the measuring unit is the voltage regulator part. Since we will give a variable input voltage we need a regulated +5V volt for the Arduino and the Op-amp to operate. This regulated voltage will be provided by the 7805 Voltage regulator. A capacitor is added at the output to filter the noise.

Computation and display unit

In the measuring unit we have designed the circuit to convert the Voltage and Current parameters into 0-5V which can be fed to the Arduino Analog pins. Now in this part of the circuit we will connect these voltage signals to Arduino and also interface a 16×2 alphanumeric display to the Arduino so that we can view the results. The circuit for the same is shown below As you can see the Voltage pin is connected to Analog pin A3 and the current pin is connected to Analog pin A4. The LCD is powered from the +5V from the 7805 and is connected to the digital pins of Arduino to work in 4-bit mode. We have also used a potentiometer (10k) connected to Con pin to vary the contrast of the LCD.

Programming the Arduino

Now that we have a good understanding of the hardware, let us open the Arduino and start programming. The purpose of the code is to read the analog voltage on pin A3 and A4 and calculate the Voltage, Current and Power value and finally display it on the LCD screen. The complete program to do the same is given at the end of the page which can be used as such for the hardware discussed above. Further the code is split into small snippets and explained. As all programs we begin with, defining the pins that we have used. In out project the A3 and A4 pin is used to measure voltage and current respectively and the digital pins 3,4,8,9,10 and 11 is used for interfacing the LCD with Arduino int Read_Voltage = A3; int Read_Current = A4; const int rs = 3, en = 4, d4 = 8, d5 = 9, d6 = 10, d7 = 11; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7); We also have included a header file called liquid crystal to interface the LCD with Arduino. Then inside the setup function we initialise the LCD display and display an intro text as “Arduino Wattmeterᾠand wait for two seconds before clearing it. The code for the same is shown below. void setup() { lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print(" Arduino Wattmeter"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print("-Circuitdigest"); //Intro Message line 2 delay(2000); lcd.clear(); } Inside the main loop function, we use the analog read function to read the voltage value from the pin A3 and A4. As we know the Arduino ADC output value from 0-1203 since it has a 10-bit ADC. This value has to be then converted to 0-5V which can be done by multiplying with (5/1023). Then again earlier in the hardware we have mapped the actual value of voltage from 0-24V to 0-5V and the actual value of current form 0-1A to 0-5V. So now we have to use a multiplier to revert these values back to actual value. This can be done by multiplying it with a multiplier value. The value of the multiplier can either be calculated theoretically using the formulae provided in hardware section or if you have a known set of voltage and current values you can calculate it practically. I have followed the latter option because it tends to be more accurate in real time. So here the value of multipliers is 6.46 and 0.239. Hence the code looks like below float Voltage_Value = analogRead(Read_Voltage); float Current_Value = analogRead(Read_Current); Voltage_Value = Voltage_Value * (5.0/1023.0) * 6.46; Current_Value = Current_Value * (5.0/1023.0) * 0.239;

How to measure with more accuracy?

The above way of calculating the value of Actual Voltage and current will work just fine. But suffers from one drawback, that is the relationship between the measured ADC voltage and actual voltage will not be linear hence a single multiplier will not give very accurate results, the same applied for current as well. in which I have used a similar method. Finally, once we have calculated the value of actual voltage and actual current through the load, we can calculate the Power using the formulae (P=V*I). Then we display all the three values on the LCD display using the code below. lcd.setCursor(0, 0); lcd.print("V="); lcd.print(Voltage_Value); lcd.print(" "); lcd.print("I=");lcd.print(Current_Value); float Power_Value = Voltage_Value * Current_Value; lcd.setCursor(0, 1); lcd.print("Power="); lcd.print(Power_Value);

Working and Testing

For the sake of tutorial I have used a perf board to solder all the components as shown in the circuit. I have used a Phoenix screw terminal to connect the load and normal DC barrel Jack to connect my power source. The Arduino Nano board and the LCD are mounted on a Female Bergstik so that they can be re-used if required later. After getting the hardware ready, upload the Arduino code to your Nano board. Adjust the trimmer pot to control the contrast level of the LCD until you see a clear intro text. To test the board connect the load to the screw terminal connector and the source to the Barrel jack. The source voltage should be more than 6V for this project to work, since the Arduino required +5V to operate. IF everything is working fine you should see the value of Voltage across the load and the current through it displayed in the first line of the LCD and the calculated power displayed on the second line of the LCD as shown below. The fun part of building something lies in testing it to check how far it will work properly. To do that I have used 12V automobile indicator bubs as load and the RPS as source. Since the RPS itself can measure and display the value of current and voltage it will be easy for us to cross check the accuracy and performance of our circuit. And yes, I also used my RPS to calibrate my multiplier value so that I get close to accurate value. The complete working can be found at the video given at the end of this page. Hope you understood the circuit and program and learnt something useful. If you have any problem in getting this to work post it on the comment section below or write on our forums for more technical help. has many more upgrades that can be added to increase the performance to auto data logging, plotting graph, notifying over voltage or over current situations etc. So stay curious and let me know what you would use this for. Code /* * Wattmeter for Solar PV using Arduino * Dated: 27-7-2018 * Website: www.circuitdigest.com * * Power LCD and circuitry from the +5V pin of Arduino whcih is powered via 7805 * LCD RS -> pin 2 * LCD EN -> pin 3 * LCD D4 -> pin 8 * LCD D5 -> pin 9 * LCD D6 -> pin 10 * LCD D7 -> pin 11 * Potetnital divider to measure voltage -> A3 * Op-Amp output to measure current -> A4 */ #include <LiquidCrystal.h> //Default Arduino LCD Librarey is included int Read_Voltage = A3; int Read_Current = A4; const int rs = 3, en = 4, d4 = 8, d5 = 9, d6 = 10, d7 = 11; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7); void setup() { lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print(" Arduino Wattmeter"); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print(" With Arduino "); //Intro Message line 2 delay(2000); lcd.clear(); } void loop() { float Voltage_Value = analogRead(Read_Voltage); float Current_Value = analogRead(Read_Current); Voltage_Value = Voltage_Value * (5.0/1023.0) * 6.46; Current_Value = Current_Value * (5.0/1023.0) * 0.239; lcd.setCursor(0, 0); lcd.print("V="); lcd.print(Voltage_Value); lcd.print(" "); lcd.print("I=");lcd.print(Current_Value); float Power_Value = Voltage_Value * Current_Value; lcd.setCursor(0, 1); lcd.print("Power="); lcd.print(Power_Value); delay(200); } Video microcontroller-projects/arduino-based-self-balancing-robot

DIY Self Balancing Robot using Arduino

works. Once I started building, I realized that this bot is a bit of a challenge to build. There are so many options to select from and hence the confusions start right form selecting the motors and remains till tuning PID values. And there are so many things to consider like type of battery, position of battery, wheel grip, type of motor driver, maintaining the CoG (Centre of gravity) and much more. But let me break it to you, once you build it you will agree that it’s not as hard as it sounds to be. So let’s face it, in this tutorial I will document my experience in building the self balancing robot. You might be an absolute beginner who is just getting started or might have landed up here after a long frustration of not getting your bot to work. This place aims to be your final destination. So let’s get started......

Selecting the Parts for Self Balancing Robot

Before I tell you all the options for building the bot let me list the items that I have used in this self balancing robot project Arduino UNO Geared DC motors (Yellow coloured) ᾠ2Nos L298N Motor Driver Module MPU6050 A pair of wheels 7.4V Li-ion Battery Connecting wires 3D Printed Body You can mix and choose for any of the above components based on the availability to make your own self balancing robot kit, just make sure that the components fits the following criteria. The controller that I have used here is Arduino UNO, why because it is simply easy to use. You can also use a Arduino Nano or Arduino mini but I would recommend you to stick with UNO since we can program it directly without any external hardware. The best choice of motor that you can use for a self balancing robot, without a doubt will be Stepper motor. But To keep things simple I have used a DC gear motor. Yes it is not mandatory to have a stepper; the bot works fine with these cheap commonly available yellow coloured DC gear motors as well. Do not under estimate these guys; I had a tough time figuring out that the problem was with my wheels. So make sure your wheels have good grip over the floor you are using. Watch closely, your grip should never allow your wheels to skit on the floor. We need a battery that is as light as possible and the operating voltage should be more than 5V so that we can power our Arduino directly without a boost module. So the ideal choice will be a 7.4V Li-polymer battery. Here, since I had a 7.4V Li-ion battery readily available I have used it. But remember a Li-po is advantageous than Li-ion. Another place where you should not compromise is with your bots chassis. You can use cardboard, wood, plastic anything that you are good with. But, just make sure the chassis is sturdy and should not wiggle when the bot is trying to balance. I have designed by own chassis on Solidworks inferring from the other bots and 3D printed it. If you have a printer then you can also print the design, the design files will be attached in the upcoming heading.

3D Printing and Assembling our Self BalancingRobot

I have also added the design files along with it so you can also modify it as per your personnel preferences. The parts have no overhanging structures so you can easily print them without any supports and an infill of 25% will work fine. The designs are pretty plain and any basic printer should be able to handle it with ease. I used the Cura software to slice the model and printed using my Tevo Tarantula, the setting are shown below. You would have to print the body part as well as four motor mounting parts. The assembling is pretty straight forward; use 3mm nuts and bolts to secure the motor and boards in place. After assembling it should look something like this shown in the picture below. in the bottom rack the Arduino and battery on top of it as shown above. If you are following the same order you can directly screw the board trough the holes provided and use a wire tag for the Li-po battery. This arrangement should also work, except for the super plain wheels which I had to change later. finally looks like this

Circuit Diagram

so we ave to interface the MPU6050 with Arduino and connect the motors though the Motor driver module. The whole set-up is powered by the 7.4V li-ion battery. The circuit diagram for the same is shown below. The Arduino and the L298N Motor driver module is directly powered through the Vin pin and the 12V terminal respectively. The on-board regulator on the Arduino board will convert the input 7.4V to 5V and the ATmega IC and MPU6050 will be powered by it. The DC motors can run from voltage 5V to 12V. But we will be connecting the 7.4V positive wire from battery to 12V input terminal of motor driver module. This will make the motors operate with 7.4V. The following table will list how the MPU6050 and L298N motor driver module is connected with Arduino.
Vcc+5V
GroundGnd
SCLA5
SDAA4
INTD2
IN1D6
IN2D9
IN3D10
IN4D11
and L298N Motor driver tutorial.

Self Balancing Robot Code

and then if it’s leaning towards the front we have to rotate the wheels in forward direction and if it is leaning towards the back we have to rotate the wheels in the reverse direction. , if the bot is slightly disoriented from centre position the wheels rotate slowly and the speed increase as it gets more away from the centre position. To achieve this logic we use the PID algorithm, which has the centre position as set-point and the level of disorientation as the output. combined. In order to get a reliable value of position from the sensor we need to use the value of both accelerometer and gyroscope, because the values from accelerometer has noise problems and the values from gyroscope tends to drift with time. So we have to combine both and get the value of yaw pitch and roll of our robot, of which we will use only the value of yaw. respectively. Before proceeding download their libraries form the following link and add them to your Arduino lib directory. we are just going to optimize the code for our purpose and add the PID and control technique for our self balancing robot. that are required for this program to work. They include the in-built I2C library, PID Library and MPU6050 Library that we just downloaded. #include "I2Cdev.h" #include <PID_v1.h> //From https://github.com/br3ttb/Arduino-PID-Library/blob/master/PID_v1.h #include "MPU6050_6Axis_MotionApps20.h" //https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050 will hold the final result. // MPU control/status vars bool dmpReady = false; // set true if DMP init was successful uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU uint8_t devStatus; // return status after each device operation (0 = success, !0 = error) uint16_t packetSize; // expected DMP packet size (default is 42 bytes) uint16_t fifoCount; // count of all bytes currently in FIFO uint8_t fifoBuffer[64]; // FIFO storage buffer // orientation/motion vars Quaternion q; // [w, x, y, z] quaternion container VectorFloat gravity; // [x, y, z] gravity vector float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector at the end of this page to get an idea of how to adjust these values. /*********Tune these 4 values for your BOT*********/ double setpoint= 176; //set the value when the bot is perpendicular to ground using serial monitor. //Read the project documentation on circuitdigest.com to learn how to set these values double Kp = 21; //Set this first double Kd = 0.8; //Set this secound double Ki = 140; //Finally set this /******End of values setting*********/ Out of these we have already set the values of set-point Kp,Ki and Kd in the above snippet of code. The value of input will be the current value of yaw that is read from the MPU6050 sensor and the value of output will be the value that is calculated by the PID algorithm. So basically the PID algorithm will give us an output value which should be used to correct the Input value to being it close to the set point. PID pid(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT); to calculate the offset value of you sensor and update the following lines accordingly in your program. // supply your own gyro offsets here, scaled for min sensitivity mpu.setXGyroOffset(220); mpu.setYGyroOffset(76); mpu.setZGyroOffset(-85); mpu.setZAccelOffset(1688); that we are using to connect our motors to. In our case it is D6, D9, D10 and D11. So we initialise these pins as output pins make them LOW by default. //Initialise the Motor outpu pins pinMode (6, OUTPUT); pinMode (9, OUTPUT); pinMode (10, OUTPUT); pinMode (11, OUTPUT); //By default turn off both the motors analogWrite(6,LOW); analogWrite(9,LOW); analogWrite(10,LOW); analogWrite(11,LOW); If yes then we use it to compute the PID value and then display the input and output value of PID on serial monitor just to check how the PID is responding. Then based on the value of output we decide if the bot has to move forward or backward or stand still. So we check for this condition and call the appropriate functions to move the bot forward or back ward. while (!mpuInterrupt && fifoCount < packetSize) { //no mpu data - performing PID calculations and output to motors pid.Compute(); //Print the value of Input and Output on serial monitor to check how it is working. Serial.print(input); Serial.print(" =>"); Serial.println(output); if (input>150 && input<200){//If the Bot is falling if (output>0) //Falling towards front Forward(); //Rotate the wheels forward else if (output<0) //Falling towards back Reverse(); //Rotate the wheels backward } else //If Bot not falling Stop(); //Hold the wheels still } If the bot is just about to fall then we make minor correction by rotating the wheel slowly. If these minor correction dint work and still if the bot is falling down we increase the speed of the motor. The value of how fast the wheels rotate will be decided by the PI algorithm. Note that for the Reverse function we have multiplied the value of output with -1 so that we can convert the negative value to positive. void Forward() //Code to rotate the wheel forward { analogWrite(6,output); analogWrite(9,0); analogWrite(10,output); analogWrite(11,0); Serial.print("F"); //Debugging information } void Reverse() //Code to rotate the wheel Backward { analogWrite(6,0); analogWrite(9,output*-1); analogWrite(10,0); analogWrite(11,output*-1); Serial.print("R"); } void Stop() //Code to stop both the wheels { analogWrite(6,0); analogWrite(9,0); analogWrite(10,0); analogWrite(11,0); Serial.print("S"); }

Working of Arduino Self Balancing Robot

Once you are ready with the hardware, you can upload the code to your Arduino board. Make sure the connections are proper since we are using a Li-ion battery extreme caution is needed. So double check for short circuits and ensure that the terminals won’t come into contact even if your bot experiences some small impacts. Power up your module and open your serial monitor, if your Arduino could communicate with MPU6050 successfully and if everything is working as expected you should see the following screen. The input value is the current value from the MPU6050 sensor. The alphabet “Fᾠrepresents that the bot is moving in forward and “Rᾠrepresents that the bot in reverse. and also shows how to correct your PID values. Code /*Arduino Self Balancing Robot * Code by: B.Aswinth Raj * Build on top of Lib: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050 * Website: circuitdigest.com */ #include "I2Cdev.h" #include <PID_v1.h> //From https://github.com/br3ttb/Arduino-PID-Library/blob/master/PID_v1.h #include "MPU6050_6Axis_MotionApps20.h" //https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050 MPU6050 mpu; // MPU control/status vars bool dmpReady = false; // set true if DMP init was successful uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU uint8_t devStatus; // return status after each device operation (0 = success, !0 = error) uint16_t packetSize; // expected DMP packet size (default is 42 bytes) uint16_t fifoCount; // count of all bytes currently in FIFO uint8_t fifoBuffer[64]; // FIFO storage buffer // orientation/motion vars Quaternion q; // [w, x, y, z] quaternion container VectorFloat gravity; // [x, y, z] gravity vector float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector /*********Tune these 4 values for your BOT*********/ double setpoint= 176; //set the value when the bot is perpendicular to ground using serial monitor. //Read the project documentation on circuitdigest.com to learn how to set these values double Kp = 21; //Set this first double Kd = 0.8; //Set this secound double Ki = 140; //Finally set this /******End of values setting*********/ double input, output; PID pid(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT); volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high void dmpDataReady() { mpuInterrupt = true; } void setup() { Serial.begin(115200); // initialize device Serial.println(F("Initializing I2C devices...")); mpu.initialize(); // verify connection Serial.println(F("Testing device connections...")); Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed")); // load and configure the DMP devStatus = mpu.dmpInitialize(); // supply your own gyro offsets here, scaled for min sensitivity mpu.setXGyroOffset(220); mpu.setYGyroOffset(76); mpu.setZGyroOffset(-85); mpu.setZAccelOffset(1688); // make sure it worked (returns 0 if so) if (devStatus == 0) { // turn on the DMP, now that it's ready Serial.println(F("Enabling DMP...")); mpu.setDMPEnabled(true); // enable Arduino interrupt detection Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)...")); attachInterrupt(0, dmpDataReady, RISING); mpuIntStatus = mpu.getIntStatus(); // set our DMP Ready flag so the main loop() function knows it's okay to use it Serial.println(F("DMP ready! Waiting for first interrupt...")); dmpReady = true; // get expected DMP packet size for later comparison packetSize = mpu.dmpGetFIFOPacketSize(); //setup PID pid.SetMode(AUTOMATIC); pid.SetSampleTime(10); pid.SetOutputLimits(-255, 255); } else { // ERROR! // 1 = initial memory load failed // 2 = DMP configuration updates failed // (if it's going to break, usually the code will be 1) Serial.print(F("DMP Initialization failed (code ")); Serial.print(devStatus); Serial.println(F(")")); } //Initialise the Motor outpu pins pinMode (6, OUTPUT); pinMode (9, OUTPUT); pinMode (10, OUTPUT); pinMode (11, OUTPUT); //By default turn off both the motors analogWrite(6,LOW); analogWrite(9,LOW); analogWrite(10,LOW); analogWrite(11,LOW); } void loop() { // if programming failed, don't try to do anything if (!dmpReady) return; // wait for MPU interrupt or extra packet(s) available while (!mpuInterrupt && fifoCount < packetSize) { //no mpu data - performing PID calculations and output to motors pid.Compute(); //Print the value of Input and Output on serial monitor to check how it is working. Serial.print(input); Serial.print(" =>"); Serial.println(output); if (input>150 && input<200){//If the Bot is falling if (output>0) //Falling towards front Forward(); //Rotate the wheels forward else if (output<0) //Falling towards back Reverse(); //Rotate the wheels backward } else //If Bot not falling Stop(); //Hold the wheels still } // reset interrupt flag and get INT_STATUS byte mpuInterrupt = false; mpuIntStatus = mpu.getIntStatus(); // get current FIFO count fifoCount = mpu.getFIFOCount(); // check for overflow (this should never happen unless our code is too inefficient) if ((mpuIntStatus & 0x10) || fifoCount == 1024) { // reset so we can continue cleanly mpu.resetFIFO(); Serial.println(F("FIFO overflow!")); // otherwise, check for DMP data ready interrupt (this should happen frequently) } else if (mpuIntStatus & 0x02) { // wait for correct available data length, should be a VERY short wait while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount(); // read a packet from FIFO mpu.getFIFOBytes(fifoBuffer, packetSize); // track FIFO count here in case there is > 1 packet available // (this lets us immediately read more without waiting for an interrupt) fifoCount -= packetSize; mpu.dmpGetQuaternion(&q, fifoBuffer); //get value for q mpu.dmpGetGravity(&gravity, &q); //get value for gravity mpu.dmpGetYawPitchRoll(ypr, &q, &gravity); //get value for ypr input = ypr[1] * 180/M_PI + 180; } } void Forward() //Code to rotate the wheel forward { analogWrite(6,output); analogWrite(9,0); analogWrite(10,output); analogWrite(11,0); Serial.print("F"); //Debugging information } void Reverse() //Code to rotate the wheel Backward { analogWrite(6,0); analogWrite(9,output*-1); analogWrite(10,0); analogWrite(11,output*-1); Serial.print("R"); } void Stop() //Code to stop both the wheels { analogWrite(6,0); analogWrite(9,0); analogWrite(10,0); analogWrite(11,0); Serial.print("S"); } Video microcontroller-projects/controlling-arduino-with-raspberry-pi-using-pyfirmata

Controlling Arduino with Raspberry Pi using pyFirmata

to give commands to Arduino using Raspberry Pi python script. PyFirmata is basically a prebuilt library package of python program which can be installed in Arduino to allow serial communication between a python script on any computer and an Arduino. This python package can give access to read and write any pin on the Arduino. So here we will run python program on Arduino using Raspberry pi.

Requirements

Raspberry Pi with Raspbian OS installed in it Arduino Uno or any other Arduino board Arduino USB cable LED

Installing PyFirmata in Arduino using Raspberry Pi

Follow these steps to install: Connect the Raspberry Pi to the internet. Open command terminal and type the following command and hit enter sudo apt-get -y install arduino python-serial mercurial Wait for few minutes, it will take time. This command will install the Arduino IDE in your Raspberry Pi. Now, we will install pyFirmata files using the given github: git clone https://github.com/tino/pyFirmata Then run the following command: cd pyFirmata sudo python setup.py install We have installed all the required files and setups. in terminal window. command to check whether Arduino is connected with your raspberry pi. In Arduino IDE, Go to tools and choose your board and Serial Port. and then click upload button. As shown below.

Code Explanation

by following the link. So let’s start writing the code import pyfirmata Define pin on the Arduino to connect the LED led_pin = 9 variable. board = pyfirmata.Arduino("/dev/ttyACM0") print "Code is runningᾼ/strong> function. while True: board.digital[led_pin].write(0) board.pass_time(1) board.digital[led_pin].write(1) board.pass_time(1) extension to the file name. to run the code on the Arduino board. Make sure your Arduino board is connected with your Raspberry Pi board using USB cable. on the Arduino board. is given at the end.

Fading LED on Arduino using pyFirmata

loops, one for increase brightness and other for decrease brightness. for more details. is given at the end. and try building them using Raspberry pi and python script. Code importpyfirmata led_pin = 9 board = pyfirmata.Arduino("/dev/ttyACM0") while True: board.digital[led_pin].write(0) board.pass_time(1) board.digital[led_pin].write(1) board.pass_time(1) import time import pyfirmata delay = 0.3 brightness = 0 board = pyfirmata.Arduino("/dev/ttyACM0") led = board.get_pin('d:9:p') while True: # increase for i in range(0, 10): brightness = brightness + 0.1 print "Setting brightness to %s" % brightness led.write(brightness) board.pass_time(delay) # decrease for i in range(0, 10): print "Setting brightness to %s" % brightness led.write(brightness) brightness = brightness - 0.1 board.pass_time(delay) Video microcontroller-projects/arduino-oscilloscope-code-circuit

Arduino Based Real-Time Oscilloscope

capable of performing the tasks for which some of the cheap oscilloscope are deployed like the display of waveforms and determination of voltage levels for signals.

How it works

There are two parts for this project; The Data Converter The Plotter which will be developed using python will convert the incoming stream of data to a waveform by plotting each data against time.

Required Components

The following components are required to build this project; ArduinoUno(Any of the other boards can be used) Breadboard 10k Resistor (1) LDR (1) Jumper wires Arduino IDE Python Python Libraries: Pyserial, Matplotlib, Drawnow

Schematics

, such that the generated waveform will describe the voltage level, based on the intensity of light around the LDR. Connect the components as shown in the schematics below; After connection, the setup should like the image below. With the connections all done, we can proceed to write the code.

ArduinoOsclloscopeCode

, we will be writing an Arduino sketch that takes in the data from the ADC and converts it to voltage levels which are sent to the plotter.

Python (Plotter) Script

Since the python code is more complex, we will start with it. provides a means for us to update the plot in real time. Pip can be installed via command line on a windows or linux machine. PIP is packaged with python3 so I will advise you install python3 and check the box about adding python to path. If you are having issues with installing pip, check out this the official python website for tips. , we can now install the other libraries we need. Open the command prompt for windows users, terminal for linux users and enter the following; pip install pyserial using; pip install matplotlib is sometimes installed alongside matplotlib but just to be sure, run; pip install drawnow With the installation complete, we are now ready to write the python script. We start by importing all the libraries needed for the code; import time import matplotlib.pyplot as plt from drawnow import * import pyserial will be used to count. Data at location 0 will be deleted after every 50 data counts. This is done to keep the data being displayed on the oscilloscope. val = [ ] cnt = 0 through which the Arduino will communicate with our python script. Ensure the com port specified below is the same com port through which your Arduino board communicates with the IDE. The 115200 baud rate used above was used to ensure high speed communication with the Arduino. To prevent errors, the Arduino serial port must also be enabled to communicate with this baud rate. port = serial.Serial('COM4', 115200, timeout=0.5) interactive using; plt.ion() We also set the title, label each axis and add a legend to make it easy to identify the plot. #create the figure function def makeFig(): plt.ylim(-1023,1023) plt.title('Osciloscope') plt.grid(True) plt.ylabel('ADC outputs') plt.plot(val, 'ro-', label='Channel 0') plt.legend(loc='lower right') to indicate its readiness to read data. When the Arduino receives the handshake data, it replies with data from the ADC. Without this handshake, we will not be able to plot the data in real time. while (True): port.write(b's') #handshake with Arduino if (port.inWaiting()):# if the arduino replies value = port.readline()# read the reply print(value)#print so we can monitor it number = int(value) #convert received data to integer print('Channel 0: {0}'.format(number)) # Sleep for half a second. time.sleep(0.01) val.append(int(number)) drawnow(makeFig)#update plot to reflect new data input plt.pause(.000001) cnt = cnt+1 if(cnt>50): val.pop(0)#keep the plot fresh by deleting the data at position 0 is given at the end of this article shown below.

Arduino code

The second code is the Arduino sketch to obtain the data representing the signal from the ADC, then wait to receive the handshake signal from the plotter software. As soon as it receives the handshake signal, it sends the acquired data to the plotter software via UART. to which the signal will be applied. int sensorpin = A0; Next, we initialize and start serial communication with a baud rate of 115200 void setup() { // initialize serial communication at 115200 bits per second to match that of the python script: Serial.begin(115200); } function which handles the reading of the data, and sends the data over serial to the plotter. void loop() { // read the input on analog pin 0: float sensorValue = analogRead(sensorpin); byte data = Serial.read(); if (data == 's') { Serial.println(sensorValue); delay(10); // delay in between reads for stability } } is given below as well as at the end of this article shown below. int sensorpin = A0; void setup() { // initialize serial communication at 115200 bits per second to match that of the python script: Serial.begin(115200); } void loop() { // read the input on analog pin 0:######################################################## float sensorValue = analogRead(sensorpin); byte data = Serial.read(); if (data == 's') { Serial.println(sensorValue); delay(10); // delay in between reads for stability } }

Arduino Oscilloscope in Action

Upload the code to the Arduino setup and run the python script. You should see the data start streaming in via the python command line and the plot varying with the light intensity as shown in the image below. Code import time import matplotlib.pyplot as plt from drawnow import * import serial val = [ ] cnt = 0 #create the serial port object port = serial.Serial('COM4', 115200, timeout=0.5) plt.ion() #create the figure function def makeFig(): plt.ylim(-1023,1023) plt.title('Osciloscope') plt.grid(True) plt.ylabel('data') plt.plot(val, 'ro-', label='Channel 0') plt.legend(loc='lower right') while (True): port.write(b's') #handshake with Arduino if (port.inWaiting()):# if the arduino replies value = port.readline()# read the reply print(value)#print so we can monitor it number = int(value) #convert received data to integer print('Channel 0: {0}'.format(number)) # Sleep for half a second. time.sleep(0.01) val.append(int(number)) drawnow(makeFig)#update plot to reflect new data input plt.pause(.000001) cnt = cnt+1 if(cnt>50): val.pop(0)#keep the plot fresh by deleting the data at position 0 int sensorpin = A0; void setup() { // initialize serial communication at 115200 bits per second to match that of the python script: Serial.begin(115200); } void loop() { // read the input on analog pin 0:######################################################## float sensorValue = analogRead(sensorpin); byte data = Serial.read(); if (data == 's') { Serial.println(sensorValue); delay(10); // delay in between reads for stability } } microcontroller-projects/arduino-automatic-water-dispenser

Automatic Water Dispenser using Arduino

About 71% of earth is covered with water, but sadly only 2.5% of it is drinking water. With rise in population, pollution and climate change, it is expected that by as soon as 2025 we will experience perennial water shortages. At one hand there are already minor disputes among nations and states for sharing river water on the other hand we as humans waste a lot of drinking water due to our negligence. that can automatically give you water when a glass is placed near it. Sounds cool right! So let’s build one...

Materials Required

Solenoid Valve Arduino Uno (any version) HCSR04 ᾠUltrasonic Sensor IRF540 MOSFET 1k and 10k Resistor Breadboard Connecting Wires

Working Concept

Circuit Diagram

is shown below to turn it on and off. It has the 3 pins Gate, Source and Drain from pin 1 respectively. As shown in the circuit diagram the positive terminal of the solenoid is powered with the Vin pin of the Arduino. Because we will use a 12V adapter to power the Arduino and thus the Vin pin will output 12V which can be used to control the Solenoid. The negative terminal of the solenoid is connected to the ground through the MOSFET’s Source and Drain pins. So the solenoid will be powered only if the MOSFET is turned on. The gate pin of the MOSFET is used to turn it on or off. It will remain off if the gate pin is grounded and will turn on if a gate voltage is applied. To keep the MOSFET turned off when no voltage is applied to gate pin, the gate pin is pulled to ground though a 10k resistor. The Arduino pin 12 is used to turn on or off the MOSFET, so the D12 pin is connected to the gate pin through a 1K resistor. This 1K resistor is used for current limiting purpose. pin is connected to the pin 8 and pin 9 respectively. We can then program the Arduino to use the Ultrasonic sensor to measure the distance and turn on the MOSFET when an object is detect. The whole circuit is simple and hence can be easily build on top of a breadboard. Mine looked something like this below after making the connections.

Programming the Arduino Board

to do the same is given at the end of this page. Just below I have explained the program by breaking it into small meaningful snippets. digital pin respectively. Then the MOSFET pin is connected to pin 12 and the onboard LED by default is connected to pin 13. We define the same using the following lines #define trigger 9 #define echo 8 #define LED 13 #define MOSFET 12 function of Arduino to specify the same as shown below pinMode(trigger,OUTPUT); pinMode(echo,INPUT); pinMode(LED,OUTPUT); pinMode(MOSFET,OUTPUT); , read though the link. The program to calculate the distance is give below digitalWrite(trigger,LOW); delayMicroseconds(2); digitalWrite(trigger,HIGH); delayMicroseconds(10); digitalWrite(trigger,LOW); delayMicroseconds(2); time=pulseIn(echo,HIGH); distance=time*340/20000; statement we make the MOSFET and LED to go low. The program to do the same is shown below. if(distance<10) { digitalWrite(LED,HIGH);digitalWrite(MOSFET,HIGH); } else { digitalWrite(LED,LOW);digitalWrite(MOSFET,LOW); }

Working of Automatic Water Dispenser

Make the connections as shown in the circuit and upload the below given program into your Arduino board. Make some simple arrangement to connect the solenoid valve to the water inlet and power up the circuit using the 12V adapter to the DC jack of Arduino board. Make sure the on board LED is turned off, this ensures that the Solenoid is also off. The set-up that I have made to demonstrate the project is shown below As you can see I have placed the Ultrasonic sensor directly below the solenoid valve such that when the glass/tumbler is placed below the solenoid it gets directly opposite to the ultrasonic sensor. This object will be sensed by the ultrasonic sensor and the MOSFET along with the LED will turn ON thus making the solenoid to open and the water flows down. below. If you have any doubt in getting this to work, post it in the comment section or use the forum for technical help. Code #define trigger 9 #define echo 8 #define LED 13 #define MOSFET 12 float time=0,distance=0; void setup() { Serial.begin(9600); pinMode(trigger,OUTPUT); pinMode(echo,INPUT); pinMode(LED,OUTPUT); pinMode(MOSFET,OUTPUT); delay(2000); } void loop() { measure_distance(); if(distance<10) { digitalWrite(LED,HIGH);digitalWrite(MOSFET,HIGH); } else { digitalWrite(LED,LOW);digitalWrite(MOSFET,LOW); } delay(500); } void measure_distance() { digitalWrite(trigger,LOW); delayMicroseconds(2); digitalWrite(trigger,HIGH); delayMicroseconds(10); digitalWrite(trigger,LOW); delayMicroseconds(2); time=pulseIn(echo,HIGH); distance=time*340/20000; } Video microcontroller-projects/record-and-play-3d-printed-robotic-arm-using-arduino

Record and Play 3D Printed Robotic Arm using Arduino

that could help me with my daily works just like Dum-E and Dum-U that Tony stark uses in his lab. These two bots can be seen helping him while building the Iron man suits or filming his work using a video camera. Actually Dum-E has also saved his life once....... and this is where I would like to stop it because this is no fan Page. Apart from the fictional world there are many cool real world Robotic Arms made by Fanuc, Kuka, Denso, ABB, Yaskawa etc. These robotic arms are used in Production line of automobiles, mining plants, Chemical industries and many other places. feature so that we can record a motion and ask the Robotic Arm to repeat it as many times as we require it. Sounds cool right!!! So lets start building....

Material Required

Arduino Nano 5 MG-995 Servo Motor 5-Potentiometer Perf Board Servo horns Nuts and Screws

3D Printing and Assembling the Robotic Arm

will work perfectly with our MG995 Servo Motors and would exactly suit our purpose. itself and hence I am not going to cover it. One small tip is that you would have to sand/file the edges of the parts for the motors to fit in. All the motors will fit in vey snug with a little bit of mechanical force. Have patience and use a file to create room for the motors if they seem a bit tight. You would need like 20 numbers of 3mm bolts to assemble the Robotic ARM. As soon as mounting a motor make sure it can rotate and reach the desired places before screwing it permanently. After assembling, you can proceed with extending the wires of the top three servo motors. I have used the male to female wires to extend them and bring it to circuit board. Make sure you harness the wires properly so that they do not come into your way while the Arm is working. Once assembled my robotic Arm Looked something like this in the picture below.

Circuit Diagram

pins and 5 Potentiometers to the Arduino Analog pins to control the Servo Motor. The circuit diagram for the same is given below. which can be sourced by the on-board voltage regulator of the Arduino Board. These 5 potentiometers are connected to the 5 Analog pins A0 to A4 of the Arduino board. The Servo motors are controlled by PWM signals so we have to connect them to the PWM pins of Arduino. On Arduino Nano the pins D3,D5,D6,D9 and D11 only supports PWM, so we use the first 5 pins for our servo motors. I have used a perf board to solder the connections and my board looked something like this below when completed. I have also added a barrel jack to power the device through battery if required. However it is completely optional. article before you proceed with the project.

Programming Arduino for Robotic Arm

to do the same can be found at the bottom of this page, you can use the program as it is. But further below I have explained the program with small snippets for you to understand. which as the name states will save all the recorded movements of the Robotic ARM. #include <Servo.h> //Servo header file //Declare object for 5 Servo Motors Servo Servo_0; Servo Servo_1; Servo Servo_2; Servo Servo_3; Servo Gripper; //Global Variable Declaration int S0_pos, S1_pos, S2_pos, S3_pos, G_pos; int P_S0_pos, P_S1_pos, P_S2_pos, P_S3_pos, P_G_pos; int C_S0_pos, C_S1_pos, C_S2_pos, C_S3_pos, C_G_pos; int POT_0,POT_1,POT_2,POT_3,POT_4; int saved_data[700]; //Array for saving recorded data int array_index=0; char incoming = 0; int action_pos; int action_servo; function. Since the setup function runs during the start-up we can use it to set our Robotic arm in a start position. So I have hardcoded the position value for all five motors. These hardcoded values can be changed according to your preference later. At the end of setup function we print a serial line asking the user to press R or P to do the corresponding action void setup() { Serial.begin(9600); //Serial Monitor for Debugging //Decalre the pins to which the Servo Motors are connected to Servo_0.attach(3); Servo_1.attach(5); Servo_2.attach(6); Servo_3.attach(9); Gripper.attach(10); //Write the servo motors to intial position Servo_0.write(70); Servo_1.write(100); Servo_2.write(110); Servo_3.write(10); Gripper.write(10); Serial.println("Press 'R' to Record and 'P' to play"); //Instrust the user } and maps it to the Servo position values. As we know the Arduino has a 8-bit ADC which gives us an output from 0-1023 but the servo motors position values ranges from only 0-180. Also since these servo motors are not very precise it is not safe to drive them to the extreme 0 end or 180 end so we set 10-170 as our limits. We use the map function to convert 0-1023 to 10-170 for all the five motor as shown below. void Read_POT() //Function to read the Analog value form POT and map it to Servo value { POT_0 = analogRead(A0); POT_1 = analogRead(A1); POT_2 = analogRead(A2); POT_3 = analogRead(A3); POT_4 = analogRead(A4); //Read the Analog values form all five POT S0_pos = map(POT_0,0,1024,10,170); //Map it for 1st Servo (Base motor) S1_pos = map(POT_1,0,1024,10,170); //Map it for 2nd Servo (Hip motor) S2_pos = map(POT_2,0,1024,10,170); //Map it for 3rd Servo (Shoulder motor) S3_pos = map(POT_3,0,1024,10,170); //Map it for 4th Servo (Neck motor) G_pos = map(POT_4,0,1024,10,170); //Map it for 5th Servo (Gripper motor) }

Recording Mode Code

function. is not left constant and sometime jitters up/down randomly. function. Read_POT(); //Read the POT values for 1st time //Save it in a varibale to compare it later P_S0_pos = S0_pos; P_S1_pos = S1_pos; P_S2_pos = S2_pos; P_S3_pos = S3_pos; P_G_pos = G_pos; Read_POT(); //Read the POT value for 2nd time Also after controlling we have to save the motor number and motor position in the array. We could have used two different array one for motor number and the other for its position, but to save memory and complexity I have combined both of them by adding a differentiator value to the pos value before saving it in the array. if (P_S0_pos == S0_pos) //If 1st and 2nd value are same { Servo_0.write(S0_pos); //Control the servo if (C_S0_pos != S0_pos) //If the POT has been turned { saved_data[array_index] = S0_pos + 0; //Save the new position to the array. Zero is added for zeroth motor (for understading purpose) array_index++; //Increase the array index } C_S0_pos = S0_pos; //Saved the previous value to check if the POT has been turned } The differentiator value for Sero_0 is 0 and for Servo_1 is 1000 similarly for Servo_3 it is 3000 and for Gripper it is 4000. The lines of code in which the differentiator is added to the value of position and saved to the array is shown below. saved_data[array_index] = S0_pos + 0; //Save the new position to the array. Zero is added for zeroth motor (for understading purpose) saved_data[array_index] = S1_pos + 1000; //1000 is added for 1st servo motor as differentiater saved_data[array_index] = S2_pos + 2000; //2000 is added for 2nd servo motor as differentiater saved_data[array_index] = S3_pos + 3000; //3000 is added for 3rd servo motor as differentiater saved_data[array_index] = G_pos + 4000; //4000 is added for 4th servo motor as differentiater

Playing mode Code

Inside the play mode we have access each element saved in the array and split the value to get the motor number and motor position and control their position accordingly. to get the number of servo motor to be controlled and its position respectively. To get the number of servo motor we have to divide it by 1000 and to get the position we need the last three digits which can be obtained by taking a modulus. motor has to be moved to the position of 125. for (int Play_action=0; Play_action<array_index; Play_action++) //Navigate through every saved element in the array { action_servo = saved_data[Play_action] / 1000; //The fist charector of the array element is split for knowing the servo number action_pos = saved_data[Play_action] % 1000; //The last three charectors of the array element is split to know the servo postion case to get into the corresponding servo motor number and the write function to move the servo motor to that position. The switch case is shown below switch(action_servo){ //Check which servo motor should be controlled case 0: //If zeroth motor Servo_0.write(action_pos); break; case 1://If 1st motor Servo_1.write(action_pos); break; case 2://If 2nd motor Servo_2.write(action_pos); break; case 3://If 3rd motor Servo_3.write(action_pos); break; case 4://If 4th motor Gripper.write(action_pos); break; Inside the main loop function, we only have to check what the user has entered through the serial monitor and execute the record mode of the play mode accordingly. The variable incoming is used to hold the value of the user. If ‘Rᾠis entered Record mode will be activated and if ‘Pᾠif pressed Play mode will be executed by if conditional statements as shown below. void loop() { if (Serial.available() > 1) //If something is recevied from serial monitor { incoming = Serial.read(); if (incoming == 'R') Serial.println("Robotic Arm Recording Started......"); if (incoming == 'P') Serial.println("Playing Recorded sequence"); } if (incoming == 'R') //If user has selected Record mode Record(); if (incoming == 'P') //If user has selected Play Mode Play(); }

Working of Record and Play Robotic ARM

Make the connection as shown in the circuit diagram and upload the code that is given below. Power your Arduino Nano though the USB port of your computer and open the serial monitor you will be welcomed with this intro message. Now enter R in the serial monitor and press enter. Note that at the bottom of the serial monitor Newline should be selected. Once entered the bot will get into Recording mode and you will the following screen. and press enter and we will be taken to the Play mode and the serial monitor will display the following. linked in the bottom of the page. using Raspberry Pi and Open CV and check what it can do. What are your ideas? Leave them in the comment section and I will be happy to hear from you. Code /* Robotic ARM with Record and Play option using Arduino Code by: B. Aswinth Raj Website: www.circuitdigest.com Dated: 05-08-2018 */ #include <Servo.h> //Servo header file //Declare object for 5 Servo Motors Servo Servo_0; Servo Servo_1; Servo Servo_2; Servo Servo_3; Servo Gripper; //Global Variable Declaration int S0_pos, S1_pos, S2_pos, S3_pos, G_pos; int P_S0_pos, P_S1_pos, P_S2_pos, P_S3_pos, P_G_pos; int C_S0_pos, C_S1_pos, C_S2_pos, C_S3_pos, C_G_pos; int POT_0,POT_1,POT_2,POT_3,POT_4; int saved_data[700]; //Array for saving recorded data int array_index=0; char incoming = 0; int action_pos; int action_servo; void setup() { Serial.begin(9600); //Serial Monitor for Debugging //Declare the pins to which the Servo Motors are connected to Servo_0.attach(3); Servo_1.attach(5); Servo_2.attach(6); Servo_3.attach(9); Gripper.attach(10); //Write the servo motors to initial position Servo_0.write(70); Servo_1.write(100); Servo_2.write(110); Servo_3.write(10); Gripper.write(10); Serial.println("Press 'R' to Record and 'P' to play"); //Instruct the user } void Read_POT() //Function to read the Analog value form POT and map it to Servo value { POT_0 = analogRead(A0); POT_1 = analogRead(A1); POT_2 = analogRead(A2); POT_3 = analogRead(A3); POT_4 = analogRead(A4); //Read the Analog values form all five POT S0_pos = map(POT_0,0,1024,10,170); //Map it for 1st Servo (Base motor) S1_pos = map(POT_1,0,1024,10,170); //Map it for 2nd Servo (Hip motor) S2_pos = map(POT_2,0,1024,10,170); //Map it for 3rd Servo (Shoulder motor) S3_pos = map(POT_3,0,1024,10,170); //Map it for 4th Servo (Neck motor) G_pos = map(POT_4,0,1024,10,170); //Map it for 5th Servo (Gripper motor) } void Record() //Function to Record the movements of the Robotic Arm { Read_POT(); //Read the POT values for 1st time //Save it in a variable to compare it later P_S0_pos = S0_pos; P_S1_pos = S1_pos; P_S2_pos = S2_pos; P_S3_pos = S3_pos; P_G_pos = G_pos; Read_POT(); //Read the POT value for 2nd time if (P_S0_pos == S0_pos) //If 1st and 2nd value are same { Servo_0.write(S0_pos); //Control the servo if (C_S0_pos != S0_pos) //If the POT has been turned { saved_data[array_index] = S0_pos + 0; //Save the new position to the array. Zero is added for zeroth motor (for understading purpose) array_index++; //Increase the array index } C_S0_pos = S0_pos; //Saved the previous value to check if the POT has been turned } //Similarly repeat for all 5 servo Motors if (P_S1_pos == S1_pos) { Servo_1.write(S1_pos); if (C_S1_pos != S1_pos) { saved_data[array_index] = S1_pos + 1000; //1000 is added for 1st servo motor as differentiator array_index++; } C_S1_pos = S1_pos; } if (P_S2_pos == S2_pos) { Servo_2.write(S2_pos); if (C_S2_pos != S2_pos) { saved_data[array_index] = S2_pos + 2000; //2000 is added for 2nd servo motor as differentiator array_index++; } C_S2_pos = S2_pos; } if (P_S3_pos == S3_pos) { Servo_3.write(S3_pos); if (C_S3_pos != S3_pos) { saved_data[array_index] = S3_pos + 3000; //3000 is added for 3rd servo motor as differentiater array_index++; } C_S3_pos = S3_pos; } if (P_G_pos == G_pos) { Gripper.write(G_pos); if (C_G_pos != G_pos) { saved_data[array_index] = G_pos + 4000; //4000 is added for 4th servo motor as differentiator array_index++; } C_G_pos = G_pos; } //Print the value for debugging Serial.print(S0_pos); Serial.print(" "); Serial.print(S1_pos); Serial.print(" "); Serial.print(S2_pos); Serial.print(" "); Serial.print(S3_pos); Serial.print(" "); Serial.println(G_pos); Serial.print ("Index = "); Serial.println (array_index); delay(100); } void Play() //Functon to play the recorded movements on the Robotic ARM { for (int Play_action=0; Play_action<array_index; Play_action++) //Navigate through every saved element in the array { action_servo = saved_data[Play_action] / 1000; //The fist character of the array element is split for knowing the servo number action_pos = saved_data[Play_action] % 1000; //The last three characters of the array element is split to know the servo postion switch(action_servo){ //Check which servo motor should be controlled case 0: //If zeroth motor Servo_0.write(action_pos); break; case 1://If 1st motor Servo_1.write(action_pos); break; case 2://If 2nd motor Servo_2.write(action_pos); break; case 3://If 3rd motor Servo_3.write(action_pos); break; case 4://If 4th motor Gripper.write(action_pos); break; } delay(50); } } void loop() { if (Serial.available() > 1) //If something is received from serial monitor { incoming = Serial.read(); if (incoming == 'R') Serial.println("Robotic Arm Recording Started......"); if (incoming == 'P') Serial.println("Playing Recorded sequence"); } if (incoming == 'R') //If user has selected Record mode Record(); if (incoming == 'P') //If user has selected Play Mode Play(); } Video microcontroller-projects/arduino-labview-interfacing-tutorial

Interfacing LabVIEW With Arduino

Requirements

To interface LabVIEW with Arduino, you require the following software’s and hardware’s, LabVIEW (software) NI VISA (software) VI packet manager (software) Arduino IDE (software) LINX, (this will be available inside VI package manager, open VI package manager and search for it, double click on it. You will reach to an installation window. Click install button visible to you in that window.) LabVIEW Interface for Arduino, this will be available inside VI package manager, open VI package manager and search for it, double click on it. You will reach to an installation window. Click install button visible to you in that window, as shown below

Why we interface Arduino with LabVIEW?

language. Arduino programme is made up of lines of codes but when we interface LabVIEW with Arduino, lines of codes are reduced into a pictorial program, which is easy to understand and execution time is reduced into half.

LED Blink with Arduino & LabVIEW

Launch the LabVIEW. To launch LabVIEW refer previous article. Now start graphical coding. In Block diagram window, right click select Makerhub >> LINX >> Open, drag & drop the Open box. Then create a control by right clicking the first wire tip and selecting Create >> Control. Thus created a Serial port. In Block diagram window, right click and select Makerhub >> LINX >> Close. Drag & drop Close. In Block diagram window, right click and select Makerhub >> LINX >> Digital >>Write. Drag & drop Write. Then create a controls on second and third tip of wires by right clicking each individually and selecting Create >> Control. Thus created a D0 channel and Output Value. In Block diagram window, right click and select Structures >> While loop. Drag the While loop across the Digital write. Then create a Shift register by right clicking on the While loop. In Block diagram window, right click and select Makerhub >> LINX >> Utilities >> Loop rate. Drag & drop it inside the While loop. In Block diagram window, right click select Boolean >> or. Drag & drop or inside the While loop. In Block diagram window, right click and select Timing >> Wait(ms). Drag & drop Wait(ms) into the While loop and create a constant for it by right clicking on the wire tip which is left most to the Wait(ms) and select Create >> Constant. In Front panel window, right click and select Boolean >> Stop button. Now stop button appears in the Block diagram window. Drag & drop it inside the While loop. Now by connecting all these created blocks using wiring connections, you can build the Graphical LED blink program to interface with your Arduino hardware.

Connect the LabVIEW code with Arduino

After building the graphical code, select Tools >> Makerhub >> LINX >> LINX Firmware wizard. Now LINX Firmware wizard window open’s, in that select Device Family as Arduino; Device type as Arduino Uno ; Firmware Upload Method as Serial/USB. Then click Next. Then connect the Arduino board to your PC using Arduino USB cable. Now in Next window select the Arduino port by clicking to the drop down list. Select COM4. Then click Next twice. Then click Finish button. Now you have setup the serial port and interfaced Arduino board with LabVIEW.

Run the Program

Now select the Continuously Run Icon, then in the front panel window select the port and enter the digital pin. Then by switching the Output Value (which acts as an On & Off switch), you can see the in-built LED of the Arduino board blinking till the Output Value is turned Off . below. Video microcontroller-projects/arduino-motor-driver-shield-pcb

DIY Arduino Motor Driver Shield

for driving motors and an 8-bit shift register for controlling them.

Components Required

Motor Driver IC L293D -2 74HC595 Shift Resistor -1 104 capacitors-5 3 Pin Terminal Block -5 Push button -1 SMD LED -1 1k ᾠresistor -1 PCB (ordered from JLCPCB) -1 Resistor network 10k -1 Burg sticks male Arduino Uno Power supply

Arduino Motor Driver Shield Circuit

, land robbers, maze followers and many more projects. This board can be controlled by using Arduino like Arduino UNO, Arduino Mega and similar boards. It has screw terminal for conncecting motors wires. L293D motor driver is signaled by using a shift register 74HC595 and the shift register is signaled by using the Arduino. It has jumper pins to select either12v Power to Motors or 5v power to motors. Here ST, DS, OE, SH, and MR is used for driving S hift Register M1PWM, M2PWM, M3PWM, and M4PWM are used for controlling DC motor speed. If DC motor speed controlling is not necessary make these pins HIGH. SERVO1 and SERVO2 for Servo Motors. With this shield, making motor based projects are super easy with Arduino. You just have to fix the shield over Arduino and control motors using this shield. You can use the given code (in the end) or use your own code for controlling the motors according to your application. You can also learninterfacingof all these motors and shift register withArduinoin our previous articles without using the Motor Driver shield: Interfacing Stepper Motor withArduinoUNO Controlling Multiple Servo Motor withArduino DC Motor Control usingArduino How to Use Shift Register74HC595withArduinoUno

Circuit and PCB Design using EasyEDA

where they have a large stock of electronic components and users can order the required components along with the PCB boards. While designing your circuits and PCBs with EasyEDA, you can make your circuit and PCB designs public so that other users can copy or edit them and can take benefit from your work, we have made the Circuit and PCB layout public for thisproject,available at the below link: button in EasyEDA:

Calculating and Ordering Samples online

page. and click onQuote NoworBuy Now button, then you can select the number of PCBs you want to order, how manycopper layers you need, the PCB thickness, copper weight, and even the PCB color, like the snapshot shown below: Afteryou have selected all of theoptions, click “Save to Cartᾠand then you will be taken to the page where you can upload your Gerber File which we have downloaded fromEasyEDA. Upload your Gerber file and click “Save to Cartᾮ Andfinallyclick on Checkout Securely to complete your order, then you will get your PCBs a few days later. They are fabricating the PCB atverylow rate which is $2. Theirbuild time is also verylesswhichis 48 hours with DHL delivery of 3-5 days,basicallyyou will get your PCBs within a week of ordering. with date and time. You check it by going on Account page and click on "Production Progress" link under the PCB like, shown in below image. After few days of orderingPCB’sI got thePCB samples in nice packagingas shown in below pictures. After getting these pieces I have mounted all the required components over the PCB connected it with Arduino for demonstration. So our Arduino Motor Driver Shield is ready, and you can directly use it with Arduino to control many motors at a time. Code #include <Servo.h> Servo myservo; #define MR 2 #define M2PWM 3 #define SH 4 #define M4PWM 5 #define M3PWM 6 #define OE 7 #define DS 8 #define SERVO1 9 #define SERVO2 10 #define M1PWM 11 #define ST 12 #define M1 0 #define M2 2 #define M3 4 #define M4 6 #define STOP 0 #define CW 1 #define CCW 2 char pAction=0x00; void setup() { Serial.begin(9600); pinMode(MR, OUTPUT); pinMode(M2PWM, OUTPUT); pinMode(SH, OUTPUT); pinMode(M4PWM, OUTPUT); pinMode(M3PWM, OUTPUT); pinMode(OE, OUTPUT); pinMode(DS, OUTPUT); pinMode(M1PWM, OUTPUT); pinMode(ST, OUTPUT); digitalWrite(M1PWM, HIGH); digitalWrite(M2PWM, HIGH); digitalWrite(M3PWM, HIGH); digitalWrite(M4PWM, HIGH); digitalWrite(MR, HIGH); digitalWrite(OE, LOW); myservo.attach(SERVO1); myservo.write(0); } void loop() { DriveMotor(M1,CW); DriveMotor(M2,CCW); DriveMotor(M2,CW); DriveMotor(M3,CW); DriveMotor(M4,CW); myservo.write(0); delay(5000); DriveMotor(M1,STOP); DriveMotor(M2,STOP); DriveMotor(M3,STOP); DriveMotor(M4,STOP); delay(1000); DriveMotor(M1,CCW); DriveMotor(M2,CCW); DriveMotor(M3,CCW); DriveMotor(M4,CCW); myservo.write(90); delay(5000); DriveMotor(M1,STOP); DriveMotor(M2,STOP); DriveMotor(M3,STOP); DriveMotor(M4,STOP); delay(1000); DriveMotor(M1,CW); DriveMotor(M2,CCW); DriveMotor(M3,CW); DriveMotor(M4,CCW); myservo.write(180); delay(5000); DriveMotor(M1,STOP); DriveMotor(M2,STOP); DriveMotor(M3,STOP); DriveMotor(M4,STOP); delay(1000); DriveMotor(M1,CCW); DriveMotor(M2,CW); DriveMotor(M3,CCW); DriveMotor(M4,CW); myservo.write(90); delay(5000); DriveMotor(M1,STOP); DriveMotor(M2,STOP); DriveMotor(M3,STOP); DriveMotor(M4,STOP); delay(1000); DriveMotor(M1,STOP); DriveMotor(M2,CW); DriveMotor(M3,CCW); DriveMotor(M4,CW); myservo.write(0); delay(5000); DriveMotor(M1,STOP); DriveMotor(M2,STOP); DriveMotor(M3,STOP); DriveMotor(M4,STOP); delay(1000); DriveMotor(M1,STOP); DriveMotor(M2,STOP); DriveMotor(M3,CW); DriveMotor(M4,CCW); myservo.write(90); delay(5000); DriveMotor(M1,STOP); DriveMotor(M2,STOP); DriveMotor(M3,STOP); DriveMotor(M4,STOP); delay(1000); DriveMotor(M1,STOP); DriveMotor(M2,STOP); DriveMotor(M3,STOP); DriveMotor(M4,CCW); myservo.write(180); delay(5000); DriveMotor(M1,STOP); DriveMotor(M2,STOP); DriveMotor(M3,STOP); DriveMotor(M4,STOP); myservo.write(90); delay(5000); } int Action=0; void DriveMotor(int Motor, int Dir) { // Serial.print("Motor :"); // Serial.println(Motor, HEX); // Serial.print("Action:"); // Serial.println(Action,HEX); if(Dir == CW) { Action|=(1<<Motor); Action&=~(1<<Motor+1); } else if(Dir == CCW) { Action&=~(1<<Motor); Action|=(1<<Motor+1); } else { Action&=~(1<<Motor); Action&=~(1<<Motor+1); } Serial.print("Action:"); Serial.println(Action, HEX); // delay(2000); for (int i = 0; i < 8; i++) { if ((Action << i) & 0x80) digitalWrite(DS, HIGH); else digitalWrite(DS, LOW); digitalWrite(SH, HIGH); delay(1); digitalWrite(SH, LOW); } digitalWrite(ST, HIGH); delay(1); digitalWrite(ST, LOW); pAction=Action; } Video microcontroller-projects/arduino-flame-sensor-interfacing

Interfacing Flame Sensor with Arduino to Build a Fire Alarm System

, these sensors have an IR photodiode which is sensitive to IR light. Now, in the event of a fire, the fire will not only produce heat but will also emit IR rays, yes every burning flame will emit some level of IR light, this light is not visible to human eyes but our flame sensor can detect it and alert a microcontroller like Arduino that a fire has been detected. , you can also check that our if you are interested.

Flame Sensor

sometimes. There are different types of flame detection methods. Some of them are: Ultraviolet detector, near IR array detector, infrared (IR) detector, Infrared thermal cameras, UV/IR detector etc. When fire burns it emits a small amount of Infra-red light, this light will be received by the Photodiode (IR receiver) on the sensor module. Then we use an Op-Amp to check for a change in voltage across the IR Receiver, so that if a fire is detected the outputpin (DO) will give 0V(LOW), and if the is no fire the output pin will be 5V(HIGH). It is based on the YG1006 sensor which is a high speed and high sensitive NPN silicon phototransistor. It can detect infrared light with a wavelength ranging from 700nm to 1000nm and its detection angle is about 60°. The flame sensor module consists of a photodiode (IR receiver), resistor, capacitor, potentiometer, and LM393 comparator in an integrated circuit. The sensitivity can be adjusted by varying the onboard potentiometer. Working voltage is between 3.3v and 5v DC, with a digital output. A logic high on the output indicates the presence of flame or fire. A logic low on output indicates the absence of flame or fire. Below is the Pin Description of the Flame sensor Module:
Vcc3.3 ᾠ5V power supply
GNDGround
DoutDigital output
Hydrogen stations Combustion monitors for burners Oil and gas pipelines Automotive manufacturing facilities Nuclear facilities Aircraft hangars Turbine enclosures

Components Required

Arduino Uno (any Arduino board can be used) Flame sensor module LED Buzzer Resistor Jumper wires

Circuit Diagram

circuit diagram, it shows how to interface the fire sensor module with Arduino.

Working of Flame Sensor with Arduino

Uno is a open-source microcontroller board based on the ATmega328p microcontroller. It has 14 digital pins (out of which 6 pins can be used as PWM outputs), 6 analog inputs, on-board voltage regulators etc. Arduino Uno has 32KB of flash memory, 2KB of SRAM and 1KB of EEPROM. It operates at a clock frequency of 16MHz. Arduino Uno supports Serial, I2C, SPI communication for communicating with other devices. The table below shows the technical specification of Arduino Uno.
MicrocontrollerATmega328p
Operating voltage5V
Input Voltage7-12V (recommended)
Digital I/O pins14
Analog pins6
Flash memory32KB
SRAM2KB
EEPROM1KB
Clock speed16MHz
or flame based on the Infrared (IR) wavelength emitted by the flame. It gives logic 1 as output if a flame is detected, otherwise, it gives logic 0 as output. Arduino Uno checks the logic level on the output pin of the sensor and performs further tasks such as activating the buzzer and LED, sending an alert message. Also, check our other fire alarm projects: Fire Alarm using Thermistor Fire Alarm System using AVR Microcontroller Arduino Based Fire Fighting Robot

Code explanation

for this project is given at the end of this article. The code is split into small meaningful chunks and explained below. which are connected to Arduino. The flame sensor is connected to digital pin 4 of Arduino. The buzzer is connected to digital pin 8 of Arduino. LED is connected to digital pin 7 of Arduino. ᾠis used for storing the digital value read out from the flame sensor. Based on this value we will detect the presence of flame. int buzzer = 8 ; int LED = 7 ; int flame_sensor = 4 ; int flame_detected ; and configure Baud rate for Serial communication with PC for displaying the status of the flame detection circuit. void setup() { Serial.begin(9600) ; pinMode(buzzer, OUTPUT) ; pinMode(LED, OUTPUT) ; pinMode(flame_sensor, INPUT) ; } ᾮ flame_detected = digitalRead(flame_sensor) ; , it indicates that flame has been detected. We have to turn on buzzer and LED and then display an alert message in Serial monitor of Arduino IDE. , then it indicates that no flame has been detected so we have to turn off LED and buzzer. This process is repeated every second to identify the presence of fire or flame. if (flame_detected == 1) { Serial.println("Flame detected...! take action immediately."); digitalWrite(buzzer, HIGH); digitalWrite(LED, HIGH); delay(200); digitalWrite(LED, LOW); delay(200); } else { Serial.println("No flame detected. stay cool"); digitalWrite(buzzer, LOW); digitalWrite(LED, LOW); } delay(1000); based on this concept, which automatically detects the fire and pump out the water to put down the fire. Now you know how to do fire detection using Arduino and flame sensor, hope you enjoyed learningit, if you have any questions leave them in the comment section below. below. Code int buzzer = 8; int LED = 7; int flame_sensor = 4; int flame_detected; void setup() { Serial.begin(9600); pinMode(buzzer, OUTPUT); pinMode(LED, OUTPUT); pinMode(flame_sensor, INPUT); } void loop() { flame_detected = digitalRead(flame_sensor); if (flame_detected == 1) { Serial.println("Flame detected...! take action immediately."); digitalWrite(buzzer, HIGH); digitalWrite(LED, HIGH); delay(200); digitalWrite(LED, LOW); delay(200); } else { Serial.println("No flame detected. stay cool"); digitalWrite(buzzer, LOW); digitalWrite(LED, LOW); } delay(1000); } Video microcontroller-projects/arduino-reed-switch-interfacing

Reed Switch Interfacing with Arduino

Reed Switch

around the switch. The glass enclosure of the two metal pieces protect them from dirt, dust and other particles. Reed switch can be operated in any environment such as environment where flammable gas is present or environment where corrosion would affect open switch contacts. Normally open reed switch Normally closed reed switch , switch is open in the absence of magnetic field and it is closed in the presence of magnetic field. Under the presence of magnetic field, two metal contacts inside the glass tube attract each other to make contact. , switch is closed in the absence of magnetic field and it is open in the presence of magnetic field. Used in telephone exchange In laptops to put the screen on sleep if the lid is closed Used in window and door sensors in burglar alarm system

Components Required

Arduino Uno Reed switch Resistors LED Magnet Connecting wires

Arduino Reed Switch Circuit Diagram

Working of Reed Switch with Arduino

Uno is a open source microcontroller board based on ATmega328p microcontroller. It has 14 digital pins (out of which 6 pins can be used as PWM outputs), 6 analog inputs, on board voltage regulators etc. Arduino Uno has 32KB of flash memory, 2KB of SRAM and 1KB of EEPROM. It operates at the clock frequency of 16MHz. Arduino Uno supports Serial, I2C, SPI communication for communicating with other devices. The table below shows the technical specification of Arduino Uno.
MicrocontrollerATmega328p
Operating voltage5V
Input Voltage7-12V (recommended)
Digital I/O pins14
Analog pins6
Flash memory32KB
SRAM2KB
EEPROM1KB
Clock speed16MHz
in this project. Switch is closed in the presence of magnetic field and it is open in the absence of magnetic field.

Code explanation

is given at the end of this article. The code is split into small meaningful chunks and explained below. is used to hold the status of reed switch. int LED = 7; int reed_switch = 4; int reed_status; Pin number 4 is set as input and pin number 7 is set as output. void setup() { pinMode(LED, OUTPUT); pinMode(reed_switch, INPUT); } If it is equal to 1, switch is open and LED is turned off. If it is equal to 0, switch is closed and we have to turn on LED. This process is repeated every second. This task is accomplished with this part of the code below. void loop() { reed_status = digitalRead(reed_switch); if (reed_status == 1) digitalWrite(LED, LOW); else digitalWrite(LED, HIGH); delay(1000); } So as you have seen its very easy to use Reed Switch with Arduino. Code int LED = 7; int reed_switch = 4; int reed_status; void setup() { pinMode(LED, OUTPUT); pinMode(reed_switch, INPUT); } void loop() { reed_status = digitalRead(reed_switch); if (reed_status == 1) digitalWrite(LED, LOW); else digitalWrite(LED, HIGH); delay(1000); } Video microcontroller-projects/interfacing-rotary-encoder-with-arduino

What is Rotary Encoder and How to Use It with Arduino

is an input device which helps the user to interact with a system. It looks more like a Radio potentiometer but it outputs a train of pulses which makes its application unique. When the knob of the Encoder is rotated it rotates in form of small steps which helps it to be used for stepper/Servo motor controlling, navigating through a sequence of menu and Increasing/decreasing the value of a number and much more. and control the value of an integer by rotating the Encoder and display its value on a 16*2 LCD screen. At the end of this tutorial you will be comfortable with using an Rotary Encoder for your projects. So let’s get started...

Materials Required

Rotary Encoder (KY-040) Arduino UNO 16*2 Alphanumeric LCD Potentiometer 10k Breadboard Connecting wires

How does a Rotary Encoder Work?

since we are using it for our tutorial. (copper colour) placed on top of this circular disc. These conductive pads are placed at an equal distance as shown below. The Output pins are fixed on top of this circular disc, in such a way that when the knob is rotates the conductive pads get in contact with the output pins. Here there are two output pin, Output A and Output B as shown in the figure below. The output waveform produced by the Output pin A and Output B is show in blue and green colour respectively. When the conductive pad is directly under the pin it goes high resulting it on time and when the conductive pad moves away the pin goes low resulting in off time of the waveform shown above. Now, if we count the number of pulses we will be able to determine how many steps the Encoder has been moved. Now the question may arise that, why do we need two pulse signals when one is enough to count the number of steps taken while rotating the knob. This is because we need to identify in which direction the knob has been rotated. If you take a look at the two pulses you can notice that they both are 90° out of phase. Hence when the knob is rotated clockwise the Output A will go high first and when the knob is rotated anti-clockwise the Output B will go high first.

Types of Rotary Encoder

There are many types of rotary encoder in the market the designer can choose one according to his application. The most common types are listed below Incremental Encoder Absolute Encoder Magnetic Encoder Optical Encoder Laser Encoder

KY-040 Rotary Encoder Pinout and description

The pinouts of the KY-040 Incremental type rotary encoder is shown below The first two pins (Ground and Vcc) is used to power the Encoder, typically +5V supply is used. Apart from rotating the knob in clock wise and anti-clockwise direction, the encoder also has a switch (Active low) which can be pressed by pressing the knob inside. The signal from this switch is obtained through the pin 3 (Switch). Finally it has the two output pins which produce the waveforms as already discussed above. Now let us learn how to interface it with Arduino.

ArduinoRotary Encoder Circuit Diagram

is shown in the picture below The Rotary Encoder has 5 pins in the order shown in the label above. The first two pins are Ground and Vcc which is connected to the Ground and +5V pin of the Arduino. The switch of the encoder is connected to digital pin D10 and is also pulled high though a 1k resistor. The two output pins are connected to D9 and D8 respectively. follow the link. The complete circuit can be built on top of a breadboard, my looked something like this below once all the connections were done.

Programming your Arduino for Rotary Encoder

, it does not require any library. Now, let’s split the program into small chunks to understand the working. #include <LiquidCrystal.h> //Default Arduino LCD Library is included const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7); lcd.begin(16, 2); //Initialise 16*2 LCD , and then wait for 2 seconds so that that message is user readable. This is to ensure that the LCD is working properly. lcd.print(" Rotary Encoder "); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print(" With Arduino "); //Intro Message line 2 delay(2000); lcd.clear(); as shown below. //pin Mode declaration pinMode (Encoder_OuputA, INPUT); pinMode (Encoder_OuputB, INPUT); pinMode (Encoder_Switch, INPUT); function, we read the status of the output A pin to check the last status of the pin. We will then use this information to compare with the new value to check which pin (Output A or Output B) has gone high. Previous_Output = digitalRead(Encoder_OuputA); //Read the inital value of Output A to check which one goes high first. This can be done by simply comparing the value of current output of A and B with the previous output as shown below. if (digitalRead(Encoder_OuputA) != Previous_Output) { if (digitalRead(Encoder_OuputB) != Previous_Output) { Encoder_Count ++; lcd.clear(); lcd.print(Encoder_Count); lcd.setCursor(0, 1); lcd.print("Clockwise"); } direction. The code for the same is shown below. else { Encoder_Count--; lcd.clear(); lcd.print(Encoder_Count); lcd.setCursor(0, 1); lcd.print("Anti - Clockwise"); } } we have to update the previous output value with the current output value so that the loop can be repeated with the same logic. The following code does the same Previous_Output = digitalRead(Encoder_OuputA); , meaning that it will go low when the button is pressed. If not pressed the pin stays high, we also have used a pull up resistor to make sure the stays high when switch is not pressed thus avoiding floating point condition. if (digitalRead(Encoder_Switch) == 0) { lcd.clear(); lcd.setCursor(0, 1); lcd.print("Switch pressed"); }

Working of Rotary Encoder with Arduino

Once the hardware and code is ready, just upload the code to the Arduino board and power up the Arduino Board. You can either power it through the USB cable or use a 12V adapter. When powered the LCD should display the intro message and then get blank. Now rotate the rotary encoder and you should see the value begin incremented or decremented based on the direction you rotate. The second line will show you if the encoder is being rotated in clockwise or anti-clockwise direction. The picture below shows the same below. This is just a sample program to interface the Encoder with Arduino and check if it is working as expected. Once you get here you should be able to use the encoder for any of your projects and program accordingly. Hope you have understood the tutorial and things worked as it is supposed to. If you have any problems use the comment section or the forums for technical help. Code /* * Interfacing Rotary Encoder with Arduino * Dated: 6-7-2018 * Website: www.circuitdigest.com * * Power LCD and Rotary encoder from the +5V pin of Arduino * LCD RS -> pin 7 * LCD EN -> pin 6 * LCD D4 -> pin 5 * LCD D5 -> pin 4 * LCD D6 -> pin 3 * LCD D7 -> pin 2 * Encoder Switch -> pin 10 * Encoder Output A -> pin 9 * Encoder Output B -> pin 8 */ int Encoder_OuputA = 9; int Encoder_OuputB = 8; int Encoder_Switch = 10; int Previous_Output; int Encoder_Count; #include <LiquidCrystal.h> //Default Arduino LCD Librarey is included const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7); void setup() { lcd.begin(16, 2); //Initialise 16*2 LCD lcd.print(" Rotary Encoder "); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print(" With Arduino "); //Intro Message line 2 delay(2000); lcd.clear(); //pin Mode declaration pinMode (Encoder_OuputA, INPUT); pinMode (Encoder_OuputB, INPUT); pinMode (Encoder_Switch, INPUT); Previous_Output = digitalRead(Encoder_OuputA); //Read the inital value of Output A } void loop() { //aVal = digitalRead(pinA); if (digitalRead(Encoder_OuputA) != Previous_Output) { if (digitalRead(Encoder_OuputB) != Previous_Output) { Encoder_Count ++; lcd.clear(); lcd.print(Encoder_Count); lcd.setCursor(0, 1); lcd.print("Clockwise"); } else { Encoder_Count--; lcd.clear(); lcd.print(Encoder_Count); lcd.setCursor(0, 1); lcd.print("Anti - Clockwise"); } } Previous_Output = digitalRead(Encoder_OuputA); if (digitalRead(Encoder_Switch) == 0) { lcd.clear(); lcd.setCursor(0, 1); lcd.print("Switch pressed"); } } Video microcontroller-projects/what-is-bldc-motor-and-arduino-bldc-motor-control

What is Brushless DC Motor (BLDC) and How to Control it with Arduino

and why do we use it? If you have questions like these then this tutorial is your one stop solution. outrunner motor is usedwith a 20A Electronic Speed Controller (ESC). Thismotoriscommonlyused tobuild drones.

Materials Required

A2212/13T BLDC Motor ESC (20A) Power Source (12V 20A) Arduino Potentiometer

Understanding BLDC Motors

is previously explained in detail.Unlike other motors, the BLDC motors have three wires coming out of them and each wire forms its own phase thus given us a three phase Motor. Wait... what!!?? , so that current enters through one phase and leaves through other. During this process the coil inside the motor is energised and hence the magnets on the rotor align itself to the energised coil. Then the next two wires are energised by the ESC, this process is continued to make the motor rotate. The speed of the motor depends on how fast the coil is energised and direction of motor depends on in which order the coils are energised. We will learn more about ESC later in this article. There are many types of BLDC motors available, let’s take look at the most common classifications. are just the opposite, the Outer casing of the motor rotates along with the shaft while the coil inside stays fixed. Out runner motors are very advantages in Electric bikes since the outer casing (the one that rotates) itself is made into a Rim for the tyres and hence a coupling mechanism is avoided. Also the out runner motors tend to give more torque than in runner types, hence it becomes an ideal choice in EV and Drones. The one that we are using here is also an out runner type. There is another type of motor called the coreless BLDC motors which are also used for pocket Drones, they have a different working principle but for now let’s skip it for the sake of this tutorial. For a BLDC motor to rotate without any jerk a feedback is required. That is the ESC has to know the position and pole of the magnets in the rotor so as to energise the stator according. This information can be acquired in two ways; one is by placing hall sensor inside the motor. The hall sensor will detect the magnet and send the information to ESC this type of motor is called a Sensord BLDC motor and is used in Electric vehicles. The second method is by using the back EMF generated by the coils when the magnets cross them, this required not additional hardware or wires the phase wire itself is used as a feedback to check for back EMF. This method is used in our motor and is common for drones and other flying projects.

Why do Drones and other Multi-copters use BLDC Motors?

There are many types of cool drones out there from Quad copter to helicopters and gliders everything has one hardware in common. That is the BLDC motors, but why? Why do they use a BLDC motor which is a bit expensive compared to DC Motors? , this is very ideal to our drone stable in mid-air. This is very important because the motors used on drones should be of high power (high speed and high torque) but should also be of less weight. A DC motor which could provide the same torque and speed of that of a BLDC motor will be twice as heavy as the BLDC motor.

Why do we need an ESC and what is its function?

here. Almost all ESC’s comes with a Battery eliminator circuit. As the name suggests this circuit eliminates the need of separate battery for microcontroller, in this case we do not need a separate power supply to power our Arduino; the ESC itself will provide a regulated +5V which can be used power our Arduino. There are many types of circuit which regulates this voltage normally it will be linear regulation on the cheap ESCs, but you can also find ones with switching circuits. Every ESC has a firmware program written into it by the manufactures. This firmware greatly determines how your ESC responds; some of the popular firmware is Traditional, Simon-K and BL-Heli. This firmware is also user programmable but we will not get into much of that in this tutorial.

Some common terms with BLDC and ESC’s:

Let’s take a look into what these terms mean. Braking is the ability of your BLDC motor to stop rotating as soon as the throttle is removed. This ability is very important for multi-copters since they have to change their RPM more often to manoeuvre in the air. Soft start is an important feature to consider when your BLDC motor is associated with gear. When a motor has soft start enabled, it will not start rotating very fast all of a sudden, it will always gradually increase the speed no matter how quickly the throttle was given. This will help us in reducing the wear and tear of gears attached with the motors (if any). The motor direction in BLDC motors are normally not changed during operation. But when assembling, the user might need to change the direction in which the motor is rotating. The easiest way to change the direction of the motor is by simply inter changing any two wires of the motor. Once calibrated we would always need our BLDC motors run at the same particular speed for a particular value of throttle. But this is hard to achieve because the motors tend to reduce their speed for the same value of throttle as the battery voltage decreases. To avoid this we normally program the ESC to stop working when the battery voltage has reached below the threshold value this function is called Low Voltage Stop and is useful in drones. The ability of the motor to quickly change its speed based on the change in throttle is called response time. The lesser the response time is the better the control will be. Advance is a problem or more like a bug with BLDC motors. All BLDC motors have a little bit of advance in them. That is when the stator coils are energised the rotor is attracted towards it because of the permanent magnet present on them. After getting attracted the rotor tends to move a bit more forward in that same direction before the coil de-energises and then next coil energises. This movement is called “Advanceᾠand it will create problems like jittering, heating up, making noise etc. So this is something a good ESC should avoid on its own. Okay, enough theory now let us get started with the hardware by connecting the motor with the Arduino.

ArduinoBLDCMotor Control Circuit Diagram

is pretty straight forward. The ESC needs a powers source of around 12V and 5A minimum. In this tutorial I have used my RPS as a power source but you can also use a Li-Po battery to power the ESC. The three phase wires of the ESC should be connected to the three phase wires of the motors, there is no order to connect these wires you can connect them in any order. Some ESC will not have connectors on them, in that case make sure your connection is solid and protect the exposed wires using insulation tape. Since there will be high current passing through the phases any short would lead to permanent damage of the ESC and motor. in the ESC itself will regulate a +5V which can be used to power up the Arduino Board. Finally to set the speed of the BLDC motor we also use a potentiometer connected to A0 pin of the Arduino

Program for BLDCSpeed Control using Arduino

so we connect the ESC signal pin (orange wire) to pin 9 we also mention the same inn code by using the following line ESC.attach(9); by using the analog read function as shown below int throttle = analogRead(A0); because the value 0 will generate 0% PWM and value 180 will generate 100% duty cycle. Any values above 180 will make no sense. So we map the value to 0-180 by using the map function as shown below. throttle = map(throttle, 0, 1023, 0, 180); so that it can generate the PWM signal on that pin. Since we have named out servo object as ESC the code will look like this below, where the variable throttle contains the value from 0-180 to control the duty cycle of the PWM signal ESC.write(throttle);

ArduinoBLDCMotorControl

Make the connections according to the circuit diagram and upload the code to Arduino and power up the ESC. Make sure you have mounted the BLDC motor onto something since the motor will jump all around when rotating. Once the setup is powered on, your ESC will make a welcome tone and will keep beeping until the throttle signal is within the threshold limits, simple increase the POT from 0V gradually and the beeping tone will stop, this means that we are now providing PWM signal above the lower threshold value and as you increase further your motor will start rotating slowly. The more voltage you provide the more speed the motor will pick up, finally when the voltage reaches above the upper threshold limit the motor will stop. You can then repeat the process. can also be found at the video link below. If you had faced any problem on getting this to work feel free to use the comment section or use the forums for more technical help. Code #include <Servo.h> //Use the Servo librarey for generating PWM Servo ESC; //name the servo object, here ESC void setup() { ESC.attach(9); //Generate PWM in pin 9 of Arduino } void loop() { int throttle = analogRead(A0); //Read the voltage from POT throttle = map(throttle, 0, 1023, 0, 180); //Map the values of 0-102 from pot to 0-180 bcs servo works only from 0-180 ESC.write(throttle); //based on the value of throttle generate PWM signal } Video microcontroller-projects/iot-electricity-energy-meter-using-esp12-arduino

IoT Based Electricity Energy Meter using ESP12 and Arduino

of Energy Meter. to measure the energy consumption, we will discuss about it shortly. Android App to monitor our Energy uses. So Lets Get started‐󬋊

Materials Required:

Arduino Uno ESP12/NodeMCU ACS712-30Amp Current sensor Any AC Appliance Male-Female Wires

Working of ACS712 Current Sensor:

Before we start building the project it is very important for us to understand the working of the ACS712 Current sensor as it is the key component of the project. Measuring current especially AC current is always a tough task due to the noise coupled with it improper isolation problem etc. But, with the help of this ACS712 module which was engineered by Allegro thing have become a lot easier. , which was discovered by Dr. Edwin Hall. According his principle, when a current carrying conductor is placed into a magnetic field, a voltage is generated across its edges perpendicular to the directions of both the current and the magnetic field. Let us not get too deep into the concept but, simply put we use a hall sensor to measure the magnetic field around a current carrying conductor. This measurement will be in terms of millivolts which we called as the hall-voltage. This measured hall-voltage is proportional to the current that was flowing through the conductor. is that is can measure both AC and DC current and it also provides isolation between the Load (AC/DC load) and Measuring Unit (Microcontroller part). As shown in the picture we have three pins on the module which are Vcc, Vout and Ground respectively. The 2-pin terminal block is where the current carrying wire should be passed through. The module work on +5V so the Vcc should be powered by 5V and the ground should be connected to Ground of the system. The Vout pin has an offset voltage of 2500mV, meaning when there is no current flowing through the wire then the output voltage will be 2500mV and when current flowing is positive, the voltage will be greater than 2500mV and when the current flowing is negative, the voltage will be less than 2500mV. We will be using theAnalog pin of Arduinoto read the output voltage (Vout) of the module, which will be 512(2500mV) when there is no current flowing through the wire. This value will reduce as the current flows in negative direction and will increase as the current flows in positive direction. The below table will help you understand how the output voltage and ADC value varies based on the current flowing through the wire. These values were calculated based on the information given in the Datasheet of ACS712. You can also calculate them using the below formulae: Vout Voltage(mV) = (ADC Value/ 1023)*5000 Current Through the Wire (A) = (Vout(mv)-2500)/185 Now, that we know how the ACS712 Sensor works and what we could expect from it. Let us proceed to the circuit diagram.

Circuit diagram:

is given above, connect ESP12 as below: Connect Rx of ESP12 -> Tx of Arduino. Connect Tx of ESP12 -> Rx of Arduino. There is one analog pin available in NodeMCU (ESP12), we could use that pin but ESP series can take upto 3.3 volts on their pins. As we are using current sensor which can give upto 5 Volts so, it can damage our Wi-Fi module that’s why we are not using standalone NodeMCU. , we cannot use voltage divider circuit between Current sensor and analog pin of NodeMCU because as we discussed above about the current sensor that at 2.5Volts output, current is 0Amp. So, Arduino will read the current sensor value through analog pin and send it to the Wi-Fi module ESP12 using Serial communication. Use voltage divider circuit at receiver pin of NodeMCU so that receiver pin can get upto 3.3 Voltage level. and follow the below process to make this IoT Energy Meter Setting up an AdaFruit account for storing Electricity meter readings. Create Applet in IFTTT for Triggering SMS/Email for Energy Meter Codes for Arduino and ESP12Wi-Fi module.

Setting up an AdaFruit account for communication:

Feed stores the data sent by IFTTT. To make feed follow these steps: with your credentials or Sign up if you don’t have an account. . button and note down the AIO Keys, we will use this key in our code. to display Energy uses level. You can also use simple text box to display energy. Then Select the feed and click on Next step. In block settings, fill the min. and max values as 0 and 100 respectively or you can modify as you want. Your Power feed is successfully created. Now, create feed to display Bill by clicking on ᾫᾠsign. Now, we have to link AdaFruit IO to SMS/E-mail using IFTTT.

Create Applet in IFTTT for Triggering SMS/Email for Energy Meter:

with your credentials. and click on it. on AdaFruit IO. I have used 4 as my threshold trigger value. Search for G-mail and click on it and Login with your g-mail credentials. Write your subject and body as shown and click to create. ᾠis ready. Review it and click on finish. Now, we are done with web integration. Let’s move on coding part..

Code and Explanation:

So, we have to write code for both Arduino and NodeMCU for transmitting and receiving. This library has inbuilt function to calculate current. You can write your code to calculate current but this library has accurate current measuring algorithms. First, include library for current sensor as: #include "ACS712.h" Make an array to store power for sending it to NodeMCU. char watt[5]; Create an instance to use ACS712-30Amp at PIN A0. Change First argument if you are using 20Amp or 5 Amp variant. ACS712 sensor(ACS712_30A, A0); function for calibrating current sensor to get accurate readings. void setup() { Serial.begin(115200); sensor.calibrate(); } After getting current, calculate power using P=V*I formula. We use 230V because it is the common standard in European countries, Change to your local, if necessary void loop() { float V= 230; float I = sensor.getCurrentAC(); float P = V * I; These lines convert power into Wh. last_time = current_time; current_time = millis(); Wh = Wh+ P *(( current_time -last_time) /3600000.0) ; will convert a float to a char array so it can then be printed easily: dtostrf(Wh, 4, 2, watt); The format is: dtostrf(floatvar, StringLengthIncDecimalPoint, numVarsAfterDecimal, charbuf); value to NodeMCU. Serial.write(watt); delay(10000); } Now, open Arduino IDE. Go to examples -> AdaFruit MQTT library -> mqtt_esp8266 We will edit this code according to our AIO keys and Wi-Fi credentials and incoming serial data from the Arduino. First, we included all the libraries for ESP12Wi-Fi Module and AdaFruit MQTT. #include <ESP8266WiFi.h> #include "Adafruit_MQTT.h" #include "Adafruit_MQTT_Client.h" We define the SSID and Password for your Wi-Fi, from which you want to connect your ESp-12e. #define WLAN_SSID "xxxxxxxx" #define WLAN_PASS "xxxxxxxxxxx" This section defines the AdaFruit server and server port which is fixed as “io.adafruit.comᾠand ᾱ883ᾠrespectively. #define AIO_SERVER "io.adafruit.com" #define AIO_SERVERPORT 1883 Replace these fields with your username and AIO keys which you have copied from AdaFruit site while making the Feed. #define AIO_USERNAME "********" #define AIO_KEY "******************************" Then we have created an ESP12WiFiClient class to connect to the MQTT server. WiFiClient client; Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); for publishing to changes. Adafruit_MQTT_Publish Power = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Power"); Adafruit_MQTT_Publish bill = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/bill"); function, we connect Wi-Fi module to Wi-fi access point. void setup() { Serial.begin(115200); delay(10); Serial.println(F("Adafruit MQTT demo")); // Connect to WiFi access point. Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(WLAN_SSID); WiFi.begin(WLAN_SSID, WLAN_PASS); …. …. … } function, we will check for incoming data from the Arduino and publish this data to AdaFruit IO. void loop() { // Ensure the connection to the MQTT server is alive (this will make the first // connection and automatically reconnect when disconnected). See the MQTT_connect // function definition further below. MQTT_connect(); int i=0; float watt1; function. if(Serial.available() > 0 ){ delay(100); //allows all serial sent to be received together while(Serial.available() && i<5) { watt[i++] = Serial.read(); } watt[i++]='\0'; } watt1 = atof(watt); Calculate bill amount by multiplying power (in Wh) with energy tariff and divide it by 1000 to make power in KWh. bill_amount = watt1 * (energyTariff/1000); // 1unit = 1kwH Now we can publish stuff! Serial.print(F("\nSending Power val ")); Serial.println(watt1); Serial.print("..."); feed if (! Power.publish(watt1)) { Serial.println(F("Failed")); } else { Serial.println(F("OK!")); } feed. if (! bill.publish(bill_amount)) { Serial.println(F("Failed")); } else { Serial.println(F("OK!")); } so these lines will give time for triggering so that we can receive threshold email. value on which you want to get email. Also, change in the IFTTT AdaFruit IO setup. if (bill_amount==4){ for (int i =0; i<=2; i++) { bill.publish(bill_amount); delay(5000); } bill_amount =6; } are given at the end of this tutorial. Open the dashboard you just created. You will see the Power consumption and electricity Bill is updating.

Android App for Monitoring Electricity Consumption:

To setup connection with the io.adafruit.com follow these steps: Open the App and click on ᾫᾠsign. Fill Client Id anything you want. Server and port remain same as shown in the screenshot. You will get Username and password (Active key) from the AdaFruit IO dashboard as shown below. Active Key is your password. and click on create. feed. , which can be not only monitored from anywhere in the world but also trigger Email when you have high Electricity consumption. Code #include "ACS712.h" char watt[5]; ACS712 sensor(ACS712_30A, A0); unsigned long last_time =0; unsigned long current_time =0; float Wh =0 ; void setup() { Serial.begin(115200); sensor.calibrate(); } void loop() { float V = 230; float I = sensor.getCurrentAC(); // Serial.println(I); float P = V * I; last_time = current_time; current_time = millis(); Wh = Wh+ P *(( current_time -last_time) /3600000.0) ; dtostrf(Wh, 4, 2, watt); Serial.write(watt); delay(10000); } #include <ESP8266WiFi.h> #include "Adafruit_MQTT.h" #include "Adafruit_MQTT_Client.h" #define WLAN_SSID "a*************" #define WLAN_PASS "*******************" char watt[5]; #define AIO_SERVER "io.adafruit.com" #define AIO_SERVERPORT 1883 #define AIO_USERNAME "rjrishabh" #define AIO_KEY "***********************" WiFiClient client; int bill_amount = 0; unsigned int energyTariff = 8.0; Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); Adafruit_MQTT_Publish Power = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Power"); Adafruit_MQTT_Publish bill = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/bill"); void MQTT_connect(); void setup() { Serial.begin(115200); delay(10); Serial.println(F("Adafruit MQTT demo")); // Connect to WiFi access point. Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(WLAN_SSID); WiFi.begin(WLAN_SSID, WLAN_PASS); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void loop() { // Ensure the connection to the MQTT server is alive (this will make the first // connection and automatically reconnect when disconnected). See the MQTT_connect // function definition further below. MQTT_connect(); int i=0; float watt1; if(Serial.available() > 0 ){ delay(100); //allows all serial sent to be received together while(Serial.available() && i<5) { watt[i++] = Serial.read(); } watt[i++]='\0'; } watt1 = atof(watt); bill_amount = watt1 * (energyTariff/1000); // 1unit = 1kwH Serial.print(F("\nSending Power val ")); Serial.println(watt1); Serial.print("..."); if (! Power.publish(watt1)) { Serial.println(F("Failed")); } else { Serial.println(F("OK!")); } if (! bill.publish(bill_amount)) { Serial.println(F("Failed")); } else { Serial.println(F("OK!")); } if (bill_amount==4){ for (int i =0; i<=2; i++) { bill.publish(bill_amount); delay(5000); } bill_amount =6; } delay(5000); } // Function to connect and reconnect as necessary to the MQTT server. // Should be called in the loop function and it will take care if connecting. void MQTT_connect() { int8_t ret; // Stop if already connected. if (mqtt.connected()) { return; } Serial.print("Connecting to MQTT... "); uint8_t retries = 3; while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected Serial.println(mqtt.connectErrorString(ret)); Serial.println("Retrying MQTT connection in 5 seconds..."); mqtt.disconnect(); delay(5000); // wait 5 seconds retries--; if (retries == 0) { // basically die and wait for WDT to reset me while (1); } } Serial.println("MQTT Connected!"); } Video microcontroller-projects/arduino-relay-driver-shield-pcb

DIY Arduino Relay Driver Shield

we can operate 3 AC appliances at a time. We have put a two pin screw terminal blocks (Neutral, NO) for connecting appliances. Here we have provided PCB layout, circuit diagram, and Gerber files so that you can build or directly order this Relay Driver Module.

Components Required:

SPDT relay 12v -3 817 Optocoupler -3 Transistor BC547 -3 SMD LEDs -4 PCB (ordered from JLCPCB) -1 Terminal Block 2 pin -4 1N4007 Diode -3 1k Resistor -7 Burg sticks male -1 Jumper ᾠ1 Push Button Power supply Arduino for demonstration Connecting wire AC appliances

Arduino Relay Driver Shield Circuit Diagram:

which further drives the relay. And optocoupler will be triggered by the active LOW signal. Here we have used a 12v 10Amp relay in this PCB board, you can also use 5v relays.

Working and Demonstration:

at the end of this project. then follow this link. You just have to fix the Arduino shield over Arduino and control 3 Appliances using this shield. You can use the given code (in the end) or use your own code for controlling the AC appliaces.

Circuit and PCB Design using EasyEDA:

where they have a large stock of electronic components and users can order their required components along with the PCB order. While designing your circuits and PCBs, you can also make your circuit and PCB designs public so that other users can copy or edit them and can take benefit from your work, we have also made our whole Circuit and PCB layouts public for thiscircuit,check the below link: button in EasyEDA:

Calculating and Ordering Samples online:

page. and click onQuote NoworBuy Now button, then you can select the number of PCBs you want to order, how manycopper layers you need, the PCB thickness, copper weight, and even the PCB color, like the snapshot shown below: Afteryou have selected all of theoptions, click “Save to Cartᾠand then you will be taken to the page where you can upload your Gerber File which we have downloaded fromEasyEDA. Upload your Gerber file and click “Save to Cartᾮ Andfinallyclick on Checkout Securely to complete your order, then you will get your PCBs a few days later. They are fabricating the PCB atverylow rate which is $2. Theirbuild time is also verylesswhichis 48 hours with DHL delivery of 3-5 days,basicallyyou will get your PCBs within a week of ordering. with date and time. You check it by going on Account page and click on "Production Progress" link under the PCB like, shown in below image. After few days of orderingPCB’sI got thePCB samples in nice packagingas shown in below pictures. After getting these pieces I have mounted all the required components over the PCB connected it with Arduino for demonstration. So our Arduino Relay Shield is ready, and you can directly use it with Arduino to control three AC appliances. You just have to place this Arduino shield over Arduino and upload the below given code. You can adjust the code according to you. given below. Code #define RLY1 7 #define RLY2 9 #define RLY3 12 void setup() { pinMode(RLY1, OUTPUT); pinMode(RLY2, OUTPUT); pinMode(RLY3, OUTPUT); digitalWrite(RLY1, LOW); digitalWrite(RLY2, LOW); digitalWrite(RLY3, LOW); } void loop() { digitalWrite(RLY1, HIGH); digitalWrite(RLY2, HIGH); digitalWrite(RLY3, LOW); delay(1000); digitalWrite(RLY1, HIGH); digitalWrite(RLY2, LOW); digitalWrite(RLY3, HIGH); delay(1000); digitalWrite(RLY1, LOW); digitalWrite(RLY2, HIGH); digitalWrite(RLY3, HIGH); delay(1000); } Video microcontroller-projects/arduino-piano-with-record-and-playback

Arduino Based Piano with Recording and Replay

when required. Sound interesting right!! So letsᾠget building....

Materials Required:

Arduino Uno 16*2 LCD Display Buzzer Trimmer 10k SPDT switch Push button (8 Nos) Resistors (10k, 560R, 1.5k, 2.6k, 3.9, 5.6k, 6.8k, 8.2k, 10k) Breadboard Connecting wires

Circuit Diagram:

can be built on top of a breadboard with some connecting wires. The circuit diagram made using fritzing that shows the breadboard view of the project is shown below Just follow the circuit diagram and connect the wires accordingly, the push buttons and buzzer as used with a PCB module but in actual hardware we have used only the switch and buzzer, it should not confuse you much because they have the same type of pin out. You can also refer to the below image of the hardware to make your connections. If you do not have the same DPST switch you can use normal toggle switch like the one shown in the circuit diagram above. Now let’s look into the schematics of the project to understand why we have made the following connections.

Schematics and Explanation:

The schematics for the circuit diagram that is shown above is given below, it was also made using Fritzing. with varying resistor values to complete the circuit. This way when each button is pressed a different analog voltage will be supplied to the Analog pin. A sample circuit with only two resistors and two push buttons are shown below. page. is connected to the pin 6 of Arduino. The complete project is powered through the USB port of the laptop. You can also connect the Arduino to a 9V or 12V supply through the DC jack and the project will still work the same.

Understanding theTone()function of Arduino:

The Arduino has a handy tone() function which can be used to generate varying frequency signals that can be used to produce different sounds using a buzzer. So let’s understand how the function works and how it can be used with Arduino. Before that we should know how a Piezo buzzer works. We might have learnt about Piezo crystals in our school, it is nothing but a crystal which converts mechanical vibrations into electricity or vice versa. Here we apply a variable current (frequency) for which the crystal vibrates thus producing sound. Hence in order to make the Piezo buzzer to make some noise we have to make the Piezo electric crystal to vibrate, the pitch and tone of noise depends on how fast the crystal vibrates. Hence the tone and pitch can be controlled by varying the frequency of the current. comes in. The tone () can generate a particular frequency on a specific pin. The time duration can also be mentioned if required. The syntax fortone ()is Syntax tone(pin, frequency) tone(pin, frequency, duration) Parameters pin: the pin on which to generate the tone frequency: the frequency of the tone in hertz – unsigned int duration: the duration of the tone in milliseconds (optional1) ᾠunsigned long The values of pin can be any of your digital pin. I have used pin number 8 here. The frequency that can be generated depends on the size of the timer in your Arduino board. For UNO and most other common boards the minimum frequency that can be produced is 31Hz and the maximum frequency that can be produced is 65535Hz. However we humans can hear only frequencies between 2000Hz and 5000 Hz.

Playing piano tones on Arduino:

Okay, before even I get started on this topic let me make it clear that I am a novice with musical notes or piano, so please forgive me if anything mentioned under this heading is gibberish. library in that project. Our project has only 8 push buttons so each button can play only one particular musical note and thus totally we can play only 8 notes. I selected the most used notes on a piano, but can you can select any 8 or even expand the project with more push buttons and add more notes. which can be played using the buttons 1 to 8 respectively.

Programming the Arduino:

is given at the end of this page you can jump down if you eager or read further to understand how the code works. , then predict which button was pressed and play the respective tone for that button. While doing this we should also record which button the user has pressed and how long he/she has pressed, so that we can recreate the tone that was played by the user later. library and then a array is formed as shown below. Here the frequency to play note C4 is 262 and so on. int notes[] = {262, 294, 330, 349, 392, 440, 494, 523}; // Set frequency for C4, D4, E4, F4, G4, A4, B4, to. If you are following the exact same schematics given above then you don’t have to change anything here. const int rs = 8, en = 9, d4 = 10, d5 = 11, d6 = 12, d7 = 13; //Pins to which LCD is connected LiquidCrystal lcd(rs, en, d4, d5, d6, d7); In recording mode the user can pay the tones required and at the same time the tone that is being played will also be saved. So the while loop looks like this below while (digitalRead(6) == 0) //If the toggle switch is set in recording mode { lcd.setCursor(0, 0); lcd.print("Recording.."); lcd.setCursor(0, 1); Detect_button(); Play_tone(); } function records how long the button was pressed. we read the analog voltage from the pin A0 and compare it with some predefined values to find out which button has been pressed. The value can be determined by either using the voltage divider calculator above or by using the serial monitor to check what analog value is read for each button. void Detect_button() { analogVal = analogRead(A0); //read the analog voltag on pin A0 pev_button = button; //remember the previous button pressed by the user if (analogVal < 550) button = 8; if (analogVal < 500) button = 7; if (analogVal < 450) button = 6; if (analogVal < 400) button = 5; if (analogVal < 300) button = 4; if (analogVal < 250) button = 3; if (analogVal < 150) button = 2; if (analogVal < 100) button = 1; if (analogVal > 1000) button = 0; /****Rcord the pressed buttons in a array***/ if (button != pev_button && pev_button != 0) { recorded_button[button_index] = pev_button; button_index++; recorded_button[button_index] = 0; button_index++; } /**End of Recording program**/ } We first check if there is a new button pressed, if pressed then we also check if it is not the button 0. Where button 0 is nothing but no button is pressed. Inside the if loop we store the value on the index location given by the variable button_index and then we also increase this index value so that we don’t over write on the same location. /****Rcord the pressed buttons in a array***/ if (button != pev_button && pev_button != 0) { recorded_button[button_index] = pev_button; button_index++; recorded_button[button_index] = 0; button_index++; } /**End of Recording program**/ function to determine how long each button was pressed, also for reducing the size of the variable we divide the value by 10. For button 0, which means the user is not pressing anything we play no tone for the same duration. The complete code inside the function is shown below. void Play_tone() { /****Rcord the time delay between each button press in a array***/ if (button != pev_button) { lcd.clear(); //Then clean it note_time = (millis() - start_time) / 10; recorded_time[time_index] = note_time; time_index++; start_time = millis(); } /**End of Recording program**/ if (button == 0) { noTone(7); lcd.print("0 -> Pause.."); } if (button == 1) { tone(7, notes[0]); lcd.print("1 -> NOTE_C4"); } if (button == 2) { tone(7, notes[1]); lcd.print("2 -> NOTE_D4"); } if (button == 3) { tone(7, notes[2]); lcd.print("3 -> NOTE_E4"); } if (button == 4) { tone(7, notes[3]); lcd.print("4 -> NOTE_F4"); } if (button == 5) { tone(7, notes[4]); lcd.print("5 -> NOTE_G4"); } if (button == 6) { tone(7, notes[5]); lcd.print("6 -> NOTE_A4"); } if (button == 7) { tone(7, notes[6]); lcd.print("7 -> NOTE_B4"); } if (button == 8) { tone(7, notes[7]); lcd.print("8 -> NOTE_C5"); } } loop and enters the second while loop where we play the notes in the sequence of the buttons pressed for a duration that was previously recorded. The code to do the same is shown below. while (digitalRead(6) == 1) //If the toggle switch is set in Playing mode { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Now Playing.."); for (int i = 0; i < sizeof(recorded_button) / 2; i++) { delay((recorded_time[i]) * 10); //Wait for before paying next tune if (recorded_button[i] == 0) noTone(7); //user dint touch any button else tone(7, notes[(recorded_button[i] - 1)]); //play the sound corresponding to the button touched by the user } } }

Play, Record, Replay and Repeat! :

and on the second line you will see the name of the note that is currently being pressed as shown below and then start playing the tone that you just played. The same tone will be played again and again as long as the toggle switch is kept in the position as shown in the below picture. given below. Code /* Arduino based Piano and Record and play option Code by: B. Aswinth Raj Website: www.circuitdigest.com Dated: 22-05-2017 */ #include <LiquidCrystal.h> int notes[] = {262, 294, 330, 349, 392, 440, 494, 523}; // Set frequency for C4, D4, E4, F4, G4, A4, B4, C5 const int rs = 8, en = 9, d4 = 10, d5 = 11, d6 = 12, d7 = 13; //Pins to which LCD is connected LiquidCrystal lcd(rs, en, d4, d5, d6, d7); char button = 0; int analogVal; char REC = 0; int recorded_button[200]; int pev_button; int recorded_time [200]; char time_index; char button_index = 0; unsigned long start_time; int note_time; void setup() { Serial.begin(9600); pinMode (6, INPUT); lcd.begin(16, 2); //We are using a 16*2 LCD display lcd.print("Arduino Piano"); //Display a intro message lcd.setCursor(0, 1); // set the cursor to column 0, line 1 lcd.print("-CircuitDigest"); //Display a intro message delay(2000); //Wait for display to show info lcd.clear(); //Then clean it } void loop() { while (digitalRead(6) == 0) //If the toggle switch is set in recording mode { lcd.setCursor(0, 0); lcd.print("Recording.."); lcd.setCursor(0, 1); Detect_button(); Play_tone(); } while (digitalRead(6) == 1) //If the toggle switch is set in Playing mode { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Now Playing.."); for (int i = 0; i < sizeof(recorded_button) / 2; i++) { delay((recorded_time[i]) * 10); //Wait for before paying next tune if (recorded_button[i] == 0) noTone(7); //user dint touch any button else tone(7, notes[(recorded_button[i] - 1)]); //play the sound corresponding to the button touched by the user } } } void Detect_button() { analogVal = analogRead(A0); //read the analog voltag on pin A0 pev_button = button; //remember the previous button pressed by the user if (analogVal < 550) button = 8; if (analogVal < 500) button = 7; if (analogVal < 450) button = 6; if (analogVal < 400) button = 5; if (analogVal < 300) button = 4; if (analogVal < 250) button = 3; if (analogVal < 150) button = 2; if (analogVal < 100) button = 1; if (analogVal > 1000) button = 0; /****Rcord the pressed buttons in a array***/ if (button != pev_button && pev_button != 0) { recorded_button[button_index] = pev_button; button_index++; recorded_button[button_index] = 0; button_index++; } /**End of Recording program**/ } void Play_tone() { /****Rcord the time delay between each button press in a array***/ if (button != pev_button) { lcd.clear(); //Then clean it note_time = (millis() - start_time) / 10; recorded_time[time_index] = note_time; time_index++; start_time = millis(); } /**End of Recording program**/ if (button == 0) { noTone(7); lcd.print("0 -> Pause.."); } if (button == 1) { tone(7, notes[0]); lcd.print("1 -> NOTE_C4"); } if (button == 2) { tone(7, notes[1]); lcd.print("2 -> NOTE_D4"); } if (button == 3) { tone(7, notes[2]); lcd.print("3 -> NOTE_E4"); } if (button == 4) { tone(7, notes[3]); lcd.print("4 -> NOTE_F4"); } if (button == 5) { tone(7, notes[4]); lcd.print("5 -> NOTE_G4"); } if (button == 6) { tone(7, notes[5]); lcd.print("6 -> NOTE_A4"); } if (button == 7) { tone(7, notes[6]); lcd.print("7 -> NOTE_B4"); } if (button == 8) { tone(7, notes[7]); lcd.print("8 -> NOTE_C5"); } } Video microcontroller-projects/arduino-based-bluetooth-controlled-sign-board-circuit-on-pcb

Bluetooth Controlled 8x8 LED Matrix Sign Board Display using Arduino

This enables the user to create custom designs with ease and display it on the LED display, sounds interesting right?!! So let’s get started...

Materials Required:

Arduino Pro mini MAX7219 HC-05 Bluetooth Module 8*8 LED Matrix Display 20k Resistor DC Barrel Jack

Circuit Diagram:

from it and fabricate it using EasyEDA. The Tx and Rx pins of the Bluetooth module is connected to D11 and D10 of the Arduino to enable serial connection. The digital pins D5 to D7 is connected to the MAX7219 IC to send and receive data through SPI communication. The ISET pin of MAX7219 is pulled high through a 20k Resistor. , you can get the design file of the PCB and use the same or build the circuit on a breadboard. However due to the its complexity it is recommended to either buy a 8x8 Display module or use the PCB is very useful display module and can be used in many cool projects: Controlling 8x8 LED Matrix with Raspberry Pi Scrolling Text Display on 8x8 LED Matrix using Arduino 8x8 LED Matrix using Arduino 8x8 LED Matrix Interfacing with AVR Microcontroller

Creating the Android Application using Processing:

software. It is an Open-Source development application and can be easily downloaded and put to use for developing interesting projects using Arduino or other Microcontrollers since it can develop android application and system applications. We have already done few projects using Processing and you can check them out by clicking on the links below. DIY FM Radio Using Processing Virtual Reality/ Gesture control using Arduino Private Chat room using Arduino. Arduino Radar System using Processing APP and Ultrasonic Sensor Real Time Face Detection and Tracking using Arduino DIY Speedometer using Arduino and Processing Ping Pong Game using Arduino Accelerometer Biped Robot Using Arduino DIY Arduino Thermal Imaging Camera Getting back to topic, it is impossible for me explain the complete code of the android application so you would have to learn processing by yourself and then look at the code to understand how it works. Hence for people who are willing to skip the process of learning Processing can download the android application from the below link Download Android Application[APK file] : The APK file can be directly installed on any android application and launched like any other application. But make sure your HC-05 Bluetooth device is named as “HC-05ᾬ because only then it will work.

Understanding the Processing Code:

The complete code of the Android application can be downloaded from the below link. Processing Code for Android Application loop to iterate from 1 to 64 using an array. This was each LED will have its own value of X position, Y position and colour and we can change them easily. //dipslay all leds for (int i=1; i<=64; i++) led_array[i].display(); //All leds displayed class Led{ float X_Pos; float Y_Pos; color colour; //CONSTRUTOR Led (float tempx, float tempy, color tempc){ X_Pos = tempx; Y_Pos = tempy; colour = tempc; } void display() { fill(colour); ellipse(X_Pos, Y_Pos, led_dia, led_dia); } } The LED’s are loaded on the screen on the same order of that of the display. Each LED is separated by a distance equal to the diameter of the LED, this way we can easily distinguish which LED is currently selected by the user. As shown in the below program we create an array in which each element holds the information of the X,Y position and colour of the LED. void load_leds(){ led_array = new Led[65]; int a=1; for (int j=0; j<=7; j++){ float y = height/6 + j*(led_dia*1.5); for (int i=0; i<=7; i++) { float x = (width/6) + i*(led_dia*1.5); //fill(255); //ellipse(x, y, led_dia, led_dia); led_array[a] = new Led(x,y,color(255,255,255)); a++; } } } Since now we can address to the location and colour of each LED easily we can do this by just comparing the X,Y values of where the user has pressed with the X,Y value of the LEDs. If the values merger into each other then we change the state of the LED and also send the number through Bluetooth as shown below. //check if mouse over led //If yes send the led number for (int i=1; i<=64; i++) { if( (mouseX < (led_array[i].X_Pos + led_dia/2)) && (mouseX > (led_array[i].X_Pos - led_dia/2)) && (mouseY < (led_array[i].Y_Pos + led_dia/2)) && (mouseY > (led_array[i].Y_Pos - led_dia/2))) {led_array[i] = new Led(led_array[i].X_Pos, led_array[i].Y_Pos, led_color); byte[] data = {byte(i)}; bt.broadcast(data); } } by turning off them all and also you can either make an LED turn red (ON) or white (OFF) so we also have an toggle button for that. The toggle button is displayed and waits for the input. If pressed the respective action will be taken. The code to do the same is shown below as function which is called inside the draw loop. void load_buttons() { rectMode(CENTER); textAlign(CENTER,CENTER); noStroke(); fill(#1BF2D4); rect(width/2-width/4,height/1.3,width/4,height/12); fill(0); text("Reset",width/2-width/4,height/1.3); //button 1 if (red==true) { fill(#080F89); rect(width/2+width/4,height/1.3,width/4,height/12);fill(255,0,0); text("RED",width/2+width/4,height/1.3);} //button 2 if (red==false) {fill(#080F89); rect(width/2+width/4,height/1.3,width/4,height/12);fill(255); text("WHITE",width/2+width/4,height/1.3);} //button 2 } void read_buttons() { if (mousePressed && click_flag==true) { color_val = get(mouseX, mouseY); click_flag=false; if (color_val==-14945580) { byte[] data = {0}; bt.broadcast(data); println("RESET");load_leds(); //load all led in position and colour } if (color_val==-16248951) { byte[] data = {100}; bt.broadcast(data); if (red == true) red = false; else if (red == false) red = true; println("TOGGLE"); } color_val=0; } }

Programming your Arduino:

is given at the bottom of this screen; you can use it directly and upload it on your board. The important lines in the program are explained below. using the code below if (BT.available()) { incoming = BT.read(); Serial.println(incoming); if (incoming==0) m.clear(); // Clears the display phone and weather to turn ON or OFF that LED. So we check if the value is equal to 100. If the value is 10, then it means the user has asked to toggle the colour of the LED. So we toggle the variable red to know whether the LED should be turned on or off. else if (incoming == 100)//Check if we should on or off the LED { if (red == true) red= false; else if (red == false) red= true; Serial.print("RED:"); Serial.println(red); } Based on the number from 1 to 64 we have to determine which LED the user has pressed. To toggle that LED we will need the value of Row and Column of that LED which is calculated and stored on variable X and Y respectively and shown on the code below. Finally based on the value of variable red we either turn on or turn off the LED as per the user request else if (incoming<=64) { //Calculate where to ON ro OFF the LED toggle=true; Y = incoming / 8; X = incoming - (Y * 8); if (incoming%8 == 0) {X = 8; Y -= 1;} Serial.println(X - 1); Serial.println(Y); if(red==true) m.setDot((X - 1), (Y), true); //LED ON else if (red == false) m.setDot((X - 1), (Y), false); //LED OFF }

Circuit and PCB Design using EasyEDA:

where they have a large stock of electronic components and users can order their required components along with the PCB order. While designing your circuits and PCBs, you can also make your circuit and PCB designs public so that other users can copy or edit them and can take benefit from your work, we have also made our whole Circuit and PCB layouts public for thiscircuit ,check the below link: (Top, Bottom, Topsilk, bottomsilk etc) of the PCB by selecting the layer form the ‘LayersᾠWindow. button in EasyEDA:

Calculating and Ordering Samples online:

page. and click onQuote NoworBuy Now button, then you can select the number of PCBs you want to order, how manycopper layers you need, the PCB thickness, copper weight, and even the PCB color, like the snapshot shown below: Afteryou have selected all of theoptions, click “Save to Cartᾠand then you will be taken to the page where you can upload your Gerber File which we have downloaded fromEasyEDA. Upload your Gerber file and click “Save to Cartᾮ Andfinallyclick on Checkout Securely to complete your order, then you will get your PCBs a few days later. They are fabricating the PCB atverylow rate which is $2. Theirbuild time is also veryless whichis 48 hours with DHL delivery of 3-5 days,basicallyyou will get your PCBs within a week of ordering. After few days of orderingPCB’sI got thePCB samples in nice packagingas shown in below pictures. And after getting these pieces I have soldered all the required components over the PCB. In my PCB, I made a blunt mistake by selecting the wrong footprint for the 8*8 Display module, hence I had to use an Perf board to mount the display as shown in the picture. But now the footprint is updates in the PCB and you can order the corrected PCB and mount the display module with ease.

Working of Bluetooth Sign board display:

is also provided above, use it and install the application on your preferred Android device. ᾠat the top of the screen, then you will be able to touch the LED on the screen and notice that the same LED is being turned on in the board as well. If you have any problem in getting it to work use the comments box below or write on our forums for more technical help. Hope you understood the tutorial and enjoyed building it. Code /* 8*8 LED Sign Board display B.Aswinth Raj www.circuitdigest.com library: GitHub | riyas-org/max7219 https://github.com/riyas-org/max7219 */ #include <MaxMatrix.h> #include <SoftwareSerial.h>// import the serial library SoftwareSerial BT(10, 11); // RX, TX int DIN = 7; // DIN pin of MAX7219 module int CLK = 6; // CLK pin of MAX7219 module int CS = 5; // CS pin of MAX7219 module int maxInUse = 1; boolean red = true; boolean toggle = true; MaxMatrix m(DIN, CS, CLK, maxInUse); void setup() { BT.begin(9600); //start the Bluetooth communication at 9600 baudrate Serial.begin(9600); // BT.println("Bluetooth working"); m.init(); // MAX7219 initialization m.setIntensity(8); // initial led matrix intensity, 0-15 m.clear(); // Clears the display } int incoming; int Y = 0; int X = 0; void loop() { if (BT.available()) { incoming = BT.read(); Serial.println(incoming); if (incoming==0) m.clear(); // Clears the display else if (incoming == 100)//Check if we should on or off the LED { if (red == true) red= false; else if (red == false) red= true; Serial.print("RED:"); Serial.println(red); } else if (incoming<=64) { //Calculate where to ON ro OFF the LED toggle=true; Y = incoming / 8; X = incoming - (Y * 8); if (incoming%8 == 0) {X = 8; Y -= 1;} Serial.println(X - 1); Serial.println(Y); if(red==true) m.setDot((X - 1), (Y), true); //LED ON else if (red == false) m.setDot((X - 1), (Y), false); //LED OFF } } } Video microcontroller-projects/arduino-rfid-door-lock-code

Arduino RFID Door Lock

Mechanism in some Hotels and other places, where you don’t need a key to unlock the room. You are given a card and you just need to put it in front of a RFID Reader box, and the lock gets unlocked with a Beep and a Blink of LED. This RFID Door Lock can be made easily at your home and you can install it in any door. These Door lock is just electrically operating door lock which gets open when you apply some voltage (typically 12v) to it. .-

Material Required:

Arduino UNO EM-18 Reader Module with Tags Relay 5v LED Buzzer Connecting wire Resistors

ArduinoRFID Door Lock Circuit Diagram

EM-18 RFID Reader:

operates at 125 KHz and it comes with an on-chip antenna and it can be powered with 5V power supply. It provides serial output along with weigand output. The range is around 8-12cm. serial communication parameters are 9600bps, 8 data bits, 1 stop bit. This wireless RF Identification is used in many systems like RFID Based Attendance System, Security systems, Voting machines, E-toll road pricing The output provided by EM-18 RFID reader is in 12 digit ASCII format. Out of 12 digits first 10 digits are card number and the last two digits are the XOR result of the card number. Last two digits are used for error checking. For example, card number is 0200107D0D62 read from the reader then the card number on the card will be as below. 02 ᾠPreamble 00107D0D = 1080589 in decimal. 62 is XOR value for (02 XOR 00 XOR 10 XOR 7D XOR 0D). Hence number on the card is 0001080589

Code and Explanation:

is given at the end of this project. 12 defines the no. of character or size of array. char tag[] ="180088F889E1"; char input[12]; int count = 0; boolean flag = 0; is used for the serial data transmission. Here the pin 2 is used for the relay operation, pin 3 is for the standby red LED and pin 4 is for the buzzer. void setup() { pinMode(2,OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); Serial.begin(9600); } , for the standby red LED the pin 3 remains HIGH until any task performed. array which we defined for saving RFID tag number. void loop( { digitalWrite(3,1); if(Serial.available()) { count = 0; while(Serial.available() && count < 12) { input[count] = Serial.read(); count++; delay(5); } variable to 0. if(count == 12) { count =0; flag = 1; while(count<12 && flag !=0) { if(tag[count]==input[count]) flag = 1; else flag= 0; } , so with the relay turned on, the Door Lock will be opened, and after 5 seconds it will again get locked. if(flag == 1) { digitalWrite(2,HIGH); digitalWrite(3,LOW); delay(5000); digitalWrite(2,LOW); } will be zero and the buzzer start beeping alerting that the RFID card is wrong. if(flag == 0) { for(int k =0; k<= 10; k++) { digitalWrite(4,HIGH); delay(300); digitalWrite(4,LOW); delay(300); } }

Working of ArduinoBased RFID Door Lock

The RFID tag consist of integrated circuit and an antenna, integrated circuit is for the storage of the data, and an antenna is for transmitting the data to the RFID Reader module. Whenever the RFID tag comes in the range of RFID reader, RF signal power the tag and then tag starts transmitting data serially. Data is further received by the RFID reader and the reader sends it to the Arduino board. And, after that as per the code in micro-controller different task performs. , so that whenever the Relay gets activated the lock will be opened. If we scan any other RFID card, the buzzer will start beeping as it’s the wrong RFID tag. Hence, for the door lock system we have used this concept that the door will only get opened by using the right RFID tag. The relay will itself get deactivated after 5 seconds, the door will be closed after 5 seconds, and you can change this delay in the code. is given below. Code char tag[] ="180088F889E1"; char input[12]; int count = 0; boolean flag = 0; void setup() { pinMode(2,OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); Serial.begin(9600); } void loop() { digitalWrite(3,1); if(Serial.available()) { count = 0; while(Serial.available() && count < 12) { input[count] = Serial.read(); count++; delay(5); } if(count == 12) { count =0; flag = 1; while(count<12 && flag !=0) { if(tag[count]==input[count]) flag = 1; else flag= 0; } if(flag == 1) { digitalWrite(2,HIGH); digitalWrite(3,LOW); delay(5000); digitalWrite(2,LOW); } if(flag == 0) { for(int k =0; k<= 10; k++) { digitalWrite(4,HIGH); } } } } } Video microcontroller-projects/auto-intensity-control-of-power-led-using-arduino

Auto Intensity Control of Power LED using Arduino

automatically. , the output signal via a PWM pin will be an analog signal and acquired as a digital signal from the Arduino. It uses the duty cycle of the digital wave to generate the sequential analog value for the signal. And, that signal is further used to control the brightness of the Power LED.

Material Required

Arduino UNO LDR Resistor (510, 100k ohm) Capacitor (0.1uF) Transistor 2N2222 1 watt Power LED Connecting wires Breadboard

Circuit Diagram

Code and Explanation

is given at the end. In the below code, we are defining the PWM pin and the variables to be used in the code. int pwmPin = 2; // assigns pin 12 to variable pwm int LDR = A0; // assigns analog input A0 to variable pot int c1 = 0; // declares variable c1 int c2 = 0; // declares variable c2 By doing some mathematic calculation we are generating the PWM signal. Here, we are controlling the intensity of light using PWM only if the analog value is less than 500, and if it is more than 500 we completely turn off the lights. int value = analogRead(LDR); Serial.println(value); c1= value; c2= 500-c1; // subtracts c2 from 1000 ans saves the result in c1 if (value < 500) { digitalWrite(pwmPin, HIGH); delayMicroseconds(c2); digitalWrite(pwmPin, LOW); delayMicroseconds(c1); } if (value > 500) { digitalWrite(2,LOW); } }

How itControls the Light Intensity Automatically:

using LDR and 100k resistor. The voltage divider output is feed to the analog pin of the Arduino. The analog Pin senses the voltage and gives some analog value to Arduino. The analog value changes according to the resistance of LDR. So, if is dark over the LDR, its resistance get increased and hence the voltage value (analog value) decreases. Hence, the analog value vary the PWM output or the duty cycle, and duty cycle is further proportional to intensity of light of power LED.So the light over the LDRwill automatically control the intensity of Power LED. Below is the flow diagram how this will work, upside arrow sign is indicating "increasing" and downside arrow sign is indicating "decreasing". ℍ Ifitsfull bright outside (when analog value increases more than 500) the powerLED turns off. . Code int pwmPin = 2; // assigns pin 12 to variable pwm int pot = A0; // assigns analog input A0 to variable pot int c1 = 0; // declares variable c1 int c2 = 0; // declares variable c2 void setup() // setup loop { pinMode(pwmPin, OUTPUT); pinMode(pot, INPUT); Serial.begin(9600); } void loop() { int value = analogRead(pot); Serial.println(value); c1= value; c2= 500-c1; // subtracts c2 from 1000 ans saves the result in c1 if (value < 500) { digitalWrite(pwmPin, HIGH); delayMicroseconds(c2); digitalWrite(pwmPin, LOW); delayMicroseconds(c1); } if (value > 500) { digitalWrite(2,LOW); } } Video microcontroller-projects/arduino-based-voice-controlled-leds

Voice Controlled LEDs using Arduino and Bluetooth

Controlling LEDs with voice command seems to be a difficult task, but it’s easy and you can quickly build it. We just need an Arduino UNO to serially communicate with HC-06 Bluetooth module and a smartphone to send voice command to Bluetooth module HC-06. For receiving voice command we are using “Arduino Bluetooth Voice Controllerᾠandroid app which you can download from play store (link is given below).

Material Required

Arduino UNO HC-06 Bluetooth Module LEDs (Red, and Green) Resistor 220 ohm (2 nos.) Arduino Bluetooth Voice Controller (Download from play store) Breadboard Connecting wires

HC-06 Bluetooth Module:

Bluetooth can operate in the following two modes: Command Mode Operating Mode is the one in which we will be able to send and receive data between the PIC Microcontroller and the Bluetooth module. Hence in this tutorial we will be toying only with the Operating Mode. The Command mode will be left to the default settings. The Device name will be HC-05 (I am using HC-06) and the password will be 0000 or 1234 and most importantly the default baud rate for all Bluetooth modules will be 9600. The module works on 5V supply and the signal pins operate on 3.3V, hence a 3.3V regulator is present in the module itself. Hence we need not worry about it. Out of the six pins only four will be used in the Operating mode. The pin connection table is shown below
S.NoPin on HC-05/HC-06Pin name on MCUPin number in PIC
1VccVdd31stpin
2VccGnd32ndpin
3TxRC6/Tx/CK25thpin
4RxRC7/Rx/DT26thpin
5StateNCNC
EN (Enable)NCNC
Check our other projects to learn more about Bluetooth module HC-05 with other microcontrollers: Bluetooth Controlled Toy Car using Arduino Bluetooth Controlled Home Automation System using 8051 Voice Controlled Lights using Raspberry Pi Smart Phone Controlled FM Radio using Arduino and Processing Interfacing Bluetooth Module HC-06 with PIC Microcontroller Bluetooth Controlled Servo Motor using Arduino

Circuit Diagram

is given below, while uploading the code in the Arduino UNO disconnect the Rx and Tx pins and connect again after the code is uploaded.

Code and Explanation

is given at the end. Here we are explaining few parts of code. Here, in the below code we are defining the pins for Rx and Tx. int TxD = 11; int RxD = 10; of the Arduino as output. pinMode(2, OUTPUT); pinMode(3, OUTPUT); then both the LEDs turns ON, like this we have coded other voice commands for turning on or off the individual LED. Check the complete working and demonstration video later in this article. if (bluetooth.available()) { value = bluetooth.readString(); if (value == "all LED turn on"){ digitalWrite(2, HIGH); digitalWrite(3, HIGH); } if (value == "all LED turn off"){ digitalWrite(2, LOW); digitalWrite(3, LOW); } if (value == "turn on Red LED"){ digitalWrite(2, HIGH); } if (value == "turn on green LED"){ digitalWrite(3, HIGH); } if (value == "turn off red LED"){ digitalWrite(2, LOW); } if (value == "turn off green LED"){ digitalWrite(3, LOW); } }

Working Procedure:

Connect all components as per the circuit diagram; disconnect Rx and Tx pins while uploading the code. ᾠwhich is free on play store. ᾠand select your Bluetooth module and check if it is connected or not. Then click on the mic icon to speak and send the voice command to the HC-06 module. After setting up all the things, you just have to send the voice command by using the app which is further sent to Bluetooth module HC-06 and the HC-06 serially communicate with the Arduino UNO and then the task is performed as per the command. The below shows the command and the action to be performed by the command:
1.all LED turn onBoth Red and Green LED turns ON
2.all LED turn offBoth Red and Green LED turns OFF
3.turn on Red LEDRed LED turns ON
4.turn on green LEDGreen LED turns ON
5.turn off red LEDRed LED turns OFF
6.turn off green LEDGreen LED turns OFF
Code #include <SoftwareSerial.h> String value; int TxD = 11; int RxD = 10; int servoposition; SoftwareSerial bluetooth(TxD, RxD); void setup() { pinMode(2, OUTPUT); pinMode(3, OUTPUT); Serial.begin(9600); // start serial communication at 9600bps bluetooth.begin(9600); } void loop() { Serial.println(value); if (bluetooth.available()) { value = bluetooth.readString(); if (value == "all LED turn on"){ digitalWrite(2, HIGH); digitalWrite(3, HIGH); } if (value == "all LED turn off"){ digitalWrite(2, LOW); digitalWrite(3, LOW); } if (value == "turn on Red LED"){ digitalWrite(2, HIGH); } if (value == "turn on green LED"){ digitalWrite(3, HIGH); } if (value == "turn off red LED"){ digitalWrite(2, LOW); } if (value == "turn off green LED"){ digitalWrite(3, LOW); } } } Video microcontroller-projects/arduino-color-mixing-lamp

Arduino Color Mixing Lamp using RGB LED and LDR

in the room. , and different colors will be produced. Below table shows the color combinations with respective change in duty cycles.

Materials required:

1 x Arduino UNO 1 x Breadboard 3 x 220-ohm resistors 3 x 1-kilohm resistors Jumper wires 3 x LDRs 3 x colored strips (red, green, blue) 1 x RGB LED

LDR:

) here in this circuit. LDRs are made from semiconductor materials to enable them to have their light-sensitive properties. These LDRs or PHOTO RESISTORS works on the principle of “Photo Conductivityᾮ Now what this principle says is, whenever light falls on the surface of the LDR (in this case) the conductance of the element increases or in other words, the resistance of the LDR falls when the light falls on the surface of the LDR. This property of the decrease in resistance for the LDR is achieved because it is a property of semiconductor material used on the surface. here.

RGB LED:

RGBLEDs, one is common cathode type (common negative) and other is common anode type (common positive) type.In CC (Common Cathode or Common Negative), there will be three positive terminals each terminal representing a color and one negative terminal representing all three colors. (Common Anode or Common Positive) type. In Common Anode type, if we want RED LED to be ON in, we need to ground the RED LED pin and power the common positive. The same goes for all theLEDs. Learn here to interface RGB LED with Arduino.

Circuit Diagram:

The complete circuit diagram of this projectis given above. The +5V and ground connection shown in the circuit diagram can be obtained from the 5V and ground pin of the Arduino. The Arduino itself can be powered from your laptop or through the DC jack using a 12V adapter or 9V battery. Here are some PWM examples with Arduino: Variable Power Supply By Arduino Uno DC Motor Control using Arduino Arduino Based Tone Generator

Programming Explanation:

First, we declare all the inputs and output pins as shown below. const byte red_sensor_pin = A0; const byte green_sensor_pin = A1; const byte blue_sensor_pin = A2; const byte green_led_pin = 9; const byte blue_led_pin = 10; const byte red_led_pin = 11; Declare initial values of sensors and leds as 0. unsigned int red_led_value = 0; unsigned int blue_led_value = 0; unsigned int green_led_value = 0; unsigned int red_sensor_value = 0; unsigned int blue_sensor_value = 0; unsigned int green_sensor_value = 0; void setup() { pinMode(red_led_pin,OUTPUT); pinMode(blue_led_pin,OUTPUT); pinMode(green_led_pin,OUTPUT); Serial.begin(9600); } function and store in three different variables. void loop() { red_sensor_value = analogRead(red_sensor_pin); delay(50); blue_sensor_value = analogRead(blue_sensor_pin); delay(50); green_sensor_value = analogRead(green_sensor_pin); Print those values onto the serial monitor for debugging purpose Serial.println("Raw Sensor Values:"); Serial.print("\t Red: "); Serial.print(red_sensor_value); Serial.print("\t Blue: "); Serial.print(blue_sensor_value); Serial.print("\t Green: "); Serial.println(green_sensor_value); simply we can use mapping function of Arduino to convert these values. red_led_value = red_sensor_value / 4; // define Red LED blue_led_value = blue_sensor_value / 4; // define Blue LED green_led_value = green_sensor_value / 4; // define Green Led Print mapped values to serial monitor Serial.println("Mapped Sensor Values:"); Serial.print("\t Red: "); Serial.print(red_led_value); Serial.print("\t Blue: "); Serial.print(blue_led_value); Serial.print("\t Green: "); Serial.println(green_led_value); to set output for RGB LED analogWrite(red_led_pin,red_led_value); // indicate red LED analogWrite(blue_led_pin,blue_led_value); // indicate blue LED analogWrite(green_led_pin,green_led_value); // indicate green

Working of Arduino Color Mixing Lamp:

As we are using three LDR’s so, when light incident on these sensors ,it’s resistance changes as a result voltages also changes at analog pins of Arduino which is acting as a input pins for sensors. When intensity of light changes on these sensors, it’s respective led in RGB will glow with amount of resistance changing and we have different color mixing in RGB led using PWM. Code const byte red_sensor_pin = A0; const byte green_sensor_pin = A1; const byte blue_sensor_pin = A2; const byte green_led_pin = 9; const byte blue_led_pin = 10; const byte red_led_pin = 11; unsigned int red_led_value = 0; unsigned int blue_led_value = 0; unsigned int green_led_value = 0; unsigned int red_sensor_value = 0; unsigned int blue_sensor_value = 0; unsigned int green_sensor_value = 0; void setup() { pinMode(red_led_pin,OUTPUT); pinMode(blue_led_pin,OUTPUT); pinMode(green_led_pin,OUTPUT); Serial.begin(9600); } void loop() { red_sensor_value = analogRead(red_sensor_pin); delay(50); blue_sensor_value = analogRead(blue_sensor_pin); delay(50); green_sensor_value = analogRead(green_sensor_pin); // print those values onto the serial monitor Serial.println("Raw Sensor Values:"); Serial.print("\t Red: "); Serial.print(red_sensor_value); Serial.print("\t Blue: "); Serial.print(blue_sensor_value); Serial.print("\t Green: "); Serial.println(green_sensor_value); // convert from 0-1023 to 0-255 red_led_value = red_sensor_value / 4; // define Red LED blue_led_value = blue_sensor_value / 4; // define Blue LED green_led_value = green_sensor_value / 4; // define Green LEd // print mapped values to serial monitor Serial.println("Mapped Sensor Values:"); Serial.print("\t Red: "); Serial.print(red_led_value); Serial.print("\t Blue: "); Serial.print(blue_led_value); Serial.print("\t Green: "); Serial.println(green_led_value); // use analogWrite() to set output for RGB LED analogWrite(red_led_pin,red_led_value); // indicate red LED analogWrite(blue_led_pin,blue_led_value); // indicate blue LED analogWrite(green_led_pin,green_led_value); // indicate green } Video microcontroller-projects/space-race-game-using-arduino-nokia-5110-display-and-joystick

Space Race Game using Arduino and Nokia 5110 Graphical Display

where you need to keep your ship safe from enemy ships using joystick.

Game Plan:

Within this space we have to tightly fit in the gaming area and the score board area which will display things like score and stuff. It is very important to know the pixel location of where you place stuff to keep track of the pixel locations and update them on the screen. Once the game screen appearance is decided we have to decide the characters in our game. For my game we have only two, the player character which is a space ship and an enemy character which should kind of look like an alien spaceship. The Nokia LCD can display bitmap images, so I decided to use that option to display my space ship and the enemies. So we will have a space ship that is racing through the aliens spaceships, this spaceship will have three lanes to changes in order to avoid a hit with the aliens. At all time the aliens can occupy only two track and the player should be able to drive through the free track. Once these ideas are concluded we can proceed with the Hardware and then the programming.

Circuit Diagram:

is very simple; we just have to interface the Nokia 5110 LCD module and the Joystick with Arduino. The complete circuit diagram is shown below The Nokia 5110 LCD works with the 3.3V and the Joystick module work son 5V, so make sure you connect the LCD with 3.3V only, because 5V may damage it permanently. The LCD communicates with Arduino through SPI protocol and the Joystick only read ADC to read the change in voltage. The connection set-up will look something like this below

Pre-requisites:

Before we dive into the programming part it is important for you people to be convenient with the Display module and the Joystick, so you can use the following tutorials to know more about them and then get back here to make sure things are working the way we need it to! Nokia 5110 LCD Interfacing with Arduino Joystick module interfacing with Arduino

Programming Arduino for Space Race Game:

can be found at the end of this page; you can use it directly on your Arduino IDE and upload it to you Board. But if you want to know what actually happens inside the code then read further. mentioned in the pre-requisites section if you are not sure how to add the library. #include <SPI.h> //SPI librarey for Communication #include <Adafruit_GFX.h> //Graphics lib for LCD #include <Adafruit_PCD8544.h> //Nokia 5110 LCD library by using software mentioned in the tutorial, you can select any image from the internet and use it by converting them to bitmap code. Make sure the image is simple enough to be displayed on our LCD screen, check the preview before actually trying on the LCD screen. In our program we have used two bitmap characters one is the space ship and the other is the enemy ship, the bitmap code for both is added in our code as shown below. //Bitmap Data for SpaceShip static const unsigned char PROGMEM ship[] = { B00000000,B00000000, B00000001,B00000000, B00000011,B10000000, B00000010,B10000000, B00000010,B11000000, B00000111,B11000000, B00001101,B11100000, B00011111,B11110000, B00111111,B11111000, B01111111,B11111100, B01111111,B11111100, B01111111,B11111100, B00011111,B11110000, B00000111,B11100000, B00000000,B00000000, }; //Bitmap Data for enemyship static const unsigned char PROGMEM enemy[] = { B00000101,B11000000, B00001011,B11100000, B00000011,B11100000, B00110011,B11111000, B01111111,B11111100, B10111111,B11111010, B01110111,B11011100, B01111110,B11111100, B00111111,B11111100, B11101111,B11101110, B11000001,B00000110, B10000001,B00000010, B10000000,B00000010, B00000000,B00000000, }; The display is communicated with using the SPI communication, if you have followed the circuit diagram above, the code to initialise the LCD will be as follows you need not change it. Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3); //Specifiy the pins to which the LCD is connected , each display will work the best in a different contrast level, so play with the value to check which suits the best for you. Finally we also clear the display screen to start fresh. void setup() { Serial.begin(9600); //Serial Monitor for Debugging display.begin(); //Begin the LCD communication display.setContrast(30); //Set the contrast of the display display.clearDisplay(); // clears the screen and start new } The game screen is nothing but which displays a basic skeleton for the game along with the score and speed level. We have used the line function to draw three lines as borders and to the right we display the text score and speed just like the old retro hand held gaming devices. void gamescreen() { //Draw the Border for Screen display.drawLine(0, 0, 0, 47, BLACK); display.drawLine(50, 0, 50, 47, BLACK); display.drawLine(0, 47, 50, 47, BLACK); //Enter Default Texts display.setTextSize(1); display.setTextColor(BLACK); display.setCursor(52,2); display.println("Speed"); display.setCursor(54,12); display.println(game_speed); display.setCursor(52,25); display.println("Score"); display.setCursor(54,35); display.println(score); } The input will be received from the Joystick module which is connected to pin A1. The analog value from the sensor will be 512 if it is not moved and will increase and decrease when moved along the X-axis. We use these values to determine if the user wants to move to left or to the right. You should read the Joystick interfacing with Arduino tutorial mentioned in the pre-requisites if you finding it hard to understand the below program. //Get input from user Joy_X = analogRead(A1); //Read the X vaue from Joystick if (Joy_X < 312 && POS!=1 && control==true) //If joy stick moves right { POS--; control = false;} //Decrement position of spaceship else if (Joy_X > 712 && POS!=3 && control==true) //If joy stick moves right { POS++; control = false;} //Increment position of spaceship else if (Joy_X >502 && Joy_X<522) //If joystick back to initial position control = true; //Preare it for next move //Input from user received We use the below function and pass the value of position as a parameter, then based on the position the space ship is placed in its respective track. void player_car(char pos) //Place the spaceship based on the user selected position { if (pos==1) display.drawBitmap(2, 32, ship, 15, 15, BLACK); if (pos==2) display.drawBitmap(18, 32, ship, 15, 15, BLACK); if (pos==3) display.drawBitmap(34, 32, ship, 15, 15, BLACK); } and when he is dead we have to create a new space ship. The below function does just the same. It creates a new position for two enemy ships and places them on the top of the screen. if (enemy_dead) //Check of enemy ships are dead { //If they are dead enemy_0_pos = POS; //create first enemy above the space ship enemy_1_pos = random(0,4); //create secound enemy at some other random place enemy_phase = 0; //Bring the enemy form the top enemy_dead = false; //Enemy is created so they are not dead anymore } so that it spears as if our player is racing upwards, to do that we just have to increment the phase (the place where the image is displayed) so that it comes down slowly. The same is done for both the enemy ships as shown below enemy_ship (enemy_0_pos,enemy_phase); enemy_phase++; //Place the first enemy on screen and drive him down enemy_ship (enemy_1_pos,enemy_phase); enemy_phase++; //Place the secound enemy on screen and drive him down is shown below, it is very similar to the player car function but here we have two parameters. One is for placing the enemy on a track and the other is for moving the enemy towards the bottom. void enemy_ship(int place, int phase) //Place the enemy_ship in the new place and phase { if (place==1) display.drawBitmap(2, phase, enemy, 15, 15, BLACK); if (place==2) display.drawBitmap(18, phase, enemy, 15, 15, BLACK); if (place==3) display.drawBitmap(34, phase, enemy, 15, 15, BLACK); } To check this we need to know the position of enemy ships and the player’s space ship. Since we know all that we just have to check if the space ship position is as same as the enemy ship. We check this only if the enemy ship has reached near the space ship. If the player has not avoided the enemy it means game over. if (enemy_phase>22 && ((enemy_0_pos == POS) || (enemy_1_pos == POS)) ) //If the Spaceship touches any one of the enemy game_over(); //Display game over To do this we just check if the enemy has reached to the bottom of the screen and if it does we kill it using the code below if (enemy_phase>40) //If thespace ship escapes the enemies {enemy_dead = true; score++;} //Increase the score and kill the enemies The speed is actually controlled by using the delay function this will control the refresh interval of the game thus making it fast or slow. void Level_Controller() //Increase the speed of game based on the score. { if (score>=0 && score<=10) //If score 0-10 { game_speed = 0; delay(80); //slow the game by 80ms } if (score>10 && score<=20) //If score 10-40 { game_speed = 1; delay(70); //slow the game by 70ms } if (score>20 && score<=30) //If score 20-40 { game_speed = 2; delay(60); //slow the game by 60ms } if (score>30 && score<=40) //If score 30-40 { game_speed = 3; delay(50); //slow the game by 50ms } }

Arduino Space Racer Game working:

After making sure the hardware and program is understood, just build the circuit and upload the code to the Arduino Board. You should notice the game getting started as shown below Hope you understood the project and enjoyed building it. If you have faced any problem in getting this to work, please feel free to post the problem on the comment section below or use the forums for technical help. Happy gaming!! Code /* SPACE RACE Game using Arduino and Nokia 5110 LCD * Coded by: Aswinth Raj * Dated: 10-5-2018 * Website: www.circuitdigest.com * Input -> Joystick (A0,A1) */ #include <SPI.h> //SPI librarey for Communication #include <Adafruit_GFX.h> //Graphics lib for LCD #include <Adafruit_PCD8544.h> //Nokia 5110 LCD librarey //More info on how to interface Nokia 5110 with LCD is given here: https://circuitdigest.com/microcontroller-projects/nokia5110-graphical-l... //Bitmap Data for SpaceShip static const unsigned char PROGMEM ship[] = { B00000000,B00000000, B00000001,B00000000, B00000011,B10000000, B00000010,B10000000, B00000010,B11000000, B00000111,B11000000, B00001101,B11100000, B00011111,B11110000, B00111111,B11111000, B01111111,B11111100, B01111111,B11111100, B01111111,B11111100, B00011111,B11110000, B00000111,B11100000, B00000000,B00000000, }; //Bitmap Data for enemyship static const unsigned char PROGMEM enemy[] = { B00000101,B11000000, B00001011,B11100000, B00000011,B11100000, B00110011,B11111000, B01111111,B11111100, B10111111,B11111010, B01110111,B11011100, B01111110,B11111100, B00111111,B11111100, B11101111,B11101110, B11000001,B00000110, B10000001,B00000010, B10000000,B00000010, B00000000,B00000000, }; Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3); //Specifiy the pins to which the LCD is connected int enemy_0_pos, enemy_1_pos, enemy_phase; int Joy_X; int game_speed = 0; int score = 0; char POS=2; boolean enemy_dead = true; boolean control = true; void setup() { Serial.begin(9600); //Serial Monitor for Debugging display.begin(); //Begin the LCD communication display.setContrast(30); //Set the contrast of the display display.clearDisplay(); // clears the screen and start new } void loop() { display.clearDisplay(); // clears the screen and start new gamescreen(); //Displays the box, score and speed values //Get input from user Joy_X = analogRead(A1); //Read the X vaue from Joystick if (Joy_X < 312 && POS!=1 && control==true) //If joy stick moves right { POS--; control = false;} //Decrement position of spaceship else if (Joy_X > 712 && POS!=3 && control==true) //If joy stick moves right { POS++; control = false;} //Increment position of spaceship else if (Joy_X >502 && Joy_X<522) //If joystick back to initial position control = true; //Preare it for next move //Input from user received player_car(POS); //Place the Space ship based on the input from user if (enemy_dead) //Check of enemy ships are dead { //If they are dead enemy_0_pos = POS; //create first enemy above the space ship enemy_1_pos = random(0,4); //create secound enemy at some other random place enemy_phase = 0; //Bring the enemy form the top enemy_dead = false; //Enemy is created so they are not dead anymore } enemy_ship (enemy_0_pos,enemy_phase); enemy_phase++; //Place the first enemy on screen and drive him down enemy_ship (enemy_1_pos,enemy_phase); enemy_phase++; //Place the secound enemy on screen and drive him down if (enemy_phase>22 && ((enemy_0_pos == POS) || (enemy_1_pos == POS)) ) //If the Spaceship touches any one of the enemy game_over(); //Display game over if (enemy_phase>40) //If thespace ship escapes the enemys {enemy_dead = true; score++;} //Increase the score and kill the enemys Level_Controller(); //BAsed on score increase the speed of game display.display(); //Update the display with all the changes made so far } void Level_Controller() //Increase the speed of game based on the score. { if (score>=0 && score<=10) //If score 0-10 { game_speed = 0; delay(80); //slow the game by 80ms } if (score>10 && score<=20) //If score 10-40 { game_speed = 1; delay(70); //slow the game by 70ms } if (score>20 && score<=30) //If score 20-40 { game_speed = 2; delay(60); //slow the game by 60ms } if (score>30 && score<=40) //If score 30-40 { game_speed = 3; delay(50); //slow the game by 50ms } } void enemy_ship(int place, int phase) //Place the enemy_ship in the new place and phase { if (place==1) display.drawBitmap(2, phase, enemy, 15, 15, BLACK); if (place==2) display.drawBitmap(18, phase, enemy, 15, 15, BLACK); if (place==3) display.drawBitmap(34, phase, enemy, 15, 15, BLACK); } void game_over() //Display game over screen { while(1) //The program will be stuck here for ever { delay(100); display.clearDisplay(); display.setCursor(20,2); display.println("GAME OVER"); display.display(); } } void gamescreen() { //Draw the Border for Screen display.drawLine(0, 0, 0, 47, BLACK); display.drawLine(50, 0, 50, 47, BLACK); display.drawLine(0, 47, 50, 47, BLACK); //Enter Default Texts display.setTextSize(1); display.setTextColor(BLACK); display.setCursor(52,2); display.println("Speed"); display.setCursor(54,12); display.println(game_speed); display.setCursor(52,25); display.println("Score"); display.setCursor(54,35); display.println(score); } void player_car(char pos) //Place the spaceship based on the user selected position { if (pos==1) display.drawBitmap(2, 32, ship, 15, 15, BLACK); if (pos==2) display.drawBitmap(18, 32, ship, 15, 15, BLACK); if (pos==3) display.drawBitmap(34, 32, ship, 15, 15, BLACK); } Video microcontroller-projects/arduino-tilt-sensor-interfacing

Interfacing Tilt Sensor with Arduino

is an electronic device that detects the orientation of an object and gives its output High or Low accordingly. Basically, it has a mercury ball inside it which moves and makes the circuit. So tilt sensor can turn on or off the circuit based on the orientation.

Material Required

Mercury Switch/ Tilt Sensor Arduino UNO Buzzer LED Resistor - 220 ohm Breadboard Connecting wires

Circuit Diagram

, it requires 5v dc input to operate. That 5v is supplied using Arduino UNO and the output of Tilt sensor is taken at PIN 4 of the Arduino. LED is connected with the PIN 2 of the Arduino UNO with 220-ohm resistor to limit the current to a safe value. And, the buzzer is directly connected to the PIN 3 of the Arduino UNO.

Tilt Sensor

This is a Mercury switch based tilt sensor module that gives high at its output pin when tilted. It requires a 5V of DC input. It’s a three-terminal device consist of input, ground, and output. It has a glass tube consist of two electrode and liquid mercury ball. The liquid mercury ball closes and opens the circuit when inclined in a particular direction. The working and internal structure of the module is given below:

Working of Tilt Sensor

Initially, when it is in NOT tilted position as shown in the image below, it gives LOW output because of the liquid mercury complete the circuit by connecting the two electrodes. When the output is LOW on-board LED remain ON. When it is inclined in a particular direction or angle, the liquid mercury breaks the contact between the metal electrodes and the circuit gets open. Hence, we get HIGH output in this condition and the onboard LED turns off.

Code and Working Explanation

for Interfacing Tilt Sensor with Arduino is given at the end. as Input and Output. Pin 2 and Pin 3 are set as output pins for LED and Buzzer respectively and Pin 4 is set as input to get input data from the Tilt sensor. void setup() { pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, INPUT); } Now, whenever the Tilt sensor is inclined beyond a particular angle the Output of tilt sensor gets HIGH. This output is read through Pin 4. Therefore, whenever the Pin 4 is HIGH, it turns ON the LED and Buzzer. void loop() { if (digitalRead(4) == 1) { digitalWrite(2, HIGH); digitalWrite(3, HIGH); delay(300); digitalWrite(2, LOW); digitalWrite(3, LOW); delay(300); } } This can be cool hobby projects like an antitheft box, alarm box or secret document box. Code void setup() { pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, INPUT); } void loop() { if (digitalRead(4) == 1) { digitalWrite(2, HIGH); digitalWrite(3, HIGH); delay(300); digitalWrite(2, LOW); digitalWrite(3, LOW); delay(300); } } Video microcontroller-projects/bluetooth-servo-motor-control-using-arduino

Bluetooth Controlled Servo Motor using Arduino

Material Required

Arduino UNO HC-05 or HC-06 Bluetooth module Servo Motor Roboremo App from Playstore Breadboard Connecting wire

HC-06 Bluetooth Module

Bluetooth can operate in the following two modes: Command Mode Operating Mode is the one in which we will be able to send and receive data between the PIC Microcontroller and the Bluetooth module. Hence in this tutorial we will be toying only with the Operating Mode. The Command mode will be left to the default settings. The Device name will be HC-05 (I am using HC-06) and the password will be 0000 or 1234 and most importantly the default baud rate for all Bluetooth modules will be 9600. The module works on 5V supply and the signal pins operate on 3.3V, hence a 3.3V regulator is present in the module itself. Hence we need not worry about it. Out of the six pins only four will be used in the Operating mode. The pin connection table is shown below
S.NoPin on HC-05/HC-06Pin name on MCUPin number in PIC
1VccVdd31stpin
2VccGnd32ndpin
3TxRC6/Tx/CK25thpin
4RxRC7/Rx/DT26thpin
5StateNCNC
6EN (Enable)NCNC
Check our other projects to learn more about Bluetooth module HC-05 with other microcontrollers: Bluetooth Controlled Toy Car using Arduino Bluetooth Controlled Home Automation System using 8051 Voice Controlled Lights using Raspberry Pi Smart Phone Controlled FM Radio using Arduino and Processing Interfacing Bluetooth Module HC-06 with PIC Microcontroller here.

Circuit Diagram

project is given below:

Configuring Roboremo App for Controlling Servo:

button you will see window shown in figure2 below: and then you will be able to connect your HC-06 bluetooth module with your android app ‘Roboremoᾮ ᾠfor creating the user interface according to your need. ᾠto get the button structure. (as shown in figure6) and type the value you want to send from that particular button. Like, we are sending ᾱᾠfor rotating the servo by pressing the ‘Startᾠbutton in Roboremo android application. You can check all the values, being sent on clicking on different buttons, in the table given later section. using Smartphone.

Code and Explanation

is given at the end. which will rotate the servo to desired angle. So here we are starting by defining the library for Servo motor and Software Serial library is used for defining the Rx and Tx pin. #include <SoftwareSerial.h> #include <Servo.h> Servo myServo; int TxD = 11; int RxD = 10; int servoposition; int servopos; int new1; SoftwareSerial bluetooth(TxD, RxD); pin of the Arduino and made the initial position of servo to 0 degree. Baud rate for serial and Bluetooth communication has also been set to 9600. void setup() { int pos=0; myServo.attach(9); myServo.write(0); Serial.begin(9600); // start serial communication at 9600bps bluetooth.begin(9600); } function, Arduino will be checking the incoming values all the time and rotate the servo according to received value from Smart phone. All the values will be received using Serial Communication. If the value is 0 the servo will rotate to 0 degree. Similarly if we send 45, 90, 135 and 180 from the Bluetooth application, the servo will rotate to 45, 90, 135 and 180 degree angle respectively. void loop() { if (bluetooth.available()){ String value = bluetooth.readString(); servoposition = value.toInt(); if (value.toInt() == 0){ Serial.println(servoposition); myServo.write(0); } if (value.toInt() == 45){ Serial.println(servoposition); myServo.write(45); } if (value.toInt() == 90){ Serial.println(servoposition); myServo.write(90); } if (value.toInt() == 135){ Serial.println(servoposition); myServo.write(135); } if (value.toInt() == 180){ Serial.println(servoposition); myServo.write(180); } loop and servo will be stopped. while(value.toInt()==1){ if (bluetooth.available()) { value = bluetooth.readString(); Serial.println(value); if (value.toInt()==2) {Serial.println("YYY"); break; } } servopos++; delay(30); Serial.println(servopos); myServo.write(servopos); if (servopos ==180 ) {servopos=0;break;} } } }

Working of Servo motor Control using Bluetooth:

“Roboremoᾮ In this application’s interface, we have created 5 buttons to control the Servo motor as explained earlier. The working of every button is given in the below table:
1.Start1This button is used to start rotating the servo from 0 to 180.
2.Stop2This button is used to stop the servo at any point.
3.00This button is used to rotate the servo to 0.
4.9090This button is used to rotate the servo to 90.
5.180180This button is used to rotate the servo to 180.
, the data will be sent through the smartphone’s Bluetooth to HC-06 Bluetooth module. From that HC-06 module data is received by the Arduino and Arduino rotates the Servo at the angle defined in the code for the particular button. We have also coded for angle 45 and 135, but due to the limitation of Roboremo app, you can only create 5 buttons, so we skipped two buttons. etc. Code #include <SoftwareSerial.h> #include <Servo.h> Servo myServo; int TxD = 11; int RxD = 10; int servoposition; int servopos; int new1; SoftwareSerial bluetooth(TxD, RxD); void setup() { int pos=0; myServo.attach(9); myServo.write(0); Serial.begin(9600); // start serial communication at 9600bps bluetooth.begin(9600); } void loop() { if (bluetooth.available()) { String value = bluetooth.readString(); servoposition = value.toInt(); if (value.toInt() == 0) { Serial.println(servoposition); myServo.write(0); } if (value.toInt() == 45) { Serial.println(servoposition); myServo.write(45); } if (value.toInt() == 90) { Serial.println(servoposition); myServo.write(90); } if (value.toInt() == 135) { Serial.println(servoposition); myServo.write(135); } if (value.toInt() == 180) { Serial.println(servoposition); myServo.write(180); } while(value.toInt()==1){ if (bluetooth.available()) { value = bluetooth.readString(); Serial.println(value); if (value.toInt()==2) {Serial.println("YYY"); break; } } servopos++; delay(30); Serial.println(servopos); myServo.write(servopos); if (servopos ==180 ) {servopos=0;break;} } } } Video microcontroller-projects/arduino-with-esp8266-reading-data-from-internet

Arduino with ESP8266 - Reading Data from Internet

This way we will be able to send or receive data between the Arduino and Internet. using an API with the ESP8266-01. Then send these values to an Arduino board and display them on the 16*2 LCD screen. Sounds cool right!! So let’s get started.

Materials Required:

Arduino Board (Any version) ESP8266-01 FTDI programmer board with 3.3V option 16x2 LCD Potentiometer Push button Connecting wires Breadboard

How things work?

and the code will be written to use an API to read a JSON file through http request. Then we will phrase this JSON file to extract only the required information from the complete JSON file. Once the information is phrased we will print it out using the serial communication. These serial lines will then be connected to the Arduino, so that the Arduino could read the information sent from ESP8266. Once the information is read and processed we will display it on the LCD screen. It’s okay, if you have not completely understood this, for we will be learning the same in the rest of this tutorial.

Programming the ESP8266-01:

This tutorial assumes that you have some experience with the ESP8266 module. If not then it is recommended to read through the following three tutorials to understand completely about it. Getting started with ESP8266-01 Programming ESP8266-01 using AT commands Programming the ESP8266-01 using Arduino IDE and Flashing its memory , since it will make the hardware much simple. The circuit diagram for connecting your ESP8266 with FTDI board is shown below. Make sure the following conditions are met 1. The ESP8266-01 is only 3.3V tolerant, do not use 5V. So set FTDI only in 3.3V mode. 2. GPIO_0 must be grounded for programming mode 3. The reset pin should be connected through a button to the ground pin. This button should be pressed just before uploading the code. Each time the button is pressed the blue LED on the ESP8266-01 module will go high to indicate that the module is reset. to learn it. At this point I assume that you have successfully uploaded the blink program. So you have to allow it to connect to your Wi-Fi by proving the SSID and Password in the below lines const char* ssid = "JIO-Fi"; //Enter your Wi-Fi SSID const char* password = "Pas123"; //Enter you Wi-Fi Password , if not it will wait there forever just by printing “Connecting..ᾠon the serial monitor. while (WiFi.status() != WL_CONNECTED) { //Wait till Wi-Fi is connected delay(1000); Serial.print("Connecting.."); //Print Connecting.. till connection is established } So if you are planning to use the same you can get into link and signup for the free API key or use any API of your choice. Once you are finalised with your API you will end up with a link something like this below : I have changed the API key of this link so this will not work. Keep your API key secured and do not share. using the following lines int httpCode = http.GET(); //pass a get request if (httpCode > 0) { //Check the returning code // payload = http.getString(); // Store the value on varibale Payload for debugging // Serial.println(payload); //Print the payload for debugging otherwise comment both lines I have commented these lines, as they are needed only for testing. Once you have ensured that ESP8266 is able to obtain the JSON data it’s time for phrasing the Data. As you can see this data is huge and most of the values are useless except for the ones that are required for us like date, time, temperature and humidity. This is possible because the values in JSON file are assigned as name value pairs. So this name is a string which will hold the value required for us. and pastes the JSON file that we loaded in our browser and press enter. When done mine looked something like this below Scroll down a bit to see the phrasing program that is created automatically , like I have done here /*Phrasing Data using the JSON librarey */ //Use https://arduinojson.org/assistant/ to get the phrasing values for your JSON string const size_t bufferSize = JSON_OBJECT_SIZE(0) + JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(2) + 2*JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(8) + JSON_OBJECT_SIZE(12) + JSON_OBJECT_SIZE(56) + 2160; DynamicJsonBuffer jsonBuffer(bufferSize); JsonObject& root = jsonBuffer.parseObject(http.getString()); /*End of Phrasing Data*/ //Address the value sin to desired variables JsonObject& current_observation = root["current_observation"]; //under current_observation JsonObject& current_observation_observation_location = current_observation["observation_location"]; //under observation_location const char* current_observation_station_id = current_observation["station_id"]; // "ICHENNAI1" //get the location detials const char* current_observation_local_time_rfc822 = current_observation["local_time_rfc822"]; //Local time //get the local time const char* current_observation_temperature_string = current_observation["temperature_string"]; // "90.7 F (32.6 C)" //get the temperature value const char* current_observation_relative_humidity = current_observation["relative_humidity"]; // "73%" //get the humidity value Since we are planning to display only those four data on our LCD screen. The following lines will do exactly the same //Print the variables through serial monitor Serial.print (current_observation_station_id); //send the location details to Arduino delay(100); //stability delay Serial.print (current_observation_local_time_rfc822); //send the local time details to Arduino delay(100); //stability delay Serial.print (current_observation_temperature_string); //send the temperature details to Arduino delay(100); //stability delay Serial.print (current_observation_relative_humidity); //send the humidity details to Arduino delay(100); //stability delay will append a /n and /r along with the data which is not needed for us. We have also added a delay of 10 seconds so that the ESP will send these values only at an interval of 10seconds to Arduino.

Connecting ESP8266-01 with Arduino:

is shown below Make sure the GPIO_0 pin is left free, power the module only with the 3.3V pin of Arduino and press the push button to put the ESP module in operating module. Now the program that we uploaded to ESP should have started working and the module should be send the data via serial pin to Arduino. These serial pins are connected to pin number 6 and 7 on the Arduino. So we can use the software serial option on Arduino to read these serial data from the pins.

Arduino Program and Working:

You can scroll down to view the program or read further if you want to understand the program. const int rs = 8, en = 9, d4 = 10, d5 = 11, d6 = 12, d7 = 13; //Pins to which LCD is connected LiquidCrystal lcd(rs, en, d4, d5, d6, d7); for those pins so that we can receive the serial data from them .I have names this as ESP_Serial, you can name them anything you wish SoftwareSerial ESP_Serial(6,7); //Tx,Rx for Serial monitor and also for the software serial. If you could recollect we made the ESP program to communicate at 9600 baud rate so we have to use the same baud rate for the software serial port. We also display a small intro message on the LCD for 2 seconds. void setup() { lcd.begin(16, 2); //We are using a 16*2 LCD display lcd.print(" Arduino & ESP"); //Display a intro message Serial.begin(115200); ESP_Serial.begin(9600); delay(2000); lcd.clear(); } The variable payload is of type String and it will hold the complete information sent form the ESP8266 module. while (ESP_Serial.available() > 0) { payload = ESP_Serial.readString(); function. You can print the payload on serial monitor to know the position of characters and use them to categorise the substrings as shown below local_date = payload.substring(14, 20); local_time = payload.substring(26, 31); temperature = payload.substring(48, 54); Humidity = payload.substring(55, 60); However printing them on the Serial monitor will help us o check if the substrings are split correctly. Next we just print them on the LCD display using the following lines lcd.clear(); lcd.setCursor(1, 0); lcd.print(local_date); lcd.setCursor(8, 0); lcd.print(local_time); lcd.setCursor(1, 1); lcd.print(temperature); lcd.setCursor(10, 1); lcd.print(Humidity); Upload the program to Arduino, and make sure the connections are as shown in the above circuit diagram. Adjust the contrast of the LCD display till you view the things clearly. You should see the Intro message on the LCD and then after few seconds the details such as date, time, temperature and Humidity should be displayed in the LCD screen as shown below. If you cannot see this it means the ESP is not in programming mode try pressing the Reset button also check the connections. Similar to this you can use any API to get any required data from the internet and feed it to the Arduino and the process your work with Arduino. There is tons of API available on the internet and with all those you can make a limitless number of projects. Hope you understood the project and enjoyed building it. If you had faced any problem, post them on the comment section below or on our forums. here. Code

Code for ESP8266:

#include <ESP8266WiFi.h> //ESP8266 Library #include <ESP8266HTTPClient.h> //ESP8266 Library #include <ArduinoJson.h> //For phrasing JSON file download from https://github.com/bblanchon/ArduinoJson const char* ssid = "Jio-Fi"; //Enter your Wi-Fi SSID const char* password = "pas123"; //Enter you Wi-Fi Password String payload; //To store the JSON object as string void setup () { Serial.begin(9600); //initialise serial monitor to send data to Arduino WiFi.begin(ssid, password); //connect to the network specified above while (WiFi.status() != WL_CONNECTED) { //Wait till Wi-Fi is connected delay(1000); Serial.print("Connecting.."); //Print Connecting.. till connection is established } } void loop() { if (WiFi.status() == WL_CONNECTED) { //If Wi-Fi connected successfully HTTPClient http; //start a HTTPClinet as http //####DO NOT USE THE SAME API as below http.begin("http://api.wunderground.com/api/abcd123qwert456/conditions/q/IN/Chennai...."); //Enter your API int httpCode = http.GET(); //pass a get request if (httpCode > 0) { //Check the returning code // payload = http.getString(); // Store the value on varibale Payload for debugging // Serial.println(payload); //Print the payload for debugging otherwise comment both lines /*Phrasing Data using the JSON librarey */ //Use https://arduinojson.org/assistant/ to get the phrasing values for your JSON string const size_t bufferSize = JSON_OBJECT_SIZE(0) + JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(2) + 2*JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(8) + JSON_OBJECT_SIZE(12) + JSON_OBJECT_SIZE(56) + 2160; DynamicJsonBuffer jsonBuffer(bufferSize); JsonObject& root = jsonBuffer.parseObject(http.getString()); /*End of Phrasing Data*/ //Address the value sin to desired variables JsonObject& current_observation = root["current_observation"]; //under current_observation JsonObject& current_observation_observation_location = current_observation["observation_location"]; //under observation_location const char* current_observation_station_id = current_observation["station_id"]; // "ICHENNAI1" //get the location detials const char* current_observation_local_time_rfc822 = current_observation["local_time_rfc822"]; //Local time //get the local time const char* current_observation_temperature_string = current_observation["temperature_string"]; // "90.7 F (32.6 C)" //get the temperature value const char* current_observation_relative_humidity = current_observation["relative_humidity"]; // "73%" //get the humidity value //Print the variables thorugh serial monitor Serial.print (current_observation_station_id); //send the location details to Arduino delay(100); //stability delay Serial.print (current_observation_local_time_rfc822); //send the local time details to Arduino delay(100); //stability delay Serial.print (current_observation_temperature_string); //send the temperature details to Arduino delay(100); //stability delay Serial.print (current_observation_relative_humidity); //send the humidity details to Arduino delay(100); //stability delay } http.end(); //Close http connection } delay(10000); //send values to Arduino every 30 sec. }

Code for Arduino:

#include <SoftwareSerial.h> #include <LiquidCrystal.h> //Header file for LCD from https://www.arduino.cc/en/Reference/LiquidCrystal const int rs = 8, en = 9, d4 = 10, d5 = 11, d6 = 12, d7 = 13; //Pins to which LCD is connected LiquidCrystal lcd(rs, en, d4, d5, d6, d7); String local_time; String local_date; String temperature; String Humidity; String payload; SoftwareSerial ESP_Serial(6, 7); //Tx,Rx void setup() { lcd.begin(16, 2); //We are using a 16*2 LCD display lcd.print(" Arduino & ESP"); //Display a intro message Serial.begin(115200); ESP_Serial.begin(9600); delay(2000); lcd.clear(); } void loop() { while (ESP_Serial.available() > 0) { payload = ESP_Serial.readString(); local_date = payload.substring(14, 20); local_time = payload.substring(26, 31); temperature = payload.substring(48, 54); Humidity = payload.substring(55, 60); delay(10); Serial.println(payload); Serial.println(local_time); Serial.println(local_date); Serial.println(temperature); Serial.println(Humidity); lcd.clear(); lcd.setCursor(1, 0); lcd.print(local_date); lcd.setCursor(8, 0); lcd.print(local_time); lcd.setCursor(1, 1); lcd.print(temperature); lcd.setCursor(10, 1); lcd.print(Humidity); } } Video microcontroller-projects/controlling-multiple-servo-motors-with-arduino

Controlling Multiple Servo Motors with Arduino

is Easy but what if we want to use more than one Servo Motors? Connecting multiple Servo Motors with Arduino seems to be easy and but if we connect all the Servos to Arduino supply pins then they won’t work correctly because of lack of enough current to drive all the motors. So you have to use separate power supply for the motors, either it be from some adapters (5v 2A) or from good quality 9v batteries.

Material Required

Arduino UNO Servo Motor Power Supply Breadboard Connecting Wires

Circuit Diagram

What is a Servo Motor?

Before going into detail, first we should know about Servo Motors. are available at different shapes and sizes. A servo motor will have mainly there wires, one is for positive voltage another is for ground and last one is for position setting. The RED wire is connected to power, Black wire is connected to ground and YELLOW wire is connected to signal. A servo motor is a combination of DC motor, position control system, gears.The position of the shaft of the DC motor is adjusted by the control electronics in the servo, based on the duty ratio of the PWM signal the SIGNAL pin. Simply speaking the control electronics adjust shaft position by controlling DC motor. This data regarding position of shaft is sent through the SIGNAL pin.The position data to the control should be sent in the form of PWM signal through the Signal pin of servo motor. The frequency of PWM (Pulse Width Modulated) signal can vary based on type of servo motor. The important thing here is the DUTY RATIO of the PWM signal. Based on this DUTY RATION the control electronics adjust the shaft. As shown in figure below, for the shaft to be moved to 9o clock the TURN ON RATION must be 1/18.ie. 1ms of ON time and 17ms of OFF time in a 18ms signal. For the shaft to be moved to 12o clock the ON time of signal must be 1.5ms and OFF time should be 16.5ms.This ratio is decoded by control system in servo and it adjusts the position based on it.This PWM in here is generated by using ARDUINO UNO. Also check our below Servo projects: Servo Motor Control using Arduino Servo Motor Control with Arduino Due Servo Motor Interfacing with 8051 Microcontroller Servo Motor Control using MATLAB Servo Motor Control by Flex Sensor Servo Position Control with Weight (Force Sensor)

Arduino Code Explanation

is given at the end. which will rotate the servo to desired angle. So here we are starting by defining the library for Servo motor. #include <Servo.h> as Servo1, Servo2, Servo3, and Servo4. Servo servo1; Servo servo2; Servo servo3; Servo servo4; As shown in the below code, Servo1 is connected to the 3rd pin of the Arduino. You can change the pins according to you but keep in mind that it should be a PWM pin. Using a Servo with digital pins of the Arduino is not reliable. void setup() { servo1.attach(3); servo2.attach(5); servo3.attach(6); servo4.attach(9); } degree and then 180 to 0 degree. The delay used in the below code is used to increase or decrease the speed of the servo as it effect the increasing or decreasing speed of variable ‘iᾮ void loop() { for (int i = 0; i < 180; i++) { servo1.write(i); servo2.write(i); servo3.write(i); servo4.write(i); delay(10); } for (i = 180; i > 0; i--) { servo1.write(i); servo2.write(i); servo3.write(i); servo4.write(i); delay(10); } }

Controlling Multiple Servos with Arduino- Working:

To use the external supply you just have to short the Arduino ground to external supply ground. Use the Arduino code given below to program your Arduino and connect all the Servo Motors as shown in the circuit diagram with proper power supply to Motors. Therefore, all servos will work together without any interrupt. Code #include <Servo.h> Servo servo1; Servo servo2; Servo servo3; Servo servo4; int i = 0; void setup() { servo1.attach(3); servo2.attach(5); servo3.attach(6); servo4.attach(9); } void loop() { for (i = 0; i < 180; i++) { servo1.write(i); servo2.write(i); servo3.write(i); servo4.write(i); delay(10); } for (i = 180; i > 0; i--) { servo1.write(i); servo2.write(i); servo3.write(i); servo4.write(i); delay(10); } } Video microcontroller-projects/interfacing-matlab-with-arduino

Interfacing Arduino with MATLAB - Blinking LED

In this project, we are going to learn, How to set up hardware support for Arduino in MATLAB software. How to control an Arduino using MATLAB code.

Setup Hardware Support Package for MATLAB:

Start MATLAB (latest Version preferred). It will start the Add-On explorer window. After logging in, Accept the license agreement and proceed to installation. .

Testing MATLAB:

After installing the support package for MATLAB, we need to check whether it is installed properly or not. 1. Open MATLAB. 2. Connect Arduino to PC. a = arduino() a = arduino( ‘COM5ᾠ, ‘unoᾠ) 5. After entering the above command, MATLAB will try to communicate with your Arduino, if successful, MATLAB will display the properties of Arduino board connected to PC. clear a It will remove the Arduino object from the workspace.

Controlling LEDs using MATLAB and Arduino:

In this example, we are going to blink a LED that is connected to Arduino using MATLAB. Arduino Resistors LEDs USB cable for Arduino Start MATLAB. Connect your Arduino to PC. Make the circuit as shown in the schematic. Open your .m code. Save it and Run. LED starts Blinking. After blinking 5 times, LED turns off. below. Code % create an arduino object a = arduino(); % start the loop to blink led for 5 seconds for i=1:5 writeDigitalPin(a, 'D10', 1); pause(0.5); writeDigitalPin(a, 'D10', 0); pause(0.5); end % end communication with arduino clear a Video microcontroller-projects/tvoc-co2-measurement-using-aduino-and-ccs811-air-quality-sensor

TVOC and CO2 Measurement using Arduino and CCS811 Air Quality Sensor

Also, you will learn to interface CSS811 with Arduino.

Material Required

Arduino UNO CCS811 Air Quality Sensor Potentiometer (10k) LCD 16*2 Breadboard Connecting Wires

Circuit Diagram

CCS811 Air Quality Sensor

unique micro-hotplate technology which empowers highly reliable solutions for Gas Sensors, with low power consumption.
1VinInput Supply (3.3v to 5v)
23V33.3V output Pin for external use
3GndGround
4SDAThis is I2C clock pin
5SCLI2C data pin
6WAKEWakeup Pin of sensor, should be connected to ground in order to communicate with the sensor
7RSTReset pin: When connected to ground the sensor reset itself
8INTThis is interrupt output pin, used to detect when a new reading is ready or when a reading gets too high or low
Smartphones Wearables Home and Building Automation Accessories

Code and Explanation

for TVOC and CO2 Measurement using CCS811 Air Quality Sensor is given at the end. #include <LiquidCrystal.h> #include "Adafruit_CCS811.h" Below we have defined Pins for connection of 16*2 LCD with Arduino. LiquidCrystal lcd(12, 13, 8, 9, 10, 11); /// REGISTER SELECT PIN,ENABLE PIN,D4 PIN,D5 PIN, D6 PIN, D7 PIN Adafruit_CCS811 ccs; Below we have set up LCD and CCS811 air quality sensor and calibrated it for the showing correct temperature, as shown in the below code, void setup() { lcd.begin(16, 2); ccs.begin(); //calibrate temperature sensor while(!ccs.available()); float temp = ccs.calculateTemperature(); ccs.setTempOffset(temp - 25.0); } (Function is already defined in library) to check if there is some data coming. As we get the data we are able to calculate the temperature and display it on 16*2 LCD. , asshown in the below code. Hence, we have received the value of air quality parameters using CCS811 air quality sensor. void loop() { if(ccs.available()){ float temp = ccs.calculateTemperature(); if(!ccs.readData()){ int co2 = ccs.geteCO2(); int tvoc = ccs.getTVOC(); lcd.setCursor(0, 0); lcd.print(String ("CO2:")+ String (co2)+String(" PPM")); lcd.setCursor(0, 1); lcd.print(String ("TVOC:")+ String (tvoc)+String(" PPB ")); lcd.print(String("T:"+String (int(temp)))+String("C")); delay(3000); lcd.clear(); } else{ lcd.print("ERROR"); while(1); } } } Complete Arduino code is given below. Code is simple, all the work is done by its library itself and we have used functions defined in the CCS library to get the values of CO2 and TOVC. Also, check: IOT based Air Pollution Monitoring System using Arduino Measuring PPM from MQ Gas Sensors using Arduino Code #include <LiquidCrystal.h> #include "Adafruit_CCS811.h" LiquidCrystal lcd(12, 13, 8, 9, 10, 11); /// REGISTER SELECT PIN,ENABLE PIN,D4 PIN,D5 PIN, D6 PIN, D7 PIN Adafruit_CCS811 ccs; void setup() { lcd.begin(16, 2); ccs.begin(); //calibrate temperature sensor while(!ccs.available()); float temp = ccs.calculateTemperature(); ccs.setTempOffset(temp - 25.0); } void loop() { if(ccs.available()){ float temp = ccs.calculateTemperature(); if(!ccs.readData()){ int co2 = ccs.geteCO2(); int tvoc = ccs.getTVOC(); lcd.setCursor(0, 0); lcd.print(String ("CO2:")+ String (co2)+String(" PPM")); lcd.setCursor(0, 1); lcd.print(String ("TVOC:")+ String (tvoc)+String(" PPB ")); lcd.print(String("T:"+String (int(temp)))+String("C")); delay(3000); lcd.clear(); } else{ lcd.print("ERROR"); while(1); } } } microcontroller-projects/arduino-countdown-timer

Arduino Countdown Timer

And when the timer reaches to Zero, alert sound will be produced with the help of Buzzer.

Material Required

Arduino UNO LCD 16*2 4*4 matrix keypad Buzzer Pushbutton Potentiometer (10k) Resistor (10k, 100 ohm) Connecting wires

Arduino Countdown Timer Circuit Diagram

Arduino Countdown Timer Code and Explanation

is given at the end of this Project. and the variables used in the code. #include <LiquidCrystal.h> #include <Keypad.h> long int set1; long int set2; long int set3; long int set4; long int j; int t1, t2, t3, t4, t5, t6; int r1, r2, r3; char key; String r[8]; String hours; String minutes; String seconds; for defining the matrix for keypad. const byte ROWS = 4; // Four rows const byte COLS = 4; // Three columns char keys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; byte rowPins[ROWS] = { 6, 7, 8, 9 };// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins byte colPins[COLS] = { 10, 11, 12, 13 };// Connect keypad COL0, COL1 and COL2 to t LiquidCrystal lcd(A0, A1, 5, 4, 3, 2); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7) The below code is used for making the keypad, Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); function code, after pressing the pushbutton we are able to enter the time for timer, then after entering the timer time duration, we have to Press D to begin the countdown. void setFeedingTime() { feed = true; int i=0; lcd.clear(); lcd.setCursor(0,0); lcd.print("Set feeding Time"); lcd.clear(); lcd.print("HH:MM:SS"); lcd.setCursor(0,1); while(1){ key = kpd.getKey(); char j; if(key!=NO_KEY){ lcd.setCursor(j,1); lcd.print(key); r[i] = key-48; i++; j++; if (j==2 || j == 5) { lcd.print(":"); j++; } delay(500); } if (key == 'D') {key=0; break; } } lcd.clear(); } , we have initialized the LCD and serial communication, and defined the pins as INPUT and OUTPUT in the below code. void setup() { lcd.begin(16,2); Serial.begin(9600); pinMode(A0, OUTPUT); pinMode(A1, OUTPUT); pinMode(A3, INPUT); pinMode(A4, OUTPUT); } is simple but the code is a little complex. The code is explained by the comments in the code. below. As the timer reaches to zero, the buzzer starts beeping and beeps for 100 times only (as per the code). To stop the buzzer, press and hold the pushbutton. You can use the Pushbutton anytime to stop the timer in between counting. Code // Arduino Countdown Timer Code #include <LiquidCrystal.h> #include <Keypad.h> const byte ROWS = 4; // Four rows const byte COLS = 4; // Three columns long int set1; long int set2; long int set3; long int set4; long int j; String hours; String minutes; String seconds; // Define the Keymap char keys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; byte rowPins[ROWS] = { 6, 7, 8, 9 };// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins byte colPins[COLS] = { 10, 11, 12, 13 };// Connect keypad COL0, COL1 and COL2 to t Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); LiquidCrystal lcd(A0, A1, 5, 4, 3, 2); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7) int t1, t2, t3, t4, t5, t6; int r1, r2, r3; boolean feed = true; // condition for alarm char key; String r[8]; void setFeedingTime() { feed = true; int i=0; lcd.clear(); lcd.setCursor(0,0); lcd.print("Set feeding Time"); lcd.clear(); lcd.print("HH:MM:SS"); lcd.setCursor(0,1); while(1){ key = kpd.getKey(); char j; if(key!=NO_KEY){ lcd.setCursor(j,1); lcd.print(key); r[i] = key-48; i++; j++; if (j==2 || j == 5) { lcd.print(":"); j++; } delay(500); } if (key == 'D') {key=0; break; } } lcd.clear(); } void setup() { lcd.begin(16,2); Serial.begin(9600); pinMode(A0, OUTPUT); pinMode(A1, OUTPUT); pinMode(A3, INPUT); pinMode(A4, OUTPUT); } void loop() { lcd.setCursor(0,0); lcd.print("Arduino Timer"); //Serial.println(A3); if (digitalRead(A3)==1) // { lcd.clear(); setFeedingTime(); for(int i = 0; i < 6; i++) // this for loop is used to get the value of the feeding time and print it serially { Serial.print(r[i]); Serial.println(); } hours = String (r[0]) + String (r[1]) ; //combining two separateint values of r[0] and r[1] into one string and save it to "hours" minutes = String (r[2]) + String (r[3]) ;//combining two separateint values of r[2] and r[3] into one string and save it to "minutes" seconds = String (r[4]) + String (r[5]) ;//combining two separateint values of r[4] and r[5] into one string and save it to "seconds" set1 = (hours.toInt()*3600); //converting hours into seconds set2 = (minutes.toInt() * 60);//converting minutes into seconds set3 = seconds.toInt(); set4 = (hours.toInt() * 3600)+ (minutes.toInt() * 60) + seconds.toInt(); //adding set1, set2 and set3together in set4 Serial.print("set4"); Serial.print(set4); Serial.println(); lcd.setCursor(0,0); lcd.print("Countdown begins"); delay(1000); lcd.clear(); for(long int j = set4; j >= 0; j--) // this for loopis used to decrease the total time in seconds { Serial.println(j); lcd.setCursor(0,0); lcd.print("HH:MM:SS"); long int HH = j / 3600; // converting the remaining time into remaining hours lcd.setCursor(0,1); Serial.println(HH); if (HH < 10) { lcd.print('0'); } lcd.print(HH); lcd.print(":"); long int MM = (j - (HH*3600))/60 ; //converting the remaining time into remaining minutes lcd.setCursor(3,1); Serial.println(MM); if (MM < 10) { lcd.print('0'); } lcd.print(MM); lcd.print(":"); long int SS = j - ((HH*3600)+(MM*60)); //converting the remaining time into remaining seconds lcd.setCursor(6,1); Serial.println(SS); if (SS < 10) { lcd.print('0'); } lcd.print(SS); delay(1000); if (digitalRead(A3)==1){break;} if (j == 0) { lcd.clear(); lcd.setCursor(0,0); lcd.print("Timer Stop"); lcd.setCursor(2,1); lcd.print("-Ring-Ring-"); for(int k =0; k<= 100; k++) //this for loop is used for the buzzer to beep 100 time as the timer reaches zero { digitalWrite(A4,HIGH); delay(300); digitalWrite(A4,LOW); delay(300); if (digitalRead(A3)==1){break;} } } } } } microcontroller-projects/graphical-lcd-interfacing-with-arduino

Interfacing Graphical LCD (ST7920) with Arduino

and many more. .

Material Required

Arduino UNO 128*64 Graphical LCD ST9720 Potentiometer-10k Connecting wires Breadboard

Circuit Diagram

128*64 Graphical LCD

GndGround terminal
VccInput supply voltage (2.7v to 5.5v)
VoLCD contrast
RSRegister Select RS = 0: Instruction Register RS = 1: Data Register
R/WRead/Write control
EEnable
DB0, DB1, DB2, DB3, DB4, DB5, DB6, DB7Data Pins (used in parallel 8/4bit communication mode)
PSBInterface selection: Low(0) for serial communication mode High (1) for 8/4-bit parallel bus mode.
NCNot connected
RSTReset Pin
VoutLCD voltage doubler output. VOUT ≐󞶖.
BLABacklight positive supply
BLKBacklight Negative supply
Industrial device Embedded Systems Security Medical Hand-held equipment

Converting Image into Hex Code:

To show any image on Graphical LCD, we need HEX code of that image, so here are few steps to convert Image into HEX code. Before that you have to make sure that the size of image should not exceed 128*64. Decrease the size of the normal image to 128*64 or less, which you can do using any image editing software like MS paint. As shown in the picture above, we are setting the width and height of the image to 128*64. ᾠformat. Select the format shown in the above image and save the file for further process. , which convert Bmp file to hex code. (X BitMap)format. After saving it open that file using Notepad and you will get the Hex code of the image. format: Select the format shown in the picture below and export the image file. and you will get the HEX code as shown in picture below.

Arduino Code and Working Explanation

Then you can include the library like below: #include "U8glib.h" ᾠis defining the connection of RS(Register Select) pin of graphical LCD with the 10th pin of the Arduino UNO. RS pin used as ‘chip selectᾠand ‘Register Selectᾠwhen used in Serial and Parallel mode respectively. So, we are using the serial mode and RS pin set to High (1) for chip enabled and Low (0) for chip disabled. U8GLIB_ST7920_128X64_4X u8g(10); we need to place the Hex code of the image in the below code. You can print any other image all you just need to do is paste the hex code of the image. const uint8_t rook_bitmap[] U8G_PROGMEM = { Paste the Hex code of image here }; at the end of this Article. Where, X and Y is the starting position of the image on LCD and we also need to write the size of the image which should not exceed 128*64 and in final argument we have called function in which we placed the HEX code of image. void picture(void) { u8g.drawXBMP( 0, 0, 128, 64, rook_bitmap); } ᾠis the content to be print. void draw(void) { u8g.setFont(u8g_font_unifont); u8g.drawStr( 07, 35, "CIRCUIT DIGEST"); } void next(void) { u8g.setFont(u8g_font_unifont); u8g.drawStr( 0, 15, "Interfacing"); u8g.drawStr( 0, 35, "Graphical LCD"); u8g.drawStr( 0, 55, "with Arduino"); } by just giving null value to the function. void clearLCD(){ u8g.firstPage(); do { } while( u8g.nextPage() ); } by using the code below void setup(void) { if ( u8g.getMode() == U8G_MODE_R3G3B2 ) { u8g.setColorIndex(255); // white } else if ( u8g.getMode() == U8G_MODE_GRAY2BIT ) { u8g.setColorIndex(3); // max intensity } else if ( u8g.getMode() == U8G_MODE_BW ) { u8g.setColorIndex(1); // pixel on } else if ( u8g.getMode() == U8G_MODE_HICOLOR ) { u8g.setHiColorByRGB(255,255,255); } } function which will stay on screen for 3 seconds. This will continue till the power supply is turned on. void loop(void) { u8g.firstPage(); do { draw(); } while( u8g.nextPage() ); delay(2000); clearLCD(); u8g.firstPage(); do { next(); } while( u8g.nextPage() ); delay(2000); clearLCD(); u8g.firstPage(); do { picture(); } while( u8g.nextPage() ); delay(3000); clearLCD(); delay(50); } given below. , Code #include "U8glib.h" U8GLIB_ST7920_128X64_4X u8g(10); const uint8_t rook_bitmap[] U8G_PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x63, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xff, 0xff, 0x03, 0x00, 0x78, 0x0e, 0xee, 0x3f, 0x7c, 0x70, 0xf0, 0xe0, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xfc, 0x02, 0x00, 0x78, 0x1e, 0xee, 0xff, 0x7c, 0xf8, 0xf0, 0xe1, 0x00, 0x00, 0x00, 0xfe, 0x07, 0xf0, 0x01, 0x00, 0x78, 0x3e, 0xee, 0xff, 0x7d, 0xf8, 0xf0, 0xe3, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xf0, 0x01, 0x00, 0x78, 0x7e, 0xce, 0xf3, 0x7f, 0xf8, 0xf0, 0xe7, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xf0, 0x01, 0x00, 0x78, 0xfe, 0xce, 0xe3, 0x7f, 0xfc, 0xf1, 0x67, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xf3, 0x00, 0x00, 0x78, 0xfe, 0xcf, 0xe3, 0x7b, 0xfc, 0xf1, 0x6f, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xfb, 0x00, 0x00, 0x78, 0xfe, 0xcf, 0xc3, 0x7b, 0xee, 0xf3, 0x7f, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0x00, 0x00, 0x78, 0xf6, 0xcf, 0xe3, 0x7b, 0xfe, 0x73, 0x7f, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x7f, 0x00, 0x00, 0x78, 0xe6, 0xcf, 0xe3, 0x7f, 0xff, 0x77, 0x7e, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x7f, 0x00, 0x00, 0x78, 0xc6, 0xcf, 0xe3, 0x7d, 0xff, 0x77, 0x7c, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x3f, 0x00, 0x00, 0x78, 0x86, 0xcf, 0xfb, 0xfd, 0xc7, 0x7f, 0x78, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x3f, 0x00, 0x00, 0x78, 0x0e, 0xef, 0xff, 0xfc, 0x83, 0x7f, 0x70, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x7f, 0x00, 0x00, 0x78, 0x0e, 0xee, 0x3f, 0xfc, 0x83, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0x01, 0x00, 0xf8, 0xe7, 0x1f, 0xfe, 0x79, 0xe0, 0x7c, 0xff, 0xfe, 0x01, 0x00, 0x00, 0xc0, 0xff, 0x03, 0x00, 0xf8, 0xef, 0x7f, 0xfe, 0x79, 0xf0, 0x7c, 0xff, 0xfe, 0x07, 0x00, 0x00, 0x80, 0xff, 0x07, 0x00, 0xf8, 0xef, 0x7f, 0xfe, 0x79, 0xf0, 0x7c, 0xff, 0xfe, 0x07, 0x00, 0x00, 0x00, 0xff, 0x07, 0x00, 0x78, 0xef, 0x7b, 0x1e, 0xf8, 0xf8, 0x7c, 0x0f, 0xbe, 0x07, 0x00, 0x00, 0x00, 0xfe, 0x0f, 0x00, 0x78, 0xef, 0x7b, 0x1e, 0xfc, 0xf8, 0x7d, 0x0f, 0xbe, 0x07, 0x00, 0x00, 0x00, 0xfc, 0x3f, 0x00, 0x78, 0xcf, 0x7b, 0xfe, 0xfc, 0xfd, 0x7d, 0xff, 0xfe, 0x07, 0x00, 0x00, 0x00, 0xf8, 0x3f, 0x00, 0xf8, 0xcf, 0x7f, 0xfe, 0xfc, 0xfd, 0x7d, 0xff, 0xfe, 0x07, 0x00, 0x00, 0x00, 0xf0, 0x7f, 0x00, 0xf8, 0xc3, 0x1f, 0xfe, 0xfc, 0xff, 0x7d, 0xff, 0xfe, 0x01, 0x00, 0x00, 0x00, 0xf0, 0xff, 0x00, 0x78, 0xe0, 0x3f, 0x1e, 0xfc, 0xef, 0x7d, 0x0f, 0xfe, 0x03, 0x00, 0x00, 0x00, 0xf0, 0xff, 0x01, 0x78, 0xe0, 0x7f, 0x1e, 0xdc, 0xef, 0x7d, 0x0f, 0xfe, 0x07, 0x00, 0x00, 0x00, 0xf0, 0xff, 0x03, 0x78, 0xe0, 0x7f, 0xfe, 0xdd, 0xe7, 0x7d, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0xe0, 0xff, 0x03, 0x78, 0xe0, 0xfb, 0xfe, 0x9d, 0xe7, 0x7d, 0xff, 0xbf, 0x0f, 0x00, 0x00, 0x00, 0xe0, 0xff, 0x07, 0x78, 0xe0, 0xfb, 0xfe, 0x9f, 0xe3, 0x7f, 0xff, 0xbf, 0x0f, 0x00, 0x00, 0x00, 0xe0, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x3f, 0x78, 0xf0, 0x0f, 0x1c, 0xe0, 0xcf, 0xc3, 0xfd, 0x03, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x3f, 0x78, 0xf0, 0x0f, 0x1e, 0xf8, 0xcf, 0xc3, 0xfd, 0x03, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x3f, 0x78, 0xf0, 0x0f, 0x3e, 0xfc, 0xce, 0xc3, 0xfd, 0x03, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x1f, 0x78, 0xf0, 0x00, 0x3f, 0x3c, 0xcc, 0xc3, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x0f, 0x78, 0xf0, 0x00, 0x7f, 0x3e, 0xc0, 0xc3, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0x03, 0x78, 0xf0, 0x8f, 0x7f, 0x1e, 0xc0, 0xc3, 0xf9, 0x03, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0x01, 0x78, 0xf0, 0x8f, 0x7b, 0x1e, 0xc0, 0xc3, 0xf9, 0x03, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0x00, 0x78, 0xf0, 0x8f, 0xff, 0x1e, 0xdf, 0xc3, 0xf9, 0x03, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x7f, 0x00, 0x78, 0xf0, 0xc0, 0xff, 0x3e, 0xde, 0xc3, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x3f, 0x00, 0x78, 0xf0, 0xc0, 0xff, 0x3f, 0xde, 0xc3, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x1f, 0x00, 0xf8, 0xfe, 0xfd, 0xf1, 0x7d, 0xde, 0xe7, 0x7d, 0x07, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x0f, 0x00, 0xf8, 0xff, 0xff, 0xf0, 0xff, 0x9f, 0xff, 0xfc, 0x07, 0x00, 0x00, 0x00, 0x00, 0xff, 0x07, 0x00, 0xf8, 0xff, 0xff, 0xe0, 0xf3, 0x1f, 0x7f, 0xfc, 0x07, 0x00, 0x00, 0x00, 0x80, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x9f, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; void draw(void) { //u8g.setFont(u8g_font_unifont); u8g.setFont(u8g_font_osb18); u8g.drawStr( 07, 27, "CIRCUIT"); u8g.drawStr( 12, 52, "DIGEST"); } void picture(void) { u8g.drawXBMP( 0, 0, 128, 64, rook_bitmap); } void next(void) { u8g.setFont(u8g_font_unifont); //u8g.setFont(u8g_font_osb18); u8g.drawStr( 07, 18, "Interfacing"); u8g.drawStr( 07, 38, "Graphical LCD"); u8g.drawStr( 07, 58, "with Arduino"); } void clearLCD(){ u8g.firstPage(); do { } while( u8g.nextPage() ); } void setup(void) { // assign default color value if ( u8g.getMode() == U8G_MODE_R3G3B2 ) { u8g.setColorIndex(255); // white } else if ( u8g.getMode() == U8G_MODE_GRAY2BIT ) { u8g.setColorIndex(3); // max intensity } else if ( u8g.getMode() == U8G_MODE_BW ) { u8g.setColorIndex(1); // pixel on } else if ( u8g.getMode() == U8G_MODE_HICOLOR ) { u8g.setHiColorByRGB(255,255,255); } } void loop(void) { // picture loop u8g.firstPage(); do { u8g.drawFrame(1,2,126,62); draw(); } while( u8g.nextPage() ); delay(2000); clearLCD(); u8g.firstPage(); do { u8g.drawFrame(1,2,126,62); next(); } while( u8g.nextPage() ); delay(2000); clearLCD(); u8g.firstPage(); do { picture(); } while( u8g.nextPage() ); delay(3000); clearLCD(); // rebuild the picture after some delay delay(50); } Video microcontroller-projects/automatic-pet-feeder-using-arduino

Automatic Pet Feeder using Arduino

(Real Time Clock) Module, which used to set time and date on which your pet should be given food. So, by setting up the time according to your pet’s eating schedule, the device drop or fill the food bowl automatically. is used to rotate the containers to provide the food and 4*4 matrix keypad to manually set up the time for feeding the Pet. You can set the rotation angle and container opening duration according to the quantity of food you want to serve to your pet. The quantity of food may also depend upon your pet whether it’s a dog, cat or bird.

Material Required

Arduino UNO 4*4 Matrix Keypad 16*2 LCD Push Button Servo Motor Resistor Connecting Wires Breadboard

Circuit Diagram

, for Getting Time and Date, we have used RTC (Real Time Clock) Module. We have used the 4*4 Matrix Keypad to set the Pet’s eating time manually with the help of 16x2 LCD. The Servo motor rotates the container and drop the food on the time set by the user. The LCD is used for displaying the Date and Time. Complete working can be found in the Video given at the end.

3D-Printed Pet Feeder Model

The material used for printing this model is PLA. It has four Parts as shown in the image below: Assemble the four parts and connect the Servo Motor as shown in the picture below:

DS3231 RTC Module

(Real Time Clock) module. It is used to maintain the date and time for most of the Electronics projects. This module has its own coin cell power supply using which it maintains the date and time even when the main power is removed or the MCU has gone through a hard reset. So once we set the date and time in this module it will keep track of it always. In our circuit, we are using DS3231 to feed the pet according to the time, set up by the Pet’s owner, like an alarm. As, clock reaches to the set time, it operates the servo motor to open the container gate and the food drops in the Pet’s food bowl.

Code and Explanation

is given at the end. Arduino have default libraries for using the Servo motor and LCD 16*2 with it. But for using DS3231 RTC Module and 4*4 Matrix Keypad with the Arduino, you have to download and install the libraries. The download link for both the libraries is given below: DS3231 RTC (Real Time Clock) Module Library 4*4 Matrix Keypad Library for 4*4 Matrix Keypad. #include <DS3231.h> #include <Servo.h> #include <LiquidCrystal.h> #include <Keypad.h> In the below code, we are defining the keymap for the 4*4 matrix keypad and assigning the Arduino pins for the Row and Columns of keypad. char keys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; byte rowPins[ROWS] = { 2, 3, 4, 5 }; byte colPins[COLS] = { 6, 7, 8, 9 }; Here, we are creating the keypad by using the command below in the code. Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); Assigning A4 and A5 Arduino pins to connect with SCL and SDA pins of DS3231. Also, assigning pins to the LCD and initializing the Servo motor. DS3231 rtc(A4, A5); Servo servo_test; //initialize a servo object for the connected servo LiquidCrystal lcd(A0, A1, A2, 11, 12, 13); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7) In the below code, we are declaring the t1 to t6, key, and array r[6], and the feed. int t1, t2, t3, t4, t5, t6; boolean feed = true; char key; int r[6]; pin of the Arduino. Defining A0, A1 and A2 as the Output Pin and initializing LCD and RTC module. void setup() { servo_test.attach(10); // attach the signal pin of servo to pin9 of arduino rtc.begin(); lcd.begin(16,2); servo_test.write(55); Serial.begin(9600); pinMode(A0, OUTPUT); pinMode(A1, OUTPUT); pinMode(A2, OUTPUT); } function. Then it compares the real time and the entered time by the user. If the condition is true which means the real time and the entered time is same, then the Servo motor rotates to and angle of 100 degree and after 0.4seconds of delay it comes back to its initial position. void loop() { lcd.setCursor(0,0); int buttonPress; buttonPress = digitalRead(A3); if (buttonPress==1) setFeedingTime(); lcd.print("Time: "); String t = ""; t = rtc.getTimeStr(); t1 = t.charAt(0)-48; t2 = t.charAt(1)-48; t3 = t.charAt(3)-48; t4 = t.charAt(4)-48; t5 = t.charAt(6)-48; t6 = t.charAt(7)-48; lcd.print(rtc.getTimeStr()); lcd.setCursor(0,1); lcd.print("Date: "); lcd.print(rtc.getDateStr()); if (t1==r[0] && t2==r[1] && t3==r[2] && t4==r[3]&& t5<1 && t6<3 && feed==true) { servo_test.write(100); //command to rotate the servo to the specified angle delay(400); servo_test.write(55); feed=false; } } function code, After pressing the pushbutton we are able to enter the pet feeding time, then we have to Press ‘Dᾠto save that time. When the saved time matches with real time then servo start rotating. void setFeedingTime() { feed = true; int i=0; lcd.clear(); lcd.setCursor(0,0); lcd.print("Set feeding Time"); lcd.clear(); lcd.print("HH:MM"); lcd.setCursor(0,1); while(1){ key = kpd.getKey(); char j; if(key!=NO_KEY){ lcd.setCursor(j,1); lcd.print(key); r[i] = key-48; i++; j++; if (j==2) { lcd.print(":"); j++; } delay(500); } if (key == 'D') {key=0; break; } } }

Working of the Automatic Pet Feeder

After uploading the code to the Arduino Uno, the time and date will be displayed on the 16*2 LCD. When you pressed the pushbutton it asks for Pet’s feeding time and you have to enter the time using the 4*4 matrix Keypad. Display will show the entered time and as you press ‘Dᾠit saves the time. When the real time and the Entered time matches, it rotates the servo motor from its initial position 55 to 100 and after a delay again return to its initial position. Therefore, Servo motor is connected to the Food Container gate, so as it moves, the gate will open and some amount of food falls in the bowl or plate. After a delay 0.4 seconds Servo motor rotates again and close the gate. The whole process completes within a few seconds. This is how your pet get the food automatically on the time you entered. Change time and degree according to food Code #include <DS3231.h> #include <Servo.h> #include <LiquidCrystal.h> #include <Keypad.h> const byte ROWS = 4; // Four rows const byte COLS = 4; // Three columns // Define the Keymap char keys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; // Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins. byte rowPins[ROWS] = { 2, 3, 4, 5 }; // Connect keypad COL0, COL1 and COL2 to these Arduino pins. byte colPins[COLS] = { 6, 7, 8, 9 }; // Create the Keypad Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); DS3231 rtc(A4, A5); Servo servo_test; //initialize a servo object for the connected servo LiquidCrystal lcd(A0, A1, A2, 11, 12, 13); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7) //int angle = 0; // int potentio = A0; // initialize the A0analog pin for potentiometer int t1, t2, t3, t4, t5, t6; boolean feed = true; // condition for alarm char key; int r[6]; void setup() { servo_test.attach(10); // attach the signal pin of servo to pin9 of arduino rtc.begin(); lcd.begin(16,2); servo_test.write(55); Serial.begin(9600); pinMode(A0, OUTPUT); pinMode(A1, OUTPUT); pinMode(A2, OUTPUT); } void loop() { lcd.setCursor(0,0); int buttonPress; buttonPress = digitalRead(A3); if (buttonPress==1) setFeedingTime(); //Serial.println(buttonPress); lcd.print("Time: "); String t = ""; t = rtc.getTimeStr(); t1 = t.charAt(0)-48; t2 = t.charAt(1)-48; t3 = t.charAt(3)-48; t4 = t.charAt(4)-48; t5 = t.charAt(6)-48; t6 = t.charAt(7)-48; lcd.print(rtc.getTimeStr()); lcd.setCursor(0,1); lcd.print("Date: "); lcd.print(rtc.getDateStr()); if (t1==r[0] && t2==r[1] && t3==r[2] && t4==r[3]&& t5<1 && t6<3 && feed==true) { servo_test.write(100); //command to rotate the servo to the specified angle delay(400); servo_test.write(55); feed=false; } } void setFeedingTime() { feed = true; int i=0; lcd.clear(); lcd.setCursor(0,0); lcd.print("Set feeding Time"); lcd.clear(); lcd.print("HH:MM"); lcd.setCursor(0,1); while(1){ key = kpd.getKey(); char j; if(key!=NO_KEY){ lcd.setCursor(j,1); lcd.print(key); r[i] = key-48; i++; j++; if (j==2) { lcd.print(":"); j++; } delay(500); } if (key == 'D') {key=0; break; } } } Video microcontroller-projects/arduino-inclinometer-using-mpu6050

DIY Arduino Inclinometer using MPU6050

The reason for using a remote display like a mobile phone is that we can monitor the values from MPU6050 without having to look at the hardware, this would come very handy when the MPU6050 is placed on a drone or some other inaccessible locations.

Materials Required:

Arduino Pro-mini (5V) MPU6050 Gyro Sensor HC-05 or HC-06 Bluetooth module FTDI board Breadboard Connecting wires Smart Phone

Circuit Diagram:

is shown below. It just has only three components and can be easily built over the breadboard. works with the help of Serial communication hence the Rx pin of Bluetooth is connected to pin D11 and the Tx pin of Bluetooth is connected to pin D10 of the Arduino. These pin D10 and D11 will be configured as Serial pin by programming the Arduino. The HC-05 module and the MSP6050 module operates on +5V and hence they are powered by the Vcc pin of the Arduino as shown above. I used some breadboard connecting wires and built the set-up over a small breadboard. Once the connections are done my board looks like this below.

Powering your setup:

You can either power your circuit through the FTDI programming board as I have did, or use a 9V battery or 12V adapter and connect it to the Raw pin of the Arduino pro mini. The Arduino Pro-mini has an in-built voltage regulator which would convert this external voltage regulated +5V.

Programming your Arduino:

for this project can be found at the bottom of this page. But to understand the project better I have broken the code to small chinks and explained them as steps below. For this project we are going to use the library developed by Korneliusz which can be downloaded from link below This will open the example program that uses the library that we just downloaded. So click on upload and wait for the program to be uploaded to your Arduino Pro mini. Once that is done open your serial monitor and set your baud rate to 115200 and check if you are getting the following. vary according to the way you tilt your sensor. If you get confused press the reset button on the Arduino and the values will be initialized to zero again, then tilt the sensor in one direction and check which values are varying. The below picture will help you to understand better. Now that we have understood the basics lets actually start programming the Arduino to read these values send it over to Arduino via Bluetooth. As always let's start by including all the libraries needed for this project #include <Wire.h> //Lib for IIC communication #include <MPU6050.h> //Lib for MPU6050 #include <SoftwareSerial.h>// import the serial library This is possible because of the Software Serial library in Arduino, the IO pins can be programmed to work as Serial pins. Here we are using the digital pins D10 and D11, where D10 id Rx and D11 is Tx. SoftwareSerial BT(10, 11); // RX, TX and set its threshold values using its respective functions as shown below. void setup() { Serial.begin(115200); BT.begin(9600); //start the Bluetooth communication at 9600 baudrate // Initialize MPU6050 while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G)) { Serial.println("Could not find a valid MPU6050 sensor, check wiring!"); delay(500); } mpu.calibrateGyro(); // Calibrate gyroscope during start mpu.setThreshold(3); //Controls the sensitivty } this function controls how much the value varies for the movement on sensor a too low value will increase the noise so be careful while fiddling around with this. calculate the value of pitch, roll and yaw, send it to the Bluetooth module. The following two lines will read the raw Gyro values and the temperature value Vector norm = mpu.readNormalizeGyro(); temp = mpu.readTemperature(); is nothing but the interval between successive readings. pitch = pitch + norm.YAxis * timeStep; roll = roll + norm.XAxis * timeStep; yaw = yaw + norm.ZAxis * timeStep; To understand time step better let’s take a look at the below line. This line is placed to read the values from MPU6050 exactly at an interval of 10mS or 0.01 Second. So we declare the value of timeStep as 0.01. And use the line below to hold the program if there if there is more time left. (millis() ᾠtimer()) gives the time taken for the program to execute so far. We just subtract it with 0.01 seconds and for the remaining time we just hold our program there using the delay function. delay((timeStep*1000) - (millis() - timer)); (8 bits) which allows us to send numbers only from 0 to 255. So we have to split our values and map it inside this range. This is done by the following lines if (roll>-100 && roll<100) x = map (roll, -100, 100, 0, 100); if (pitch>-100 && pitch<100) y = map (pitch, -100, 100, 100, 200); if (temp>0 && temp<50) t = 200 + int(temp); using the following lines. BT.write(x); BT.write(y); BT.write(t); If you have understood the complete program, scroll down to have a look at the program and upload it to the Arduino board.

Preparing the Android Application using Processing:

This is very much similar to Arduino and can be used to create system application, Android application, web designs and much more. We have already used processing to develop some of our other cool projects that are listed below Ping Pong Game using Arduino Smart Phone Controlled FM Radio using Processing. Arduino Radar System using Processing and Ultrasonic Sensor However, it is not possible to explain the complete code on how to create this application. So you have two ways to go over this. Either you can download the APK file from the below link and install the android application directly on your phone. Or scroll below to find the complete processing code and learn by yourself how it works (Right Click and Save Link As...) The application by default only connects to Bluetooth devices named as “HC-06ᾍ , I would like to explain few important points. The code requires Android mode of processing to be functioning which in turn needs the Android SDK files. The installation is a bit bulky but it is all worth it. Second, if you are trying to use this code given below then you will need the following ZIP file which contains the data file along with the code bt.connectToDeviceByName("HC-06"); based on the values form the Bluetooth module. You can check what happens inside each function by reading through the program. void draw() //The infinite loop { background(0); imageMode(CENTER); image(logo, width/2, height/1.04, width, height/12); load_images(); textfun(); getval(); } to normal values. if (info<100 && info>0) x = map(info, 0, 100, -(width/1.5)/3, +(width/1.5)/3);//x = info; else if (info<200 && info>100) y = map(info, 100, 200, -(width/4.5)/0.8, +(width/4.5)/0.8);//y = info; else if (info>200) temp = info -200; println(temp,x,y); There are much better ways to get data from a Bluetooth module to phone, but since this is just a hobby project we have ignored them, you can dig deep if interested.

Working of Arduino Inclinometer:

lines and check if the hardware is working as expected using the serial monitor. Anyway, that is completely optional. Once the code is uploaded, launch the Android application on your mobile phone. The application should automatically connect to your HC-06 module and it will display “Connect to: HC-06ᾠon the top of the application as shown below. below. So now you can place the breadboard anywhere and check if the surface is perfectly leveled. Hope you understood the project and learned something useful out of it. If you have any doubt please use the comment section below or the forums to get it resolved. Code /* (c) 2014 by Korneliusz Jarzebski */ #include <Wire.h> //Lib for IIC communication #include <MPU6050.h> //Lib for MPU6050 #include <SoftwareSerial.h>// import the serial library SoftwareSerial BT(10, 11); // RX, TX MPU6050 mpu; unsigned long timer = 0; unsigned long timer2 = 0; float timeStep = 0.01; float pitch = 0; float roll = 0; float yaw = 0; float temp =0; void setup() { Serial.begin(115200); BT.begin(9600); //start the Bluetooth communication at 9600 baudrate // Initialize MPU6050 while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G)) { Serial.println("Could not find a valid MPU6050 sensor, check wiring!"); delay(500); } mpu.calibrateGyro(); // Calibrate gyroscope during start mpu.setThreshold(3); //Controls the sensitivty } void loop() { timer = millis(); //Read Gyro and Temperature sensor values Vector norm = mpu.readNormalizeGyro(); temp = mpu.readTemperature(); // Calculate Pitch, Roll and Yaw pitch = pitch + norm.YAxis * timeStep; roll = roll + norm.XAxis * timeStep; yaw = yaw + norm.ZAxis * timeStep; // Print values Serial.print(" Pitch = "); Serial.print(pitch); Serial.print(" Roll = "); Serial.print(roll); Serial.print(" Yaw = "); Serial.print(yaw); Serial.print(" Temp = "); Serial.print(temp); Serial.println(" *C"); delay((timeStep*1000) - (millis() - timer)); //makes sure we read only at a an interval of 0.01 secounds if ((millis()-timer2) > 200) send_BT(); } void send_BT() { int t; int x; int y; if (roll>-100 && roll<100) x = map (roll, -100, 100, 0, 100); if (pitch>-100 && pitch<100) y = map (pitch, -100, 100, 100, 200); if (temp>0 && temp<50) t = 200 + int(temp); BT.write(x); BT.write(y); BT.write(t); timer2 = millis(); } Video microcontroller-projects/arduino-joystick-interfacing

Interfacing Joystick with Arduino

is the game controller. Yes, it’s exactly the same and can be used for gaming purpose. Apart from gaming, it has many other applications in DIY electronics. This joystick is nothing but a combination of two potentiometers for X and Y plane respectively. It reads the voltage through the potentiometer and gives analog value to the Arduino, and the analog value changes as we move the joystick shaft (which is simply the potentiometer pointer). which can be used for various other purposes or can be left idle. A single LED is also attached to the switch of the joystick, as the joystick button pressed that single LED will turn ON.

Material Required

Arduino UNO Joystick Module LEDs-5 Resistor: 100ohm-3 Connecting wires Breadboard

Circuit Diagram

Joystick Module

This joystick module has two axes as you can see. They are X-axis and Y-axis. Each axis of JOYSTICK is mounted to a potentiometer or pot. The midpoints of these pots are driven out as Rx and Ry. So Rx and Ry are variable points to these pots. When the Joystick is in standby, Rx and Ry act as a voltage divider. When the stick is moved, the voltage on each pin goes high or low depending on direction.

Code and Explanation

Complete Arduino Code is mentioned at the end. In below code, we have defined X and Y axis of the Joystick module for analog pin A0 and A1 respectively. #define joyX A0 #define joyY A1 will be 0 at the start. int button=2; int buttonState = 0; int buttonState1 = 0; In the below code, we are setting up the baud rate to 9600 and defined Pin 7 as an output pin and button pin as an input Pin. Initially, the button pin will remain high until the Switch will press. void setup() { pinMode(7,OUTPUT); pinMode(button,INPUT); digitalWrite(button, HIGH); Serial.begin(9600); } and printing serially. int xValue = analogRead(joyX); int yValue = analogRead(joyY); Serial.print(xValue); Serial.print("\t"); Serial.println(yValue); shaft, are defined in the code below. Here we are just taking analog values of voltage at pin A0 and A1 of Arduino. These analog values will change as we move the joystick and LED will glow according to movement of joystick. if (xValue>=0 && yValue<=10){ digitalWrite(10, HIGH); } else{digitalWrite(10, LOW);} if (xValue<=10 && yValue>=500){ digitalWrite(11, HIGH); } else{digitalWrite(11, LOW);} if (xValue>=1020 && yValue>=500){ digitalWrite(9, HIGH); } else{digitalWrite(9, LOW);} if (xValue>=500 && yValue>=1020){ digitalWrite(8, HIGH); } else{digitalWrite(8, LOW);} When we move the joystick shaft diagonally then one position come when the analog value of X and Y will be 1023 and 1023 respectively, both Pin 9 and Pin 8 LED will glow. Because it satisfies the condition of the LED. So, for removing that mismatch we have given a condition that if the value of (X, Y) is (1023, 1023) then both the LED remain in OFF condition if (xValue>=1020 && yValue>=1020) { digitalWrite(9, LOW); digitalWrite(8, LOW); } As we press the Joystick switch the LED will turn ON and latch until the button release. Its optional to use the Push button switch on Joystick module. if (buttonState == LOW) { Serial.println("Switch = High"); digitalWrite(7, HIGH); } else{digitalWrite(7, LOW);}

Controlling LEDs using Joystick with Arduino

After uploading the code to the Arduino and connect the components as per the circuit diagram, we can now control the LEDs with Joystick. We can turn ON the four LEDs in each direction as per the Joystick shaft movement. The Joystick is having two potentiometer inside it, one is for X-axis movement and another is for Y-axis movement. Each potentiometer is getting 5v from the Arduino. So as we move the joystick, the voltage value will change and the analog value at Analog pins A0 and A1 will also change. So, from the Arduino, we are reading the analog value for X and Y axis and turning ON the LEDs as per the axis movement of the Joystick. A push button switch on Joystick module is used to control the single LED in the circuit as shown in the video below. Code #define joyX A0 #define joyY A1 int button=2; int buttonState = 0; int buttonState1 = 0; void setup() { pinMode(7,OUTPUT); pinMode(button,INPUT); digitalWrite(button, HIGH); Serial.begin(9600); } void loop() { int xValue = analogRead(joyX); int yValue = analogRead(joyY); Serial.print(xValue); Serial.print("\t"); Serial.println(yValue); buttonState = digitalRead(button); Serial.println(buttonState); if (xValue>=0 && yValue<=10) { digitalWrite(10, HIGH); } else{digitalWrite(10, LOW);} if (xValue<=10 && yValue>=500) { digitalWrite(11, HIGH); } else{digitalWrite(11, LOW);} if (xValue>=1020 && yValue>=500) { digitalWrite(9, HIGH); } else{digitalWrite(9, LOW);} if (xValue>=500 && yValue>=1020) { digitalWrite(8, HIGH); } else{digitalWrite(8, LOW);} if (xValue>=1020 && yValue>=1020) { digitalWrite(9, LOW); digitalWrite(8, LOW); } if (buttonState == LOW) { Serial.println("Switch = High"); digitalWrite(7, HIGH); } else{digitalWrite(7, LOW);} buttonState1 = digitalRead(7); Serial.println(buttonState1); delay(50); } microcontroller-projects/arduino-light-sensor-using-ldr

Arduino Light Sensor Circuit using LDR

but this time we are using Arduino to get more control over light. as per light condition of the room or outside area.

Material Required

Arduino UNO LDR (Light Dependent Resistor) Resistor (100k-1;330ohm-1) LED - 1 Relay module - 5v Bulb/CFL Connecting wires Breadboard

Circuit Diagram

LDR

LDRs are made from semiconductor materials to enable them to have their light-sensitive properties. There are many types but one material is popular and it is cadmium sulfide (CdS). These LDRs or PHOTO RESISTORS works on the principle of “Photo Conductivityᾮ Now what this principle says is, whenever light falls on the surface of the LDR (in this case) the conductance of the element increases or in other words, the resistance of the LDR falls when the light falls on the surface of the LDR. This property of the decrease in resistance for the LDR is achieved because it is a property of semiconductor material used on the surface. , which use LDR to automate the lights according to requirement.

Working of LDR controlled LED using Arduino

using LDR and 100k resistor. The voltage divider output is feed to the analog pin of the Arduino. The analog Pin senses the voltage and gives some analog value to Arduino. The analog value changes according to the resistance of LDR. So, as the light falls on the LDR the resistance of it get decreased and hence the voltage value increase. As per the Arduino code, if the analog value falls below 700 we consider it as dark and the light turns ON. If the value comes above 700 we consider it as bright and the light turns OFF.

Code Explanation:

is given at the end of this project. Here, we are defining the Pins for Relay, LED and LDR. #define relay 10 int LED = 9; int LDR = A0; Setting up the LED and Relay as Output pin, and LDR as input pin. pinMode(LED, OUTPUT); pinMode(relay, OUTPUT); pinMode(LDR, INPUT); Reading the voltage analog value through the A0 pin of the Arduino. This analog Voltage will be increased or decreased according to the resistance of LDR. int LDRValue = analogRead(LDR); Giving the condition for dark and bright. If the value is less than 700 then it is dark and the LED or Light turns ON. If the value is greater than 700 then it is bright and the LED or light turns OFF. if (LDRValue <=700) { digitalWrite(LED, HIGH); digitalWrite(relay, HIGH); Serial.println("It's Dark Outside; Lights status: ON"); } else { digitalWrite(LED, LOW); digitalWrite(relay, LOW); Serial.println("It's Bright Outside; Lights status: OFF"); }

Controlling Relay using LDR with Arduino

Also, check: Automatic Street Light Controller Circuit Using Relay and LDR Automatic Staircase Light Raspberry Pi Emergency Light Code #define relay 10 int LED = 9; int LDR = A0; void setup() { Serial.begin(9600); pinMode(LED, OUTPUT); pinMode(relay, OUTPUT); pinMode(LDR, INPUT); } void loop() { int LDRValue = analogRead(LDR); Serial.print("sensor = "); Serial.print(LDRValue); if (LDRValue <=700) { digitalWrite(LED, HIGH); digitalWrite(relay, HIGH); Serial.println("It's Dark Outside; Lights status: ON"); } else { digitalWrite(LED, LOW); digitalWrite(relay, LOW); Serial.println("It's Bright Outside; Lights status: OFF"); } } Video microcontroller-projects/arduino-ohm-meter

Arduino Ohm Meter

Components Required:

Arduino Uno 16*2 LCD display Potentiometer (1 kilo Ohm) Resistors Breadboard Jumper wires

Circuit Diagram:

Arduino Uno:

Uno is a open source microcontroller board based on ATmega328p microcontroller. It has 14 digital pins (out of which 6 pins can be used as PWM outputs), 6 analog inputs, on board voltage regulators etc. Arduino Uno has 32KB of flash memory, 2KB of SRAM and 1KB of EEPROM. It operates at the clock frequency of 16MHz. Arduino Uno supports Serial , I2C , SPI communication for communicating with other devices. The table below shows the technical specification of Arduino Uno.
MicrocontrollerATmega328p
Operating voltage5V
Input Voltage7-12V (recommended)
Digital I/O pins14
Analog pins6
Flash memory32KB
SRAM2KB
EEPROM1KB
Clock speed16MHz

16x2 LCD:

is a widely used display for embedded applications. Here is the brief explanation about pins and working of 16*2 LCD display. There are two very important registers inside the LCD. They are data register and command register. Command register is used to send commands such as clear display, cursor at home etc., data register is used to send data which is to be displayed on 16*2 LCD. Below table shows the pin description of 16*2 lcd.
1Vss-Ground
2Vdd-+5V power supply
3Vee-Power supply to control contrast
4RSIRS=0 for command register , RS=1 for data register
5RWIR/W=0 for write , R/W=1 for read
6EI/OEnable
7D0I/O8-bit data bus(LSB)
8D1I/O8-bit data bus
9D2I/O8-bit data bus
10D3I/O8-bit data bus
11D4I/O8-bit data bus
12D5I/O8-bit data bus
13D6I/O8-bit data bus
14D7I/O8-bit data bus(MSB)
15A-+5V for backlight
16K-Ground

Concept of Resistance Color Code:

To identify the value of the resistance we can use the below formula. R= { (AB*10c)Ω ± T% } Where A = Value of the color in the first band. B = Value of the color in the second band. C = Value of the color in the third band. T = Value of the color in the fourth band. The table below shows the color code of resistors.
Black0-
Brown1± 1%
Red2± 2%
Orange3-
Yellow4-
Green5-
Blue6-
Violet7-
Gray8-
White9-
Gold-± 5%
Silver-± 10%
No band--± 20%
the value of resistance is calculated as, Brown = 1 Green = 5 Red = 2 Silver = ± 10% R = 15 * 10+2 R = 1500 Ω Fourth band indicates tolerance of ± 10% 10% of 1500 = 150 For + 10 percent, the value is 1500 + 150 = 1650Ω For - 10 percent, the value is 1500 -150 = 1350Ω Therefore the actual resistance value can be anywhere between 1350Ω to 1650Ω. where you only need enter the color of rings on resistor and you will get the resistance value.

Calculating Resistance using Arduino Ohm Meter:

shown below. From the voltage divider network of resistors R1 and R2, Vout = Vin * R2 / (R1 + R2 ) From the above equation, we can deduce the value of R2 as R2 = Vout * R1 / (Vin ᾠVout) Where R1 = known resistance R2 = Unknown resistance Vin = voltage produced at the 5V pin of Arduino Vout = voltage at R2 with respect to ground. the value of known resistance (R1) chosen is 3.3KΩ, but the users should replace it with the resistance value of resistor they have chosen. So if we get the value of voltage across unknown resistance (Vout), we can easily calculate the unknown resistance R2. Here we have read the voltage value Vout using the analog pin A0 (see the circuit diagram) and converted those digital values (0 -1023) into voltage as explained in Code below. If the value of the known Resistance is far greater or smaller than the unknown resistance the error will be more. So it is advised to keep the known resistance value nearer to the unknown resistance.

Code explanation:

for this project is given at the end of this project. The code is split into small meaningful chunks and explained below. pin of 16*2 lcd is connected to digital pin 3 of Arduino. Data pins (D4-D7) of 16*2 lcd is connected to digital pins 4,5,6,7 of Arduino. LiquidCrystal lcd(2,3,4,5,6,7); //rs,e,d4,d5,d6,d7 that are used in the program. Vin is the voltage provided by 5V pin of arduino. Vout is the voltage at resistor R2 with respect to ground. R1 is the value of known resistance. R2 is the value of unknown resistance. int Vin=5; //voltage at 5V pin of arduino float Vout=0; //voltage at A0 pin of arduino float R1=3300; //value of known resistance float R2=0; //value of unknown resistance The commands are given to 16*2 lcd display for different settings such as clear screen, display on cursor blinking etc. lcd.begin(16,2); (0 to 1023) and stored in a variable. a2d_data = analogRead(A0); for further calculations. buffer=a2d_data*Vin; Vout=(buffer)/1024.0; using the procedure as explained above. buffer=Vout/(Vin-Vout); R2=R1*buffer; display. lcd.setCursor(4,0); lcd.print("ohm meter"); lcd.setCursor(0,1); lcd.print("R (ohm) = "); lcd.print(R2); This is we can easily calculate the resistance of an unknown resistor using Arduino. Also check: Arduino Frequency Meter Arduino Capacitance Meter Code #include<LiquidCrystal.h> LiquidCrystal lcd(2,3,4,5,6,7); //rs,e,d4,d5,d6,d7 int Vin=5; //voltage at 5V pin of arduino float Vout=0; //voltage at A0 pin of arduino float R1=3300; //value of known resistance float R2=0; //value of unknown resistance int a2d_data=0; float buffer=0; void setup() { lcd.begin(16,2); } void loop() { a2d_data=analogRead(A0); if(a2d_data) { buffer=a2d_data*Vin; Vout=(buffer)/1024.0; buffer=Vout/(Vin-Vout); R2=R1*buffer; lcd.setCursor(4,0); lcd.print("ohm meter"); lcd.setCursor(0,1); lcd.print("R (ohm) = "); lcd.print(R2); delay(1000); } } Video microcontroller-projects/mpu6050-gyro-sensor-interfacing-with-arduino

MPU6050 Gyro Sensor Interfacing with Arduino

and showing the values over 16x2 LCD.

Required Components:

Arduino Uno MPU-6050 10K POT Jumper wire Breadboard USB cable Power supply

MPU6050 Gyro Sensor:

is an 8 pin 6 axis gyro and accelerometer in a single chip. This module works on I2C serial communication by default but it can be configured for SPI interface by configuring it register. For I2C this has SDA and SCL lines. Almost all the pins are multifunctioning but here we are proceeding only with I2C mode pins. this pin is used for powering theMPU6050 module with respect to ground this is ground pin SDA pin is used for data between controller and mpu6050 module SCL pin is used for clock input This is sensor I2C SDA Data line for configuring and reading from external sensors ((optional) not used in our case) This is sensor I2C SCL clock line for configuring and reading from external sensors ((optional) not used in our case) I2C Slave Address LSB(not applicable in our case) Interrupt pin for indication of data ready.

Description:

with Arduino. as shown in the images below:

Circuit Diagram and Explanation:

A 10k pot is used for controlling the brightness of the LCD. In connection with MPU6050, we have done 5 connections in which we have connected the 3.3v power supply and ground of MPU6050 to the 3.3v and ground of Arduino. SCL and SDA pins of MPU6050 is connected with Arduino’s A4 and A5 pin. And INT pin of MPU6050 is connected to interrupt 0 of Arduino (D2). LCD’s RS, RW and EN are directly connected to 8, gnd and 9 of Arduino. Data pin are directly connected to digital pin number 10, 11, 12 and 13.

Programming Explanation:

to interface it with Arduino. So first of all, we need to download the MPU6050 library from GitHub and install it in Arduino IDE. After it, we can find example codes in the example. The user may test that code by directly uploading them to Arduino and can see values over serial monitor. Or the user may use our code given at the end of the article to show values over LCD and serial monitor as well. In coding, we have included some required libraries like MPU6050 and LCD. #include<LiquidCrystal.h> LiquidCrystal lcd(8,9,10,11,12,13); #include <Wire.h> #include <MPU6050.h> and write welcome message over LCD void setup() { lcd.begin(16,2); lcd.createChar(0, degree); Serial.begin(9600); Serial.println("Initialize MPU6050"); while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G)) { lcd.clear(); lcd.print("Device not Found"); Serial.println("Could not find a valid MPU6050 sensor, check wiring!"); delay(500); } count=0; mpu.calibrateGyro(); mpu.setThreshold(3); In loop Function, we have called three functions in every 10seconds for displaying temperature, gyro, and accelerometer reading on LCD. These three functions are tempShow, gyroShow and accelShow, you can check those functions in the complete Arduino code given at the end of this article: void loop() { lcd.clear(); lcd.print("Temperature"); long st=millis(); Serial.println("Temperature"); while(millis()<st+period) { lcd.setCursor(0,1); tempShow(); } lcd.clear(); lcd.print("Gyro"); delay(2000); st=millis(); Serial.println("Gyro"); while(millis()<st+period) { lcd.setCursor(0,1); gyroShow(); } lcd.clear(); lcd.print("Accelerometer"); delay(2000); st=millis(); both are used to detect the position and orientation of any device. Gyro uses earth gravity to determine the x,y and z-axis positions and accelerometer detects based on the rate of the change of movement. We already used the accelerometer with Arduino in many of our projects like: Accelerometer Based Hand Gesture Controlled Robot Arduino Based Vehicle Accident Alert System Earthquake Detector Alarm using Arduino Code #include<LiquidCrystal.h> LiquidCrystal lcd(8,9,10,11,12,13); #include <Wire.h> #include <MPU6050.h> #define period 10000 MPU6050 mpu; int count=0; char okFlag=0; byte degree[8] = { 0b00000, 0b00110, 0b01111, 0b00110, 0b00000, 0b00000, 0b00000, 0b00000 }; void setup() { lcd.begin(16,2); lcd.createChar(0, degree); Serial.begin(9600); Serial.println("Initialize MPU6050"); while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G)) { lcd.clear(); lcd.print("Device not Found"); Serial.println("Could not find a valid MPU6050 sensor, check wiring!"); delay(500); } count=0; mpu.calibrateGyro(); mpu.setThreshold(3); lcd.clear(); lcd.print("MPU6050 Interface"); lcd.setCursor(0,1); lcd.print(" Circuit Digest"); delay(2000); lcd.clear(); } void loop() { lcd.clear(); lcd.print("Temperature"); long st=millis(); Serial.println("Temperature"); while(millis()<st+period) { lcd.setCursor(0,1); tempShow(); } lcd.clear(); lcd.print("Gyro"); delay(2000); st=millis(); Serial.println("Gyro"); while(millis()<st+period) { lcd.setCursor(0,1); gyroShow(); } lcd.clear(); lcd.print("Accelerometer"); delay(2000); st=millis(); Serial.println("Accelerometer"); while(millis()<st+period) { lcd.setCursor(0,1); accelShow(); } } void tempShow() { float temp = mpu.readTemperature(); Serial.print(" Temp = "); Serial.print(temp); Serial.println(" *C"); lcd.clear(); lcd.print("Temperature"); lcd.setCursor(0,1); lcd.print(temp); lcd.write((byte)0); lcd.print("C"); delay(400); } void gyroShow() { //lcd.setCursor(0,0); lcd.clear(); lcd.print(" X Y Z"); Vector rawGyro = mpu.readRawGyro(); Vector normGyro = mpu.readNormalizeGyro(); lcd.setCursor(0,1); lcd.print(normGyro.XAxis,1); lcd.setCursor(6,1); lcd.print(normGyro.YAxis,1); lcd.setCursor(12,1); lcd.print(normGyro.ZAxis,1); Serial.print(" Xnorm = "); Serial.print(normGyro.XAxis); Serial.print(" Ynorm = "); Serial.print(normGyro.YAxis); Serial.print(" Znorm = "); Serial.println(normGyro.ZAxis); delay(200); } void accelShow() { // lcd.setCursor(0,0); lcd.clear(); lcd.print(" X Y Z"); Vector rawAccel = mpu.readRawAccel(); Vector normAccel = mpu.readNormalizeAccel(); lcd.setCursor(0,1); lcd.print(normAccel.XAxis,1); lcd.setCursor(6,1); lcd.print(normAccel.YAxis,1); lcd.setCursor(12,1); lcd.print(normAccel.ZAxis,1); Serial.print(" Xnorm = "); Serial.print(normAccel.XAxis); Serial.print(" Ynorm = "); Serial.print(normAccel.YAxis); Serial.print(" Znorm = "); Serial.println(normAccel.ZAxis); delay(200); } Video microcontroller-projects/battery-voltage-indicator-using-arduino-and-led-bar-graph

Battery Voltage Indicator using Arduino and LED Bar Graph

according to the battery voltage. It also shows your battery voltage on the LCD connected to the Arduino.

Material Required

Arduino UNO 10 Segment LED Bar Graph LCD (16*2) Potentiometer-10k Resistor (100ohm-10;330ohm) Battery (to be tested) Connecting wires 12v adapter for Arduino

Circuit Diagram

LED Bar Graph

The LED bar graph comes in industrial standard size with a low power consumption. The bar is categorized for luminous intensity. The product itself remains within RoHS compliant version. It has a forward voltage of up to 2.6v. The power dissipation per segment is 65mW. The operating temperature of the LED bar graph is -40₠to 80₮ There are many application for the LED bar graph like Audio equipment, Instrument panels, and Digital readout display.

Arduino Program for Battery Voltage Monitoring:

is given at the end of this article. Here we have explained some important parts of the code. to be used with the Arduino. The analog input is taken from pin A4 for checking the battery voltage. We have set the value as Float to get the voltage up to two decimal. #include <LiquidCrystal.h> const int rs = 12, en = 13, d4 = A0, d5 = A1, d6 = A2, d7 = A3; LiquidCrystal lcd(rs, en, d0, d1, d2, d3); const int analogPin = A4; float analogValue; float input_voltage; The array is made for assigning the pins to the LED bar graph. int ledPins[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; // an array of pin numbers to which LEDs are attached int pinCount = 10; // the number of pins (i.e. the length of the array) Setting up LCD and the analog pins (A0, A1, A2, A3) as OUTPUT pins. void setup() { Serial.begin(9600); // opens serial port, sets data rate to 9600 bps lcd.begin(16, 2); //// set up the LCD's number of columns and rows: pinMode(A0,OUTPUT); pinMode(A1,OUTPUT); pinMode(A2,OUTPUT); pinMode(A3,OUTPUT); pinMode(A4,INPUT); lcd.print("Voltage Level"); } Here, we make a function for using the LED bar graph to use in a simple manner, you can even glow the LEDs by programming them one by one , but the code get lengthy. void LED_function(int stage) { for (int j=2; j<=11; j++) { digitalWrite(j,LOW); } for (int i=1, l=2; i<=stage; i++,l++) { digitalWrite(l,HIGH); //delay(30); } } In this part, we have read the voltage value using the analog pin. Then, we are converting the analog value into a digital voltage value by using the analog to digital conversion formula and displaying it further on LCD. // Conversion formula for voltage analogValue = analogRead (A4); Serial.println(analogValue); delay (1000); input_voltage = (analogValue * 5.0) / 1024.0; lcd.setCursor(0, 1); lcd.print("Voltage= "); lcd.print(input_voltage); Serial.println(input_voltage); delay(100); According to the value of the input voltage we have given some condition to control the LED bar graph LEDs. The condition you can check below in the code: if (input_voltage < 0.50 && input_voltage >= 0.00 ) { digitalWrite(2, HIGH); delay (30); digitalWrite(2, LOW); delay (30); // when the voltage is zero or low the 1st LED will indicate by blinking } else if (input_voltage < 1.00 && input_voltage >= 0.50) { LED_function(2); } else if (input_voltage < 1.50 && input_voltage >= 1.00) { LED_function(3); } else if (input_voltage < 2.00 && input_voltage >= 1.50) { LED_function(4); } else if (input_voltage < 2.50 && input_voltage >= 2.00) { LED_function(5); } else if (input_voltage < 3.00 && input_voltage >= 2.50) { LED_function(6); } else if (input_voltage < 3.50 && input_voltage >= 3.00) { LED_function(7); } else if (input_voltage < 4.00 && input_voltage >= 3.50) { LED_function(8); } else if (input_voltage < 4.50 && input_voltage >= 4.00) { LED_function(9); } else if (input_voltage < 5.00 && input_voltage >= 4.50) { LED_function(10); } }

Working of Battery Voltage Indicator

Then the digital value is used to glow the LED bar Graph accordingly. Code #include <LiquidCrystal.h> const int rs = 12, en = 13, d0 = A0, d1 = A1, d2 = A2, d3 = A3; LiquidCrystal lcd(rs, en, d0, d1, d2, d3); const int analogPin = A4; float analogValue; float input_voltage; int ledPins[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; // an array of pin numbers to which LEDs are attached int pinCount = 10; // the number of pins (i.e. the length of the array) void setup() { Serial.begin(9600); // opens serial port, sets data rate to 9600 bps lcd.begin(16, 2); //// set up the LCD's number of columns and rows: pinMode(A0,OUTPUT); pinMode(A1,OUTPUT); pinMode(A2,OUTPUT); pinMode(A3,OUTPUT); pinMode(A4,INPUT); lcd.print("Voltage Level"); } void LED_function(int stage) { for (int j=2; j<=11; j++) { digitalWrite(j,LOW); } for (int i=1, l=2; i<=stage; i++,l++) { digitalWrite(l,HIGH); //delay(30); } } void loop() { // Conversion formula for voltage analogValue = analogRead (A4); Serial.println(analogValue); delay (1000); input_voltage = (analogValue * 5.0) / 1024.0; lcd.setCursor(0, 1); lcd.print("Voltage= "); lcd.print(input_voltage); Serial.println(input_voltage); delay(100); if (input_voltage < 0.50 && input_voltage >= 0.00 ) { digitalWrite(2, HIGH); delay (30); digitalWrite(2, LOW); delay (30); } else if (input_voltage < 1.00 && input_voltage >= 0.50) { LED_function(2); } else if (input_voltage < 1.50 && input_voltage >= 1.00) { LED_function(3); } else if (input_voltage < 2.00 && input_voltage >= 1.50) { LED_function(4); } else if (input_voltage < 2.50 && input_voltage >= 2.00) { LED_function(5); } else if (input_voltage < 3.00 && input_voltage >= 2.50) { LED_function(6); } else if (input_voltage < 3.50 && input_voltage >= 3.00) { LED_function(7); } else if (input_voltage < 4.00 && input_voltage >= 3.50) { LED_function(8); } else if (input_voltage < 4.50 && input_voltage >= 4.00) { LED_function(9); } else if (input_voltage < 5.00 && input_voltage >= 4.50) { LED_function(10); } } Video microcontroller-projects/led-binary-clock-using-arduino

LED Binary Clock Circuit using Arduino

Here we have designed a printed circuit board (PCB) to implement this clock. To design PCB layout, we have used EasyEDA online PCB designing tool.

Components Required:

Arduino Nano DS1307 RTC 32.768Khz Crystal 3v coin cell Resistor 1k, 10k Power Supply LEDs

Circuit Diagram and Explanation:

here. 2 columns used for showing hour, next two columns for minutes and next to columns for seconds. We have used 6 PNP transistor to triggers LEDs in 6 columns. The user can power the whole circuit by 5v only, here we have used laptop USB for power supply. Rest of connections are shown in circuit diagram. at the end of this Article.

How to Calculate and Read Time in Binary Clock:

As we are familiar with binary numbers that are zero and one. So by using these, we can show time and we can convert that binary time into the decimal. By using the number 8 4 2 1 (written on the Right side of PCB), we can convert binary to decimal. Suppose we have a binary number like: When we convert binary to decimal we only add ones. Here from MSB (Most significant bit) side, we have 1 it means 8 and next is 0 means that is 0 and not to be included. Next is again 1 means 2 and the last is 0 so the last one will also not be included. So finally we have 8+0+2+0=10 Basically, we can take it like this: 8x1 + 4x0 + 2x1 + 1x0 = 10 Now we can understand time from the picture: At the right side of PCB, we can see row numbers 1, 2, 4, and 8, these numbers are used for converting binary number to decimal So first of all, see HH columns, there are two columns of time. In the first column of time, there is no led is glowing means: 2x0 + 1x0 = 0 In next column, we can see there is single led is glowing in the 1-row means. So according to 8 4 2 1 8x0 + 4x0 + 2x0 + 1x1 = 1 we can see there is single led is glowing in the 1-row means 4 2 1 4x0 + 2x0 + 1x1 = 1 In the second column of MM, we can see there is single led is glowing in the row number 8 means 8 4 2 1 8x1 + 4x0 + 2x0 + 1x0 =8 we can see there is single led is glowing in the row number 4 means 4 2 1 4x1 + 2x0 + 1x0 = 4 In the second column of SS, we can see there is two led is glowing in the row number 1 and row number 4 means 8 4 2 1 8x0 + 4x1 + 2x0 + 1x1 =5 HH MM SS 01 18 45 is given at the end of this Article.

Circuit and PCB Design using EasyEDA:

where they have a large stock of electronic components and users can order their required components along with the PCB order. ,check the below link: (Top, Bottom, Topsilk, bottomsilk etc) of the PCB by selecting the layer form the ‘LayersᾠWindow. button in EasyEDA:

Calculating and Ordering Samples online:

page. , then you can select the number of PCBs you want to order, how manycopper layers you need, the PCB thickness, copper weight, and even the PCB color, like the snapshot shown below: Afteryou have selected all of theoptions, click “Save to Cartᾠand then you will be taken to the page where you can upload your Gerber File which we have downloaded from EasyEDA. Upload your Gerber file and click “Save to Cartᾮ And finally click on Checkout Securely to complete your order, then you will get your PCBs a few days later. They are fabricating the PCB atvery low rate which is $2. Theirbuild time is also very less which is 48 hours with DHL delivery of 3-5 days, basically you will get your PCBs within a week of ordering. as shown in below pictures. Code #include <Wire.h> #include "RTClib.h" #include <TimerOne.h> RTC_DS1307 RTC; int temp,inc,hours1,minut,add=11; #define d1 12 #define d2 11 #define d3 10 #define d4 9 #define d5 8 #define d6 7 #define r1 6 #define r2 5 #define r3 4 #define r4 3 int HOUR,MINUT,SECOND; volatile int count=0; void Clear(int d) { digitalWrite(d1, HIGH); digitalWrite(d2, HIGH); digitalWrite(d3, HIGH); digitalWrite(d4, HIGH); digitalWrite(d5, HIGH); digitalWrite(d6, HIGH); } void callback() { digitalWrite(13, digitalRead(13) ^ 1); count++; if(count>=7) count=1; switch(count%7) { case 1: Clear(d1); temp=SECOND%10; show(temp); digitalWrite(d1, LOW); break; case 2: Clear(d2); temp=SECOND/10; show(temp); digitalWrite(d2, LOW); for(int i=0;i<10000;i++) { } break; case 3: Clear(d3); temp=MINUT%10; show(temp); digitalWrite(d3, LOW); for(int i=0;i<10000;i++) { } break; case 4: Clear(d4); temp=MINUT/10; show(temp); digitalWrite(d4, LOW); for(int i=0;i<10000;i++) { } break; case 5: Clear(d5); temp=HOUR%10; show(temp); digitalWrite(d5, LOW); for(int i=0;i<10000;i++) { } break; case 6: Clear(d6); temp=HOUR/10; show(temp); digitalWrite(d6, LOW); for(int i=0;i<10000;i++) { } break; } } void show(int d) { for(int i=0;i<1;i++) { digitalWrite(r4, !((temp>>0)&1)); digitalWrite(r3, !((temp>>1)&1)); digitalWrite(r2, !((temp>>2)&1)); digitalWrite(r1, !((temp>>3)&1)); // delay(1); for(int i=0;i<1000;i++); } } void setup() { Wire.begin(); Serial.begin(9600); RTC.begin(); digitalWrite(next, HIGH); digitalWrite(set_mad, HIGH); digitalWrite(INC, HIGH); pinMode(14, OUTPUT); for(int i=2;i<=12;i++) { pinMode(i, OUTPUT); digitalWrite(i, HIGH); } if(!RTC.isrunning()) { RTC.adjust(DateTime(__DATE__,__TIME__)); } Timer1.initialize(1000); Timer1.attachInterrupt(callback); } void loop() { int temp=0,val=1,temp4; DateTime now = RTC.now(); HOUR=now.hour(); MINUT=now.minute(); SECOND=now.second(); Serial.print(HOUR); Serial.print(":"); Serial.print(MINUT); Serial.print(":"); Serial.println(SECOND); delay(200); } Video microcontroller-projects/arduino-mq137-ammonia-sensor

Measuring PPM from MQ Gas Sensors using Arduino (MQ-137 Ammonia)

These sensors are commonly available and are also reliable for measuring different types of gas shown below

MQ-series Gas sensors

Carbon Dioxide (CO2) : MG-811 Carbon Monoxide (CO): MQ-9 Total Volatile Organic Compounds (TVOCs): CCS811 Equivalent Carbon Dioxide (eCO2): CCS811 Metal Oxide (MOX): CCS811 Ammonia: MQ-137 Air Quality: MQ-135 LPG, Alcohol, Smoke: MQ2 Most tutorials either deal with only the Analog values or introduce some constants which are not reliable for measuring all type of gas. So after fiddling around online for a long time I finally found how to use these MQ series gas sensors to measure ppm using Arduino. I am explaining things from the bottom without any libraries so that you can use this article for any Gas sensor available with you.

Preparing your Hardware:

The MQ gas sensors can either purchased as a module or just as a sensor alone. If your purpose is to measure only ppm then it’s best to buy the sensor alone since the module is good for only using the Digital pin. So if you have purchased the module already then you have to perform a small hack which will be discussed further. For now, let’s assume you have purchased the sensor. The pinout and connection of the sensor is shown below plays a very important role in making the sensor work. So make a note of which value you are using, a value of 47k is recommended. has already done this work for us and the circuit diagram of the MQ gas sensor board is given below. and was located here as shown in the picture below. So we have to manually solder the SMD resistor (1K) shown above and we have to use our own resistor across the Ground and Vout pin which will act as RL. The best value for RL will be 47K as suggested by datasheet hence we are going to use the same.

Approach to Measure PPM from MQ Gas Sensors:

is given here but make sure you find the correct datasheet for your sensor. Inside the datasheet we are need only one graph which will be plotted against (Rs/Ro) VS PPM this is the one that we need for our calculations. So gab it and keep it someplace handy. The one for my sensor is shown below. But, here I am interested only in the values of NH3. However you can use the same method to calculate ppm for any sensor you like. This graph is the only source for us to find the value of ppm and if we could somehow calculate the ration of Rs/Ro (X-axis) we can use this graph to find the value of ppm (Y-axis). To find the value of Rs/Ro we need to find the value of Rs and the value of Ro. Where Rs is the Sensor resistance at gas concentration and Ro is the sensor resistance in clean sir. Yess... this is the plan let’s see how we can get away with this....

Calculating the Value of Ro at Clean Air:

Note that in the graph value of Rs/Ro is constant for air (thick blue line) so we can use this to our advantage and say that when the sensor is working in fresh air the value of Rs/Ro will be 3.6 refer the picture below Rs/Ro = 3.6 , I would also like to credit them in helping me to sort this out. using this formula and finally displays it in the serial monitor. The program is well explained through the comment section so I am skipping its explanation here so as to keep this article short. /* * Program to measure the value of R0 for a know RL at fresh air condition * Program by: B.Aswinth Raj * Website: www.circuitdigest.com * Dated: 28-12-2017 */ //This program works best at a fresh air room with temperaure Temp: 20℃, Humidity: 65%, O2 concentration 21% and when the value of Rl is 47K #define RL 47 //The value of resistor RL is 47K void setup() //Runs only once { Serial.begin(9600); //Initialise serial COM for displaying the value } void loop() { float analog_value; float VRL; float Rs; float Ro; for(int test_cycle = 1 ; test_cycle <= 500 ; test_cycle++) //Read the analog output of the sensor for 200 times { analog_value = analog_value + analogRead(A0); //add the values for 200 } analog_value = analog_value/500.0; //Take average VRL = analog_value*(5.0/1023.0); //Convert analog value to voltage //RS = ((Vc/VRL)-1)*RL is the formulae we obtained from datasheet Rs = ((5.0/VRL)-1) * RL; //RS/RO is 3.6 as we obtained from graph of datasheet Ro = Rs/3.6; Serial.print("Ro at fresh air = "); Serial.println(Ro); //Display calculated Ro delay(1000); //delay of 1sec } The value of Ro will be varying, allow the sensor to pre-heat at least for 10 hours and then use the value of Ro. is 47k). Yours might slightly vary.

Measure the value of Rs:

Now that we know the value of Ro we can easily calculate the value of Rs using the above two formulae. Note that the value of Rs that was calculated previously is for fresh air condition and it will not be the same when ammonia is present in the air. Calculating the value of Rs is not a big issue which we can directly take care in the final program.

Relating Rs/Ro ratio with PPM:

Now that we know how to measure the value of Rs and Ro we would be able to find its ratio (Rs/Ro). Then we can use the chart (shown below) to relate to the corresponding value of PPM. Although the NH3 line (cyan colour) appears to be linear it is actually not linear. The appearance is because the scale is divided un-uniformly for appearance. So the relating between Rs/Ro and PPM is actually logarithmic which can be represented by the below equation. log(y) = m*log(x) + b where, y = ratio (Rs/Ro) x = PPM m = slope of the line b = intersection point To find the values of m and b we have to consider two points (x1,y1) and (x2,y2) on our gas line. Here we are working with ammonia so the two points I have considered is (40,1) and (100,0.8) as shown in the picture above (marked as red) with red marking. m = [log(y2) - log(y1)] / [log(x2) - log(x1)] m = log(0.8/1) / log(100/40) m = -0.243 Similarly for (b) let’s get the midpoint value (x,y) from the graph which is (70,0.75) as shown in picture above (marked in blue) b = log(y) - m*log(x) b = log(0.75) - (-0.243)*log(70) b = 0.323 That’s it now that we have calculated the value of m and b we can equate the value of (Rs/Ro) to PPM using the below formula PPM = 10 ^ {[log(ratio) - b] / m}

Program to calculate PPM using MQ sensor:

to calculate PPM using a MQ sensor is given below. Few important lines are explained below. of Load resistance (RL), Slope(m), Intercept(b) and the value of Resistance in fresh air (Ro). The procedure to obtain all these values have already be explained so let’s just feed them in now #define RL 47 //The value of resistor RL is 47K #define m -0.263 //Enter calculated Slope #define b 0.42 //Enter calculated intercept #define Ro 30 //Enter found Ro value (VRL) and convert it to Voltage (0V to 5V) since the analog read will only return values from 0 to 1024. VRL = analogRead(MQ_sensor)*(5.0/1023.0); //Measure the voltage drop and convert to 0-5V and the also the ratio (Rs/Ro) ratio = Rs/Ro; // find ratio Rs/Ro and display it on our serial monitor as shown below double ppm = pow(10, ((log10(ratio)-b)/m)); //use formula to calculate ppm Serial.print(ppm); //Display ppm

Showing PPM value on Hardware with Arduino and MQ-137:

for my set up is shown below. Connect your sensor and your LCD as shown in the Circuit diagram and upload the code given at the end of the program. You have to modify the Ro value as explained above. Also make the changes in parameter values if you are using any other resistor as RL other than 4.7K. Leave your set-up powered for at least 2 hours before you take any readings, (48 hrs is recommended for more accurate values). This time is called the heating time, during which the sensor warms up. After this, you should be able to see the value of PPM and the voltage displayed on your LCD screen as shown below. Now to ensure if the values are really related to the presence of ammonia, let’s place this set-up inside a closed container and send ammonia gas inside it to check if the values are increasing. I do not have a proper PPM meter with me calibrate it and it would great if someone with meter could test this set-up and let me know. to check how the readings varied based on the presence of ammonia. Hope you understood the concept and enjoyed learning it. If you have any doubts leave them in the comment section or for more detailed help use the forum here. Code /* * Program to measure gas in ppm using MQ sensor * Program by: B.Aswinth Raj * Website: www.circuitdigest.com * Dated: 28-12-2017 */ #define RL 47 //The value of resistor RL is 47K #define m -0.263 //Enter calculated Slope #define b 0.42 //Enter calculated intercept #define Ro 20 //Enter found Ro value #define MQ_sensor A0 //Sensor is connected to A4 const int rs = 8, en = 9, d4 = 10, d5 = 11, d6 = 12, d7 = 13; //Pins to which LCD is connected LiquidCrystal lcd(rs, en, d4, d5, d6, d7); void setup() { lcd.begin(16, 2); //We are using a 16*2 LCD display lcd.print("NH3 in PPM"); //Display a intro message lcd.setCursor(0, 1); // set the cursor to column 0, line 1 lcd.print("-CircuitDigest"); //Display a intro message delay(2000); //Wait for display to show info lcd.clear(); //Then clean it } void loop() { float VRL; //Voltage drop across the MQ sensor float Rs; //Sensor resistance at gas concentration float ratio; //Define variable for ratio VRL = analogRead(MQ_sensor)*(5.0/1023.0); //Measure the voltage drop and convert to 0-5V Rs = ((5.0*RL)/VRL)-RL; //Use formula to get Rs value ratio = Rs/Ro; // find ratio Rs/Ro float ppm = pow(10, ((log10(ratio)-b)/m)); //use formula to calculate ppm lcd.print("NH3 (ppm) = "); //Display a ammonia in ppm lcd.print(ppm); lcd.setCursor(0, 1); // set the cursor to column 0, line 1 lcd.print("Voltage = "); //Display a intro message lcd.print(VRL); delay(200); lcd.clear(); //Then clean it } Video microcontroller-projects/arduino-calculator-using-4x4-keypad

Arduino Calculator using 4x4 Keypad

(16×2 Dot-matrix). This calculator could perform simple operations like Addition, Subtraction, Multiplication and Division with whole numbers. But once you understand the concept you can implement even scientific functions with Arduino’s built in functions. and Keypad with Arduino and also how easy it is to program for them using the readily available libraries. You will also understand how to program your Arduino for accomplishing a particular task.

Materials Required:

Arduino Uno (Any version will work) 16×2 LCD Display 4×4 Keypad 9V Battery Breadboard and Connecting wires

Circuit Diagram:

is given above. The +5V and ground connection shown in the circuit diagram can be obtained from the 5V and ground pin of the Arduino. The Arduino itself can be powered from your laptop or through the DC jack using a 12V adapter or 9V battery.
Arduino Pin Name:Connected to:
D0pin of the keyboard
D1pin of the keyboard
D2pin of the keyboard
D3pin of the keyboard
D4pin of the keyboard
D5pin of the keyboard
D6pin of the keyboard
D7pin of the keyboard
D8Register select pin of LCD (pin 4)
D9Enable pin of LCD (pin 6)
D10Data pin 4 (pin 11)
D11Data pin 4 (pin 11)
D12Data pin 4 (pin 11)
D13Data pin 4 (pin 11)
+5VConnected to Vdd pin of LCD (pin 2)
GroundConnected to Vss,Vee and RW pin of LCD (pin 1,3 and 5)
Some Arduino boards might show an error while uploading program if there are anything connected to pin 0 and pin1, so if you experience any just remove the keypad while uploading the program. Once your connections are done your hardware will look something like this below

Arduino Calculator Program:

for this project is given at the end of this project. The code is split into small meaningful chunks and explained below. click on the link to download it from Github. You will get a ZIP file, then add this lib to Arduino by Sketch -> Include Library -> Add .ZIP file and point the location to this downloaded file. Once done we are all set for programming. Even though we have used a library for using a keypad we have to mention few details (shown below) about the keypad to the Arduino. The variable ROWS and COLS will tell how many rows and columns our keypad has and the keymap shows the order in which the keys are present on the keyboard. The keypad that i am using in this project looks like this below to the key map also represents the same. const byte ROWS = 4; // Four rows const byte COLS = 4; // Three columns // Define the Keymap char keys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; byte rowPins[ROWS] = { 0, 1, 2, 3 };// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins. byte colPins[COLS] = { 4, 5, 6, 7 }; // Connect keypad COL0, COL1 and COL2 to these Arduino pins. using those details using the line below Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); // Create the Keypad to. According to our circuit diagram the definitions would be like below const int rs = 8, en = 9, d4 = 10, d5 = 11, d6 = 12, d7 = 13; //Pins to which LCD is connected LiquidCrystal lcd(rs, en, d4, d5, d6, d7); //create the LCD , we just display the name of the project and then proceed to while loop where the main project lies. function as shown below key = kpd.getKey(); //storing pressed key value in a char if (key!=NO_KEY) DetectButtons(); if (result==true) CalculateResult(); DisplayResult(); What happens inside each function is explained using the comment lines, go through the complete code below, fiddle around with it to understand how it actually works. If you have any doubt on a specific line, feel free to use the comment section or the forums.

Simulation of Arduino Calculator:

We can also try simulating the project using Proteus software. Proteus does not have an Arduino component on it’s own, but can be easily downloaded and added to its library. Once you have the Arduino component on Proteus, just add Alphanumeric LCD and Keypad to make the connection as shown in the circuit diagram. below. The hex file given is not as same as the original of the program given below. It has been modified to since the keymap of the simulation keypad and the actual hardware keypad is different.

Working of Arduino Calculator:

Make the connections as per circuit diagram and upload the code below. If it shows error make sure you have added the library as per the instruction given above. You can also try the simulation to check if the problem is with your hardware. If everything is done as it’s supposed to be, then your hardware will look something like this below with the LCD displaying this Since the keypad used here does not have proper markings on it I have assumed the Alphabets to be operators as listed below
“AᾍAddition (+)
“BᾍSubtraction (-)
“CᾍMultiplication (*)
“DᾍDivision (/)
ᾪᾍClear (C)
ᾣᾍEquals (=)
You can use a marker to write over what each button actually represents. Code /* * Arduino Keypad calculator Program */ #include <LiquidCrystal.h> //Header file for LCD from https://www.arduino.cc/en/Reference/LiquidCrystal #include <Keypad.h> //Header file for Keypad from https://github.com/Chris--A/Keypad const byte ROWS = 4; // Four rows const byte COLS = 4; // Three columns // Define the Keymap char keys[ROWS][COLS] = { {'7','8','9','D'}, {'4','5','6','C'}, {'1','2','3','B'}, {'*','0','#','A'} }; byte rowPins[ROWS] = { 0, 1, 2, 3 };// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins. byte colPins[COLS] = { 4, 5, 6, 7 }; // Connect keypad COL0, COL1 and COL2 to these Arduino pins. Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); // Create the Keypad const int rs = 8, en = 9, d4 = 10, d5 = 11, d6 = 12, d7 = 13; //Pins to which LCD is connected LiquidCrystal lcd(rs, en, d4, d5, d6, d7); long Num1,Num2,Number; char key,action; boolean result = false; void setup() { lcd.begin(16, 2); //We are using a 16*2 LCD display lcd.print("DIY Calculator"); //Display a intro message lcd.setCursor(0, 1); // set the cursor to column 0, line 1 lcd.print("-CircuitDigest"); //Display a intro message delay(2000); //Wait for display to show info lcd.clear(); //Then clean it } void loop() { key = kpd.getKey(); //storing pressed key value in a char if (key!=NO_KEY) DetectButtons(); if (result==true) CalculateResult(); DisplayResult(); } void DetectButtons() { lcd.clear(); //Then clean it if (key=='*') //If cancel Button is pressed {Serial.println ("Button Cancel"); Number=Num1=Num2=0; result=false;} if (key == '1') //If Button 1 is pressed {Serial.println ("Button 1"); if (Number==0) Number=1; else Number = (Number*10) + 1; //Pressed twice } if (key == '4') //If Button 4 is pressed {Serial.println ("Button 4"); if (Number==0) Number=4; else Number = (Number*10) + 4; //Pressed twice } if (key == '7') //If Button 7 is pressed {Serial.println ("Button 7"); if (Number==0) Number=7; else Number = (Number*10) + 7; //Pressed twice } if (key == '0') {Serial.println ("Button 0"); //Button 0 is Pressed if (Number==0) Number=0; else Number = (Number*10) + 0; //Pressed twice } if (key == '2') //Button 2 is Pressed {Serial.println ("Button 2"); if (Number==0) Number=2; else Number = (Number*10) + 2; //Pressed twice } if (key == '5') {Serial.println ("Button 5"); if (Number==0) Number=5; else Number = (Number*10) + 5; //Pressed twice } if (key == '8') {Serial.println ("Button 8"); if (Number==0) Number=8; else Number = (Number*10) + 8; //Pressed twice } if (key == '#') {Serial.println ("Button Equal"); Num2=Number; result = true; } if (key == '3') {Serial.println ("Button 3"); if (Number==0) Number=3; else Number = (Number*10) + 3; //Pressed twice } if (key == '6') {Serial.println ("Button 6"); if (Number==0) Number=6; else Number = (Number*10) + 6; //Pressed twice } if (key == '9') {Serial.println ("Button 9"); if (Number==0) Number=9; else Number = (Number*10) + 9; //Pressed twice } if (key == 'A' || key == 'B' || key == 'C' || key == 'D') //Detecting Buttons on Column 4 { Num1 = Number; Number =0; if (key == 'A') {Serial.println ("Addition"); action = '+';} if (key == 'B') {Serial.println ("Subtraction"); action = '-'; } if (key == 'C') {Serial.println ("Multiplication"); action = '*';} if (key == 'D') {Serial.println ("Devesion"); action = '/';} delay(100); } } void CalculateResult() { if (action=='+') Number = Num1+Num2; if (action=='-') Number = Num1-Num2; if (action=='*') Number = Num1*Num2; if (action=='/') Number = Num1/Num2; } void DisplayResult() { lcd.setCursor(0, 0); // set the cursor to column 0, line 1 lcd.print(Num1); lcd.print(action); lcd.print(Num2); if (result==true) {lcd.print(" ="); lcd.print(Number);} //Display the result lcd.setCursor(0, 1); // set the cursor to column 0, line 1 lcd.print(Number); //Display the result } Video microcontroller-projects/arduino-smart-blind-stick

Smart Blind Stick using Arduino

that could perform more than just a stick for visually impaired persons. All the feedbacks will be given to the blind man through a Buzzer. Of course you can use a vibrator motor in place of Buzzer and advance a lot more using your creativity.

Materials Required:

Arduino Nano (Any version will work) Ultrasonic Sensor HC-SR04 LDR Buzzer and LED 7805 433MHz RF transmitter and receiver Resistors Capacitors Push button Perf board Soldering Kit 9V batteries

Blind Stick Circuit Diagram:

is shown below: which is connected to pin 12. is shown below. Its working is also further explained. we used the HT12D and HT12E, decoder and encoder IC respectively. But, in our application we just need the receiver to detect if the transmitter is sending some signals. So the Data pin of the transmitter is connected to Ground or Vcc of the supply.

Arduino Program for Smart Blind Stick:

used for this page can be found at the bottom of this page, you can upload it directly to your Arduino board. However, if you are curious to know how the code works read further. In our program the Buzzer and Trigger pin is an Output device and the Echo pin is an Input device. We also initialise the serial monitor for debugging. void setup() { Serial.begin(9600); pinMode(Buzz,OUTPUT); digitalWrite(Buzz,LOW); pinMode(trigger, OUTPUT); pinMode(echo, INPUT); } We begin with reading the sensor data of Ultrasonic sensor for distance, LDR for light intensity and RF signal to check if the button is pressed. All these data is saved in a variable as shown below for future use. calculate_distance(trigger,echo); Signal = analogRead(Remote); Intens = analogRead(Light); to check how many times the same values are being repeated from the RF receiver. This repetition will occur only when the button is pressed. So we trigger the Remote pressed alarm if the count exceeds a value of 100. //Check if Remote is pressed int temp = analogRead(Remote); similar_count=0; while (Signal==temp) { Signal = analogRead(Remote); similar_count++; } //If remote pressed if (similar_count<100) { Serial.print(similar_count); Serial.println("Remote Pressed"); digitalWrite(Buzz,HIGH);delay(3000);digitalWrite(Buzz,LOW); } You can also check it on Serial Monitor on your computer: If the LDR gives a value of less than 200 it is assumed to be very dark and we give him the warning through buzzer with a specific tone of delay with 200ms. If the intensity is very bright that is more than 800 then also we give a warning with another tone. The alarm tone and intensity can be easily varied by changing the respective value in the below code. //If very dark if (Intens<200) { Serial.print(Intens); Serial.println("Bright Light"); digitalWrite(Buzz,HIGH);delay(200);digitalWrite(Buzz,LOW);delay(200);digitalWrite(Buzz,HIGH);delay(200);digitalWrite(Buzz,LOW);delay(200); delay(500); } //If very bright if (Intens>800) { Serial.print(Intens); Serial.println("Low Light"); digitalWrite(Buzz,HIGH);delay(500);digitalWrite(Buzz,LOW);delay(500);digitalWrite(Buzz,HIGH);delay(500);digitalWrite(Buzz,LOW);delay(500); } loop which loop based on the measured distance as shown below. if (dist<50) { Serial.print(dist); Serial.println("Object Alert"); digitalWrite(Buzz,HIGH); for (int i=dist; i>0; i--) delay(10); digitalWrite(Buzz,LOW); for (int i=dist; i>0; i--) delay(10); } The program can be easily adapted for your application by changing the value which we use to compare. You use the serial monitor to debug if a false alarm is trigger. If you have any problem you can use the comment section below to post your questions

Arduino Blind Stick in Action:

If the LDR is covered in dark or if there is too much light the buzzer will beep. If everything is normal the buzzer will not beep. is shown in the Video given at the end of this page. I also use a small stick to mount the complete assembly you can use a larger one or an actual blind stick and put it in action. If your buzzer is always beeping it means the alarm is being false triggered. You can open the serial monitor to check for the parameters and check which is falling in critical and adjust that. As always you can post your problem in the comment section to get help. Hope you understood the project and enjoyed building something. Code /* * Program for Blind Man Stick * Code by B.Aswinth Raj * Dated: 03-11-2017 * Website: www.circuitdigest.com */ const int trigger = 3; //Trigger pin of 1st Sesnor const int echo = 2; //Echo pin of 1st Sesnor const int Buzz = 13; //Echo pin of 1st Sesnor const int Remote = A0; //Echo pin of 1st Sesnor const int Light = A1; //Echo pin of 1st Sesnor long time_taken; int dist; int Signal; int Intens; int similar_count; void setup() { Serial.begin(9600); pinMode(Buzz,OUTPUT); digitalWrite(Buzz,LOW); pinMode(trigger, OUTPUT); pinMode(echo, INPUT); } /*###Function to calculate distance###*/ void calculate_distance(int trigger, int echo) { digitalWrite(trigger, LOW); delayMicroseconds(2); digitalWrite(trigger, HIGH); delayMicroseconds(10); digitalWrite(trigger, LOW); time_taken = pulseIn(echo, HIGH); dist= time_taken*0.034/2; if (dist>300) dist=300; } void loop() { //infinite loopy calculate_distance(trigger,echo); Signal = analogRead(Remote); Intens = analogRead(Light); //Check if Remote is pressed int temp = analogRead(Remote); similar_count=0; while (Signal==temp) { Signal = analogRead(Remote); similar_count++; } //If remote pressed if (similar_count<100) { Serial.print(similar_count); Serial.println("Remote Pressed"); digitalWrite(Buzz,HIGH);delay(3000);digitalWrite(Buzz,LOW); } //If very dark if (Intens<200) { Serial.print(Intens); Serial.println("Bright Light"); digitalWrite(Buzz,HIGH);delay(200);digitalWrite(Buzz,LOW);delay(200);digitalWrite(Buzz,HIGH);delay(200); digitalWrite(Buzz,LOW);delay(200); delay(500); } //If very bright if (Intens>800) { Serial.print(Intens); Serial.println("Low Light"); digitalWrite(Buzz,HIGH);delay(500);digitalWrite(Buzz,LOW);delay(500);digitalWrite(Buzz,HIGH);delay(500); digitalWrite(Buzz,LOW);delay(500); } if (dist<50) { Serial.print(dist); Serial.println("Object Alert"); digitalWrite(Buzz,HIGH); for (int i=dist; i>0; i--) delay(10); digitalWrite(Buzz,LOW); for (int i=dist; i>0; i--) delay(10); } //Serial.print("dist="); //Serial.println(dist); //Serial.print("Similar_count="); //Serial.println(similar_count); //Serial.print("Intens="); //Serial.println(Intens); } Video microcontroller-projects/arduino-metal-detector-circuit-code

Arduino Metal Detector

This is very interesting project for all electronics lovers. Wherever this detector detects any metal near it, the buzzer starts beeping very rapidly.

Required Components:

All these components should be easily available in your local hardware shop. Arduino (any) Coil 10nF capacitor Buzzer The 1k resistor 330-ohm resistor LED 1N4148 diode Breadboard or PCB Connecting jumper wire 9v Battery

How does a metal detector work?

, means the generated voltage opposes the increase in the current. The unit of Inductance is Henry and formula to measure the Inductance is: L = (μο * N2 * A) / l Where, L- Inductance in Henries μο- Permeability, its 4π*10-7 for Air N- Number of turns A- Inner Core Area (πr2) in m2 l- Length of the Coil in meters When any metal comes near to the coil then coil changes its inductance. This change in inductance depends upon the metal type. It's decreases for non-magnetic metal and increases for ferromagnetic materials like iron. They are basically coils left in the air. The medium of flow of magnetic field generated by the inductor is nothing or air. These inductors have inductances of very less value. These Ferrite Core inductor has very large inductance value. Remember the coil wound here is a air-cored one, so whena metal piece is brought near the coil, the metal piece acts as a core for the air cored inductor. By this metal acting as a core, the inductance of thecoil changes or increases considerably. With this sudden increase in inductance of coil the overall reactance or impedance of the LC circuit changes by a considerable amount when compared without the metal piece.

Circuit Diagram:

A LED and Buzzer are used as metal detection indicator. A Coil and capacitor is used for the detection of metals. A signal diode is also used for reducing the voltage. And a resistor for limiting the current to the Arduino pin.

Working Explanation:

is bit tricky. Here we provide the block wave or pulse, generated by Arduino, to the LR high pass filter. Due to this, short spikes will be generated by the coil in every transition. The pulse length of the generated spikes is proportional to the inductance of the coil. So with the help of these Spike pulses, we can measure the inductance of Coil. But here it is difficult to measure inductance precisely with those spikes because those spikes are of very short duration (approx. 0.5 microseconds) and that is very difficult to be measured by Arduino. given at the end of this Article to understand the working. is given at the end of this Article. In the programming part of this project, we have used two Arduino pins, one for generating block waves to be fed in Coil and second analog pin to read capacitor voltage. Other than these two pins, we have used two more Arduino pins for connecting LED and buzzer. below. You can see that whenever it detects some metal the LED and Buzzer start to blink very fastly. Code /* Metal Detector Arduino Code */ #define capPin A5 #define buz 9 #define pulsePin A4 #define led 10 long sumExpect=0; //running sum of 64 sums long ignor=0; //number of ignored sums long diff=0; //difference between sum and avgsum long pTime=0; long buzPeriod=0; void setup() { Serial.begin(9600); pinMode(pulsePin, OUTPUT); digitalWrite(pulsePin, LOW); pinMode(capPin, INPUT); pinMode(buz, OUTPUT); digitalWrite(buz, LOW); pinMode(led, OUTPUT); } void loop() { int minval=1023; int maxval=0; long unsigned int sum=0; for (int i=0; i<256; i++) { //reset the capacitor pinMode(capPin,OUTPUT); digitalWrite(capPin,LOW); delayMicroseconds(20); pinMode(capPin,INPUT); applyPulses(); //read the charge of capacitor int val = analogRead(capPin); //takes 13x8=104 microseconds minval = min(val,minval); maxval = max(val,maxval); sum+=val; long unsigned int cTime=millis(); char buzState=0; if (cTime<pTime+10) { if (diff>0) buzState=1; else if(diff<0) buzState=2; } if (cTime>pTime+buzPeriod) { if (diff>0) buzState=1; else if (diff<0) buzState=2; pTime=cTime; } if (buzPeriod>300) buzState=0; if (buzState==0) { digitalWrite(led, LOW); noTone(buz); } else if (buzState==1) { tone(buz,2000); digitalWrite(led, HIGH); } else if (buzState==2) { tone(buz,500); digitalWrite(led, HIGH); } } //subtract minimum and maximum value to remove spikes sum-=minval; sum-=maxval; if (sumExpect==0) sumExpect=sum<<6; //set sumExpect to expected value long int avgsum=(sumExpect+32)>>6; diff=sum-avgsum; if (abs(diff)<avgsum>>10) { sumExpect=sumExpect+sum-avgsum; ignor=0; } else ignor++; if (ignor>64) { sumExpect=sum<<6; ignor=0; } if (diff==0) buzPeriod=1000000; else buzPeriod=avgsum/(2*abs(diff)); } void applyPulses() { for (int i=0;i<3;i++) { digitalWrite(pulsePin,HIGH); //take 3.5 uS delayMicroseconds(3); digitalWrite(pulsePin,LOW); //take 3.5 uS delayMicroseconds(3); } } Video microcontroller-projects/arduino-relay-control

Arduino Relay Control Tutorial

is a very common and almost first program for every embedded learner or beginner. In which we blink an LED with having some delay. So today we are here with the same project but here we will use an AC bulb instead of normal LED and will blink an AC bulb. to control relay.

Components Required:

Arduino 5v or 6v relay AC appliance or Bulb BC547 transistor 1k resistor Breadboard or PCB Connecting jumper wire Power supply 1n4007 diode Screw terminal or terminal block

Relay:

, it has five terminals as below: When there is no voltage applied to the coil, COM (common) is connected to NC (normally closed contact). When there is some voltage applied to the coil, the electromagnetic field produced, which attracts the Armature (lever connected to spring), and COM and NO (normally open contact) gets connected, which allow a larger current to flow. Relays are available in many ratings, here we used 6V operating voltage relay, which allows 7A-250VAC current to flow. is easily available in the market with all its Driver circuit on the board or you can create it on perf board or PCB like below. Here we have used 6V Relay module. to build your own Relay module:

Circuit Diagram and Working:

we have used Arduino to control the relay via a BC547 transistor. We have connected transistor base to Arduino pin A0 through a 1k resistor. An AC bulb is used for demonstration. The 12v adaptor is used for powering the circuit. The AC light will also turn on and off according to Relay. We just programmed the Arduino to make the Relay Pin (A0) High and Low with a delay of 1 second: void loop() { digitalWrite(relay, HIGH); delay(interval); digitalWrite(relay, LOW); delay(interval); } is given below. Code // Arduino Relay Control Code #define relay A0 #define interval 1000 void setup() { pinMode(relay, OUTPUT); } void loop() { digitalWrite(relay, HIGH); delay(interval); digitalWrite(relay, LOW); delay(interval); } Video microcontroller-projects/temperature-controlled-home-appliances-using-arduino-thermistor

Temperature Controlled AC Home Appliances using Arduino and Thermistor

and displayed the Temperature on LCD. connected with the circuit.

Material Required

Arduino UNO Relay (5v) 16*2 LCD display Light Bulb (CFL) NTC thermistor 10k Connecting wires Resistors (1k and 10k ohms) Potentiometer (10k)

Circuit Diagram

The whole triggering process and temperature value setting is performed by the programmed Arduino board. It also gives us details about the change in temperature in every half second and appliance status on the LCD screen.

Relay:

Pole Double Throw (SPDT)Relay, it has five terminals as below: When there is no voltage applied to the coil, COM (common) is connected to NC (normally closed contact). When there is some voltage applied to the coil, the electromagnetic field produced, which attracts the Armature (lever connected to spring), and COM and NO (normally open contact) gets connected, which allow a larger current to flow. Relays are available in many ratings, here we used 5V operating voltage relay, which allows 7A-250VAC current to flow. is easily available in the market with all its Driver circuit on the board or you can create it by using above components. Here we have used 5V Relay module

Calculating Temperature using Thermistor:

We know from the Voltage divider circuit that: Vout= (Vin * Rt) / (R + Rt) So the value of Rt will be: Rt = R (Vin/Vout) ᾠ1 Here Rt will be the resistance of the thermistor (Rt) and R will be 10k ohm resistor. This equation is used for the calculation of thermistor resistance from the measured value of output voltage Vo. We can get the value of Voltage Vout from the ADC value at pin A0 of Arduino as shown in the Arduino Code given below. Calculation of Temperature from the thermistor resistance Mathematically the thermistor resistance can only be compute with the help of the Stein-Hart equation. T = 1 / (A + B*ln(Rt) + C*ln (Rt)3 ) Where, A, B and C are the constants, Rt is the thermistor resistance and ln represents log. by entering the three resistance values of the thermistor at three different temperatures. You can either get these constant values directly from the datasheet of the Thermistor or you can get three resistance values at different temperature and get the Constants values using the given calculator. So, for calculating the temperature we need the value of thermistor resistance only. After getting the value of Rt from the calculation given above put the values in the Stein-hart equation and we will get the value of temperature in the unit Kelvin. As there is a minor change in the output voltage cause change in the temperature.

Arduino code

is given at the end of this article. Here we have explained few parts of it. We have to assign the pins of the LCD by using the code. #include <math.h> #include "LiquidCrystal.h" #define RELAY 8 LiquidCrystal lcd(6,7,5,4,3,2); // these are in format like LCD(Rs, EN, D4, D5, D6, D7) part Void setup(){ lcd.begin(16,2); lcd.clear(); pinMode(RELAY, OUTPUT); } For the calculation of temperature by Stein-Hart equation using the electrical resistance of thermistor we perform some simple mathematical equation in code as explained in calculation above: float a = 1.009249522e-03, b = 2.378405444e-04, c = 2.019202697e-07; float T, logRt, Tf, Tc; float Thermistor(int Vo) { logRt = log(10000.0*((1024.0/Vo-1))); T = (1.0 / (a + b*logRt + c* logRt * logRt * logRt)); // We get the temperature value in Kelvin from this Stein-Hart equation Tc = T - 273.15; // Convert Kelvin to Celsius Tf = (Tc * 1.8) + 32.0; // Convert Kelvin to Fahrenheit return T; } by performing the mathematical operation lcd.print((Thermistor(analogRead(0)))); function and then the calculation is start printing float Thermistor(int Vo) if (Tc > 28) digitalWrite(RELAY, HIGH),lcd.setCursor(0,1),lcd.print("Light status:ON "),delay(500); else if (Tc < 28) digitalWrite(RELAY, LOW),lcd.setCursor(0,1),lcd.print("Light status:OFF"),delay(500);

Working of Temperature Controlled Home Automation System:

To give the supply to the Arduino you can power it via USB to your laptop or connect 12v adapter. A LCD is interfaced with Arduino to display temperature values, Thermistor and Relay is connected as per circuit diagram. The analog pin (A0) is used to check the voltage of thermistor pin at every moment and after the calculation using Stein-Hart equation through the Arduino code we are able to get the temperature and display it on LCD in the Celsius and Fahrenheit. As the temperature increases more than 28 degree Celsius Arduino makes the Relay Module Turned On by making the Pin 8 HIGH (where the Relay module is connected) when the temperature goes below 28 Degree Arduino turns off the Relay Module by making the Pin LOW. CFLbulb will also turnOn and Off according to Relay module. project. like: DTMF Based Home Automation GSM Based Home Automation using Arduino PC Controlled Home Automation using Arduino Bluetooth Controlled Home Automation using 8051 IR Remote Controlled Home Automation using Arduino home automation project using MATLAB and Arduino RF Remote Controlled LEDs Using Raspberry Pi Smart Phone Controlled Home Automation using Arduino Voice Controlled Home Automation using ESP8266 and Android App RF based Home Appliances System without Microcontroller Raspberry Pi based Smart Phone Controlled Home Automation Code #include <math.h> #include "LiquidCrystal.h" #define RELAY 8 LiquidCrystal lcd(6,7,5,4,3,2); float A = 1.009249522e-03, B = 2.378405444e-04, C = 2.019202697e-07; float T,logRt,Tf,Tc; float Thermistor(int Vo) { logRt = log(10000.0*((1024.0/Vo-1))); T = (1.0 / (A + B*logRt + C*logRt*logRt*logRt)); // We get the temperature value in Kelvin from this Stein-Hart equation Tc = T - 273.15; // Convert Kelvin to Celcius Tf = (T * 1.8) + 32.0; // Convert Kelvin to Fahrenheit return T; } void setup() { lcd.begin(16,2); lcd.clear(); pinMode(RELAY, OUTPUT); } void loop() { lcd.setCursor(0,0); lcd.print("Temperature:"); lcd.print(int(Thermistor(analogRead(0)))); lcd.print("C "); delay(500); // wait 0.5 seconds before sampling temperature again if (Tc > 28) digitalWrite(RELAY, HIGH),lcd.setCursor(0,1),lcd.print("Light status:ON "),delay(500); else if (Tc < 28) digitalWrite(RELAY, LOW),lcd.setCursor(0,1),lcd.print("Light status:OFF"),delay(500); } Video microcontroller-projects/arduino-fire-fighting-robot-code

Arduino Based Fire Fighting Robot

, which will automatically sense the fire and start the water pump that could move towards the fire and pump out water around it to put down the fire. It is a very simple robot that would teach us the underlying concept of robotics; you would be able to build more sophisticated robots once you understand the following basics. So let’s get started...

Material Required:

Arduino UNO Fire sensor or Flame sensor (3 Nos) Servo Motor (SG90) L293D motor Driver module Mini DC Submersible Pump Small Breadboard Robot chassis with motors (2) and wheels(2) (any type) A small can Connecting wires

Working Concept of Fire Fighting Robot:

(flame sensor) that is shown below. which is used to detect the fire. How is this possible? When fire burns it emits a small amount of Infra-red light, this light will be received by the IR receiver on the sensor module. Then we use an Op-Amp to check for change in voltage across the IR Receiver, so that if a fire is detected the output pin (DO) will give 0V(LOW) and if the is no fire the output pin will be 5V(HIGH). So, we place three such sensors in three directions of the robot to sense on which direction the fire is burning. so that we can control the direction in which the water has to be sprayed. Let’s proceed with the connections now

Circuit Diagram:

is given below You can either connect all the shown connections for uploading the program to check the working or you can assemble the bot completely and then proceed with the connections. Both ways the connections are very simple and you should be able to get it right. Based on the robotic chassis that you are using you might not be able to use the same type of container that I am using. In that case use your own creativity to set up the pumping system. However the code will remain same. I used a small aluminium can (cool drinks can) to set the pump inside it and poured water inside it. I then assembled the whole can on top of a servo motor to control the direction of water. My robot looks something like this after assembly. As you can see, I have fixed the servo fin to the bottom of the container using got glue and have fixed the servo motor with chassis using nuts and bolts. We can simply place the container on top of the motor and trigger the pump inside it to pump water outside through the tube. The whole container can then be rotated using the servo to control the direction of the water.

Programming your Arduino:

is given at the end of this page. However I have further explained few important bits and pieces here. by making all the pins high as shown below if (digitalRead(Left_S) ==1 && digitalRead(Right_S)==1 && digitalRead(Forward_S) ==1) //If Fire not detected all sensors are zero { //Do not move the robot digitalWrite(LM1, HIGH); digitalWrite(LM2, HIGH); digitalWrite(RM1, HIGH); digitalWrite(RM2, HIGH); } ᾠthat would execute the function to put off the fire. else if (digitalRead(Forward_S) ==0) //If Fire is straight ahead { //Move the robot forward digitalWrite(LM1, HIGH); digitalWrite(LM2, LOW); digitalWrite(RM1, HIGH); digitalWrite(RM2, LOW); fire = true; } function until the fire is put off. This is done using the code below. while (fire == true) { put_off_fire(); } the container, while this is done we can also use the servo motor to rotate the container so that the water is split all over uniformly. This is done using the code below void put_off_fire() { delay (500); digitalWrite(LM1, HIGH); digitalWrite(LM2, HIGH); digitalWrite(RM1, HIGH); digitalWrite(RM2, HIGH); digitalWrite(pump, HIGH); delay(500); for (pos = 50; pos <= 130; pos += 1) { myservo.write(pos); delay(10); } for (pos = 130; pos >= 50; pos -= 1) { myservo.write(pos); delay(10); } digitalWrite(pump,LOW); myservo.write(90); fire=false; }

Working of Fire Fighting Robot:

The maximum distance to which the fire can be detected depends on the size of the fire, for a small matchstick the distance is relatively less. You can also use the potentiometers on top of the modules to control the sensitivity of the robot. I have used a power bank to power the robot you can use a battery or even power it with a 12V battery. Hope you understood the project and would enjoy building something similar. If you have any problems in getting this build, use the comment section below to post your quires or use the forums for technical help. to find more cool DIY Robots. Code /*------ Arduino Fire Fighting Robot Code----- */ #include <Servo.h> Servo myservo; int pos = 0; boolean fire = false; /*-------defining Inputs------*/ #define Left_S 9 // left sensor #define Right_S 10 // right sensor #define Forward_S 8 //forward sensor /*-------defining Outputs------*/ #define LM1 2 // left motor #define LM2 3 // left motor #define RM1 4 // right motor #define RM2 5 // right motor #define pump 6 void setup() { pinMode(Left_S, INPUT); pinMode(Right_S, INPUT); pinMode(Forward_S, INPUT); pinMode(LM1, OUTPUT); pinMode(LM2, OUTPUT); pinMode(RM1, OUTPUT); pinMode(RM2, OUTPUT); pinMode(pump, OUTPUT); myservo.attach(11); myservo.write(90); } void put_off_fire() { delay (500); digitalWrite(LM1, HIGH); digitalWrite(LM2, HIGH); digitalWrite(RM1, HIGH); digitalWrite(RM2, HIGH); digitalWrite(pump, HIGH); delay(500); for (pos = 50; pos <= 130; pos += 1) { myservo.write(pos); delay(10); } for (pos = 130; pos >= 50; pos -= 1) { myservo.write(pos); delay(10); } digitalWrite(pump,LOW); myservo.write(90); fire=false; } void loop() { myservo.write(90); //Sweep_Servo(); if (digitalRead(Left_S) ==1 && digitalRead(Right_S)==1 && digitalRead(Forward_S) ==1) //If Fire not detected all sensors are zero { //Do not move the robot digitalWrite(LM1, HIGH); digitalWrite(LM2, HIGH); digitalWrite(RM1, HIGH); digitalWrite(RM2, HIGH); } else if (digitalRead(Forward_S) ==0) //If Fire is straight ahead { //Move the robot forward digitalWrite(LM1, HIGH); digitalWrite(LM2, LOW); digitalWrite(RM1, HIGH); digitalWrite(RM2, LOW); fire = true; } else if (digitalRead(Left_S) ==0) //If Fire is to the left { //Move the robot left digitalWrite(LM1, HIGH); digitalWrite(LM2, LOW); digitalWrite(RM1, HIGH); digitalWrite(RM2, HIGH); } else if (digitalRead(Right_S) ==0) //If Fire is to the right { //Move the robot right digitalWrite(LM1, HIGH); digitalWrite(LM2, HIGH); digitalWrite(RM1, HIGH); digitalWrite(RM2, LOW); } delay(300); //Slow down the speed of robot while (fire == true) { put_off_fire(); } } Video microcontroller-projects/arduino-thermistor-interfacing-code-circuit

Interfacing Thermistor with Arduino to Measure and Display Temperature on LCD

and a LCD to display the temperature. It is useful in various projects like remote weather station, home automation, and protection and controlling of industrial and electronics equipment’s. You can make various electronic circuit based projects using thermistor some of them are listed below: Temperature Controlled DC Fan using Thermistor Fire Alarm using Thermistor

Components Required:

NTC thermistor 10k Arduino (Any version) 10k ohm Resistor Connecting Wires

Circuit Diagram

Thermistor provides temperature value as per the change in the electrical resistance in it. In this circuit, the analog pin in the Arduino is connected with the thermistor and can provide the ADC values only, so the electrical resistance of thermistor is not calculated directly. So the circuit is made to be like a voltage divider circuit as shown in figure above, by connecting a known resistance of 10k ohm in series with the NTC. Using this Voltage divider we can get the voltage across Thermistor and with that voltage we can derive the Resistance of Thermistor at that moment. And finally we can get the temperature value by putting the resistance of thermistor in Stein-Hart equation as explained in below sections.

Thermistor

, whose resistance changes according to the temperature. There are two types of thermistor NTC (Negative Temperature Co-efficient) and PTC (Positive Temperature Co-efficient), we are using a NTC type thermistor. NTC thermistor is a resistor whose resistance decreases as rise in temperature while in PTC it will increase the resistance as rise in temperature.

Calculating Temperature using Thermistor:

We know from the Voltage divider circuit that: Vout= (Vin * Rt) / (R + Rt) So the value of Rt will be: Rt = R (Vin/Vout) ᾠ1 This equation is used for the calculation of thermistor resistance from the measured value of output voltage Vo. We can get the value of Voltage Vout from the ADC value at pin A0 of Arduino as shown in the Arduino Code given below. T = 1 / (A + Bln(Rt) + Cln (Rt)3 ) Where, A, B and C are the constants, Rt is the thermistor resistance and ln represents log. by entering the three resistance values of thermistor at three different temperatures. You can either get these constant values directly from the datasheet of the Thermistor or you can get three resistance values at different temperature and get the Constants values using the given calculator. So, for calculating the temperature we need the value of thermistor resistance only. After getting the value of Rt from the calculation given above put the values in the Stein-hart equation and we will get the value of temperature in the unit kelvin. As there is minor change in the output voltage cause change in the temperature.

Arduinothermistor code

Complete Arduino Code for Interfacing Thermistor with Arduino is given at the end of this article. Here we have explained few parts of it. We have to assign the pins of the LCD by using the code LiquidCrystal lcd(44,46,40,52,50,48); For setup the LCD at the time of start we have to write code in the void setup part Void setup(){ lcd.begin(16,2); lcd.clear(); } For the calculation of temperature by Stein-Hart equation using the electrical resistance of thermistor we perform some simple mathematical equation in code as explained in calculation above: float a = 1.009249522e-03, b = 2.378405444e-04, c = 2.019202697e-07; float T,logRt,Tf,Tc; float Thermistor(int Vo) { logRt= log(10000.0*((1024.0/Vo-1))); T = (1.0 / (A + B*logRt+ C*logRt*logRt*logRt));// We get the temperature value in Kelvin from this Stein-Hart equation Tc = T - 273.15; // Convert Kelvin to Celsius Tf = (Tc * 1.8) + 32.0; // Convert Kelvin to Fahrenheit return T; } In the below code the function thermistor is reading the value from the analog pin of the Arduino, lcd.print((Thermistor(analogRead(0)))); and that value is taken in the code below and then the calculation is start printing float Thermistor(int Vo)

Measuring Temperature with Thermistor and Arduino:

to display temperature values and Thermistor is connected as per circuit diagram. The analog pin (A0) is used to check the voltage of thermistor pin at every moment and after the calculation using Stein-Hart equation through the Arduino code we are able to get the temperature and display it on LCD in the Celsius and Fahrenheit. Code #include <math.h> #include "LiquidCrystal.h" LiquidCrystal lcd(44,46,40,52,50,48); float A = 1.009249522e-03, B = 2.378405444e-04, C = 2.019202697e-07; float T,logRt,Tf,Tc; float Thermistor(int Vo) { logRt = log(10000.0*((1024.0/Vo-1))); T = (1.0 / (A + B*logRt + C*logRt*logRt*logRt)); // We get the temperature value in Kelvin from this Stein-Hart equation Tc = T - 273.15; // Convert Kelvin to Celcius Tf = (Tc * 1.8) + 32.0; // Convert Kelvin to Fahrenheit return T; } void setup(){ lcd.begin(16,2); lcd.clear(); } void loop() { lcd.setCursor(0,0); lcd.print("Temp:"); lcd.print((Thermistor(analogRead(0)))); lcd.print("k "); lcd.setCursor(0,1); lcd.print((Tc)); lcd.print(" C ;"); lcd.setCursor(9,1); lcd.print((Tf)); lcd.print(" F"); delay(800); } Video microcontroller-projects/measuring-distance-between-two-ultrasonic-sensors-using-arduino

How To Measure Distance Between Two Ultrasonic Sensors

might sound to be a fairly simple task but I faced few challenges which are discussed in this project. The technique discussed in this article is not fairly accurate and might not be useful in any real systems without modifications. During the time of this documentation I did not find anyone getting results as close as mine so I have just shared my views on how I got it to work so that people who are trying this need not re-invent the wheel.

Materials Required:

Arduino (2Nos) ᾠAny model HCSR04 Module (2Nos)

Circuit Diagram:

Even though we are going to make one US (Ultrasonic) sensor to work as transmitter and the other as receiver it is mandatory connect all the four pins of the sensors with the Arduino. Why should we? More of that will be discussed later, but for now the circuit diagram will be as follows

How HC-SR04 module actually works:

The below timing Diagram will help us understand the working. The sensor has two pins Trigger and Echo which is used to measure distance as shown in the timing diagram. First to initiate measurement we should send an Ultrasonic wave from the transmitter, this can be done by setting the trigger pin high for 10uS. As soon as this is done the transmitter pin will send 8 sonic burst of US waves. This US wave will hit an object bounce back and will be received by the receiver. I covered the Tx (transmitter) part of my sensor and checked if the Echo pulse got high, and yes it does go high. This means that the Echo pulse does not wait for the US (ultrasonic) wave to be received by it. Once it transmits the US wave it goes high and stays high until the wave returns back. So the correct timing diagram should be something like this shown below (Sorry for my poor writing skills) It is pretty much straight forward to make a HC-SR04 to work as transmitter only. As shown in the timing diagram you have to declare the Trigger pin as output pin and make it stay high for 10 Microseconds. This will initiate the Ultrasonic wave burst. So whenever we want to transmit the wave we just have to control the trigger pin of the Transmitter sensor, for which the code is given below. As shown in the timing diagram we cannot control the rise of the Echo pin as it is related to trigger pin. So there is no way we could make the HC-SR04 to work as receiver only. But we can use a hack, by just covering the Transmitter part of the sensor with tape (as shown in the picture below) or cap the US wave cannot escape outside its Transmitter casing and the Echo pin will not be affected by this US wave. Now to make the echo pin go high we just have to pull this dummy trigger pin high for 10 Microseconds. Once this Receiver sensor gets the US wave transmitted by the Transmitter sensor the echo pin will go low.

Measuring distance between two Ultrasonic sensors (HC-SR04):

So far we have understood how to make one sensor work as transmitter and the other sensor to work as receiver. Now, we have to transmit the ultrasonic wave from transmitter sensor and receive it with the receiver sensor and check the time taken for the wave to travel from transmitter to receiver sounds easy right?? But sadly!, we have a problem here and this will not work. The Transmitter module and Receiver module are far apart and when the receiver module receives the US wave from the transmitter module it will not know when the transmitter sent this particular wave. Without knowing the start time we cannot calculate the time taken and thus the distance. To solve this problem the Echo pulse of the receiver module must be made to go high exactly when the Transmitter module has transmitted the US wave. In other words, the Transmitter module and the receiver module should trigger at the same time. This can be achieved by the following method. In the above diagram, the Tx represents Transmitter sensor and Rx represents Receiver sensor. As shown the Transmitter sensor will be made to transmit US waves at a periodic known delay, this is all it has to do. In the Receiver sensor we have to somehow make the trigger pin go high exactly during when the transmitter pin goes high. So initially we randomly make the Receivers Trigger to go high which will and stay high till the echo pin goes low. This echo pin will go low only when it receives a US wave from the transmitter. So as soon as it goes low we can assume that the Transmitter sensor just got triggered. Now, with this assumption as soon as the echo goes low we can wait for the known delay and then trigger the receivers trigger. This would partially sync the trigger of both the Transmitter and receiver and hence you can read the immediate echo pulse duration using pulseIn() and calculate the distance.

Program for Transmitter Sensor:

The complete program for the transmitter module can be found at the bottom of the page. It does nothing but trigger the transmitter sensor at a periodic interval. digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); To trigger a sensor we have to make the trigger pin to stay high for 10uS. The code to do the same is shown above

Program for Receiver Sensor:

In the receiver sensor we have cover the Transmitter eye of the sensor to make it dummy as discussed earlier. Now we can use the above mentioned technique to measure distance between two sensors. The complete program is given at the bottom of this page. Few important lines are explained below Trigger_US(); while (digitalRead(echoPin)==HIGH); delayMicroseconds (10); Trigger_US(); duration = pulseIn(echoPin, HIGH); Initially we trigger the US sensor by using the function Trigger_US() and then wait till the echo pin stays high using a while loop. Once it gets low we wait for pre-determined duration, this duration should be somewhere between 10 to 30 microseconds which can be determined using trial and error (Or you can use improvised idea given below). After this delay trigger the US again using the same function and then use the pulseIn() function to calculate the duration of the wave. Now using the same old formulae we can calculate the distance as below distance= duration*0.034;

Working:

Make the connections as explained in the program. Cover the Tx part of the receiver sensor as shown in the picture. Then upload the Transmitter code and receiver code which are given below to the transmitter and receiver Arduino respectively. Open the serial monitor of the receiver module and you should notice the distance between two modules being displayed as shown in the video below. Note: This method is just an ideology and might not be accurate or satisfying. However you can try the improvised idea below to get better results.

Improvised Idea ᾠcalibrating the sensor using a known distance:

The method that was explained so far oddly seems to be satisfying, yet it was sufficient for my project. However I would also like to share the drawbacks of this method and a way to overcome them. One major drawback of this method is that we assume that the Echo pin of the receiver falls low immediately after the Transmitter sensor has transmitted the US wave which is not true since the wave will take some time to travel from transmitter to receiver. Hence the Trigger of the transmitter and the trigger of the receiver will not be in perfect sync. To overcome this we can calibrate the sensor using a know distance initially. If the distance is know we will know the time taken for the US wave to reach the receiver from the transmitter. Let’s keep this time taken as Del(D) as shown below. Now we will exactly know after how much time we should make the Trigger pin of the Receiver to high to get sync with the trigger of the Transmitter. This duration can be calculated by Known Delay (t) ᾠDel(D). I was not able to test this idea due to time limitations so I am not sure how accurate it would work. So if you happen to try it do let me know the results through the comment section. Code

Programming code for Receiver part

const int trigPin = 9; const int echoPin = 10; // defines variables long duration; int distance, Pdistance; void setup() { pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input Serial.begin(9600); // Starts the serial communication } void loop() { Pdistance=distance; Calc(); distance= duration*0.034; if (Pdistance==distance || Pdistance==distance+1 || Pdistance==distance-1 ) { Serial.print("Measured Distance: "); Serial.println(distance/2); } //Serial.print("Distance: "); //Serial.println(distance/2); delay(500); } void Calc() { duration=0; Trigger_US(); while (digitalRead(echoPin)==HIGH); delay(2); Trigger_US(); duration = pulseIn(echoPin, HIGH); } void Trigger_US() { // Fake trigger the US sensor digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); }

Programming code for Transmitterpart

// defines pins numbers const int trigPin = 9; const int echoPin = 10; // defines variables long duration; int distance; void setup() { pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input Serial.begin(9600); // Starts the serial communication } void loop() { // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); delay(2); } Video microcontroller-projects/nokia5110-graphical-lcd-arduino-interfacing

Interfacing Nokia 5110 Graphical LCD with Arduino

and get it working. These LCD have black and white pixels of dimensions 84 × 48. They might look monotonous but still can be used to display decent graphics for your projects and can be easily used with microcontrollers like Arduino. So let’s get started....!

Materials Required:

Arduino Board (any version) Nokia 5110 display Connecting wires

Nokia 5110 Graphical Display module:

There are two types of these Graphical LCDs available in the market. One with solder pads both above and below the display and the other with solder pads only on the bottom of the display. The one that we are using belong to type 2, where there are pads only under the display. Both the modules work the same and hence the connections are the same for both. So irrespective of what module it is you can follow the tutorial. However if you are using Arduino to communicate with this IC then we need not worry about the datasheet since there are libraries that are ready to be downloaded and used. The module that we are using here is shown below.

Circuit Diagram:

is given below. The module is powered with the 3.3V pin of the Arduino board. Note that these modules work on 3.3V logic and hence do not supply 5V to the Vcc pin of the displays. I have directly wired the Pin of display to Arduino, even though the LCD works on 3.3V logic and Arduino on 5V logic because only then I found the LCD to work properly. You can use a voltage divider to convert 5V to 3.3V if required, but for me it works only without the logic conversion. The connections are pretty simple and straight forward to make. Once you are done with the connections your set-up would look something like this shown below.

Arduino Program and Working:

The steps assume that you have already installed the Arduino IDE and familiar with using it. Open the Arduino IDE on your Computer and select the appropriate board under tools menu after connecting your Arduino to your computer. by Adafruit library from GitHub repository. and browse to the location where the ZIP was downloaded. and install it same way. and click on upload button Once the program is uploaded, press the reset button on the Arduino and you should see the example program displaying all animations as shown in the video given at the end of this tutorial. The maximum image size that we can use for our display is 84 × 48. to launch the application. Open the bitmap image that we just saved using this software to get the array of encoded values. You can directly copy these values and paste it in your Arduino array. The value shown by software for our logo is shown below for your reference. static const unsigned char PROGMEM Logo[] = {B00000000,B00000000,B00000000,B00000000,B00000000,B00000000, B00000000,B00000000,B00001111,B11111000,B00000000,B00000000, B00000000,B00000000,B00001111,B11111111,B00000000,B00000000, B00000000,B00000011,B00011111,B11111111,B11000000,B00000000, B00000000,B00001110,B00111110,B00111111,B11110000,B00000000, B00000000,B00111110,B00111110,B10000000,B01111100,B00000000, B00000000,B01111100,B01111100,B11000000,B00111110,B00000000, B00000000,B11111100,B01111110,B00000000,B00001111,B00000000, B00000001,B11111000,B11111111,B00111111,B10000111,B10000000, B00000011,B11111000,B11111111,B11111111,B11000011,B11000000, B00000111,B11110001,B11111111,B11111111,B11100000,B11100000, B00000111,B11100001,B11111111,B11100011,B11111000,B01100000, B00000000,B00000011,B11100000,B00001001,B11111100,B00000000, B00000000,B00000111,B11100000,B00011001,B11111110,B00000000, B00000000,B00000111,B11000000,B00000001,B11111111,B10000000, B00011111,B11111111,B11000111,B11100011,B11111111,B11111000, B00111111,B11111111,B10001111,B11111111,B11111111,B11111100, B00111111,B11111111,B00011111,B11111111,B11111111,B11111100, B00111111,B11111111,B00011111,B11111111,B11111111,B11111100, B00111111,B11111110,B00111111,B00111111,B11111111,B11111110, B01111111,B11111110,B00111110,B00000000,B01111111,B11111100, B01111111,B11111100,B01111100,B11000000,B00000000,B00000000, B01111111,B11111100,B01111110,B10000000,B00000000,B00000000, B00000000,B00000000,B11111110,B00111111,B11111111,B11111110, B00000000,B00000001,B11111111,B11111111,B11111111,B11111110, B01111111,B11111111,B11111111,B11111111,B11111111,B11111110, B01111111,B11111111,B11111111,B11111111,B11111111,B11111110, B01111111,B11111111,B11000111,B11111111,B11111111,B11111110, B00111111,B11111111,B10000011,B11111110,B00000000,B00000000, B00111111,B11111111,B10110011,B11111000,B00000000,B00000000, B00111111,B11111111,B10000001,B11100000,B00000000,B00000000, B00111111,B11111111,B11000000,B10000001,B11111111,B11111100, B00000000,B00011111,B11111000,B00000111,B11111111,B11111000, B00000000,B00000111,B11111110,B00011111,B11111111,B11111000, B00000000,B00000001,B11111111,B01111111,B11111111,B11110000, B00001111,B11100000,B11111111,B11111111,B11111111,B11110000, B00000111,B11111000,B00001111,B11111111,B11000000,B00000000, B00000011,B11111100,B00100111,B11111111,B00000000,B00000000, B00000011,B11111111,B00110111,B11111100,B00000000,B00000000, B00000001,B11111111,B10000111,B11011000,B00111111,B10000000, B00000000,B11111111,B11001111,B10000000,B11111111,B00000000, B00000000,B01111111,B11111111,B10110001,B11111110,B00000000, B00000000,B00011111,B11111111,B10110111,B11111100,B00000000, B00000000,B00001111,B11111111,B10000111,B11110000,B00000000, B00000000,B00000011,B11111111,B11111111,B11000000,B00000000, B00000000,B00000000,B11111111,B11111111,B00000000,B00000000, B00000000,B00000000,B00001111,B11110000,B00000000,B00000000, B00000000,B00000000,B00000000,B00000000,B00000000,B00000000}; Now to display this bitmap we have to use the following lines of code. Where the previous data on screen is erased and the new bitmap image is written. display.clearDisplay(); display.drawBitmap(20, 0, Logo, 48, 48, 1); display.display(); display the position, size and color of the bitmap image. The syntax can be given as. display.drawBitmap (X_Position, Y_Position, Name of Array, length of image, breadth of image); as shown below. You can also display simple text as shown below: given below. If you face any problem in getting this to work you can use the forum to post your problem or the comment sections below. Code // Nokia5110 display demo program to display logo // RST - Pin 3 // CE - Pin 4 // DC - Pin 5 // DIN - Pin 6 // CLK - Pin 7 #include <Nokia5110.h>#include <SPI.h> #include <Adafruit_GFX.h> #include <Adafruit_PCD8544.h> Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3); /*You can create your own logo by reading the instructions on the tutorial*/ static const unsigned char PROGMEM Logo[] = {B00000000,B00000000,B00000000,B00000000,B00000000,B00000000, B00000000,B00000000,B00001111,B11111000,B00000000,B00000000, B00000000,B00000000,B00001111,B11111111,B00000000,B00000000, B00000000,B00000011,B00011111,B11111111,B11000000,B00000000, B00000000,B00001110,B00111110,B00111111,B11110000,B00000000, B00000000,B00111110,B00111110,B10000000,B01111100,B00000000, B00000000,B01111100,B01111100,B11000000,B00111110,B00000000, B00000000,B11111100,B01111110,B00000000,B00001111,B00000000, B00000001,B11111000,B11111111,B00111111,B10000111,B10000000, B00000011,B11111000,B11111111,B11111111,B11000011,B11000000, B00000111,B11110001,B11111111,B11111111,B11100000,B11100000, B00000111,B11100001,B11111111,B11100011,B11111000,B01100000, B00000000,B00000011,B11100000,B00001001,B11111100,B00000000, B00000000,B00000111,B11100000,B00011001,B11111110,B00000000, B00000000,B00000111,B11000000,B00000001,B11111111,B10000000, B00011111,B11111111,B11000111,B11100011,B11111111,B11111000, B00111111,B11111111,B10001111,B11111111,B11111111,B11111100, B00111111,B11111111,B00011111,B11111111,B11111111,B11111100, B00111111,B11111111,B00011111,B11111111,B11111111,B11111100, B00111111,B11111110,B00111111,B00111111,B11111111,B11111110, B01111111,B11111110,B00111110,B00000000,B01111111,B11111100, B01111111,B11111100,B01111100,B11000000,B00000000,B00000000, B01111111,B11111100,B01111110,B10000000,B00000000,B00000000, B00000000,B00000000,B11111110,B00111111,B11111111,B11111110, B00000000,B00000001,B11111111,B11111111,B11111111,B11111110, B01111111,B11111111,B11111111,B11111111,B11111111,B11111110, B01111111,B11111111,B11111111,B11111111,B11111111,B11111110, B01111111,B11111111,B11000111,B11111111,B11111111,B11111110, B00111111,B11111111,B10000011,B11111110,B00000000,B00000000, B00111111,B11111111,B10110011,B11111000,B00000000,B00000000, B00111111,B11111111,B10000001,B11100000,B00000000,B00000000, B00111111,B11111111,B11000000,B10000001,B11111111,B11111100, B00000000,B00011111,B11111000,B00000111,B11111111,B11111000, B00000000,B00000111,B11111110,B00011111,B11111111,B11111000, B00000000,B00000001,B11111111,B01111111,B11111111,B11110000, B00001111,B11100000,B11111111,B11111111,B11111111,B11110000, B00000111,B11111000,B00001111,B11111111,B11000000,B00000000, B00000011,B11111100,B00100111,B11111111,B00000000,B00000000, B00000011,B11111111,B00110111,B11111100,B00000000,B00000000, B00000001,B11111111,B10000111,B11011000,B00111111,B10000000, B00000000,B11111111,B11001111,B10000000,B11111111,B00000000, B00000000,B01111111,B11111111,B10110001,B11111110,B00000000, B00000000,B00011111,B11111111,B10110111,B11111100,B00000000, B00000000,B00001111,B11111111,B10000111,B11110000,B00000000, B00000000,B00000011,B11111111,B11111111,B11000000,B00000000, B00000000,B00000000,B11111111,B11111111,B00000000,B00000000, B00000000,B00000000,B00001111,B11110000,B00000000,B00000000, B00000000,B00000000,B00000000,B00000000,B00000000,B00000000}; void setup() { display.begin(); display.setContrast(50); display.display(); // show splashscreen delay(2000); display.clearDisplay(); // clears the screen and buffer } void loop() { display.clearDisplay(); display.drawBitmap(20, 0, Logo, 48, 48, 1); // display.drawBitmap (X_Position, Y_Position, Name of Array, length of image, breadth of image); display.display(); } Video microcontroller-projects/cell-phone-controlled-ac-using-arduino

Cell Phone Controlled AC using Arduino and Bluetooth

Now Mobile phones have become more than a device used for communication, they are our cameras, they are our maps, they are our shopping karts and what not? Sounds interesting right! Let’s built one

Materials Required:

Arduino Mega 2560 TSOP (HS0038) IR Led Any Colour LED and 1K Resistor(optional) HC-06 Breadboard Connecting Wires

Working Methodology:

is an IR Receiver that could be used to decode the signal coming from the Remotes. We will use this TSOP to decode all the information from our Remote and store it on Arduino. Then using that information and an IR Led we can re-create the IR signals from our Arduino whenever required.

Pre-requisites:

using this link to work with TSOP and IR Blaster.

Working of an AC Remote:

There might be only 10-12 buttons on your Remote, but they will be able to send a lot of different types of signals. Meaning the Remote does not send the same code every time for the same button. For example, when you decrease the temperature using the down button to make it 24°C (degree Celsius) you will get a signal with a set of data, but when you press it again to set 25°C you will not get the same data since the temperature is now 25 and not 24. Similarly the code for 25 will also vary for different fan speed, sleep settings etc. So let’s not fiddle around with all options and just concentrate only the temperature values with a constant value for other settings. since each signal contains a lot of information like Temp, Fan Speed, Sleep timing, Swing style etc. This is the reason why we need an Arduino Mega for better storage options.

Circuit Diagram and Explanation:

is very easy. You can simply use a breadboard and make the connections as shown below. The following table can also be used to verify your connections.
1TSOP ᾠVcc5V
2TSOP ᾠGndGnd
3TSOP - Signal8
4IR Led ᾠCathodeGnd
5IR Led ᾠAnode9
6HC-05 - Vcc5V
7HC05 ᾠGndGround
8HC05 ᾠTx10
9HC05 ᾠRx11
Once you connections are done it should look something like this shown below. I have used a Breadboard to tidy things, but you can also you Male to female wires directly to hook up all components

Decoding your AC Remote Signals:

int recvPin = 8; IRrecv irrecv(recvPin); Since our TSOP is connect to pin 8, change the line number 9 to int recPin=8 as shown above. Then Upload the program to your Arduino Mega and open the Serial Monitor. , for each button you press its respective Signal will be read by the TSOP1738, decoded by Arduino and displayed in the Serial Monitor. For every change in temperature on your Remote you will get a different Data. Save this Data for we will be using it in our main program. Your serial monitor will look something like this, I have also shown the Word file on which I have saved the copied data. given at the end of this tutorial.

Main Arduino Program:

can be at the bottom of this page, but you cannot use the same program. You have to change the Signal code values that we just obtained from the Example sketch. Open the main program on you Arduino IDE and scroll down to this area shown below where you have to replace the array values with the values that you obtained for your Remote. out of which two us used to Turn ON and turn OFF the AC while the rest 8 is used to set different temperature. For example Temp23 is used to set 23*C on your AC, so use the respective code in that Array. Once that is done, you just have to upload the code to your Arduino. library that we just added to Arduino and the other is the in-built Software Serial Library that helps us in using the Bluetooth module. #include <IRremote.h> //Lib for IT Blaster and TSOP #include <SoftwareSerial.h>// import the serial library and then use an object called irsend to access all the IR features of the library. SoftwareSerial BT_module(10, 11); // RX, TX IRsend irsend; Next comes the very important lines of code. This is where the information to control your AC is present. The one shown below is for my AC remote, you should have obtained yours in the previous step. One is Bluetooth at 9600 Baud rate and the other is Serial monitor at 57600 baud rate. void setup() { BT_module.begin(9600); //BT works on 9600 Serial.begin(57600); //Serial Monitor work son 57600 } while (BT_module.available()) //If data is coming { BluetoothData=BT_module.read(); //read it and save it Serial.println(BluetoothData); //print it on serial for testing purpose } like below if (BluetoothData == '2') { irsend.sendRaw(Temp23, sizeof(Temp23) / sizeof(Temp23[0]), khz); delay(2000);//Send signal to set Temperatue 23C } at the end of this page.

Installing Android Application:

is an excellent tool to create .EXE files or APK files for you Embedded projects. It is an Open source platform just like Arduino and hence completely free to download to use. and install it directly on your mobile phone. Open the application and you will get a screen as shown below after which you can proceed down to the next step and enjoy working with the project. But if you want to tweak the program of the application to fit it to your need then you can read further. This Zip will have the code and image source using which the application works. After open the code you can tweak the following lines to adapt it for your need. My device name here is “HC-05ᾠso my line of code will be bt.start(); //start listening for BT connections bt.getPairedDeviceNames(); bt.connectToDeviceByName("HC-05"); //Connect to our HC-06 bluetooth module and select it based on colour is shown below fill(255,145,3); rect(width/2-width/4,height/2,width/4,height/12); fill(255); text("25C",width/2-width/4,height/2); //button 5 if (color_val==-13589993) {byte[] data = {'0'}; bt.broadcast(data);} The line “byte[] data = {'0'};ᾠis a very important line. This is where we decide which code has to be sent to the Arduino via Bluetooth. Here if this button is pressed the char ᾰᾠis sent from Bluetooth to Arduino. Similarly we can send a different character for different buttons. These characters can then be compared on the Arduino side and respective action can be taken. Go ahead and fiddle around the code, if you have any doubts reach me through the comment section and will try my best in helping you out.

Working of Mobile Phone controlled AC:

ᾠas shown below Hope you enjoyed the project and understood the concept behind it. As always if you got any problem in making this work, you can use the forums to post you questions and get them resolved. Code /* *Bluetooth AC Temperature control using Arduino and TSOP * Code by: Aswinth Raj B * Dated: 25-11-2017 * Website: www.circuitdigest.com * S.No: Component Pin Arduino Pin 1 TSOP a€ᾠVcc 5V 2 TSOP a€ᾠGnd Gnd 3 TSOP - Signal 8 4 IR Led a€ᾠCathode Gnd 5 IR Led a€ᾠAnode 9 6 HC-05 - Vcc 5V 7 HC05 a€ᾠGnd Ground 8 HC05 a€ᾠTx 10 9 HC05 a€ᾠRx 11 */ #include <IRremote.h> //Lib for IT Blaster and TSOP #include <SoftwareSerial.h>// import the serial library SoftwareSerial BT_module(10, 11); // RX, TX IRsend irsend; int khz = 38; // 38kHz carrier frequency for the NEC protocol char BluetoothData; // the data read by Bluetooth Module int PevData; //Decoded Remote Signals For my AC ##CHANGE IT FOR YOUR REMOTE unsigned int ACoff[] = {2950,1750, 400,1100, 450,1050, 450,400, 400,400, 400,400, 450,1100, 400,400, 400,400, 450,1100, 400,1100, 450,350, 450,1100, 400,400, 400,400, 450,1100, 400,1100, 450,400, 400,1100, 400,1100, 450,400, 400,400, 400,1100, 450,350, 450,400, 400,1100, 450,400, 400,400, 400,400, 450,350, 450,350, 450,400, 400,400, 450,350, 450,400, 400,400, 400,400, 450,350, 450,400, 400,400, 400,400, 450,400, 400,400, 400,400, 450,350, 450,350, 450,1100, 400,400, 450,400, 400,1100, 450,1050, 450,400, 400,400, 400,400, 450,350, 450,400, 400,400, 450,350, 450,400, 400,400, 400,1100, 450,350, 450,400, 400,400, 400,400, 450,400, 400,1100, 450,350, 450,400, 400,400, 400,400, 400,1100, 450,400, 400,400, 450,350, 450,400, 400,400, 400,400, 450,350, 450,350, 450,400, 400,400, 450,350, 450,400, 400,400, 400,400, 450,350, 450,400, 400,400, 450,350, 450,400, 400,400, 400,400, 450,350, 450,350, 450,400, 450,350, 450,350, 450,400, 450,350, 450,350, 450,350, 450,400, 450,350, 450,350, 450,400, 400,1100, 450,350, 450,350, 450,400, 450,350, 450,350, 450,1100, 450}; unsigned int ACon[] = {2950,1700, 450,1100, 400,1100, 450,350, 450,350, 450,400, 450,1050, 450,350, 450,400, 450,1050, 450,1100, 400,400, 450,1050, 450,350, 450,400, 400,1100, 450,1100, 450,350, 450,1050, 450,1100, 450,350, 450,350, 450,1100, 450,350, 400,400, 450,1100, 450,350, 450,350, 450,400, 400,400, 450,350, 450,350, 450,400, 400,400, 450,350, 450,350, 450,400, 400,400, 450,350, 450,350, 450,400, 450,350, 450,350, 450,1100, 400,400, 450,350, 450,1100, 400,400, 450,350, 450,1100, 400,1100, 450,350, 450,400, 400,400, 450,350, 500,300, 450,400, 450,350, 400,400, 450,1100, 400,400, 450,350, 450,350, 450,400, 400,400, 450,350, 450,1100, 450,350, 400,400, 450,350, 450,400, 450,350, 400,400, 450,400, 450,350, 450,350, 450,350, 450,400, 400,400, 450,350, 450,400, 400,400, 400,400, 400,400, 450,350, 450,400, 450,350, 450,350, 450,400, 450,350, 450,350, 450,350, 450,400, 400,400, 400,400, 450,350, 450,400, 450,350, 400,400, 450,350, 450,400, 450,350, 450,350, 450,350, 450,400, 450,350, 450,1100, 400,400, 400,400, 450,350, 450,350, 450,1100, 400,400, 450}; unsigned int Temp23[] = {3000,1650, 550,950, 550,1000, 500,300, 550,250, 550,250, 550,1000, 500,300, 550,300, 500,1000, 550,950, 550,300, 550,950, 550,250, 550,300, 500,1000, 500,1050, 500,300, 500,1000, 550,1000, 500,300, 500,300, 550,1000, 450,350, 500,300, 500,1050, 450,350, 450,350, 450,350, 450,400, 450,350, 450,350, 450,400, 400,400, 450,350, 450,350, 450,350, 450,400, 400,400, 400,400, 450,400, 400,400, 400,400, 450,1100, 400,400, 400,400, 450,1050, 450,400, 400,400, 450,1100, 400,1100, 400,400, 450,350, 450,400, 400,400, 400,400, 450,400, 400,400, 400,400, 450,350, 450,1100, 400,400, 400,400, 450,350, 450,400, 400,400, 450,1100, 400,400, 400,1100, 450,1100, 400,1100, 450,350, 450,400, 400,400, 450,350, 450,350, 450,400, 400,400, 400,400, 450,350, 450,400, 400,400, 450,350, 450,400, 400,400, 400,400, 450,350, 450,400, 400,400, 450,350, 450,350, 450,400, 450,350, 400,400, 450,350, 450,400, 450,350, 450,350, 450,400, 450,350, 450,350, 450,350, 450,400, 400,400, 400,400, 450,350, 450,1100, 400,1100, 450,1100, 400,1100, 450,1100, 400,1100, 400,400, 450}; unsigned int Temp24[] = {3000,1650, 500,1050, 500,1000, 500,300, 500,300, 500,350, 500,1000, 500,300, 500,350, 500,1000, 500,1050, 500,300, 500,1000, 500,300, 500,350, 500,1000, 500,1050, 500,300, 500,1000, 500,1050, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,1050, 500,1000, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,1000, 500,1050, 500,1000, 500,300, 500,350, 450,350, 500,300, 500,300, 500,350, 500,1000, 500,300, 500,1050, 500,1000, 500,1050, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,300, 500,350, 500,300, 450,350, 500,350, 450,350, 450,350, 450,350, 450,400, 400,400, 400,400, 450,400, 400,400, 400,400, 400,400, 450,350, 450,400, 400,400, 450,350, 450,400, 450,350, 450,350, 450,350, 450,400, 450,350, 450,350, 450,350, 500,350, 450,1050, 500,300, 500,1050, 500,1000, 500,1050, 500,1000, 500,1000, 500,350, 550}; unsigned int Temp25[] = {3050,1650, 500,1000, 550,950, 550,300, 500,300, 500,300, 550,1000, 500,300, 500,300, 550,1000, 550,950, 550,250, 550,1000, 500,300, 550,250, 550,1000, 500,1000, 550,300, 550,950, 550,950, 550,300, 500,300, 500,1000, 550,250, 550,300, 550,950, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,250, 600,250, 500,300, 550,250, 550,250, 550,300, 550,250, 500,300, 550,300, 500,300, 500,1000, 550,250, 550,300, 500,1000, 550,250, 550,300, 500,1000, 550,1000, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,1000, 550,950, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,950, 550,300, 500,1000, 550,1000, 500,1000, 500,300, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,250, 550,300, 550,250, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 500,350, 500,1000, 500,1000, 500,1050, 500,1000, 500,1050, 500,300, 550}; unsigned int Temp26[] = {3000,1650, 500,1000, 500,1050, 500,300, 500,300, 500,350, 500,1000, 500,300, 500,350, 500,1000, 500,1050, 450,350, 500,1000, 500,300, 500,350, 500,1000, 500,1050, 500,300, 500,1000, 500,1050, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,1050, 450,350, 500,300, 500,1050, 500,1000, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,1000, 500,300, 500,1050, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,1050, 500,300, 500,1050, 450,1050, 500,1000, 500,350, 500,300, 500,300, 500,350, 450,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 450,350, 500,300, 500,350, 450,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,350, 450,1050, 500,1000, 500,350, 500,1000, 500,1000, 500,1050, 500,1000, 500,350, 500}; unsigned int Temp27[] = {3050,1600, 550,1000, 500,1000, 550,300, 500,300, 550,250, 550,1000, 500,300, 550,300, 500,1000, 550,1000, 500,300, 550,1000, 550,250, 500,300, 550,1000, 500,1050, 500,300, 500,1000, 550,1000, 500,300, 550,250, 550,1000, 550,250, 550,300, 500,1000, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,300, 500,300, 500,1000, 550,300, 500,300, 550,1000, 500,300, 500,300, 550,1000, 550,1000, 500,300, 500,300, 550,250, 550,300, 500,300, 550,300, 500,300, 500,300, 550,1000, 500,300, 550,250, 550,300, 500,300, 500,300, 500,350, 500,300, 550,250, 550,1000, 500,1000, 550,1000, 500,300, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 500,300, 550,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 500,300, 500,350, 500,300, 500,350, 500,300, 500,300, 500,1050, 500,1000, 500,1050, 500,1000, 500,350, 500}; // PANASONIC C4D3:64800024 unsigned int Temp28[] = {3100,1600, 550,950, 550,1000, 550,250, 550,250, 550,250, 550,1000, 500,300, 500,300, 550,1000, 500,1000, 550,250, 550,1000, 500,300, 550,250, 550,1000, 550,950, 550,300, 500,1000, 550,950, 550,300, 550,250, 500,1000, 550,300, 500,300, 550,950, 550,300, 500,300, 500,300, 550,250, 550,300, 550,250, 500,300, 550,300, 500,300, 500,300, 550,250, 550,250, 600,250, 500,300, 500,300, 550,300, 500,300, 500,1000, 550,300, 500,300, 500,1000, 550,250, 550,300, 500,1000, 550,1000, 550,250, 550,250, 550,250, 550,300, 500,300, 550,250, 550,1000, 500,1000, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,1000, 500,300, 500,1000, 550,1000, 500,1000, 550,250, 550,300, 500,300, 550,250, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,300, 550,250, 500,300, 550,250, 550,250, 550,300, 550,250, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,250, 550,300, 500,300, 550,1000, 500,300, 500,300, 550,950, 550,1000, 500,1000, 550,1000, 500,300, 550}; unsigned int Temp29[] = {3100,1550, 600,950, 500,1000, 550,300, 500,300, 500,300, 550,950, 550,300, 550,250, 550,1000, 500,1000, 550,250, 550,1000, 500,300, 550,250, 550,950, 600,950, 550,250, 550,1000, 500,1000, 550,250, 600,250, 550,950, 550,250, 550,300, 550,950, 550,250, 550,300, 550,250, 550,250, 550,250, 550,300, 550,250, 550,250, 550,300, 500,300, 550,250, 550,250, 550,300, 500,300, 550,250, 550,250, 600,250, 550,950, 550,250, 550,300, 500,1000, 550,250, 550,300, 550,950, 550,1000, 500,300, 500,300, 550,250, 550,250, 550,300, 500,300, 550,250, 550,1000, 500,300, 550,250, 550,300, 500,300, 550,250, 550,250, 550,300, 500,1000, 550,250, 550,1000, 500,1000, 550,1000, 500,300, 500,300, 550,300, 500,300, 500,300, 550,250, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,250, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,250, 550,1000, 500,1000, 550,1000, 500,1000, 550,300, 500}; unsigned int Temp30[] = {3000,1650, 500,1000, 550,1000, 500,300, 500,300, 550,250, 550,1000, 500,300, 500,300, 550,1000, 550,950, 550,250, 550,1000, 550,250, 550,250, 550,1000, 550,950, 550,300, 500,1000, 550,950, 550,300, 500,300, 550,950, 550,300, 550,250, 550,1000, 500,300, 500,300, 550,250, 550,250, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,950, 550,300, 500,300, 500,1000, 550,250, 550,300, 550,950, 550,1000, 500,300, 550,250, 550,250, 600,250, 500,300, 550,250, 550,1000, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,950, 550,300, 500,1000, 550,950, 550,1000, 500,300, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,250, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,950, 500,1050, 500,1000, 500,350, 500,1000, 500,1000, 500,1050, 500,300, 500}; //Change it for your remote void setup() { BT_module.begin(9600); //BT works on 9600 Serial.begin(57600); //Serial Monitor work son 57600 } void loop() { while (BT_module.available()) //If data is coming { BluetoothData=BT_module.read(); //read it and save it Serial.println(BluetoothData); //print it on serial for testing purpose } if (BluetoothData != PevData) { if (BluetoothData == '0') { irsend.sendRaw(ACon, sizeof(ACon) / sizeof(ACon[0]), khz); delay(2000);//Send signal to Turn On the AC } if (BluetoothData == '1') { irsend.sendRaw(ACoff, sizeof(ACoff) / sizeof(ACoff[0]), khz); delay(2000);//Send signal to Turn on the AC } if (BluetoothData == '2') { irsend.sendRaw(Temp23, sizeof(Temp23) / sizeof(Temp23[0]), khz); delay(2000);//Send signal to set Temperatue 23C } if (BluetoothData == '3') { irsend.sendRaw(Temp24, sizeof(Temp24) / sizeof(Temp24[0]), khz); delay(2000);//Send signal to set Temperatue 24C } if (BluetoothData == '4') { irsend.sendRaw(Temp25, sizeof(Temp25) / sizeof(Temp25[0]), khz); delay(2000);//Send signal to set Temperatue 25C } if (BluetoothData == '5') { irsend.sendRaw(Temp26, sizeof(Temp23) / sizeof(Temp26[0]), khz); delay(2000);//Send signal to set Temperatue 26C } if (BluetoothData == '6') { irsend.sendRaw(Temp27, sizeof(Temp27) / sizeof(Temp27[0]), khz); delay(2000);//Send signal to set Temperatue 27C } if (BluetoothData == '7') { irsend.sendRaw(Temp28, sizeof(Temp28) / sizeof(Temp28[0]), khz); delay(2000);//Send signal to set Temperatue 28C } if (BluetoothData == '8') { irsend.sendRaw(Temp29, sizeof(Temp29) / sizeof(Temp29[0]), khz); delay(2000);//Send signal to set Temperatue 29C } if (BluetoothData == '9') { irsend.sendRaw(Temp30, sizeof(Temp30) / sizeof(Temp30[0]), khz); delay(2000);//Send signal to set Temperatue 30C } } PevData = BluetoothData; delay(100);// prepare for next data ... } Video microcontroller-projects/arduino-hall-effect-sensor

Interfacing Hall Effect Sensor with Arduino

This sensor is capable of detecting a magnet and also the pole of the magnet. : DIY Speedometer using Arduino and Processing Android App Digital Speedometer and Odometer Circuit using PIC Microcontroller Virtual Reality using Arduino and Processing Magnetic Field Strength Measurement using Arduino In this tutorial we will use interrupts function of Arduino to detect the magnet near Hall sensor and glow a LED. Most of the time Hall sensor will be used only with Interrupts because of their applications in which high reading and executing speed is required, hence let us also use interrupts in our tutorial.

Materials Required:

Hall Effect Sensor (A3144, or any other digital version) Arduino (Any version) 10k ohm and 1K ohm Resistor LED Connecting Wires

Hall Effect Sensors:

The digital Hall sensor can only detect if a magnet is present or not (0 or 1) but an analog hall sensor’s output varies based on the magnetic field around the magnet that is it can detect how strong or how far the magnet is. In this project will aim only at the digital Hall sensors for they are the most commonly used ones. According to this law “when a conductor or semiconductor with current flowing in one direction was introduced perpendicular to a magnetic field a voltage could be measured at right angles to the current pathᾮ Using this technique, the hall sensor will be able to detect the presence of magnet around it. Enough of theory let’s get into hardware.

Arduino Hall Effect Sensor Circuit Connectionsand Explanation:

can be found below. is pretty simple. But, the place where we commonly make mistakes is at figuring out the pin numbers of hall sensors. Place the readings facing you and the first pin on your left is the Vcc and then Ground and Signal respectively. We are going to use Interrupts as told earlier, hence the output pin of Hall sensor is connected to the Pin 2 of the Arduino. The Pin is connected to a LED which will be turned ON when a magnet is detected. I have simply made the connections on a breadboard and it looked somewhat like this below once completed.

Arduino Hall Effect SensorCode:

is just few lines and it can be found at the bottom of this page which can be directly uploaded to your Arduino Board. If you want to know how the program works read further. void setup() { pinMode(LED, OUTPUT); //LED is a output pin pinMode(Hall_sensor, INPUT_PULLUP); //Hall sensor is input pin attachInterrupt(digitalPinToInterrupt(Hall_sensor), toggle, CHANGE); //Pin two is interrupt pin which will call toggle function } etc. but in this tutorial we are detecting the change of output from Hall sensor. ᾠwhich will just change its state to 0 if already 1 and to 1 if already zero. This way we can make the LED turn ON or Turn OFF. void toggle() { state = !state; } function, we just have to control the LED. The variable state will be altered each time a magnet is detected hence we use it to determine if the LED should stay on or off. void loop() { digitalWrite(LED, state); }

Arduino Hall Effect Sensor Working:

Once you are ready with your Hardware and Code, just upload the Code to the Arduino. I have used a 9V battery to power the whole set-up you can use any preferable power source. Now bring the magnet close to the sensor and your LED will glow and if you take it away it will turn off. Hall sensor is Pole sensitive, meaning one side of the sensor can either detect only North Pole or only South Pole and not both. So if you bring a south pole close to the north sensing surface your LED will not glow. What actually happens inside is, when we bring the magnet close to sensor the sensor changes its state. This change is sensed by the interrupt pin which will call the toggle function inside which we change the variable “stateᾠfrom 0 to 1. Hence the LED will turn on. Now, when we move the magnet away from the sensor, again the output of sensor will change. This change is again noticed by our interrupt statement and hence the variable “stateᾠwill be changed from 1 to 0. Thus the LED if Turned off. The same repeats every time you bring a magnet close to the sensor. of the Arduino hall effect sensor project can be found below. Hope you understood the project and enjoyed building something new. If otherwise kindly use the comment section below or the forums for help. Code const byte ledPin = 13; const byte interruptPin = 2; volatile byte state = LOW; int val=0; void setup() { pinMode(ledPin, OUTPUT); pinMode(interruptPin, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(interruptPin), test, CHANGE); Serial.begin(9600); } void loop() { digitalWrite(ledPin, state); Serial.println(val/2); } void test() { state = !state; val++; } Video microcontroller-projects/arduino-automatic-ac-temperature-control

Automatic AC Temperature Controller using Arduino, DHT11 and IR Blaster

By varying the set temperature periodically we can avoid making the AC to work for lower temperature values for a long time and thus making it consume less power. will also adjust your AC’s set temperature to maintain your temperature in just the way you want it to be. Sounds cool right?... Let’s see how to build one.

Materials Required:

Arduino Mega 2560 TSOP1738 (HS0038) IR Led DHT11 Temperature/Humidity Sensor Any Colour LED and 1K Resistor(optional) Breadboard Connecting Wires

Working Methodology:

is an IR Receiver that could be used to decode the signal coming from the Remotes. This Receiver will be interfaced with Arduino to signal for each button and then an IR Led will be used with Arduino to mimic the signal when ever required. This way we can gain control over our AC using Arduino.

Pre-requisites:

is slightly advanced for beginner’s level, however with help of few other tutorials anyone can build this with matter of time. So if you are a absolute newbie to OLED, DHT11 or TSOP then kindly fall back to these tutorials below where you can learn the basics and how to get started with these. The list might seem to be bit long, but trust me it’s easy and worth learning, also it will open doors to many new projects. Basic circuit using TSOP and IR LED to under their working Basic interfacing guide for DHT11 with Arduino Basic interfacing guide for OLED with Arduino Interfacing TSOP with Arduino to Read IR remote values and any other version of Arduino, since the code size is heavy. Also check if you have already installed the following Arduino libraries if not install them form the link below IR Remote Library for TSOP and IR Blaster Adafruit Library for OLED GFX Graphics Library for OLED DHT11 Sensor Library for Temperature sensor

Working of an AC Remote:

There might be only 10-12 buttons on your Remote, but they will be able to send a lot of different types of signals. Meaning the Remote does not send the same code every time for the same button. For example, when you decrease the temperature using the down button to make it 24°C (degree Celsius) you will get a signal with a set of data, but when you press it again to set 25°C you will not get the same data since the temperature is now 25 and not 24. Similarly the code for 25 will also vary for different fan speed, sleep settings etc. So let’s not fiddle around with all options and just concentrate only the temperature values with a constant value for other settings. since each signal contains a lot of information like Temp, Fan Speed, Sleep timing, Swing style etc. This is the reason why we need an Arduino Mega for better storage options.

Circuit Diagram and Explanation:

is very easy. You can simply use a breadboard and make the connections as shown below. The following table can also be used to verify your connections.
1OLED ᾠVcc5V
2OLED ᾠGndGnd
3OLED- SCK, D0,SCL,CLK4
4OLED- SDA, D1,MOSI, Data3
5OLED- RES, RST,RESET7
6OLED- DC, A05
7OLED- CS, Chip Select6
8DHT11 ᾠVcc5V
9DHT11 ᾠGndGnd
10DHT11 ᾠSignal13
11TSOP ᾠVcc5V
12TSOP ᾠGndGnd
13IR Led ᾠAnode9
14IR Led ᾠCathodeGnd
Once you connections are done it should look something like this shown below. I have used a Breadboard to tidy things, but you can also you Male to female wires directly to hook up all components

Decoding your AC Remote Signals:

Upload the program to your Arduino Mega and open the Serial Monitor. , for each button you press its respective Signal will be read by the TSOP1738, decoded by Arduino and displayed in the Serial Monitor. For every change in temperature on your Remote you will get a different Data. Save this Data for we will be using it in our main program. Your serial monitor will look something like this, I have also shown the Word file on which I have saved the copied data. given at the end of this tutorial.

Main Arduino Program:

can be found at the bottom of this page, but you cannot use the same program. You have to change the Signal code values that we just obtained from the Example sketch above. Open the main program on you Arduino IDE and scroll down to this area shown below where you have to replace the array values with the values that you obtained for your Remote. out of which two used to Turn ON and turn OFF the AC while the rest 8 is used to set different temperature. For example Temp23 is used to set 23°C on your AC, so use the respective code in that Array. Once that is done, you just have to upload the code to your Arduino and Place it opposite of you AC and enjoy the Cool Breeze. and display it on the OLED. This is done by the following code. DHT.read11(DHT11_PIN); //Read the Temp and Humidity Measured_temp = DHT.temperature + temp_error; Measured_Humi = DHT.humidity; // text display tests display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(0,0); display.print("Temperature: "); display.print(Measured_temp);display.println("C"); display.setCursor(0,10); display.print("Humidity: "); display.print(Measured_Humi);display.println("%"); This desired value is a constant value which is set as 27°C (Degree Celsius) in my program. So based on this comparison we will set a corresponding AC temperature as shown below if (Measured_temp == Desired_temperature+3) //If AC is ON and measured temp is very high than desired { irsend.sendRaw(Temp24, sizeof(Temp24) / sizeof(Temp24[0]), khz); delay(2000);//Send signal to set 24*C AC_Temp = 24; } loops to set different level of temperatures based on the measured temperature as shown below. if (Measured_temp == Desired_temperature-1) //If AC is ON and measured temp is low than desired value { irsend.sendRaw(Temp28, sizeof(Temp28) / sizeof(Temp28[0]), khz); delay(2000);//Send signal to set 28*C AC_Temp = 28; } if (Measured_temp == Desired_temperature-2 ) //If AC is ON and measured temp is very low than desired value { irsend.sendRaw(Temp29, sizeof(Temp29) / sizeof(Temp29[0]), khz); delay(2000);//Send signal to set 29*C AC_Temp = 29; } if (Measured_temp == Desired_temperature-3 ) //If AC is ON and measured temp is very very low desired value { irsend.sendRaw(Temp30, sizeof(Temp30) / sizeof(Temp30[0]), khz); delay(2000);//Send signal to set 30*C AC_Temp = 30; }

Working of Automatic AC Temperature Control System:

When your Code and hardware is ready, Upload the Code to your Board and you should notice the OLED displaying something similar to this. project and enjoyed building something very similar. I know there are lot of places here to get stuck, but don’t worry then. Just use the forum or comment section to explain your problem and people here will surely help you to get it solved. Code /* * Automatic AC Temperature control using Arduino and TSOP * Code by: Aswinth Raj B * Dated: 25-10-2017 * Website: www.circuitdigest.com * S.No: Component Pin Arduino Pin 1 OLED ᾠVcc 5V 2 OLED ᾠGnd Gnd 3 OLED- SCK, D0,SCL,CLK 4 4 OLED- SDA, D1,MOSI, Data 3 5 OLED- RES, RST,RESET 7 6 OLED- DC, A0 5 7 OLED- CS, Chip Select 6 8 DHT11 ᾠVcc 5V 9 DHT11 ᾠGnd Gnd 10 DHT11 ᾠSignal 13 11 TSOP ᾠVcc 5V 12 TSOP ᾠGnd Gnd 13 IR Led ᾠAnode 9 14 IR Led ᾠCathode Gnd */ #include <IRremote.h> //Lib for IT Blaster and TSOP #include <SPI.h> // Inbuilt Lib #include <Wire.h> //Inbuilt Lib #include <Adafruit_GFX.h> //Lib for OLED #include <Adafruit_SSD1306.h> //Lib for OLED #include <dht.h> //Library for dht11 Temperature and Humidity sensor (Download from Link in article) // Assign pins for OLED (Software config.) #define OLED_MOSI 3 #define OLED_CLK 4 #define OLED_DC 5 #define OLED_CS 6 #define OLED_RESET 7 Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS); #define SSD1306_LCDHEIGHT 64 //Change if you are using a Different OLED #define DHT11_PIN 13 //Sensor output pin is connected to pin 13 dht DHT; //Sensor object named as DHT #define Desired_temperature 27 //The desired temperature is 27*C at any time //Decoded Remote Signals For my AC ##CHANGE IT FOR YOUR REMOTE unsigned int ACoff[] = {2950,1750, 400,1100, 450,1050, 450,400, 400,400, 400,400, 450,1100, 400,400, 400,400, 450,1100, 400,1100, 450,350, 450,1100, 400,400, 400,400, 450,1100, 400,1100, 450,400, 400,1100, 400,1100, 450,400, 400,400, 400,1100, 450,350, 450,400, 400,1100, 450,400, 400,400, 400,400, 450,350, 450,350, 450,400, 400,400, 450,350, 450,400, 400,400, 400,400, 450,350, 450,400, 400,400, 400,400, 450,400, 400,400, 400,400, 450,350, 450,350, 450,1100, 400,400, 450,400, 400,1100, 450,1050, 450,400, 400,400, 400,400, 450,350, 450,400, 400,400, 450,350, 450,400, 400,400, 400,1100, 450,350, 450,400, 400,400, 400,400, 450,400, 400,1100, 450,350, 450,400, 400,400, 400,400, 400,1100, 450,400, 400,400, 450,350, 450,400, 400,400, 400,400, 450,350, 450,350, 450,400, 400,400, 450,350, 450,400, 400,400, 400,400, 450,350, 450,400, 400,400, 450,350, 450,400, 400,400, 400,400, 450,350, 450,350, 450,400, 450,350, 450,350, 450,400, 450,350, 450,350, 450,350, 450,400, 450,350, 450,350, 450,400, 400,1100, 450,350, 450,350, 450,400, 450,350, 450,350, 450,1100, 450}; unsigned int ACon[] = {2950,1700, 450,1100, 400,1100, 450,350, 450,350, 450,400, 450,1050, 450,350, 450,400, 450,1050, 450,1100, 400,400, 450,1050, 450,350, 450,400, 400,1100, 450,1100, 450,350, 450,1050, 450,1100, 450,350, 450,350, 450,1100, 450,350, 400,400, 450,1100, 450,350, 450,350, 450,400, 400,400, 450,350, 450,350, 450,400, 400,400, 450,350, 450,350, 450,400, 400,400, 450,350, 450,350, 450,400, 450,350, 450,350, 450,1100, 400,400, 450,350, 450,1100, 400,400, 450,350, 450,1100, 400,1100, 450,350, 450,400, 400,400, 450,350, 500,300, 450,400, 450,350, 400,400, 450,1100, 400,400, 450,350, 450,350, 450,400, 400,400, 450,350, 450,1100, 450,350, 400,400, 450,350, 450,400, 450,350, 400,400, 450,400, 450,350, 450,350, 450,350, 450,400, 400,400, 450,350, 450,400, 400,400, 400,400, 400,400, 450,350, 450,400, 450,350, 450,350, 450,400, 450,350, 450,350, 450,350, 450,400, 400,400, 400,400, 450,350, 450,400, 450,350, 400,400, 450,350, 450,400, 450,350, 450,350, 450,350, 450,400, 450,350, 450,1100, 400,400, 400,400, 450,350, 450,350, 450,1100, 400,400, 450}; unsigned int Temp23[] = {3000,1650, 550,950, 550,1000, 500,300, 550,250, 550,250, 550,1000, 500,300, 550,300, 500,1000, 550,950, 550,300, 550,950, 550,250, 550,300, 500,1000, 500,1050, 500,300, 500,1000, 550,1000, 500,300, 500,300, 550,1000, 450,350, 500,300, 500,1050, 450,350, 450,350, 450,350, 450,400, 450,350, 450,350, 450,400, 400,400, 450,350, 450,350, 450,350, 450,400, 400,400, 400,400, 450,400, 400,400, 400,400, 450,1100, 400,400, 400,400, 450,1050, 450,400, 400,400, 450,1100, 400,1100, 400,400, 450,350, 450,400, 400,400, 400,400, 450,400, 400,400, 400,400, 450,350, 450,1100, 400,400, 400,400, 450,350, 450,400, 400,400, 450,1100, 400,400, 400,1100, 450,1100, 400,1100, 450,350, 450,400, 400,400, 450,350, 450,350, 450,400, 400,400, 400,400, 450,350, 450,400, 400,400, 450,350, 450,400, 400,400, 400,400, 450,350, 450,400, 400,400, 450,350, 450,350, 450,400, 450,350, 400,400, 450,350, 450,400, 450,350, 450,350, 450,400, 450,350, 450,350, 450,350, 450,400, 400,400, 400,400, 450,350, 450,1100, 400,1100, 450,1100, 400,1100, 450,1100, 400,1100, 400,400, 450}; unsigned int Temp24[] = {3000,1650, 500,1050, 500,1000, 500,300, 500,300, 500,350, 500,1000, 500,300, 500,350, 500,1000, 500,1050, 500,300, 500,1000, 500,300, 500,350, 500,1000, 500,1050, 500,300, 500,1000, 500,1050, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,1050, 500,1000, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,1000, 500,1050, 500,1000, 500,300, 500,350, 450,350, 500,300, 500,300, 500,350, 500,1000, 500,300, 500,1050, 500,1000, 500,1050, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,300, 500,350, 500,300, 450,350, 500,350, 450,350, 450,350, 450,350, 450,400, 400,400, 400,400, 450,400, 400,400, 400,400, 400,400, 450,350, 450,400, 400,400, 450,350, 450,400, 450,350, 450,350, 450,350, 450,400, 450,350, 450,350, 450,350, 500,350, 450,1050, 500,300, 500,1050, 500,1000, 500,1050, 500,1000, 500,1000, 500,350, 550}; unsigned int Temp25[] = {3050,1650, 500,1000, 550,950, 550,300, 500,300, 500,300, 550,1000, 500,300, 500,300, 550,1000, 550,950, 550,250, 550,1000, 500,300, 550,250, 550,1000, 500,1000, 550,300, 550,950, 550,950, 550,300, 500,300, 500,1000, 550,250, 550,300, 550,950, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,250, 600,250, 500,300, 550,250, 550,250, 550,300, 550,250, 500,300, 550,300, 500,300, 500,1000, 550,250, 550,300, 500,1000, 550,250, 550,300, 500,1000, 550,1000, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,1000, 550,950, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,950, 550,300, 500,1000, 550,1000, 500,1000, 500,300, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,250, 550,300, 550,250, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 500,350, 500,1000, 500,1000, 500,1050, 500,1000, 500,1050, 500,300, 550}; unsigned int Temp26[] = {3000,1650, 500,1000, 500,1050, 500,300, 500,300, 500,350, 500,1000, 500,300, 500,350, 500,1000, 500,1050, 450,350, 500,1000, 500,300, 500,350, 500,1000, 500,1050, 500,300, 500,1000, 500,1050, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,1050, 500,300, 500,300, 500,1050, 450,350, 500,300, 500,1050, 500,1000, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,1000, 500,300, 500,1050, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,1050, 500,300, 500,1050, 450,1050, 500,1000, 500,350, 500,300, 500,300, 500,350, 450,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 450,350, 500,300, 500,350, 450,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,350, 500,300, 500,300, 500,300, 500,350, 500,300, 500,300, 500,350, 450,1050, 500,1000, 500,350, 500,1000, 500,1000, 500,1050, 500,1000, 500,350, 500}; unsigned int Temp27[] = {3050,1600, 550,1000, 500,1000, 550,300, 500,300, 550,250, 550,1000, 500,300, 550,300, 500,1000, 550,1000, 500,300, 550,1000, 550,250, 500,300, 550,1000, 500,1050, 500,300, 500,1000, 550,1000, 500,300, 550,250, 550,1000, 550,250, 550,300, 500,1000, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,300, 500,300, 500,1000, 550,300, 500,300, 550,1000, 500,300, 500,300, 550,1000, 550,1000, 500,300, 500,300, 550,250, 550,300, 500,300, 550,300, 500,300, 500,300, 550,1000, 500,300, 550,250, 550,300, 500,300, 500,300, 500,350, 500,300, 550,250, 550,1000, 500,1000, 550,1000, 500,300, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 500,300, 550,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 500,300, 500,350, 500,300, 500,350, 500,300, 500,300, 500,1050, 500,1000, 500,1050, 500,1000, 500,350, 500}; // PANASONIC C4D3:64800024 unsigned int Temp28[] = {3100,1600, 550,950, 550,1000, 550,250, 550,250, 550,250, 550,1000, 500,300, 500,300, 550,1000, 500,1000, 550,250, 550,1000, 500,300, 550,250, 550,1000, 550,950, 550,300, 500,1000, 550,950, 550,300, 550,250, 500,1000, 550,300, 500,300, 550,950, 550,300, 500,300, 500,300, 550,250, 550,300, 550,250, 500,300, 550,300, 500,300, 500,300, 550,250, 550,250, 600,250, 500,300, 500,300, 550,300, 500,300, 500,1000, 550,300, 500,300, 500,1000, 550,250, 550,300, 500,1000, 550,1000, 550,250, 550,250, 550,250, 550,300, 500,300, 550,250, 550,1000, 500,1000, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,1000, 500,300, 500,1000, 550,1000, 500,1000, 550,250, 550,300, 500,300, 550,250, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,300, 550,250, 500,300, 550,250, 550,250, 550,300, 550,250, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,250, 550,300, 500,300, 550,1000, 500,300, 500,300, 550,950, 550,1000, 500,1000, 550,1000, 500,300, 550}; unsigned int Temp29[] = {3100,1550, 600,950, 500,1000, 550,300, 500,300, 500,300, 550,950, 550,300, 550,250, 550,1000, 500,1000, 550,250, 550,1000, 500,300, 550,250, 550,950, 600,950, 550,250, 550,1000, 500,1000, 550,250, 600,250, 550,950, 550,250, 550,300, 550,950, 550,250, 550,300, 550,250, 550,250, 550,250, 550,300, 550,250, 550,250, 550,300, 500,300, 550,250, 550,250, 550,300, 500,300, 550,250, 550,250, 600,250, 550,950, 550,250, 550,300, 500,1000, 550,250, 550,300, 550,950, 550,1000, 500,300, 500,300, 550,250, 550,250, 550,300, 500,300, 550,250, 550,1000, 500,300, 550,250, 550,300, 500,300, 550,250, 550,250, 550,300, 500,1000, 550,250, 550,1000, 500,1000, 550,1000, 500,300, 500,300, 550,300, 500,300, 500,300, 550,250, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,250, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,250, 550,1000, 500,1000, 550,1000, 500,1000, 550,300, 500}; unsigned int Temp30[] = {3000,1650, 500,1000, 550,1000, 500,300, 500,300, 550,250, 550,1000, 500,300, 500,300, 550,1000, 550,950, 550,250, 550,1000, 550,250, 550,250, 550,1000, 550,950, 550,300, 500,1000, 550,950, 550,300, 500,300, 550,950, 550,300, 550,250, 550,1000, 500,300, 500,300, 550,250, 550,250, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,300, 500,300, 500,300, 550,950, 550,300, 500,300, 500,1000, 550,250, 550,300, 550,950, 550,1000, 500,300, 550,250, 550,250, 600,250, 500,300, 550,250, 550,1000, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,950, 550,300, 500,1000, 550,950, 550,1000, 500,300, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,250, 550,300, 500,300, 550,250, 550,300, 500,300, 500,300, 550,250, 550,300, 500,300, 550,950, 500,1050, 500,1000, 500,350, 500,1000, 500,1000, 500,1050, 500,300, 500}; //Change it for your remote IRsend irsend; int Measured_temp; int Measured_Humi; int AC_Temp; char temp_error = 2; int Pev_value; boolean AC = false; int khz = 38; // 38kHz carrier frequency for the NEC protocol void setup() { Serial.begin(9600); display.begin(SSD1306_SWITCHCAPVCC); display.clearDisplay(); } void loop() { DHT.read11(DHT11_PIN); //Read the Temp and Humidity Measured_temp = DHT.temperature + temp_error; Measured_Humi = DHT.humidity; // text display tests display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(0,0); display.print("Temperature: "); display.print(Measured_temp);display.println("C"); display.setCursor(0,10); display.print("Humidity: "); display.print(Measured_Humi);display.println("%"); display.setCursor(0,20); display.print("AC Temp: "); display.print(AC_Temp);display.println("C"); display.display(); delay(500); display.clearDisplay(); if ((Measured_temp <= (Desired_temperature-3)) && AC == true) //If AC is turned on and temperature is less than 3 degree of Desired value #24 turn off { irsend.sendRaw(ACoff, sizeof(ACoff) / sizeof(ACoff[0]), khz); delay(2000);//Send signal to Turn Off the AC AC_Temp = 0; AC=false; } if ((Measured_temp >= Desired_temperature+4) && AC == false) //If AC is off and measured Temp is greater than Desired Temp { irsend.sendRaw(ACon, sizeof(ACon) / sizeof(ACon[0]), khz); delay(2000); //Send Signal to Turn On the AC delay(2000); irsend.sendRaw(Temp27, sizeof(Temp27) / sizeof(Temp27[0]), khz); //Send signal to set 27*C AC_Temp = 27; AC=true; } if ( Measured_temp != Pev_value) //Change the temperature only if the measured voltage value changes { if (Measured_temp == Desired_temperature+3) //If AC is ON and measured temp is very very high than desired { irsend.sendRaw(Temp24, sizeof(Temp24) / sizeof(Temp24[0]), khz); delay(2000);//Send signal to set 24*C AC_Temp = 24; } if (Measured_temp == Desired_temperature+2) //If AC is ON and measured temp is very high than desired { irsend.sendRaw(Temp25, sizeof(Temp25) / sizeof(Temp25[0]), khz); delay(2000);//Send signal to set 25*C AC_Temp = 25; } if (Measured_temp == Desired_temperature+1) //If AC is ON and measured temp is very high than desired { irsend.sendRaw(Temp26, sizeof(Temp26) / sizeof(Temp26[0]), khz); delay(2000);//Send signal to set 26*C AC_Temp = 26; } if (Measured_temp == 27 ) //If AC is ON and measured temp is desired value { irsend.sendRaw(Temp27, sizeof(Temp27) / sizeof(Temp27[0]), khz); //Send signal to set 27*C AC_Temp = 27; } if (Measured_temp == Desired_temperature-1) //If AC is ON and measured temp is low than desired value { irsend.sendRaw(Temp28, sizeof(Temp28) / sizeof(Temp28[0]), khz); delay(2000);//Send signal to set 28*C AC_Temp = 28; } if (Measured_temp == Desired_temperature-2 ) //If AC is ON and measured temp is very low than desired value { irsend.sendRaw(Temp29, sizeof(Temp29) / sizeof(Temp29[0]), khz); delay(2000);//Send signal to set 29*C AC_Temp = 29; } if (Measured_temp == Desired_temperature-3 ) //If AC is ON and measured temp is very very low desired value { irsend.sendRaw(Temp30, sizeof(Temp30) / sizeof(Temp30[0]), khz); delay(2000);//Send signal to set 30*C AC_Temp = 30; } } Pev_value = Measured_temp; } Video microcontroller-projects/arduino-dc-motor-speed-direction-control

Arduino DC Motor Speed and Direction Control using Relays and MOSFET

Required Components:

Arduino Uno Two 12v relay( 5v relay can also be used) Two transistors; BC547 Two pushbuttons IRF540N 10k resistor 24 volt source 10K potentiometer Three diodes 1N4007 Connecting wires

Circuit Diagram and Explanations:

is shown in image below. Make the connections according to it: Connect normally closed terminal of both relays to positive terminal of battery. Connect normally open terminal of both relay to drain terminal of MOSFET. Connect source of MOSFET to negative terminal of battery and to Ground pin of Arduino UNO. Gate terminal to PWM pin 6 of Arduino. Connect 10k resistor from gate to source and 1N4007 diode from source to drain. Connect motor in between the middle terminal of relays. Out of two remaining terminals, one goes to the Vin pin of Arduino Uno and other to the collector terminal of transistor (for each relay). Connect emitter terminal of both transistor to GND pin of Arduino. Digital pin 2 and 3 of Arduino, each one in series with pushbutton, goes to base of transistors. Connect diode across relay exactly as shown in figure. Connect Potentiometer's end terminal to 5v pin and Gnd pin of Arduino respectively. And wiper terminal to A0 pin. ** if you have two separate 12 v battery then connect one battery’s positive terminal to the negative terminal of another battery and use remaining two terminals as positive and negative. Digital pins of Arduino cannot supply the amount of current needed to turn on a normal 5v relay. Besides we are using 12v relay in this project. Vin pin of Arduino cannot easily supply this much current for both relay. Hence transistors are used to conduct current from Vin pin of Arduino to relay which is controlled using a push-button connected from digital pin to base terminal of transistor. To provide the amount of current required to turn on relay. To turn on transistor. To control the Speed of DC Motors with Potentiometer using Programming. Check the complete Arduino Code at the end. MOSFET is required to control the speed of motor. MOSFET is switched on and off at high frequency voltage and since motor is connected in series with the drain of MOSFET, PWM value of voltage determines the speed of motor.

Current Calculations:

which turn out to be = 400 ohms Vin pin of Arduino gives = 12v So current need to turn on the relay = 12/400 Amps = 30 mA If both relays are energized, current= 30*2=60 mA **Vin pin of Arduino can supply maximum current = 200mA. Thus there is no over current problem in Arduino.

Working of Arduino Controlled Bi-directional Motor:

is simple. Both pins( 2 , 3 ) of Arduino will remain always high. In this case no current flows to the base of transistor, hence transistor remains off ( acts like an open switch) due to which no current flows to relay coil from Vin pin of Arduino. of motor. of motor In this case current flows to the base of both transistors due to which both transistor turns on (acts like an closed switch). And thus both relay is now in NO position. So current do not flow from positive terminal of battery to negative terminal through motor and thus it does not rotate. Gate of MOSFET is connected to PWM pin 6 of Arduino UNO. Mosfet is switched on and off at high PWM frequency voltage and since motor is connected in series with the drain of mosfet, PWM value of voltage determines the speed of motor. Now the voltage between the wiper terminal of potentiometer and Gnd determines the PWM voltage at pin no 6 and as wiper terminal is rotated, voltage at analog pin A0 changes causing change in speed of motor. Code int x; int y; void setup() { pinMode(2,OUTPUT); pinMode(3,OUTPUT); pinMode(6,OUTPUT); pinMode(A0,INPUT); } void loop() { x=analogRead(A0); y=map(x,0,1023,0,255); analogWrite(6,y); digitalWrite(2,HIGH); digitalWrite(3,HIGH); } Video microcontroller-projects/control-your-computer-with-hand-gestures

Control your Computer with Hand Gestures using Arduino

I have used this for demonstration, but once you have understood the project, you can do anything by just changing few lines of code and control your favorite application in your favorite way.

Pre-requisites:

tutorial and get along with it. So make sure you have installed Python and pyserial library before proceeding.

Concept behind the project:

library. The commands from Arduino are sent to the computer through serial port (USB). This data will be then read by python which is running on the computer and based on the read data an action will be performed.

Circuit Diagram:

, just connect the two Ultrasonic sensors with Arduino. We know US sensor work with 5V and hence they are powered by the on board Voltage regulator of Arduino. The Arduino can be connected to the PC/Laptop for powering the module and also for Serial communication. Once the connections are done place them on your monitor as shown below. I have used a double side tape to stick it on my monitor but you can use your own creativity. After securing it in a place we can proceed with the Programming.

Programming your Arduino:

as a demo. When both the hands are placed up before the sensor at a particular far distance then the video in VLC player should Play/Pause. When right hand is placed up before the sensor at a particular far distance then the video should Fast Forward one step. When left hand is placed up before the sensor at a particular far distance then the video should Rewind one step. When right hand is placed up before the sensor at a particular near distance and then if moved towards the sensor the video should fast forward and if moved away the video should Rewind. When left hand is placed up before the sensor at a particular near distance and then if moved towards the sensor the volume of video should increase and if moved away the volume should Decrease. as shown below. The two US sensors are connected to Digital pins 2,3,4 and 5 and are powered by +5V pin. The trigger pins are output pin and Echo pins are input pins. The Serial communication between Arduino and python takes places at a baud rate of 9600. const int trigger1 = 2; //Trigger pin of 1st Sesnor const int echo1 = 3; //Echo pin of 1st Sesnor const int trigger2 = 4; //Trigger pin of 2nd Sesnor const int echo2 = 5;//Echo pin of 2nd Sesnor void setup() { Serial.begin(9600); pinMode(trigger1, OUTPUT); pinMode(echo1, INPUT); pinMode(trigger2, OUTPUT); pinMode(echo2, INPUT); } which will return us the distance between the sensor and the hand. /*###Function to calculate distance###*/ void calculate_distance(int trigger, int echo) { digitalWrite(trigger, LOW); delayMicroseconds(2); digitalWrite(trigger, HIGH); delayMicroseconds(10); digitalWrite(trigger, LOW); time_taken = pulseIn(echo, HIGH); dist= time_taken*0.034/2; if (dist>50) dist = 50; } which gets updated with current distance value. calculate_distance(trigger1,echo1); distL =dist; //get distance of left sensor calculate_distance(trigger2,echo2); distR =dist; //get distance of right sensor will be sent out through serial port if ((distL >40 && distR>40) && (distL <50 && distR<50)) //Detect both hands {Serial.println("Play/Pause"); delay (500);} will be sent out through serial port if ((distL >40 && distL<50) && (distR ==50)) //Detect Left Hand {Serial.println("Rewind"); delay (500);} if ((distR >40 && distR<50) && (distL ==50)) //Detect Right Hand {Serial.println("Forward"); delay (500);} we have to place the left hand approx. At a distance of 15 cm , then you can either move it towards the sensor to decrease the volume of move it away from the sensor to increase the volume. The code for the same is shown below. Based on the action, here the word “Vupᾠor “Vdownᾠwill be sent out through serial port //Lock Left - Control Mode if (distL>=13 && distL<=17) { delay(100); //Hand Hold Time calculate_distance(trigger1,echo1); distL =dist; if (distL>=13 && distL<=17) { Serial.println("Left Locked"); while(distL<=40) { calculate_distance(trigger1,echo1); distL =dist; if (distL<10) //Hand pushed in {Serial.println ("Vup"); delay (300);} if (distL>20) //Hand pulled out {Serial.println ("Vdown"); delay (300);} } } } That is if we move the right hand towards the sensor it will fast forward the movie and if you move it away from the sensor it will rewind the movie. Based on the action, here the word “Rewindᾠor “Forwardᾠwill be sent out through serial port and try understating it as an whole and then copy it to your Arduino IDE.

Programming your Python:

for windows. If you are using other platforms the steps will also be more or less similar. Make sure your computer/Laptop is connected to internet and proceed with steps below Open Windows Command prompt and change the directory to the folder where you have installed python. By default the command should be cd C:\Python27 to upgrade your pip. Pip is a tool in python which helps us to install python modules easily. Once this module is upgraded (as shown in picture below) proceed to next step. python –m pip install –upgrade pip ᾠto install the pyautogui module. Once the process is successful you should see a screen something similar to this below. python –m pip install –upgrade pip but the explanation for the same is as follows. Let us import all the three required modules for this project. They are pyautogui, serial python and time. import serial #Serial imported for Serial communication import time #Required to use delay functions import pyautogui In my computer the Arduino is connected to COM 18. Use device manager to find to which COM port your Arduino is connected to and correct the following line accordingly. ArduinoSerial = serial.Serial('com18',9600) #Create Serial port object called arduinoSerialData time.sleep(2) #wait for 2 seconds for the communication to get established and make key board presses accordingly. while 1: incoming = str (ArduinoSerial.readline()) #read the serial data and print it as line print incoming if 'Play/Pause' in incoming: pyautogui.typewrite(['space'], 0.2) if 'Rewind' in incoming: pyautogui.hotkey('ctrl', 'left') if 'Forward' in incoming: pyautogui.hotkey('ctrl', 'right') if 'Vup' in incoming: pyautogui.hotkey('ctrl', 'down') if 'Vdown' in incoming: pyautogui.hotkey('ctrl', 'up')

Gesture Controlled Computer in Action:

Make the connections as defined above and upload the Arduino code on your Arduino board. Then use the python script below and launch the program on your laptop/computer. below. Hope you understood the project and enjoyed playing with it. This is just a demo and you can use your creativity to build a lot more cool gesture controlled stuff around this. Let me know if this was useful and what you will create using this in the comment section and I will be happy to know it. Code /* * Program for gesture control VLC Player * Controlled uisng Python * Code by B.Aswinth Raj * Dated: 11-10-2017 * Website: www.circuitdigest.com */ const int trigger1 = 2; //Trigger pin of 1st Sesnor const int echo1 = 3; //Echo pin of 1st Sesnor const int trigger2 = 4; //Trigger pin of 2nd Sesnor const int echo2 = 5;//Echo pin of 2nd Sesnor long time_taken; int dist,distL,distR; void setup() { Serial.begin(9600); pinMode(trigger1, OUTPUT); pinMode(echo1, INPUT); pinMode(trigger2, OUTPUT); pinMode(echo2, INPUT); } /*###Function to calculate distance###*/ void calculate_distance(int trigger, int echo) { digitalWrite(trigger, LOW); delayMicroseconds(2); digitalWrite(trigger, HIGH); delayMicroseconds(10); digitalWrite(trigger, LOW); time_taken = pulseIn(echo, HIGH); dist= time_taken*0.034/2; if (dist>50) dist = 50; } void loop() { //infinite loopy calculate_distance(trigger1,echo1); distL =dist; //get distance of left sensor calculate_distance(trigger2,echo2); distR =dist; //get distance of right sensor //Uncomment for debudding /*Serial.print("L="); Serial.println(distL); Serial.print("R="); Serial.println(distR); */ //Pause Modes -Hold if ((distL >40 && distR>40) && (distL <50 && distR<50)) //Detect both hands {Serial.println("Play/Pause"); delay (500);} calculate_distance(trigger1,echo1); distL =dist; calculate_distance(trigger2,echo2); distR =dist; //Control Modes //Lock Left - Control Mode if (distL>=13 && distL<=17) { delay(100); //Hand Hold Time calculate_distance(trigger1,echo1); distL =dist; if (distL>=13 && distL<=17) { Serial.println("Left Locked"); while(distL<=40) { calculate_distance(trigger1,echo1); distL =dist; if (distL<10) //Hand pushed in {Serial.println ("Vup"); delay (300);} if (distL>20) //Hand pulled out {Serial.println ("Vdown"); delay (300);} } } } //Lock Right - Control Mode if (distR>=13 && distR<=17) { delay(100); //Hand Hold Time calculate_distance(trigger2,echo2); distR =dist; if (distR>=13 && distR<=17) { Serial.println("Right Locked"); while(distR<=40) { calculate_distance(trigger2,echo2); distR =dist; if (distR<10) //Right hand pushed in {Serial.println ("Rewind"); delay (300);} if (distR>20) //Right hand pulled out {Serial.println ("Forward"); delay (300);} } } } delay(200); } import serial #Serial imported for Serial communication import time #Required to use delay functions import pyautogui ArduinoSerial = serial.Serial('com18',9600) #Create Serial port object called arduinoSerialData time.sleep(2) #wait for 2 seconds for the communication to get established while 1: incoming = str (ArduinoSerial.readline()) #read the serial data and print it as line print incoming if 'Play/Pause' in incoming: pyautogui.typewrite(['space'], 0.2) if 'Rewind' in incoming: pyautogui.hotkey('ctrl', 'left') if 'Forward' in incoming: pyautogui.hotkey('ctrl', 'right') if 'Vup' in incoming: pyautogui.hotkey('ctrl', 'down') if 'Vdown' in incoming: pyautogui.hotkey('ctrl', 'up') incoming = ""; Video microcontroller-projects/automatic-call-answering-machine-using-arduino

Automatic Call answering Machine using Arduino and GSM Module

In today’s modern world we all depend on mobile phones as our primary means of wireless communication. But, we all have faced situations during which we might not be able to answer to our calls, these calls might be an important personal call or a life changing business call and you could have just missed that opportunity since you were not able to answer that call at that particular time. Next time when you are changing to a new phone number or out for a long pilgrimage trip or enjoying a well deserved vacation just use this machine to record your voice stating the reason for absence and all your calls will be automatically answered by this machine and your recorded voice will be played to them. This can also be used for your business numbers to answer to your customer’s calls during non-office hours. Sounds interesting right? So let us build it..

Materials Required:

The project might sound a bit complicated but it is really easy to build, you just need the following components Arduino Uno GSM module ᾠFlyscale SIM 900 ISD 1820 Voice Module 12V adapter to power GSM module 9V battery to power Arduino Connecting wires Before we actually proceed into the project, let us get familiar with the GSM module and ISD 1820 Voice Module

Fly Scale SIM900 GSM Module:

are fascinating to use especially when our project requires remote access. These modules could make all actions that our normal mobile phone could do, like making/receiving a call, sending/receiving a SMS, connecting to internet using GPRS etc. You can also connect a normal microphone and speaker to this module and converse on your mobile calls. Here are some tutorials on them using different microcontroller: Call and Message using Arduino and GSM Module Call and Text using Raspberry Pi and GSM Module GSM module Interfacing with PIC Microcontroller - Make and Receive Calls through a normal DC barrel jack. Insert your SIM card in the slot of the module and power it on, you should notice a power LED going ON. Now wait for a minute or so, and you should see a red (or any other colour) LED Flashing once for every 3 seconds. This means that your Module was capable to establish connection with your SIM card. Now you can proceed with connecting you module with Phone or any Microcontroller.

ISD1820 Voice module:

and then playing it when required. The module itself comes with a microphone and a speaker (8ohms 0.5watts) and it should look something like this shown below. The PlayL will play the voice as long as you hold the button. When interfacing with a MCU, we can use the pins on the left. These pins are 3V-5V tolerable and hence can be directly driven by Arduino/ESP8266. In our project we are controlling the PLAYE pin using the D8 pin of our Arduino module. So that we can play the recorded voice when a call is detected and received by the GSM module.

Circuit Diagram and Explanation:

is given above. As you can see the connections are really simple. We power the GSM module with a 12V 1A adapter and Arduino with 9V battery, the ISD Voice module is powered by the +5V pin of the Arduino. As we know we can record anything on our voice module by pressing the rec button and this will get played when P-E is pressed, this audio has to be sent to the microphone of the GSM module. So we connect the speaker pin of the Voice module to the microphone pin of the GSM module. Here, the Arduino and GSM module is connect serially, the Tx pin of Arduino is connected to pin 9 and Rx pin is connected pin 10. This will help the Arduino to listen to the GSM module. When a call arrives to the GSM module the Arduino will listen to it and ask the GSM module to answer the call. The Arduino makes sure that the call is active and then plays the recorded voice message on the voice module by making the pin 8 (Connected to P-E of voice module) go high for 200ms.

Programming your Arduino:

of the project is given at the bottom of this page, further here I have spilt the code into small junks to explain it. because we are not using the default Rx and Tx pins of the Arduino to communicate with GSM module. #include <sim900.h> //download librarey from https://github.com/Seeed-Studio/GPRS_SIM900 #include <SoftwareSerial.h> //default librarey #include <Wire.h> //default library using the following line. This is made possible by the software serial library that we included above. SoftwareSerial gprs(9,10);//TX,RX function, we initialize the serial monitor at 9600 baud rate and GSM module is also initialized with 9600 Baudrate. The pin 8 which triggers the voice is declared as output pin. void setup(){ Serial.begin(9600); //Serial monitor works on 9600 baudrate for debugging sim900_init(&gprs, 9600); //GSM module works on 9600 baudrate pinMode(8, OUTPUT); //pin to turn on Voice Serial.println("Arduino - Automatic Voice Machine"); } through its Serial port. If we use simple serial read line like “gprs.read()ᾠto read the message we will get them in form of ASCII decimal values, this will make no sense to us. and can be used to compare with any String values. void check_Incoming() { if(gprs.available()) //If GSM is saying something { Incomingch = gprs.read(); // Listen to it and store in this variable if (Incomingch == 10 || Incomingch ==13) //If it says space (10) or Newline (13) it means it has completed one word {Serial.println(data); Fdata =data; data = ""; } //Print the word and clear the variable to start fresh else { String newchar = String (char(Incomingch)); //convert the char to string by using string objects data = data +newchar; // After converting to string, do string concatenation } } } , with these debugger lines you can send any AT commands from the Serial monitor of Arduino to GSM and also see what is responses on the serial monitor. if(Serial.available()){ //Used for debugging gprs.write(Serial.read()); //Used for debugging } //Used for debugging ᾠacknowledgement and then turns the in Pin 8 high for 200ms to play the recorded voice from voice module. if (Fdata == "RING") //If the GSM module says RING { delay(5000); //wait for 5sec to create 3 ring delay. gprs.write ("ATA\r\n"); //Answer the call Serial.println ("Placed Received"); //Used for debugging while(Fdata != "OK") //Until call successfully answered {check_Incoming(); //Read what GSM modue is saying Serial.println ("Playing Recorded message"); //Used for debugging //Play the recored voice message delay(500); digitalWrite(8, HIGH); //Go high delay(200); // wait for 200 msec digitalWrite(8, LOW); //Go low }

Working:

Once your code and hardware is ready, it is time for some fun. Power both the modules and press the REC button on the Voice module and record a message. This message can only be of 10 seconds long. and just go ahead and use it when required and amaze your friends and family with it. Hope you enjoyed the project and build something similar, If you had any troubles post them on the comment section and I will help you out. Code /* Automatic Voice machine using Arudino and GSM900 Created by: Aswinth Raj B Coded on: 22-9-2017 Website: www.circuitdigest.com */ #include <SoftwareSerial.h> //default library #include <Wire.h> //default library int Incomingch; String data,Fdata; //Connect Tx pin of GSM to 9 of Arduino //Connect Rx pin of GSM to 10 of Arduino SoftwareSerial gprs(9,10);//TX,RX void setup(){ Serial.begin(9600); //Serial monitor works on 9600 baudrate for debugging sim900_init(&gprs, 9600); //GSM module works on 9600 baudrate pinMode(8, OUTPUT); //pin to turn on Voice Serial.println("Arduino - Automatic Voice Machine"); } /*Function to read Incoming data from GSM to Arduino*/ void check_Incoming() { if(gprs.available()) //If GSM is saying something { Incomingch = gprs.read(); // Listen to it and store in this variable if (Incomingch == 10 || Incomingch ==13) //If it says space (10) or Newline (13) it means it has completed one word {Serial.println(data); Fdata =data; data = ""; } //Print the word and clear the variable to start fresh else { String newchar = String (char(Incomingch)); //convert the char to string by using string objects data = data +newchar; // After converting to string, do string concatenation } } } /*##End of Function##*/ void loop(){ check_Incoming(); //Read what GSM module is saying if(Serial.available()){ //Used for debugging gprs.write(Serial.read()); //Used for debugging } //Used for debugging if (Fdata == "RING") //If the GSM module says RING { delay(5000); //wait for 5sec to create 3 ring delay. gprs.write ("ATA\r\n"); //Answer the call Serial.println ("Placed Received"); //Used for debugging while(Fdata != "OK") //Until call successfully answered {check_Incoming(); //Read what GSM module is saying Serial.println ("Playing Recorded message"); //Used for debugging //Play the recorded voice message delay(500); digitalWrite(8, HIGH); //Go high delay(200); // wait for 200 msec digitalWrite(8, LOW); //Go low } } } Video microcontroller-projects/interfacing-arduino-with-vpython-creating-graphics

Interfacing Arduino with VPython - Creating Graphics

using a simple LED control project. If you are new, I would strongly recommend you to fall back to the previous tutorial since this tutorial is a continuation of the same. The following tutorial is applicable only for windows user since for Mac or Linux user, the procedure is different. As we move the object, Ultrasonic sensor senses the distance and sends this information to Python program using Arduino and it will move the object in the computer too. Sounds interesting right! So let get started...

Pre-requisites:

Arduino (Any version) Ultrasonic Sensor HC-SR04 Connecting Wires Computer with Python Knowledge on previous tutorial

Installing VPython on your Computer:

For the simple steps below to get started with VPython guidelines. to download the exe file for Visual Python. Do not opt to install a 64–bit version even if your machine runs on 64-bit. Just follow the link given. Launch the exe file and follow the setup. Do not change the default directory path and make sure you have selected “full installationᾮ Once installed, you should find a new application named “VIDLE(VPython)ᾠon your desktop or application panel as shown below. Launch the application and you should get a window as shown below. If everything is working as expected you should get the following screen. will astonish you by the following screen. ᾠtopic. don’t lose hope for we will be sorting out that issue in the further steps This will launch a command prompt as shown below and press enter. The new version of Numpy should get installed on your machine. You might have to wait for some time if your internet connection is slow. Once done you can fall back to step number 4 and try an example program and you should be able to get it working.

Programming VPython:

one will be placed in the centre of the screen reference to the stationary Ultrasonic sensor and the other will be at a dynamic location based on the distance between the US sensor and the object (paper). can be found at the end of this page. Further down, I have explained this python code by splitting them into small meaningful junks. so that we can create 3D objects. The below line does the same. from visual import * and also establish a serial connection with Arduino at COM18 with 9600 as baudrate import serial #Serial imported for Serial communication import time #Required to use delay functions ArduinoSerial = serial.Serial('com18',9600) #Create Serial port object called arduinoSerialData time.sleep(2) #wait for 2 secounds for the communication to get established is the movable object in white colour. I have also placed a text “US sensorᾠnear the wall object. obj = box(pos=(-5,0,0), size=(0.1,4,4), color=color.white) wallL = box(pos=(-1,0,0), size=(0.2,12,12), color=color.cyan) text(text='US sensor', axis=(0,1,0) , pos=(-2,-6,0), depth=-0.3, color=color.cyan) I am sure that the above three lines would have appeared as Greek and Latin for most of the first time readers, but with time you would be able to understand it. Everything that is mentioned inside brackets is (x,y,z) co-ordinates. And these co-ordinates are very similar to the ones that we find in our high school geometry class as shown below. controls the X co-ordinate position of the object (White rectangle). t = int (ArduinoSerial.readline()) #read the serial data and print it as line t= t* 0.05 obj.pos.x = t

Getting your Arduino Ready:

tutorial. function in Arduino. Later the time taken is converted into distance using the below line. dist = (timetaken/2) / 2.91; Here the distance is calculated in terms of millimetres (mm).

Working:

The working of the project is simple. Launch the Python program and place an object before the US sensor as shown below: will also be displayed in the shell window as show in the image below. Hope you understood the project and enjoyed building one. This is just one subtle step towards python but you can build a lot more creative things using this. If you have any idea of what to build with this post them on the comment section and use the forums for technical help. See you with another interesting python project. Code from visual import * import serial #Serial imported for Serial communication import time #Required to use delay functions ArduinoSerial = serial.Serial('com18',9600) #Create Serial port object called arduinoSerialData time.sleep(2) #wait for 2 secounds for the communication to get established obj = box(pos=(-5,0,0), size=(0.1,4,4), color=color.white) wallL = box(pos=(-1,0,0), size=(0.2,12,12), color=color.cyan) text(text='US sensor', axis=(0,1,0) , pos=(-2,-6,0), depth=-0.3, color=color.cyan) t = 0 while 1: rate(100) t = int (ArduinoSerial.readline()) #read the serial data and print it as line t= t* 0.05 obj.pos.x = t print(t) #define Trigger 2 #define Echo 3 int timetaken, dist; int sendv; void setup() { Serial.begin (9600); pinMode(Trigger, OUTPUT); pinMode(Echo, INPUT); } void loop() { timetaken=dist=0; //initialize the variable to zero before calculation //request the US to send a wave digitalWrite(Trigger, HIGH); digitalWrite(Trigger, LOW); timetaken = pulseIn(Echo, HIGH); //calculate the time taken for the wave to return dist = (timetaken/2) / 2.91; //formulae to calculate the distance using time taken if (dist <= 200 && dist > 0)//send the value to python only if it ranhes from 0-20 cm sendv = dist; Serial.println(sendv); delay(200); } Video microcontroller-projects/arduino-floor-cleaning-robot

Arduino Based Floor Cleaning Robot using Ultrasonic Sensor

that only costs a small fraction of the ones in the market. This Robot can detect the obstacles & objects in front of it and can continue moving, avoiding the obstacles, until the whole room is cleaned. It has a small brush attached to it to clean the floor.

Component Required:

Arduino UNO R3. Ultrasonic Sensor. Arduino Motor Driver shield. Wheel Drive Robot Chassis. Computer to Program the Arduino. Battery for the Motors. A Power Bank To Power The Arduino A Shoe Brush. A Scotch Brite Scrub Pad. Instead of using batteries, you can also use a long 4-stranded wire as we did. Though this is not a very elegant or practical solution but you can do if you’re not planning to use it in the real world every day. Make sure the cable’s lengths are enough. Before going into detail lets discuss about Ultrasonic first. is used to measure the distance with high accuracy and stable readings. It can measure distance from 2cm to 400cm or from 1 inch to 13 feet. It emits an ultrasound wave at the frequency of 40KHz in the air and if the object will come in its way then it will bounce back to the sensor. By using that time which it takes to strike the object and comes back, you can calculate the distance. The ultrasonic sensor uses a technique called “ECHOᾮ “ECHOᾠis simply a reflected sound wave. You will have an ECHO when sound reflects back after reaching a dead end. HCSR04 module generates a sound vibration in ultrasonic range when we make the ‘Triggerᾠpin high for about 10us which will send a 8 cycle sonic burst at the speed of sound and after striking the object, it will be received by the Echo pin. Depending on time taken by sound vibration to get back, it provides appropriate pulse output. If the object is far away then it takes more time for ECHO to be heard and the output pulse width will be big. And if the obstacle is near, then the ECHO will be heard faster and output pulse width will be smaller. We can calculate the distance of the object based on the time taken by ultrasonic wave to return back to the sensor. Since the time and speed of sound is known we can calculate the distance by the following formulae. Distance= (Time x Speed of Sound in Air (343 m/s))/2. The value is divided by two since the wave travels forward and backward covering the same distance. Thus the time to reach obstacle is just half the total time taken So Distance in centimeter = 17150*T , check them below: Arduino Based Distance Measurement using Ultrasonic Sensor Door Alarm using Arduino and Ultrasonic Sensor IOT Based Dumpster Monitoring using Arduino

Assembly of Floor Cleaner Robot:

Mount the Arduino on the chassis. Make sure you don’t short circuit anything in case your chassis is made of metal. It is a good idea to get a box for the Arduino and the motor controller shield. Secure the motors with the wheels and chassis using screws. Your chassis should have options to do this from the factory, but if it doesn't, you can improvise a different solution. Epoxy isn’t a bad idea. Mount the shoe brush on the front of the chassis. We used a combination of M-Seal epoxy and drilled screws for this, though you can use any other solution that might be easier for you. Mount the Scotch Brite scrub pad behind the brush. We used a shaft going across the chassis that holds it in play, though this is improvisable as well. A spring loaded shaft can be used to accompany it. Mount the batteries (or cables on the back of the chassis). Epoxy or a battery holder are good ways to do this. Hot glue isn’t bad either.

Wiring and Connections:

on to the Arduino like any other shield. The motor shield should have at least 2 outputs, and they should be connected to your 2 motors. Normally, these outputs are labelled “M1ᾠand “M2ᾠor “Motor 1ᾠand “Motor 2ᾮ Wire your batteries and power bank up to the motor shield and Arduino respectively. Do not cross connect them. Your motor shield should have an input channel. If you’re using wires, connect them to AC adapters.

Programing Explanation:

, given at the end of this tutorial, into the IDE. Connect your Arduino to the computer. Select the port in Tools/Port. Click the upload button. Test the robot. If it turns too little or too much, experiment with the delays until perfect. Code is easy and can be understood easily, but here we have explained few parts of it: Below code sets up the robot. First we have included the Adafruit Library for driving the motors with Motor driver shield. After that, we defined Trig pin and Echo pin. It also sets up the motors. It sets the Trig pin to output and the Echo pin to input. #include <AFMotor.h> #define trigPin 12 #define echoPin 13 AF_DCMotor motor1(1,MOTOR12_64KHZ); AF_DCMotor motor2(2, MOTOR12_8KHZ); void setup() { pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } Below code tells the Arduino to loop the following commands. After that, it uses the sensor to transmit and receive ultrasonic sounds. It calculates the distance it is from the object once ultrasonic waves bounces back, after noting that the object is within the set distance, it tells the Arduino to rotate the motors accordingly. void loop() { long duration, distance; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration/2) / 29.1; if (distance < 20) { motor1.setSpeed(255); motor2.setSpeed(0); motor1.run(BACKWARD); motor2.run(BACKWARD); delay(2000); //CHANGE THIS ACCORDING TO HOW THE ROBOT TURNS. This makes the robot turn by rotating one motor and keeping the other stagnant. Below code makes the robot turn both motors in the same direction in order to make it move forward until it detects an object in the aforementioned boundary. else { motor1.setSpeed(160); //CHANGE THIS ACCORDING TO HOW FAST YOUR ROBOT SHOULD GO. motor2.setSpeed(160); //CHANGE THIS TO THE SAME VALUE AS YOU PUT IN ABOVE. motor1.run(FORWARD); motor2.run(FORWARD); } Code #include <AFMotor.h> #define trigPin 12 #define echoPin 13 AF_DCMotor motor1(1,MOTOR12_64KHZ); AF_DCMotor motor2(2, MOTOR12_8KHZ); void setup() { pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { long duration, distance; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration/2) / 29.1; if (distance < 20) { motor1.setSpeed(255); motor2.setSpeed(0); motor1.run(BACKWARD); motor2.run(BACKWARD); delay(2000); //CHANGE THIS ACCORDING TO HOW THE ROBOT TURNS. } else { motor1.setSpeed(160); //CHANGE THIS ACCORDING TO HOW FAST YOUR ROBOT SHOULD GO. motor2.setSpeed(160); //CHANGE THIS TO THE SAME VALUE AS YOU PUT IN ABOVE. motor1.run(FORWARD); motor2.run(FORWARD); } } Video microcontroller-projects/arduino-ammeter

Arduino Based Digital Ammeter

, we will explain about measuring of current by using ohm’s law. It will be quite interesting as well as a good application of basic science that we studied in our school days. ᾠfor constant of proportionality we use resistance, so here it comes the equation of ohm’s law. V = voltage across the conductor in Volt (v). I = current pass through the conductor in Ampere (A). R = resistance constant of proportionality in Ohm (). I = V / R So in order to find out the current, we need some data: Voltage Resistance We are going to build a series resistance along with the device. As we need to find voltage drop across the device, for that we need voltage readings before and after the voltage drop, that is possible in the resistance because of no polarity. Like in the above diagram, we have to find the two voltages that are flowing across the resistor. The difference between the voltages (V1-V2) at the two ends of resistors gives us voltage drop across the resistor (R) and we divide the voltage drop by the resistor value we get the current flow (I) through the device. That is how we can calculate the Current value passing through it, let’s gets into it practical implementation.

Required Components:

Arduino Uno. Resistor 22. LCD 16x2. LED. 10K pot. Breadboard. Multimeter. Jumper cables.

Circuit Diagram and Connections:

is follows , resistor and LED. Arduino Uno is the power source forthe all other components. has analog and digital pins. The sensor circuit is connected to the analog inputs from which we get value of the voltage. The LCD is connect with the digital pins (7,8,9,10,11,12). The LCD has 16 pins the first two pins (VSS,VDD) and last two pins(Anode, Cathode) are connected to the gnd and 5v. The reset (RS) and enable (E) pins are connected to the Arduino digital pins 7 and 8. The data pins D4-D7 are connected to the digital pins of Arduino (9,10,11,12). The V0 pin is connected to the middle pin of pot. The red and black wires are 5v and gnd.

Current Sensing Circuit:

This Ammeter circuit consists resistor and LED as load. Resistor is connected in series to the LED that current flows through the load and voltage drops is determined from the resistor. The terminal V1, V2 are going to connect with the analog input of the Arduino.

Calculations:

is ranges between 0-1023 and the reference voltage is ranges between 0-5v.

Arduino Code:

, is given at the end of this article. function. int voltage_value0 = analogRead(A0); int voltage_value1 = analogRead(A1); The value is multiplied with 0.00488 to get actual voltage difference then it is divided by resistor value to find the current flow. 0.00488v is the minimal voltage that the ADC of Arduino can detect. int subraction_value =(voltage_value0 - voltage_value1) ; float temp_val = (subraction_value*0.00488); float current_value = (temp_val/22); Code #include<LiquidCrystal.h> LiquidCrystal lcd (7,8,9,10,11,12); void setup() { // put your setup code here, to run once: Serial.begin(9600); lcd.begin(16,2); lcd.clear(); } void loop() { // put your main code here, to run repeatedly: int voltage_value0 = analogRead(A0); int voltage_value1 = analogRead(A1); int subraction_value =(voltage_value0 - voltage_value1) ; float temp_val = (subraction_value*0.00488); float current_value = (temp_val/22); Serial.print(current_value); lcd.setCursor(0,0); lcd.print("current value="); lcd.setCursor(0,1); lcd.print (current_value); lcd.print("A"); delay(1000); } Video microcontroller-projects/arduino-python-tutorial

Using Python with Arduino - Controlling an LED

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics with high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development. So, Let’s get started....

Materials Required:

Arduino Uno (or any Arduino Boards) Computer with Internet connection

Installing Python on your Computer:

Obviously the first step in this tutorial would be installing Python on our computer. The steps mentioned below are applicable only for windows users running either 32-bit or 64-bit OS. The installation procedure for MAC and Linux is different. Click on 32-bit Python-2.7.9 and this will install the 32-bit Python IDLE on your Computer. Do not download the 64-bit version or updated versions since they do not provide support for our Arduino Libraries. Even if your Computer is operating on 64-bit you can use 32-bit Python itself. Open the downloaded exe file and follow through the instruction. Do not change the directory in which the python is getting installed. It will be C:\Python27 by default and leave it as such. While the installation takes place you might get a warning from your anti-virus (if any) in that case click on allow. search box and opening it. ᾠfrom now. there and verify the program here. We will later get into the details of creating a python program, for now let us check if python is working. ᾠand press enter. You should see the result getting printed as shown below.

Getting PySerial in Python:

which is used to read and write serial data to Arduino or any other Microcontroller. to download PySerial. The resulting download will be a exe file which can be directly installed. Do not change any setting while installing. Leave it to the default directory and default settings. Now, let us check if PySerial is installed properly. To do this, open Python Shell again and type in If the library was successfully installed then you should not get any error messages as shown in the picture below. If you get any errors post them on the comment section and we will try resolving it.

Our First Arduino Python Program:

Let us start with the Arduino code. is given at the end of this page. Read further to know how it works. and declare that we will be using the built in led as output and turn it low during program start. We have also sent a welcome message to python via serial print as shown below: void setup() { Serial.begin(9600); //initialize serial COM at 9600 baudrate pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output digitalWrite (LED_BUILTIN, LOW); Serial.println("Hi!, I am Arduino"); } Now based on the value of this variable (“dataᾩ we toggle the built in led as shown below. void loop() { while (Serial.available()){ data = Serial.read(); } if (data == '1') digitalWrite (LED_BUILTIN, HIGH); else if (data == '0') digitalWrite (LED_BUILTIN, LOW); } The complete python program for this tutorial is given at the end of this page. Read further to know how to write and use the same. Open your Python Shell (Python IDLE) and click File->New This will open a new text file where you can type in your program. Before we type anything lets save the file, by Ctrl+S. Type in any name and click on save. This will automatically save you file in ᾮpyᾠextension. Now, type in the program or paste the python code given at the end of this page. The explanation for the same is given below and finally run the program. The serial library as said earlier will be used to read and write serial data and the time library will be used to create delays in our program. These two libraries can be imported in our program using the following two lines: import serial #Serial imported for Serial communication import time #Required to use delay functions In this line we have to mention the name of the COM port to which our Arduino is connected and at what baud rate it is operating as shown below. ArduinoSerial = serial.Serial('com18',9600) It is very important to mention the correct COM port name. It can found by using the Device manager on your computer. for the Serial communication to be established. This can be done by using the below line: time.sleep(2) Now we can read or write anything from/to our Arduino Board. and will print it on the shell window print ArduinoSerial.readline() You can also assign the value to a variable and use it for computations. Board. ArduinoSerial.write('1') This line will write ᾱᾠto the Arduino. You can send anything from decimals to strings using the same line. Now, getting back to our program, inside the infinite while loop, we have the following lines var = raw_input() #get input from user print "you entered", var #print the input for confirmation if (var == '1'): #if the value is 1 ArduinoSerial.write('1') #send 1 print ("LED turned ON") time.sleep(1) if (var == '0'): #if the value is 0 ArduinoSerial.write('0') #send 0 print ("LED turned OFF") time.sleep(1) Later, if the value is 1 it will print ᾱᾠserially to Arduino and if 0 it will print ᾰᾠserially to Arduino. The code in our Arduino Program (discussed above) we will toggle the LED based on the received value. Once the complete program is done your script should look something like this below or press F5 this might ask you to save the program and then will launch it.

Controlling LED with Python and Arduino:

The working of this project is pretty straight forward. Upload the program to your Arduino and verify it is connected to the same COM port as mentioned in the python program. Then Launch the Python program as mentioned above. This will launch a python shell script as shown below. The window on the left is the shell window showing the output and the window on the right is the script showing the program. entered in the Arduino program is received by the Python and displayed on its shell window. When the shell window asks to enter values, we can enter either 0 or 1. If we send 1 the LED on the Arduino Board will turn ON and if we send 0 the LED on our Arduino Board will turn OFF. Showing a successfully connection between our Arduino Program and Python. , one to be uploaded and run from Arduino and second is to be run from Python Shell in Windows. Hope you understood the project and were able to get it working. If not, post your problem in the comment below and I will be happy to help you out. In our next project we will learn what else can be done cool with Python and Arduino by exploring deep into other python modules like Vpython, gamepython etc. Until then stay tuned.... Code /* * Code to blink an LED using Python * Code by: Aswint Raj, Dated: 8-9-2017 * Webiste: www.circuitdigest.com */ int data; void setup() { Serial.begin(9600); //initialize serial COM at 9600 baudrate pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output digitalWrite (LED_BUILTIN, LOW); Serial.println("Hi!, I am Arduino"); } void loop() { while (Serial.available()){ data = Serial.read(); } if (data == '1') digitalWrite (LED_BUILTIN, HIGH); else if (data == '0') digitalWrite (LED_BUILTIN, LOW); } #Program to Control LED of Arduino from Python #Code by: Aswinth Raj, Dated: 8-9-2017 #Website: www.circuitdigest.com import serial #Serial imported for Serial communication import time #Required to use delay functions ArduinoSerial = serial.Serial('com18',9600) #Create Serial port object called arduinoSerialData time.sleep(2) #wait for 2 secounds for the communication to get established print ArduinoSerial.readline() #read the serial data and print it as line print ("Enter 1 to turn ON LED and 0 to turn OFF LED") while 1: #Do this forever var = raw_input() #get input from user print "you entered", var #print the intput for confirmation if (var == '1'): #if the value is 1 ArduinoSerial.write('1') #send 1 print ("LED turned ON") time.sleep(1) if (var == '0'): #if the value is 0 ArduinoSerial.write('0') #send 0 print ("LED turned OFF") time.sleep(1) Video microcontroller-projects/arduino-dc-dc-buck-converter-circuit

DC-DC Buck Converter Circuit - How to Step Down DC Voltage

with a maximum current capacity of 6 amps. We are going to step down 12v DC to any value between 0 and 10v DC. We can control the output voltage value by rotating the potentiometer. It is just like a transformer with one difference; whereas transformer steps down AC voltage buck converter steps down DC voltage. Efficiency of buck converter is lower than a transformer. at the end of this article.

Required Components:

Arduino Uno IRF540N Inductor(100Uh) Capacitor (100uf) Schottky Diode Potentiometer 10k, 100ohm Resistor Load 12v Battery

Circuit Diagram and Connections:

Connect one terminal of inductor to source of mosfet, and another to LED in series with 1k resistor. Load is connected in parallel to this arrangement. Connect 10k resistor between gate and source. Connect capacitor in parallel to load. Connect positive terminal of battery to drain and negative to capacitor’s negative terminal. Connect p terminal of diode to negative of battery and n terminal directly to source. PWM pin of Arduino goes to gate of mosfet GND pin of Arduino goes to source of mosfet. Do connect it there or circuit will not work. Connect potentiometer’s extreme terminals to 5v pin and GND pin of Arduino respectively. Whereas wiper terminal to analog pin A1. As already explained, Arduino sends clock pulses to base of MOSFET. Frequency of these clock pulses is approx. 65 Khz. This causes very fast switching of mosfet and we obtain an average voltage value. You should learn about ADC and PWM in Arduino, which will clear you how high frequency pulses are generated by Arduino: Arduino Based LED Dimmer using PWM How to Use ADC in Arduino Uno? Mosfet is used for two purposes: For high speed switching of the output voltage. To provide high current with less dissipation of heat. Inductor is used to control voltage spikes which can damage mosfet. Inductor stores energy when mosfet is on and releases this stored energy when mosfet is off. Since frequency is very high, value of inductance required for this purpose is very low (around 100uH). Schottky diode completes the loop of current when mosfet is switched off and thus ensuring smooth supply of current to load. Apart from this, schottky diode dissipates very low heat and work fine at higher frequency than regular diodes. Brightness of LED indicates the step down voltage across load. As we rotate the Potentiometer, brightness of LED varies. When wiper terminal of potentiometer is thrown off to different position, voltage between it and ground changes which in turn changes the analog value received by pin A1 of arduino. This new value is then mapped between 0 and 255 and then given to pin 6 of Arduino for PWM. ** Capacitor smooths out voltage given to load. Even slightest noise at gate of MOSFETcan turn it on, hence to prevent this from happening it is always advised to connect high value resistor between gate and source.

Code Explanation:

, for generating high frequency pulses, is given in the code section below. Code is simple and self-explanatory, so here we have explained only few parts of code. Variable x is assigned the analog value that is received from analog pin A0 of Arduino x= analogRead(A1) ; w= map(x,0,1023,0,255) ; Normal frequency of PWM for pin 6 is approx.1khz. This frequency is not suitable for purposes like buck converter. Hence this frequency must be increased to a very high level. This can be achieved using a one line code in void setup: TCCR0B = TCCR0B & B11111000 | B00000001;// change frequency of pwm to 65 KHZ approx.

Working of DC-DC Buck Converter:

When circuit is switched on, mosfet switches on and off with a frequency of 65 khz. This causes inductor to store energy when mosfet is on and then give this stored energy to load when mosfet switches off. Since this happens at very high frequency, we get an average value of pulsed output voltage depending on the position of wiper terminal of potentiometer with respect to 5v terminal. And as this voltage between wiper terminal and ground increases so does the mapped value on pwm pin no. 6 of Arduino. Let’s say this mapped value is 200. Then PWM voltage on pin 6 will be at: [ (200*5) / 255 ]= 3.921 volts And since MOSFET is a voltage dependent device, this pwm voltage ultimately determines the voltage across load. below. We have controlled the speed of motor with Potentiometer and controlled the brightness of LED with Potentiometer. Code int x; // initialize variables int w; void setup() { pinMode(6,OUTPUT);// pwm pin 6 as output pin pinMode(A1,INPUT);// analog pin as input TCCR0B = TCCR0B & B11111000 | B00000001;// change frequency of pwm to 65 KHZ approx( explained under code section) Serial.begin(9600);// begin serial communication } void loop() { x= analogRead(A1); w= map(x,0,1023,0,255); analogWrite(6,w); // write mapped value on pin 6 Serial.print("w "); //print mapped value on screen Serial.println(w); } Video microcontroller-projects/arduino-digital-voltmeter

Simple Arduino Digital Voltmeter

and can measure the input voltage using Arduino and a 16x2 LCD display. here. (LCD). We have also displayed the voltage in Serial Monitor of Arduino IDE and confirmed the measured voltage using Multimeter.

Hardware Required:

Arduino uno 16x2 LCD (Liquid Crystal Display) 100 k ohm resistor 10 k ohm resistor 10 k ohm potentiometer breadboard jumper wires

Voltage Divider Circuit:

Voltage divider is a resistive circuit and is shown in figure. In this resistive network we have two resistors. As shown in figure, R1 and R2 which are of 10k and 100k ohm. The midpoint of branch is taken to measurement as a anolog input to the Arduino. The voltage drop across R2is called Vout , that’s the divided voltage of our circuit. Using the known value (two resistor values R1, R2, and the input voltage), we can substitute in the equation below to calculate the output voltage. Vout = Vin (R2/R1+R2) By applying this equation in the Arduino code the input voltage can be easily derived. Arduino can only measure the DC input voltage of +55v, In other words, when measuring 55V, the Arduino analog pin will be at its maximum voltage of 5V so it is safe to measure within this limit. Here the resistors R2 and R1 value is set to 100000 and 10000 i.e. in the ratio of 100:10.

Circuit Diagram and Connections:

is simple and shown in the circuit diagram below: Pin DB4, DB5, DB6, DB7, RS and EN of LCD are directlyconnetedto Pin D4, D5, D6, D7, D8, D9 ofArduinoUno The Center point of two resistors R1 and R2, which makes the voltage divider circuit, is connected toArduinoPin A0. While the other 2 ends are connected to the input volt (voltage to be measured) and gnd.

Coding Explanation:

is given in the Code part below. Code is simple and can be easily understood. The main part of the code is to convert and map the given input voltage into displayed output voltage with the help of the above given equation Vout = Vin (R2/R1+R2). As mentioned earlier Arduino ADC output value will range from 0 to 1023 and the Arduino max output voltage is 5v so we have to multiply the analog input at A0 to 5/1024 to get the real voltage. void loop() { int analogvalue = analogRead(A0); temp = (analogvalue * 5.0) / 1024.0; // FORMULA USED TO CONVERT THE VOLTAGE input_volt = temp / (r2/(r1+r2)); is used to print the values on 16x2 LCD. Serial.print("v= "); // prints the voltage value in the serial monitor Serial.println(input_volt); lcd.setCursor(0, 1); lcd.print("Voltage= "); // prints the voltage value in the LCD display lcd.print(input_voltage); , you can check the same here. Code #include <LiquidCrystal.h> // LIBRARY TO ACCESS THE LCD DISPLAY LiquidCrystal lcd( 4, 5, 6, 7,8 ,9 ); float input_volt = 0.0; float temp=0.0; float r1=10000.0; //r1 value float r2=100000.0; //r2 value void setup() { Serial.begin(9600); // opens serial port, sets data rate to 9600 bps lcd.begin(16, 2); //// set up the LCD's number of columns and rows lcd.print("DC DIGI VOLTMETER"); } void loop() { int analogvalue = analogRead(A0); temp = (analogvalue * 5.0) / 1024.0; // FORMULA USED TO CONVERT THE VOLTAGE input_volt = temp / (r2/(r1+r2)); if (input_volt < 0.1) { input_volt=0.0; } Serial.print("v= "); // prints the voltage value in the serial monitor Serial.println(input_volt); lcd.setCursor(0, 1); lcd.print("Voltage= "); // prints the voltage value in the LCD display lcd.print(input_volt); delay(300); } Video microcontroller-projects/arduino-cnc-machine-project-code

DIY Arduino Based CNC Plotter Machine

which are used to draw anything or design any mechanical part according to the design program fed into their controller unit. Controller unit can be either computer or microcontroller. CNC machines have stepper and servo motors to draw the design as per the fed program. which is by far the simplest to make. You can also use this as an Arduino CNC drawing machine with little modifications. at the end of this tutorial.

Building an Arduino CNC Machine:

to operate, 3 axes are required (x-axis, y-axis and z-axis. The x-axis and y-axis work in unison to create a 2D image on a plain paper. These x and y axis are placed 90 degrees to each other such that any point on the plain surface is defined by a given value of x and y. The z-axis is used lift and lower the pen onto the plain paper. if you are new to this. device step by step.

What You Need:

My design is quite different in hardware in terms of size and the materials used. I wasn’t able to find old DVD drives so I opted for printer parts. Whichever you use, ensure that it has a stepper motor. Aluminium sheet (710mm x 710mm) Old HP/Epson printer. You can use old computer DVD drives Bolts and nuts Perspex glass Arduino UNO L293D motor driver shield or an Arduino CNC shield Mini servo motor A pen Screwdriver Drill Cutting tool (hacksaw) Glue Bench device For the efficient operation of this machine, the following softwares are used. Go to the various websites and download them. Arduino IDE version 1.6.6 or later versions from here Processing IDE version 3.1.1 or later version from here Inkscape version 0.48.5. Download it from here. Grbl controller (optional)

The Base for CNC Plotter Machine:

The main body of this device is the base which supports all the major parts of the machine together so that the machine is firm and is also portable. In this design we will use aluminum to construct the base since it is light, simple to bend and cut and also it gives a good shiny appearance since it doesn’t rust. of my base is shown below: Note: All dimensions are in millimeters. After all the bending and cutting, I was able to produce a very firm base as shown below:

Assembly of the X, Y and Z Axes:

, two printer cradles are used. Each of these parts contains a stepper motor and a belt drive mechanism usually used to move the cartridge to and fro. , a mini servo motor is attached on the y-axis using glue. This servo motor is used to move the pen up and down. A good support mechanism should be constructed that will enable the free up and down movement of the pen.

Drawing Platform for CNC Machine:

Due to the immense size of this machine, the device is capable of drawing on an A5 sized paper. Therefore we will cut out an A5 (148mmx210mm) sized platform from the Perspex glass and then stick it onto the x-axis moving part using glue.

Wiring and Circuit of CNC Machine:

for our Plotter machine. to servo1. Connect a 7.5V - 9V power supply to the power port of the motor driver shield. The machine is now ready for testing.

ArduinoCNC Machine Codeand Testing:

and see whether they are connected correctly. Ensure you choose the correct port and board in tools and then upload the code into the Arduino board. Some movements should be observed on stepper motor one. In order to test motor two, change the motor port from 2 to 1 in the following line and then upload the code again. #include <AFMotor.h> // Connect a stepper motor with 48 steps per revolution (7.5 degree) // to motor port #2 (M3 and M4) AF_Stepper motor(48, 2); from the Code section below and upload it to the Arduino board. You can download the code from the below link. G - CODE is the language in which we tell computerized machines (CNC) to do something. It's basically a file that contains X, Y and Z coordinates. For example: G17 G20 G90 G94 G54 G0 Z0.25X-0.5 Y0. Z0.1 G01 Z0. F5. G02 X0. Y0.5 I0.5 J0. F2.5 X0.5 Y0. I0. J-0.5 X0. Y-0.5 I-0.5 J0. X-0.5 Y0. I0. J0.5 G01 Z0.1 F5. G00 X0. Y0. Z0.25 , which we have explained in next section or but you can use readily available G-Codes on the internet. This platform will help us send the G-Codes to the Arduino board. To do so, you will have to download the GCTRL.PDE file. and open it using Processing IDE and browse to the folder where you saved your G-CODE. Select the right G-CODE and press enter. If everything was connected right, you should see you device starting to plot on the paper. and the device will stop whatever it was doing.

How to Generate Your Own G-Code:

as shown below. with installation notes. If the installation was successful, Open the Inkscape, go to File menu and click "Document Properties". First change dimensions from px to mm. Also reduce the width and height to 90 mm. Now close this window. A square appears as the drawing area. This is the area that we will use to write our text. " and position it at the top right corner of the square as shown below. Click text and choose the type of font style that you prefer. Click apply and the close. " and then type the file name as "hello world" as shown in below pic. This will only appear if the Add-on installation was successful. Finally click on save and click ok on the pop-up window. You have generated a G-Code and it can be plotted using the previous procedures.

The GRBL Controller:

Once you’ve managed to generate a G-Code using Inkscape, it may be necessary to view the G-Code in order to ensure that it is within the drawing limits. in the lines shown below: above. If it goes beyond those limit for example towards the negative side of the x-axis, that part on the negative side will not be plotted. In this example x and y values range from 0mm to 40mm. Since I am using printer parts which can plot on a larger area, I change the max values from 40mm to 60mm. Whenever you generate a G-Code using Inkscape, you can first open that G-Code in the GRBL program to see whether it is within those limits. If not within, you need to resize you image in the Inkscape until it is within your limits. Try it out and let us know in comments also check the Video below. Code /* Send GCODE to this Sketch using gctrl.pde https://github.com/damellis/gctrl Convert SVG to GCODE with MakerBot Unicorn plugin for Inkscape available here https://github.com/martymcguire/inkscape-unicorn Arduino code for this Mini CNC Plotter based on: https://github.com/adidax/mini_cnc_plotter_firmware */ #include <Servo.h> #include <AFMotor.h> #define LINE_BUFFER_LENGTH 512 char STEP = MICROSTEP ; // Servo position for Up and Down const int penZUp = 115; const int penZDown = 83; // Servo on PWM pin 10 const int penServoPin =10 ; // Should be right for DVD steppers, but is not too important here const int stepsPerRevolution = 48; // create servo object to control a servo Servo penServo; // Initialize steppers for X- and Y-axis using this Arduino pins for the L293D H-bridge AF_Stepper myStepperY(stepsPerRevolution,1); AF_Stepper myStepperX(stepsPerRevolution,2); /* Structures, global variables */ struct point { float x; float y; float z; }; // Current position of plothead struct point actuatorPos; // Drawing settings, should be OK float StepInc = 1; int StepDelay = 0; int LineDelay =0; int penDelay = 50; // Motor steps to go 1 millimeter. // Use test sketch to go 100 steps. Measure the length of line. // Calculate steps per mm. Enter here. float StepsPerMillimeterX = 100.0; float StepsPerMillimeterY = 100.0; // Drawing robot limits, in mm // OK to start with. Could go up to 50 mm if calibrated well. float Xmin = 0; float Xmax = 40; float Ymin = 0; float Ymax = 40; float Zmin = 0; float Zmax = 1; float Xpos = Xmin; float Ypos = Ymin; float Zpos = Zmax; // Set to true to get debug output. boolean verbose = false; // Needs to interpret // G1 for moving // G4 P300 (wait 150ms) // M300 S30 (pen down) // M300 S50 (pen up) // Discard anything with a ( // Discard any other command! /********************** * void setup() - Initialisations ***********************/ void setup() { // Setup Serial.begin( 9600 ); penServo.attach(penServoPin); penServo.write(penZUp); delay(100); // Decrease if necessary myStepperX.setSpeed(600); myStepperY.setSpeed(600); // Set & move to initial default position // TBD // Notifications!!! Serial.println("Mini CNC Plotter alive and kicking!"); Serial.print("X range is from "); Serial.print(Xmin); Serial.print(" to "); Serial.print(Xmax); Serial.println(" mm."); Serial.print("Y range is from "); Serial.print(Ymin); Serial.print(" to "); Serial.print(Ymax); Serial.println(" mm."); } /********************** * void loop() - Main loop ***********************/ void loop() { delay(100); char line[ LINE_BUFFER_LENGTH ]; char c; int lineIndex; bool lineIsComment, lineSemiColon; lineIndex = 0; lineSemiColon = false; lineIsComment = false; while (1) { // Serial reception - Mostly from Grbl, added semicolon support while ( Serial.available()>0 ) { c = Serial.read(); if (( c == '\n') || (c == '\r') ) { // End of line reached if ( lineIndex > 0 ) { // Line is complete. Then execute! line[ lineIndex ] = '\0'; // Terminate string if (verbose) { Serial.print( "Received : "); Serial.println( line ); } processIncomingLine( line, lineIndex ); lineIndex = 0; } else { // Empty or comment line. Skip block. } lineIsComment = false; lineSemiColon = false; Serial.println("ok"); } else { if ( (lineIsComment) || (lineSemiColon) ) { // Throw away all comment characters if ( c == ')' ) lineIsComment = false; // End of comment. Resume line. } else { if ( c <= ' ' ) { // Throw away whitepace and control characters } else if ( c == '/' ) { // Block delete not supported. Ignore character. } else if ( c == '(' ) { // Enable comments flag and ignore all characters until ')' or EOL. lineIsComment = true; } else if ( c == ';' ) { lineSemiColon = true; } else if ( lineIndex >= LINE_BUFFER_LENGTH-1 ) { Serial.println( "ERROR - lineBuffer overflow" ); lineIsComment = false; lineSemiColon = false; } else if ( c >= 'a' && c <= 'z' ) { // Upcase lowercase line[ lineIndex++ ] = c-'a'+'A'; } else { line[ lineIndex++ ] = c; } } } } } } void processIncomingLine( char* line, int charNB ) { int currentIndex = 0; char buffer[ 64 ]; // Hope that 64 is enough for 1 parameter struct point newPos; newPos.x = 0.0; newPos.y = 0.0; // Needs to interpret // G1 for moving // G4 P300 (wait 150ms) // G1 X60 Y30 // G1 X30 Y50 // M300 S30 (pen down) // M300 S50 (pen up) // Discard anything with a ( // Discard any other command! while( currentIndex < charNB ) { switch ( line[ currentIndex++ ] ) { // Select command, if any case 'U': penUp(); break; case 'D': penDown(); break; case 'G': buffer[0] = line[ currentIndex++ ]; // /!\ Dirty - Only works with 2 digit commands // buffer[1] = line[ currentIndex++ ]; // buffer[2] = '\0'; buffer[1] = '\0'; switch ( atoi( buffer ) ){ // Select G command case 0: // G00 & G01 - Movement or fast movement. Same here case 1: // /!\ Dirty - Suppose that X is before Y char* indexX = strchr( line+currentIndex, 'X' ); // Get X/Y position in the string (if any) char* indexY = strchr( line+currentIndex, 'Y' ); if ( indexY <= 0 ) { newPos.x = atof( indexX + 1); newPos.y = actuatorPos.y; } else if ( indexX <= 0 ) { newPos.y = atof( indexY + 1); newPos.x = actuatorPos.x; } else { newPos.y = atof( indexY + 1); indexY = '\0'; newPos.x = atof( indexX + 1); } drawLine(newPos.x, newPos.y ); // Serial.println("ok"); actuatorPos.x = newPos.x; actuatorPos.y = newPos.y; break; } break; case 'M': buffer[0] = line[ currentIndex++ ]; // /!\ Dirty - Only works with 3 digit commands buffer[1] = line[ currentIndex++ ]; buffer[2] = line[ currentIndex++ ]; buffer[3] = '\0'; switch ( atoi( buffer ) ){ case 300: { char* indexS = strchr( line+currentIndex, 'S' ); float Spos = atof( indexS + 1); // Serial.println("ok"); if (Spos == 30) { penDown(); } if (Spos == 50) { penUp(); } break; } case 114: // M114 - Repport position Serial.print( "Absolute position : X = " ); Serial.print( actuatorPos.x ); Serial.print( " - Y = " ); Serial.println( actuatorPos.y ); break; default: Serial.print( "Command not recognized : M"); Serial.println( buffer ); } } } } /********************************* * Draw a line from (x0;y0) to (x1;y1). * int (x1;y1) : Starting coordinates * int (x2;y2) : Ending coordinates **********************************/ void drawLine(float x1, float y1) { if (verbose) { Serial.print("fx1, fy1: "); Serial.print(x1); Serial.print(","); Serial.print(y1); Serial.println(""); } // Bring instructions within limits if (x1 >= Xmax) { x1 = Xmax; } if (x1 <= Xmin) { x1 = Xmin; } if (y1 >= Ymax) { y1 = Ymax; } if (y1 <= Ymin) { y1 = Ymin; } if (verbose) { Serial.print("Xpos, Ypos: "); Serial.print(Xpos); Serial.print(","); Serial.print(Ypos); Serial.println(""); } if (verbose) { Serial.print("x1, y1: "); Serial.print(x1); Serial.print(","); Serial.print(y1); Serial.println(""); } // Convert coordinates to steps x1 = (int)(x1*StepsPerMillimeterX); y1 = (int)(y1*StepsPerMillimeterY); float x0 = Xpos; float y0 = Ypos; // Let's find out the change for the coordinates long dx = abs(x1-x0); long dy = abs(y1-y0); int sx = x0<x1 ? StepInc : -StepInc; int sy = y0<y1 ? StepInc : -StepInc; long i; long over = 0; if (dx > dy) { for (i=0; i<dx; ++i) { myStepperX.onestep(sx,STEP); over+=dy; if (over>=dx) { over-=dx; myStepperY.onestep(sy,STEP); } delay(StepDelay); } } else { for (i=0; i<dy; ++i) { myStepperY.onestep(sy,STEP); over+=dx; if (over>=dy) { over-=dy; myStepperX.onestep(sx,STEP); } delay(StepDelay); } } if (verbose) { Serial.print("dx, dy:"); Serial.print(dx); Serial.print(","); Serial.print(dy); Serial.println(""); } if (verbose) { Serial.print("Going to ("); Serial.print(x0); Serial.print(","); Serial.print(y0); Serial.println(")"); } // Delay before any next lines are submitted delay(LineDelay); // Update the positions Xpos = x1; Ypos = y1; } // Raises pen void penUp() { penServo.write(penZUp); delay(penDelay); Zpos=Zmax; digitalWrite(15, LOW); digitalWrite(16, HIGH); if (verbose) { Serial.println("Pen up!"); } } // Lowers pen void penDown() { penServo.write(penZDown); delay(penDelay); Zpos=Zmin; digitalWrite(15, HIGH); digitalWrite(16, LOW); if (verbose) { Serial.println("Pen down."); } } Video microcontroller-projects/arduino-touch-screen-calculator-tft-lcd-project-code

Arduino Touch Screen Calculator using TFT LCD

that could perform all basic calculations like Addition, Subtraction, Division and Multiplication.

Materials Required:

Arduino Uno 2.4ᾠTFT LCD display Shield 9V Battery.

Getting to know the TFT LCD Screen Module:

works and what are the types present in it. Let us take a look at the pinouts of this 2.4ᾠTFT LCD screen module. As you can see there are 28 pins which will perfectly fit into any Arduino Uno / Arduino Mega Board. A small classification of these pins is given in the table below. We need not know much about the detailed working of these pins since they will be take care by our Arduino Library. You can also find an SD card slot at the bottom of the module shown above, which can be used to load an SD card with bmp image files, and these images can be displayed in our TFT LCD screen using the Arduino Program. to try out some basic example programs and get comfortable with the LCD screen. Also check out our other TFT LCD projects with Arduino here: How to Use NeoPixel LED Strip with Arduino and TFT LCD Smart Phone Controlled Digital Code Lock using Arduino

Calibrating the TFT LCD Screen for Touch Screen:

If you planning to use the touch screen function of your TFT LCD module, then you have to calibrate it to make it work properly. A LCD screen without calibration might work unlikely, for instance you might touch at one place and the TFT might respond for a touch at some other place. These calibrations results will not be similar for all boards and hence you are left on your own to do this. The best way to calibrate is to use the calibration example program (comes with library) or use the serial monitor to detect your error. However for this project since the size of buttons is large calibration should not be a big problem and I will also explain how you can calibrate your screen under the programming section below.

TFT LCD Connections with Arduino:

The 2.4ᾠTFT LCD screen is a perfect Arduino Shield. You can directly push the LCD screen on top of the Arduino Uno and it will perfectly match with the pins and slid in through. However, as matters of safety cover the Programming terminal of your Arduino UNO with a small insulation tape, just in case if the terminal comes in contact with your TFT LCD screen. The LCD assembled on UNO will look something like this below.

Programming your Arduino for TFT LCD:

working. This is a modified library of Adafruit and can work seamlessly with our LCD TFT Module. You can check the complete program at the end of this Article. To install this library, you can simply click on the link above which will take you to a Github page. There click on clone or download and select “Download ZIPᾮ A zip file will be downloaded. Now, you can use the code below in your Arduino IDE and upload it to your Arduino UNO for the Touch Screen Calculator to work. Further down, I have explained the code into small segments. We need three libraries for this program to work; all these three libraries were given in the ZIP file you downloaded from the above provided link. I have simply included them in the code as shown below. #include <SPFD5408_Adafruit_GFX.h> // Core graphics library #include <SPFD5408_Adafruit_TFTLCD.h> // Hardware-specific library #include <SPFD5408_TouchScreen.h> As said earlier we need to calibrate the LCD screen to make it work as expected, but don’t worry the values given here are almost universal. The variables TS_MINX, TS_MINY, TS_MAXX, and TS_MAXY decide the calibration of the Screen. You can toy around them if you feel the calibration is not satisfactory. #define TS_MINX 125 #define TS_MINY 85 #define TS_MAXX 965 #define TS_MAXY 905 As we know the TFT LCD screen can display a lot of colours, all these colours have to be entered in hex value. To make it more human readable we assign these values to a variable as shown below. #define WHITE 0x0000 //Black->White #define YELLOW 0x001F //Blue->Yellow #define CYAN 0xF800 //Red->Cyan #define PINK 0x07E0 //Green-> Pink #define RED 0x07FF //Cyan -> Red #define GREEN 0xF81F //Pink -> Green #define BLUE 0xFFE0 //Yellow->Blue #define BLACK 0xFFFF //White-> Black One is creating a UI of a calculator with buttons and display. Then, detecting the buttons based on the users touch and finally calculating the results and display them. Let us get through them one by one. I have used the line and box drawing abilities to design an UI which looks very similar to the 90’s calculator. Each box has a width and height of 60 pixels. //Draw the Result Box tft.fillRect(0, 0, 240, 80, CYAN); //Draw First Column tft.fillRect (0,260,60,60,RED); tft.fillRect (0,200,60,60,BLACK); tft.fillRect (0,140,60,60,BLACK); tft.fillRect (0,80,60,60,BLACK); //Draw Third Column tft.fillRect (120,260,60,60,GREEN); tft.fillRect (120,200,60,60,BLACK); tft.fillRect (120,140,60,60,BLACK); tft.fillRect (120,80,60,60,BLACK); //Draw Secound & Fourth Column for (int b=260; b>=80; b-=60) { tft.fillRect (180,b,60,60,BLUE); tft.fillRect (60,b,60,60,BLACK);} //Draw Horizontal Lines for (int h=80; h<=320; h+=60) tft.drawFastHLine(0, h, 240, WHITE); //Draw Vertical Lines for (int v=0; v<=240; v+=60) tft.drawFastVLine(v, 80, 240, WHITE); //Display keypad lables for (int j=0;j<4;j++) { for (int i=0;i<4;i++) { tft.setCursor(22 + (60*i), 100 + (60*j)); tft.setTextSize(3); tft.setTextColor(WHITE); tft.println(symbol[j][i]); Every time the user touches somewhere we will able to how where the X and Y position of the pixel he touched. This value can be displayed on the serial monitor using the println as shown below. TSPoint p = waitTouch(); X = p.y; Y = p.x; Serial.print(X); Serial.print(','); Serial.println(Y);// + " " + Y); Since we have designed the box with width and height of 60 pixel each and have four Rows and for columns starting from (0,0). The position of each box can be predicted as shown in below picture. But in practical case, this will not be the result. There will be a big difference between the expected and actual value, due to the calibration problem. So, to predict the exact position of the box, you have to click on the line and check its corresponding position on the serial monitor. This might not be most professional way of doing it, but still it works perfectly. I measured the position of all the lines and obtained the below values. Now, since we know the position of all the boxes. When a user touches anywhere we can predict where he has touched by comparing his (X,Y) values with the value for each box as shown below. if (X<105 && X>50) //Detecting Buttons on Column 2 { if (Y>0 && Y<85) {Serial.println ("Button 0"); //Button 0 is Pressed if (Number==0) Number=0; else Number = (Number*10) + 0; //Pressed twice } if (Y>85 && Y<140) {Serial.println ("Button 2"); if (Number==0) Number=2; else Number = (Number*10) + 2; //Pressed twice } can perform operation with 2 numbers only. These two numbers are named as variables “Num1ᾠand “Num2ᾮ The variable “Numberᾠgives and takes value from Num1 and Num2 and also bears the result. When a use presses a button, one digit is added to number. When another button is pressed, the previous one digit is multiplied with 10 and the new number is added with it. For example, if we press 8 and then press 5 and then press 7. Then first the variable will hold 8 then (8*10)+5=85 then (85*10)+7 = 857. So finally the variable will have the value 857 with it. if (Y>192 && Y<245) {Serial.println ("Button 8"); if (Number==0) Number=8; else Number = (Number*10) + 8; //Pressed again } and then Number will be made zero so that it gets ready to take the input for second number. and then the respective calculation (in this case addition) will be made and the result will be again stored in the variable “Numberᾮ Finally this value will be displayed in the LCD screen.

Working:

is simple. You have to upload the below given code on your Arduino and fire it up. You get the calculator displayed on your LCD screen. Now, you can enter any number and perform your calculations. It is limited to only two operand and only operator for now. But, you can tweak the code to make it have lots of option. You have to press the “Cᾠto clear the value on screen each time after performing a calculation. Hope you understood the project and enjoyed building something similar. If you have any doubts feel free to post them on forums or on the comment section below. See you next time with another interesting project until then happy computing!! Below. Code /*______Import Libraries_______*/ #include <SPFD5408_Adafruit_GFX.h> // Core graphics library #include <SPFD5408_Adafruit_TFTLCD.h> // Hardware-specific library #include <SPFD5408_TouchScreen.h> /*______End of Libraries_______*/ /*______Define LCD pins (I have asigned the default values)_______*/ #define YP A1 // must be an analog pin, use "An" notation! #define XM A2 // must be an analog pin, use "An" notation! #define YM 7 // can be a digital pin #define XP 6 // can be a digital pin #define LCD_CS A3 #define LCD_CD A2 #define LCD_WR A1 #define LCD_RD A0 #define LCD_RESET A4 /*_______End of defanitions______*/ /*______Assign names to colors and pressure_______*/ #define WHITE 0x0000 //Black->White #define YELLOW 0x001F //Blue->Yellow #define CYAN 0xF800 //Red->Cyan #define PINK 0x07E0 //Green-> Pink #define RED 0x07FF //Cyan -> Red #define GREEN 0xF81F //Pink -> Green #define BLUE 0xFFE0 //Yellow->Blue #define BLACK 0xFFFF //White-> Black #define MINPRESSURE 10 #define MAXPRESSURE 1000 /*_______Assigned______*/ /*____Calibrate TFT LCD_____*/ #define TS_MINX 125 #define TS_MINY 85 #define TS_MAXX 965 #define TS_MAXY 905 /*______End of Calibration______*/ TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300); //300 is the sensitivity Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET); //Start communication with LCD String symbol[4][4] = { { "7", "8", "9", "/" }, { "4", "5", "6", "*" }, { "1", "2", "3", "-" }, { "C", "0", "=", "+" } }; int X,Y; long Num1,Num2,Number; char action; boolean result = false; void setup() { Serial.begin(9600); //Use serial monitor for debugging tft.reset(); //Always reset at start tft.begin(0x9341); // My LCD uses LIL9341 Interface driver IC tft.setRotation(2); // I just roated so that the power jack faces up - optional tft.fillScreen(WHITE); IntroScreen(); draw_BoxNButtons(); } void loop() { TSPoint p = waitTouch(); X = p.y; Y = p.x; // Serial.print(X); Serial.print(','); Serial.println(Y);// + " " + Y); DetectButtons(); if (result==true) CalculateResult(); DisplayResult(); delay(300); } TSPoint waitTouch() { TSPoint p; do { p = ts.getPoint(); pinMode(XM, OUTPUT); pinMode(YP, OUTPUT); } while((p.z < MINPRESSURE )|| (p.z > MAXPRESSURE)); p.x = map(p.x, TS_MINX, TS_MAXX, 0, 320); p.y = map(p.y, TS_MINY, TS_MAXY, 0, 240);; return p; } void DetectButtons() { if (X<50 && X>0) //Detecting Buttons on Column 1 { if (Y>0 && Y<85) //If cancel Button is pressed {Serial.println ("Button Cancel"); Number=Num1=Num2=0; result=false;} if (Y>85 && Y<140) //If Button 1 is pressed {Serial.println ("Button 1"); if (Number==0) Number=1; else Number = (Number*10) + 1; //Pressed twice } if (Y>140 && Y<192) //If Button 4 is pressed {Serial.println ("Button 4"); if (Number==0) Number=4; else Number = (Number*10) + 4; //Pressed twice } if (Y>192 && Y<245) //If Button 7 is pressed {Serial.println ("Button 7"); if (Number==0) Number=7; else Number = (Number*10) + 7; //Pressed twice } } if (X<105 && X>50) //Detecting Buttons on Column 2 { if (Y>0 && Y<85) {Serial.println ("Button 0"); //Button 0 is Pressed if (Number==0) Number=0; else Number = (Number*10) + 0; //Pressed twice } if (Y>85 && Y<140) {Serial.println ("Button 2"); if (Number==0) Number=2; else Number = (Number*10) + 2; //Pressed twice } if (Y>140 && Y<192) {Serial.println ("Button 5"); if (Number==0) Number=5; else Number = (Number*10) + 5; //Pressed twic } if (Y>192 && Y<245) {Serial.println ("Button 8"); if (Number==0) Number=8; else Number = (Number*10) + 8; //Pressed twic } } if (X<165 && X>105) //Detecting Buttons on Column 3 { if (Y>0 && Y<85) {Serial.println ("Button Equal"); Num2=Number; result = true; } if (Y>85 && Y<140) {Serial.println ("Button 3"); if (Number==0) Number=3; else Number = (Number*10) + 3; //Pressed twice } if (Y>140 && Y<192) {Serial.println ("Button 6"); if (Number==0) Number=6; else Number = (Number*10) + 6; //Pressed twice } if (Y>192 && Y<245) {Serial.println ("Button 9"); if (Number==0) Number=9; else Number = (Number*10) + 9; //Pressed twice } } if (X<213 && X>165) //Detecting Buttons on Column 3 { Num1 = Number; Number =0; tft.setCursor(200, 20); tft.setTextColor(RED); if (Y>0 && Y<85) {Serial.println ("Addition"); action = 1; tft.println('+');} if (Y>85 && Y<140) {Serial.println ("Subtraction"); action = 2; tft.println('-');} if (Y>140 && Y<192) {Serial.println ("Multiplication"); action = 3; tft.println('*');} if (Y>192 && Y<245) {Serial.println ("Devesion"); action = 4; tft.println('/');} delay(300); } } void CalculateResult() { if (action==1) Number = Num1+Num2; if (action==2) Number = Num1-Num2; if (action==3) Number = Num1*Num2; if (action==4) Number = Num1/Num2; } void DisplayResult() { tft.fillRect(0, 0, 240, 80, CYAN); //clear result box tft.setCursor(10, 20); tft.setTextSize(4); tft.setTextColor(BLACK); tft.println(Number); //update new value } void IntroScreen() { tft.setCursor (55, 120); tft.setTextSize (3); tft.setTextColor(RED); tft.println("ARDUINO"); tft.setCursor (30, 160); tft.println("CALCULATOR"); tft.setCursor (30, 220); tft.setTextSize (2); tft.setTextColor(BLUE); tft.println("-Circut Digest"); delay(1800); } void draw_BoxNButtons() { //Draw the Result Box tft.fillRect(0, 0, 240, 80, CYAN); //Draw First Column tft.fillRect (0,260,60,60,RED); tft.fillRect (0,200,60,60,BLACK); tft.fillRect (0,140,60,60,BLACK); tft.fillRect (0,80,60,60,BLACK); //Draw Third Column tft.fillRect (120,260,60,60,GREEN); tft.fillRect (120,200,60,60,BLACK); tft.fillRect (120,140,60,60,BLACK); tft.fillRect (120,80,60,60,BLACK); //Draw Secound & Fourth Column for (int b=260; b>=80; b-=60) { tft.fillRect (180,b,60,60,BLUE); tft.fillRect (60,b,60,60,BLACK);} //Draw Horizontal Lines for (int h=80; h<=320; h+=60) tft.drawFastHLine(0, h, 240, WHITE); //Draw Vertical Lines for (int v=0; v<=240; v+=60) tft.drawFastVLine(v, 80, 240, WHITE); //Display keypad lables for (int j=0;j<4;j++) { for (int i=0;i<4;i++) { tft.setCursor(22 + (60*i), 100 + (60*j)); tft.setTextSize(3); tft.setTextColor(WHITE); tft.println(symbol[j][i]); } } } Video microcontroller-projects/stepper-motor-control-with-potentiometer-arduino

How to Control Stepper Motor using Potentiometer and Arduino

, like if you turn the potentiometer clockwise then stepper will rotate clockwise and if you turn potentiometer anticlockwise then it will rotate anticlockwise.

Stepper Motors:

Meaning, they will move only one step at a time. These motors have a sequence of coils present in them and these coils have to be energized in a particular fashion to make the motor rotate. When each coil is being energized the motor takes a step and a sequence of energization will make the motor take continuous steps, thus making it to rotate. Let us take a look at the coils present inside the motor to know exactly know from where these wires come from. As you can see the motor has Unipolar 5-lead coil arrangement. There are four coils which have to be energized in a particular sequence. The Red wires will be supplied with +5V and the remaining four wires will be pulled to ground for triggering the respective coil. We use a microcontroller like Arduino energize these coils in a particular sequence and make the motor perform the required number of steps. ? Seriously!!! I don’t know. There is no technical reason for this motor for being named so; maybe we should dive much deeper into it. Let us look at some of the important technical data obtained from the datasheet of this motor in the picture below. That is a head full of information, but we need to look at few important ones to know what type of stepper we are using so that we can program it efficiently. First we know that it is a 5V Stepper motor since we energize the Red wire with 5V. Then, we also know that it is a four phase stepper motor since it had four coils in it. Now, the gear ratio is given to be 1:64. This means the shaft that you see outside will make one complete rotation only if the motor inside rotates for 64 times. This is because of the gears that are connected between the motor and output shaft, these gears help in increasing the torque. This means that the motor when operates in 8-step sequence will move 5.625 degree for each step and it will take 64 steps (5.625*64=360) to complete one full rotation.

Calculating the Steps per Revolution for Stepper Motor:

It is important to know how to calculate the steps per Revolution for your stepper motor because only then you can program it effectively. In Arduino we will be operating the motor in 4-step sequence so the stride angle will be 11.25° since it is 5.625°(given in datasheet) for 8 step sequence it will be 11.25° (5.625*2=11.25). Steps per revolution = 360/step angle

Why so we need Driver modules for Stepper motors?

There are a many types of driver module and the rating of one will change based on the type of motor used. The primary principle for all driver modules will be to source/sink enough current for the motor to operate.

Circuit Diagram for Rotating Stepper Motorusing Potentiometer:

is shown above. We have used the 28BYJ-48 Stepper motor and the ULN2003 Driver module. To energise the four coils of the stepper motor we are using the digital pins 8,9,10 and 11. The driver module is powered by the 5V pin of the Arduino Board.A potentiometer is connected to A0 based in whose values we will rotate the Stepper motor. But, power the driver with External Power supply when you are connecting some load to the steppe motor. Since I am just using the motor for demonstration purpose I have used the +5V rail of the Arduino Board. Also remember to connect the Ground of the Arduino with the ground of the Driver module.

Code forArduino Board:

Before we start programming with our Arduino, let us understand what should actually happen inside the program. As said earlier we will be using 4-step sequence method so we will have four steps to perform for making one complete rotation.
Step 18 and 9A and B
Step 29 and 10B and C
Step 310 and 11C and D
Step 411 and 8D and A
can be found at the end of this tutorial. The complete program can be found at the end of the tutorial few important lines are explained below. The number of steps per revolution for our stepper motor was calculated to be 32; hence we enter that as shown in the line below #define STEPS 32 Next you have to create instances in which we specify the pins to which we have connected the Stepper motor. Stepper stepper (STEPS, 8, 10, 9, 11); The pins number are disordered as 8,10,9,11 on purpose. You have to follow the same pattern even if you change the pins to which your motor is connected. Since we are using the Arduino stepper library, we can set the speed of the motor using the below line. The speed can range between 0 to 200 for 28-BYJ48 stepper motors. stepper.setSpeed(200); Now, to make the motor move one step clockwise we can use the following line. stepper.step(1); To make the motor move one step anti-clockwise we can use the following line. stepper.step(-1); In our program we will read the value of the Analog pin A0 and compare it with previous value (Pval). If it has increased we move 5 steps in clockwise and if it is decreased then we move 5 steps in anti-clockwise. potVal = map(analogRead(A0),0,1024,0,500); if (potVal>Pval) stepper.step(5); if (potVal<Pval) stepper.step(-5); Pval = potVal;

Working:

Once the connection is made the hardware should look something like this in the picture below. Rotating it in clockwise will turn the stepper motor in clockwise direction and vice versa. below. If you have any doubts post them on the comment section below or on our forums. Code #include <Stepper.h> // Include the header file // change this to the number of steps on your motor #define STEPS 32 // create an instance of the stepper class using the steps and pins Stepper stepper(STEPS, 8, 10, 9, 11); int Pval = 0; int potVal = 0; void setup() { Serial.begin(9600); stepper.setSpeed(200); } void loop() { potVal = map(analogRead(A0),0,1024,0,500); if (potVal>Pval) stepper.step(5); if (potVal<Pval) stepper.step(-5); Pval = potVal; Serial.println(Pval); //for debugging } Video microcontroller-projects/arduino-ac-voltmeter

AC Voltmeter using Arduino

which will measure the voltage of Alternating Current Supply at our home. We are going to print that voltage on serial monitor of Arduino IDE as well as show on the multimeter. : Simple Digital Voltmeter Circuit with PCB using ICL7107 LM3914 Voltmeter Circuit 0-25V Digital Voltmeter using AVR Microcontroller

Required Components:

One 12-0-12 transformer 1N4007 diode 1uf capacitor Resistors 10k; 4.7k. Zener diode(5v) Arduino UNO Connecting wires

Arduino Voltmeter Circuit Diagram:

is shown above. Connect high voltage side(220V) of transformer to the mains supply and low voltage(12v) to the voltage divider circuit. Connect 10k resistor in series with 4.7k resistor but make sure to take voltage as input across 4.7k resistor. Connect diode as shown. Connect capacitor and zener diode across 4.7k Connect a wire from n-terminal of diode to the analog pin A0 of Arduino. Do connect ground pin of Arduino to the point as shown in the figure or circuit will not work. As we are using 220/12 v transformer, we get 12 v on l.v side. Since this voltage is not suitable as input for Arduino we need a voltage divider circuit which can give suitable voltage value as input to Arduino to learn more about rectification. This rectified voltage is not smooth as it contains large ripples which cannot give us any exact analog value. Hence capacitor is connected to smooth out the a.c signal. Arduino can get damage if voltage greater than 5v is fed to it. Hence a 5v zener diode is connected to ensure safety of Arduino which breakdowns in case this voltage exceeded 5v.

Working of Arduinobased AC Voltmeter:

1. Step down voltage is obtained on l.v side of transformer which is suitable to use across normal power rating resistors. 2. Then we get suitable voltage value across 4.7k resistor Maximum voltage that can be measured is found by simulating this circuit on proteus (explained in simulation section). 3. Arduino takes this voltage as input from pin A0 in form of analog values between 0 to 1023. 0 being 0 volt and 1023 being 5v. 4. Arduino then converts this analog value into corresponding mains a.c. voltage by a formula. (Explained in code section).

Simulation:

Exact circuit is made in proteus and then simulated. To find maximum voltage that this circuit can measure hit and trial method is used. On making alternator’s peak voltage 440 (311 r.m.s), voltage on pin A0 was found to be 5 volts i.e. maximum. Hence this circuit can measure maximum 311 r.m.s voltage. Simulation is performed for various voltages between 220 r.m.s to 440v.

Code Explanation:

is given at the end of this project and it is well explained through the comments. Here we are explaining few part of it. m is the input analog value received on pin A0 i.e., m= pinMode (A0,INPUT) ; // set pin a0 as input pin first some sort of calculations is performed by using the data obtained in simulation section: As seen in simulation photograph, 5v or 1023 analog value is obtained at pin A0 when input a.c voltage is 311volts. Hence: So any random analog value corresponds to (311/1023)*m where m is obtained analog value. Hence we arrive at this formula: below. Analog input value as specified in the code: Serial.print(" analog input ") ; // this gives name which is “analog input” to the printed analog value Serial.print(m);// this simply prints the input analog value Required a.c voltage as specified in the code: Serial.print(" ac voltage ") ; // this gives name “ac voltageᾠ to the printed analog value Serial.print(n) ; // this simply prints the ac voltage value Code int m;// initialise variable m float n;//initialise variable n void setup() { pinMode(A0,INPUT); // set pin a0 as input pin Serial.begin(9600);// begin serial communication between arduino and pc } void loop() { m=analogRead(A0);// read analog values from pin A0 across capacitor n=(m* .304177);// converts analog value(x) into input ac supply value using this formula ( explained in woeking section) Serial.print(" analaog input " ) ; // specify name to the corresponding value to be printed Serial.print(m) ; // print input analog value on serial monitor Serial.print(" ac voltage ") ; // specify name to the corresponding value to be printed Serial.print(n) ; // prints the ac value on Serial monitor Serial.println(); } Video microcontroller-projects/arduino-stepper-motor-control-tutorial

Arduino Stepper Motor Tutorial - Interfacing 28-BYJ48 Stepper Motor with Arduino Uno

Stepper Motors:

Meaning, they will move only one step at a time. These motors have a sequence of coils present in them and these coils have to be energized in a particular fashion to make the motor rotate. When each coil is being energized the motor takes a step and a sequence of energization will make the motor take continuous steps, thus making it to rotate. Let us take a look at the coils present inside the motor to know exactly know from where these wires come from. As you can see the motor has Unipolar 5-lead coil arrangement. There are four coils which have to be energized in a particular sequence. The Red wires will be supplied with +5V and the remaining four wires will be pulled to ground for triggering the respective coil. We use a microcontroller like Arduino energize these coils in a particular sequence and make the motor perform the required number of steps. ? Seriously!!! I don’t know. There is no technical reason for this motor for being named so; maybe we should dive much deeper into it. Let us look at some of the important technical data obtained from the datasheet of this motor in the picture below. That is a head full of information, but we need to look at few important ones to know what type of stepper we are using so that we can program it efficiently. First we know that it is a 5V Stepper motor since we energize the Red wire with 5V. Then, we also know that it is a four phase stepper motor since it had four coils in it. Now, the gear ratio is given to be 1:64. This means the shaft that you see outside will make one complete rotation only if the motor inside rotates for 64 times. This is because of the gears that are connected between the motor and output shaft, these gears help in increasing the torque.

Calculating the Steps per Revolution for Stepper Motor:

It is important to know how to calculate the steps per Revolution for your stepper motor because only then you can program it effectively. In Arduino we will be operating the motor in 4-step sequence so the stride angle will be 11.25° since it is 5.625°(given in datasheet) for 8 step sequence it will be 11.25° (5.625*2=11.25). Steps per revolution = 360/step angle

Why so we need Driver modules for Stepper motors?

There are a many types of driver module and the rating of one will change based on the type of motor used. The primary principle for all driver modules will be to source/sink enough current for the motor to operate.

ArduinoStepper Motor Position Control Circuit Diagram and Explanation:

is shown above. We have used the 28BYJ-48 Stepper motor and the ULN2003 Driver module. To energise the four coils of the stepper motor we are using the digital pins 8,9,10 and 11. The driver module is powered by the 5V pin of the Arduino Board. But, power the driver with External Power supply when you are connecting some load to the steppe motor. Since I am just using the motor for demonstration purpose I have used the +5V rail of the Arduino Board. Also remember to connect the Ground of the Arduino with the ground of the Diver module.

Code forArduino Board:

Before we start programming with our Arduino, let us understand what should actually happen inside the program. As said earlier we will be using 4-step sequence method so we will have four steps to perform for making one complete rotation.
Step 18 and 9A and B
Step 29 and 10B and C
Step 310 and 11C and D
Step 411 and 8D and A
The Driver module will have four LED using which we can check which coil is being energised at any given time. The video which shows the sequence of energization can be found at the end of this tutorial. in such a way that we can enter the number of steps to be taken by the stepper motor through the serial monitor of the Arduino. The complete program can be found at the end of the tutorial few important lines are explained below. The number of steps per revolution for our stepper motor was calculated to be 32; hence we enter that as shown in the line below #define STEPS 32 Next you have to create instances in which we specify the pins to which we have connected the Stepper motor. Stepper stepper (STEPS, 8, 10, 9, 11); The pins number are disordered as 8,10,9,11 on purpose. You have to follow the same pattern even if you change the pins to which your motor is connected. Since we are using the Arduino stepper library, we can set the speed of the motor using the below line. The speed can range between 0 to 200 for 28-BYJ48 stepper motors. stepper.setSpeed(200); Now, to make the motor move one step we can use the following line. stepper.step(val); The number of steps to be moved will be provided by the variable “valᾮ Since we have 32 steps and 64 as the gear ratio we need to move 2048 (32*64=2048), to make one complete rotation. The value of the variable “valᾠcan be entered by the user using the serial monitor.

Working of Stepper Motor with Arduino:

Once the connection is made the hardware should look something like this in the picture below. Now, upload the below program in your Arduino UNO and open the serial monitor. As discussed earlier we will have to make 2048 steps to make one complete rotation, so when we enter 2048 the motor will make one complete rotation in clockwise direction by making 2048 steps. To rotate in anti-clockwise just enter the number with “–“negative sign. So, entering -1024 will make the motor to rotate half the way in anti-clock wise direction. You can enter any desired values, like entering 1will make the motor to take only one step. Hope you understood the project and enjoyed building it. The complete working of the project is shown in the video below. If you have any doubts post them on the comment section below our on our forums. Code // Arduino stepper motor control code #include <Stepper.h> // Include the header file // change this to the number of steps on your motor #define STEPS 32 // create an instance of the stepper class using the steps and pins Stepper stepper(STEPS, 8, 10, 9, 11); int val = 0; void setup() { Serial.begin(9600); stepper.setSpeed(200); } void loop() { if (Serial.available()>0) { val = Serial.parseInt(); stepper.step(val); Serial.println(val); //for debugging } } Video microcontroller-projects/arduino-motion-detector-using-pir-sensor

Arduino Motion Detector using PIR Sensor

and blink a LED and beep a Buzzer whenever a movement is detected. The following components will be needed to build this project.

Materials Required:

PIR Sensor Module Arduino UNO (any version) LED Buzzer Breadboard Connecting Wires 330 ohm resistor

PIR sensor:

stands for Passive Infrared sensor. It is a low cost sensor which can detect the presence of Human beings or animals. There are two important materials present in the sensor one is the pyroelectric crystal which can detect the heat signatures from a living organism (humans/animals) and the other is a Fresnel lenses which can widen the range of the sensor. Also the PIR sensor modules provide us some options to adjust the working of the sensor as shown in below image. The two potentiometers (orange color) are used to control the sensitivity and trigger on time of the sensor. Basically the Dout pin of the sensor is present in between the Vcc and Gnd pins. The module works on 3.3V but can be powered with 5V as well. On the top left corner it also has a trigger pin setup which can be used to make the module work in two different modes. One is the “Hᾠmode and the other is the “Iᾠmode. In “Hᾠmode the output pin Dout will go high (3.3V) when a person is detected within range and goes low after a particular time (time is set by potentiometer). In this mode the output pin will go high irrespective of whether the person is still present inside the range or has left the area. We are using our module in “Hᾠmode in our project. In “Iᾠmode the output pin Dout will go high (3.3V) when a person is detected within range and will stay high as long as he/she stays within the limit of the Sensors range. Once the person has left the area the pin will go low after the particular time which can be set using the potentiometer. Note:The position of potentiometers or pins may vary based on your PIR sensor vendor. Follow the Silk screen to determine you pinouts

Circuit Diagram and Explanation:

by interfacing Arduino with PIR module and blinking an LED/Buzzer is shown in the below image. pin. The complete Program is explained below.

Programming the Arduino:

we have to assign the pin number 2 as input and pin number 3 as output. Then we have to produce a discontinuous trigger whenever the pin 2 goes high. Each line is explained below. In the void setup function shown below, we have to declare that the pin 2 connected to PIR output will be used as input and the pin 3 connected to LED/Buzzer will be used as input. void setup() { pinMode(2, INPUT); //Pin 2 as INPUT pinMode(3, OUTPUT); //PIN 3 as OUTPUT } Then we proceed to the loop() function. As we know the code in here gets executed as long as the MCU is powered on. So we always check if the Pin 2 has gone high by using the below line inside the loop() function. if (digitalRead(2) == HIGH) If we find that the particular pin has gone high, it means that the PIR module has be triggered. So, now we has make our output pin (pin 3) to go high. We turn this pin on and off with a delay of 100 milli second so that we can attain the flashing or buzzing output. The code to do the same is shown below. void setup() { pinMode(2, INPUT); //Pin 2 as INPUT pinMode(3, OUTPUT); //PIN 3 as OUTPUT } void loop() { if (digitalRead(2) == HIGH) // check if PIR is triggered. { digitalWrite(3, HIGH); // turn the LED/Buzz ON delay(100); // wait for 100 msecond digitalWrite(3, LOW); // turn the LED/Buzz OFF delay(100); // wait for 100 msecond } }

Working:

is already discussed above. Now, you can build this circuit on a breadboard by following the schematics given above and upload the program which could found at the end of this tutorial. Once your connections are done your set-up should look like something shown below. Now, power on the Arduino and wait for about 50-60 seconds for your PIR sensor to calibrate. Do not be frustrated by the output that you get during this period. After that, try moving in front of the PIR sensor and you LED/Buzzer should be triggered as shown in the video below. The beeping/flashing should stop after some time; you can now toy around the output by varying the potentiometer to change the sensitivity or the low time of the module. Hope you understood the project and got it working, if you have any trouble in getting this thing work, you can search out through the comment section or on our forums. Code void setup() { pinMode(2, INPUT); //Pin 2 as INPUT pinMode(3, OUTPUT); //PIN 3 as OUTPUT } void loop() { if (digitalRead(2) == HIGH) { digitalWrite(3, HIGH); // turn the LED/Buzz ON delay(100); // wait for 100 msecond digitalWrite(3, LOW); // turn the LED/Buzz OFF delay(100); // wait for 100 msecond } } Video microcontroller-projects/fingerprint-attendance-system-using-arduino-uno

Fingerprint Based Biometric Attendance System using Arduino

RequiredComponents

Arduino -1 Finger print module -1 Push Button - 4 LEDs -1 1K Resistor -2 2.2K resistor -1 Power Connecting wires Box Buzzer -1 16x2 LCD -1 Bread Board -1 RTC Module -1

Project Description:

to authenticate a true person or employee by taking their finger input inthe system. Here we are using 4 push buttons to enroll, Delete, UP/Down. ENROLL and DEL key has triple features. ENROLL key is used for enrollment of a new person into the system. So when the user wants to enroll new finger then he/she need to press ENROLL key then LCD asks for the ID, where user want to be store the finger print image. Now if at this time user does not want to proceed further then he/she can press ENROLL key again to go back. This time ENROLL key behave as Back key, i.e. ENROLL key has both enrollment and back function. Besides enroll key is also used to download attendance data over serial monitor. Similarly, DEL/OK key also has the same double function like when user enrolls new finger, then he/she need to select finger ID by using another two key namely UP and DOWN. Now user need to press DEL/OK key (this time this key behave like OK) to proceed with selected ID. And Del key is used for reset or delete data from EEPROM of Arduino.

FingerPrint module:

Fingerprint sensor module captures finger’s print image and then converts it into the equivalent template and saves them into its memory as per selected ID by Arduino. All the process is commanded by Arduino like taking an image of finger’s print, convert it into templates and storing as ID etc. You can check some more projects using fingerprint module: Here we have added a Yellow LED which indicates that fingerprint module is ready to take an image of the finger. A buzzer is also used for various indications. Arduino is the main component of this system it is responsible for control of the whole system.

Working of Fingerprint Based Attendance System

is fairly simple. First of all, the user needs to enroll fingerprints of the userwith the help of push buttons. To do this, user need to press ENROLL key and then LCD asks for entering ID for the fingerprint to save it in memory by ID name. So now user needs to enter ID by using UP/DOWN keys. After selecting ID, user needs to press OK key (DEL key). Now LCD will ask to place finger over the fingerprint module. Now user needs to place his finger over finger print module and then the module takes finger image. Now the LCD will say to remove finger from fingerprint module, and again ask toplace finger again. Now user needs to put his finger again and module takes an image and convert it into templates and stores it by selected ID into the finger print module’s memory. Now the user will be registered and he/she can feed attendance by putting their finger over fingerprint module.By the same method, all the users will be registered into the system. Now if the user wants to remove or delete any of the stored ID or fingerprint, then he/she need to press DEL key. Once delete key is pressedLCD will ask to select ID that need to be deleted. Now user needs to select ID and press OK key (same DEL key). Now LCD will let you know that fingerprint has been deleted successfully. Whenever user placehis finger over fingerprint module then fingerprint module captures finger image, and search if any ID is associated with this fingerprint inthe system. If fingerprint ID is detected then LCD will show Attendance registered and in the same time buzzer will beep once and LED will turn off until the system is ready to take input again. Time and date are running continuously in the system. So Arduinotake time and date whenever a true user places his finger over fingerprint and save them in the EEPROM at the allotted slot of memory. Here we have created 5 user space in this system for 30 days. By pressing the RESET button in Arduino and then immediately enroll key will be responsible for downloading attendance data over serial monitor from the Arduino EEPROM Memory. We have 1023 byte memory in Arduino UNO out of which we have 1018 byte to store data and we have taken 5 user attendance data for 30 days. And every attendance will record time and date so this becomes 7-byte data. So total memory required is 5*30*7=1050 so here we need more 32 bytes But if we will use 4 users then we required 4*30*7=840 user. You may try it by 4 users by changing some lines in code. I have made the comments in the codewhere the changes are needed.

Circuit Diagram and Description for Fingerprint Attendance System Project

, as shown in the above diagramis quite simple. It hasArduino for controlling all the process of the project, push button for enrolling, deleting, selecting IDs and for attendance, a buzzer for alerting, LEDs for indication and LCD to instruct user and showing the resultant messages. and its RS, EN, D4, D5, D6, and D7 are directly connected at Digital pin D13, D12, D11, D10,D9, and D8 of Arduino.

Code Explanation:

First of all, we include the header file and defines input and output pin and define the macro and declared variables. After this, in setup function, we give direction to defined pin and initiate LCD and finger print module After it, we have to write code for downloading attendance data. void setup() { delay(1000); lcd.begin(16,2); Serial.begin(9600); pinMode(enroll, INPUT_PULLUP); pinMode(up, INPUT_PULLUP); pinMode(down, INPUT_PULLUP); pinMode(del, INPUT_PULLUP); pinMode(match, INPUT_PULLUP); pinMode(buzzer, OUTPUT); pinMode(indFinger, OUTPUT); digitalWrite(buzzer, LOW); if(digitalRead(enroll) == 0) { digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); lcd.clear(); lcd.print("Please wait"); lcd.setCursor(0,1); lcd.print("Downloding Data"); Afterit,we have to write code for clearing attendance data from EEPROM. if(digitalRead(del) == 0) { lcd.clear(); lcd.print("Please Wait"); lcd.setCursor(0,1); lcd.print("Reseting....."); for(int i=1000;i<1005;i++) EEPROM.write(i,0); for(int i=0;i<841;i++) EEPROM.write(i, 0xff); lcd.clear(); lcd.print("System Reset"); delay(1000); } After it, we initiate finger print module, showing welcome message over LCD and also initeiated RTC module. After it, in loop function, we have read RTC time and displayed it on LCD void loop() { now = rtc.now(); lcd.setCursor(0,0); lcd.print("Time->"); lcd.print(now.hour(), DEC); lcd.print(':'); lcd.print(now.minute(), DEC); lcd.print(':'); lcd.print(now.second(), DEC); lcd.print(" "); lcd.setCursor(0,1); lcd.print("Date->"); lcd.print(now.day(), DEC); lcd.print('/'); lcd.print(now.month(), DEC); lcd.print('/'); lcd.print(now.year(), DEC); After it, waiting for the finger print to take input and compare captured image ID with stored IDs. If amatch occurs then proceed with next step. And checking enroll del keys as well int result=getFingerprintIDez(); if(result>0) { digitalWrite(indFinger, LOW); digitalWrite(buzzer, HIGH); delay(100); digitalWrite(buzzer, LOW); lcd.clear(); lcd.print("ID:"); lcd.print(result); lcd.setCursor(0,1); lcd.print("Please Wait...."); delay(1000); attendance(result); lcd.clear(); lcd.print("Attendance "); lcd.setCursor(0,1); lcd.print("Registed"); delay(1000); digitalWrite(indFinger, HIGH); return; } function is called. function that will delete finger from records. Given Function is used to taking finger print image and convert them into the template and save as well by selected ID into the finger print module memory. uint8_t getFingerprintEnroll() { int p = -1; lcd.clear(); lcd.print("finger ID:"); lcd.print(id); lcd.setCursor(0,1); lcd.print("Place Finger"); delay(2000); while (p != FINGERPRINT_OK) { p = finger.getImage(); ..... ..... ....... .... Given function is used for storing attendance time and date in the allotted slot of EEPROM void attendance(int id) { int user=0,eepLoc=0; if(id == 1) { eepLoc=0; user=user1++; } else if(id == 2) { eepLoc=210; user=user2++; } else if(id == 3) .... .... ..... Given function is used to fetching data from EEPROM and send to serial monitor void download(int eepIndex) { if(EEPROM.read(eepIndex) != 0xff) { Serial.print("T->"); if(EEPROM.read(eepIndex)<10) Serial.print('0'); Serial.print(EEPROM.read(eepIndex++)); Serial.print(':'); if(EEPROM.read(eepIndex)<10) Serial.print('0'); Serial.print(EEPROM.read(eepIndex++)); .... .... ..... Code #include<EEPROM.h> #include<LiquidCrystal.h> LiquidCrystal lcd(13,12,11,10,9,8); #include <SoftwareSerial.h> SoftwareSerial fingerPrint(2, 3); #include <Wire.h> #include "RTClib.h" RTC_DS1307 rtc; #include "Adafruit_Fingerprint.h" uint8_t id; Adafruit_Fingerprint finger = Adafruit_Fingerprint(&fingerPrint); #define enroll 14 #define del 15 #define up 16 #define down 17 #define match 5 #define indFinger 7 #define buzzer 5 #define records 4 // 5 for 5 user int user1,user2,user3,user4,user5; DateTime now; void setup() { delay(1000); lcd.begin(16,2); Serial.begin(9600); pinMode(enroll, INPUT_PULLUP); pinMode(up, INPUT_PULLUP); pinMode(down, INPUT_PULLUP); pinMode(del, INPUT_PULLUP); pinMode(match, INPUT_PULLUP); pinMode(buzzer, OUTPUT); pinMode(indFinger, OUTPUT); digitalWrite(buzzer, LOW); if(digitalRead(enroll) == 0) { digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); lcd.clear(); lcd.print("Please wait"); lcd.setCursor(0,1); lcd.print("Downloding Data"); Serial.println("Please wait"); Serial.println("Downloding Data.."); Serial.println(); Serial.print("S.No. "); for(int i=0;i<records;i++) { digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); Serial.print(" User ID"); Serial.print(i+1); Serial.print(" "); } Serial.println(); int eepIndex=0; for(int i=0;i<30;i++) { if(i+1<10) Serial.print('0'); Serial.print(i+1); Serial.print(" "); eepIndex=(i*7); download(eepIndex); eepIndex=(i*7)+210; download(eepIndex); eepIndex=(i*7)+420; download(eepIndex); eepIndex=(i*7)+630; download(eepIndex); // eepIndex=(i*7)+840; // 5th user // download(eepIndex); Serial.println(); } } if(digitalRead(del) == 0) { lcd.clear(); lcd.print("Please Wait"); lcd.setCursor(0,1); lcd.print("Reseting....."); for(int i=1000;i<1005;i++) EEPROM.write(i,0); for(int i=0;i<841;i++) EEPROM.write(i, 0xff); lcd.clear(); lcd.print("System Reset"); delay(1000); } lcd.clear(); lcd.print(" Attendance "); lcd.setCursor(0,1); lcd.print(" System "); delay(2000); lcd.clear(); lcd.print("Circuit Digest"); lcd.setCursor(0,1); lcd.print("Saddam Khan"); delay(2000); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); for(int i=1000;i<1000+records;i++) { if(EEPROM.read(i) == 0xff) EEPROM.write(i,0); } finger.begin(57600); Serial.begin(9600); lcd.clear(); lcd.print("Finding Module"); lcd.setCursor(0,1); delay(1000); if (finger.verifyPassword()) { Serial.println("Found fingerprint sensor!"); lcd.clear(); lcd.print("Found Module "); delay(1000); } else { Serial.println("Did not find fingerprint sensor :("); lcd.clear(); lcd.print("module not Found"); lcd.setCursor(0,1); lcd.print("Check Connections"); while (1); } if (! rtc.begin()) Serial.println("Couldn't find RTC"); // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); if (! rtc.isrunning()) { Serial.println("RTC is NOT running!"); // following line sets the RTC to the date & time this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // This line sets the RTC with an explicit date & time, for example to set // January 21, 2014 at 3am you would call: // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); } lcd.setCursor(0,0); lcd.print("Press Match to "); lcd.setCursor(0,1); lcd.print("Start System"); delay(2000); user1=EEPROM.read(1000); user2=EEPROM.read(1001); user3=EEPROM.read(1002); user4=EEPROM.read(1003); user5=EEPROM.read(1004); lcd.clear(); digitalWrite(indFinger, HIGH); } void loop() { now = rtc.now(); lcd.setCursor(0,0); lcd.print("Time->"); lcd.print(now.hour(), DEC); lcd.print(':'); lcd.print(now.minute(), DEC); lcd.print(':'); lcd.print(now.second(), DEC); lcd.print(" "); lcd.setCursor(0,1); lcd.print("Date->"); lcd.print(now.day(), DEC); lcd.print('/'); lcd.print(now.month(), DEC); lcd.print('/'); lcd.print(now.year(), DEC); lcd.print(" "); delay(500); int result=getFingerprintIDez(); if(result>0) { digitalWrite(indFinger, LOW); digitalWrite(buzzer, HIGH); delay(100); digitalWrite(buzzer, LOW); lcd.clear(); lcd.print("ID:"); lcd.print(result); lcd.setCursor(0,1); lcd.print("Please Wait...."); delay(1000); attendance(result); lcd.clear(); lcd.print("Attendance "); lcd.setCursor(0,1); lcd.print("Registed"); delay(1000); digitalWrite(indFinger, HIGH); return; } checkKeys(); delay(300); } // dmyyhms - 7 bytes void attendance(int id) { int user=0,eepLoc=0; if(id == 1) { eepLoc=0; user=user1++; } else if(id == 2) { eepLoc=210; user=user2++; } else if(id == 3) { eepLoc=420; user=user3++; } else if(id == 4) { eepLoc=630; user=user4++; } /*else if(id == 5) // fifth user { eepLoc=840; user=user5++; }*/ else return; int eepIndex=(user*7)+eepLoc; EEPROM.write(eepIndex++, now.hour()); EEPROM.write(eepIndex++, now.minute()); EEPROM.write(eepIndex++, now.second()); EEPROM.write(eepIndex++, now.day()); EEPROM.write(eepIndex++, now.month()); EEPROM.write(eepIndex++, now.year()>>8 ); EEPROM.write(eepIndex++, now.year()); EEPROM.write(1000,user1); EEPROM.write(1001,user2); EEPROM.write(1002,user3); EEPROM.write(1003,user4); // EEPROM.write(4,user5); // figth user } void checkKeys() { if(digitalRead(enroll) == 0) { lcd.clear(); lcd.print("Please Wait"); delay(1000); while(digitalRead(enroll) == 0); Enroll(); } else if(digitalRead(del) == 0) { lcd.clear(); lcd.print("Please Wait"); delay(1000); delet(); } } void Enroll() { int count=1; lcd.clear(); lcd.print("Enter Finger ID:"); while(1) { lcd.setCursor(0,1); lcd.print(count); if(digitalRead(up) == 0) { count++; if(count>records) count=1; delay(500); } else if(digitalRead(down) == 0) { count--; if(count<1) count=records; delay(500); } else if(digitalRead(del) == 0) { id=count; getFingerprintEnroll(); for(int i=0;i<records;i++) { if(EEPROM.read(i) != 0xff) { EEPROM.write(i, id); break; } } return; } else if(digitalRead(enroll) == 0) { return; } } } void delet() { int count=1; lcd.clear(); lcd.print("Enter Finger ID"); while(1) { lcd.setCursor(0,1); lcd.print(count); if(digitalRead(up) == 0) { count++; if(count>records) count=1; delay(500); } else if(digitalRead(down) == 0) { count--; if(count<1) count=records; delay(500); } else if(digitalRead(del) == 0) { id=count; deleteFingerprint(id); for(int i=0;i<records;i++) { if(EEPROM.read(i) == id) { EEPROM.write(i, 0xff); break; } } return; } else if(digitalRead(enroll) == 0) { return; } } } uint8_t getFingerprintEnroll() { int p = -1; lcd.clear(); lcd.print("finger ID:"); lcd.print(id); lcd.setCursor(0,1); lcd.print("Place Finger"); delay(2000); while (p != FINGERPRINT_OK) { p = finger.getImage(); switch (p) { case FINGERPRINT_OK: Serial.println("Image taken"); lcd.clear(); lcd.print("Image taken"); break; case FINGERPRINT_NOFINGER: Serial.println("No Finger"); lcd.clear(); lcd.print("No Finger"); break; case FINGERPRINT_PACKETRECIEVEERR: Serial.println("Communication error"); lcd.clear(); lcd.print("Comm Error"); break; case FINGERPRINT_IMAGEFAIL: Serial.println("Imaging error"); lcd.clear(); lcd.print("Imaging Error"); break; default: Serial.println("Unknown error"); lcd.clear(); lcd.print("Unknown Error"); break; } } // OK success! p = finger.image2Tz(1); switch (p) { case FINGERPRINT_OK: Serial.println("Image converted"); lcd.clear(); lcd.print("Image converted"); break; case FINGERPRINT_IMAGEMESS: Serial.println("Image too messy"); lcd.clear(); lcd.print("Image too messy"); return p; case FINGERPRINT_PACKETRECIEVEERR: Serial.println("Communication error"); lcd.clear(); lcd.print("Comm Error"); return p; case FINGERPRINT_FEATUREFAIL: Serial.println("Could not find fingerprint features"); lcd.clear(); lcd.print("Feature Not Found"); return p; case FINGERPRINT_INVALIDIMAGE: Serial.println("Could not find fingerprint features"); lcd.clear(); lcd.print("Feature Not Found"); return p; default: Serial.println("Unknown error"); lcd.clear(); lcd.print("Unknown Error"); return p; } Serial.println("Remove finger"); lcd.clear(); lcd.print("Remove Finger"); delay(2000); p = 0; while (p != FINGERPRINT_NOFINGER) { p = finger.getImage(); } Serial.print("ID "); Serial.println(id); p = -1; Serial.println("Place same finger again"); lcd.clear(); lcd.print("Place Finger"); lcd.setCursor(0,1); lcd.print(" Again"); while (p != FINGERPRINT_OK) { p = finger.getImage(); switch (p) { case FINGERPRINT_OK: Serial.println("Image taken"); break; case FINGERPRINT_NOFINGER: Serial.print("."); break; case FINGERPRINT_PACKETRECIEVEERR: Serial.println("Communication error"); break; case FINGERPRINT_IMAGEFAIL: Serial.println("Imaging error"); break; default: Serial.println("Unknown error"); return; } } // OK success! p = finger.image2Tz(2); switch (p) { case FINGERPRINT_OK: Serial.println("Image converted"); break; case FINGERPRINT_IMAGEMESS: Serial.println("Image too messy"); return p; case FINGERPRINT_PACKETRECIEVEERR: Serial.println("Communication error"); return p; case FINGERPRINT_FEATUREFAIL: Serial.println("Could not find fingerprint features"); return p; case FINGERPRINT_INVALIDIMAGE: Serial.println("Could not find fingerprint features"); return p; default: Serial.println("Unknown error"); return p; } // OK converted! Serial.print("Creating model for #"); Serial.println(id); p = finger.createModel(); if (p == FINGERPRINT_OK) { Serial.println("Prints matched!"); } else if (p == FINGERPRINT_PACKETRECIEVEERR) { Serial.println("Communication error"); return p; } else if (p == FINGERPRINT_ENROLLMISMATCH) { Serial.println("Fingerprints did not match"); return p; } else { Serial.println("Unknown error"); return p; } Serial.print("ID "); Serial.println(id); p = finger.storeModel(id); if (p == FINGERPRINT_OK) { Serial.println("Stored!"); lcd.clear(); lcd.print("Stored!"); delay(2000); } else if (p == FINGERPRINT_PACKETRECIEVEERR) { Serial.println("Communication error"); return p; } else if (p == FINGERPRINT_BADLOCATION) { Serial.println("Could not store in that location"); return p; } else if (p == FINGERPRINT_FLASHERR) { Serial.println("Error writing to flash"); return p; } else { Serial.println("Unknown error"); return p; } } int getFingerprintIDez() { uint8_t p = finger.getImage(); if (p != FINGERPRINT_OK) return -1; p = finger.image2Tz(); if (p != FINGERPRINT_OK) return -1; p = finger.fingerFastSearch(); if (p != FINGERPRINT_OK) { lcd.clear(); lcd.print("Finger Not Found"); lcd.setCursor(0,1); lcd.print("Try Later"); delay(2000); return -1; } // found a match! Serial.print("Found ID #"); Serial.print(finger.fingerID); return finger.fingerID; } uint8_t deleteFingerprint(uint8_t id) { uint8_t p = -1; lcd.clear(); lcd.print("Please wait"); p = finger.deleteModel(id); if (p == FINGERPRINT_OK) { Serial.println("Deleted!"); lcd.clear(); lcd.print("Figer Deleted"); lcd.setCursor(0,1); lcd.print("Successfully"); delay(1000); } else { Serial.print("Something Wrong"); lcd.clear(); lcd.print("Something Wrong"); lcd.setCursor(0,1); lcd.print("Try Again Later"); delay(2000); return p; } } void download(int eepIndex) { if(EEPROM.read(eepIndex) != 0xff) { Serial.print("T->"); if(EEPROM.read(eepIndex)<10) Serial.print('0'); Serial.print(EEPROM.read(eepIndex++)); Serial.print(':'); if(EEPROM.read(eepIndex)<10) Serial.print('0'); Serial.print(EEPROM.read(eepIndex++)); Serial.print(':'); if(EEPROM.read(eepIndex)<10) Serial.print('0'); Serial.print(EEPROM.read(eepIndex++)); Serial.print(" D->"); if(EEPROM.read(eepIndex)<10) Serial.print('0'); Serial.print(EEPROM.read(eepIndex++)); Serial.print('/'); if(EEPROM.read(eepIndex)<10) Serial.print('0'); Serial.print(EEPROM.read(eepIndex++)); Serial.print('/'); Serial.print(EEPROM.read(eepIndex++)<<8 | EEPROM.read(eepIndex++)); } else { Serial.print("---------------------------"); } Serial.print(" "); } Video microcontroller-projects/arduino-traffic-light-controller-project

Arduino Based 3-Way Traffic Light Controller

Here have demonstrated it for 3 sides or ways. Now let’s get into the project‐󋈍

Components Required:

3*Red LED Lights 3*Green LED Lights 3*Yellow LED Lights 3*220ohm Resistors Breadboard Male To Male Connectors Arduino Uno With Ide Cable

Circuit Explanation:

is given below: It’s pretty simple and can be easily built on bread board as explained in below steps: Connect the LEDs in the order as Red, Green, and Yellow in the breadboard. Place the negative terminal of the LEDs in common and connect the 220ohm resistor in series. Connect the connector wires accordingly. Connect the other end of the wire to the Arduino Uno in the consecutive pins(2,3,4‐󯮩 Power up the breadboard using the Arduino 5v and GND pin.

Program and Working Explanation:

is simple and can be easily understood. Here we have demonstrated Traffic lights for the 3 ways road and the code glows LED’s on all the three sides in a particular sequence, in which the actual Traffic Lights works. Like, at a time, there will be two Red signals on any of the two sides and one Green light on the remaining side. And yellow light will also glow, for 1 second each time, in between transition from Red to Green, means first red light glows for 5 second then yellow light glows for 1 second and then finally green light will be turned on. for 9 LEDs (three on each side i.e. forward, right and left side). void setup() { // configure the output pins pinMode(2,OUTPUT); pinMode(3,OUTPUT); pinMode(4,OUTPUT); pinMode(5,OUTPUT); pinMode(6,OUTPUT); pinMode(7,OUTPUT); pinMode(8,OUTPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); } function we have written the code for traffic lights to be turned on and off in sequence as mentioned above. void loop() { digitalWrite(2,1); //enables the 1st set of signals digitalWrite(7,1); digitalWrite(10,1); digitalWrite(4,0); digitalWrite(3,0); digitalWrite(6,0); digitalWrite(8,0); digitalWrite(9,0); digitalWrite(5,0); delay(5000); ..... .... ..... .... function for continuous process. Here we can modify delays for which the Red, yellow and Green light remain on and off. is given below. Code void setup() { // configure the output pins pinMode(2,OUTPUT); pinMode(3,OUTPUT); pinMode(4,OUTPUT); pinMode(5,OUTPUT); pinMode(6,OUTPUT); pinMode(7,OUTPUT); pinMode(8,OUTPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); } void loop() { digitalWrite(2,1); //enables the 1st set of signals digitalWrite(7,1); digitalWrite(10,1); digitalWrite(4,0); digitalWrite(3,0); digitalWrite(6,0); digitalWrite(8,0); digitalWrite(9,0); digitalWrite(5,0); delay(5000); digitalWrite(3,1); //enables the yellow lights digitalWrite(6,1); digitalWrite(2,0); digitalWrite(7,0); delay(1000); digitalWrite(4,1); //enables the 2nd set of signals digitalWrite(5,1); digitalWrite(10,1); digitalWrite(2,0); digitalWrite(3,0); digitalWrite(6,0); digitalWrite(8,0); digitalWrite(9,0); digitalWrite(7,0); delay(5000); digitalWrite(9,1); //enables the yellow lights digitalWrite(6,1); digitalWrite(10,0); digitalWrite(5,0); digitalWrite(4,0); delay(1000); digitalWrite(8,1); //enables the 3rd set of signals digitalWrite(4,1); digitalWrite(7,1); digitalWrite(2,0); digitalWrite(3,0); digitalWrite(5,0); digitalWrite(6,0); digitalWrite(9,0); digitalWrite(10,0); delay(5000); digitalWrite(9,1); //enables the yellow lights digitalWrite(3,1); digitalWrite(7,0); digitalWrite(8,0); digitalWrite(4,0); delay(1000); } Video microcontroller-projects/arduino-angry-bird-game-controller-with-flex-sensor

Arduino based Angry Bird Game Controller using Flex Sensor and Potentiometer

It’s all started with a small game from the dark ages called “Marioᾬ right from the time of being a tiny little guy jumping on ducks to save my princess till being a masculine handsome Prince roaming in Persia (Prince of Persia) fighting against darkness to save my world behind I have been a great fan of playing video games and I grew up playing them. But they do get bored up sometimes and I feel less involved into it. Today, the advanced gaming consoles enables virtual gaming and helps us to feel the game a lot more better than a keyboard or a mouse can do.

Software and Hardware Requirements:

Arduino IDE Processing IDE Angry Birds Game on Computer Arduino (Any Version) Potentiometer Flex Sensor 47K ohm Resistor Connecting Wires Breadboard

Concept Behind:

function. We then read this information using Processing and control the mouse cursor using the Robot class in Java which is supported by processing IDE. We have programmed the processing IDE in such a way that when the Flex sensor is pulled a mouse click will be made and based on how much it is pulled the mouse pointer will move in X direction. Then based on the value from potentiometer we will move the mouse cursor in Y direction, this way we can set the direction in which bird should be launched.

Circuit Diagram:

is easy. We have simple connected a potentiometer and a flex sensor to the Analog inputs (A0,A1) of the Arduino. The output of the Flex sensor is also pulled down using a 47K pull down resistor. You can directly connect it on breadboard or solder them to a Perf board and assemble it on a gloves or something to make it more creative. I have simply used a breadboard to do my connections as shown below:

Arduino Program:

The complete Arduino code is given at the end of the tutorial. Few important lines are explained below. function can send only one byte of data at a time. Since One byte is 8 bits and 2^8 = 256. We will be able to send values from 0 to 256. So we have to compress the values of Flex sensor output and Potentiometer Output into 0 to 256. function in Arduino. All the values from the flex sensor are converted from 5 to 100, so when we bend the sensor it will increment from 5 and when released it will go back to 5. To mention the mouse clicks the value 1 and 0 is used. When 1 is sent the mouse is pressed and when 0 is sent the mouse is released. if (FlexValue>=65 && FlexValue<=120) //my flex sensor varies from 65 to 120, your might be different { FlexValue = map (FlexValue,120,65,0,100); //based on bending convert to 0 to 100 if (FlexValue>=5) // 1 and 0 is used for mouse click so start from 5 { Mclick=true; Serial.write(1); //1 is sent to make mouse left click Serial.write(FlexValue); //Flex value is the distance to move mouse in X direction } else { Mclick=false; Serial.write(0);} } function as shown below. if (potValue<=200) { potValue = map(potValue,0,200,101,201); //Based in turn convert to 101 to 201 Serial.write(potValue); //Pot value is the distance to move mouse in Y direction } The rest of the program is explained using the comments. is an Open-Source development application and can be easily downloaded and put to use for developing interesting projects using Arduino or other Microcontrollers. We have already done few projects using Processing and you can check them out by clicking on the links below. DIY FM Radio Using Processing Virtual Reality/ Gesture control using Arduino Private Chat room using Arduino. Arduino Radar System using Processing APP and Ultrasonic Sensor Real Time Face Detection and Tracking using Arduino DIY Speedometer using Arduino and Processing Ping Pong Game using Arduino Accelerometer Biped Robot Using Arduino DIY Arduino Thermal Imaging Camera can be downloaded from the below link: Processing Code for this Angry Bird Game Controller(right Click and 'Save link as') Port in my computer and the baud rate in Arduino was 9600 so the code is as follows port = new Serial(this,Serial.list()[0],9600); Once we start reading the values we distinguish it by recognizing it based on its value on how we sent from Arduino. The values are again mapped from 0 to 100 so that we will be able to control the mouse based in that value. if (port.available()>0) { data=port.read(); println(data); //Read the data from COM port and save it in data } if (data>=101 && data<=201) //If the value if from 101 to 201 then it must be from Potentiometer { Turn = int (map (data,101,201,0,100)); //Use that value to turn the catapullt } if (data>=5 && data <=100) //If the value if from 5 to 100 then it must be from Flex Sensor { Pull = int (map(data,5,100,0,100));} //Use that value to pull the catapult if (data == 1) click = true; //Use that value to press the mouse button if (data == 0) click = false; //Use that value to release the mouse button can be used to press or release the mouse button respectively. if (click == false) //when Flex Sesnor is not pulled { crntX = (int)p.getX() ; crntY = (int)p.getY() ; if (Pull>50) robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); //Release the mouse button } if (click == true) //when Flex Sesnor is pulled { robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); //Press the mouse Button robot.mouseMove(crntX-Pull, crntY+Turn); //Move the mouse based on the Flex and POT value } } The processing IDE when launched will also display a small dialog Box on which you can find the values of Pull, Turn and status of Mouse Click as shown below This detail can be used to debug the Program or correct any data required.

Working:

work using the code provided, assemble your hardware according to the circuit diagram and upload the given Arduino Code. Then Note which COM port your Arduino is connected to and make the necessary changes in the Processing code and launch the processing sketch. Now, simply launch the angry bird game and place you cursor near the catapult and pull the flex sensor to pull the bird and set the direction using the potentiometer. Once the direction is set release the Flex sensor EEEEWWWWWEEEEEEEEEE!!!!!!!!!!............... below. Hope you enjoyed the project and were able to build something similar. If you have any doubts you can reach me on the comment section or post your question on the forum for technical questions. Now, time to crash into those piggy boxes and get back our birds eggs!!!! Code /* * Angry Bird Game Controller Program * Code by : B.Aswinth Raj * Dated : 3-8-2017 * More details : www.circuitdigest.com */ void setup() { Serial.begin(9600); //Transmit at 9600 Baud Rate } boolean Mclick = false; void loop() { int potValue = analogRead(A0); //variable to store potValue int FlexValue = analogRead(A1); //variable to store Flex Value // Serial.println(FlexValue); // Serial.print("POT: "); // Serial.println(potValue); // Serial.print("Flex: "); if (FlexValue>=65 && FlexValue<=115) //my flex sensor varies from 65 to 120, your might be different { FlexValue = map (FlexValue,120,65,0,100); //based on bending convert to 0 to 100 if (FlexValue>=5) // 1 and 0 is used for mouse click so start from 5 { Mclick=true; Serial.write(1); //1 is sent to make mouse left click Serial.write(FlexValue); //Flex value is the distance to move mouse in X direction } else { Mclick=false; Serial.write(0);} } else { Mclick=false; Serial.write(0);} if (potValue<=200) { potValue = map(potValue,0,200,101,201); //Based in turn convert to 101 to 201 Serial.write(potValue); //Pot value is the distance to move mouse in Y direction } delay(500); //stability delay } Video microcontroller-projects/fingerprint-based-biometric-voting-machine-arduino

Fingerprint Based Biometric Voting Machine using Arduino

Also check our previous Electronic Voting Machine Projects using different Microcontrollers: Electronic Voting Machine using Raspberry Pi RFID Based Voting Machine AVR Microcontroller Based Electronic Voting Machine Project Electronic Voting Machine using Arduino

Required Components:

Arduino Uno Finger Print Sensor Module Push Buttons LEDs -2 1K Resistor -3 2.2K resistor Power Connecting wires Buzzer 16x2 LCD Bread Board

Finger Print Sensor Module in Voting Machine:

is a module which captures finger’s print image and then converts it into the equivalent template and saves them into its memory on selected ID (location) by Arduino. Here all the process is commanded by Arduino like taking an image of finger print, convert it into templates and storing location etc. is used for whenever voter wants to vote then he/she needs to authenticate first for true voter by keeping finger on Finger Print Sensor, if he/she passed in this authentication then he/she can vote. at the end of this tutorial.

Working Explanation:

is a little bit complex for beginners. First of all, user needs to enroll finger or voters (in this code max limit of the voter is 25) with the help of push buttons/keys. To do this user need to press ENROLL key and then LCD asks for entering location/ID where finger will be a store. So now user needs to enter ID (Location) by using UP/DOWN keys. After selecting Location/ID user needs to press an OK key (DEL key). Now LCD will ask for placing finger over the finger print module. Now user needs to put his finger over finger print module. Then LCD will ask to remove the finger from finger print module and again ask for placing the finger. Now user needs to put his finger again over finger print module. Now finger print module takes an image and converts it into templates and stores it by selected ID in to the finger print module’s memory.Now voter will be registered and he/she can vote. By same method all the voter can be registered into the system. Now if the user wants to remove or delete any of stored ID then he/she need to press DEL key, after pressing DEL key, LCD will ask for select location means select ID that to be deleted. Now user needs to select ID and press OK key (same DEL key). Now LCD will let you know that finger has been deleted successfully. CAN1, CAN2, CAN3 here represents the Candidate 1, Candidate 2 and Candidate 3, who have stood for election.

Circuit Explanation:

for instruct Voter and showing the result as well. Yellow LED indicates that fingerprint module is ready to take an image of the finger and Green LED indicates that system is ready to take a vote or see results. The push button is directly connected to pin A0(ENROL), A1(DEL), A2(UP), A3(DOWN) and A4(Match), D5(Can1), D4(Can2), D3(Can3), D2(Result) of Arduino with respect to ground. Yellow LED is connected at Digital pin D7 of Arduino with respect to ground through a 1k resistor and Green LED is connected to D6 of Arduino with the same method. Fingerprint module’s Rx and Tx directly connected at Serial pin Tx and Rx of Arduino. 5v supply is used for powering finger print module taken from Arduino board. A buzzer is also connected at A5. A 16x2 LCD is configured in 4-bit mode and its RS, EN, D4, D5, D6, and D7 are directly connected at Digital pin D13, D12, D11, D10, D9, and D8 of Arduino.

Program Explanation:

.You can check the complete Code below. Here we are explaining main functions of the Arduino Program. In setup function, we have given directions to defined pins and have initiated the LCD and Fingerprint module. function, we have waited forcheck key and press Match key to start the finger print to take input and compare captured image id with stored IDs. If a match occurs then proceed with next step. void loop() { lcd.setCursor(0,0); lcd.print("Press Match Key "); lcd.setCursor(0,1); lcd.print("to start system"); digitalWrite(indVote, LOW); digitalWrite(indFinger, LOW); if(digitalRead(match)==0) { digitalWrite(buzzer, HIGH); delay(200); digitalWrite(buzzer, LOW); digitalWrite(indFinger, HIGH); for(int i=0;i<3;i++) ..... ..... ....... .... function is called. void checkKeys() { if(digitalRead(enroll) == 0) { lcd.clear(); lcd.print("Please Wait"); delay(1000); while(digitalRead(enroll) == 0); Enroll(); } else if(digitalRead(del) == 0) { lcd.clear(); lcd.print("Please Wait"); delay(1000); delet(); } } function that will delete finger from records. void delet() { int count=0; lcd.clear(); lcd.print("Delete Finger "); lcd.setCursor(0,1); lcd.print("Location:"); while(1) { lcd.setCursor(9,1); lcd.print(count); if(digitalRead(up) == 0) { count++; if(count>25) count=0; delay(500); } .... ..... ..... ..... Given function is used for delete finger print from the record of selected ID. uint8_t deleteFingerprint(uint8_t id) { uint8_t p = -1; lcd.clear(); lcd.print("Please wait"); p = finger.deleteModel(id); if (p == FINGERPRINT_OK) { Serial.println("Deleted!"); lcd.clear(); lcd.print("Figer Deleted"); lcd.setCursor(0,1); lcd.print("Successfully"); delay(1000); } else { Serial.print("Something Wrong"); lcd.clear(); lcd.print("Something Wrong"); lcd.setCursor(0,1); lcd.print("Try Again Later"); delay(2000); return p; } } Given Function is used to taking finger print image and convert them into the template and save it by selected ID into the finger print module memory. uint8_t getFingerprintEnroll() { int p = -1; lcd.clear(); lcd.print("finger ID:"); lcd.print(id); lcd.setCursor(0,1); lcd.print("Place Finger"); delay(2000); while (p != FINGERPRINT_OK) { p = finger.getImage(); ..... ..... ....... .... Given function is used for Voting and display results: void Vote() { lcd.clear(); lcd.print("Please Place"); lcd.setCursor(0,1); lcd.print("Your Vote"); digitalWrite(indVote, HIGH); digitalWrite(indFinger, LOW); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(1000); while(1) { if(digitalRead(sw1)==0) ..... ..... ....... .... Below. Code #include<EEPROM.h> #include<LiquidCrystal.h> LiquidCrystal lcd(13,12,11,10,9,8); #include <Adafruit_Fingerprint.h> uint8_t id; Adafruit_Fingerprint finger = Adafruit_Fingerprint(&Serial); #define enroll 14 #define del 15 #define up 16 #define down 17 #define match 18 #define indVote 6 #define sw1 5 #define sw2 4 #define sw3 3 #define resultsw 2 #define indFinger 7 #define buzzer 19 #define records 25 int vote1,vote2,vote3; int flag; void setup() { delay(1000); pinMode(enroll, INPUT_PULLUP); pinMode(up, INPUT_PULLUP); pinMode(down, INPUT_PULLUP); pinMode(del, INPUT_PULLUP); pinMode(match, INPUT_PULLUP); pinMode(sw1, INPUT_PULLUP); pinMode(sw2, INPUT_PULLUP); pinMode(sw3, INPUT_PULLUP); pinMode(resultsw, INPUT_PULLUP); pinMode(buzzer, OUTPUT); pinMode(indVote, OUTPUT); pinMode(indFinger, OUTPUT); lcd.begin(16,2); if(digitalRead(resultsw) ==0) { for(int i=0;i<records;i++) EEPROM.write(i+10,0xff); EEPROM.write(0,0); EEPROM.write(1,0); EEPROM.write(2,0); lcd.clear(); lcd.print("System Reset"); delay(1000); } lcd.clear(); lcd.print("Voting Machine"); lcd.setCursor(0,1); lcd.print("by Finger Print"); delay(2000); lcd.clear(); lcd.print("Circuit Digest"); lcd.setCursor(0,1); lcd.print("Saddam Khan"); delay(2000); if(EEPROM.read(0) == 0xff) EEPROM.write(0,0); if(EEPROM.read(1) == 0xff) EEPROM.write(1,0); if(EEPROM.read(1) == 0xff) EEPROM.write(1,0); //finger.begin(57600); Serial.begin(57600); lcd.clear(); lcd.print("Finding Module"); lcd.setCursor(0,1); delay(1000); if (finger.verifyPassword()) { //Serial.println("Found fingerprint sensor!"); lcd.clear(); lcd.print("Found Module "); delay(1000); } else { //Serial.println("Did not find fingerprint sensor :("); lcd.clear(); lcd.print("module not Found"); lcd.setCursor(0,1); lcd.print("Check Connections"); while (1); } lcd.clear(); lcd.setCursor(0,0); lcd.print("Cn1"); lcd.setCursor(4,0); lcd.print("Cn2"); lcd.setCursor(8,0); lcd.print("Cn3"); lcd.setCursor(12,0); lcd.print("Cn4"); lcd.setCursor(0,1); vote1=EEPROM.read(0); lcd.print(vote1); lcd.setCursor(6,1); vote2=EEPROM.read(1); lcd.print(vote2); lcd.setCursor(12,1); vote3=EEPROM.read(2); lcd.print(vote3); delay(2000); } void loop() { lcd.setCursor(0,0); lcd.print("Press Match Key "); lcd.setCursor(0,1); lcd.print("to start system"); digitalWrite(indVote, LOW); digitalWrite(indFinger, LOW); if(digitalRead(match)==0) { digitalWrite(buzzer, HIGH); delay(200); digitalWrite(buzzer, LOW); digitalWrite(indFinger, HIGH); for(int i=0;i<3;i++) { lcd.clear(); lcd.print("Place Finger"); delay(2000); int result=getFingerprintIDez(); if(result>=0) { flag=0; for(int i=0;i<records;i++) { if(result == EEPROM.read(i+10)) { lcd.clear(); lcd.print("Authorised Voter"); lcd.setCursor(0,1); lcd.print("Please Wait...."); delay(1000); Vote(); EEPROM.write(i+10, 0xff); flag=1; return; } } if(flag == 0) { lcd.clear(); lcd.print("Already Voted"); //lcd.setCursor(0,1); //lcd.print("") digitalWrite(buzzer, HIGH); delay(5000); digitalWrite(buzzer, LOW); return; } } } lcd.clear(); } checkKeys(); delay(1000); } void checkKeys() { if(digitalRead(enroll) == 0) { lcd.clear(); lcd.print("Please Wait"); delay(1000); while(digitalRead(enroll) == 0); Enroll(); } else if(digitalRead(del) == 0) { lcd.clear(); lcd.print("Please Wait"); delay(1000); delet(); } } void Enroll() { int count=0; lcd.clear(); lcd.print("Enter Finger ID:"); while(1) { lcd.setCursor(0,1); lcd.print(count); if(digitalRead(up) == 0) { count++; if(count>25) count=0; delay(500); } else if(digitalRead(down) == 0) { count--; if(count<0) count=25; delay(500); } else if(digitalRead(del) == 0) { id=count; getFingerprintEnroll(); for(int i=0;i<records;i++) { if(EEPROM.read(i+10) == 0xff) { EEPROM.write(i+10, id); break; } } return; } else if(digitalRead(enroll) == 0) { return; } } } void delet() { int count=0; lcd.clear(); lcd.print("Enter Finger ID"); while(1) { lcd.setCursor(0,1); lcd.print(count); if(digitalRead(up) == 0) { count++; if(count>25) count=0; delay(500); } else if(digitalRead(down) == 0) { count--; if(count<0) count=25; delay(500); } else if(digitalRead(del) == 0) { id=count; deleteFingerprint(id); for(int i=0;i<records;i++) { if(EEPROM.read(i+10) == id) { EEPROM.write(i+10, 0xff); break; } } return; } else if(digitalRead(enroll) == 0) { return; } } } uint8_t getFingerprintEnroll() { int p = -1; lcd.clear(); lcd.print("finger ID:"); lcd.print(id); lcd.setCursor(0,1); lcd.print("Place Finger"); delay(2000); while (p != FINGERPRINT_OK) { p = finger.getImage(); switch (p) { case FINGERPRINT_OK: //Serial.println("Image taken"); lcd.clear(); lcd.print("Image taken"); break; case FINGERPRINT_NOFINGER: //Serial.println("No Finger"); lcd.clear(); lcd.print("No Finger"); break; case FINGERPRINT_PACKETRECIEVEERR: //Serial.println("Communication error"); lcd.clear(); lcd.print("Comm Error"); break; case FINGERPRINT_IMAGEFAIL: //Serial.println("Imaging error"); lcd.clear(); lcd.print("Imaging Error"); break; default: //Serial.println("Unknown error"); lcd.clear(); lcd.print("Unknown Error"); break; } } // OK success! p = finger.image2Tz(1); switch (p) { case FINGERPRINT_OK: //Serial.println("Image converted"); lcd.clear(); lcd.print("Image converted"); break; case FINGERPRINT_IMAGEMESS: //Serial.println("Image too messy"); lcd.clear(); lcd.print("Image too messy"); return p; case FINGERPRINT_PACKETRECIEVEERR: //Serial.println("Communication error"); lcd.clear(); lcd.print("Comm Error"); return p; case FINGERPRINT_FEATUREFAIL: //Serial.println("Could not find fingerprint features"); lcd.clear(); lcd.print("Feature Not Found"); return p; case FINGERPRINT_INVALIDIMAGE: //Serial.println("Could not find fingerprint features"); lcd.clear(); lcd.print("Feature Not Found"); return p; default: //Serial.println("Unknown error"); lcd.clear(); lcd.print("Unknown Error"); return p; } //Serial.println("Remove finger"); lcd.clear(); lcd.print("Remove Finger"); delay(2000); p = 0; while (p != FINGERPRINT_NOFINGER) { p = finger.getImage(); } //Serial.print("ID "); //Serial.println(id); p = -1; //Serial.println("Place same finger again"); lcd.clear(); lcd.print("Place Finger"); lcd.setCursor(0,1); lcd.print(" Again"); while (p != FINGERPRINT_OK) { p = finger.getImage(); switch (p) { case FINGERPRINT_OK: //Serial.println("Image taken"); break; case FINGERPRINT_NOFINGER: //Serial.print("."); break; case FINGERPRINT_PACKETRECIEVEERR: //Serial.println("Communication error"); break; case FINGERPRINT_IMAGEFAIL: //Serial.println("Imaging error"); break; default: //Serial.println("Unknown error"); return; } } // OK success! p = finger.image2Tz(2); switch (p) { case FINGERPRINT_OK: //Serial.println("Image converted"); break; case FINGERPRINT_IMAGEMESS: //Serial.println("Image too messy"); return p; case FINGERPRINT_PACKETRECIEVEERR: //Serial.println("Communication error"); return p; case FINGERPRINT_FEATUREFAIL: //Serial.println("Could not find fingerprint features"); return p; case FINGERPRINT_INVALIDIMAGE: //Serial.println("Could not find fingerprint features"); return p; default: //Serial.println("Unknown error"); return p; } // OK converted! //Serial.print("Creating model for #"); //Serial.println(id); p = finger.createModel(); if (p == FINGERPRINT_OK) { //Serial.println("Prints matched!"); } else if (p == FINGERPRINT_PACKETRECIEVEERR) { //Serial.println("Communication error"); return p; } else if (p == FINGERPRINT_ENROLLMISMATCH) { //Serial.println("Fingerprints did not match"); return p; } else { //Serial.println("Unknown error"); return p; } //Serial.print("ID "); //Serial.println(id); p = finger.storeModel(id); if (p == FINGERPRINT_OK) { //Serial.println("Stored!"); lcd.clear(); lcd.print("Stored!"); delay(2000); } else if (p == FINGERPRINT_PACKETRECIEVEERR) { //Serial.println("Communication error"); return p; } else if (p == FINGERPRINT_BADLOCATION) { //Serial.println("Could not store in that location"); return p; } else if (p == FINGERPRINT_FLASHERR) { //Serial.println("Error writing to flash"); return p; } else { //Serial.println("Unknown error"); return p; } } int getFingerprintIDez() { uint8_t p = finger.getImage(); if (p != FINGERPRINT_OK) return -1; p = finger.image2Tz(); if (p != FINGERPRINT_OK) return -1; p = finger.fingerFastSearch(); if (p != FINGERPRINT_OK) { lcd.clear(); lcd.print("Finger Not Found"); lcd.setCursor(0,1); lcd.print("Try Later"); delay(2000); return -1; } // found a match! //Serial.print("Found ID #"); //Serial.print(finger.fingerID); return finger.fingerID; } uint8_t deleteFingerprint(uint8_t id) { uint8_t p = -1; lcd.clear(); lcd.print("Please wait"); p = finger.deleteModel(id); if (p == FINGERPRINT_OK) { //Serial.println("Deleted!"); lcd.clear(); lcd.print("Figer Deleted"); lcd.setCursor(0,1); lcd.print("Successfully"); delay(1000); } else { //Serial.print("Something Wrong"); lcd.clear(); lcd.print("Something Wrong"); lcd.setCursor(0,1); lcd.print("Try Again Later"); delay(2000); return p; } } void Vote() { lcd.clear(); lcd.print("Please Place"); lcd.setCursor(0,1); lcd.print("Your Vote"); digitalWrite(indVote, HIGH); digitalWrite(indFinger, LOW); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(1000); while(1) { if(digitalRead(sw1)==0) { vote1++; voteSubmit(1); EEPROM.write(0, vote1); while(digitalRead(sw1)==0); return; } if(digitalRead(sw2)==0) { vote2++; voteSubmit(2); EEPROM.write(1, vote2); while(digitalRead(sw2)==0); return; } if(digitalRead(sw3)==0) { vote3++; voteSubmit(3); EEPROM.write(2, vote3); while(digitalRead(sw3)==0); return; } if(digitalRead(resultsw)==0) { lcd.clear(); lcd.setCursor(0,0); lcd.print("Can1"); lcd.setCursor(6,0); lcd.print("Can2"); lcd.setCursor(12,0); lcd.print("Can3"); for(int i=0;i<3;i++) { lcd.setCursor(i*6,1); lcd.print(EEPROM.read(i)); } delay(2000); int vote=vote1+vote2+vote3; if(vote) { if((vote1 > vote2 && vote1 > vote3)) { lcd.clear(); lcd.print("Can1 Wins"); delay(2000); lcd.clear(); } else if(vote2 > vote1 && vote2 > vote3) { lcd.clear(); lcd.print("Can2 Wins"); delay(2000); lcd.clear(); } else if((vote3 > vote1 && vote3 > vote2)) { lcd.clear(); lcd.print("Can3 Wins"); delay(2000); lcd.clear(); } else { lcd.clear(); lcd.print(" Tie Up Or "); lcd.setCursor(0,1); lcd.print(" No Result "); delay(1000); lcd.clear(); } } else { lcd.clear(); lcd.print("No Voting...."); delay(1000); lcd.clear(); } vote1=0;vote2=0;vote3=0;vote=0; lcd.clear(); return; } } digitalWrite(indVote, LOW); } void voteSubmit(int cn) { lcd.clear(); if(cn == 1) lcd.print("Can1"); else if(cn == 2) lcd.print("Can2"); else if(cn == 3) lcd.print("Can3"); lcd.setCursor(0,1); lcd.print("Vote Submitted"); digitalWrite(buzzer , HIGH); delay(1000); digitalWrite(buzzer, LOW); digitalWrite(indVote, LOW); return; } Video microcontroller-projects/fingerprint-based-biometric-security-system-arduino-uno

Biometric Security System using Arduino and Fingerprint Sensor

with door locking.Finger Print is considered one of the safest key to lock or unlock any system as it can recognize any person uniquely and can’t be copied easily.

Components Required:

Arduino Uno Finger Print Module Push Button -4 LEDs -2 1K Resistor -3 2.2K resistor -1` Power Supply Connecting wires Cardboard Box Servo Motor -1 16x2 LCD -1 Bread Board -1

Finger Print Sensor Module with Arduino:

is a module which captures finger’s print image and then converts it into the equivalent template and saves them into its memory on selected ID (location) by Arduino. Here all the process is commanded by Arduino like taking an image of finger print, convert it into templates and storing location etc. at the end for full demonstration. to act as a security gate, which will only open when the system will read correct Finger Print. Yellow LED indicates gate is closed and Green LED indicates gate is opened.

Working Explanation:

is easy. In this project, we have used a gate that will be open when we place stored finger at the finger print module. First of all, the user needs to enroll finger with the help of push button/keys. To do this user need to press ENROLL key and then LCD asks for entering location/ID where finger will be a store. So now user needs to enter ID (Location) by using UP/DOWN keys. After selecting Location/ID user needs to press an OK key (DEL key). Now LCD will ask for placing finger over the finger print module. Now user needs to put his finger over finger print module. Then LCD will ask to remove the finger from finger print module and again ask for placing the finger. Now user needs to put his finger again over finger print module. Now finger print module takes an image and converts it into templates and stores it by selected ID in to the finger print module’s memory. Now user can open the gate by placing the same finger that he/she have added or enrolled into the system and then press MATCH key (UP/Down key). By the same method, the user can add more fingers. Check the Video below for full demonstration. Now if the user wants to remove or delete any of stored ID then he/she need to press DEL key, after pressing DEL key, LCD will ask for select location means select ID that to be deleted. Now user needs to select ID and press OK key (same DEL key). Now LCD will let you know that finger has been deleted successfully. Now the user may check it was deleted or not by placing the same finger over the finger print module and pressing MATCH key (UP/Down key). When placed finger will be valid Green LED will glow for five second and gate also opens at the same time. After 5-seconds gate will be closed automatically. The user may customize gate/door opening and closing according to their requirement. Servo motor is responsible for open and closing of the gate.

Circuit Explanation:

is very simple which contains Arduino which controls whole the process of the project, push button, buzzer, and LCD. Arduino controls the complete processes. is configured in 4-bit mode and its RS, EN, D4, D5, D6, and D7 are directly connected at Digital pin D13, D12, D11, D10, D9, and D8 of Arduino. here D14, D15, D16, D17 are A0, A1, A2, A3 respectively.

Program Explanation:

You can check the complete Code below, it can be easily understood. Here we are explaining main functions of the Arduino Program. Below piece of code is used to take Finger Print as input and take action according to validation of finger. If finger will be validated gate will be open otherwise remain closed. for(int i=0;i<5;i++) { lcd.clear(); lcd.print("Place Finger"); delay(2000); int result=getFingerprintIDez(); if(result>=0) { digitalWrite(openLight, HIGH); digitalWrite(closeLight, LOW); lcd.clear(); lcd.print("Allowed"); lcd.setCursor(0,1); lcd.print("Gete Opened "); myServo.write(0); delay(5000); myServo.write(180); digitalWrite(closeLight, HIGH); digitalWrite(openLight, LOW); lcd.setCursor(0,1); lcd.print("Gate Closed "); function is called. void checkKeys() { if(digitalRead(enroll) == 0) { lcd.clear(); lcd.print("Please Wait"); delay(1000); while(digitalRead(enroll) == 0); Enroll(); } else if(digitalRead(del) == 0) { lcd.clear(); lcd.print("Please Wait"); delay(1000); delet(); } } function that will delete finger from records. void delet() { int count=0; lcd.clear(); lcd.print("Delete Finger "); lcd.setCursor(0,1); lcd.print("Location:"); while(1) { lcd.setCursor(9,1); lcd.print(count); if(digitalRead(up) == 0) { count++; if(count>25) count=0; delay(500); } .... ..... ..... ..... Given function is used for delete finger print from the record of selected ID. uint8_t deleteFingerprint(uint8_t id) { uint8_t p = -1; lcd.clear(); lcd.print("Please wait"); p = finger.deleteModel(id); if (p == FINGERPRINT_OK) { Serial.println("Deleted!"); lcd.clear(); lcd.print("Figer Deleted"); lcd.setCursor(0,1); lcd.print("Successfully"); delay(1000); } else { Serial.print("Something Wrong"); lcd.clear(); lcd.print("Something Wrong"); lcd.setCursor(0,1); lcd.print("Try Again Later"); delay(2000); return p; } } Given Function is used to taking finger print image and convert them into the template and save it by selected ID into the finger print module memory. uint8_t getFingerprintEnroll() { int p = -1; lcd.clear(); lcd.print("finger ID:"); lcd.print(id); lcd.setCursor(0,1); lcd.print("Place Finger"); delay(2000); while (p != FINGERPRINT_OK) { p = finger.getImage(); ..... ..... ....... .... Code #include<LiquidCrystal.h> LiquidCrystal lcd(13,12,11,10,9,8); #include <SoftwareSerial.h> SoftwareSerial fingerPrint(2, 3); #include<Servo.h> Servo myServo; #include <Adafruit_Fingerprint.h> uint8_t id; Adafruit_Fingerprint finger = Adafruit_Fingerprint(&fingerPrint); #define enroll 14 #define del 15 #define up 16 #define down 17 #define openLight 6 #define closeLight 7 #define servoPin 5 void setup() { delay(1000); myServo.attach(servoPin); myServo.write(180); pinMode(enroll, INPUT_PULLUP); pinMode(up, INPUT_PULLUP); pinMode(down, INPUT_PULLUP); pinMode(del, INPUT_PULLUP); pinMode(openLight, OUTPUT); pinMode(closeLight, OUTPUT); lcd.begin(16,2); lcd.print("Security System"); lcd.setCursor(0,1); lcd.print("by Finger Print"); delay(2000); lcd.clear(); lcd.print("Circuit Digest"); lcd.setCursor(0,1); lcd.print("Saddam Khan"); delay(2000); finger.begin(57600); Serial.begin(9600); lcd.clear(); lcd.print("Finding Module"); lcd.setCursor(0,1); delay(1000); if (finger.verifyPassword()) { Serial.println("Found fingerprint sensor!"); lcd.clear(); lcd.print("Found Module "); delay(1000); } else { Serial.println("Did not find fingerprint sensor :("); lcd.clear(); lcd.print("module not Found"); lcd.setCursor(0,1); lcd.print("Check Connections"); while (1); } } void loop() { lcd.setCursor(0,0); lcd.print("Press UP/Down "); lcd.setCursor(0,1); lcd.print("to start System"); digitalWrite(closeLight, HIGH); if(digitalRead(up)==0 || digitalRead(down)==0) { for(int i=0;i<5;i++) { lcd.clear(); lcd.print("Place Finger"); delay(2000); int result=getFingerprintIDez(); if(result>=0) { digitalWrite(openLight, HIGH); digitalWrite(closeLight, LOW); lcd.clear(); lcd.print("Allowed"); lcd.setCursor(0,1); lcd.print("Gete Opened "); myServo.write(0); delay(5000); myServo.write(180); digitalWrite(closeLight, HIGH); digitalWrite(openLight, LOW); lcd.setCursor(0,1); lcd.print("Gate Closed "); return; } } } checkKeys(); delay(1000); } void checkKeys() { if(digitalRead(enroll) == 0) { lcd.clear(); lcd.print("Please Wait"); delay(1000); while(digitalRead(enroll) == 0); Enroll(); } else if(digitalRead(del) == 0) { lcd.clear(); lcd.print("Please Wait"); delay(1000); delet(); } } void Enroll() { int count=0; lcd.clear(); lcd.print("Enroll Finger "); lcd.setCursor(0,1); lcd.print("Location:"); while(1) { lcd.setCursor(9,1); lcd.print(count); if(digitalRead(up) == 0) { count++; if(count>25) count=0; delay(500); } else if(digitalRead(down) == 0) { count--; if(count<0) count=25; delay(500); } else if(digitalRead(del) == 0) { id=count; getFingerprintEnroll(); return; } else if(digitalRead(enroll) == 0) { return; } } } void delet() { int count=0; lcd.clear(); lcd.print("Delete Finger "); lcd.setCursor(0,1); lcd.print("Location:"); while(1) { lcd.setCursor(9,1); lcd.print(count); if(digitalRead(up) == 0) { count++; if(count>25) count=0; delay(500); } else if(digitalRead(down) == 0) { count--; if(count<0) count=25; delay(500); } else if(digitalRead(del) == 0) { id=count; deleteFingerprint(id); return; } else if(digitalRead(enroll) == 0) { return; } } } uint8_t getFingerprintEnroll() { int p = -1; lcd.clear(); lcd.print("finger ID:"); lcd.print(id); lcd.setCursor(0,1); lcd.print("Place Finger"); delay(2000); while (p != FINGERPRINT_OK) { p = finger.getImage(); switch (p) { case FINGERPRINT_OK: Serial.println("Image taken"); lcd.clear(); lcd.print("Image taken"); break; case FINGERPRINT_NOFINGER: Serial.println("No Finger"); lcd.clear(); lcd.print("No Finger"); break; case FINGERPRINT_PACKETRECIEVEERR: Serial.println("Communication error"); lcd.clear(); lcd.print("Comm Error"); break; case FINGERPRINT_IMAGEFAIL: Serial.println("Imaging error"); lcd.clear(); lcd.print("Imaging Error"); break; default: Serial.println("Unknown error"); lcd.clear(); lcd.print("Unknown Error"); break; } } // OK success! p = finger.image2Tz(1); switch (p) { case FINGERPRINT_OK: Serial.println("Image converted"); lcd.clear(); lcd.print("Image converted"); break; case FINGERPRINT_IMAGEMESS: Serial.println("Image too messy"); lcd.clear(); lcd.print("Image too messy"); return p; case FINGERPRINT_PACKETRECIEVEERR: Serial.println("Communication error"); lcd.clear(); lcd.print("Comm Error"); return p; case FINGERPRINT_FEATUREFAIL: Serial.println("Could not find fingerprint features"); lcd.clear(); lcd.print("Feature Not Found"); return p; case FINGERPRINT_INVALIDIMAGE: Serial.println("Could not find fingerprint features"); lcd.clear(); lcd.print("Feature Not Found"); return p; default: Serial.println("Unknown error"); lcd.clear(); lcd.print("Unknown Error"); return p; } Serial.println("Remove finger"); lcd.clear(); lcd.print("Remove Finger"); delay(2000); p = 0; while (p != FINGERPRINT_NOFINGER) { p = finger.getImage(); } Serial.print("ID "); Serial.println(id); p = -1; Serial.println("Place same finger again"); lcd.clear(); lcd.print("Place Finger"); lcd.setCursor(0,1); lcd.print(" Again"); while (p != FINGERPRINT_OK) { p = finger.getImage(); switch (p) { case FINGERPRINT_OK: Serial.println("Image taken"); break; case FINGERPRINT_NOFINGER: Serial.print("."); break; case FINGERPRINT_PACKETRECIEVEERR: Serial.println("Communication error"); break; case FINGERPRINT_IMAGEFAIL: Serial.println("Imaging error"); break; default: Serial.println("Unknown error"); return; } } // OK success! p = finger.image2Tz(2); switch (p) { case FINGERPRINT_OK: Serial.println("Image converted"); break; case FINGERPRINT_IMAGEMESS: Serial.println("Image too messy"); return p; case FINGERPRINT_PACKETRECIEVEERR: Serial.println("Communication error"); return p; case FINGERPRINT_FEATUREFAIL: Serial.println("Could not find fingerprint features"); return p; case FINGERPRINT_INVALIDIMAGE: Serial.println("Could not find fingerprint features"); return p; default: Serial.println("Unknown error"); return p; } // OK converted! Serial.print("Creating model for #"); Serial.println(id); p = finger.createModel(); if (p == FINGERPRINT_OK) { Serial.println("Prints matched!"); } else if (p == FINGERPRINT_PACKETRECIEVEERR) { Serial.println("Communication error"); return p; } else if (p == FINGERPRINT_ENROLLMISMATCH) { Serial.println("Fingerprints did not match"); return p; } else { Serial.println("Unknown error"); return p; } Serial.print("ID "); Serial.println(id); p = finger.storeModel(id); if (p == FINGERPRINT_OK) { Serial.println("Stored!"); lcd.clear(); lcd.print("Stored!"); delay(2000); } else if (p == FINGERPRINT_PACKETRECIEVEERR) { Serial.println("Communication error"); return p; } else if (p == FINGERPRINT_BADLOCATION) { Serial.println("Could not store in that location"); return p; } else if (p == FINGERPRINT_FLASHERR) { Serial.println("Error writing to flash"); return p; } else { Serial.println("Unknown error"); return p; } } int getFingerprintIDez() { uint8_t p = finger.getImage(); if (p != FINGERPRINT_OK) return -1; p = finger.image2Tz(); if (p != FINGERPRINT_OK) return -1; p = finger.fingerFastSearch(); if (p != FINGERPRINT_OK) { lcd.clear(); lcd.print("Finger Not Found"); lcd.setCursor(0,1); lcd.print("Try Later"); delay(2000); return -1; } // found a match! Serial.print("Found ID #"); Serial.print(finger.fingerID); return finger.fingerID; } uint8_t deleteFingerprint(uint8_t id) { uint8_t p = -1; lcd.clear(); lcd.print("Please wait"); p = finger.deleteModel(id); if (p == FINGERPRINT_OK) { Serial.println("Deleted!"); lcd.clear(); lcd.print("Figer Deleted"); lcd.setCursor(0,1); lcd.print("Successfully"); delay(1000); } else { Serial.print("Something Wrong"); lcd.clear(); lcd.print("Something Wrong"); lcd.setCursor(0,1); lcd.print("Try Again Later"); delay(2000); return p; } } Video microcontroller-projects/secret-knock-pattern-detecting-door-lock-arduino

Smart Knock Detecting Door Lock using Arduino

at the end.

Components:

Arduino Uno Push Button Buzzer 1M Resistor Power Connecting wires Box Servo Motor

Circuit Explanation:

for open and close the gate and save the pattern to Arduino. pin D3 of Arduino.

Feeding Knocking Pattern in Arduino:

to take knock input pattern inthe system. Here we are using a push button to allow to take input from the sensor and also save that into the Arduino. This system is designed by taking idea from Morse code pattern but not exactly similar with that. Here we have used a card board box for demonstration. To take input we knock over the board after pressing push button. Here we have knocked by keeping a time period in mind that is 500ms. This 500ms is because we have fixed it in code and input pattern is depending upon it. This 500ms time period will define the input was 1 or 0. Check the code below to understand this thing. When we knock it, Arduino starts monitoring the time of the first knock to second knock and put that in an array. Here in this system, we are taking 6 knocks. It means we will get 5 time periods. Now we check the time period one by one. First, we check time period between first knock and second knock if the time difference between these less the 500ms then it will be 0 and if greater than 500ms it will be 1 and it will be saved into a variable. Now after it, we check time period between second knock and third knock and so on. Finally, we will get 5 digit output in 0 and 1 format (binary).

Working Explanation:

is simple. First we have to save a pattern in the system. So we have to press and hold push button until we knock 6 times. Here in this project, I have used 6 knocks but the user may change it as they want. After six times knock, Arduino find the knock pattern and save that in EEPROM. Now after saving the input pattern, press and immediately released the push button for taking input from the sensor to Arduino to open the lock. Now we have to knock 6 times. After it, Arduino decodes it and compares with saved pattern. If a match occurs then Arduino open the gate by driving servo motor. Note: when we press or press and hold the push button Arduino start a 10 seconds timer to take all 6 knock. Means user need to knock within this 10 seconds time. And the user may open Serial monitor to see the log.

Programming Explanation:

In a program first of all we include the header file and defines input and output pin and define the macro and declared variables as you can see in the Full Code in code section below. function, we give direction to defined pin and initiate servo motor. void setup() { pinMode(sw, INPUT_PULLUP); myServo.attach(servoPin); myServo.write(180); Serial.begin(9600); } After it, we take input and save the input pattern or knock time in an array. void loop() { int i=0; if(digitalRead(sw) == LOW) { Serial.println("Start"); delay(1000); long stt= millis(); while(millis()<(stt+patternInputTime)) { int temp=analogRead(A0); if(temp>sensitivity && flag==0 && i<=patternLenth) { .... ..... .... After it, we decode the input pattern for(int i=0;i<patternLenth;i++) { knok=1; if(slot[i+1]-slot[i] <500 ) pattern[i]=0; else pattern[i]=1; Serial.println(pattern[i]); } And then save if push button is still pressed if(digitalRead(sw) == 0) { for(int i=0;i<patternLenth;i++) EEPROM.write(i,pattern[i]); while(digitalRead(sw) == 0); } And if push button is not still pressed then Arduino will compare input decoded pattern with saved pattern. else { if(knok == 1) { for(int i=0;i<patternLenth;i++) { if(pattern[i] == EEPROM.read(i)) { Serial.println(acceptFlag++); } else { Serial.println("Break"); break; } } } If any password matched, then Servo open the gate otherwise nothing happened but the user may see result over serial monitor. Serial.println(acceptFlag); if(acceptFlag >= patternLenth-1) { Serial.println(" Accepted"); myServo.write(openGate); delay(5000); myServo.write(closeGate); } else Serial.println("Rejected"); } Code #include<EEPROM.h> #include<Servo.h> #define patternLenth 5 #define patternInputTime 10000 #define sensitivity 80 #define margin 100 #define sw 7 #define servoPin 3 #define openGate 0 #define closeGate 180 long slot[patternLenth+1]; int pattern[patternLenth]; int flag=0; int acceptFlag=0; int knok; Servo myServo; void setup() { pinMode(sw, INPUT_PULLUP); myServo.attach(servoPin); myServo.write(180); Serial.begin(9600); } void loop() { int i=0; if(digitalRead(sw) == LOW) { Serial.println("Start"); delay(1000); long stt= millis(); while(millis()<(stt+patternInputTime)) { int temp=analogRead(A0); if(temp>sensitivity && flag==0 && i<=patternLenth) { delay(10); flag=1; slot[i++]=millis()-stt; //Serial.println(slot[i-1] - stt); if(i>patternLenth) break; } else if(temp == 0) flag=0; } long stp=millis(); Serial.println("Stop"); // Serial.println(stp-stt); for(int i=0;i<patternLenth;i++) { knok=1; if(slot[i+1]-slot[i] <500 ) pattern[i]=0; else pattern[i]=1; Serial.println(pattern[i]); } if(digitalRead(sw) == 0) { for(int i=0;i<patternLenth;i++) EEPROM.write(i,pattern[i]); while(digitalRead(sw) == 0); } else { if(knok == 1) { for(int i=0;i<patternLenth;i++) { if(pattern[i] == EEPROM.read(i)) { Serial.println(acceptFlag++); } else { Serial.println("Break"); break; } } } Serial.println(acceptFlag); if(acceptFlag >= patternLenth-1) { Serial.println(" Accepted"); myServo.write(openGate); delay(5000); myServo.write(closeGate); } else Serial.println("Rejected"); } for(int i=0;i<patternLenth;i++) { pattern[i]=0; slot[i]=0; } slot[i]=0; acceptFlag=0; } } Video microcontroller-projects/generating-tones-by-tapping-fingers-arduino

Generating Tones by Tapping Fingers using Arduino

and create your own rhythms, its like playing Piano on your palm. Sounds cool right so, let us build it.

Components required:

The materials required for this project is listed below, it is not mandatory to stick on to the same. Once you grab the concept you can use your own way of building it. Arduini Pro Mini Peizo Speaker Flex Sensor Finger Gloves 10K Resistors BC547 Transistors 9V Battery

Circuit Diagram and Explanation:

is shown below. in such a way that the current amplified by the first one is further amplified by the second transistor. A Darlington pair is shown in the image below: so whenever we touch the base of the transistor the second transistor gets biased. Using this to our favour we have built the touch sensor for this project. transistor) an interrupt will be triggered from the Arduino. I have programmed to produce three different tones per finger based on how much the finger (flex sensor) is bent. You can increase the number if you would like to have more tones at your finger tips. I made the complete board on a perf board so that it fits easily into my palms, but you can use a breadboard as well. Just make sure your body touches the ground of the circuit at some point. Once you solder everything it should look something like this I have used two finger gloves to secure the wires from Darlington pair and the flex sensor in position as shown above. You can come up with your own (better if possible) idea to secure them in place while you are playing your tones.

Arduino Programming:

is pretty straight forward. We just have to look out for interrupts from the Darlington wires and if found one we have to play tone which depends on how much flex sensor is bent. The complete code is given at the end of this post but I have explained few important chunks below. pin. These interrupts will be triggered whenever these pins get LOW from their pulled-up state. void setup() { pinMode(2, INPUT_PULLUP); pinMode(3, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(2), tone1, LOW); attachInterrupt(digitalPinToInterrupt(3), tone2, LOW); Serial.begin(9600); } function, we constantly check how much the flex sensor is bent. My FlexSensor 1 for example gave values around 200 when left flat and went down all the way to 130 when I bent it to its maximum, so I have mapped the value from 200 to 130 as 1 to 3 since I have to play 3 different types of tones. You have to tweak these two lines based on your Flex sensor values and number of tones. void loop() { flexSensor1 = map(analogRead(A0),200,130,1,3); //Map up with your own values based on your flex sensor flexSensor2 = map(analogRead(A1),170,185,1,3); //Map up with your own values based on your flex sensor } void tone1() { if (flexSensor1==1) tone(8, NOTE_D4,50); else if (flexSensor1==2) tone(8, NOTE_A3,50); else if (flexSensor1==3) tone(8, NOTE_G4,50); else tone(8, NOTE_D4,50); } The below line is used to play the tone. You can play any tone that is available in the “pitches.hᾠheader file. The above line for instance plays the NOTE_A3 on pin for duration of 50 milli seconds. tone(8, NOTE_A3,50); //tone(PinNum,Note name, Duration);

Working:

Once your hardware is ready, upload the code and mount them on your fingers. Make sure your body is touching the ground of the circuit at some point. Now simply touch any conductive material or your body and you should be able to hear the respective tone. You can play your own melody or music by tapping at different intervals and different positions. Code /* * Arduino based Tap and Tone player * Published by: CircuitDigest.com * Code By: B.Aswinth Raj * Dated:8-7-2017 * * ###CONNECTIONS### * Darlington Wire 1 -> Pin 2 * Darlington Wire 2 -> Pin 3 * FlexSensor 1 -> A0 * FlexSensor 2 -> A1 * Speaker -> Pin 8 */ #include "pitches.h" //add this librarey into the project folder int flexSensor1,flexSensor2; void setup() { pinMode(2, INPUT_PULLUP); pinMode(3, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(2), tone1, LOW); //Trigger tone1 when LOW attachInterrupt(digitalPinToInterrupt(3), tone2, LOW); //Trigger tone2 when LOW Serial.begin(9600); } void loop() { flexSensor1 = map(analogRead(A0),200,130,1,3); //Map up with your own values based on your flex sensor flexSensor2 = map(analogRead(A1),170,185,1,3); //Map up with your own values based on your flex sensor } //**Function to execute on Interrupt 1**// void tone1() { if (flexSensor1==1) tone(8, NOTE_D4,50); else if (flexSensor1==2) tone(8, NOTE_A3,50); else if (flexSensor1==3) tone(8, NOTE_G4,50); else tone(8, NOTE_D4,50); } //**Function to execute on Interrupt 2**// void tone2() { if (flexSensor1==1) tone(8, NOTE_A4,50); else if (flexSensor1==2) tone(8, NOTE_F4,50); else if (flexSensor1==3) tone(8, NOTE_E4,50); else tone(8, NOTE_A4,50); } Video microcontroller-projects/arduino-data-logger-project

Arduino Data Logger (Log Temperature, Humidity, Time on SD Card and Computer)

where we will learn how we can log data at a specific interval of time. We will use an Arduino board to read some data (here temperature, humidity, date and time) and save them on a SD card and the computer simultaneously. At the end of the project you will learn How to log data into SD card with Date, Time and sensor values. How to write data directly to Excel Sheet on PC via serial communication.

Materials Required:

Breadboard Arduino UNO (any Arduino board) DHT11 Temperature sensor DS3231 RTC module SD card module SD card Connecting wires Computer/Laptop

Circuit Diagram:

is shown below. As shown in the circuit diagram the connections are very simple since we have used them as modules we can directly build them on a breadboard. The connections are further classified in the table below
Vcc5V
GndGnd
NcNc
OutPin 7
Vcc5V
GndGnd
SCLPin A5
SDAPin A4
Vcc5V
GndGnd
MISOPin 12
MOSIPin 11
SCKPin 13
CSPin 4
in Music player project.

Arduino Program Explanation:

We have to write the Arduino program which can do the following. Read data from DTH11 Sensor (or any other data that you wish to log). Initialize the I2C bus to read data from RTC module. Initialize the SPI bus to interface the SD card module with Arduino. Store the Date, Time, Temperature and Humidity into the SD card. Store the Date, Time, Temperature and Humidity on a Excel Sheet running on a computer/Laptop. The above steps might sound complicated but they are very easy since we have the libraries to do the hard job for us. You have to download the following two libraries DHT11 Sensor Library from GitHub DS3231 RTC module library from Rinky-Dink Electronics Once you have downloaded the library add them to your Arduino IDE by following Sketch->Include Library -> Add .ZIP Library provided by Parallax Inc. Follow the link to download the file and install them based on your operating system. This should have created a folder named PLS-DAQ on your desktop. We will take care of it later in our working section. (given at bottom of tutorial) and upload them to your Arduino. I have tried my best to keep the code as simple as possible and the explanations are also given through comment sections. Further, I will explain the important segments below. DS3231 is a RTC (Real Time Clock) module. It is used to maintain the date and time for most of the Electronics projects. This module has its own coin cell power supply using which it maintains the date and time even when the main power is removed or the MCU has gone though a hard reset. So once we set the date and time in this module it will keep track of it always. Using this module is very easy because of the library provided by Arduino. // Init the DS3231 using the hardware interface DS3231 rtc(SDA, SCL); void Initialize_RTC() { // Initialize the rtc object rtc.begin(); //#### the following lines can be uncommented to set the date and time for the first time### /* rtc.setDOW(FRIDAY); // Set Day-of-Week to SUNDAY rtc.setTime(18, 46, 45); // Set the time to 12:00:00 (24hr format) rtc.setDate(6, 30, 2017); // Set the date to January 1st, 2014 */ } DHT11 is a Temperature come Humidity sensor. It sends the values of temperature and humidity as an 8-bit data serially through the output pin of the module. The library reads this data by using the software serial function of the Arduino. #define DHT11_PIN 7 //Sensor output pin is connected to pin 7 dht DHT; //Sensor object named as DHT void Read_DHT11() { int chk = DHT.read11(DHT11_PIN); } void Initialize_SDcard() { // see if the card is present and can be initialized: if (!SD.begin(chipSelect)) { Serial.println("Card failed, or not present"); // don't do anything more: return; } // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. File dataFile = SD.open("LoggerCD.txt", FILE_WRITE); // if the file is available, write to it: if (dataFile) { dataFile.println("Date,Time,Temperature,Humidity"); //Write the first row of the excel file dataFile.close(); } } Using an SD card with Arduino is easy because of the SD card library which will be added to the Arduino IDE by default. In the SD card initialize function we will create a text file named “LoggerCD.txtᾠand write the first row of our content. Here we separate the values by using a ᾬᾠas a delimiter. Meaning when a comma is placed it means we have to move to the next cell in the Excel sheet. void Write_SDcard() { // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. File dataFile = SD.open("LoggerCD.txt", FILE_WRITE); // if the file is available, write to it: if (dataFile) { dataFile.print(rtc.getDateStr()); //Store date on SD card dataFile.print(","); //Move to next column using a "," dataFile.print(rtc.getTimeStr()); //Store date on SD card dataFile.print(","); //Move to next column using a "," dataFile.print(DHT.temperature); //Store date on SD card dataFile.print(","); //Move to next column using a "," dataFile.print(DHT.humidity); //Store date on SD card dataFile.print(","); //Move to next column using a "," dataFile.println(); //End of Row move to next row dataFile.close(); //Close the file } else Serial.println("OOPS!! SD card writing failed"); } With the help of the DS3231 library and the DHT11 library our Arduino will be capable of reading all these four parameters and storing them into the following parameters as shown in table below
Datertc.getDateStr());
Timertc.getTimeStr());
TemperatureDHT.temperature
HumidityDHT.humidity
Now we can directly use these parameters to store them on the SD card using the print line dataFile.print(parameter); is used to indicate the end of the line. PLX-DAQ is Microsoft Excel Plug-in software that helps us to write values from Arduino to directly into an Excel file on our Laptop or PC. This is my personal favourite because of two reasons: 1.You can write and monitor the data at the same time and provides us way to plot them as graphs. 2.You do not need a RTC Module like DS3231 to keep track of date and time. You can simply use the date and time running on your Laptop/computer and save them directly on Excel. To use this software with Arduino we have to send the data serially in a specific pattern just like displaying value on serial monitor. The key lines are explained below: void Initialize_PlxDaq() { Serial.println("CLEARDATA"); //clears up any data left from previous projects Serial.println("LABEL,Date,Time,Temperature,Humidity"); //always write LABEL, to indicate it as first line } void Write_PlxDaq() { Serial.print("DATA"); //always write "DATA" to Inidicate the following as Data Serial.print(","); //Move to next column using a "," Serial.print("DATE"); //Store date on Excel Serial.print(","); //Move to next column using a "," Serial.print("TIME"); //Store date on Excel Serial.print(","); //Move to next column using a "," Serial.print(DHT.temperature); //Store date on Excel Serial.print(","); //Move to next column using a "," Serial.print(DHT.humidity); //Store date on Excel Serial.print(","); //Move to next column using a "," Serial.println(); //End of Row move to next row } As said earlier we can write the system date and time by sending the keywords “DATEᾠand “TIMEᾠrespectively as shown above. Do not use serial monitor when using this PLX_DAQ software.

Working Explanation:

is simple. Once the hardware and the software are ready it is time to burn the program into your Arduino Board. As soon your program gets uploaded, your temperature and humidity values will start to get stored in your SD card. You have to follow the steps below to enable PLX-DAQ to log the into Excel sheet in the computer. Open the “Plx-Daq Spreadsheetᾠfile that was created on your desktop during installation. to get the following screen. Now select the baud rate as Ᾱ600ᾠand the port to which your Arduino is connected and click on Connect. Your values should start to get logged like shown in the picture below. in it. When opened it would look something like this. This file has data, but it would be hard to analyse them on a notepad. Hence we can open it on Excel as a CSV (Comma separated values) file, thus making it more effective. To open in excel 1.Open Excel. Click on File->Open and select “All fileᾠat bottom right corner and select the “LoggerCDᾠfile from the SD card. This will open a text import wizard. 2.Click on “Nextᾠand select comma as a delimiter. Click on “Nextᾠagain. Then Finish. 3.Now your values will be opened in a Excel file as shown below below. Hope you liked the project, if you have any doubt write them in the below comment section and I will help you out. Once you have succeeded up to this point, then with few advancements and just adding a few lines of code you can log data wirelessly. and connect your Laptop to your Bluetooth Module an select the COM port to which your Laptops Bluetooth is connected and Taadaaa...... You have a working a Wireless Data Logging System in no time. Code /* * Program to demonstrate Data Logging/Visualisation using Arduino * * ###Connection with SD card module### * Vcc->5V * Gnd->Gnd * MISO->pin 12 * MOSI->pin 11 * SCK-> pin 13 * CS-> pin 4 * * ###Connection with DS3231### * Vcc->5V * Gns->Gnd * SCL->pin A5 * SDA-> pin A4 * * ###Connection with DT11### * Vcc->5V * Gnd->Gnd * Out-> pin 7 * * */ #include <DS3231.h> //Library for RTC module (Download from Link in article) #include <SPI.h> //Library for SPI communication (Pre-Loaded into Arduino) #include <SD.h> //Library for SD card (Pre-Loaded into Arduino) #include <dht.h> //Library for dht11 Temperature and Humidity sensor (Download from Link in article) #define DHT11_PIN 7 //Sensor output pin is connected to pin 7 dht DHT; //Sensor object named as DHT const int chipSelect = 4; //SD card CS pin connected to pin 4 of Arduino // Init the DS3231 using the hardware interface DS3231 rtc(SDA, SCL); void setup() { // Setup Serial connection Serial.begin(9600); Initialize_SDcard(); Initialize_RTC(); Initialize_PlxDaq(); } void loop() { Read_DHT11(); Write_SDcard(); Write_PlxDaq(); delay(5000); //Wait for 5 seconds before writing the next data } void Write_PlxDaq() { Serial.print("DATA"); //always write "DATA" to Indicate the following as Data Serial.print(","); //Move to next column using a "," Serial.print("DATE"); //Store date on Excel Serial.print(","); //Move to next column using a "," Serial.print("TIME"); //Store date on Excel Serial.print(","); //Move to next column using a "," Serial.print(DHT.temperature); //Store date on Excel Serial.print(","); //Move to next column using a "," Serial.print(DHT.humidity); //Store date on Excel Serial.print(","); //Move to next column using a "," Serial.println(); //End of Row move to next row } void Initialize_PlxDaq() { Serial.println("CLEARDATA"); //clears up any data left from previous projects Serial.println("LABEL,Date,Time,Temperature,Humidity"); //always write LABEL, to indicate it as first line } void Write_SDcard() { // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. File dataFile = SD.open("LoggerCD.txt", FILE_WRITE); // if the file is available, write to it: if (dataFile) { dataFile.print(rtc.getDateStr()); //Store date on SD card dataFile.print(","); //Move to next column using a "," dataFile.print(rtc.getTimeStr()); //Store date on SD card dataFile.print(","); //Move to next column using a "," dataFile.print(DHT.temperature); //Store date on SD card dataFile.print(","); //Move to next column using a "," dataFile.print(DHT.humidity); //Store date on SD card dataFile.print(","); //Move to next column using a "," dataFile.println(); //End of Row move to next row dataFile.close(); //Close the file } else Serial.println("OOPS!! SD card writing failed"); } void Initialize_SDcard() { // see if the card is present and can be initialized: if (!SD.begin(chipSelect)) { Serial.println("Card failed, or not present"); // don't do anything more: return; } // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. File dataFile = SD.open("LoggerCD.txt", FILE_WRITE); // if the file is available, write to it: if (dataFile) { dataFile.println("Date,Time,Temperature,Humidity"); //Write the first row of the excel file dataFile.close(); } } void Initialize_RTC() { // Initialize the rtc object rtc.begin(); //#### The following lines can be uncommented to set the date and time for the first time### /* rtc.setDOW(FRIDAY); // Set Day-of-Week to SUNDAY rtc.setTime(18, 46, 45); // Set the time to 12:00:00 (24hr format) rtc.setDate(6, 30, 2017); // Set the date to January 1st, 2014 */ } void Read_DHT11() { int chk = DHT.read11(DHT11_PIN); } /*void Read_DateTime() { // Send date Serial.print(rtc.getDateStr()); Serial.print(" -- "); // Send time Serial.println(rtc.getTimeStr()); }*/ /*void Read_TempHum() { Serial.print("Temperature = "); Serial.println(DHT.temperature); Serial.print("Humidity = "); Serial.println(DHT.humidity); // delay(1000); }*/ Video microcontroller-projects/playing-melodies-on-piezo-buzzer-using-arduino-tone-function

Playing Melodies using Arduino Tone() Function

out here for you to try and have fun. Some of your projects might need some sounds action to notify about something or just to impress the viewers. What if I told you that almost any theme songs that could be played on a piano can be mimicked on your Arduino with the help of a simple program and a cheap Piezo speaker? You will also learn how to play any piece of piano music with Arduino. Check the Video at the end.

Hardware Required:

Arduino (any version ᾠUNO is used here) Piezo Speaker/Buzzer or any other 8ohm speaker. Breadboard Connecting Wires Push buttons 1k resistor (optional)

Understanding the Tone() function of Arduino:

works we should know how a Piezo buzzer works. We might have learnt about Piezo crystals in our school, it is nothing but a crystal which converts mechanical vibrations into electricity or vice versa. Here we apply a variable current (frequency) for which the crystal vibrates thus producing sound. Hence in order to make the Piezo buzzer to make some noise we have to make the Piezo electric crystal to vibrate, the pitch and tone of noise depends on how fast the crystal vibrates. Hence the tone and pitch can be controlled by varying the frequency of the current. is Syntax tone(pin, frequency) tone(pin, frequency, duration) Parameters pin: the pin on which to generate the tone frequency: the frequency of the tone in hertz - unsigned int duration: the duration of the tone in milliseconds (optional) - unsigned long The values of pin can be any of your digital pin. I have used pin number 8 here. The frequency that can be generated depends on the size of the timer in your Arduino board. For UNO and most other common boards the minimum frequency that can be produced is 31Hz and the maximum frequency that can be produced is 65535Hz. However we humans can hear only frequencies between 2000Hz and 5000 Hz.

The pitches.h header file:

But, how do we know what kind of tone will be generated for each frequency? command was based. We will use this note table to play our themes. If you are someone familiar with sheet music you should be able to make some sense of this table, for others like me these are just another block of code. #define NOTE_B0 31 #define NOTE_C1 33 #define NOTE_CS1 35 #define NOTE_D1 37 #define NOTE_DS1 39 #define NOTE_E1 41 #define NOTE_F1 44 #define NOTE_FS1 46 #define NOTE_G1 49 #define NOTE_GS1 52 #define NOTE_A1 55 #define NOTE_AS1 58 #define NOTE_B1 62 #define NOTE_C2 65 #define NOTE_CS2 69 #define NOTE_D2 73 #define NOTE_DS2 78 #define NOTE_E2 82 #define NOTE_F2 87 #define NOTE_FS2 93 #define NOTE_G2 98 #define NOTE_GS2 104 #define NOTE_A2 110 #define NOTE_AS2 117 #define NOTE_B2 123 #define NOTE_C3 131 #define NOTE_CS3 139 #define NOTE_D3 147 #define NOTE_DS3 156 #define NOTE_E3 165 #define NOTE_F3 175 #define NOTE_FS3 185 #define NOTE_G3 196 #define NOTE_GS3 208 #define NOTE_A3 220 #define NOTE_AS3 233 #define NOTE_B3 247 #define NOTE_C4 262 #define NOTE_CS4 277 #define NOTE_D4 294 #define NOTE_DS4 311 #define NOTE_E4 330 #define NOTE_F4 349 #define NOTE_FS4 370 #define NOTE_G4 392 #define NOTE_GS4 415 #define NOTE_A4 440 #define NOTE_AS4 466 #define NOTE_B4 494 #define NOTE_C5 523 #define NOTE_CS5 554 #define NOTE_D5 587 #define NOTE_DS5 622 #define NOTE_E5 659 #define NOTE_F5 698 #define NOTE_FS5 740 #define NOTE_G5 784 #define NOTE_GS5 831 #define NOTE_A5 880 #define NOTE_AS5 932 #define NOTE_B5 988 #define NOTE_C6 1047 #define NOTE_CS6 1109 #define NOTE_D6 1175 #define NOTE_DS6 1245 #define NOTE_E6 1319 #define NOTE_F6 1397 #define NOTE_FS6 1480 #define NOTE_G6 1568 #define NOTE_GS6 1661 #define NOTE_A6 1760 #define NOTE_AS6 1865 #define NOTE_B6 1976 #define NOTE_C7 2093 #define NOTE_CS7 2217 #define NOTE_D7 2349 #define NOTE_DS7 2489 #define NOTE_E7 2637 #define NOTE_F7 2794 #define NOTE_FS7 2960 #define NOTE_G7 3136 #define NOTE_GS7 3322 #define NOTE_A7 3520 #define NOTE_AS7 3729 #define NOTE_B7 3951 #define NOTE_C8 4186 #define NOTE_CS8 4435 #define NOTE_D8 4699 #define NOTE_DS8 4978 you just need to download and include this file in our Arduino code as given at the end this tutorial or use the code given in the zip file.

Playing Musical Notes on Arduino:

To play a decent melody using Arduino we should know what constitutes these melodies. The three main factors required to play a theme are Note value Note Duration Tempo like tone (pinName, Note Value, Note Duration); using which you can play them in your projects. But if you have any specific tone in your mine and you want to play it in your project read on.... Else skip this topic and fall down to the next. by reading the note value and note duration from it. If you are a musical student it would be a piece of cake for you, else spent some time and break you head like I did. But at the end of the day when your tone plays on the Piezo buzzer you will find your effort worth it. Once you have the note value and note duration, load them into the program inside the “themes.hᾠheader file as shown below //##############**"HE IS A PIRATE" Theme song of Pirates of caribbean**##############// int Pirates_note[] = { NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_A3, NOTE_C4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_E4, NOTE_F4, NOTE_F4, NOTE_F4, NOTE_G4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_C4, NOTE_C4, NOTE_D4, 0, NOTE_A3, NOTE_C4, NOTE_B3, NOTE_D4, NOTE_B3, NOTE_E4, NOTE_F4, NOTE_F4, NOTE_C4, NOTE_C4, NOTE_C4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_D4, 0, 0, NOTE_A3, NOTE_C4, NOTE_D4, NOTE_D4, NOTE_D4, NOTE_F4, NOTE_G4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_G4, NOTE_A4, NOTE_D4, 0, NOTE_D4, NOTE_E3, NOTE_F4, NOTE_F4, NOTE_G4, NOTE_A4, NOTE_D4, 0, NOTE_D4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_F4, NOTE_D4 }; int Pirates_duration[] = { 4,8,4,8,4,8,8,8,8,4,8,4,8,4,8,8,8,8,4,8,4,8, 4,8,8,8,8,4,4,8,8,4,4,8,8,4,4,8,8, 8,4,8,8,8,4,4,8,8,4,4,8,8,4,4,8,4, 4,8,8,8,8,4,4,8,8,4,4,8,8,4,4,8,8, 8,4,8,8,8,4,4,4,8,4,8,8,8,4,4,8,8 }; //###########End of He is a Pirate song#############// The above block of code shows the note value and note duration of “He is a Pirateᾠtheme form the movie Pirates of the Caribbean. You can add your theme similarly like this.

Schematic and Hardware:

project is shown in the figure below: The connection is pretty simple we have aPiezospeaker which is connected to pin 8 and Ground of theArduinothrough a 1K resistor. This 1k resistor is a current limiting resistor, which is used to keep the current within the safe limits. We also have four switches to select the required melody. One end of the switch is connected to ground and the other end is connected to pin 2, 3, 4 and 5 respectively. The switches will have pull up resistors enabled internally using the software. Since the circuit is pretty simple it can be connect using a bread board as shown below:

Arduino Program Explanation:

from here and directly upload it to your Arduino. contains the note value and note duration of all the four tones. #include "pitches.h" #include "themes.h" value void Play_Pirates() { for (int thisNote = 0; thisNote < (sizeof(Pirates_note)/sizeof(int)); thisNote++) { int noteDuration = 1000 / Pirates_duration[thisNote];//convert duration to time delay tone(8, Pirates_note[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 1.05; //Here 1.05 is tempo, increase to play it slower delay(pauseBetweenNotes); noTone(8); } } The pin 2, 3, 4 and 5 are used to select the particular tone to be played. These pins are held high by default using the internal pull up resistors by using the above line of code. When the button is pressed it is pulled down to ground. pinMode(2, INPUT_PULLUP); pinMode(3, INPUT_PULLUP); pinMode(4, INPUT_PULLUP); pinMode(5, INPUT_PULLUP); Below block of code is used to play the song when a button is pressed. It reads the digital value of each button and when it gets low (zero) it assumes that the button is pressed and plays the respective tone by calling the required function. if (digitalRead(2)==0) { Serial.println("Selected -> 'He is a Pirate' "); Play_Pirates(); } if (digitalRead(3)==0) { Serial.println("Selected -> 'Crazy Frog' "); Play_CrazyFrog(); } if (digitalRead(4)==0) { Serial.println("Selected -> 'Mario UnderWorld' "); Play_MarioUW(); } if (digitalRead(5)==0) { Serial.println("Selected -> 'He is a Pirate' "); Play_Pirates(); }

Working of this Melody Player Arduino Circuit:

Once your Code and Hardware is ready, simply burn the program into your Arduino and you should be able to play the tone by simply pressing the buttons. If you have any problems take a look at your serial monitor for debugging or use the comment section to report the problem and I will be happy to help you out. Hope you enjoyed the project and would use it in some of your project or create a new tone for your project. If yes feel free to share your work in the comment section. Code #include "pitches.h" //add Equivalent frequency for musical note #include "themes.h" //add Note vale and duration void Play_Pirates() { for (int thisNote = 0; thisNote < (sizeof(Pirates_note)/sizeof(int)); thisNote++) { int noteDuration = 1000 / Pirates_duration[thisNote];//convert duration to time delay tone(8, Pirates_note[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 1.05; //Here 1.05 is tempo, increase to play it slower delay(pauseBetweenNotes); noTone(8); //stop music on pin 8 } } void Play_CrazyFrog() { for (int thisNote = 0; thisNote < (sizeof(CrazyFrog_note)/sizeof(int)); thisNote++) { int noteDuration = 1000 / CrazyFrog_duration[thisNote]; //convert duration to time delay tone(8, CrazyFrog_note[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 1.30;//Here 1.30 is tempo, decrease to play it faster delay(pauseBetweenNotes); noTone(8); //stop music on pin 8 } } void Play_MarioUW() { for (int thisNote = 0; thisNote < (sizeof(MarioUW_note)/sizeof(int)); thisNote++) { int noteDuration = 1000 / MarioUW_duration[thisNote];//convert duration to time delay tone(8, MarioUW_note[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 1.80; delay(pauseBetweenNotes); noTone(8); //stop music on pin 8 } } void Play_Titanic() { for (int thisNote = 0; thisNote < (sizeof(Titanic_note)/sizeof(int)); thisNote++) { int noteDuration = 1000 / Titanic_duration[thisNote];//convert duration to time delay tone(8, Titanic_note[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 2.70; delay(pauseBetweenNotes); noTone(8); //stop music on pin 8 } } void setup() { pinMode(2, INPUT_PULLUP); //Button 1 with internal pull up pinMode(3, INPUT_PULLUP); //Button 2 with internal pull up pinMode(4, INPUT_PULLUP); //Button 3 with internal pull up pinMode(5, INPUT_PULLUP); //Button 4 with internal pull up Serial.begin(9600); } void loop() { if (digitalRead(2)==0) { Serial.println("Selected -> 'He is a Pirate' "); Play_Pirates(); } if (digitalRead(3)==0) { Serial.println("Selected -> 'Crazy Frog' "); Play_CrazyFrog(); } if (digitalRead(4)==0) { Serial.println("Selected -> 'Mario UnderWorld' "); Play_MarioUW(); } if (digitalRead(5)==0) { Serial.println("Selected -> 'Titanic' "); Play_Titanic(); } } Video microcontroller-projects/send-data-to-web-server-using-sim900a-arduino

How to Send Data to Web Server using Arduino and SIM900A GPRS/GSM Module

board, to send some data to the web service on the internet. etc.

Components Required:

Arduino GSM Module SIM900A 16x2 LCD 4x4 Matrix Keypad Breadboard or PCB Connecting jumper wire Power supply 12v SIM Card

Using GPRS in GSM Module:

to send data to different servers over internet. But this time we have used GPRS. Check the detailed Video at the end of this tutorial. which is apacket basedwireless communication service that works with data rate of 56-114kbps and provides a connection to the internet. There are many AT commands already mentioned in the datasheet of SIMCOM SIM900A GSM module. Now for sending data to server by using GPRS, first we need to initialize GSM module. AT :- this command is used to check whether GSM module is responding or not. AT+CPIN? :- this command is used to check whether SIM card is inserted in GSM Module or not. ATE0 :- is used for disabling echo ATE1 :- is used for enabling echo AT+CIPSHUT :- to close TCP Port Explicitly means disconnect connection if any AT+CGATT? :- Checking SIM card has internet connection or not AT+CSTT = "APN","userName","Pass" :- connect to internet (ex; AT+CSTT="airtelgprs.com","","") AT+CIICR :- bring up with the wireless network. Checking SIM card has data pack or balance AT+CIFSR :- get IP (sometimes without this command GSM do not work so use this command) AT+CIPSTART = ”TCP”,”SERVER IP”,”PORT” :- is used for creating TCP connection with the server that we provide in place of SERVER IP AT+CIPSEND :- this command is used for sending data to the server. After input, this command server asks for data.

Working Explanation:

is easy. Here in this project, we are sending some string or words to the server by typing using keypad. Same string or word will appear over the LCD, then press D/OK to send the input string to the server. Here we have created an Alphanumeric Keypad for inputting the characters or numeric values to Arduino or LCD. C/clear is programmed for backspace. to accept alphabets also. Check the full code at the end of the article.

Circuit Explanation:

is used for input string to Arduino and its Row pins R1, R2, R3, R4 are directly linked to pin number 11,10, 9, 8 of Arduino and Colum pin of keypad C1, C2, C3 are linked with pin number 7, 6, 5,4 of Arduino. Here we have also connected GSM Tx pin to Tx of Arduino to get response data over the serial monitor.

Programming Explanation:

for interfacing simple keypad for entering numbers. And for entering alphabets we have used the same library and keypad but used one more function to make it alphanumeric keypad. Means we have made every key multi-functioning and can enter all the characters and integers by using only 10 keys. If we press key 2 (ABC2), it will show ‘Aᾠand if we press it again then it will replace ‘Aᾠwith ‘Bᾠand if again we press it then it will show ‘Cᾠat the same place in LCD. If we wait for some time after pressing a key, the cursor will automatically move to next position in LCD. Now we can enter next char or number. And same procedure is applied to other keys. It works same as keypad in old mobile phones. library and define array matrix for the keys: #include <Keypad.h> // keypad library for interfacing keypad const byte ROWS = 4; //four rows const byte COLS = 4; //four columns int x=0; int y=0; int n=0; int minValue=0; int maxValue=0; char keyPress=0; int keyPressTime=100; String msg=""; char hexaKeys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; byte rowPins[ROWS] = {11, 10, 9, 8}; //connect to the row pinouts of the keypad byte colPins[COLS] = {7, 6, 5, 4}; //connect to the column pinouts of the keypad function is used for input alphabets void getkey(int minValue, int maxValue, char keyPress) { int ch=minValue; int pressed=1; char key=keyPress; lcd.noBlink(); for(int i=0;i<keyPressTime;i++) { if(key==keyPress) { lcd.setCursor(x,y); lcd.print(alpha[ch]); ch++; if(ch>maxValue) ch=minValue; i=0; } .... ..... functions are used for initializing GSM module and GPRS void initGSM() { connectGSM("AT","OK"); connectGSM("ATE1","OK"); connectGSM("AT+CPIN?","READY"); } void initGPRS() { connectGSM("AT+CIPSHUT","OK"); connectGSM("AT+CGATT=1","OK"); connectGSM("AT+CSTT=\"airtelgprs.com\",\"\",\"\"","OK"); connectGSM("AT+CIICR","OK"); delay(1000); Serial1.println("AT+CIFSR"); delay(1000); } Below part of the code is used to create URL and send the data to server via URL. else if(key == 'D') { lcd.clear(); lcd.noBlink(); lcd.print("Sending Data"); lcd.setCursor(0,1); lcd.print("To Server"); url="GET /input/"; url+=publicKey; url+="?private_key="; url+=pvtKey; url+="&log="; url+=msg; url+=" HTTP/1.0\r\n\r\n"; String svr=Start+","+ip+","+port; delay(1000); connectGSM(svr,"CONNECT"); delay(1000); int len = url.length(); String str=""; str=SendCmd+len; sendToServer(str); Code #include <SoftwareSerial.h> // serial software library for interfacing gsm module SoftwareSerial Serial1(2, 3); // RX, TX // connect gsm Tx at D2 and Rx at D3 #include<LiquidCrystal.h> // LCD library for interfacing LCD LiquidCrystal lcd(14,15,16,17,18,19); // connect rs,en,d4,d5,d6,d7 respectevely String pvtKey="wY9DPG5vzpH99KNrNkx2"; // private key for posting data to sparkfun String publicKey="w5nXxM6rp0tww5YVYg3G"; // public key for open page of sparkfun String url=""; String ip="\"data.sparkfun.com\""; // sparkfun server ip or url int port=80; // sparkfun server port String SendCmd="AT+CIPSEND="; // sending number of byte command String Start="AT+CIPSTART=\"TCP\""; // TCPIP start command // strings and variables //String msg=""; String instr=""; String str_sms=""; String str1=""; int i=0,temp=0; #include <Keypad.h> // keypad library for interfacing keypad const byte ROWS = 4; //four rows const byte COLS = 4; //four columns int x=0; int y=0; int n=0; int minValue=0; int maxValue=0; char keyPress=0; int keyPressTime=100; String msg=""; char hexaKeys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; byte rowPins[ROWS] = {11, 10, 9, 8}; //connect to the row pinouts of the keypad byte colPins[COLS] = {7, 6, 5, 4}; //connect to the column pinouts of the keypad Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); String alpha="1!@_$%?ABC2DEF3GHI4JKL5MNO6PQRS7TUV8WXYZ9* 0#"; void setup() { Serial1.begin(9600); // init serial1 for GSM lcd.begin(16,2); // init LCD lcd.print("Sending Data "); lcd.setCursor(0,1); lcd.print("to Server"); delay(2000); lcd.clear(); lcd.print("Circuit Digest"); lcd.setCursor(0,1); lcd.print("Saddam Khan"); delay(2000); lcd.clear(); lcd.print("Initializing GSM"); initGSM(); // init GSM module lcd.clear(); lcd.print("Initializing GPRS"); initGPRS(); // init GPRS in GSM Module lcd.clear(); lcd.print("System Ready"); delay(2000); } void loop() { int n=0; lcd.clear(); lcd.noCursor(); while(1) { lcd.cursor(); char key = customKeypad.getKey(); if(key=='1') getkey(0, 6, key); if(key=='2') getkey(7, 10, key); else if(key=='3') getkey(11, 14, key); else if(key=='4') getkey(15, 18, key); else if(key=='5') getkey(19, 22, key); else if(key=='6') getkey(23, 26, key); else if(key=='7') getkey(27, 31, key); else if(key=='8') getkey(32,35, key); else if(key=='9') getkey(36, 40, key); else if(key=='*') getkey(41, 41, key); else if(key=='0') getkey(42, 43, key); else if(key=='#') getkey(44, 44, key); else if(key == 'C') { x--; lcd.setCursor(x,y); lcd.print(" "); n--; msg[n]=' '; lcd.setCursor(x,y); } else if(key == 'D') { lcd.clear(); lcd.noBlink(); lcd.print("Sending Data"); lcd.setCursor(0,1); lcd.print("To Server"); url="GET /input/"; url+=publicKey; url+="?private_key="; url+=pvtKey; url+="&log="; url+=msg; url+=" HTTP/1.0\r\n\r\n"; String svr=Start+","+ip+","+port; delay(1000); connectGSM(svr,"CONNECT"); delay(1000); int len = url.length(); String str=""; str=SendCmd+len; sendToServer(str); Serial1.print(url); delay(1000); Serial1.write(0x1A); delay(1000); lcd.clear(); lcd_status(); // clearmsg(); n=0; i=0; x=0; y=0; msg=""; } } } void getkey(int minValue, int maxValue, char keyPress) { int ch=minValue; int pressed=1; char key=keyPress; lcd.noBlink(); for(int i=0;i<keyPressTime;i++) { if(key==keyPress) { lcd.setCursor(x,y); lcd.print(alpha[ch]); ch++; if(ch>maxValue) ch=minValue; i=0; } key=customKeypad.getKey(); delay(10); } if(pressed) { x++; msg+=alpha[ch-1]; n++; if(x>15) { x=0; y=1; } } pressed=0; lcd.blink(); } void lcd_status() { lcd.clear(); lcd.print("Data Sent to"); lcd.setCursor(0,1); lcd.print("Server"); delay(2000); lcd.clear(); } void sendToServer(String str) { Serial1.println(str); delay(1000); } void initGSM() { connectGSM("AT","OK"); connectGSM("ATE1","OK"); connectGSM("AT+CPIN?","READY"); } void initGPRS() { connectGSM("AT+CIPSHUT","OK"); connectGSM("AT+CGATT=1","OK"); connectGSM("AT+CSTT=\"airtelgprs.com\",\"\",\"\"","OK"); connectGSM("AT+CIICR","OK"); delay(1000); Serial1.println("AT+CIFSR"); delay(1000); } void connectGSM (String cmd, char *res) { while(1) { Serial.println(cmd); Serial1.println(cmd); delay(500); while(Serial1.available()>0) { if(Serial1.find(res)) { delay(1000); return; } } delay(1000); } } /* Public URL http://data.sparkfun.com/streams/w5nXxM6rp0tww5YVYg3G Public Key w5nXxM6rp0tww5YVYg3G Private Key wY9DPG5vzpH99KNrNkx2 Keep this key secret, and in a safe place. You will not be able to retrieve it. Delete Key xxxxxxxxxxxxx This key can only be used once. Keep this key secret, and in a safe place. You will not be able to retrieve it. Logging using query string parameters Format: http://data.sparkfun.com/input/[publicKey]?private_key=[privateKey]&log=[value] Example: http://data.sparkfun.com/input/w5nXxM6rp0tww5YVYg3G?private_key=wY9DPG5vzpH99KNrNkx2&log=22.21 */ Video microcontroller-projects/arduino-audio-music-player

Simple Arduino Audio Player and Amplifier with LM386

Thanks to the Arduino community who have developed some libraries to build this in a fast and easy way. We have also used IC LM386 here for amplification and noise cancelation purpose. which we have built earlier.

Hardware Required:

Arduino UNO SD Card Reader module SD card LM386 Audio Amplifier 10uf Capacitor (2 Nos) 100uf Capacitor (2 Nos) 1K,10K Resistor Push buttons (2 Nos) Breadboard Connecting Wires

Getting ready with your WAV audio files:

, thereare websites which you can be used to convert any audio file on your computer into that specific WAV file. So to convert any audio file into wav format, follow the below steps: to enter into the website. Arduino can play a wav file in the following format. You can toy around with the settings later, but these settings were experiment to be the best in quality.
8 Bit
16000 Hz
Mono
PCM unsigned 8-bit
In the website click on “choose fileᾠand select the file you want to convert. Then feed in the above settings. Once done it should look something like this in the below image Now, click on “Convert Fileᾠand your Audio file will be converter to .Wav file format. It will also be downloaded once the conversion is done. Finally format your SD card and save your .wav audio file into it. Make sure you format it before you add this file. Also remember the name of your audio file. Similarly you can select any of your four audios and save them with names 1, 2, 3 and 4(Names should not be changed). I have converted four songs and have saved them as 1.wav, 2.wav, 3.wav and 4.wav like shown below.

Circuit and Hardware:

is simple. The complete circuit diagram is shown in the Image below.
+5VVcc
GndGnd
Pin 12MISO (Master In Slave out)
Pin 11MOSI (Master Out Slave In)
Pin 13SCK (Synchronous Clock)
Pin 4CS (Chip Select)
. We also have two push buttons connected to the pin 2 and 3 of the Arduino. These switches are used to play the next track of the song and play/pause the music respectively. I have used these buttons just to demonstrate its abilities; you can play the song whenever required. Check the Demo Video at the end. You can assemble this circuit completely over a Breadboard as shown in the picture below

Programming your Arduino:

Once we are ready with the Hardware and the SD card, we are just one step away playing those songs. Insert the card into your SD card module and follow the steps below. As said earlier we will be using a library to make this project work. The link for the library is given below. Click on it and select “Clone or downloadᾠand choose download as ZIP. TMRpcm library Add this Zip file into your Arduino IDE by selecting Sketch->Include Library -> Add .ZIP Library as shown below and select the ZIP file that we just downloaded. is given at the end of this article, simply copy it and paste it in the Arduino Program. Now, click on Upload and get ready to play your audio files. The program is self explanatory since they have the comment lines. But, I have also explained the ability of the TMRpcm library below. You can play any audio that is stored in Wav format inside the SD card module by using the line below. music.play("3.wav"); //object name.play (“FileName.wavᾩ; You can use this line at places where you want to trigger the Audio To pause an Audio file, you can simply call the line below. music.pause(); //objectname.pause(); There are not direct ways to forward or rewind an Audio file, but you can use the line below to play a song at a particular time. This can be used to forward/rewind with some additional programming. music.play("2.wav",33); //Plays the song from 33rd second //objectname.play(“Filename.wavᾬtime in second); The library gives us two qualities to play the music, one is to play as normal mode the other to play with 2X oversampling. music.quality(0); //Normal Mode music.quality(1); //2X over sampling mode Yes, you can control the volume of the audio through software. You can simply set the volume by using the line below. Higher music volumes tend to affect the quality of the audio, hence use hardware control when possible. music.setVolume(5); //Plays the song at volume 5 //objectname.setVolume(Volume level);

Working of this Arduino Music Player:

After programming your Arduino simply press the button connected to pin 2 and your Arduino will play the first song (saved as 1.wav) for you. Now you can press the button again to change your track to the next song that is to play 2.wav. Likewise you can navigate to all four songs. for complete working (or maybe to relax yourself with some songs). Hope you enjoyed the project. Now it is up to your creativity to use them in your projects. You can make a speaking clock, voice assistant, talking robot, voice alert security system and much more. Let me know how you are planning to use it through the comment section and also if you have any problems in getting this thing work you can reach me through the forums or the comment section below. Code /* Arduino Based Music Player This example shows how to play three songs from SD card by pressing a push button The circuit: * Push Button on pin 2 and 3 * Audio Out - pin 9 * SD card attached to SPI bus as follows: ** MOSI - pin 11 ** MISO - pin 12 ** CLK - pin 13 ** CS - pin 4 created 25 Jun 2017 by Aswinth Raj This example code was created for CircuitDigest.com */ #include "SD.h" //Lib to read SD card #include "TMRpcm.h" //Lib to play auido #include "SPI.h" //SPI lib for SD card #define SD_ChipSelectPin 4 //Chip select is pin number 4 TMRpcm music; //Lib object is named "music" int song_number=0; boolean debounce1=true; boolean debounce2=true; boolean play_pause; void setup(){ music.speakerPin = 9; //Auido out on pin 9 Serial.begin(9600); //Serial Com for debugging if (!SD.begin(SD_ChipSelectPin)) { Serial.println("SD fail"); return; } pinMode(2, INPUT_PULLUP); //Button 1 with internal pull up to chage track pinMode(3, INPUT_PULLUP); //Button 2 with internal pull up to play/pause pinMode(3, INPUT_PULLUP); //Button 2 with internal pull up to fast forward music.setVolume(5); // 0 to 7. Set volume level music.quality(1); // Set 1 for 2x oversampling Set 0 for normal //music.volume(0); // 1(up) or 0(down) to control volume //music.play("filename",30); plays a file starting at 30 seconds into the track } void loop() { if (digitalRead(2)==LOW && debounce1 == true) //Button 1 Pressed { song_number++; if (song_number==5) {song_number=1;} debounce1=false; Serial.println("KEY PRESSED"); Serial.print("song_number="); Serial.println(song_number); if (song_number ==1) {music.play("1.wav",10);} //Play song 1 from 10th second if (song_number ==2) {music.play("2.wav",33);} //Play song 2 from 33rd second if (song_number ==3) {music.play("3.wav");} //Play song 3 from start if (song_number ==4) {music.play("4.wav",25);} //Play song 4 from 25th second if (digitalRead(3)==LOW && debounce2 == true) //Button 2 Pressed { music.pause(); Serial.println("PLAY / PAUSE"); debounce2=false; } if (digitalRead(2)==HIGH) //Avoid debounce debounce1=true; if (digitalRead(3)==HIGH)//Avoid debounce debounce2=true; } } Video microcontroller-projects/arduino-ssd1306-oled-display

Interfacing SSD1306 OLED Display with Arduino

There are lots of types of OLED displays available in the market and there are lots of ways to get them working. In this tutorial we will discuss about its classifications and also which will be best suited for your project.

Hardware Required:

7pin 128×64 OLED display Module (SSD1306) Arduino UNO/Nano Breadboard Connecting Wires Computer/Laptop

Getting to know about OLED Displays:

as it is the fastest mode of communication and the default one. The pins and its functions are explained in the table below.
GndGroundGround pin of the module
VddVcc, 5VPower pin (3-5V tolerable)
SCKD0,SCL,CLKActs as the clock pin. Used for both I2C and SPI
SDAD1,MOSIData pin of the module. Used for both IIC and SPI
RESRST,RESETResets the module (useful during SPI)
DCA0Data Command pin. Used for SPI protocol
CSChip SelectUseful when more than one module is used under SPI protocol
In this tutorial we will simply operate the module in 4-Wire SPI mode, we will leave the rest for some other tutorial. Library was very easy to use and had a handful of graphical options hence we will use the same in this tutorial. But, if your project has a memory/speed constraint try using the U8g Library as it works faster and occupies less program memory.

Hardware and connections:

is really simple and is shown below Since the OLED runs on 3V-5V and consumes very little power it does not need an external power supply. You can simply use wires to make the connection or use a breadboard as I have used so that it is easy to experiment. The connection is also listed in tale below
Gnd, GroundGround
Vdd, Vcc, 5V5V
SCK, D0,SCL,CLK10
SDA, D1,MOSI9
RES, RST,RESET13
DC, A011
CS, Chip Select12

Programming the SSD1306 OLED display for Arduino:

Once the connections are ready you can start programming the Arduino. As said earlier we will be using the Adafruit library and GFX library for working with this OLED module. Follow the steps to test run your OLED display. Download the Adafruit Library and the GFX library from Github using the link below Adafruit Library GFX Graphics Library You should have download two Zip files. Now add them to your Arduino by following as shown below. Then select the library we just downloaded. You can select only one library at a time, hence you have to repeat this step again. as shown in the image below. as shown in the image below. This example program shows you all possible graphics that could be displayed in the OLED screen. This code should be enough for you to create bitmaps, draw lines/circles/rectangles, play with pixels, display char and string with different fonts and size etc... is given at the end of this Article Writing on OLED screen is just like writing on a black board, we have to write the values and then clean it before it could be overwritten. The following commands are used to write and clear the display display.display(); //Write to display display.clearDisplay(); //clear the display To display the content inside a variable the following code can be used. char i=5; //the variable to be displayed display.setTextSize(1); //Select the size of the text display.setTextColor(WHITE); //for monochrome display only whit is possible display.setCursor(0,0); //0,0 is the top left corner of the OLED screen display.write(i); //Write the variable to be displayed If you want add some symbols to your display you can use the following code to draw any of the following display.drawLine(display.width()-1, 0, i, display.height()-1, WHITE); //void drawLine( x0, y0, x1, y1, color); display.drawRect(i, i, display.width()-2*i, display.height()-2*i, WHITE); //void drawRect( x0, y0, w, h, color); display.drawTriangle(display.width()/2, display.height()/2-i,display.width()/2-i,display.height()/2+i, display.width()/2+i, display.height()/2+i, WHITE); //void drawTriangle( x0, y0, x1, y1, x2, y2, color); display.drawCircle(display.width()/2, display.height()/2, i, WHITE); //void drawCircle( x0, y0, r, color); The following chunk of code can be used o display any message in the screen at a particular place and size display.setTextSize(2); //set the size of the text display.setTextColor(WHITE); //color setting display.setCursor(10,0); //The string will start at 10,0 (x,y) display.clearDisplay(); //Eraser any previous display on the screen display.println("Circuit Digest"); //Print the string here “Circuit Digestᾍ display.display(); //send the text to the screen One untrusting thing that can be done with the OLED module is that it can be used to display bitmaps. The following code is used to display an bitmap image static const unsigned char PROGMEM logo16_glcd_bmp[] = { B00000000, B11000000, B00000001, B11000000, B00000001, B11000000, B00000011, B11100000, B11110011, B11100000, B11111110, B11111000, B01111110, B11111111, B00110011, B10011111, B00011111, B11111100, B00001101, B01110000, B00011011, B10100000, B00111111, B11100000, B00111111, B11110000, B01111100, B11110000, B01110000, B01110000, B00000000, B00110000 }; display.drawBitmap(XPO], YPOS, bitmap, w, h, WHITE); //void drawBitmap( x, y, *bitmap, w, h, color); As you can see, in order to display an image the bitmap data must be stored in the program memory in form of PROMGMEM directive. Simply put, we have to instruct the OLED display what to do with each pixel by passing it a sequence or values from a n array as shown above. This array will contain the bitmap data of the image. and load them into the above array. and this is how it turned out. page. Hope you got this running and ready to implement an OLED display in some of your projects. If you had any problem share them in the comment section and I will try my best to rectify them. Code /********************************************************************* This is an example for our Monochrome OLEDs based on SSD1306 drivers Pick one up today in the adafruit shop! ------> http://www.adafruit.com/category/63_98 This example is for a 128x64 size display using SPI to communicate 4 or 5 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, check license.txt for more information All text above, and the splash screen must be included in any redistribution *********************************************************************/ #include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> // If using software SPI (the default case): #define OLED_MOSI 9 #define OLED_CLK 10 #define OLED_DC 11 #define OLED_CS 12 #define OLED_RESET 13 Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS); /* Uncomment this block to use hardware SPI #define OLED_DC 6 #define OLED_CS 7 #define OLED_RESET 8 Adafruit_SSD1306 display(OLED_DC, OLED_RESET, OLED_CS); */ #define NUMFLAKES 10 #define XPOS 0 #define YPOS 1 #define DELTAY 2 #define LOGO16_GLCD_HEIGHT 16 #define LOGO16_GLCD_WIDTH 16 static const unsigned char PROGMEM logo16_glcd_bmp[] = { B00000000, B11000000, B00000001, B11000000, B00000001, B11000000, B00000011, B11100000, B11110011, B11100000, B11111110, B11111000, B01111110, B11111111, B00110011, B10011111, B00011111, B11111100, B00001101, B01110000, B00011011, B10100000, B00111111, B11100000, B00111111, B11110000, B01111100, B11110000, B01110000, B01110000, B00000000, B00110000 }; #define SSD1306_LCDHEIGHT 64 #if (SSD1306_LCDHEIGHT != 64) #error("Height incorrect, please fix Adafruit_SSD1306.h!"); #endif void setup() { Serial.begin(9600); // by default, we'll generate the high voltage from the 3.3v line internally! (neat!) display.begin(SSD1306_SWITCHCAPVCC); // init done // Show image buffer on the display hardware. // Since the buffer is intialized with an Adafruit splashscreen // internally, this will display the splashscreen. display.display(); delay(2000); // Clear the buffer. display.clearDisplay(); // draw a single pixel display.drawPixel(10, 10, WHITE); // Show the display buffer on the hardware. // NOTE: You _must_ call display after making any drawing commands // to make them visible on the display hardware! display.display(); delay(2000); display.clearDisplay(); // draw many lines testdrawline(); display.display(); delay(2000); display.clearDisplay(); // draw rectangles testdrawrect(); display.display(); delay(2000); display.clearDisplay(); // draw multiple rectangles testfillrect(); display.display(); delay(2000); display.clearDisplay(); // draw mulitple circles testdrawcircle(); display.display(); delay(2000); display.clearDisplay(); // draw a white circle, 10 pixel radius display.fillCircle(display.width()/2, display.height()/2, 10, WHITE); display.display(); delay(2000); display.clearDisplay(); testdrawroundrect(); delay(2000); display.clearDisplay(); testfillroundrect(); delay(2000); display.clearDisplay(); testdrawtriangle(); delay(2000); display.clearDisplay(); testfilltriangle(); delay(2000); display.clearDisplay(); // draw the first ~12 characters in the font testdrawchar(); display.display(); delay(2000); display.clearDisplay(); // draw scrolling text testscrolltext(); delay(2000); display.clearDisplay(); // text display tests display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(0,0); display.println("Hello, world!"); display.setTextColor(BLACK, WHITE); // 'inverted' text display.println(3.141592); display.setTextSize(2); display.setTextColor(WHITE); display.print("0x"); display.println(0xDEADBEEF, HEX); display.display(); delay(2000); display.clearDisplay(); // miniature bitmap display display.drawBitmap(30, 16, logo16_glcd_bmp, 16, 16, 1); display.display(); // invert the display display.invertDisplay(true); delay(1000); display.invertDisplay(false); delay(1000); display.clearDisplay(); // draw a bitmap icon and 'animate' movement testdrawbitmap(logo16_glcd_bmp, LOGO16_GLCD_HEIGHT, LOGO16_GLCD_WIDTH); } void loop() { } void testdrawbitmap(const uint8_t *bitmap, uint8_t w, uint8_t h) { uint8_t icons[NUMFLAKES][3]; // initialize for (uint8_t f=0; f< NUMFLAKES; f++) { icons[f][XPOS] = random(display.width()); icons[f][YPOS] = 0; icons[f][DELTAY] = random(5) + 1; Serial.print("x: "); Serial.print(icons[f][XPOS], DEC); Serial.print(" y: "); Serial.print(icons[f][YPOS], DEC); Serial.print(" dy: "); Serial.println(icons[f][DELTAY], DEC); } while (1) { // draw each icon for (uint8_t f=0; f< NUMFLAKES; f++) { display.drawBitmap(icons[f][XPOS], icons[f][YPOS], bitmap, w, h, WHITE); } display.display(); delay(200); // then erase it + move it for (uint8_t f=0; f< NUMFLAKES; f++) { display.drawBitmap(icons[f][XPOS], icons[f][YPOS], bitmap, w, h, BLACK); // move it icons[f][YPOS] += icons[f][DELTAY]; // if its gone, reinit if (icons[f][YPOS] > display.height()) { icons[f][XPOS] = random(display.width()); icons[f][YPOS] = 0; icons[f][DELTAY] = random(5) + 1; } } } } void testdrawchar(void) { display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(0,0); for (uint8_t i=0; i < 168; i++) { if (i == '\n') continue; display.write(i); if ((i > 0) && (i % 21 == 0)) display.println(); } display.display(); } void testdrawcircle(void) { for (int16_t i=0; i<display.height(); i+=2) { display.drawCircle(display.width()/2, display.height()/2, i, WHITE); display.display(); } } void testfillrect(void) { uint8_t color = 1; for (int16_t i=0; i<display.height()/2; i+=3) { // alternate colors display.fillRect(i, i, display.width()-i*2, display.height()-i*2, color%2); display.display(); color++; } } void testdrawtriangle(void) { for (int16_t i=0; i<min(display.width(),display.height())/2; i+=5) { display.drawTriangle(display.width()/2, display.height()/2-i, display.width()/2-i, display.height()/2+i, display.width()/2+i, display.height()/2+i, WHITE); display.display(); } } void testfilltriangle(void) { uint8_t color = WHITE; for (int16_t i=min(display.width(),display.height())/2; i>0; i-=5) { display.fillTriangle(display.width()/2, display.height()/2-i, display.width()/2-i, display.height()/2+i, display.width()/2+i, display.height()/2+i, WHITE); if (color == WHITE) color = BLACK; else color = WHITE; display.display(); } } void testdrawroundrect(void) { for (int16_t i=0; i<display.height()/2-2; i+=2) { display.drawRoundRect(i, i, display.width()-2*i, display.height()-2*i, display.height()/4, WHITE); display.display(); } } void testfillroundrect(void) { uint8_t color = WHITE; for (int16_t i=0; i<display.height()/2-2; i+=2) { display.fillRoundRect(i, i, display.width()-2*i, display.height()-2*i, display.height()/4, color); if (color == WHITE) color = BLACK; else color = WHITE; display.display(); } } void testdrawrect(void) { for (int16_t i=0; i<display.height()/2; i+=2) { display.drawRect(i, i, display.width()-2*i, display.height()-2*i, WHITE); display.display(); } } void testdrawline() { for (int16_t i=0; i<display.width(); i+=4) { display.drawLine(0, 0, i, display.height()-1, WHITE); display.display(); } for (int16_t i=0; i<display.height(); i+=4) { display.drawLine(0, 0, display.width()-1, i, WHITE); display.display(); } delay(250); display.clearDisplay(); for (int16_t i=0; i<display.width(); i+=4) { display.drawLine(0, display.height()-1, i, 0, WHITE); display.display(); } for (int16_t i=display.height()-1; i>=0; i-=4) { display.drawLine(0, display.height()-1, display.width()-1, i, WHITE); display.display(); } delay(250); display.clearDisplay(); for (int16_t i=display.width()-1; i>=0; i-=4) { display.drawLine(display.width()-1, display.height()-1, i, 0, WHITE); display.display(); } for (int16_t i=display.height()-1; i>=0; i-=4) { display.drawLine(display.width()-1, display.height()-1, 0, i, WHITE); display.display(); } delay(250); display.clearDisplay(); for (int16_t i=0; i<display.height(); i+=4) { display.drawLine(display.width()-1, 0, 0, i, WHITE); display.display(); } for (int16_t i=0; i<display.width(); i+=4) { display.drawLine(display.width()-1, 0, i, display.height()-1, WHITE); display.display(); } delay(250); } void testscrolltext(void) { display.setTextSize(2); display.setTextColor(WHITE); display.setCursor(10,0); display.clearDisplay(); display.println("scroll"); display.display(); display.startscrollright(0x00, 0x0F); delay(2000); display.stopscroll(); delay(1000); display.startscrollleft(0x00, 0x0F); delay(2000); display.stopscroll(); delay(1000); display.startscrolldiagright(0x00, 0x07); delay(2000); display.startscrolldiagleft(0x00, 0x07); delay(2000); display.stopscroll(); } Video microcontroller-projects/arduino-face-tracking-robot

Real Time Face Detection and Tracking Robot using Arduino

here is that you do not need to invest on a camera module and the whole image detection work can be done in the phone itself, you do not need your Arduino connected to your computer for this to work. Here we have used Bluetooth Module with Arduino to communicate with Mobile wirelessly. at the end this tutorial to see it working. Let’s see how we can build one... I have tried my best to make this project to work as simple as possible, anyone with minimum knowledge on hardware or coding can use this guidelines to make this project work in no time. However once you make it I suggest you to get behind the codes so that you can really know what makes this thing work and how.

Materials Required:

Arduino Nano Servo motor SG90 ᾠ2Nos Android Phone with decent camera HC-05/HC-06 Bluetooth Module Computer for programming 3D printer (optional) 9V Battery

3D Printing the Required Parts (Optional):

In order to pan and tilt our mobile phone we need some mechanical structures like a mobile holder and a few servo brackets. You can use a cardboard to make one, since I have a 3D printer I decided to 3D print these parts. to directly print and assemble them. However few parts like the mobile phone holder might need some modifications based on the dimensions of your phone. I have designed it for my MOTO G mobile phone.I have used a very basic printer of mine to print all the parts. The printer is FABX v1 from 3ding which comes at an affordable pricewith a print volume of 10 cubic cm. The cheap price comes with a trade off with low print resolution and no SD card or print resuming function. I am using software called Cura to print the STL files. The settings that I used to print the materials are given below you can use the same or change them based on your printer. Once you print all the required materials you can secure them in position by using screws and some hot glue. After you assembly is complete it should look something like this below.

Schematic and Hardware:

project is shown in the image below: The whole circuit is powered by a 9V battery. This circuit can be connected easily on your breadboard or you can also solder these on a small Perf board like I have done here.

Setting up your Android Application:

You can directly install this application on your mobile phone and launch that by following the steps below. Download the APK file from here. Power on the circuit shown above. In your phone settings search for Bluetooth module named “HC-05ᾍ If you have named it something else other than “HC-05ᾠchange it back to HC-05 since only then the application will work. Pair with your Bluetooth module with the password ᾱ234ᾠor ᾰ000ᾮ Now, launch the Application in portrait mode. You should see your camera screen and also “Connected to: HC-05ᾠon the top of your screen. Try moving your camera over a face and a green box should appear on top of it and its position will also be displayed on the top left corner of your screen as shown below. You are free to make any advancement with your own creativity. Check below projects to learn more about Processing: Virtual Reality using Arduino and Processing Ping Pong Game using Arduino Smart Phone Controlled FM Radio using Processing. Arduino Radar System using Processing and Ultrasonic Sensor

Programming your Arduino:

The Android application will detect the face and its position on screen; it will then decide which direction it should move based on the position of the face so that the face gets to the centre of the screen. This direction is then sent to the Arduino via Bluetooth Module. can be found at the end of this tutorial, I have also explained few important lines below. Below line of code establishes a serial connection with pins D12 as RX and D11 as TX. Hence the pin D12 must be connected to the TX of the BT module and the pin D11 to the RX of the BT module. SoftwareSerial cam_BT(12, 11); // RX, TX Then we have initialised the Bluetooth module at a baud rate of 9600. Make sure you module also works on the same baud rate. Else change it accordingly. cam_BT.begin(9600); //start the Bluetooth communication at 9600 baudrate cam_BT.println("Ready to take commands"); Below line reads what is coming in through the Bluetooth module. Also the data is saved in the variable “BluetoothDataᾮ if (cam_BT.available()) //Read whats coming in through Bluetooth { BluetoothData=cam_BT.read(); Serial.print("Incoming from BT:"); Serial.println(BluetoothData); } Based on the data received from the Bluetooth the motors direction is controlled. To turn a motor left the motor is decrement by a value of 2 from its previous position. You can increase this value 2 to 4 or 6 if you need the arm to move faster. But, it might create some jerks making the camera unstable. if (BluetoothData==49) //Turn Left {pos1+=2; servo1.write(pos1);} if (BluetoothData==50) //Turn Right {pos1-=2; servo1.write(pos1);} if (BluetoothData==51) //Turn Up {pos2-=2; servo2.write(pos2);} if (BluetoothData==52) //Turn Down {pos2+=2; servo2.write(pos2);}

Working:

Once we are ready with our hardware, code and Android Application its time for some action. Simply power your Arduino and open the android application. The Application will automatically connect to the HC-05 (must be named HC-05) Bluetooth module and will wait for a face to be detected. Simply place the phone in our mobile holder and sit in front of it. You should notice your servo motors moving your phone so that your face will be placed at the centre of the screen. Now move around within the range of the camera and your mobile phone will follow your movements. You can also try it by placing and moving any picture. You can build a lot more on top of it which is left for your creativity, I hope you enjoyed the project and got it working. If not, leave your feedbacks in the comment section and I will respond to them. section on the website to find more such projects. Code /*Arduino Code for Face Tracking Arduino * Coded by Circuitdigest.com * On 25-05-2017 */ /*CONNECTION DETIALS * Arduino D11 -> RX of BT Module * Arduino D12 -> Tx of BT * Servo1 -> pin 3 of arduino Nano to pan * Servo2 -> pin 5 of arduino Nano to tilt */ #include <Servo.h> //header to drive servo motors #include <SoftwareSerial.h>// import the serial library SoftwareSerial cam_BT(12, 11); // RX, TX int ledpin=13; // led on D13 will show blink on / off int BluetoothData; // the data given from Computer //lets declare the servo objects Servo servo1; Servo servo2; long gmotor,gnum1,gnum2; int pos; int flag=0; int pos1 = 40; int pos2 = 90; void setup() { servo1.attach(3); servo2.attach(5);; //**Initial position of all four servo motors**// servo1.write(pos1); servo2.write(pos2); //**initialised**// cam_BT.begin(9600); //start the Bluetooth communication at 9600 baudrate cam_BT.println("Ready to take commands"); Serial.begin(57600); Serial.println("Face tracking programming by CircuitDigest.com"); } //***Function for each Servo actions**// void call(int motor, int num1, int num2) // The values like Motor number , from angle and to angle are received { Serial.println("Passing values..."); flag =0; switch (motor) { case 1: // For motor one { Serial.println("Executing motor one"); if(num1<num2) // Clock wise rotation { for ( pos =num1; pos<=num2; pos+=1) { servo1.write(pos); delay( 20); } } if(num1>num2) // Anti-Clock wise rotation { for ( pos =num1; pos>=num2; pos-=1) { servo1.write(pos); delay( 20); } } break; } ////////JUST DUPLICATE FOR OTHER SERVOS//// case 2: // For motor 2 { Serial.println("Executing motor two"); if(num1<num2) { for ( pos =num1; pos<=num2; pos+=1) { servo2.write(pos); delay( 20); } } if(num1>num2) { for ( pos =num1; pos>=num2; pos-=1) { servo2.write(pos); delay( 20); } } break; } } } void loop() { if(Serial.available()>0) //Read whats coming in through Serial { gmotor= Serial.parseInt(); Serial.print(" selected Number-> "); Serial.print(gmotor); Serial.print(" , "); gnum1= Serial.parseInt(); Serial.print(gnum1); Serial.print(" degree , "); gnum2= Serial.parseInt(); Serial.print(gnum2); Serial.println(" degree "); flag=1; } if (cam_BT.available()) //Read whats coming in through Bluetooth { BluetoothData=cam_BT.read(); Serial.print("Incoming from BT:"); Serial.println(BluetoothData); } if (flag ==1) call(gmotor,gnum1,gnum2); //call the respective motor for action if (BluetoothData==49) //Turn Left {pos1+=2; servo1.write(pos1);} if (BluetoothData==50) //Turn Right {pos1-=2; servo1.write(pos1);} if (BluetoothData==51) //Turn Up {pos2-=2; servo2.write(pos2);} if (BluetoothData==52) //Turn Down {pos2+=2; servo2.write(pos2);} flag=0; BluetoothData=0; } Video microcontroller-projects/arduino-earthquake-detector-alarm-circuit

Earthquake Detector Alarm using Arduino

.

Components Required for Arduino Earthquake Detector Shield

Arduino UNO Accelerometer ADXL335 16x2 LCD Buzzer BC547 transistor 1k Resistors 10K POT LED Power Supply 9v/12v Berg sticks male/female Pin Description of accelerometer: Vcc 5 volt supply should connect at this pin. X-OUT This pin gives an Analog output in x direction Y-OUT This pin give an Analog Output in y direction Z-OUT This pin gives an Analog Output in z direction GND Ground ST This pin used for set sensitivity of sensor Also check our other projects using Accelerometer: Ping Pong Game using Arduino Accelerometer Based Hand Gesture Controlled Robot. Arduino Based Vehicle Accident Alert System using GPS, GSM and Accelerometer

Working Explanation:

by taking the samples of surrounding vibrations whenever Arduino Powers up. Then we need to subtract those sample values from the actual readings to get the real readings. This calibration is needed so that it will not show alerts with respect to its normal surrounding vibrations. After finding real readings, Arduino compares these values with predefined max and min values. If Arduino finds any changes values are more then or less then the predefined values of any axis in both direction (negative and positive) then Arduino trigger the buzzer and shows the status of alert over the 16x2 LCD and a LED also turned on as well. We can adjust the sensitivity of Earthquake detector by changing the Predefined values in Arduino code. are given at the end of the article.

Circuit Explanation:

and calculate and compare values and take appropriate action. Next part is Accelerometer which detects vibration of earth and generates analog voltages in 3 axes (X, Y, and Z). LCD is used for showing X, Y and Z axis’s change in values and also showing alert message over it. This LCD is attached to Arduino in 4-bit mode. RS, GND, and EN pins are directly connected to 9, GND and 8 pins of Arduino and rest of 4 data pins of LCD namely D4, D5, D6 and D7 are directly connected to digital pin 7, 6, 5 and 4 of Arduino. The buzzer is connected to pin 12 of Arduino through an NPN BC547 transistor. A 10k pot is also used for controlling the brightness of the LCD.

Programming Explanation:

to plot the earthquake vibrations over the graph on Computer. We will learn about both the codes one by one: : with respect to its placing surface, so that it will not show alerts with respect to its normal surrounding vibrations. In this calibration, we take some samples and then take an average of them and stores in a variable. for(int i=0;i<samples;i++) // taking samples for calibration { xsample+=analogRead(x); ysample+=analogRead(y); zsample+=analogRead(z); } xsample/=samples; // taking avg for x ysample/=samples; // taking avg for y zsample/=samples; // taking avg for z delay(3000); lcd.clear(); lcd.print("Calibrated"); delay(1000); lcd.clear(); lcd.print("Device Ready"); delay(1000); lcd.clear(); lcd.print(" X Y Z "); Now whenever Accelerometer takes readings, we will subtract those sample values from the readings so that it can ignore surroundings vibrations. int value1=analogRead(x); // reading x out int value2=analogRead(y); //reading y out int value3=analogRead(z); //reading z out int xValue=xsample-value1; // finding change in x int yValue=ysample-value2; // finding change in y int zValue=zsample-value3; // finding change in z /*displying change in x,y and z axis values over lcd*/ lcd.setCursor(0,1); lcd.print(zValue); lcd.setCursor(6,1); lcd.print(yValue); lcd.setCursor(12,1); lcd.print(zValue); delay(100) Then Arduino compares those calibrated (subtracted) values with predefined limits. And take action accordingly. If the values are higher than predefined values then it will beep the buzzer and plot the vibration graph on computer using Processing. /* comparing change with predefined limits*/ if(xValue < minVal || xValue > maxVal || yValue < minVal || yValue > maxVal || zValue < minVal || zValue > maxVal) { if(buz == 0) start=millis(); // timer start buz=1; // buzzer / led flag activated } else if(buz == 1) // buzzer flag activated then alerting earthquake { lcd.setCursor(0,0); lcd.print("Earthquake Alert "); if(millis()>= start+buzTime) buz=0; } Below is the Processing Code attached, you can download the code from below link: We have designed a graph using Processing, for earth quake vibrations, in which we defined the size of the window, units, font size, background, reading and displaying serial ports, open selected serial port etc. // set the window size: and Font size f6 = createFont("Arial",6,true); f8 = createFont("Arial",8,true); f10 = createFont("Arial",10,true); f12 = createFont("Arial",12,true); f24 = createFont("Arial",24,true); size(1200, 700); // List all the available serial ports println(Serial.list()); myPort = new Serial(this, "COM43", 9600); println(myPort); myPort.bufferUntil('\n'); background(80) In below function, we have received data from serial port and extract required data and then mapped it with the size of the graph. // extracting all required values of all three axis: int l1=inString.indexOf("x=")+2; String temp1=inString.substring(l1,l1+3); l1=inString.indexOf("y=")+2; String temp2=inString.substring(l1,l1+3); l1=inString.indexOf("z=")+2; String temp3=inString.substring(l1,l1+3); //mapping x, y and z value with graph dimensions float inByte1 = float(temp1+(char)9); inByte1 = map(inByte1, -80,80, 0, height-80); float inByte2 = float(temp2+(char)9); inByte2 = map(inByte2,-80,80, 0, height-80); float inByte3 = float(temp3+(char)9); inByte3 = map(inByte3,-80,80, 0, height-80); float x=map(xPos,0,1120,40,width-40); After this, we have plotted unit space, max and min limits, values of x, y and z-axis. //ploting graph window, unit strokeWeight(2); stroke(175); Line(0,0,0,100); textFont(f24); fill(0,00,255); textAlign(RIGHT); xmargin("EarthQuake Graph By Circuit Digest",200,100); fill(100); strokeWeight(100); line(1050,80,1200,80); .... .... .......... After this we plot the values over the graph by using 3 different colors as Blue for x-axis value, green color for y axis and z is represented by red color. stroke(0,0,255); if(y1 == 0) y1=height-inByte1-shift; line(x, y1, x+2, height-inByte1-shift) ; y1=height-inByte1-shift; stroke(0,255,0); if(y2 == 0) y2=height-inByte2-shift; line(x, y2, x+2, height-inByte2-shift) ; y2=height-inByte2-shift; stroke(255,0,0); if(y2 == 0) y3=height-inByte3-shift; line(x, y3, x+2, height-inByte3-shift) ; y3=height-inByte3-shift;

Circuit and PCB Design using EasyEDA:

where they have a large stock of electronic components and users can order their required components along with the PCB order. ,check the below link: Below is the Snapshot of Top layer of PCB layout from EasyEDA, you can view any Layer (Top, Bottom, Topsilk, bottomsilk etc) of the PCB by selecting the layer form the ‘LayersᾠWindow. using EasyEDA:

Calculating and Ordering Samples online:

or download Gerber files of your PCB. Here you can select the number of PCBs you want to order, how manycopper layers you need, the PCB thickness, copper weight, and even the PCB color. Afteryou have selected all of theoptions, click “Save to Cartᾠand complete your order. Recently they have dropped their PCB rates significantly and now you can order10 pcs 2-layer PCBwith 10cm x 10cm size just for $2. Here is thePCBsI Got from EasyEDA: : Code #include<LiquidCrystal.h> // lcd Header LiquidCrystal lcd(9,8,7,6,5,4); // pins for LCD Connection #define buzzer 12 // buzzer pin #define led 13 //led pin #define x A0 // x_out pin of Accelerometer #define y A1 // y_out pin of Accelerometer #define z A2 // z_out pin of Accelerometer /*variables*/ int xsample=0; int ysample=0; int zsample=0; long start; int buz=0; /*Macros*/ #define samples 50 #define maxVal 20 // max change limit #define minVal -20 // min change limit #define buzTime 5000 // buzzer on time void setup() { lcd.begin(16,2); //initializing lcd Serial.begin(9600); // initializing serial delay(1000); lcd.print("EarthQuake "); lcd.setCursor(0,1); lcd.print("Detector "); delay(2000); lcd.clear(); lcd.print("Circuit Digest "); lcd.setCursor(0,1); lcd.print("Saddam Khan "); delay(2000); lcd.clear(); lcd.print("Calibrating....."); lcd.setCursor(0,1); lcd.print("Please wait..."); pinMode(buzzer, OUTPUT); pinMode(led, OUTPUT); buz=0; digitalWrite(buzzer, buz); digitalWrite(led, buz); for(int i=0;i<samples;i++) // taking samples for calibration { xsample+=analogRead(x); ysample+=analogRead(y); zsample+=analogRead(z); } xsample/=samples; // taking avg for x ysample/=samples; // taking avg for y zsample/=samples; // taking avg for z delay(3000); lcd.clear(); lcd.print("Calibrated"); delay(1000); lcd.clear(); lcd.print("Device Ready"); delay(1000); lcd.clear(); lcd.print(" X Y Z "); } void loop() { int value1=analogRead(x); // reading x out int value2=analogRead(y); //reading y out int value3=analogRead(z); //reading z out int xValue=xsample-value1; // finding change in x int yValue=ysample-value2; // finding change in y int zValue=zsample-value3; // finding change in z /*displying change in x,y and z axis values over lcd*/ lcd.setCursor(0,1); lcd.print(zValue); lcd.setCursor(6,1); lcd.print(yValue); lcd.setCursor(12,1); lcd.print(zValue); delay(100); /* comparing change with predefined limits*/ if(xValue < minVal || xValue > maxVal || yValue < minVal || yValue > maxVal || zValue < minVal || zValue > maxVal) { if(buz == 0) start=millis(); // timer start buz=1; // buzzer / led flag activated } else if(buz == 1) // buzzer flag activated then alerting earthquake { lcd.setCursor(0,0); lcd.print("Earthquake Alert "); if(millis()>= start+buzTime) buz=0; } else { lcd.clear(); lcd.print(" X Y Z "); } digitalWrite(buzzer, buz); // buzzer on and off command digitalWrite(led, buz); // led on and off command /*sending values to processing for plot over the graph*/ Serial.print("x="); Serial.println(xValue); Serial.print("y="); Serial.println(yValue); Serial.print("z="); Serial.println(zValue); Serial.println(" $"); } Video microcontroller-projects/arduino-timer-tutorial

Arduino Timer Tutorial

The Arduino Development Platform was originally developed in 2005 as an easy-to-use programmable device for art design projects. Its intention was to help non-engineers to work with basic electronics and microcontrollers without much programming knowledge. But then, because of its easy to use nature it was soon adapted by electronics beginners and hobbyists around the world and today it is even preferred for prototype development and POC developments. is very easy to understand as most of the work is done by pre-built functions like digitalWrite(), AnalogWrite(), Delay() etc. while the low level machine language is hidden behind them. The Arduino programs are not similar to other Embedded C coding where we deal with register bits and make them high or low based on the logic of our program. of the ATmega microcontroller. The preloader value of the Timer bit can also be adjusted using pushbuttons to control the duration in which the interrupt occurs.

What is TIMER in Embedded Electronics?

It is like a simple clock which can measure time interval of an event. Every microcontroller has a clock (oscillator), say in Arduino Uno it is 16Mhz. This is responsible for speed. Higher the clock frequency higher will be the processing speed. A timer uses counter which counts at certain speed depending upon the clock frequency. In Arduino Uno it takes 1/16000000 seconds or 62nano seconds to make a single count. Meaning Arduino moves from one instruction to another instruction for every 62 nano second. In Arduino UNO there are three timers used for different functions. It is an 8-Bit timer and used in timer function such as delay(), millis(). It is a 16-Bit timer and used in servo library. It is an 8-Bit Timer and used in tone() function.

Arduino Timer Registers

To change the configuration of the timers, timer registers are used. This register holds the main control bits of the timer and used to control the prescalers of timer. It also allows to control the mode of timer using the WGM bits.
TCCR1A76543210
COM1A1COM1A0COM1B1COM1B0COM1C1COM1C0WGM11WGM10
TCCR1B76543210
ICNC1ICES1-WGM13WGM12CS12CS11CS10
The CS12, CS11, CS10 bits in TCCR1B sets the prescaler value. A prescaler is used to setup the clock speed of the timer. Arduino Uno has prescalers of 1, 8, 64, 256, 1024.
CS12CS11CS10USE
000No Clock Timer STOP
001CLCK i/o /1 No Prescaling
010CLK i/o /8 (From Prescaler)
011CLK i/o /64 (From Prescaler)
100CLK i/o /256 (From Prescaler)
101CLK i/o /1024 (From Prescaler)
110External clock source on T1 Pin. Clock on falling edge
111External Clock source on T1 pin. Clock on rising edge.
This Register is used to control the counter value and to set a preloader value. Formula for preloader value for required time in second: xTime in sec / Prescaler Value) To calculate preloader value for timer1 for time of 2 Sec: x2 / 1024) = 34285

Arduino Timer Interrupts

We previously learned about Arduino Interrupts and have seen that Timer interrupts are kind of software interrupts. There are various timer interrupts in Arduino which are explained below. occurs. So, an ISR interrupt service routine is called when the Timer Overflow Interrupt bit enabled in the TOIEx present in timer interrupt mask register TIMSKx. ISR(TIMERx_OVF_vect) { } Here when the Output Compare Match Interrupt occurs then the interrupt service ISR (TIMERx_COMPy_vect) is called and also OCFxy flag bit will be set in TIFRx register. This ISR is enabled by setting enable bit in OCIExy present in TIMSKx register. Where TIMSKx is Timer Interrupt Mask Register. Next when the timer Input Capture Interrupt occurs then the interrupt service ISR (TIMERx_CAPT_vect) is called and also the ICFx flag bit will be set in TIFRx (Timer Interrupt Flag Register). This ISR is enabled by setting the enable bit in ICIEx present in TIMSKx register.

Components Required

Arduino UNO Push Buttons (2) LED (Any Color) 10k Resistor (2), 2.2k (1) 16x2 LCD Display

Circuit Diagram

VSSGND
VDD+5V
V0To potentiometer centre pin for contrast control of LCD
RS8
RWGND
E9
D410
D511
D612
D713
A+5V
KGND
with pull down resistors of 10K are connected with the Arduino pins 2 & 4 and a LED is connected to PIN 7 of Arduino through a 2.2K resistor.

Programming Arduino UNO Timers

for Arduino Timer is given at the end. Here we are explaining the code line by line: is used in the project to display the preloader value, so liquid crystal library is used. #include<LiquidCrystal.h> #define ledPin 7 Next the object for accessing Liquid Crystal class is declared with the LCD pins (RS, E, D4, D5, D6, D7) that are connected with Arduino UNO. LiquidCrystal lcd(8,9,10,11,12,13); Then set the preloader value 3035 for 4 seconds. Check the formula above to calculate the preloader value. float value = 3035; first set the LCD in 16x2 mode and display a welcome message for few seconds. lcd.begin(16,2); lcd.setCursor(0,0); lcd.print("ARDUINO TIMERS"); delay(2000); lcd.clear(); Next set the LED pin as OUTPUT pin and the Push buttons are set as INPUT pins pinMode(ledPin, OUTPUT); pinMode(2,INPUT); pinMode(4,INPUT); Next disable all the interrupts: noInterrupts(); Next the Timer1 is initialized. TCCR1A = 0; TCCR1B = 0; The preloader timer value is set (Initially as 3035). TCNT1 = value; Then the Pre scaler value 1024 is set in the TCCR1B register. TCCR1B |= (1 << CS10)|(1 << CS12); The Timer overflow interrupt is enabled in the Timer Interrupt Mask register so that the ISR can be used. TIMSK1 |= (1 << TOIE1); At last all interrupts are enabled. interrupts(); The state changes whenever the timer overflow interrupt occurs. ISR(TIMER1_OVF_vect) { TCNT1 = value; digitalWrite(ledPin, digitalRead(ledPin) ^ 1); } the value of preloader is incremented or decremented by using the push button inputs and also the value is displayed on 16x2 LCD. if(digitalRead(2) == HIGH) { value = value+10; //Incement preload value } if(digitalRead(4)== HIGH) { value = value-10; //Decrement preload value } lcd.setCursor(0,0); lcd.print(value); } below where we have demonstrated the change in delay by increasing and decreasing the preloader value using Push buttons. Code #include<LiquidCrystal.h> //LCD display library #define ledPin 7 LiquidCrystal lcd(8,9,10,11,12,13); float value = 3035; //Preload timer value (3035 for 4 seconds) void setup() { lcd.begin(16,2); lcd.setCursor(0,0); lcd.print("ARDUINO TIMERS"); delay(2000); lcd.clear(); pinMode(ledPin, OUTPUT); pinMode(2,INPUT); pinMode(4,INPUT); noInterrupts(); // disable all interrupts TCCR1A = 0; TCCR1B = 0; TCNT1 = value; // preload timer TCCR1B |= (1 << CS10)|(1 << CS12); // 1024 prescaler TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt ISR interrupts(); // enable all interrupts } ISR(TIMER1_OVF_vect) // interrupt service routine for overflow { TCNT1 = value; // preload timer digitalWrite(ledPin, digitalRead(ledPin) ^ 1); //Turns LED ON and OFF } void loop() { if(digitalRead(2) == HIGH) { value = value+10; //Incement preload value } if(digitalRead(4)== HIGH) { value = value-10; //Decrement preload value } lcd.setCursor(0,0); lcd.print(value); } Video microcontroller-projects/arduino-bluetooth-biped-bob-robot

Arduino based Bluetooth Biped Bob (Walking & Dancing Robot)

that takes command from an Android Mobile Phoneto perform some pre-defined actions. You can also use the program (given at the end of the tutorial) to easily manipulate the actions of your very own robot by controlling the position of the servo motors using the Serial monitor. Having a 3d printer will make this project more interesting and look cool. But, if you do not have one you can use any of the online services or just use some cardboard to build the same.

Materials Required:

The following are the materials required for building this robot: Arduino nano Servo SG90 ᾠ4Nos Male berg sticks HC-05/HC-06 Bluetooth module 3D printer requires very minimal electronics parts to build to keep the cost of the project as low as possible. This project is only for conceptual and fun purpose and does not have any real time application so far.

3D printing the required parts:

Load these files on your 3D printing software like Cura and directly print them. I have used a very basic printer of mine to print all the parts. The printer is FABX v1 from 3ding which comes at an affordable pricewith a print volume of 10 cubic cm. The cheap price comes with a trade off with low print resolution and no SD card or print resuming function. I am using software called Cura to print the STL files. The settings that I used to print the materials are given below you can use the same or change them based on your printer. Once you print all the parts clean the supports (if any) and then make sure the holes on the leg and belly part are big enough to fit a screw. If not, use a needle to make the hole lightly bigger. Your 3D printed parts will look like something below.

Hardware and Schematics:

is really simple. The complete schematics is shown in the below image I have used a Perf board to make the above connections. Make sure that your circuit will also fit inside the head of the robot. Once your Perf board is ready it should look something like below.

Assembling the robot:

Once the Hardware and the 3D printed parts are ready we can assemble the robot. Before fixing the motors make sure you place the motors in the below angles so that the program works flawlessly.
Motor NumberMotor placeMotor position
1Left Hip motor110
2Right Hip motor100
4Right Ankle Motor90
5Right Hip motor80
These angles can be set by using the program given at the end of the tutorial. Simply upload the program to your Arduino after making the above connections and type in the following in the serial monitor (Note: Baud rate is 57600). 1, 100, 110 2,90,100 4,80,90 5,70,80 Your Serial monitor should look something like this after placing all your motors in position. Once the motors are set in the corresponding angles mount them as shown in above figure. at the end of this tutorial. Once the Robot is assembled it is time to program our dancing robot

Programming the Arduinofor Biped Robot:

category. I will explain the segments of the same below. The program is capable of controlling the Robots actions through serial monitor or Bluetooth. You can also make your own moves by controlling every individual motor using the serial monitor. servo1.attach(3); servo2.attach(5); servo4.attach(9); servo5.attach(10); The above lines of code it use to mention which servo motor is connected to which pin of the Arduino. Here in our case Servo 1,2,4 and 5 are connected to pins 3,5,9 and 10 respectively. Bot_BT.begin(9600); //start the Bluetooth communication at 9600 baudrate Serial.begin(57600); As said earlier our walking robot can work on Bluetooth commands and also from commands from the serial monitor. Hence the Bluetooth serial communication works with a Baud Rate of 9600 and the serial communication works with Baud Rate of 57600. The name of our Bluetooth object here is “Bot_BTᾮ switch (motor) { case 1: // For motor one { Serial.println("Executing motor one"); if(num1<num2) // Clock wise rotation { for ( pos =num1; pos<=num2; pos+=1) { servo1.write(pos); delay( 20); }} if(num1>num2) // Anti-Clock wise rotation { for ( pos =num1; pos>=num2; pos-=1) { servo1.write(pos); delay( 20); }} break; } ////////JUST DUPLICATE FOR OTHER SERVOS//// case 2: // For motor 2 { Serial.println("Executing motor two"); if(num1<num2) { for ( pos =num1; pos<=num2; pos+=1) { servo2.write(pos); delay( 20); }} if(num1>num2) { for ( pos =num1; pos>=num2; pos-=1) { servo2.write(pos); delay( 20); }} break; } case 4: // for motor four { Serial.println("Executing motor four"); if(num1<num2) { for ( pos =num1; pos<=num2; pos+=1) { servo4.write(pos); delay (20); }} if(num1>num2) { for ( pos =num1; pos>=num2; pos-=1) { servo4.write(pos); delay (20); }} break; } case 5: // for motor five { Serial.println("Executing motor five"); { for ( pos =num1; pos<=num2; pos+=1) if(num1<num2) { servo5.write(pos); delay (20); }} if(num1>num2) { for ( pos =num1; pos>=num2; pos-=1) { servo5.write(pos); delay (20); }} break; } The switch case shown above is used to control the servo motors individually. This will help in making your own creative moves with your robot. With this segment of code you can simply tell the motor number, from angle and to angle to make a particular motor move to a desired location. For example if we want to move the motor number 1 which is the left hip motor from its default location of 110 degree to 60 degree. We can simply write ᾱ,110,60ᾠin the serial monitor of Arduino and hit enter. This will come in handy to make your own complex moves with your Robot. Once you experiment with all the from angel and to angle you can then make your own moves and repeat them by making it as a function. if(Serial.available()>0) //Read whats coming in through Serial { gmotor= Serial.parseInt(); Serial.print(" selected Number-> "); Serial.print(gmotor); Serial.print(" , "); gnum1= Serial.parseInt(); Serial.print(gnum1); Serial.print(" degree , "); gnum2= Serial.parseInt(); Serial.print(gnum2); Serial.println(" degree "); flag=1; } If a Serial data is available the number before the first ᾬᾠis considered as gmotor and then the number before the second ᾬᾠis considered as gnum1 and the number after the second ᾬᾠis considered as gnum2. if (Bot_BT.available()) //Read whats coming in through Bluetooth { BluetoothData=Bot_BT.read(); Serial.print("Incoming from BT:"); Serial.println(BluetoothData); } If the Bluetooth receives some information, the received information is stored in the variable “BluetoothDataᾮ This variable is then compared to the pre-defined values to execute a particular action. if (flag ==1 ) call(gmotor,gnum1,gnum2); //call the respective motor for action //Execute the functions as per the commond received through the Serial monitor or Bluetooth// if (gmotor ==10) left_leg_up(); if (gmotor ==11) right_leg_up(); if (gmotor ==12) move_left_front(); if (gmotor ==13) move_right_front(); if (BluetoothData ==49 || gmotor ==49) say_hi(); if (BluetoothData ==50 || gmotor ==50) walk1(); if (BluetoothData ==51 || gmotor ==51) walk2(); if (BluetoothData ==52 || gmotor ==52) dance1(); if (BluetoothData ==53 || gmotor ==53) dance2(); if (BluetoothData ==54 || gmotor ==54) {test();test();test();} This is where the functions are called based on the values received from the serial monitor or the Bluetooth. As shown above the variable gmotor will have the value of serial monitor and BluetoothData will have the value from Bluetooth device. The numbers 10,11,12 upto 53,54 are pre-defined numbers. For example if you enter the number 49 in the serial monitor. The say_hi() function will be executed where the robot will wave you a hi. All the functions are defined inside the page “Bot_Functionsᾮ You can open it and see what actually happens inside each function. All these functions were created by experimenting th e from angel and to angel of every motor using the switch case explained above. If you have any doubt you can use the comment section to post them and I will be happy to help you out.

Processing based Android Application:

and directly install it on your mobile phone. Note: Your Bluetooth module should be named HC-06 else the application will not be able to connect to your Bluetooth Module. Once the application is installed, you can pair the Bluetooth module with your Phone and then launch the application. It should look something like this below. If you want to make your app more attractive or connect to any other device other than Hc-06. You can use the processing code and make some changes to it and then upload the code directly to your phone.

Working of Bluetooth Controlled Biped Robot:

Once your Hardware, Android Application and Arduino Sketch is ready it is time to have some fun with our robot. You can control the Robot from Bluetooth Application by using the buttons in the application or directly from Serial monitor by using as of the following commands as shown in the image below. Each command will make the robot perform some peculiar tasks and you can also add on more actions based on your creativity. The Robot can also be powered by a 12V adapter or can also be powered by using a 9V battery. This battery can be easily positioned below the Perf board and can also be covered with the Head of the Robot. can be found in the Video below. Code /*Arduino Code for Walking and Dancing Robot * Coded by Circuitdigest.com * On 25-05-2017 */ /*CONNECTION DETIALS * Arduino D11 -> RX of BT Module * Arduino D12 -> Tx of BT * Arduino D2 -> Hall sensor 3rd pin * Servo1 -> pin 3 of arduino Nano * Servo2 -> pin 5 of arduino Nano * Servo4 -> pin 9 of arduino Nano * Servo5 -> pin 10 of arduino Nano */ #include <Servo.h> //header to srive servo motors #include <SoftwareSerial.h>// import the serial library SoftwareSerial Bot_BT(12, 11); // RX, TX int ledpin=13; // led on D13 will show blink on / off int BluetoothData; // the data given from Computer //lets declare the servo objects Servo servo1; Servo servo2; Servo servo3; Servo servo4; Servo servo5; //End of declaration long gmotor,gnum1,gnum2; int pos,pos2; int flag=0; int poss1,poss2,poss3,poss4; void setup() { servo1.attach(3); servo2.attach(5);; servo4.attach(9); servo5.attach(10); //**Initial position of all four servo motors**// servo1.write(110); servo2.write(100); servo4.write(90); servo5.write(80); //**inititialised**// Bot_BT.begin(9600); //start the Bluetooth communication at 9600 baudrate Bot_BT.println("Blue Bob is ready to take actions"); Serial.begin(57600); Serial.println("Biped Servo programming by CircuitDigest.com"); Serial.println("Enter any of the following commands for theier respective actions"); Serial.println("1. Servomotor Number, From angle, To angle -> To control one particular Servo"); Serial.println(" Servomotor Number -> 1,2,4,5"); Serial.println(" From angle -> 0 to 180"); Serial.println(" To angle -> 0 to 180"); Serial.println("2. Servomotor Number, From angle, To angle -> To control one particular Servo"); Serial.println("3. Enter 10 -> To lift left leg up"); Serial.println("4. Enter 11 -> To lift right leg up"); Serial.println("5. Enter 12 -> To move left leg front"); Serial.println("6. Enter 13 -> To move right leg front"); Serial.println("7. Enter 49 -> To say Hi ;-)"); Serial.println("8. Enter 50 -> To Walk with style 1"); Serial.println("9. Enter 51 -> To Walk with style 2"); Serial.println("10. Enter 52 -> To Dance with style 1"); Serial.println("11. Enter 53 -> To Dance with style 2"); Serial.println("12. Enter 54 -> To Say Bye!!"); } //***Function for each Servo actions**// void call(int motor, int num1, int num2) // The values like Motor number , from angle and to angle are received { Serial.println("Passing values..."); flag =0; switch (motor) { case 1: // For motor one { Serial.println("Executing motor one"); if(num1<num2) // Clock wise rotation { for ( pos =num1; pos<=num2; pos+=1) { servo1.write(pos); delay( 20); }} if(num1>num2) // Anti-Clock wise rotation { for ( pos =num1; pos>=num2; pos-=1) { servo1.write(pos); delay( 20); }} break; } ////////JUST DUPLICATE FOR OTHER SERVOS//// case 2: // For motor 2 { Serial.println("Executing motor two"); if(num1<num2) { for ( pos =num1; pos<=num2; pos+=1) { servo2.write(pos); delay( 20); }} if(num1>num2) { for ( pos =num1; pos>=num2; pos-=1) { servo2.write(pos); delay( 20); }} break; } case 4: // for motor four { Serial.println("Executing motor four"); if(num1<num2) { for ( pos =num1; pos<=num2; pos+=1) { servo4.write(pos); delay (20); }} if(num1>num2) { for ( pos =num1; pos>=num2; pos-=1) { servo4.write(pos); delay (20); }} break; } case 5: // for motor five { Serial.println("Executing motor five"); { for ( pos =num1; pos<=num2; pos+=1) if(num1<num2) { servo5.write(pos); delay (20); }} if(num1>num2) { for ( pos =num1; pos>=num2; pos-=1) { servo5.write(pos); delay (20); }} break; } } } void loop() { if(Serial.available()>0) //Read whats coming in through Serial { gmotor= Serial.parseInt(); Serial.print(" selected Number-> "); Serial.print(gmotor); Serial.print(" , "); gnum1= Serial.parseInt(); Serial.print(gnum1); Serial.print(" degree , "); gnum2= Serial.parseInt(); Serial.print(gnum2); Serial.println(" degree "); flag=1; } if (Bot_BT.available()) //Read whats coming in through Bluetooth { BluetoothData=Bot_BT.read(); Serial.print("Incoming from BT:"); Serial.println(BluetoothData); } if (flag ==1 ) call(gmotor,gnum1,gnum2); //call the respective motor for action //Execute the functions as per the commond received through the Serial monitor or Bluetooth// if (gmotor ==10) left_leg_up(); if (gmotor ==11) right_leg_up(); if (gmotor ==12) move_left_front(); if (gmotor ==13) move_right_front(); if (BluetoothData ==49 || gmotor ==49) say_hi(); if (BluetoothData ==50 || gmotor ==50) walk1(); if (BluetoothData ==51 || gmotor ==51) walk2(); if (BluetoothData ==52 || gmotor ==52) dance1(); if (BluetoothData ==53 || gmotor ==53) dance2(); if (BluetoothData ==54 || gmotor ==54) {test();test();test();} //End of executions// gmotor=0; //To prevet repetetion BluetoothData = 0; //To prevet repetetion //stay_put(); //bring the Bot to initial posotion if required } /*---------------------------------------------------------------------------*/ //***Function to lift the left leg**// void stay_put() { servo5.attach(10); servo1.write(110); servo2.write(100); servo4.write(90); servo5.write(80); delay(20); } //**_____End of Function______**// //***Function to lift the left lef**// void left_leg_up() { Serial.println("left leg up"); poss1 = 80; poss2 = 110; do{ servo5.write(poss1); servo4.write(poss2); poss1++; poss2++; delay(20); }while(poss1 <100 || poss2<140); call(4,130,100); } //**_____End of Function______**// //***Function to lift the left lef**// void right_leg_up() { Serial.println("right leg up"); poss1 = 80; poss2 = 100; do{ servo4.write(poss2); servo5.write(poss1); poss1--; poss2--; delay(20); }while(poss1 >50 || poss2>60); call(5,50,80); } //**_____End of Function______**// //***Function to lift the left lef**// void move_left_front() { Serial.println("moving left front"); poss1=120;poss2=110;poss3=110; do{ servo2.write(poss1); servo1.write(poss2); servo5.write(poss3); poss1--; poss2--; poss3--; delay(20); }while(poss1 >100 || poss2>80 || poss3>80 ); } //**_____End of Function______**// //***Function to lift the left lef**// void move_right_front() { poss1=80;poss2=100;poss3=60; do{ servo1.write(poss1); servo2.write(poss2); servo4.write(poss3); poss1++; poss2++; poss3++; delay(20); }while(poss1 <110 || poss2<120 || poss3<90); } //**_____End of Function______**// //***Function to lift the left lef**// void say_hi() { stay_put(); right_leg_up(); call(5,80,50); //wave up call(5,50,80); //wave down call(5,80,50); //wave up call(5,50,80); //wave down stay_put(); } //**_____End of Function______**// //***Function to lift the left lef**// void walk1() { stay_put(); char temp=10; //number of steps to make * 2 do{ right_leg_up(); move_right_front(); left_leg_up(); move_left_front(); temp--; }while(temp>0); } //**_____End of Function______**// //***Function to lift the left lef**// void walk2() { stay_put(); char temp=10; //number of steps to make * 2 do{ move_right_front(); move_left_front(); temp--; }while(temp>0); } //**_____End of Function______**// //***Function to lift the left lef**// void dance1() { stay_put(); char temp=3; //number of steps to make * 2 do{ poss1 = 80; poss2 = 60; do{ servo1.write(poss1); servo2.write(poss2); poss1++; poss2++; delay(20); }while(poss1 <140 || poss2<120); poss1 = 140; poss2 = 120; do{ servo1.write(poss1); servo2.write(poss2); poss1--; poss2--; delay(20); }while(poss1 >80 || poss2>60); temp--; }while(temp>0); stay_put(); } //**_____End of Function______**// //***Function to lift the left lef**// void dance2() { stay_put(); char temp=3; //number of steps to make * 2 do{ right_leg_up(); right_leg_up(); stay_put(); left_leg_up();left_leg_up(); stay_put(); temp--; }while(temp>0); stay_put(); } //**_____End of Function______**// //***Function to lift the left lef**// void test() { poss1 = 40; poss2 = 130; do{ servo5.write(poss1); servo4.write(poss2); poss1++; poss2--; delay(5); }while(poss1 <120 || poss2>50); poss1 = 120; poss2 = 50; do{ servo5.write(poss1); servo4.write(poss2); poss1--; poss2++; delay(5); }while(poss1 >40 || poss2<130); } //**_____End of Function______**// Video microcontroller-projects/virtual-reality-using-arduino

Virtual Reality using Arduino and Processing

This is a very interesting project in which we are going to learn how to implement virtual reality using Arduino and Processing. For most of us, the movie Iron man by Jon Favreau has always been an inspiration to build new things that will make our life easy and more fun. I have personally admired the Techs that are shown in the movie and have always wanted to build something similar to that. So, in this project I have tried to mimic the Virtual reality stuffs that happen in the movie, like we can simply wave our hand in front of the computer and move the pointer to the desired location and perform some tasks. I will also show you how you can toggle lights by virtually moving your hand and making clicks with your fingers in the air.

Concept:

, but Processing might be new for you. Processing is an application just like Arduino and it is also Open source and free to download. Using Processing you can create simple system applications, Android applications and much more. It also has the ability to do Image Processing and Voice recognition. It is just like Arduino and is much easy to learn, but do not worry if you are completely new to processing because I have written this tutorial fairly simple so that anyone with interest can make this working in no time. In this tutorial we are using Processing to create a simple System application which provides us an UI and track the position of our hand using Image processing. Now, we have to make left click and right click using our fingers. To make that happen I have used two hall sensors (one on my index finger and the other on middle finger) which will be read by the Arduino Nano. The Arduino also transmits the click status to the Computer wirelessly via Bluetooth. It might sound complicated but, Trust me; it is not as hard as it sounds. So let us take a look at the materials needed for this project to be up and running.

Materials Required:

Arduino Nano Hall sensor (A3144) ᾠ2Nos A small piece of magnet Bluetooth Module (HC-05/HC-06) 9V battery Connecting Wires Dot board. A pair of gloves Arduino IDE (Software) Processing IDE(Software) A Computer with Webcam and Bluetooth (you can also use external Bluetooth or Webcam for your computer)

Schematics and Hardware:

The hardware part of this project is very simple and easy to build. The complete schematic is shown below. The Arduino, resistors and the berg stick pins are soldered onto a dot board as shown below. The hall sensor and the Bluetooth module is soldered to a connector wire as shown below. Once these two sections are ready it can be assembled onto gloves so that it is easy to use. I have used disposable plastic gloves which can be purchased from any medical shop near you. You should make sure that the magnet comes on your thumb finger and the hall sensor 1 and hall sensor 2 should be present before your index and middle finger respectively. I have used duck tapes to secure the components in place. Once the components are assembled it should look something like this. Now let us open the Arduino IDE and start programming.

Program for Arduino:

The purpose of this Arduino code is it to read the status of the hall sensor and broadcast them using the Bluetooth module. It should also receive data from Bluetooth and toggle the onboard LED based on the incoming value. The complete program is given at the end of this tutorial; I have also explained few lines below. if (Phs1!=HallState_1 || Phs2!=HallState_2) //Check if new keys are pressed { if (HallState_1==LOW && HallState_2==LOW) Aisha.write(1); if (HallState_1==HIGH && HallState_2==LOW) Aisha.write(2); if (HallState_1==LOW && HallState_2==HIGH) Aisha.write(3); if (HallState_1==HIGH && HallState_2==HIGH) Aisha.write(4); } As shown in the above lines based on the status of the hall sensor the Bluetooth will write a particular value. For example if hall sensor 1 is high and hall sensor 2 is low, then we will broadcast the vale ᾲᾠvia the Bluetooth module. Make sure you write the values to the BT module and not print them. Because it will be easy to read the only on Processing side only if they are written. Also the value will only send if it is not as same as the previous value. if (BluetoothData=='y') digitalWrite(ledpin,HIGH); if (BluetoothData=='n') digitalWrite(ledpin,LOW); These lines are used to toggle the onboard LED which is connected to the Pin 13, based on the value receive by the BT module. For example if the module receives a ‘yᾠthen the LED is turned on and if it receives an ‘nᾠthen it is turned off.

Program for processing:

The purpose of the Processing program is to create a system application which can act as an UI (User interface) and also perform image processing to track a particular object. In this case we track the blue object that we stuck to our gloves above. The program basically has four screens. Calibration Screen Main Screen Paint Screen LED toggle Screen We can navigate from one screen to another by simply waving our hands and dragging screens on air. We can also make clicks on desired places to toggle LED or even draw something on screen. , and follow the following steps to launch the application. Install JAVA in your computer if you have not installed it before Install You Cam perfect on your computer Power up your Arduino and pair your Computer with the Bluetooth Module Launch the application file If everything goes fine you should be able to notice the LED on your Bluetooth module getting stable and your webcam light going ON. If you have any problems reach me through the comment section and I will help you out. Watch the video at the end to know how to calibrate your application and use it. If you want to modify the code and build more features into this then you can use the following insights of the program Processing has the ability to read Serial data, in this program the serial data is comes from the Bluetooth COM port. You have to select which COM port your Bluetooth is connect to by using this line below port = new Serial(this,Serial.list()[1],9600); COM port which is COM5 in my case (see image below) and I have mentioned that by Bluetooth module runs on 9600 baudrate. tutorial. If you want to know more about the sketch you can reach me through the comment section and I will help you out.

Working:

and then launch the Application. The led on the Bluetooth module should go stable. Now it means that your System application has established a Bluetooth link with your Arduino. You will get the following screen where you have to select the object to be tracked. This tracing can be simply done by clicking on the object. In this case the object is the Blue disc. Now you can move your object and notice that the pointer follows your object. Use a unique colour object and a bright room for best results. Now touch your thumb finger with index finger and you should see the message “Key 1 Pressedᾠand the when you press your thumb with middle finger you should see “Key 2 Pressedᾠthis indicates that everything works fine and the calibration is over. Now click on the Done button. Once the Done button is pressed you will be directed to the main screen where you can paint on air or toggle the LED on the Arduino Board as shown in the Video below. Code #include <SoftwareSerial.h>// import the serial library SoftwareSerial Aisha(11, 12); // TX, RX int ledpin=13; // led on D13 will show blink on / off int hall_1=9; int hall_2=10; int BluetoothData; // the data given from Computer int HallState_1,HallState_2; int change; int Phs1,Phs2; void setup() { Aisha.begin(9600); //Bluetooth Module works at 9600 baudrate pinMode(ledpin,OUTPUT); //led pin as output pinMode(hall_1,INPUT); //hall sensor 1 as input pinMode(hall_2,INPUT); //hall snesor 2 is also input } void loop() { if (Aisha.available()) //if data is sent from laptop BluetoothData=Aisha.read(); //read it and store it in BluetoothData Phs1=HallState_1; Phs2=HallState_2; HallState_1 = digitalRead(hall_1); HallState_2 = digitalRead(hall_2); if (Phs1!=HallState_1 || Phs2!=HallState_2) //Check if new keys are pressed { if (HallState_1==LOW && HallState_2==LOW) Aisha.write(1); if (HallState_1==HIGH && HallState_2==LOW) Aisha.write(2); if (HallState_1==LOW && HallState_2==HIGH) Aisha.write(3); if (HallState_1==HIGH && HallState_2==HIGH) Aisha.write(4); } if (BluetoothData=='y') digitalWrite(ledpin,HIGH); if (BluetoothData=='n') digitalWrite(ledpin,LOW); } //----------- Arduino code ends---------------// //------------Processing code starts-----------// import processing.video.*; // Import Librarey to use video import processing.serial.*; //Import Librarey to use Serial Port (Bluetooth) //**Global Variable Declarations**// Serial port; //port is an object variable for Serial communication int data; boolean calibration= false; int mirror =0; int mirrorn =-1; PImage Done,Aisha,Paint,LED_Toggle,LED_on,LED_off; boolean key1,key2,key3,movePaint,PaintScreen,PaintScreenClear,moveLED,LEDscreen; float Paintx,Painty,avgX,avgY,LEDx,LEDy; int count; PImage img = createImage(380, 290, RGB); int Px,Py; Capture video; //create an object named video color trackColor; //variable to store the color that we are going to track float threshold = 50 ; //can be varied by the user //_____End of variable declaration______// //*Function to load all the images from data folder of the sketch*// void loadImages() { Done = loadImage("Done.png"); Aisha = loadImage ("Aisha.png"); Paint = loadImage("Paint.png"); LED_Toggle = loadImage("LED_Toggle.png"); LED_on = loadImage("LED_on.png"); LED_off = loadImage ("LED_off.png"); } //_____End of variable declaration______// //**Executes only ones**// void setup() { size(800, 600); loadImages(); String[] cameras = Capture.list(); printArray(cameras); video = new Capture(this, cameras[34]); video.start(); key1=key2=key3=false; Paintx=width/10; Painty=height/8.5; LEDx=width/1.1; LEDy=height/8.5; movePaint=PaintScreen=PaintScreenClear=moveLED=LEDscreen=false; port = new Serial(this,Serial.list()[1],9600); println(Serial.list()); } //**End of Setup**// //**Triggered to update each frame of the video**// void captureEvent(Capture video) //when a new image comes in { video.read(); } //reas it as a video //*Function to point which color to Track*// void Calibrate() { image(video,0,0); imageMode(CORNERS); image(Done,width/1.2,height/1.1,width,height); //position of the Done button if (mouseX>width/1.2 && mouseY>height/1.1) //If mouse is within the Done button { calibration=true; cursor(HAND); mirrorn=1; mirror=width; } fill(#1B96E0); textSize(20); if (key1==true) //if hall sensor 1 is active on Arduino text("Key-1 Pressed",width/12,height/1.05); //Text and its position if (key2==true) //if hall sensor 2 is active on Arduino text("Key-2 Pressed",width/12,height/1.05); //Text and its position } //_____End of Calibration______// //*Function to represent the main Screen*// void UI() { imageMode(CORNERS); image(Aisha,0,0,width,height); imageMode(CENTER); if ((avgX<(width/10+((width/4)/2)) && avgY<(height/8.5+((height/4)/2)) && key1==true) || (movePaint==true&&key1==true)) //if clicked inside the image { movePaint=true; image (Paint, avgX,avgY,width/4, height/4); //Drag the image } else if (movePaint==false) image (Paint, Paintx,Painty,width/4, height/4); //place the image at corner else PaintScreen=true; if ((avgX>(width/1.1-((width/4)/2)) && avgY<(height/8.5+((height/4)/2)) && key1==true) || (moveLED==true&&key1==true)) //if clicked inside the image { moveLED=true; image (LED_Toggle, avgX,avgY,width/4, height/4); //Drag the image } else if (moveLED==false) image (LED_Toggle, LEDx,LEDy,width/4, height/4); //place the image at corner else LEDscreen=true; } //_____End of main screen function______// //*Function to represent the Paint Screen*// void Paintfun() { imageMode(CENTER); background(#0B196A); image (Paint, width/2,height/2,width/1.5, height); img.loadPixels(); for (int IX = 210, Px=0; IX<=590; IX++, Px++) { for (int IY = 85, Py=0; IY<=375; IY++, Py++) { if ((dist(avgX,avgY,IX,IY)<4) && key1==true) img.pixels[(Px+(Py*img.width))] = color(255); //color of the paint background updated if (key2==true) PaintScreen = false; } } img.updatePixels(); image(img, width/2, height/2.6); } //_____End of main Paintscreen function______// //*Function to display Toggle LED screen*// void LEDfun() { imageMode(CENTER); background(255); image(LED_on,(width/2 - width/4), height/3,width/4, height/5); image(LED_off,(width/2 + width/4), height/3,width/4, height/5); textSize(50); textAlign(CENTER); if (key1==true && avgX<300 && avgY>150 && avgX>95 && avgY<260) { fill(#751EE8); text("LED turned on",width/2,height/1.5); port.write(121); } if (key1==true && avgX<700 && avgY>150 && avgX>500 && avgY<260) { fill(#FC0808); text("LED turned off",width/2,height/1.5); port.write(110); } } //_____End of main LEDscreen function_____// //*Function to know which key is pressed*// void key_select() { switch(data){ case 1: key1=true; key2=true; break; case 2: key1=false; key2=true; break; case 3: key1=true; key2=false; break; case 4: key1=false; key2=false; break; } } //_____End of function______// void draw() { if (port.available()>0) //if there is an incoming BT value { data=port.read(); //read the BT incoming value and save in data println(key1,key2,data); //print for debugging key_select(); //toggle the variable key 1 and key2 } video.loadPixels(); if (calibration==false) //no calibration done Calibrate(); //Calibrate Screen if (calibration==true && (PaintScreen==false || LEDscreen==false) ) UI(); //Main Screen if (PaintScreen==true && calibration ==true) Paintfun(); //Paint Screen if (LEDscreen==true && calibration ==true) LEDfun(); //LED toffle screen if (key2==true) movePaint=PaintScreen=PaintScreenClear=moveLED=LEDscreen=false; //go back to main screen avgX = avgY = count = 0; // Begin loop to walk through every pixel for (int x = 0; x < video.width; x++ ) { for (int y = 0; y < video.height; y++ ) { int loc = x + y * video.width; // What is current color color currentColor = video.pixels[loc]; float r1 = red(currentColor); float g1 = green(currentColor); float b1 = blue(currentColor); float r2 = red(trackColor); float g2 = green(trackColor); float b2 = blue(trackColor); float d = distSq(r1, g1, b1, r2, g2, b2); if (d < threshold*threshold) { stroke(255); strokeWeight(1); // point((mirror-x)*mirrorn, y); avgX += x; avgY += y; count++; } } } if (count > 0) { avgX = avgX / count; avgY = avgY / count; // Draw a circle at the tracked pixel fill(#21FADB); avgX = (mirror-avgX)*mirrorn; ellipse(avgX, avgY, 15, 15); } } float distSq(float x1, float y1, float z1, float x2, float y2, float z2) { float d = (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) +(z2-z1)*(z2-z1); return d; } void mousePressed() { if(calibration==false) { int loc = mouseX + mouseY*video.width; trackColor = video.pixels[loc]; //load the color to be tracked } } Video microcontroller-projects/arduino-based-accident-alert-system-using-gps-gsm-accelerometer

Arduino Based Vehicle Accident Alert System using GPS, GSM and Accelerometer

at the end. ThisVehicle Accident alert project can also be used as a Tracking System and much more, by just making few changes in hardware and software.

Components Required:

Arduino Uno GSM Module (SIM900A) GPS Module (SIM28ML) Accelerometer (ADXL335) 16x2 LCD Power Supply Connecting Wires 10 K-POT Breadboard or PCB Power supply 12v 1amp Before going into Project, we will discuss about GPS, GSM and Accelerometer.

GPS Module and Its Working:

to find the Latitude and Longitude Coordinates. We can extract coordinate from $GPGGA string by counting the commas in the string. Suppose you find $GPGGA string and stores it in an array, then Latitude can be found after two commas and Longitude can be found after four commas. Now, this latitude and longitude can be put in other arrays. String, along with its description: $GPGGA,104534.000,7791.0381,N,06727.4434,E,1,08,0.9,510.4,M,43.9,M,,*47 $GPGGA,HHMMSS.SSS,latitude,N,longitude,E,FQ,NOS,HDP,altitude,M,height,M,,checksum data
$GPGGAGlobal Positioning system fix data
HHMMSS.SSSTime in hour minute seconds and milliseconds format.
LatitudeLatitude (Coordinate)
NDirection N=North, S=South
LongitudeLongitude(Coordinate)
EDirection E= East, W=West
FQFix Quality Data
NOSNo. of Satellites being Used
HDPHorizontal Dilution of Precision
AltitudeAltitude (meters above from sea level)
MMeter
HeightHeight
ChecksumChecksum Data

GSM Module:

The SIM900 is a complete Quad-band GSM/GPRS Module which can be embedded easily used by customer or hobbyist. SIM900 GSM Module provides an industry-standard interface. SIM900 delivers GSM/GPRS 850/900/1800/1900MHz performance for voice, SMS, Data with low power consumption. It is easily available in the market. SIM900 designed by using single-chip processor integrating AMR926EJ-S core Quad - band GSM/GPRS module in small size. GPRS Enabled we used here in this project: ATE0 For echo off AT+CNMI=2,2,0,0,0 <ENTER> Auto opened message Receiving. (No need to open message) ATD<Mobile Number>; <ENTER> making a call (ATD+919610126059;\r\n) AT+CMGF=1 <ENTER> Selecting Text mode AT+CMGS=”Mobile Number” <ENTER> Assigning recipient’s mobile number >>Now we can write our message >>After writing message Ctrl+Z send message command (26 in decimal). ENTER=0x0d in HEX )

Accelerometer:

Pin Description of accelerometer: Vcc 5 volt supply should connect at this pin. X-OUT This pin gives an Analog output in x direction Y-OUT This pin give an Analog Output in y direction Z-OUT This pin gives an Analog Output in z direction GND Ground ST This pin used for set sensitivity of sensor

Circuit Explanation:

here, we have allowed serial communication on pin 10 and 11, and made them Rx and Tx respectively and left the Rx pin of GPS Module open. By default Pin 0 and 1 of Arduino are used for serial communication but by using the SoftwareSeriallibrary, we can allow serial communication on other digital pins of the Arduino. 12 Volt supply is used to power the GPS Module. data pins D4, D5, D6, and D7 are connected to pin number 6, 7, 8, and 9of Arduino. Command pin RS and EN of LCD are connected with pin number 4 and 5 of Arduino and RW pin is directly connected with ground. A Potentiometer is also used for setting contrast or brightness of LCD. is added in this system for detecting an accident and its x,y, and z-axis ADC output pins are directly connected to Arduino ADC pin A1, A2, and A3.

Working Explanation:

below the Project. by putting min and max value in the code. Here in the demo have used given values: #define minVal -50 #define MaxVal 50 But for better results you can use 200 in place of 50, or can set according to your requirement.

Programming Explanation:

Complete Program has been given below in Code section; here we are explaining its various functions in brief. First we have included all the required libraries or headers files and declared various variables for calculations and storing data temporary. to initialize the GSM module and checking its response using AT commands. void initModule(String cmd, char *res, int t) { while(1) { Serial.println(cmd); Serial1.println(cmd); delay(100); while(Serial1.available()>0) { if(Serial1.find(res)) { Serial.println(res); delay(t); return; } else { Serial.println("Error"); } } delay(t); } } function, we have initialized hardware and software serial communication, LCD, GPS, GSM module and accelerometer. void setup() { Serial1.begin(9600); Serial.begin(9600); lcd.begin(16,2); lcd.print("Accident Alert "); lcd.setCursor(0,1); lcd.print(" System "); delay(2000); lcd.clear(); .... ...... ...... ..... loop. In this, we have taken some samples and then find the average values for the x-axis, y-axis, and z-axis. And store them in a variable. Then we have used these sample values to read changes in accelerometer axis when vehicle gets tilt (accident). lcd.print("Callibrating "); lcd.setCursor(0,1); lcd.print("Acceleromiter"); for(int i=0;i<samples;i++) { xsample+=analogRead(x); ysample+=analogRead(y); zsample+=analogRead(z); } xsample/=samples; ysample/=samples; zsample/=samples; Serial.println(xsample); Serial.println(ysample); Serial.println(zsample); function, we have read accelerometer axis values and done a calculation to extract changes with the help of samples that are taken in Calibration. Now if any changes are more or less then defined level then Arduino sends a message to the predefined number. void loop() { int value1=analogRead(x); int value2=analogRead(y); int value3=analogRead(z); int xValue=xsample-value1; int yValue=ysample-value2; int zValue=zsample-value3; Serial.print("x="); Serial.println(xValue); Serial.print("y="); Serial.println(yValue); Serial.print("z="); Serial.println(zValue); ..... ..... ........ ... for sending alert SMS to the predefined number. is given below, you can check all the functions in the code. Code #include<SoftwareSerial.h> SoftwareSerial Serial1(2,3); //make RX arduino line is pin 2, make TX arduino line is pin 3. SoftwareSerial gps(10,11); #include<LiquidCrystal.h> LiquidCrystal lcd(4,5,6,7,8,9); #define x A1 #define y A2 #define z A3 int xsample=0; int ysample=0; int zsample=0; #define samples 10 #define minVal -50 #define MaxVal 50 int i=0,k=0; int gps_status=0; float latitude=0; float logitude=0; String Speed=""; String gpsString=""; char *test="$GPRMC"; void initModule(String cmd, char *res, int t) { while(1) { Serial.println(cmd); Serial1.println(cmd); delay(100); while(Serial1.available()>0) { if(Serial1.find(res)) { Serial.println(res); delay(t); return; } else { Serial.println("Error"); } } delay(t); } } void setup() { Serial1.begin(9600); Serial.begin(9600); lcd.begin(16,2); lcd.print("Accident Alert "); lcd.setCursor(0,1); lcd.print(" System "); delay(2000); lcd.clear(); lcd.print("Initializing"); lcd.setCursor(0,1); lcd.print("Please Wait..."); delay(1000); Serial.println("Initializing...."); initModule("AT","OK",1000); initModule("ATE1","OK",1000); initModule("AT+CPIN?","READY",1000); initModule("AT+CMGF=1","OK",1000); initModule("AT+CNMI=2,2,0,0,0","OK",1000); Serial.println("Initialized Successfully"); lcd.clear(); lcd.print("Initialized"); lcd.setCursor(0,1); lcd.print("Successfully"); delay(2000); lcd.clear(); lcd.print("Callibrating "); lcd.setCursor(0,1); lcd.print("Acceleromiter"); for(int i=0;i<samples;i++) { xsample+=analogRead(x); ysample+=analogRead(y); zsample+=analogRead(z); } xsample/=samples; ysample/=samples; zsample/=samples; Serial.println(xsample); Serial.println(ysample); Serial.println(zsample); delay(1000); lcd.clear(); lcd.print("Waiting For GPS"); lcd.setCursor(0,1); lcd.print(" Signal "); delay(2000); gps.begin(9600); get_gps(); show_coordinate(); delay(2000); lcd.clear(); lcd.print("GPS is Ready"); delay(1000); lcd.clear(); lcd.print("System Ready"); Serial.println("System Ready.."); } void loop() { int value1=analogRead(x); int value2=analogRead(y); int value3=analogRead(z); int xValue=xsample-value1; int yValue=ysample-value2; int zValue=zsample-value3; Serial.print("x="); Serial.println(xValue); Serial.print("y="); Serial.println(yValue); Serial.print("z="); Serial.println(zValue); if(xValue < minVal || xValue > MaxVal || yValue < minVal || yValue > MaxVal || zValue < minVal || zValue > MaxVal) { get_gps(); show_coordinate(); lcd.clear(); lcd.print("Sending SMS "); Serial.println("Sending SMS"); Send(); Serial.println("SMS Sent"); delay(2000); lcd.clear(); lcd.print("System Ready"); } } void gpsEvent() { gpsString=""; while(1) { while (gps.available()>0) //Serial incoming data from GPS { char inChar = (char)gps.read(); gpsString+= inChar; //store incoming data from GPS to temparary string str[] i++; // Serial.print(inChar); if (i < 7) { if(gpsString[i-1] != test[i-1]) //check for right string { i=0; gpsString=""; } } if(inChar=='\r') { if(i>60) { gps_status=1; break; } else { i=0; } } } if(gps_status) break; } } void get_gps() { lcd.clear(); lcd.print("Getting GPS Data"); lcd.setCursor(0,1); lcd.print("Please Wait....."); gps_status=0; int x=0; while(gps_status==0) { gpsEvent(); int str_lenth=i; coordinate2dec(); i=0;x=0; str_lenth=0; } } void show_coordinate() { lcd.clear(); lcd.print("Lat:"); lcd.print(latitude); lcd.setCursor(0,1); lcd.print("Log:"); lcd.print(logitude); Serial.print("Latitude:"); Serial.println(latitude); Serial.print("Longitude:"); Serial.println(logitude); Serial.print("Speed(in knots)="); Serial.println(Speed); delay(2000); lcd.clear(); lcd.print("Speed(Knots):"); lcd.setCursor(0,1); lcd.print(Speed); } void coordinate2dec() { String lat_degree=""; for(i=20;i<=21;i++) lat_degree+=gpsString[i]; String lat_minut=""; for(i=22;i<=28;i++) lat_minut+=gpsString[i]; String log_degree=""; for(i=32;i<=34;i++) log_degree+=gpsString[i]; String log_minut=""; for(i=35;i<=41;i++) log_minut+=gpsString[i]; Speed=""; for(i=45;i<48;i++) //extract longitude from string Speed+=gpsString[i]; float minut= lat_minut.toFloat(); minut=minut/60; float degree=lat_degree.toFloat(); latitude=degree+minut; minut= log_minut.toFloat(); minut=minut/60; degree=log_degree.toFloat(); logitude=degree+minut; } void Send() { Serial1.println("AT"); delay(500); serialPrint(); Serial1.println("AT+CMGF=1"); delay(500); serialPrint(); Serial1.print("AT+CMGS="); Serial1.print('"'); Serial1.print("9821757249"); //mobile no. for SMS alert Serial1.println('"'); delay(500); serialPrint(); Serial1.print("Latitude:"); Serial1.println(latitude); delay(500); serialPrint(); Serial1.print(" longitude:"); Serial1.println(logitude); delay(500); serialPrint(); Serial1.print(" Speed:"); Serial1.print(Speed); Serial1.println("Knots"); delay(500); serialPrint(); Serial1.print("http://maps.google.com/maps?&z=15&mrt=yp&t=k&q="); Serial1.print(latitude,6); Serial1.print("+"); //28.612953, 77.231545 //28.612953,77.2293563 Serial1.print(logitude,6); Serial1.write(26); delay(2000); serialPrint(); } void serialPrint() { while(Serial1.available()>0) { Serial.print(Serial1.read()); } } Video microcontroller-projects/diy-speedometer-using-arduino-and-processing-android-app