Arduino – PIR Sensor

Arduino – PIR Sensor ”; Previous Next PIR sensors allow you to sense motion. They are used to detect whether a human has moved in or out of the sensor’s range. They are commonly found in appliances and gadgets used at home or for businesses. They are often referred to as PIR, “Passive Infrared”, “Pyroelectric”, or “IR motion” sensors. Following are the advantages of PIR Sensors − Small in size Wide lens range Easy to interface Inexpensive Low-power Easy to use Do not wear out PIRs are made of pyroelectric sensors, a round metal can with a rectangular crystal in the center, which can detect levels of infrared radiation. Everything emits low-level radiation, and the hotter something is, the more radiation is emitted. The sensor in a motion detector is split in two halves. This is to detect motion (change) and not average IR levels. The two halves are connected so that they cancel out each other. If one-half sees more or less IR radiation than the other, the output will swing high or low. PIRs have adjustable settings and have a header installed in the 3-pin ground/out/power pads. For many basic projects or products that need to detect when a person has left or entered the area, PIR sensors are great. Note that PIRs do not tell you the number of people around or their closeness to the sensor. The lens is often fixed to a certain sweep at a distance and they are sometimes set off by the pets in the house. Components Required You will need the following components − 1 × Breadboard 1 × Arduino Uno R3 1 × PIR Sensor (MQ3) Procedure Follow the circuit diagram and make the connections as shown in the image below. Sketch Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. Arduino Code #define pirPin 2 int calibrationTime = 30; long unsigned int lowIn; long unsigned int pause = 5000; boolean lockLow = true; boolean takeLowTime; int PIRValue = 0; void setup() { Serial.begin(9600); pinMode(pirPin, INPUT); } void loop() { PIRSensor(); } void PIRSensor() { if(digitalRead(pirPin) == HIGH) { if(lockLow) { PIRValue = 1; lockLow = false; Serial.println(“Motion detected.”); delay(50); } takeLowTime = true; } if(digitalRead(pirPin) == LOW) { if(takeLowTime){ lowIn = millis();takeLowTime = false; } if(!lockLow && millis() – lowIn > pause) { PIRValue = 0; lockLow = true; Serial.println(“Motion ended.”); delay(50); } } } Code to Note PIR sensor has three terminals – Vcc, OUT and GND. Connect the sensor as follows − Connect the +Vcc to +5v on Arduino board. Connect OUT to digital pin 2 on Arduino board. Connect GND with GND on Arduino. You can adjust the sensor sensitivity and delay time via two variable resistors located at the bottom of the sensor board. Once the sensor detects any motion, Arduino will send a message via the serial port to say that a motion is detected. The PIR sense motion will delay for certain time to check if there is a new motion. If there is no motion detected, Arduino will send a new message saying that the motion has ended. Result You will see a message on your serial port if a motion is detected and another message when the motion stops. Print Page Previous Next Advertisements ”;

Arduino – Temperature Sensor

