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 – 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 – Wireless Communication

Arduino – Wireless Communication ”; Previous Next The wireless transmitter and receiver modules work at 315 Mhz. They can easily fit into a breadboard and work well with microcontrollers to create a very simple wireless data link. With one pair of transmitter and receiver, the modules will only work communicating data one-way, however, you would need two pairs (of different frequencies) to act as a transmitter/receiver pair. Note − These modules are indiscriminate and receive a fair amount of noise. Both the transmitter and receiver work at common frequencies and do not have IDs. Receiver Module Specifications Product Model − MX-05V Operating voltage − DC5V Quiescent Current − 4mA Receiving frequency − 315Mhz Receiver sensitivity − -105DB Size − 30 * 14 * 7mm Transmitter Module Specifications Product Model − MX-FS-03V Launch distance − 20-200 meters (different voltage, different results) Operating voltage − 3.5-12V Dimensions − 19 * 19mm Operating mode − AM Transfer rate − 4KB / S Transmitting power − 10mW Transmitting frequency − 315Mhz An external antenna − 25cm ordinary multi-core or single-core line Pinout from left → right − (DATA; VCC; GND) Components Required You will need the following components − 2 × Arduino UNO board 1 × Rf link transmitter 1 × Rf link receiver 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. Note − You must include the keypad library in your Arduino library file. Copy and paste the VirtualWire.lib file in the libraries folder as highlighted in the screenshot given below. Arduino Code for Transmitter //simple Tx on pin D12 #include <VirtualWire.h> char *controller; void setup() { pinMode(13,OUTPUT); vw_set_ptt_inverted(true); vw_set_tx_pin(12); vw_setup(4000);// speed of data transfer Kbps } void loop() { controller=”1″ ; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone digitalWrite(13,1); delay(2000); controller=”0″ ; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone digitalWrite(13,0); delay(2000); } Code to Note This is a simple code. First, it will send character ”1” and after two seconds it will send character ”0” and so on. Arduino Code for Receiver //simple Rx on pin D12 #include <VirtualWire.h> void setup() { vw_set_ptt_inverted(true); // Required for DR3100 vw_set_rx_pin(12); vw_setup(4000); // Bits per sec pinMode(5, OUTPUT); vw_rx_start(); // Start the receiver PLL running } void loop() { uint8_t buf[VW_MAX_MESSAGE_LEN]; uint8_t buflen = VW_MAX_MESSAGE_LEN; if (vw_get_message(buf, &buflen)) // Non-blocking { if(buf[0]==”1”) { digitalWrite(5,1); } if(buf[0]==”0”) { digitalWrite(5,0); } } } Code to Note The LED connected to pin number 5 on the Arduino board is turned ON when character ”1” is received and turned OFF when character ”0” received. Print Page Previous Next Advertisements ”;

Arduino – Mouse Button Control

Arduino – Mouse Button Control ”; Previous Next Using the Mouse library, you can control a computer”s onscreen cursor with an Arduino Leonardo, Micro, or Due. This particular example uses five pushbuttons to move the onscreen cursor. Four of the buttons are directional (up, down, left, right) and one is for a left mouse click. Cursor movement from Arduino is always relative. Every time an input is read, the cursor”s position is updated relative to its current position. Whenever one of the directional buttons is pressed, Arduino will move the mouse, mapping a HIGH input to a range of 5 in the appropriate direction. The fifth button is for controlling a left-click from the mouse. When the button is released, the computer will recognize the event. Components Required You will need the following components − 1 × Breadboard 1 × Arduino Leonardo, Micro or Due board 5 × 10k ohm resistor 5 × momentary pushbuttons 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 Arduino Code /* Button Mouse Control For Leonardo and Due boards only .Controls the mouse from five pushbuttons on an Arduino Leonardo, Micro or Due. Hardware: * 5 pushbuttons attached to D2, D3, D4, D5, D6 The mouse movement is always relative. This sketch reads four pushbuttons, and uses them to set the movement of the mouse. WARNING: When you use the Mouse.move() command, the Arduino takes over your mouse! Make sure you have control before you use the mouse commands. */ #include “Mouse.h” // set pin numbers for the five buttons: const int upButton = 2; const int downButton = 3; const int leftButton = 4; const int rightButton = 5; const int mouseButton = 6; int range = 5; // output range of X or Y movement; affects movement speed int responseDelay = 10; // response delay of the mouse, in ms void setup() { // initialize the buttons” inputs: pinMode(upButton, INPUT); pinMode(downButton, INPUT); pinMode(leftButton, INPUT); pinMode(rightButton, INPUT); pinMode(mouseButton, INPUT); // initialize mouse control: Mouse.begin(); } void loop() { // read the buttons: int upState = digitalRead(upButton); int downState = digitalRead(downButton); int rightState = digitalRead(rightButton); int leftState = digitalRead(leftButton); int clickState = digitalRead(mouseButton); // calculate the movement distance based on the button states: int xDistance = (leftState – rightState) * range; int yDistance = (upState – downState) * range; // if X or Y is non-zero, move: if ((xDistance != 0) || (yDistance != 0)) { Mouse.move(xDistance, yDistance, 0); } // if the mouse button is pressed: if (clickState == HIGH) { // if the mouse is not pressed, press it: if (!Mouse.isPressed(MOUSE_LEFT)) { Mouse.press(MOUSE_LEFT); } } else { // else the mouse button is not pressed: // if the mouse is pressed, release it: if (Mouse.isPressed(MOUSE_LEFT)) { Mouse.release(MOUSE_LEFT); } } // a delay so the mouse does not move too fast: delay(responseDelay); } Code to Note Connect your board to your computer with a micro-USB cable. The buttons are connected to digital inputs from pins 2 to 6. Make sure you use 10k pull-down resistors. 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 ”;