Arduino – Temperature Sensor ”; Previous Next The Temperature Sensor LM35 series are precision integrated-circuit temperature devices with an output voltage linearly proportional to the Centigrade temperature. The LM35 device has an advantage over linear temperature sensors calibrated in Kelvin, as the user is not required to subtract a large constant voltage from the output to obtain convenient Centigrade scaling. The LM35 device does not require any external calibration or trimming to provide typical accuracies of ±¼°C at room temperature and ±¾°C over a full −55°C to 150°C temperature range. Technical Specifications Calibrated directly in Celsius (Centigrade) Linear + 10-mV/°C scale factor 0.5°C ensured accuracy (at 25°C) Rated for full −55°C to 150°C range Suitable for remote applications Components Required You will need the following components − 1 × Breadboard 1 × Arduino Uno R3 1 × LM35 sensor Procedure Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below. Sketch Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. Arduino Code float temp; int tempPin = 0; void setup() { Serial.begin(9600); } void loop() { temp = analogRead(tempPin); // read analog volt from sensor and save to variable temp temp = temp * 0.48828125; // convert the analog volt to its temperature equivalent Serial.print(“TEMPERATURE = “); Serial.print(temp); // display temperature value Serial.print(“*C”); Serial.println(); delay(1000); // update sensor reading each one second } Code to Note LM35 sensor has three terminals – Vs, Vout and GND. We will connect the sensor as follows − Connect the +Vs to +5v on your Arduino board. Connect Vout to Analog0 or A0 on Arduino board. Connect GND with GND on Arduino. The Analog to Digital Converter (ADC) converts analog values into a digital approximation based on the formula ADC Value = sample * 1024 / reference voltage (+5v). So with a +5 volt reference, the digital approximation will be equal to input voltage * 205. Result You will see the temperature display on the serial port monitor which is updated every second. Print Page Previous Next Advertisements ”;

Arduino – Stepper Motor

Arduino – Stepper Motor ”; Previous Next A Stepper Motor or a step motor is a brushless, synchronous motor, which divides a full rotation into a number of steps. Unlike a brushless DC motor, which rotates continuously when a fixed DC voltage is applied to it, a step motor rotates in discrete step angles. The Stepper Motors therefore are manufactured with steps per revolution of 12, 24, 72, 144, 180, and 200, resulting in stepping angles of 30, 15, 5, 2.5, 2, and 1.8 degrees per step. The stepper motor can be controlled with or without feedback. Imagine a motor on an RC airplane. The motor spins very fast in one direction or another. You can vary the speed with the amount of power given to the motor, but you cannot tell the propeller to stop at a specific position. Now imagine a printer. There are lots of moving parts inside a printer, including motors. One such motor acts as the paper feed, spinning rollers that move the piece of paper as ink is being printed on it. This motor needs to be able to move the paper an exact distance to be able to print the next line of text or the next line of an image. There is another motor attached to a threaded rod that moves the print head back and forth. Again, that threaded rod needs to be moved an exact amount to print one letter after another. This is where the stepper motors come in handy. How a Stepper Motor Works? A regular DC motor spins in only direction whereas a Stepper motor can spin in precise increments. Stepper motors can turn an exact amount of degrees (or steps) as desired. This gives you total control over the motor, allowing you to move it to an exact location and hold that position. It does so by powering the coils inside the motor for very short periods of time. The disadvantage is that you have to power the motor all the time to keep it in the position that you desire. All you need to know for now is that, to move a stepper motor, you tell it to move a certain number of steps in one direction or the other, and tell it the speed at which to step in that direction. There are numerous varieties of stepper motors. The methods described here can be used to infer how to use other motors and drivers which are not mentioned in this tutorial. However, it is always recommended that you consult the datasheets and guides of the motors and drivers specific to the models you have. Components Required You will need the following components − 1 × Arduino UNO board 1 × small bipolar stepper Motor as shown in the image given below 1 × LM298 driving IC Procedure Follow the circuit diagram and make the connections as shown in the image given below. Sketch Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. Arduino Code /* Stepper Motor Control */ #include <Stepper.h> const int stepsPerRevolution = 90; // change this to fit the number of steps per revolution // for your motor // initialize the stepper library on pins 8 through 11: Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); void setup() { // set the speed at 60 rpm: myStepper.setSpeed(5); // initialize the serial port: Serial.begin(9600); } void loop() { // step one revolution in one direction: Serial.println(“clockwise”); myStepper.step(stepsPerRevolution); delay(500); // step one revolution in the other direction: Serial.println(“counterclockwise”); myStepper.step(-stepsPerRevolution); delay(500); } Code to Note This program drives a unipolar or bipolar stepper motor. The motor is attached to digital pins 8 – 11 of Arduino. Result The motor will take one revolution in one direction, then one revolution in the other direction. Print Page Previous Next Advertisements ”;

Arduino – Network Communication

Arduino – Network Communication ”; Previous Next The CC3000 WiFi module from Texas Instruments is a small silver package, which finally brings easy-to-use, affordable WiFi functionality to your Arduino projects. It uses SPI for communication (not UART!) so you can push data as fast as you want or as slow as you want. It has a proper interrupt system with IRQ pin so you can have asynchronous connections. It supports 802.11b/g, open/WEP/WPA/WPA2 security, TKIP & AES. A built-in TCP/IP stack with a “BSD socket” interface supports TCP and UDP in both the client and the server mode. Components Required You will need the following components − 1 × Arduino Uno 1 × Adafruit CC3000 breakout board 1 × 5V relay 1 × Rectifier diode 1 × LED 1 × 220 Ohm resistor 1 × Breadboard and some jumper wires For this project, you just need the usual Arduino IDE, the Adafruit’s CC3000 library, and the CC3000 MDNS library. We are also going to use the aREST library to send commands to the relay via WiFi. Procedure Follow the circuit diagram and make the connections as shown in the image given below. The hardware configuration for this project is very easy. Connect the IRQ pin of the CC3000 board to pin number 3 of the Arduino board. VBAT to pin 5, and CS to pin 10. Connect the SPI pins to Arduino board: MOSI, MISO, and CLK to pins 11, 12, and 13, respectively. Vin is connected to Arduino 5V, and GND to GND. Let us now connect the relay. After placing the relay on the breadboard, you can start identifying the two important parts on your relay: the coil part which commands the relay, and the switch part where we will attach the LED. First, connect pin number 8 of Arduino board to one pin of the coil. Connect the other pin to the ground of Arduino board. You also have to place the rectifier diode (anode connected to the ground pin) over the pins of the coil to protect your circuit when the relay is switching. Connect the +5V of Arduino board to the common pin of the relay’s switch. Finally, connect one of the other pin of the switch (usually, the one which is not connected when the relay is off) to the LED in series with the 220 Ohm resistor, and connect the other side of the LED to the ground of Arduino board. Testing Individual Components You can test the relay with the following sketch − const int relay_pin = 8; // Relay pin void setup() { Serial.begin(9600); pinMode(relay_pin,OUTPUT); } void loop() { // Activate relay digitalWrite(relay_pin, HIGH); // Wait for 1 second delay(1000); // Deactivate relay digitalWrite(relay_pin, LOW); // Wait for 1 second delay(1000); } Code to Note The code is self-explanatory. You can just upload it to the board and the relay will switch states every second, and the LED will switch ON and OFF accordingly. Adding WiFi Connectivity Let us now control the relay wirelessly using the CC3000 WiFi chip. The software for this project is based on the TCP protocol. However, for this project, Arduino board will be running a small web server, so we can “listen” for commands coming from the computer. We will first take care of Arduino sketch, and then we will see how to write the server-side code and create a nice interface. First, the Arduino sketch. The goal here is to connect to your WiFi network, create a web server, check if there are incoming TCP connections, and then change the state of the relay accordingly. Important Parts of the Code #include <Adafruit_CC3000.h> #include <SPI.h> #include <CC3000_MDNS.h> #include <Ethernet.h> #include <aREST.h> You need to define inside the code what is specific to your configuration, i.e. Wi-Fi name and password, and the port for TCP communications (we have used 80 here). // WiFi network (change with your settings!) #define WLAN_SSID “yourNetwork” // cannot be longer than 32 characters! #define WLAN_PASS “yourPassword” #define WLAN_SECURITY WLAN_SEC_WPA2 // This can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, // WLAN_SEC_WPA or WLAN_SEC_WPA2 // The port to listen for incoming TCP connections #define LISTEN_PORT 80 We can then create the CC3000 instance, server and aREST instance − // Server instance Adafruit_CC3000_Server restServer(LISTEN_PORT); // DNS responder instance MDNSResponder mdns; // Create aREST instance aREST rest = aREST(); In the setup() part of the sketch, we can now connect the CC3000 chip to the network − cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY); How will the computer know where to send the data? One way would be to run the sketch once, then get the IP address of the CC3000 board, and modify the server code again. However, we can do better, and that is where the CC3000 MDNS library comes into play. We will assign a fixed name to our CC3000 board with this library, so we can write down this name directly into the server code. This is done with the following piece of code − if (!mdns.begin(“arduino”, cc3000)) { while(1); } We also need to listen for incoming connections. restServer.begin(); Next, we will code the loop() function of the sketch that will be continuously executed. We first have to update the mDNS server. mdns.update(); The server running on Arduino board will wait for the incoming connections and handle the requests. Adafruit_CC3000_ClientRef client = restServer.available(); rest.handle(client); It is now quite easy to test the projects via WiFi. Make sure you updated the sketch with your own WiFi name and password, and upload the sketch to your Arduino board. Open your Arduino IDE serial monitor, and look for the IP address of your board. Let us assume for the rest here that it is something like 192.168.1.103. Then, simply go to your favorite web browser, and type − 192.168.1.103/digital/8/1 You should see that your relay automatically turns ON. Building the Relay Interface We will now code the interface of the project. There will be two parts here: an HTML file containing the interface, and a client-side Javascript file

Arduino – Discussion

Discuss Arduino ”; Previous Next Arduino is a prototype platform (open-source) based on an easy-to-use hardware and software. It consists of a circuit board, which can be programed (referred to as a microcontroller) and a ready-made software called Arduino IDE (Integrated Development Environment), which is used to write and upload the computer code to the physical board. Arduino provides a standard form factor that breaks the functions of the micro-controller into a more accessible package. Print Page Previous Next Advertisements ”;

Arduino – Keyboard Logout

Arduino – Keyboard Logout ”; Previous Next This example uses the Keyboard library to log you out of your user session on your computer when pin 2 on the ARDUINO UNO is pulled to ground. The sketch simulates the keypress in sequence of two or three keys at the same time and after a short delay, it releases them. Warning − When you use the Keyboard.print() command, Arduino takes over your computer”s keyboard. To ensure you do not lose control of your computer while running a sketch with this function, set up a reliable control system before you call Keyboard.print(). This sketch is designed to only send a Keyboard command after a pin has been pulled to ground. Components Required You will need the following components − 1 × Breadboard 1 × Arduino Leonardo, Micro, or Due board 1 × pushbutton 1 × Jumper Procedure Follow the circuit diagram and hook up the components on the breadboard as shown in the image below. Sketch Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. For this example, you need to use Arduino IDE 1.6.7 Note − You must include the keyboard library in your Arduino library file. Copy and paste the keypad library file inside the file with the name libraries (highlighted) as shown in the following screenshot. Arduino Code /* Keyboard logout This sketch demonstrates the Keyboard library. When you connect pin 2 to ground, it performs a logout. It uses keyboard combinations to do this, as follows: On Windows, CTRL-ALT-DEL followed by ALT-l On Ubuntu, CTRL-ALT-DEL, and ENTER On OSX, CMD-SHIFT-q To wake: Spacebar. Circuit: * Arduino Leonardo or Micro * wire to connect D2 to ground. */ #define OSX 0 #define WINDOWS 1 #define UBUNTU 2 #include “Keyboard.h” // change this to match your platform: int platform = WINDOWS; void setup() { // make pin 2 an input and turn on the // pullup resistor so it goes high unless // connected to ground: pinMode(2, INPUT_PULLUP); Keyboard.begin(); } void loop() { while (digitalRead(2) == HIGH) { // do nothing until pin 2 goes low delay(500); } delay(1000); switch (platform) { case OSX: Keyboard.press(KEY_LEFT_GUI); // Shift-Q logs out: Keyboard.press(KEY_LEFT_SHIFT); Keyboard.press(”Q”); delay(100); // enter: Keyboard.write(KEY_RETURN); break; case WINDOWS: // CTRL-ALT-DEL: Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_LEFT_ALT); Keyboard.press(KEY_DELETE); delay(100); Keyboard.releaseAll(); //ALT-l: delay(2000); Keyboard.press(KEY_LEFT_ALT); Keyboard.press(”l”); Keyboard.releaseAll(); break; case UBUNTU: // CTRL-ALT-DEL: Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_LEFT_ALT); Keyboard.press(KEY_DELETE); delay(1000); Keyboard.releaseAll(); // Enter to confirm logout: Keyboard.write(KEY_RETURN); break; } // do nothing: while (true); } Keyboard.releaseAll(); // enter: Keyboard.write(KEY_RETURN); break; case WINDOWS: // CTRL-ALT-DEL: Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_LEFT_ALT); Keyboard.press(KEY_DELETE); delay(100); Keyboard.releaseAll(); //ALT-l: delay(2000); Keyboard.press(KEY_LEFT_ALT); Keyboard.press(”l”); Keyboard.releaseAll(); break; case UBUNTU: // CTRL-ALT-DEL: Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_LEFT_ALT); Keyboard.press(KEY_DELETE); delay(1000); Keyboard.releaseAll(); // Enter to confirm logout: Keyboard.write(KEY_RETURN); break; } // do nothing: while (true); } Code to Note Before you upload the program to your board, make sure you assign the correct OS you are currently using to the platform variable. While the sketch is running, pressing the button will connect pin 2 to the ground and the board will send the logout sequence to the USB connected PC. Result When you connect pin 2 to the ground, it performs a logout operation. It uses the following keyboard combinations to logout − On Windows, CTRL-ALT-DEL followed by ALT-l On Ubuntu, CTRL-ALT-DEL, and ENTER On OSX, CMD-SHIFT-q Print Page Previous Next Advertisements ”;

Arduino – Tone Library

Arduino – Tone Library ”; Previous Next In this chapter, we will use the Arduino Tone Library. It is nothing but an Arduino Library, which produces square-wave of a specified frequency (and 50% duty cycle) on any Arduino pin. A duration can optionally be specified, otherwise the wave continues until the stop() function is called. The pin can be connected to a piezo buzzer or a speaker to play the tones. Warning − Do not connect the pin directly to any audio input. The voltage is considerably higher than the standard line level voltages, and can damage sound card inputs, etc. You can use a voltage divider to bring the voltage down. Components Required You will need the following components − 1 × 8-ohm speaker 1 × 1k resistor 1 × Arduino UNO board Procedure Follow the circuit diagram and make the connections as shown in the image given below. Sketch Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. To make the pitches.h file, either click the button just below the serial monitor icon and choose “New Tab”, or use Ctrl+Shift+N. Then paste the following code − /************************************************* * Public Constants *************************************************/ #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 Save the above given code as pitches.h Arduino Code #include “pitches.h” // notes in the melody: int melody[] = { NOTE_C4, NOTE_G3,NOTE_G3, NOTE_GS3, NOTE_G3,0, NOTE_B3, NOTE_C4}; // note durations: 4 = quarter note, 8 = eighth note, etc.: int noteDurations[] = { 4, 8, 8, 4,4,4,4,4 }; void setup() { // iterate over the notes of the melody: for (int thisNote = 0; thisNote < 8; thisNote++) { // to calculate the note duration, take one second // divided by the note type. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. int noteDuration = 1000/noteDurations[thisNote]; tone(8, melody[thisNote],noteDuration); //pause for the note”s duration plus 30 ms: delay(noteDuration +30); } } void loop() { // no need to repeat the melody. } Code to Note The code uses an extra file, pitches.h. This file contains all the pitch values for typical notes. For example, NOTE_C4 is middle C. NOTE_FS4 is F sharp, and so forth. This note table was originally written by Brett Hagman, on whose work the tone() command was based. You may find it useful whenever you want to make musical notes. Result You will hear musical notes saved in the pitches.h. file. Print Page Previous Next Advertisements ”;

Arduino – Keyboard Serial

Arduino – Keyboard Serial ”; Previous Next This example listens for a byte coming from the serial port. When received, the board sends a keystroke back to the computer. The sent keystroke is one higher than what is received, so if you send an “a” from the serial monitor, you will receive a “b” from the board connected to the computer. A “1” will return a “2” and so on. Warning − When you use the Keyboard.print() command, the Leonardo, Micro or Due board takes over your computer”s keyboard. To ensure you do not lose control of your computer while running a sketch with this function, set up a reliable control system before you call Keyboard.print(). This sketch is designed to only send a Keyboard command after the board has received a byte over the serial port. Components Required You will need the following components − 1 × Arduino Leonardo, Micro, or Due board Procedure Just connect your board to the computer using USB cable. Sketch Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. Notes − You must include the keypad library in your Arduino library file. Copy and paste the keypad library file inside the file with the name ‘libraries’ highlighted with yellow color. Arduino Code /* Keyboard test For the Arduino Leonardo, Micro or Due Reads a byte from the serial port, sends a keystroke back. The sent keystroke is one higher than what”s received, e.g. if you send a, you get b, send A you get B, and so forth. The circuit: * none */ #include “Keyboard.h” void setup() { // open the serial port: Serial.begin(9600); // initialize control over the keyboard: Keyboard.begin(); } void loop() { // check for incoming serial data: if (Serial.available() > 0) { // read incoming serial data: char inChar = Serial.read(); // Type the next ASCII value from what you received: Keyboard.write(inChar + 1); } } Code to Note Once programed, open your serial monitor and send a byte. The board will reply with a keystroke, that is one number higher. Result The board will reply with a keystroke that is one number higher on Arduino IDE serial monitor when you send a byte. Print Page Previous Next Advertisements ”;

Arduino – Humidity Sensor

Arduino – Humidity Sensor ”; Previous Next In this section, we will learn how to interface our Arduino board with different sensors. We will discuss the following sensors − Humidity sensor (DHT22) Temperature sensor (LM35) Water detector sensor (Simple Water Trigger) PIR SENSOR ULTRASONIC SENSOR GPS Humidity Sensor (DHT22) The DHT-22 (also named as AM2302) is a digital-output, relative humidity, and temperature sensor. It uses a capacitive humidity sensor and a thermistor to measure the surrounding air, and sends a digital signal on the data pin. In this example, you will learn how to use this sensor with Arduino UNO. The room temperature and humidity will be printed to the serial monitor. The DHT-22 Sensor The connections are simple. The first pin on the left to 3-5V power, the second pin to the data input pin and the right-most pin to the ground. Technical Details Power − 3-5V Max Current − 2.5mA Humidity − 0-100%, 2-5% accuracy Temperature − 40 to 80°C, ±0.5°C accuracy Components Required You will need the following components − 1 × Breadboard 1 × Arduino Uno R3 1 × DHT22 1 × 10K ohm resistor Procedure Follow the circuit diagram and hook up the components on the breadboard as shown in the image below. Sketch Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. Arduino Code // Example testing sketch for various DHT humidity/temperature sensors #include “DHT.h” #define DHTPIN 2 // what digital pin we”re connected to // Uncomment whatever type you”re using! //#define DHTTYPE DHT11 // DHT 11 #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 //#define DHTTYPE DHT21 // DHT 21 (AM2301) // Connect pin 1 (on the left) of the sensor to +5V // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1 // to 3.3V instead of 5V! // Connect pin 2 of the sensor to whatever your DHTPIN is // Connect pin 4 (on the right) of the sensor to GROUND // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor // Initialize DHT sensor. // Note that older versions of this library took an optional third parameter to // tweak the timings for faster processors. This parameter is no longer needed // as the current DHT reading algorithm adjusts itself to work on faster procs. DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); Serial.println(“DHTxx test!”); dht.begin(); } void loop() { delay(2000); // Wait a few seconds between measurements float h = dht.readHumidity(); // Reading temperature or humidity takes about 250 milliseconds! float t = dht.readTemperature(); // Read temperature as Celsius (the default) float f = dht.readTemperature(true); // Read temperature as Fahrenheit (isFahrenheit = true) // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t) || isnan(f)) { Serial.println(“Failed to read from DHT sensor!”); return; } // Compute heat index in Fahrenheit (the default) float hif = dht.computeHeatIndex(f, h); // Compute heat index in Celsius (isFahreheit = false) float hic = dht.computeHeatIndex(t, h, false); Serial.print (“Humidity: “); Serial.print (h); Serial.print (” %t”); Serial.print (“Temperature: “); Serial.print (t); Serial.print (” *C “); Serial.print (f); Serial.print (” *Ft”); Serial.print (“Heat index: “); Serial.print (hic); Serial.print (” *C “); Serial.print (hif); Serial.println (” *F”); } Code to Note DHT22 sensor has four terminals (Vcc, DATA, NC, GND), which are connected to the board as follows − DATA pin to Arduino pin number 2 Vcc pin to 5 volt of Arduino board GND pin to the ground of Arduino board We need to connect 10k ohm resistor (pull up resistor) between the DATA and the Vcc pin Once hardware connections are done, you need to add DHT22 library to your Arduino library file as described earlier. Result You will see the temperature and humidity display on serial port monitor which is updated every 2 seconds. Print Page Previous Next Advertisements ”;

Arduino – Inter Integrated Circuit

Arduino – Inter Integrated Circuit ”; Previous Next Inter-integrated circuit (I2C) is a system for serial data exchange between the microcontrollers and specialized integrated circuits of a new generation. It is used when the distance between them is short (receiver and transmitter are usually on the same printed board). Connection is established via two conductors. One is used for data transfer and the other is used for synchronization (clock signal). As seen in the following figure, one device is always a master. It performs addressing of one slave chip before the communication starts. In this way, one microcontroller can communicate with 112 different devices. Baud rate is usually 100 Kb/sec (standard mode) or 10 Kb/sec (slow baud rate mode). Systems with the baud rate of 3.4 Mb/sec have recently appeared. The distance between devices, which communicate over an I2C bus is limited to several meters. Board I2C Pins The I2C bus consists of two signals − SCL and SDA. SCL is the clock signal, and SDA is the data signal. The current bus master always generates the clock signal. Some slave devices may force the clock low at times to delay the master sending more data (or to require more time to prepare data before the master attempts to clock it out). This is known as “clock stretching”. Following are the pins for different Arduino boards − Uno, Pro Mini A4 (SDA), A5 (SCL) Mega, Due 20 (SDA), 21 (SCL) Leonardo, Yun 2 (SDA), 3 (SCL) Arduino I2C We have two modes – master code and slave code – to connect two Arduino boards using I2C. They are − Master Transmitter / Slave Receiver Master Receiver / Slave Transmitter Master Transmitter / Slave Receiver Let us now see what is master transmitter and slave receiver. Master Transmitter The following functions are used to initialize the Wire library and join the I2C bus as a master or slave. This is normally called only once. Wire.begin(address) − Address is the 7-bit slave address in our case as the master is not specified and it will join the bus as a master. Wire.beginTransmission(address) − Begin a transmission to the I2C slave device with the given address. Wire.write(value) − Queues bytes for transmission from a master to slave device (in-between calls to beginTransmission() and endTransmission()). Wire.endTransmission() − Ends a transmission to a slave device that was begun by beginTransmission() and transmits the bytes that were queued by wire.write(). Example #include <Wire.h> //include wire library void setup() //this will run only once { Wire.begin(); // join i2c bus as master } short age = 0; void loop() { Wire.beginTransmission(2); // transmit to device #2 Wire.write(“age is = “); Wire.write(age); // sends one byte Wire.endTransmission(); // stop transmitting delay(1000); } Slave Receiver The following functions are used − Wire.begin(address) − Address is the 7-bit slave address. Wire.onReceive(received data handler) − Function to be called when a slave device receives data from the master. Wire.available() − Returns the number of bytes available for retrieval with Wire.read().This should be called inside the Wire.onReceive() handler. Example #include <Wire.h> //include wire library void setup() { //this will run only once Wire.begin(2); // join i2c bus with address #2 Wire.onReceive(receiveEvent); // call receiveEvent when the master send any thing Serial.begin(9600); // start serial for output to print what we receive } void loop() { delay(250); } //—–this function will execute whenever data is received from master—–// void receiveEvent(int howMany) { while (Wire.available()>1) // loop through all but the last { char c = Wire.read(); // receive byte as a character Serial.print(c); // print the character } } Master Receiver / Slave Transmitter Let us now see what is master receiver and slave transmitter. Master Receiver The Master, is programmed to request, and then read bytes of data that are sent from the uniquely addressed Slave Arduino. The following function is used − Wire.requestFrom(address,number of bytes) − Used by the master to request bytes from a slave device. The bytes may then be retrieved with the functions wire.available() and wire.read() functions. Example #include <Wire.h> //include wire library void setup() { Wire.begin(); // join i2c bus (address optional for master) Serial.begin(9600); // start serial for output } void loop() { Wire.requestFrom(2, 1); // request 1 bytes from slave device #2 while (Wire.available()) // slave may send less than requested { char c = Wire.read(); // receive a byte as character Serial.print(c); // print the character } delay(500); } Slave Transmitter The following function is used. Wire.onRequest(handler) − A function is called when a master requests data from this slave device. Example #include <Wire.h> void setup() { Wire.begin(2); // join i2c bus with address #2 Wire.onRequest(requestEvent); // register event } Byte x = 0; void loop() { delay(100); } // function that executes whenever data is requested by master // this function is registered as an event, see setup() void requestEvent() { Wire.write(x); // respond with message of 1 bytes as expected by master x++; } Print Page Previous Next Advertisements ”;