Arduino – Serial Peripheral Interface

Arduino – Serial Peripheral Interface ”; Previous Next A Serial Peripheral Interface (SPI) bus is a system for serial communication, which uses up to four conductors, commonly three. One conductor is used for data receiving, one for data sending, one for synchronization and one alternatively for selecting a device to communicate with. It is a full duplex connection, which means that the data is sent and received simultaneously. The maximum baud rate is higher than that in the I2C communication system. Board SPI Pins SPI uses the following four wires − SCK − This is the serial clock driven by the master. MOSI − This is the master output / slave input driven by the master. MISO − This is the master input / slave output driven by the master. SS − This is the slave-selection wire. The following functions are used. You have to include the SPI.h. SPI.begin() − Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high. SPI.setClockDivider(divider) − To set the SPI clock divider relative to the system clock. On AVR based boards, the dividers available are 2, 4, 8, 16, 32, 64 or 128. The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to one-quarter of the frequency of the system clock (5 Mhz for the boards at 20 MHz). Divider − It could be (SPI_CLOCK_DIV2, SPI_CLOCK_DIV4, SPI_CLOCK_DIV8, SPI_CLOCK_DIV16, SPI_CLOCK_DIV32, SPI_CLOCK_DIV64, SPI_CLOCK_DIV128). SPI.transfer(val) − SPI transfer is based on a simultaneous send and receive: the received data is returned in receivedVal. SPI.beginTransaction(SPISettings(speedMaximum, dataOrder, dataMode)) − speedMaximum is the clock, dataOrder(MSBFIRST or LSBFIRST), dataMode(SPI_MODE0, SPI_MODE1, SPI_MODE2, or SPI_MODE3). We have four modes of operation in SPI as follows − Mode 0 (the default) − Clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0). Mode 1 − Clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1). Mode 2 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0). Mode 3 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1). SPI.attachInterrupt(handler) − Function to be called when a slave device receives data from the master. Now, we will connect two Arduino UNO boards together; one as a master and the other as a slave. (SS) : pin 10 (MOSI) : pin 11 (MISO) : pin 12 (SCK) : pin 13 The ground is common. Following is the diagrammatic representation of the connection between both the boards − Let us see examples of SPI as Master and SPI as Slave. SPI as MASTER Example #include <SPI.h> void setup (void) { Serial.begin(115200); //set baud rate to 115200 for usart digitalWrite(SS, HIGH); // disable Slave Select SPI.begin (); SPI.setClockDivider(SPI_CLOCK_DIV8);//divide the clock by 8 } void loop (void) { char c; digitalWrite(SS, LOW); // enable Slave Select // send test string for (const char * p = “Hello, world!r” ; c = *p; p++) { SPI.transfer (c); Serial.print(c); } digitalWrite(SS, HIGH); // disable Slave Select delay(2000); } SPI as SLAVE Example #include <SPI.h> char buff [50]; volatile byte indx; volatile boolean process; void setup (void) { Serial.begin (115200); pinMode(MISO, OUTPUT); // have to send on master in so it set as output SPCR |= _BV(SPE); // turn on SPI in slave mode indx = 0; // buffer empty process = false; SPI.attachInterrupt(); // turn on interrupt } ISR (SPI_STC_vect) // SPI interrupt routine { byte c = SPDR; // read byte from SPI Data Register if (indx < sizeof buff) { buff [indx++] = c; // save data in the next index in the array buff if (c == ”r”) //check for the end of the word process = true; } } void loop (void) { if (process) { process = false; //reset the process Serial.println (buff); //print the array on serial monitor indx= 0; //reset button to zero } } Print Page Previous Next Advertisements ”;