You are on page 1of 187

1

Arduino

Fabio Brandespim brandesp@hotmail.com Sunnyvale, Ca Sugestions and errors are welcome.

What is Arduino?
Arduino is an open-source physical computing platform based on a simple i/o board and a development environment that implements the Processing/Wiring language. Arduino can be used to develop stand-alone interactive objects or can be connected to software on your computer (e.g. Flash, Processing, MaxMSP). The boards can be assembled by hand or purchased preassembled; the open-source IDE can be downloaded for free. Arduino is an open-source electronics prototyping platform based on flexible, easy-to-use hardware and software. It's intended for artists, designers, hobbyists, and anyone interested in creating interactive objects or environments. Arduino can sense the environment by receiving input from a variety of sensors and can affect its surroundings by controlling lights, motors, and other actuators. The microcontroller on the board is programmed using the Arduino programming language (based on Wiring) and the Arduino development environment (based on Processing). Arduino projects can be stand-alone or they can communicate with software on running on a computer (e.g. Flash, Processing, MaxMSP).
Want to join the world of Arduino developers? Wired editor in chief Chris Anderson already has, designing two Arduino-based autopilots for unmanned model aircraft: ArduPilot and BlimpDuino (you can find them at diydrones.com). Here's his formula for getting your creation out and into the world. 1 Download the Arduino schematic and circuit board files from arduino .cc. Use the free version of CadSoft Eagle (from cadsoft.de) to modify them for your particular creation. 4 If you want to produce and sell the product yourself, use a manufacturing service like Screaming Circuits to assemble the boards on robotic pick-and-place soldering machines. 2 Upload your files to a board fabricator like BatchPCB. Your boards will be manufactured in Chinese robotic-electronics factories and sent to your house. Typical cost is $10 each. 5 Alternately, an open source hardware specialist like SparkFun or Adafruit can make and sell the product for you. They'll add a profit margin and pay you a license fee . 3 Order bulk electronic parts from digikey .com and solder the components onto the board to make a prototype. Test the board and your code. You're ready to distribute your gizmo to the masses! 6 Publish your revised schematics and circuit board files so that others can modify them. The cycle begins again.

Basic Parts for wiring up Arduino


A breadboard 22 AWG wire 7805 Voltage regulator 2 LEDs 2 220 Ohm resistors 1 10k Ohm resistor 2 10 uF capacitors 16 MHz clock crystal 2 22 pF capacitors small momentary normally open ("off") button, i.e. Omron type B3F

USB to Serial Communication Board


You will need a FT232 USB Breakout board from SparkFun. There are two options available from them:

5 FT232RL USB to Serial Breakout Board, SKU BOB-0071 Arduino Serial USB Board, SKU DEV-08165

Atmega328 Flash memory 30K RAM 2K EPROM 1K So, to recap: The AVR chip runs whatever program is stored in the flash, uses the RAM for temporary storage and the EEPROM for longer term storage.

Componentes: Resistor 10k Interruptor

L e sd L l c 1R 0

L C R 20 1k l e

L e 1R 0

t s

10

N T e 1 Rs i L e

10

11

11

12

12

13

int pingPin = 7; void setup() { Serial.begin(9600); } void loop() { long duration, inches, cm; // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. // We give a short LOW pulse beforehand to ensure a clean HIGH pulse. pinMode(pingPin, OUTPUT); digitalWrite(pingPin, LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(5); digitalWrite(pingPin, LOW); // The same pin is used to read the signal from the PING))): a HIGH // pulse whose duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. pinMode(pingPin, INPUT); duration = pulseIn(pingPin, HIGH); // convert the time into a distance inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); 13

14 Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); } delay(100);

long microsecondsToInches(long microseconds) { // According to Parallax's datasheet for the PING))), there are // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per // second). This gives the distance travelled by the ping, outbound // and return, so we divide by 2 to get the distance of the obstacle. // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter. // The ping travels out and back, so to find the distance of the // object we take half of the distance travelled. return microseconds / 29 / 2; } Exemplo 2 //More accurate exemple // * Copyleft 2007 Jason Ch //This code returns the distance in Inches... I think it's more accurate than other code I have seen online and returns more usable results. Remove the *.39 to return cm instead of inches. You could make float ultrasoundValue = 0; but then you can't print it unless you transfer it into another type, but it could be used for further calculations. unsigned long echo = 0; int ultraSoundSignal = 7; // Ultrasound signal pin unsigned long ultrasoundValue = 0; void setup() { Serial.begin(9600); pinMode(ultraSoundSignal,OUTPUT); } unsigned long ping(){ pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output digitalWrite(ultraSoundSignal, LOW); // Send low pulse delayMicroseconds(2); // Wait for 2 microseconds digitalWrite(ultraSoundSignal, HIGH); // Send high pulse delayMicroseconds(5); // Wait for 5 microseconds

14

15 digitalWrite(ultraSoundSignal, LOW); // Holdoff pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input digitalWrite(ultraSoundSignal, HIGH); // Turn on pullup resistor echo = pulseIn(ultraSoundSignal, HIGH); //Listen for echo ultrasoundValue = (echo / 58.138) * .39; //convert to CM then to inches return ultrasoundValue; } void loop() { int x = 0; x = ping(); Serial.println(x); delay(250); //delay 1/4 seconds. }

15

16

//Listen for the $GPRMC string and extract the GPS location data from //this. Display the result in the Arduino's serial monitor. */ #include <string.h> #include <ctype.h> int ledPin = 13; int rxPin = 0; int txPin = 1; int byteGPS=-1; char linea[300] = ""; char comandoGPR[7] = "$GPRMC"; int cont=0; int bien=0; int conta=0; int indices[13]; void setup() { pinMode(ledPin, OUTPUT); pinMode(rxPin, INPUT); pinMode(txPin, OUTPUT);

// LED test pin // RX PIN // TX TX

// Initialize LED pin

16

17 Serial.begin(4800); for (int i=0;i<300;i++){ // Initialize a buffer for received data linea[i]=' '; } } void loop() { digitalWrite(ledPin, HIGH); byteGPS=Serial.read(); // Read a byte of the serial port if (byteGPS == -1) { // See if the port is empty yet delay(100); } else { linea[conta]=byteGPS; // If there is serial port data, it is put in the buffer conta++; printByte(byteGPS); if (byteGPS==13){ // If the received byte is = to 13, end of transmission digitalWrite(ledPin, LOW); cont=0; bien=0; for (int i=1;i<7;i++){ // Verifies if the received command starts with $GPR if (linea[i]==comandoGPR[i-1]){ bien++; } } if(bien==6){ // If yes, continue and process the data for (int i=0;i<300;i++){ if (linea[i]==','){ // check for the position of the "," separator indices[cont]=i; cont++; } if (linea[i]=='*'){ // ... and the "*" indices[12]=i; cont++; } } Serial.println(""); // ... and write to the serial port Serial.println(""); Serial.println("---------------"); for (int i=0;i<12;i++){ switch(i){ case 0 :Serial.print("Time in UTC (HhMmSs): ");break; case 1 :Serial.print("Status (A=OK,V=KO): ");break; case 2 :Serial.print("Latitude: ");break; case 3 :Serial.print("Direction (N/S): ");break; case 4 :Serial.print("Longitude: ");break; case 5 :Serial.print("Direction (E/W): ");break; case 6 :Serial.print("Velocity in knots: ");break; case 7 :Serial.print("Heading in degrees: ");break; case 8 :Serial.print("Date UTC (DdMmAa): ");break; case 9 :Serial.print("Magnetic degrees: ");break; case 10 :Serial.print("(E/W): ");break; case 11 :Serial.print("Mode: ");break;

17

18 case 12 :Serial.print("Checksum: ");break; } for (int j=indices[i];j<(indices[i+1]-1);j++){ Serial.print(linea[j+1]); } Serial.println("");

} conta=0; for (int i=0;i<300;i++){ linea[i]=' '; } } } }

} Serial.println("---------------");

// Reset the buffer //

18

19

19

20

20

21 }

21

22

22

23

23

24

24

25 1 Potentiometer 0

25

26 LEDs are commonly used as lights, but then can also be used as photodiodes to detect light. This example circuit uses a single LED to sample the ambient light level and then glow at an appropriate brightness. It is tragically flawed by a slow refresh rate in the dark, but it shows how to sense. // // This example shows one way of using an LED as a light sensor. // You will need to wire up your components as such: // // + digital2 // | // < // > 100 ohm resistor // < // | // | // ----// / \ LED, maybe a 5mm, clear plastic is good // ----// | // | // + digital3 // // What we are going to do is apply a positive voltage at digital2 and // a low voltage at digital3. This is backwards for the LED, current will // not flow and light will not come out, but we will charge up the // capacitance of the LED junction and the Arduino pin. // // Then we are going to disconnect the output drivers from digital2 and // count how long it takes the stored charge to bleed off through the // the LED. The brighter the light, the faster it will bleed away to // digital3. // // Then just to be perverse we will display the brightness back on the // same LED by turning it on for a millisecond. This happens more often // with brighter lighting, so the LED is dim in a dim room and brighter // in a bright room. Quite nice. // // (Though a nice idea, this implementation is flawed because the refresh // rate gets too long in the dark and it flickers disturbingly.) // #define LED_N_SIDE 2 #define LED_P_SIDE 3 void setup() {} void loop() { unsigned int j; // Apply reverse voltage, charge up the pin and led capacitance pinMode(LED_N_SIDE,OUTPUT); pinMode(LED_P_SIDE,OUTPUT); digitalWrite(LED_N_SIDE,HIGH); digitalWrite(LED_P_SIDE,LOW);

26

27 // Isolate the pin 2 end of the diode pinMode(LED_N_SIDE,INPUT); digitalWrite(LED_N_SIDE,LOW); // turn off internal pull-up resistor // Count how long it takes the diode to bleed back down to a logic zero for ( j = 0; j < 30000; j++) { if ( digitalRead(LED_N_SIDE)==0) break; } // You could use 'j' for something useful, but here we are just using the // delay of the counting. In the dark it counts higher and takes longer, // increasing the portion of the loop where the LED is off compared to // the 1000 microseconds where we turn it on. // Turn the light on for 1000 microseconds digitalWrite(LED_P_SIDE,HIGH); digitalWrite(LED_N_SIDE,LOW); pinMode(LED_P_SIDE,OUTPUT); pinMode(LED_N_SIDE,OUTPUT); delayMicroseconds(1000); // we could turn it off, but we know that is about to happen at the loop() start }

27

28

TIP 120/121/122 Motor Driver

Componentes: Tip120/121/122 1k resistor 1N4001 diodo Example: int motorPin = 9; int ledPin = 13; int val = 0; void setup() { pinMode(motorPin, OUTPUT); Serial.begin(19200); Serial.println("Welcome to Serial Motor Speed!"); Serial.println("Enter speed number 0-9:"); } void loop() { val = Serial.read(); if (val >= '0' && val <= '9') { val = val - '0'; val = 28 * val; Serial.print("Setting speed to "); Serial.println(val); analogWrite(motorPin,val); } } Serial.println("Enter speed number 0-9:");

28

29

29

30

30

31

tas wr ft cm (n oe ed cb he ol ir e n t 2 h e h a

de h c , e a

t s

http://www.arduino.cc/en/Hacking/ParallelProgrammer http://www.geocities.jp/arduino_diecimila/bootloader/index_en.html

31

32

1) 3.3V 2) GND 3) MISO 4) MOSI 5) SCLK 6) SS or SCS 7) INT 8) RESET

32

33

1) 3.3V

2) GND 3) MISO 4) MOSI 5) SCLK 6) SS or SCS 7) INT 8) RESET

Pyro Sensor

33

34

#define LED 13 #define PYRO 9 int val = 0; void setup() { pinMode(LED, OUTPUT); pinMode(PYRO, INPUT); //Serial.begin(9600); } void loop(){ val = digitalRead(PYRO); // val = analogRead(0); if (val == HIGH) { digitalWrite(LED, HIGH); } else { digitalWrite(LED, LOW); } // Serial.println(val); }

34

35

VDIP1 Module
http://www.saelig.com/miva/merchant.mvc?Screen=PROD&Product_Code=UI1E3&Category_Code=UI1E http://www.arduino.cc/playground/Main/UsbMemory http://www.vinculum.com/documents/schematics/VDIP1%20Schematic%20Prints.pdf http://www.dontronics-shop.com/ftdi-vdip1.html http://www.picbasic.co.uk/forum/showthread.php?t=7700 http://www.vinculum.com/prd_vnc1l.html http://www.vinculum.com/downloads.html

The VNC1L, is the first device to be released from FTDI's new Vinculum range of Slave/Host USB Controllers. Vinculum now makes it even easier to integrate USB functionality into your products and with the VNC1L device you can implement USB Host Controller functionality in no time at all. As you would expect the device features FTDI's award winning, tried and tested, firmware which is stored on-board in flash and can easily be updated ensuring your products are future proof. The VNC1L USB Host Controller ICs not only handle the USB Host Interface, and data transfer functions but owing to the inbuilt 8/32-bit MCU and embedded Flash memory, VNC1L encapsulates the USB device classes as well. When interfacing to mass storage devices such as USB Flash drives, VNC1L also transparently handles the FAT file structure communicating via UART, SPI or parallel FIFO interfaces via a simple to implement command set. The VNC1L device features two USB Ports which can be individually configured by firmware as Host or Slave ports. VNC1L brings cost effective USB Host capability to products that previously did not have the hardware resources available. We anticipate that these devices will be especially popular for adding USB Flash drive connectivity to a wide range of consumer and industrial products. As VNC1L comes complete with FTDI's in-house developed firmware, there are no USB software stacks to license, indeed, no knowledge of USB is required to use these devices.

35

36

With the VNC1L you can now connect USB Flash Drives to MCU's via a UART or parallel FIFO interface or connect Digital Cameras, PDA's and other USB slave peripherals to USB Flash Keys and other USB slave devices in stand-alone mode. The FTDI Vinculum VDIP1 module appears to be a simple way of adding USB memory cards to PIC projects for massive storage. Via common USB multimedia card readers, Compact Flash, SD/MMC and other Memory Sticks can also be written to. WARNING - Regardless of when and where you bought your VDIP1 modules, get the latest code first (ver 3.61 as at 11 December 2007). I had patchy success with inconsistent operation until I flashed the latest code into the VDIP1 module. You simply load the appropriately named file to a clean memory stick and plug the stick into the VDIP1. The bootloader will take over and load the code. If you blow it, which I did, the VPROG application allows the code to be added via a PC COM port and a max232 level converter. Schematic details. Data TO the VDIP1 destined for the USB stick is sent into pin 8 called RXD. Data FROM the VDIP1 is ignored in this application. VDIP1 pin 9 called RTS is an output from the VDIP1. It is monitored by the PIC and data from the PIC is only sent while RTS is LOW. VDIP1 pin 10 called CTS is an input to the VDIP1 and is pulled low by the PIC and left low throughout. The VDIP1 RESET line, pin 22, needs to float normally but every now and then a manual reset is required. This could either be by code or an external pushbutton. Put the button in - you are going to need it. +5 volts is applied to VDIP1 pin 1. VDIP pins 7 and 18 are tied to ground. All other pins are floating. Setup for simplest UART mode. a/ The interface defaults to 9600 bps, 8N1 TTL where steady mark/idle is +v and a space bit is zero volts. Use SEROUT 'driven true' mode 2. b/ Set the jumpers to be both 1-2 or both 2-3 for UART mode. c/ You can permanently ground the VDIP1 pin 10 called CTS. This pin must be low before the VDIP1 will work. d/ You MUST monitor the VDIP1 pin 9, called RTS. Do not tie RTS to CTS as shown in the Circuit Cellar article - that only sometimes works and will cost you hours trying to work out why. RTS is low when ready to accept data and when RTS goes high you must stop sending data to the VDIP1. If you continue to send data, the VDIP1 will likely lock up and need a manual reset or power cycle before it comes good. Any active file
36

37

on the USB stick will be left open and appear empty when viewed on a PC. e/ RTS going high apparently indicates there are only 32 character positions left in the 64 character buffer. RTS also goes high immediately after issuing some commands. Just which commands seems to vary with brand and size of card. For example, the WRF 26 <cr> in the code below causes pin 9 RTS to immediately go high with a Rundisk 2 GB memory stick but RTS does NOT go high with a Verbatim 512 MB stick. f/ Every command must be terminated with a carriage return. No line feed is necessary. g/ You must count your characters very carefully. The WRF nn command tells the VDIP1 that nn characters are to be written to the memory stick. If you send more than nn the VDIP1 module will harmlessly truncate the data and the file will be readable but will be missing those overflow characters. If you don't send enough characters however, the VDIP1 will hang waiting for the balance. Subsequent commands to close the file will be lost and the file will remain open and be unreadable or empty. h/ The following code creates a new directory called TESTFILE (8 character limit) and creates a file in that directory called Test1.txt. It then opens Test1.txt, writes a short header block and closes the file. It then opens the file a second time and appends 10,330 bytes to Test1.txt and closes the file. Finally it opens it, appends a trailer and closes Test1.txt. Only 8.3 format file and directory names are allowed. All file names are changed to upper case by the VDIP1. i/ I have put a flow control test after every command. This is probably overkill but I don't know what are the fast and what are the slow commands. These appear to vary between brands and memory sizes so I have left them in. This code appears to be universal and has worked reliably with 6 different brands and sizes of USB stick. It has also been tested with Compact Flash and SD/MMC cards plugged into a USB multicard reader. The VDIP1 does NOT work with an external hard drive as the storage medium.

37

38

int incomingByte=0; int fileNumber=1; int noOfChars; long int valToWrite; char activityToLog; long int x; long int startLogTime = 0; void setup() { Serial.begin(9600); data rate to 9600 bps Serial.print("IPA"); ascii numbers the code easily!) Serial.print(13, BYTE); vdip its end of message } // opens serial port, sets // sets the vdip to use //(so I can read them in // return character to tell

void loop() { if (Serial.available() > 0) { // read the incoming byte incomingByte = Serial.read(); if (incomingByte=='1'){ Serial.print("OPW LOG%"); file - named Serial.print(fileNumber); round - .TXT is for the computer Serial.print(".TXT"); the name so I can files that it has created that may be on already Serial.print(13, BYTE); } if (incomingByte=='2'){ Serial.print("CLF LOG%"); Serial.print(fileNumber); Serial.print(".TXT"); Serial.print(13, BYTE); } if (incomingByte=='3'){ Serial.print("DIR"); the memory stick Serial.print(13, BYTE); the file LOG%1.TXT } if (incomingByte=='5'){ activityToLog='P'; different letters to label my time stamps // if it receives a 2 // it closes the file // LOG%1.TXT // return character // if it receives 3 // lists the directory on // which will now include // if it receives a 1 // open to write creates a // LOG%1.TXT first time // I have used the % sign in //search the disk for log //so as not to overwrite any // return character

// I will be using

38

39 valToWrite=millis() - startLogTime; // time since we started logging noOfChars=1; x=valToWrite; // need to copy valToWrite as getting no of characters will consume it while (x>= 10){ // counts the characters in the number noOfChars++; // thanks to D Mellis for this bit x/=10; } noOfChars +=2; //add 2 to the num as will also write the letter P and a return character Serial.print("WRF "); needs to have been opened to write first) Serial.print(noOfChars); told how many characters will be written Serial.print(13, BYTE); command is finished Serial.print(activityToLog); to write Serial.print(valToWrite); Serial.print(13, BYTE); the contents of the file (so each entry appears on } if (incomingByte=='6'){ fileNumber++; other files } if (incomingByte=='7'){ if (fileNumber>0){ ones fileNumber--; } } if (incomingByte=='8'){ Serial.print("RD LOG%"); of named file Serial.print(fileNumber); Serial.print(".TXT"); Serial.print(13, BYTE); }} if (incomingByte=='9'){ startLogTime=millis(); } } //write to file (file //needs to then be //return to say //followed by the info //write a return to a new line)

//so we can create

//and look at previous

//reads the contents

// reset timing

39

40

Color Mixing

http://todbot.com/blog/bionicarduino/

/*

40

41 * Code for cross-fading 3 LEDs, red, green and blue, or one tri-color LED, using PWM * The program cross-fades slowly from red to green, green to blue, and blue to red * The debugging code assumes Arduino 0004, as it uses the new Serial.begin()-style functions * originally "dimmingLEDs" by Clay Shirky <clay.shirky@nyu.edu> */ // Output int a = 9; int b = 10; int c = 11; int redPin = 6; int greenPin = 5; int bluePin = 3; // Red LED, connected to digital pin 9 // Green LED, connected to digital pin 10 // Blue LED, connected to digital pin 11

// Program variables int redVal = 255; // Variables to store the values to send to the pins int greenVal = 1; // Initial values are Red full, Green and Blue off int blueVal = 1; int i = 0; // Loop counter int wait = 15; // 50ms (.05 second) delay; shorten for faster fades int DEBUG = 0; // DEBUG counter; if set to 1, will write values back via serial void setup() { pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); pinMode(a, OUTPUT); pinMode(b, OUTPUT); pinMode(c, OUTPUT); if (DEBUG) { debugging... Serial.begin(9600); } } // If we want to see the pin values for // ...set up the serial ouput on 0004 style

// sets the pins as output

// Main program void loop() { i += 1; // Increment counter if (i < 255) // First phase of fades { redVal -= 1; // Red down greenVal += 1; // Green up blueVal = 1; // Blue low } else if (i < 509) // Second phase of fades {

41

42 redVal = 1; // Red low greenVal -= 1; // Green down blueVal += 1; // Blue up } else if (i < 763) // Third phase of fades { redVal += 1; // Red up greenVal = 1; // Green lo2 blueVal -= 1; // Blue down } else // Re-set the counter, and start the fades again { i = 1; } // we do "255-redVal" // LEDs are hooked up analogWrite(redPin, pins analogWrite(greenPin, analogWrite(bluePin, instead of just "redVal" because the to +5V instead of Gnd 255 - redVal); // Write current values to LED 255 - greenVal); 255 - blueVal);

analogWrite(a, 255 - redVal); // Write current values to LED pins analogWrite(b, 255 - greenVal); analogWrite(c, 255 - blueVal); if (DEBUG) { // If we want to read the output DEBUG += 1; // Increment the DEBUG counter if (DEBUG > 10) { // Print every 10 loops DEBUG = 1; // Reset the counter Serial.print(i); // Serial commands in 0004 style Serial.print("\t"); // Print a tab Serial.print("R:"); // Indicate that output is red value Serial.print(redVal); // Print red value Serial.print("\t"); // Print a tab Serial.print("G:"); // Repeat for green and blue... Serial.print(greenVal); Serial.print("\t"); Serial.print("B:"); Serial.println(blueVal); // println, to end with a carriage return } } delay(wait); // Pause for 'wait' milliseconds before resuming the loop }

42

43

USB

43

44

Interfacing SD / MMC Card with SPI


Filesystem
SD-Card must be formatted with FAT-16 Filesystem with only a single partition on it.

44

45

45

46

http://www.electronics-lab.com/articles/LM317/ http://www.cpemma.co.uk/317calc.html Calculate LM317 Resistor Values This calculator is used to find the value of the voltage adjustment resistor required to set the output of an LM317 to a specified level. Typically R1 is 220 ohms or 240 ohms, but it could be some other value. Check the Data Sheet for more information regarding this. Select a value for R2 and hit the Calculate button. The LM317 output value is reported in volts. Note: The input voltage to the LM317 must be at least 1.5v greater than the output voltage. Note2: You can get ridiculous values with the right combination of R1 and R2. Please note the actual capability of the device from the Data Sheet.

46

47

DS1307 DIP-8 Dallas Maxim 64x8 Serial Real-Time Clock


http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1191209057/15 http://www.glacialwanderer.com/hobbyrobotics/?p=12 http://em.typodemon.com/wordpress/?p=149 http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1198881858 http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1233375650 http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1235070596/9 http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1191209057/15

// // Maurice Ribble // 4-17-2008 // http://www.glacialwanderer.com/hobbyrobotics/?p=12 // // // // // This code tests the DS1307 Real Time clock on the Arduino board. The ds1307 works in binary coded decimal or BCD. You can look up bcd in google if you aren't familior with it. There can output a square wave, but I don't expose that in this code. See the ds1307 for it's full capabilities.

#include "Wire.h" #define DS1307_I2C_ADDRESS 0x68 // Convert normal decimal numbers to binary coded decimal byte decToBcd(byte val) { return ( (val/10*16) + (val%10) ); } // Convert binary coded decimal to normal decimal numbers byte bcdToDec(byte val) { return ( (val/16*10) + (val%16) ); } // Stops the DS1307, but it has the side effect of setting seconds to 0 // Probably only want to use this for testing /*void stopDs1307() { Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.send(0); Wire.send(0x80);

47

48 Wire.endTransmission(); }*/ // 1) Sets the date and time on the ds1307 // 2) Starts the clock // 3) Sets hour mode to 24 hour clock // Assumes you're passing in valid numbers void setDateDs1307(byte second, // 0-59 byte minute, // 0-59 byte hour, // 1-23 byte dayOfWeek, // 1-7 byte dayOfMonth, // 1-28/29/30/31 byte month, // 1-12 byte year) // 0-99 { Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.send(0); Wire.send(decToBcd(second)); // 0 to bit 7 starts the clock Wire.send(decToBcd(minute)); Wire.send(decToBcd(hour)); // If you want 12 hour am/pm you need to set // bit 6 (also need to change readDateDs1307) Wire.send(decToBcd(dayOfWeek)); Wire.send(decToBcd(dayOfMonth)); Wire.send(decToBcd(month)); Wire.send(decToBcd(year)); Wire.endTransmission(); } // Gets the date and time from the ds1307 void getDateDs1307(byte *second, byte *minute, byte *hour, byte *dayOfWeek, byte *dayOfMonth, byte *month, byte *year) { // Reset the register pointer Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.send(0); Wire.endTransmission(); Wire.requestFrom(DS1307_I2C_ADDRESS, 7); // A few of these need masks because certain bits are control bits *second = bcdToDec(Wire.receive() & 0x7f); *minute = bcdToDec(Wire.receive()); *hour = bcdToDec(Wire.receive() & 0x3f); // Need to change this if 12 hour am/pm *dayOfWeek = bcdToDec(Wire.receive()); *dayOfMonth = bcdToDec(Wire.receive()); *month = bcdToDec(Wire.receive()); *year = bcdToDec(Wire.receive()); }

48

49 void setup() { byte second, minute, hour, dayOfWeek, dayOfMonth, month, year; Wire.begin(); Serial.begin(9600); // Change these values to what you want to set your clock to. // You probably only want to set your clock once and then remove // the setDateDs1307 call. second = 45; minute = 3; hour = 7; dayOfWeek = 5; dayOfMonth = 17; month = 4; year = 8; setDateDs1307(second, minute, hour, dayOfWeek, dayOfMonth, month, year); } void loop() { byte second, minute, hour, dayOfWeek, dayOfMonth, month, year; getDateDs1307(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year); Serial.print(hour, DEC); Serial.print(":"); Serial.print(minute, DEC); Serial.print(":"); Serial.print(second, DEC); Serial.print(" "); Serial.print(month, DEC); Serial.print("/"); Serial.print(dayOfMonth, DEC); Serial.print("/"); Serial.print(year, DEC); Serial.print(" Day_of_week:"); Serial.println(dayOfWeek, DEC); delay(1000); }

49

50

Writing a Library for Arduino


This document explains how to create a library for Arduino. It starts with a sketch with a sketch for flashing Morse code and explains how to convert its functions into a library. This allows other people to easily use the code that you've written and to easily update it as you improve the library. We start with a sketch that does simple Morse code: int pin = 13; void setup() { pinMode(pin, OUTPUT); } void loop() { dot(); dot(); dot(); dash(); dash(); dash(); dot(); dot(); dot(); delay(3000); } void dot() { digitalWrite(pin, HIGH); delay(250); digitalWrite(pin, LOW); delay(250); } void dash() { digitalWrite(pin, HIGH); delay(1000); digitalWrite(pin, LOW); delay(250); } If you run this sketch, it will flash out the code for SOS (a distress call) on pin 13. The sketch has a few different parts that we'll need to bring into our library. First, of course, we have the dot() and dash() functions that do the actual blinking. Second, there's the ledPin variable which the functions use to determine which pin to use. Finally, there's the call to pinMode() that initializes the pin as an output. Let's start turning the sketch into a library! You need at least two files for a library: a header file (w/ the extension .h) and the source file (w/ extension .cpp). The header file has definitions for the library: basically a listing of everything that's inside; while the source file has the actual code. We'll call our library "Morse", so our header file will be Morse.h. Let's take a look at what goes in it. It might seem a bit strange at first, but it will make more sense once you see the source file that goes with it. The core of the header file consists of a line for each function in the library, wrapped up in a class along with any variables you need: class Morse { public: Morse(int pin); void dot(); void dash(); private:

50

51 int _pin; }; A class is simply a collection of functions and variables that are all kept together in one place. These functions and variables can be public, meaning that they can be accessed by people using your library, or private, meaning they can only be accessed from within the class itself. Each class has a special function known as a constructor, which is used to create an instance of the class. The constructor has the same name as the class, and no return type. You need a couple of other things in the header file. One is an #include statement that gives you access to the standard types and constants of the Arduino language (this is automatically added to normal sketches, but not to libraries). It looks like this (and goes above the class definition given previously): #include "WConstants.h" Finally, it's common to wrap the whole header file up in a weird looking construct: #ifndef Morse_h #define Morse_h // the #include statment and code go here... #endif Basically, this prevents problems if someone accidently #include's your library twice. Finally, you usually put a comment at the top of the library with its name, a short description of what it does, who wrote it, the date, and the license. Let's take a look at the complete header file: /* Morse.h - Library for flashing Morse code. Created by David A. Mellis, November 2, 2007. Released into the public domain. */ #ifndef Morse_h #define Morse_h #include "WConstants.h" class Morse { public: Morse(int pin); void dot(); void dash(); private: int _pin; }; #endif Now let's go through the various parts of the source file, Morse.cpp. First comes a couple of #include statements. These give the rest of the code access to the standard Arduino functions, and to the definitions in your header file: #include "WProgram.h" #include "Morse.h" Then comes the constructor. Again, this explains what should happen when someone creates an instance of your class. In this case, the user specifies which pin they would like to use. We configure the pin as an output save it into a private variable for use in the other functions:

51

52 Morse::Morse(int pin) { pinMode(pin, OUTPUT); _pin = pin; } There are a couple of strange things in this code. First is the Morse:: before the name of the function. This says that the function is part of the Morse class. You'll see this again in the other functions in the class. The second unusual thing is the underscore in the name of our private variable, _pin. This variable can actually have any name you want, as long as it matches the definition in the header file. Adding an underscore to the start of the name is a common convention to make it clear which variables are private, and also to distinguish the name from that of the argument to the function (pin in this case). Next comes the actual code from the sketch that you're turning into a library (finally!). It looks pretty much the same, except with Morse:: in front of the names of the functions, and _pin instead of pin: void Morse::dot() { digitalWrite(_pin, HIGH); delay(250); digitalWrite(_pin, LOW); delay(250); } void Morse::dash() { digitalWrite(_pin, HIGH); delay(1000); digitalWrite(_pin, LOW); delay(250); } Finally, it's typical to include the comment header at the top of the source file as well. Let's see the whole thing: /* Morse.cpp - Library for flashing Morse code. Created by David A. Mellis, November 2, 2007. Released into the public domain. */ #include "WProgram.h" #include "Morse.h" Morse::Morse(int pin) { pinMode(pin, OUTPUT); _pin = pin; } void Morse::dot() { digitalWrite(_pin, HIGH); delay(250); digitalWrite(_pin, LOW); delay(250); } void Morse::dash() {

52

53 digitalWrite(_pin, HIGH); delay(1000); digitalWrite(_pin, LOW); delay(250);

And that's all you need (there's some other nice optional stuff, but we'll talk about that later). Let's see how you use the library. First, make a Morse directory inside of the hardware/libraries sub-directory of the Arduino application directory. Copy or move the Morse.h and Morse.cpp files into that directory. Now launch the Arduino environment. When it starts, it will compile your library, generating an object file (Morse.o) and displaying any warnings or errors. If you open the Sketch > Import Library menu, you should see Morse inside. As you work on your library, you'll need to delete the Morse.o file and relaunch the Arduino environment (or pick a new board from the Tools > Boards menu) to recompile your library. If the library doesn't seem to build, make sure that the files really end in .cpp and .h (with no extra .pde or .txt extension, for example). Let's see how we can replicate our old SOS sketch using the new library: #include <Morse.h> Morse morse(13); void setup() { } void loop() { morse.dot(); morse.dot(); morse.dot(); morse.dash(); morse.dash(); morse.dash(); morse.dot(); morse.dot(); morse.dot(); delay(3000); } There are a few differences from the old sketch (besides the fact that some of the code has moved to a library). First, we've added an #include statement to the top of the sketch. This makes the Morse library available to the sketch and includes it in the code sent to the board. That means if you no longer need a library in a sketch, you should delete the #include statement to save space. Second, we now create an instance of the Morse class called morse: Morse morse(13); When this line gets executed (which actually happens even before the setup() function), the constructor for the Morse class will be called, and passed the argument you've given here (in this case, just 13). Notice that our setup() is now empty; that's because the call to pinMode() happens inside the library (when the instance is constructed). Finally, to call the dot() and dash() functions, we need to prefix them with morse. - the name of the instance we want to use. We could have multiple instances of the Morse class, each on their own pin stored in the _pin private variable of that instance. By calling a function on a particular instance, we specify which instance's variables should be used during that call to a function. That is, if we had both: Morse morse(13); Morse morse2(12); then inside a call to morse2.dot(), _pin would be 12. If you tried the new sketch, you probably noticed that nothing from our library was recognized by the environment and highlighted in color. Unfortunately, the Arduino software can't automatically figure out what you've define in your library (though it would be a nice feature to have), so you have to give it a little help. To do this, create a file called keywords.txt in the Morse directory. It should look like this:

53

54 Morse dash dot KEYWORD1 KEYWORD2 KEYWORD2

Each line has the name of the keyword, followed by a tab (not spaces), followed by the kind of keyword. Classes should be KEYWORD1 and are colored orange; functions should be KEYWORD2 and will be brown. You'll have to restart the Arduino environment to get it to recognize the new keywords. It's also nice to provide people with an example sketch that uses your library. To do this, create an examples directory inside the Morse directory. Then, move or copy the directory containing the sketch (let's call it SOS) we wrote above into the examples directory. (You can find the sketch using the Sketch > Show Sketch Folder command.) If you restart the Arduino environment (this is the last time, I promise) - you'll see a Library-Morse item inside the File > Sketchbook > Examples menu containing your example. You might want to add some comments that better explain how to use your library.

54

55

LiquidCrystal()
Description
Creates a variable of type LiquidCrystal.

Syntax
LiquidCrystal(rs, rw, enable, d4, d5, d6, d7) LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)

Parameters
rs: the number of the Arduino pin that is connected to the RS pin on the LCD rw: the number of the Arduino pin that is connected to the RW pin on the LCD enable: the number of the Arduino pin that is connected to the enable pin on the LCD d0, d1, d2, d3, d4, d5, d6, d7: the numbers of the Arduino pins that are connected to the corresponding data pins on the LCD. d0, d1, d2, and d3 are optional; if omitted, the LCD will be controlled using only the four data lines (d4, d5, d6, d7).

Example
#include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2); void setup() { lcd.print("hello, world!"); } void loop() {} Reference Home Corrections, suggestions, and new documentation should be posted to the Forum. The text of the Arduino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.

55

56

http://www.reconnsworld.com/ir_ultrasonic_basicirdetectemit.html

56

57

Simple IR Distance Sensor Tutorial

http://www.arduino.cc/playground/Main/PanasonicIrSensor Paralax books: Robotics with the Boe-Bot pag. 238 Understanding Signals pag.137 Programming Robot Controllers pag. 229

Introduction
This tutorial explains how to make a simple IR distance sensor using a Panasonic pna4602m IR sensor and an IR led.

Hardware Requirments
1. 2. 3. 4. 5. IR led (1) 1.1 ohm brown-brown-red 2 ohm red-black-red Panasonic pna4602m IR sensor (1) 220 ohm red-red-brown

Theory and circuits


For the theory behind this sensor, and for information about setting up the circuit see the boe bot instruction manual page 249. The circuit schematics are on page 252. http://parallax.com/Portals/0/Downloads/docs/books/edu/Roboticsv2_2.pdf In a nutshell, you have to output a 38.5khZ square wave to the IR led for 1 millisecond, and then check the state of the sensor pin. If the pin is low, then an object is detected. Note that the schematic in the boe bot manual recommends a 1k resistor for the IR led. I chose to use a 220 ohm resistor. With a 220 ohm resistor, this sensor can detect my hand up to about 30cm(1 foot) away. If you use a higher value resistor, then the sensor has less range.

57

58

Arduino Code
//define pins. I used pins 4 and 5 #define irLedPin 9 // IR Led on this pin #define irSensorPin 2 // IR sensor on this pin #define led 13 int irRead(int readPin, int triggerPin); //function prototype void setup() { pinMode(irSensorPin, INPUT); pinMode(irLedPin, OUTPUT); pinMode(led,OUTPUT); Serial.begin(9600); // prints title with ending line break Serial.println("Program Starting"); // wait for the long string to be sent delay(100); } void loop() { if (irRead(irSensorPin, irLedPin) == 0) digitalWrite(led, HIGH); else digitalWrite(led, LOW); Serial.println(irRead(irSensorPin, irLedPin)); //display the results delay(10); //wait for the string to be sent

/*********************************************************************** * This function can be used with a panasonic pna4602m ir sensor * it returns a zero if something is detected by the sensor, and a 1 otherwise * The function bit bangs a 38.5khZ waveform to an IR led connected to the * triggerPin for 1 millisecond, and then reads the IR sensor pin to see if * the reflected IR has been detected ***********************************************************************/ int irRead(int readPin, int triggerPin) { int halfPeriod = 13; //one period at 38.5khZ is aproximately 26 microseconds int cycles = 38; //26 microseconds * 38 is more or less 1 millisecond int i; for (i=0; i <=cycles; i++) { digitalWrite(triggerPin, HIGH); delayMicroseconds(halfPeriod); digitalWrite(triggerPin, LOW); delayMicroseconds(halfPeriod - 1); // - 1 to make up for digitaWrite overhead 58

59 } return digitalRead(readPin);

59

60

Infra Red

+ led

R L300 a

Regra Para descobrir a Resistencia necessaria para reduziar a voltagem R = (B - V)/I = (4.5 - 3.6) / .02 = 45 ohm

60

61

PIR Motion Sensor


sku: SEN-08630

http://www.sparkfun.com/commerce/product_info.php?products_id=8630 http://www.seeedstudio.com/depot/pir-motion-sensor-module-p-74.html Description: This is a simple to use motion sensor. Power it up and wait 1-2 seconds for the sensor to get a snapshot of the still room. If anything moves after that period, the 'alarm' pin will go low. Red wire is power (5 to 12V). Brown wire is GND. Black wire is open collector Alarm. This unit works great from 5 to 12V (datasheet shows 12V). You can also install a jumper wire past the 5V regulator on board to make this unit work at 3.3V. Sensor uses 1.6mA@3.3V.

Exemplo 1 #define LED 13 #define pirPin 12 int val = 0; void setup() { pinMode(LED, OUTPUT); pinMode(pirPin, INPUT); digitalWrite(pirPin, HIGH); Serial.begin(9600); } void loop(){ val = digitalRead(pirPin); delay(10); Serial.println(val,DEC); if (val == LOW) { digitalWrite(LED, HIGH); } else { digitalWrite(LED, LOW); }

61

62 Exemplo 2 http://www.arduino.cc/playground/Code/PIRsense /* * * ////////////////////////////////////////////////// * //making sense of the Parallax PIR sensor's output * ////////////////////////////////////////////////// * * Switches a LED according to the state of the sensors output pin. * Determines the beginning and end of continuous motion sequences. * * @author: Kristian Gohlke / krigoo (_) gmail (_) com / http://krx.at * @date: 3. September 2006 * * kr1 (cleft) 2006 * released under a creative commons "Attribution-NonCommercialShareAlike 2.0" license * http://creativecommons.org/licenses/by-nc-sa/2.0/de/ * * * The Parallax PIR Sensor is an easy to use digital infrared motion sensor module. * (http://www.parallax.com/detail.asp?product_id=555-28027) * * The sensor?s output pin goes to HIGH if motion is present. * However, even if motion is present it goes to LOW from time to time, * which might give the impression no motion is present. * This program deals with this issue by ignoring LOW-phases shorter than a given time, * assuming continuous motion is present during these phases. * */ ///////////////////////////// //VARS //the time we give the sensor to calibrate (10-60 secs according to the datasheet) int calibrationTime = 10; //the time when the sensor outputs a low impulse long unsigned int lowIn; //the amount of milliseconds the sensor has to be low //before we assume all motion has stopped long unsigned int pause = 5000; boolean lockLow = true; boolean takeLowTime; int pirPin = 12; output int ledPin = 13; //the digital pin connected to the PIR sensor's

/////////////////////////////

62

63 //SETUP void setup(){ Serial.begin(9600); pinMode(pirPin, INPUT); pinMode(ledPin, OUTPUT); digitalWrite(pirPin, HIGH); //give the sensor some time to calibrate Serial.print("calibrating sensor "); for(int i = 0; i < calibrationTime; i++){ Serial.print("."); delay(1000); } Serial.println(" done"); Serial.println("SENSOR ACTIVE"); delay(50); } //////////////////////////// //LOOP void loop(){ if(digitalRead(pirPin) == LOW){ digitalWrite(ledPin, HIGH); //the led visualizes the sensors output pin state if(lockLow){ //makes sure we wait for a transition to LOW before any further output is made: lockLow = false; Serial.println("---"); Serial.print("motion detected at "); Serial.print(millis()/1000); Serial.println(" sec"); delay(50); } takeLowTime = true; } if(digitalRead(pirPin) == HIGH){ digitalWrite(ledPin, LOW); //the led visualizes the sensors output pin state if(takeLowTime){ lowIn = millis(); //save the time of the transition from high to LOW takeLowTime = false; //make sure this is only done at the start of a LOW phase } //if the sensor is low for more than the given pause, //we assume that no more motion is going to happen if(!lockLow && millis() - lowIn > pause){ //makes sure this block of code is only executed again after //a new motion sequence has been detected lockLow = true; Serial.print("motion ended at "); //output Serial.print((millis() - pause)/1000); Serial.println(" sec");

63

64 delay(50); }

} }

64

65

I2C EEPROM - 256kbit


sku: COM-00525

Description: 2 Wire Serial Communication (I2C) EEPROM - The back bone of any microprocessor project. These 8 pin chips need only two wires to communicate and retain their data even with power failure. Use the 256K EEPROM for some serious data storage!

http://www.ghettohax.com/2009/02/i2c-eeprom-for-arduino.html http://lusorobotica.com/index.php/topic,461.msg2738.html ----------------------------------------------------------------------http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1229523445 http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1214682544/22 http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1233314173/4 http://lusorobotica.com/index.php/topic,460.0.html //http://10kohms.com/arduino-external-eeprom-24lc256 #include <Wire.h> #define disk1 0x50 //Address of 24LC256 eeprom chip

void setup(void){ Serial.begin(9600); Wire.begin(); unsigned int address = 0; writeEEPROM(disk1, address, 'F'); Serial.print(readEEPROM(disk1, address), BYTE); } void loop(){} void writeEEPROM(int deviceaddress, unsigned int eeaddress, byte data ) { Wire.beginTransmission(deviceaddress); Wire.send((int)(eeaddress >> 8)); // MSB Wire.send((int)(eeaddress & 0xFF)); // LSB Wire.send(data);

65

66 Wire.endTransmission(); delay(5);

byte readEEPROM(int deviceaddress, unsigned int eeaddress ) { byte rdata = 0xFF; Wire.beginTransmission(deviceaddress); Wire.send((int)(eeaddress >> 8)); // MSB Wire.send((int)(eeaddress & 0xFF)); // LSB Wire.endTransmission(); Wire.requestFrom(deviceaddress,1); if (Wire.available()) rdata = Wire.receive(); return rdata; }

Serial to Parallel Shifting-Out with a 74HC595


http://www.arduino.cc/en/Tutorial/ShiftOut http://www.codeproject.com/KB/system/ArduinoShiftRegisters.aspx
Started by Carlyn Maw and Tom Igoe Nov, 06 Shifting Out & the 595 chip

66

67 At sometime or another you may run out of pins on your Arduino board and need to extend it with shift registers. This example is based on the 74HC595. The datasheet refers to the 74HC595 as an "8-bit serial-in, serial or parallel-out shift register with output latches; 3-state." In other words, you can use it to control 8 outputs at a time while only taking up a few pins on your microcontroller. You can link multiple registers together to extend your output even more. (Users may also wish to search for other driver chips with "595" or "596" in their part numbers, there are many. The STP16C596 for example will drive 16 LED's and eliminates the series resistors with built-in constant current sources.) How this all works is through something called "synchronous serial communication," i.e. you can pulse one pin up and down thereby communicating a data byte to the register bit by bit. It's by pulsing second pin, the clock pin, that you delineate between bits. This is in contrast to using the "asynchronous serial communication" of the Serial.begin() function which relies on the sender and the receiver to be set independently to an agreed upon specified data rate. Once the whole byte is transmitted to the register the HIGH or LOW messages held in each bit get parceled out to each of the individual output pins. This is the "parallel output" part, having all the pins do what you want them to do all at once. The "serial output" part of this component comes from its extra pin which can pass the serial information received from the microcontroller out again unchanged. This means you can transmit 16 bits in a row (2 bytes) and the first 8 will flow through the first register into the second register and be expressed there. You can learn to do that from the second example. "3 states" refers to the fact that you can set the output pins as either high, low or "high impedance." Unlike the HIGH and LOW states, you can"t set pins to their high impedance state individually. You can only set the whole chip together. This is a pretty specialized thing to do -- Think of an LED array that might need to be controlled by completely different microcontrollers depending on a specific mode setting built into your project. Neither example takes advantage of this feature and you won"t usually need to worry about getting a chip that has it.

67

68

68

69

69

70

70

71

71

72

72

73

Arduino + Bluetooth + Android


http://www.sparkfun.com/products/582 http://www.sparkfun.com/products/10336 http://bebop.cc/blog/2011/05/30/arduino-bluetooth-android/ http://lucasfragomeni.com/arduino/2011-01/arduino-bluetooth-android/ https://github.com/lucasfragomeni/arduino/tree/master/RouchBT/design http://www.amarino-toolkit.net/ https://github.com/lucasfragomeni/arduino/tree/master/RouchBT http://lucasfragomeni.com/arduino/ http://lucasfragomeni.com/arduino/2011-01/arduino-bluetooth-android/

73

74

Controlando motores usando o SN754410NE


http://www.arduino.cc/en/Tutorial/ShiftOut http://www.codeproject.com/KB/system/ArduinoShiftRegisters.aspx As you are looking at the SN754410NE chip, you will notice a u-shaped notch at one end. This will help to identify pin 1. Pins 1, 9, and 16 are +5V Pin 8 is +12V and will run the +12V DC motors. Pins 4, 5, 12, and 13 are for GND DC Motors have two hook ups on them. If you hooked one up straight to the source power you would have one lead going to positive and one lead going to GND. For our H-Bridge driver, you will hook the left motor leads to pin 3 & 6. The right motor leads will hook up to pins 11 & 14. Connect h-bridge pin 2 to the Arduino digital pin 2, and h-bridge pin 7 to Arduino digital pin 3. Connect h-bridge pin 10 to Arduino digital pin 8, and h-bridge pin 15 to Arduino digital pin 7

74

75

http://bebop.cc/blog/2011/05/30/arduino-bluetooth-android/

75

76

1-Dual Motor Driver with Arduino using a SN754410NE Quad Half H-Bridge
// Use this code to test your motor with the Arduino board: // if you need PWM, just use the PWM outputs on the Arduino // and instead of digitalWrite, you should use the analogWrite command // Motors int motor_left[] = {2, 3}; int motor_right[] = {7, 8}; int ledPin = 13; // LED connected to digital pin 13 // Setup void setup() { Serial.begin(9600); // Setup motors int i; for(i = 0; i < 2; i++){ pinMode(motor_left[i], OUTPUT); pinMode(motor_right[i], OUTPUT); pinMode(ledPin, OUTPUT); } } // Loop void loop() { drive_forward(); delay(1000); motor_stop(); Serial.println("1"); drive_backward(); delay(1000); motor_stop(); Serial.println("2"); turn_left(); delay(1000); motor_stop(); Serial.println("3"); turn_right(); delay(1000); motor_stop(); Serial.println("4"); motor_stop(); 76

77 delay(1000); motor_stop(); Serial.println("5"); digitalWrite(ledPin, HIGH); delay(1000); digitalWrite(ledPin, LOW); delay(1000); } // Drive void motor_stop(){ digitalWrite(motor_left[0], LOW); digitalWrite(motor_left[1], LOW); digitalWrite(motor_right[0], LOW); digitalWrite(motor_right[1], LOW); delay(25); } void drive_forward(){ digitalWrite(motor_left[0], HIGH); digitalWrite(motor_left[1], LOW); digitalWrite(motor_right[0], HIGH); digitalWrite(motor_right[1], LOW); } void drive_backward(){ digitalWrite(motor_left[0], LOW); digitalWrite(motor_left[1], HIGH); digitalWrite(motor_right[0], LOW); digitalWrite(motor_right[1], HIGH); } void turn_left(){ digitalWrite(motor_left[0], LOW); digitalWrite(motor_left[1], HIGH); digitalWrite(motor_right[0], HIGH); digitalWrite(motor_right[1], LOW); } void turn_right(){ digitalWrite(motor_left[0], HIGH); digitalWrite(motor_left[1], LOW); digitalWrite(motor_right[0], LOW); digitalWrite(motor_right[1], HIGH); } // set the LED on // wait for a second // set the LED off // wait for a second

77

78

2-Controlando um motor com potenciometro


/* * Arduino code for SN754410 H-bridge * motor driver control. A potentiometer's * 270 degree rotational angle is used to * control a DC motor in the following way: * 0-135 degrees - motor runs forward, speed * getting slower the higher the angle, motor * stops at 135 degrees. * 135-270 degrees: motor runs backward, * speed is getting faster the higher the * angle, motor speed is 0 at 135 degrees. * copyleft Feb. 2008, Fabian Winkler */ int potPin = 0; // analog input pin 0 for the potentiometer int speedPin = 3; // H-bridge enable pin for speed control int motor1Pin = 6; // H-bridge leg 1 int motor2Pin = 7; // H-bridge leg 2 int ledPin = 13; // status LED int val = 0; // variable to store the value coming from the potentiometer void setup() { // set digital i/o pins as outputs: pinMode(speedPin, OUTPUT); pinMode(motor1Pin, OUTPUT); pinMode(motor2Pin, OUTPUT); pinMode(ledPin, OUTPUT); } void loop() { digitalWrite(ledPin, HIGH); // status LED is always on val = analogRead(potPin); // read the value from the potentiometer val = val/4; // convert 0-1023 range to 0-255 range if (val <= 127) { // put motor in forward motion digitalWrite(motor1Pin, LOW); // set leg 1 of the H-bridge low digitalWrite(motor2Pin, HIGH); // set leg 2 of the H-bridge high // control speed based on angle of potentiometer analogWrite(speedPin, 254-(val*2)); // output speed as PWM value // this value needs to go from 254 to 0 for input values //from 0 to 127 } else // put motor in backward motion { digitalWrite(motor1Pin, HIGH); // set leg 1 of the H-bridge high digitalWrite(motor2Pin, LOW); // set leg 2 of the H-bridge low // control speed based on angle of potentiometer analogWrite(speedPin, (val*2)-256); // output speed as PWM value // this value needs to go from 0 to 254 for input values // from 128 to 255 } }

78

79

3-MOTOR SHILD
// Motor Shield test // by NKC Electronics // Test Motor B

(SN755410)

//Motor A int dirbpinA = 13; // Direction pin for motor B is Digital 13 int speedbpinA = 10; // Speed pin for motor B is Digital 10 (PWM) //Motor B int dirbpinB = 12; // Direction pin for motor B is Digital 12 int speedbpinB = 9; // Speed pin for motor B is Digital 9 (PWM) int speed = 100; int dir = 0; void setup() { pinMode(dirbpinA, OUTPUT); pinMode(dirbpinB, OUTPUT); } void loop() { //Motor A ---------------------------------digitalWrite(dirbpinA, dir); // set direction analogWrite(speedbpinA, speed); // set speed (PWM) //Motor B ---------------------------------digitalWrite(dirbpinB, dir); // set direction analogWrite(speedbpinB, speed); // set speed (PWM) dir = ((dir == 0) ? 1 : 0); // change direction delay(20000); // 5 seconds }

79

80

4-http://www.smartsurfaces.net/hbridge
// Updated from http://itp.nyu.edu/physcomp/Labs/DCMotorControl int int int int int switchPin = 2; motor1Pin = 3; motor2Pin = 4; enablePin = 9; ledPin = 13; // // // // // switch input H-bridge leg 1 (pin 2, 1A) H-bridge leg 2 (pin 7, 2A) H-bridge enable pin LED

void setup() { // set the switch as an input: pinMode(switchPin, INPUT); // set all the other pins you're using as outputs: pinMode(motor1Pin, OUTPUT); pinMode(motor2Pin, OUTPUT); pinMode(enablePin, OUTPUT); pinMode(ledPin, OUTPUT); // set enablePin high so that motor can turn on: digitalWrite(enablePin, HIGH); // blink the LED 3 times. This should happen only once. // if you see the LED blink three times, it means that the module // reset itself,. probably because the motor caused a brownout // or a short. blink(ledPin, 3, 100);

void loop() { // if the switch is high, motor will turn on one direction: if (digitalRead(switchPin) == HIGH) { digitalWrite(motor1Pin, LOW); // set leg 1 of the H-bridge low digitalWrite(motor2Pin, HIGH); // set leg 2 of the H-bridge high } // if the switch is low, motor will turn in the other direction: else { digitalWrite(motor1Pin, HIGH); // set leg 1 of the H-bridge high digitalWrite(motor2Pin, LOW); // set leg 2 of the H-bridge low } } /* blinks an LED */ void blink(int whatPin, int howManyTimes, int milliSecs) { int i = 0; for ( i = 0; i < howManyTimes; i++) { digitalWrite(whatPin, HIGH); delay(milliSecs/2); digitalWrite(whatPin, LOW); delay(milliSecs/2); } }

80

81

How to program a AVR (arduino) with another arduino


http://www.instructables.com/id/How-to-program-a-AVR-arduino-with-another-arduin/
http://www.instructables.com/id/Turn-Your-Arduino-Into-an-ISP/step4/Using-Your-Arduino-ISP-Burning-Bootloaders/

http://www.instructables.com/id/Programming-Arduino-Bootloader-without-External-Pr/ http://code.google.com/p/mega-isp/downloads/list This instructables is usefull if: * you've got your arduino with atmega168 and you bought an atmega328 at you local electronics store. It doesn't have an arduino bootloader * you want to make a project that doesn't use arduino - just a regular AVR chip (like the USBTinyISP) - you have a clean attiny2313/attiny48 etc that you want to burn firmware on. Normally you would have to have an ISP (In System Programmer) like USBTinyISP to program your new chip. Having the arduino you can teach it to be a programmer thank to a great work done by Randall Bohn. He created Mega-ISP - an arduino sketch that works like a programmer.

81

82

82

83

83

84 BREAD BOARD

84

85

85

86

86

87

87

88

// // // //

rsbohn 25 July 2007 adapted/extended from the avr910 assembler code this is so I can use avrdude to program chips I would use a different syntax otherwise... LED 9 SCK 13 MISO 12 MOSI 11 RESET 10

#define #define #define #define #define

#define SWVER "23" #define HWVER "10" #define PACE 50 char *DeviceList = "\x01\x56\x76\x5e"; byte device=1; // device type, get from avrdude int here = 0; // current memory location int last = -1; byte cmdlog[16]; byte logcount = 0; byte DEBUG = 0; void spiInit(); void setup() { Serial.begin(19200); pinMode(LED, OUTPUT); digitalWrite(LED, HIGH); delay(100); //spiInit(); digitalWrite(LED, LOW); } byte ReadChar() { do {} while (!Serial.available()); return Serial.read(); } void loop() { char ch; ch = ReadChar(); //Serial.print(ch); //Serial.print(' '); cmdlog[logcount++ & 0x0F] = ch; Dispatch(ch); } void bprint(byte b) { if (b < 0x10) Serial.print('0'); Serial.print(b, HEX); } /// SPI Routines //////////////////////////////////////////////////////////// void spiInit() {

88

89 byte x; SPCR = 0x53; x=SPSR; x=SPDR; // read to clear them //digitalWrite(SCK, LOW);

} void spiBusyWait() { do {} while (!(SPSR & (1 << SPIF))); //delay(PACE); }

byte spiXfer(byte b) { byte reply; if (DEBUG) { bprint(b); bprint(SPSR); } //spiBusyWait(); //delay(PACE); // writing SPDR starts transfer SPDR=b; spiBusyWait(); // get reply from SPDR reply = SPDR; if (DEBUG) { Serial.print("::"); bprint(reply); Serial.println(); } return SPDR; } byte spiTransaction(byte a, byte b, byte c, byte d) { spiXfer(a); spiXfer(b); spiXfer(c); return spiXfer(d); } void SelectDevice(byte b) { device=b; } void EnableProgramMode() { //Serial.println("Enable Program Mode"); pinMode(MISO, INPUT); pinMode(MOSI, OUTPUT); pinMode(SCK, OUTPUT); pinMode(RESET, OUTPUT); spiInit(); digitalWrite(RESET, HIGH); digitalWrite(SCK, LOW); delay(50); digitalWrite(RESET, LOW); spiTransaction(0xAC, 0x53, 0x00, 0x00); digitalWrite(LED, HIGH); } void LeaveProgramMode() { pinMode(MISO, INPUT);

89

90 pinMode(MOSI, INPUT); pinMode(SCK, INPUT); pinMode(RESET, INPUT); digitalWrite(LED, LOW);

void ListSupportedDevices() { Serial.print(DeviceList); Serial.print(0, BYTE); } void WriteProgH(byte b) { spiTransaction(0x48, (here >> 8) & 0xFF, here & 0xFF, b); // delay? here++; } void WriteProgL(byte b) { spiTransaction(0x40, (here >> 8) & 0xFF, here & 0xFF, b); // delay? //here++; } void ReadProg() { byte d = spiTransaction(0x28, (here >> 8) & 0xFF, here & 0xFF, 0); Serial.print(d, BYTE); d = spiTransaction(0x20, (here >> 8) & 0xFF, here & 0xFF, 0); Serial.print(d, BYTE); here++; } //void LoadAddress(byte ah, byte al) { //whatever: void LoadAddress(byte al, byte ah) { here = ah; here = here * 256; here = here | al; last = here; } // write EEPROM void WriteData(byte b) { spiTransaction(0xC0, (here >> 8) & 0xFF, here & 0xFF, b);

90

91 here++; } void ReadData() { byte b = spiTransaction(0xA0, (here >> 8) & 0xFF, here & 0xFF, 0); Serial.print(b, BYTE); here++; } void ChipErase() { spiTransaction(0xac, 0x80, 0x04, 0x00); } void ReadSignature() { byte b; b = spiTransaction(0x30, 0x00, 0x02, 0x00); Serial.print(b, BYTE); b = spiTransaction(0x30, 0x00, 0x01, 0x00); Serial.print(b, BYTE); b = spiTransaction(0x30, 0x00, 0x00, 0x00); Serial.print(b, BYTE); } void WriteProgramPage() { spiTransaction(0x4C, (here >> 8) & 0xFF, here & 0xFF, 0); } void Universal(byte a, byte b, byte c, byte d) { byte reply; reply = spiTransaction(a, b, c,d); Serial.print(reply, BYTE); } void todo(char *feature) { Serial.print("Not Implemented "); Serial.println(feature); } void SelfTest() { Serial.println("AVR910"); Serial.print(logcount, HEX); Serial.println(" commands received:"); for (byte lx = 0; lx < 16; lx++) { if (cmdlog[lx]) Serial.print(cmdlog[lx], BYTE); else Serial.print('~'); } Serial.println(); Serial.print("Device is "); Serial.print(device, HEX); Serial.print(", DDRB is "); bprint(DDRB); Serial.println(); Serial.print("SPCR is ");

91

92 bprint(SPCR); Serial.println(); Serial.print(last, HEX); Serial.print(' '); Serial.println(here, HEX); DEBUG = 1; //Dispatch('s'); //DEBUG = 0;

} /// Dispatch /// -------- /////////////////////////////////////////////// +++++ void Dispatch(char ch) { if (ch == 'T') SelectDevice(ReadChar()); if (ch == 'S') // show_id {Serial.print("AVR ISP"); return;} if (ch == 'V') //todo("Software Version"); {Serial.print(SWVER); return;} if (ch == 'v') //todo("Hardware Version"); {Serial.print(HWVER); return;} if (ch == 't') { ListSupportedDevices(); return; } if (ch == 'p') { Serial.print('S'); // Serial type programmer. return; } if (ch == 'a') { Serial.print('Y'); // we support autoincrement return; } if (ch == 'x') digitalWrite(LED, HIGH); // x,y ignored in AVR910 if (ch == 'y') digitalWrite(LED, LOW); // but not here! //if (device == 0) // need a device from here on out... // {Serial.print('?'); return;} if (ch == 'P') EnableProgramMode(); if (ch == 'C') WriteProgH(ReadChar()); if (ch == 'c') WriteProgL(ReadChar()); if (ch == 'R') {ReadProg(); return;} if (ch == 'A') LoadAddress(ReadChar(), ReadChar()); if (ch == 'D') WriteData(ReadChar()); if (ch == 'd') {ReadData(); return;} if (ch == 'L') LeaveProgramMode(); if (ch == 'e') ChipErase(); if (ch == 'l') todo("Write Lock Bits"); if (ch == 's') {ReadSignature(); return;} // seems to read them 02 01 00 for some reason. // see what avrdude wants! if (ch == 'm') WriteProgramPage(); if (ch == ':') Universal(ReadChar(),ReadChar(),ReadChar(),0); if (ch == '.') Universal(ReadChar(),ReadChar(),ReadChar(),ReadChar()); if (ch == '$') SelfTest();

92

93 if (ch == '0') LoadAddress(0,0); // put_ret ;send CR Serial.print(0x0D, BYTE); }

93

94

Ethernet EXEMPLO 1
//SO FUNCIONA NO ATMEGA168 DEVIDO AO USO DA BIBLIOTECA <Ethernet.h> //http://blog.whatididwas.com/2008/12/wiznet-sample-code.html #include <Ethernet.h> /* this code will get all the analog values from the pins it will default the digital pins to output and allow you to turn them on or off added code from */ // network configuration. gateway and subnet are optional. byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; byte ip[] = { 192, 168, 1, 7 }; byte gateway[] = { 192, 168, 1, 1 }; byte subnet[] = { 255, 255, 255, 0 }; int pins[]={0,1,2,3,4,5,6,7};//port "A???" bool values[]={false,false,false,false,false,false,false,false}; Server server = Server(80); unsigned long time; void setup() { // initialize the ethernet device Ethernet.begin(mac, ip);//, gateway, subnet); // start listening for clients for (int i=0;i<8;i++) { pinMode(pins[i], OUTPUT); // sets the digital pin as output digitalWrite(pins[i], LOW); // sets the pin off (LOW) values[i]=false; } server.begin(); Serial.begin(9600); // setup serial } void loop() { Client client = server.available(); if (client) { //reset the values in preperation to get values server.print("HTTP/1.0 200 OK\r\nServer: arduino\r\nContent-Type: text/html\r\n\r\n"); server.print("<HTML><HEAD><TITLE>");

94

95 server.print("Syd's 'duino - "); server.print(millis());//to make sure that we habve a new page server.print("</TITLE>"); server.print("<script type=\"text/JavaScript\"><!--function timedRefresh(timeoutPeriod) {setTimeout(\"location.reload(true);\",timeoutPeriod);}//--></script>"); server.print("</HEAD><BODY>"); server.print("HEADERS:"); dumpheader(client);//dump the headers and recover any values passed in from the form //now that we have the values from the checkboxes - set the pins for (int i=0;i<8;i++){ if(values[i]){ digitalWrite(pins[i], HIGH); }else{ digitalWrite(pins[i], LOW); //true - set pin high } } all_analog();//display all the analog pins values htmlform(client);//write out the form to get the checkboxes server.print("</BODY></HTML>"); client.stop();//close the connection with the client delay(1000);//pause wait for a new connection }

} void dumpheader(Client client){ int count = 0; char c = client.read(); server.print(c); count++; bool resetvalues=false;//asume that the headers have no settings coming in while ((c!= -1) && (count < 64)){ c = client.read(); server.print(c); count++; if (c=='?' || c=='&') { //we have some form data so reset the values[] to known state if (!resetvalues){ for (int i=0;i<8;i++){ values[i]=false; } resetvalues=true; } capturevariable(client); } } } void htmlform(Client client){

95

96 server.print("<form method='get'>"); for (int i=0;i<8;i++){ printcheckbox( i,values[i]); } server.print("<input type='reset' value='Reset'/>"); server.print("<input type='submit' value='Submit'/>"); server.print("</form>"); } void printcheckbox(int pin, bool checked) { //assumes pins 0-7 server.print("Digital pin "); //server.print(pin); //server.print("<input type=\"text\" size='2' maxlenth='2' name='p"); server.print(pin); //server.print("' value='"); //server.print(pin); //server.print("'/>"); server.print(":<input type='checkbox' name='v"); //server.print(pin); server.print("' value='"); server.print(pin); server.print("'"); if (checked) { server.print(" checked='checked' "); } server.print("/><br/>"); } void capturevariable(Client client){ //we get a string like:GET /? p0=0&v=0&p1=1&v=1&p2=2&v=2&p3=3&v=3&p4=4&v=4&p5=5&v=5&p6=6&v=6&p7=7&v=7 we enter here after the ? or the & char c= client.read(); server.print(c); if(c=='v'){ c = client.read();//skip the = server.print(c); //c = client.read();server.print(c);//capture the p server.print("<b>"); c = client.read();//capture the value server.print(c); server.print("</b>"); int pin=int(c)-48;//adjust from the char value to the int value server.print(pin);//debuging values[pin]=true; } } int get_analog(int pin) { int val = analogRead(pin); // read the input pin Serial.println(val); // debug value return val;

96

97 } int set_analog(int pin,int value) { return -1; } void all_analog() { server.print("<table border = '1'>"); for (int i=0; i<6;i++){ server.print("<tr><td>"); server.print("Analog pin "); server.print(i); server.print(":</td><td>"); server.print(get_analog(i)); server.print("</td></tr>"); } server.print("<table>"); }

97

98

EXEMPLO 2
//http://www.nkcelectronics.com/arduino-ethernet-shield.html With the following code, the Arduino can access Google and search for "Arduino" and bring the result to the serial port. #include byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; byte ip[] = { 10, 0, 0, 177 }; byte server[] = { 64, 233, 187, 99 }; // Google Client client(server, 80); void setup() { Ethernet.begin(mac, ip); Serial.begin(9600); delay(1000); Serial.println("connecting..."); if (client.connect()) { Serial.println("connected"); client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } else { Serial.println("connection failed"); } } void loop() { if (client.available()) { char c = client.read(); Serial.print(c); } if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); for(;;) ; } }

98

99

EXEMPLO 3
Features: TCP/IP stack on board provided by the W5100 chip Allows the Arduino / Freeduino to access the Internet, as a server or a client Very small and efficient Library (Did I say the TCP/IP stack is embedded in the W5100 chip>) The shield comes with stackable shields Arduino communicates with the shield using SPI (But the complexity of SPI communication is hidden by the Library) Sample Code With the following code, the Arduino can access Google and search for "Arduino" and bring the result to the serial port. #include byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; byte ip[] = { 10, 0, 0, 177 }; byte server[] = { 64, 233, 187, 99 }; // Google Client client(server, 80); void setup() { Ethernet.begin(mac, ip); Serial.begin(9600); delay(1000); Serial.println("connecting..."); if (client.connect()) { Serial.println("connected"); client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } else { Serial.println("connection failed"); } } void loop() { if (client.available()) { char c = client.read();

99

100 Serial.print(c); } if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); for(;;) ; } }

100

101

Melody
int speakerPin = 9; int length = 15; // the number of notes char notes[] = "ccggaagffeeddc "; // a space represents a rest int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 }; int tempo = 300; void playTone(int tone, int duration) { for (long i = 0; i < duration * 1000L; i += tone * 2) { digitalWrite(speakerPin, HIGH); delayMicroseconds(tone); digitalWrite(speakerPin, LOW); delayMicroseconds(tone); } } void playNote(char note, int duration) { char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' }; int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 }; // play the tone corresponding to the note name for (int i = 0; i < 8; i++) { if (names[i] == note) { playTone(tones[i], duration); } }

void setup() { pinMode(speakerPin, OUTPUT); } void loop() { for (int i = 0; i < length; i++) { if (notes[i] == ' ') { delay(beats[i] * tempo); // rest } else { playNote(notes[i], beats[i] * tempo); } // pause between notes delay(tempo / 2);

} }

101

102

GPS
/* Example code for connecting a Parallax GPS module to the Arduino Igor Gonz?lez Mart?n. 05-04-2007 igor.gonzalez.martin@gmail.com English translation by djmatic 19-05-2007 Listen for the $GPRMC string and extract the GPS location data from this. Display the result in the Arduino's serial monitor. */ #include <string.h> #include <ctype.h> int ledPin = 13; int rxPin = 0; int txPin = 1; int byteGPS=-1; char linea[300] = ""; char comandoGPR[7] = "$GPRMC"; int cont=0; int bien=0; int conta=0; int indices[13]; // LED test pin // RX PIN // TX TX

// *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D int int int int int int led DI RW DB[] Enable count = = = = = = 13; 12; 11; {7, 8, 9, 10}; 6; 0;

//************************ //***** S P A C O S ****** //************************ void Spacos(int _spaces) { LcdCommandWrite(0x02); //move cursor to home postion delay(5); for (int i = 1;i < _spaces;++i) { LcdCommandWrite(0x14); delay(5); } }

102

103 //**************************************************** //**************** I m p r i m e LCD ***************** //**************************************************** //int myLength = sizeof(myArray void ImprimeLCD(int _linha, int _coluna, char msg[], int _tamanho) { if (_linha==1) Spacos(_coluna); else if (_linha==2) Spacos(_coluna+40); for (int i=0;i<_tamanho;++i) LcdDataWrite(msg[i]);

//**************************************************** //**************** I m p r i m e LCD 2 *************** //**************************************************** void ImprimeLCD2(int _linha, int _coluna, char msg, int _tamanho) { if (_linha==1) Spacos(_coluna); else if (_linha==2) Spacos(_coluna+40); for (int i=0;i<_tamanho;++i) LcdDataWrite(msg); } //******************************* //**** C O M A N D W R I T E *** //******************************* void LcdCommandWrite(int value) { int i = 0; int value1 = 0; value1 = value; value1 >>= 4; //send the first 4 databits (from 8) + RW and DI for (i=DB[0]; i <= DI; i++) { digitalWrite(i,value1 & 01); value1 >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet delay(1); for (i=DB[0]; i <= DB[3]; i++) { // secound part of the secound 4 bits (from 8) digitalWrite(i,value & 01); value >>= 1; } value >>= 4; // send the RW and DI of the secound 4 bits(from 8) for (i=RW; i <= DI; i++) { digitalWrite(i,value & 01);

103

104 value >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet } //**************************** //**** D A T A W R I T E **** //**************************** void LcdDataWrite(int value) { int i = 0; int value1 = 0; digitalWrite(DI, HIGH); digitalWrite(RW, LOW); value1 =value; value1 >>= 4; //send the first 4 databits (from 8) for (i=DB[0]; i <= DB[3]; i++) { digitalWrite(i,value1 & 01); value1 >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet delay(1); digitalWrite(DI, HIGH); digitalWrite(RW, LOW); for (i=DB[0]; i <= DB[3]; i++) { digitalWrite(i,value & 01); value >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet } //**************************************************************** //********************* N U M B E R W R I T E ******************* //**************************************************************** // this funktion help us to write number over 9, easyely in the lcd display void LcdNumberWrite(int nr) { int n1 = 0; int n2 = 0; n1 = n2 = nr;

104

105 n1 = n1 / 100; LcdCommandWrite(560 + n1); //512 used to wirte data (see commands for character modul) n2 = (n2 - n1 * 100) / 10; LcdCommandWrite(560 + n2); //512 used to wirte data (see commands for character modul) nr = nr - n1 *100 - n2 * 10; LcdCommandWrite(560 + nr); //512 used to wirte data (see commands for character modul) } // *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D *** L C D

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>> //>>>>>>>>>>>>>>>>>>>>> S E T U P >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>> void setup() { int i = 0; for (i=Enable; i <= DI; i++) { pinMode(i,OUTPUT); } delay(100); // initiatize lcd after a short pause // needed by the LCDs controller ///////////////////////////////////////////////////// 4 pin initialization LcdCommandWrite(0x03); // function set: // 4 pin initialization delay(64); LcdCommandWrite(0x03); // function set: // 4 pin initialization delay(50); LcdCommandWrite(0x03); // function set: // 4 pin initialization delay(50); LcdCommandWrite(0x02); // function set: // 4 pin initialization delay(50); /////////////////////////////////////////////////////////////////////// ////// LcdCommandWrite(0x28); // function set: // 4-bit interface, 2 display lines, 5x7 font //LcdCommandWrite(0x2C); // function set: // 4-bit interface, 1 display lines, 5x7 font ///////////////////////////////////////////////////// end of 4 pin initialization

105

106 delay(20); LcdCommandWrite(0x06); // entry mode set: // increment automatically, no display shift delay(20); LcdCommandWrite(0x0E); // display control: // turn display on, cursor on, no blinking delay(20); LcdCommandWrite(0x01); // clear display, set cursor position to zero delay(100); LcdCommandWrite(0x80); // display control: delay(20); //////// unter this line are the special stuff you don't need for a initialitzation LcdCommandWrite(0x0F); // delay(10); cursor blink

LcdCommandWrite(0x01); // clear display, set the cursor to home position delay(1000); LcdCommandWrite(0x0E); // cursor not blink LcdCommandWrite(0x02); // set cursor position to zero delay(10); //ImprimeLCD(1,1,"Scanning...",16); //ImprimeLCD(1,30," ",1); //LcdCommandWrite(0x01); //delay(10); //************************************************* //***************** G P S ************************* //************************************************* pinMode(ledPin, OUTPUT); // Initialize LED pin pinMode(rxPin, INPUT); pinMode(txPin, OUTPUT); Serial.begin(4800); for (int i=0;i<300;i++){ // Initialize a buffer for received data linea[i]=' '; }

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>> //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> L O O P >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>> void loop() { digitalWrite(ledPin, HIGH); // Serial.print(0x03);

106

107 byteGPS=Serial.read(); // Read a byte of the serial port if (byteGPS == -1) { // See if the port is empty yet delay(100); } else { linea[conta]=byteGPS; // If there is serial port data, it is put in the buffer conta++; Serial.print(byteGPS, BYTE); if (byteGPS==13){ // If the received byte is = to 13, end of transmission digitalWrite(ledPin, LOW); cont=0; bien=0; for (int i=1;i<7;i++){ // Verifies if the received command starts with $GPR if (linea[i]==comandoGPR[i-1]){ bien++; } } if(bien==6){ // If yes, continue and process the data for (int i=0;i<300;i++){ if (linea[i]==','){ // check for the position of the "," separator indices[cont]=i; cont++; } if (linea[i]=='*'){ // ... and the "*" indices[12]=i; cont++; } } Serial.println(""); // ... and write to the serial port Serial.println(""); Serial.println("---------------"); for (int i=0;i<12;i++){ switch(i){ case 0 :Serial.print("Time in UTC (HhMmSs): ");break; case 1 :Serial.print("Status (A=OK,V=KO): ");break; case 2 :Serial.print("Latitude: ");break; case 3 :Serial.print("Direction (N/S): ");break; case 4 :Serial.print("Longitude: ");break; case 5 :Serial.print("Direction (E/W): ");break; case 6 :Serial.print("Velocity in knots: ");break; case 7 :Serial.print("Heading in degrees: ");break; case 8 :Serial.print("Date UTC (DdMmAa): ");break; case 9 :Serial.print("Magnetic degrees: ");break; case 10 :Serial.print("(E/W): ");break; case 11 :Serial.print("Mode: ");break; case 12 :Serial.print("Checksum: ");break; } for (int j=indices[i];j<(indices[i+1]-1);j++){ Serial.print(linea[j+1]); ImprimeLCD2(1,j-6,linea[j+1],1); switch(i){ case 0 : ImprimeLCD2(1,j-6,linea[j+1],1); break;

// //

107

108 // // // case 1 : ImprimeLCD2(1,j-6,linea[j+1],1); break; case 8 : ImprimeLCD2(1,j-6,linea[j+1],1); break;

} } Serial.println(""); }

} Serial.println("---------------"); conta=0; for (int i=0;i<300;i++){ linea[i]=' '; } } } } // Reset the buffer //

108

109

TIP122 motor driver


int motorPin = 9; int ledPin = 13; int val = 0; void setup() { pinMode(motorPin, OUTPUT); Serial.begin(19200); Serial.println("Welcome to Serial Motor Speed!"); Serial.println("Enter speed number 0-9:"); } void loop() { val = Serial.read(); if (val >= '0' && val <= '9') { val = val - '0'; val = 28 * val; Serial.print("Setting speed to "); Serial.println(val); analogWrite(motorPin,val); Serial.println("Enter speed number 0-9:"); } }

109

110

BLINK WITHOUT DELAY


/* int ledPin = 13; void setup() { pinMode(ledPin, OUTPUT); } void loop() { digitalWrite(ledPin, HIGH); delay(1000); digitalWrite(ledPin, LOW); delay(1000); } */ int ledPin = 13; int value = LOW; long previousMillis = 0; long interval = 1000; (milliseconds) void setup() { pinMode(ledPin, OUTPUT); }

// // // //

LED connected to digital pin 13 previous value of the LED will store last time LED was updated interval at which to blink

// sets the digital pin as output

void loop() { // here is where you'd put code that needs to be running all the time. // check to see if it's time to blink the LED; that is, is the difference // between the current time and last time we blinked the LED bigger than // the interval at which we want to blink the LED. if (millis() - previousMillis > interval) { previousMillis = millis(); // remember the last time we blinked the LED // if the if (value value = else value = } } LED is off turn it on and vice-versa. == LOW) HIGH; LOW;

digitalWrite(ledPin, value);

110

111

LED 1
/* * * * * * * * */ Loop by David A. Mellis Lights multiple LEDs in sequence, then in reverse. the use of a for() loop and arrays. http://www.arduino.cc/en/Tutorial/Loop Demonstrates

int timer = 100; // The higher the number, the slower the timing. int pins[] = {9, 10, 11, 12, 13 }; // an array of pin numbers int num_pins = 5; // the number of pins (i.e. the length of the array) void setup() { int i; for (i = 0; i < num_pins; i++) from 0 to num_pins - 1 pinMode(pins[i], OUTPUT); } void loop() { int i; for (i = 0; i < num_pins; i++) { // loop through each pin... digitalWrite(pins[i], HIGH); // turning it on, delay(timer); // pausing, digitalWrite(pins[i], LOW); // and turning it off. } for (i = num_pins - 1; i >= 0; i--) { digitalWrite(pins[i], HIGH); delay(timer); digitalWrite(pins[i], LOW); } } // the array elements are numbered // set each pin as an output

111

112

LED 2
/* * Blink * * The basic Arduino example. Turns on an LED on for one second, * then off for one second, and so on... We use pin 13 because, * depending on your Arduino board, it has either a built-in LED * or a built-in resistor so that you need only an LED. * * http://www.arduino.cc/en/Tutorial/Blink */ const int a = 15; int ledPin13 = int ledPin12 = int ledPin11 = int ledPin10 = int ledPin9 = int ledPin8 = int ledPin7 = int ledPin6 = int ledPin5 = int ledPin4 = int ledPin3 = int ledPin2 = int ledPin1 = //int ledPin0 13; 12; 11; 10; 9; 8; 7; 6; 5; 4; 3; 2; 1; = 0; // // // // // // // // // // // // // LED connected to digital pin 13 LED connected to digital pin 13 LED connected to digital pin 13 LED connected to digital pin 13 LED connected to digital pin 13 LED connected to digital pin 13 LED connected to digital pin 13 LED connected to digital pin 13 LED connected to digital pin 13 LED connected to digital pin 13 LED connected to digital pin 13 LED connected to digital pin 13 LED connected to digital pin 13 // LED connected to digital pin 13

void setup() { pinMode(ledPin13, OUTPUT); pinMode(ledPin12, OUTPUT); pinMode(ledPin11, OUTPUT); pinMode(ledPin10, OUTPUT); pinMode(ledPin9, OUTPUT); pinMode(ledPin8, OUTPUT); pinMode(ledPin7, OUTPUT); pinMode(ledPin6, OUTPUT); pinMode(ledPin5, OUTPUT); pinMode(ledPin4, OUTPUT); pinMode(ledPin3, OUTPUT); pinMode(ledPin2, OUTPUT); pinMode(ledPin1, OUTPUT); // pinMode(ledPin0, OUTPUT); } void loop() { digitalWrite(ledPin13, HIGH); delay(a); // digitalWrite(ledPin13, LOW); delay(a); //

// run once, when the sketch starts // // // // // // // // // // // // // sets the digital pin as output sets the digital pin as output sets the digital pin as output sets the digital pin as output sets the digital pin as output sets the digital pin as output sets the digital pin as output sets the digital pin as output sets the digital pin as output sets the digital pin as output sets the digital pin as output sets the digital pin as output sets the digital pin as output // sets the digital pin as output

// run over and over again // sets the waits for a // sets the waits for a LED on second LED off second

112

113 digitalWrite(ledPin12, HIGH); delay(a); // digitalWrite(ledPin12, LOW); delay(a); // digitalWrite(ledPin11, HIGH); delay(a); // digitalWrite(ledPin11, LOW); delay(a); // digitalWrite(ledPin10, HIGH); delay(a); // digitalWrite(ledPin10, LOW); delay(a); // // sets the waits for a // sets the waits for a // sets the waits for a // sets the waits for a // sets the waits for a // sets the waits for a LED on second LED off second LED on second LED off second LED on second LED off second LED on second LED off second

digitalWrite(ledPin9, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin9, LOW); // sets the delay(a); // waits for a

digitalWrite(ledPin8, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin8, LOW); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin7, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin7, LOW); // sets the delay(a); // waits for a digitalWrite(ledPin6, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin6, LOW); // sets the delay(a); // waits for a digitalWrite(ledPin5, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin5, LOW); // sets the delay(a); // waits for a digitalWrite(ledPin4, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin4, LOW); // sets the delay(a); // waits for a digitalWrite(ledPin3, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin3, LOW); // sets the delay(a); // waits for a digitalWrite(ledPin2, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin2, LOW); // sets the delay(a); // waits for a LED on second LED off second LED on second LED off second LED on second LED off second LED on second LED off second LED on second LED off second LED on second LED off second

/*

digitalWrite(ledPin1, HIGH); // sets the LED on delay(a); // waits for a second

113

114 digitalWrite(ledPin1, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin0, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin0, LOW); // sets the delay(a); // waits for a */ LED on second LED off second

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> digitalWrite(ledPin1, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin1, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin2, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin2, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin3, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin3, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin4, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin4, LOW); // sets the delay(a); // waits for a LED on second LED off second

digitalWrite(ledPin5, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin5, LOW); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin6, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin6, LOW); // sets the delay(a); // waits for a digitalWrite(ledPin7, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin7, LOW); // sets the delay(a); // waits for a digitalWrite(ledPin8, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin8, LOW); // sets the delay(a); // waits for a digitalWrite(ledPin9, HIGH); // sets the delay(a); // waits for a digitalWrite(ledPin9, LOW); // sets the delay(a); // waits for a LED on second LED off second LED on second LED off second LED on second LED off second LED on second LED off second

digitalWrite(ledPin10, HIGH); // sets the LED on delay(a); // waits for a second

114

115 digitalWrite(ledPin10, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin11, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin11, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin12, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin12, LOW); // sets the LED off delay(a); // waits for a second

115

116

LED 3 candle light


/* * CandleLight * ----------* * Use random numbers to emulate a flickering candle with a PWM'd LED * * 2007 Tod E. Kurt <tod@todbot.com> * http://todbot.com/ * */ int ledPin = 9; int val = 0; int delayval = 0; // select the pin for the LED // variable that holds the current LED brightness // variable that holds the current delay time // initialize the random number generator // declare the ledPin as an OUTPUT

void setup() { randomSeed(0); pinMode(ledPin, OUTPUT); } void loop() { val = random(100,255); 255 analogWrite(ledPin, val); delayval = random(50,150); delay(delayval);

// pick a random number between 100 and // set the LED brightness // pick a random number between 30 and 100 // delay that many milliseconds

116

117

LED 4 FADING
// Fading LED // by BARRAGAN <http://people.interaction-ivrea.it/h.barragan> int value value int ledRed pin 9 int ledGreen pin 9 int ledBlue pin 9 = 0; = 11; = 10; = 9; // variable to keep the actual // light connected to digital // light connected to digital // light connected to digital

void setup() { // nothing for setup } void loop() { //Red for(value = 0 ; value <= 255; value+=5) { analogWrite(ledRed, value); to 255) delay(17); to see the dimming effect } for(value = 255; value >=0; value-=5) { analogWrite(ledRed, value); delay(17); } // fade in (from min to max) // sets the value (range from 0 // waits for 30 milli seconds // fade out (from max to min)

//Green for(value = 0 ; value <= 255; value+=5) // fade in (from min to max) { analogWrite(ledGreen, value); // sets the value (range from 0 to 255) delay(17); // waits for 30 milli seconds to see the dimming effect } for(value = 255; value >=0; value-=5) // fade out (from max to min) { analogWrite(ledGreen, value); delay(17); } //Blue for(value = 0 ; value <= 255; value+=5) // fade in (from min to max) { analogWrite(ledBlue, value); // sets the value (range from 0 to 255)

117

118 delay(17); to see the dimming effect } for(value = 255; value >=0; value-=5) { analogWrite(ledBlue, value); delay(17); } } // waits for 30 milli seconds // fade out (from max to min)

118

119

LED 5 RGB MOON LIGHT


/* * Code for cross-fading 3 LEDs, red, green and blue, or one tri-color LED, using PWM * The program cross-fades slowly from red to green, green to blue, and blue to red * The debugging code assumes Arduino 0004, as it uses the new Serial.begin()-style functions * originally "dimmingLEDs" by Clay Shirky <clay.shirky@nyu.edu> */ // Output int a = 9; int b = 10; int c = 11; int redPin = 6; int greenPin = 5; int bluePin = 3; // Red LED, connected to digital pin 9 // Green LED, connected to digital pin 10 // Blue LED, connected to digital pin 11

// Program variables int redVal = 255; // Variables to store the values to send to the pins int greenVal = 1; // Initial values are Red full, Green and Blue off int blueVal = 1; int i = 0; // Loop counter int wait = 15; // 50ms (.05 second) delay; shorten for faster fades int DEBUG = 0; // DEBUG counter; if set to 1, will write values back via serial void setup() { pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); pinMode(a, OUTPUT); pinMode(b, OUTPUT); pinMode(c, OUTPUT); if (DEBUG) { debugging... Serial.begin(9600); } } // If we want to see the pin values for // ...set up the serial ouput on 0004 style

// sets the pins as output

// Main program void loop() { i += 1; // Increment counter if (i < 255) // First phase of fades { redVal -= 1; // Red down greenVal += 1; // Green up

119

120 blueVal = 1; // Blue low } else if (i < 509) // Second phase of fades { redVal = 1; // Red low greenVal -= 1; // Green down blueVal += 1; // Blue up } else if (i < 763) // Third phase of fades { redVal += 1; // Red up greenVal = 1; // Green lo2 blueVal -= 1; // Blue down } else // Re-set the counter, and start the fades again { i = 1; } // we do "255-redVal" // LEDs are hooked up analogWrite(redPin, pins analogWrite(greenPin, analogWrite(bluePin, instead of just "redVal" because the to +5V instead of Gnd 255 - redVal); // Write current values to LED 255 - greenVal); 255 - blueVal);

analogWrite(a, 255 - redVal); // Write current values to LED pins analogWrite(b, 255 - greenVal); analogWrite(c, 255 - blueVal); if (DEBUG) { // If we want to read the output DEBUG += 1; // Increment the DEBUG counter if (DEBUG > 10) { // Print every 10 loops DEBUG = 1; // Reset the counter Serial.print(i); // Serial commands in 0004 style Serial.print("\t"); // Print a tab Serial.print("R:"); // Indicate that output is red value Serial.print(redVal); // Print red value Serial.print("\t"); // Print a tab Serial.print("G:"); // Repeat for green and blue... Serial.print(greenVal); Serial.print("\t"); Serial.print("B:"); Serial.println(blueVal); // println, to end with a carriage return } } delay(wait); // Pause for 'wait' milliseconds before resuming the loop }

120

121

ULTRASONIC PING
int pingPin = 7; void setup() { Serial.begin(9600); } void loop() { long duration, inches, cm; // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. // We give a short LOW pulse beforehand to ensure a clean HIGH pulse. pinMode(pingPin, OUTPUT); digitalWrite(pingPin, LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(5); digitalWrite(pingPin, LOW); // The same pin is used to read the signal from the PING))): a HIGH // pulse whose duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. pinMode(pingPin, INPUT); duration = pulseIn(pingPin, HIGH); // convert the time into a distance inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100);

long microsecondsToInches(long microseconds) { // According to Parallax's datasheet for the PING))), there are // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per // second). This gives the distance travelled by the ping, outbound // and return, so we divide by 2 to get the distance of the obstacle. // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter.

121

122 // The ping travels out and back, so to find the distance of the // object we take half of the distance travelled. return microseconds / 29 / 2; }

int pingPin = 7; void setup() { Serial.begin(9600); } void loop() { long duration, inches, cm; // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. // We give a short LOW pulse beforehand to ensure a clean HIGH pulse. pinMode(pingPin, OUTPUT); digitalWrite(pingPin, LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(5); digitalWrite(pingPin, LOW); // The same pin is used to read the signal from the PING))): a HIGH // pulse whose duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. pinMode(pingPin, INPUT); duration = pulseIn(pingPin, HIGH); // convert the time into a distance inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); } long microsecondsToInches(long microseconds) { // According to Parallax's datasheet for the PING))), there are // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per // second). This gives the distance travelled by the ping, outbound // and return, so we divide by 2 to get the distance of the obstacle. // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf return microseconds / 74 / 2; }

122

123 long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter. // The ping travels out and back, so to find the distance of the // object we take half of the distance travelled. return microseconds / 29 / 2; }

// * Copyleft 2007 Jason Ch //This code returns the distance in Inches... I think it's more accurate than other code I have seen online and returns more usable results. Remove the *.39 to return cm instead of inches. You could make float ultrasoundValue = 0; but then you can't print it unless you transfer it into another type, but it could be used for further calculations. unsigned long echo = 0; int ultraSoundSignal = 7; // Ultrasound signal pin unsigned long ultrasoundValue = 0; void setup() { Serial.begin(9600); pinMode(ultraSoundSignal,OUTPUT); } unsigned long ping(){ pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output digitalWrite(ultraSoundSignal, LOW); // Send low pulse delayMicroseconds(2); // Wait for 2 microseconds digitalWrite(ultraSoundSignal, HIGH); // Send high pulse delayMicroseconds(5); // Wait for 5 microseconds digitalWrite(ultraSoundSignal, LOW); // Holdoff pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input digitalWrite(ultraSoundSignal, HIGH); // Turn on pullup resistor echo = pulseIn(ultraSoundSignal, HIGH); //Listen for echo ultrasoundValue = (echo / 58.138) * .39; //convert to CM then to inches return ultrasoundValue; } void loop() { int x = 0; x = ping(); Serial.println(x); delay(250); //delay 1/4 seconds. }

123

124

EXEMPLO 4
int pingPin = 7; void setup() { Serial.begin(9600); } void loop() { long duration, inches, cm; // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. // We give a short LOW pulse beforehand to ensure a clean HIGH pulse. pinMode(pingPin, OUTPUT); digitalWrite(pingPin, LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(5); digitalWrite(pingPin, LOW); // The same pin is used to read the signal from the PING))): a HIGH // pulse whose duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. pinMode(pingPin, INPUT); duration = pulseIn(pingPin, HIGH); // convert the time into a distance inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100);

long microsecondsToInches(long microseconds) { // According to Parallax's datasheet for the PING))), there are // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per // second). This gives the distance travelled by the ping, outbound // and return, so we divide by 2 to get the distance of the obstacle. // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter. // The ping travels out and back, so to find the distance of the // object we take half of the distance travelled. return microseconds / 29 / 2;

124

125 }

125

126

LCD
/* Analog in to LCD 4 bits * --------* Adapted from the "analog_read_send" and "lcd_8bits" tutorials. * This example uses 4 less pins on the Arduino than the 8 bit example. * It will take a reading from a 'K' Type thermocouple ice point reference chip * on Analog Input 2 and display the temperature in degrees Centigrade on the LCD. * One can also set a target temperature for turning a relay off, say for a heater, * at a given setpoint temperature. This is done on digital pin 4. * * These are the pins used on the LCD: * * - DI(register select), RW, DB4..DB7, Enable (7 in total) * * the pinout for LCD displays is standard and there is plenty * of documentation to be found on the internet. * * 2006, Dave Sopchak glasspusher at outofoptions dot net * */ int DI = 12; // register select int RW = 11; int DB[] = {7, 8, 9, 10}; int Enable = 6; int temperaturePin = 2; int ledPin = 13; // select the input pin for the temperature // pin for the LED

void tickleEnable() { // send a pulse to enable digitalWrite(Enable,HIGH); delayMicroseconds(1); // pause 1 ms according to datasheet digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet } void cmdWriteSet() { digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet digitalWrite(DI,0); digitalWrite(RW,0); } void LcdCommandWrite(int value) { int i = 0; for (i=DB[3]; i >= DB[0]; i--) // high nybble first {

126

127 digitalWrite(i, value & 128); value <<= 1; cmdWriteSet(); tickleEnable(); for (i=DB[3]; i >= DB[0]; i--) // low nybble next { digitalWrite(i, value & 128); value <<= 1; } cmdWriteSet(); tickleEnable(); } void LcdDataWrite(int value) { int i = 0; digitalWrite(DI, HIGH); digitalWrite(RW, LOW); for (i=DB[3]; i >= DB[0]; i--) // high nybble first { digitalWrite(i, value & 128); value <<= 1; } tickleEnable(); for (i=DB[3]; i >= DB[0]; i--) // low nybble next { digitalWrite(i, value & 128); value <<= 1; } tickleEnable(); } void setup (void) { int i; for (i=Enable; i <= DI; i++) pinMode(i,OUTPUT); delay(100); // initiatize lcd after a short pause // needed by the LCDs controller LcdCommandWrite(0x28); // function set: delay(64); // 4-bit interface, 2 display lines, 5x7 font // other interaces: // 0x20 = 4 bit, 1 display line LcdCommandWrite(0x28); delay(64); LcdCommandWrite(0x06); delay(20); // function set: // 4-bit interface, 2 display lines, 5x7 font // entry mode set: // increment automatically, no display shift

127

128 LcdCommandWrite(0x0E); delay(20); LcdCommandWrite(0x01); delay(100); LcdCommandWrite(0x80); delay(20); } void loop (void) { int i, val = 0; for(i = 0; i < 20; ++i) { val += analogRead(temperaturePin); sensor delay(50); } val /= 4.06; // display control: // turn display on, cursor on, no blinking // clear display, set cursor position to zero // display control: // turn display on, cursor on, no blinking

// read the value from the

// conversion value to millivolts // turn the ledPin on // stop the program for some time // turn the ledPin off

digitalWrite(ledPin, HIGH); delay(500); digitalWrite(ledPin, LOW);

if(val > 175 * 10) // temperature in deg C times 10, since we're measuring to tenths of a degree digitalWrite(4,LOW); else digitalWrite(4,HIGH); LcdCommandWrite(0x02); delay(10); firstDisplay(val); } // set cursor position to zero

void firstDisplay(int value) { int first,second, third, fourth; first second third fourth = value / 1000; = (value - 1000 * first)/ 100; = (value - 1000 * first - 100 * second)/ 10; = (value - 1000 * first - 100 * second - 10 * third);

LcdDataWrite('T'); LcdDataWrite('e'); LcdDataWrite('m'); LcdDataWrite('p'); LcdDataWrite(' '); LcdDataWrite('='); LcdDataWrite(' ');

128

129

LcdDataWrite(value > 999 ? first + 48 : ' '); LcdDataWrite(value > 99 ? second + 48 : ' '); LcdDataWrite(third + 48); LcdDataWrite('.'); LcdDataWrite(fourth + 48); LcdDataWrite(' '); LcdDataWrite('C'); LcdDataWrite(' '); LcdDataWrite(' '); }

// begin onscreen

129

130

EXEMPLO 2
/* LCD display with 4 DataPins * * This is a example in how to use an LCD screen * configured with data transfers over 2 x 4 bits. The example * based on the "LCD Hola example" by DojoDave. * * There are the following pins to be considered: * * - DI, RW, DB0..DB3, Enable (7 in total) * * the pinout for LCD displays is standard and there is plenty * of documentation to be found on the internet. * * (cleft) 2006 Tomek for K3 and fh-potsdam * */ int led = 13; int DI = 12; int RW = 11; int DB[] = {7, 8, 9, 10}; int Enable = 6; int count = 0; //************************ //***** S P A C O S ****** //************************ void Spacos(int _spaces) { LcdCommandWrite(0x02); //move cursor to home postion delay(5); for (int i = 1;i < _spaces;++i) { LcdCommandWrite(0x14); delay(5); } } //**************************************************** //**************** I m p r i m e LCD ***************** //**************************************************** void ImprimeLCD(int _linha, int _coluna, char msg[], int _tamanho) { if (_linha==1) Spacos(_coluna); else if (_linha==2) Spacos(_coluna+40); for (int i=0;i<_tamanho;++i) LcdDataWrite(msg[i]);

//******************************* //**** C O M A N D W R I T E *** //******************************* void LcdCommandWrite(int value) {

130

131 int i = 0; int value1 = 0; value1 = value; value1 >>= 4; //send the first 4 databits (from 8) + RW and DI for (i=DB[0]; i <= DI; i++) { digitalWrite(i,value1 & 01); value1 >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet delay(1); for (i=DB[0]; i <= DB[3]; i++) { // secound part of the secound 4 bits (from 8) digitalWrite(i,value & 01); value >>= 1; } value >>= 4; // send the RW and DI of the secound 4 bits(from 8) for (i=RW; i <= DI; i++) { digitalWrite(i,value & 01); value >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet } //**************************** //**** D A T A W R I T E **** //**************************** void LcdDataWrite(int value) { int i = 0; int value1 = 0; digitalWrite(DI, HIGH); digitalWrite(RW, LOW); value1 =value; value1 >>= 4; //send the first 4 databits (from 8) for (i=DB[0]; i <= DB[3]; i++) { digitalWrite(i,value1 & 01); value1 >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet delay(1);

131

132 digitalWrite(DI, HIGH); digitalWrite(RW, LOW); for (i=DB[0]; i <= DB[3]; i++) { digitalWrite(i,value & 01); value >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet } //**************************************************************** //********************* N U M B E R W R I T E ******************* //**************************************************************** // this funktion help us to write number over 9, easyely in the lcd display void LcdNumberWrite(int nr) { int n1 = 0; int n2 = 0; n1 = n2 = nr; n1 = n1 / 100; LcdCommandWrite(560 + n1); //512 used to wirte data (see commands for character modul) n2 = (n2 - n1 * 100) / 10; LcdCommandWrite(560 + n2); //512 used to wirte data (see commands for character modul) nr = nr - n1 *100 - n2 * 10; LcdCommandWrite(560 + nr); //512 used to wirte data (see commands for character modul) } //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //>>>>>>>>>>>>>>>>>>>>> S E T U P >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void setup (void) { int i = 0; for (i=Enable; i <= DI; i++) { pinMode(i,OUTPUT); } delay(100); // initiatize lcd after a short pause // needed by the LCDs controller ///////////////////////////////////////////////////// 4 pin initialization LcdCommandWrite(0x03); // function set: // 4 pin initialization delay(64); LcdCommandWrite(0x03); // function set: // 4 pin initialization delay(50);

132

133 LcdCommandWrite(0x03); // function set: // 4 pin initialization delay(50); LcdCommandWrite(0x02); // function set: // 4 pin initialization delay(50); ///////////////////////////////////////////////////////////////////////// //// LcdCommandWrite(0x28); // function set: // 4-bit interface, 2 display lines, 5x7 font //LcdCommandWrite(0x2C); // function set: // 4-bit interface, 1 display lines, 5x7 font ///////////////////////////////////////////////////// end of 4 pin initialization delay(20); LcdCommandWrite(0x06); // entry mode set: // increment automatically, no display shift delay(20); LcdCommandWrite(0x0E); // display control: // turn display on, cursor on, no blinking delay(20); LcdCommandWrite(0x01); // clear display, set cursor position to zero delay(100); LcdCommandWrite(0x80); // display control: delay(20); //////// unter this line are the special stuff you don't need for a initialitzation LcdCommandWrite(0x0F); // delay(10); cursor blink

LcdCommandWrite(0x01); // clear display, set the cursor to home position delay(1000); LcdCommandWrite(0x0E); // cursor not blink LcdCommandWrite(0x02); // set cursor position to zero delay(10); } //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //>>>>>>>>>>>>>>>>>>>>>>>>>>> L O O P >>>>>>>>>>>>>>>>>>>>>>>>>>>> //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void loop (void) { //>>>>>>>>>>>>>>>>>>>>>>>>>>>possible commands for the Lcd Display>>>>>>><< able to use for LcdDisplays with 4 or with 8 DataPins //LcdCommandWrite(0x01); // clear display, set the cursor to home position //LcdCommandWrite(0x02); // set cursor position to zero //LcdCommandWrite(0x0A); // set the display off

133

134 //LcdCommandWrite(0x0E); //LcdCommandWrite(0x0F); //LcdCommandWrite(0x0F); //LcdCommandWrite(0x0E); //LcdCommandWrite(0x18); //LcdCommandWrite(0x1c); //LcdCommandWrite(0x14); //LcdCommandWrite(0x10); // // // // // // // // set the display on and with out cursor blink set the display on and with cursor blink cursor blink cursor not blink shift display and cursor to the left shift display and cursor to the right shift cursor to the right shift cursor to the left

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> example <<<<<<<<<<<<<<<<<<<<<<<<<<<<< ImprimeLCD(1,1,"Fabio Brandespim",16); ImprimeLCD(2,1,"Roberta Pinto",13); ImprimeLCD(2,30," ",1); LcdCommandWrite(0x01); delay(10); ImprimeLCD(1,2,"Fabio Brandespim",16); ImprimeLCD(2,2,"Roberta Pinto",13); ImprimeLCD(2,30," ",1); LcdCommandWrite(0x01); delay(10); ImprimeLCD(1,3,"Fabio Brandespim",16); ImprimeLCD(2,3,"Roberta Pinto",13); ImprimeLCD(2,30," ",1); LcdCommandWrite(0x01); delay(10); ImprimeLCD(1,4,"Fabio Brandespim",16); ImprimeLCD(2,4,"Roberta Pinto",13); ImprimeLCD(2,30," ",1); LcdCommandWrite(0x01); //FAZER FUNCAO PARA MENSAGEM RODAR USANDO ARRAY }

/* // Write the message //like this LcdDataWrite('F'); LcdDataWrite('a'); LcdDataWrite('b'); LcdDataWrite('i'); LcdDataWrite('o'); LcdDataWrite(' '); for ( count = 0; count<=9; count++) { int wrote [] = { 'B', 'r', 'a', 'n', 'd', 'e', 's', LcdDataWrite(wrote[count]); } //espacos for ( count = 1; count<=(40-16); count++) { LcdDataWrite(' '); } 'p', 'i', 'm'};

134

135 for ( count = 0; count<=12; count++) { int wrote [] = { 'R', 'o', 'b', 'e', 'r', 't', 'a',' ', 'P', 'i', 'n', 't', 'o'}; LcdDataWrite(wrote[count]); } //and Number over 9 easyely like this LcdNumberWrite(999);

delay(2000); */

135

136

EXEMPLO 3

ESTA ESCREVENDO NAS DUAS LINHAS

/* LCD display with 4 DataPins * -------* * This is a example in how to use an LCD screen * configured with data transfers over 2 x 4 bits. The example * based on the "LCD Hola example" by DojoDave. * * There are the following pins to be considered: * * - DI, RW, DB0..DB3, Enable (7 in total) * * the pinout for LCD displays is standard and there is plenty * of documentation to be found on the internet. * * (cleft) 2006 Tomek for K3 and fh-potsdam * (cleft) 2008 Carl - Modifications * */ int led = 13; int DI = 12; int RW = 11; int DB[] = { 7, 8, 9, 10}; int Enable = 6; int count = 1; int count1 = 1; int count2 = 1; void LcdCommandWrite(int value) { int i = 0; int value1 = 0; value1 = value; value1 >>= 4; //send the first 4 databits (from DI for (i=DB[0]; i <= DI; i++) { digitalWrite(i,value1 & 01); value1 >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet delay(1); + RW and

for (i=DB[0]; i <= DB[3]; i++) { // secound part of the secound 4 bits (from digitalWrite(i,value & 01); value >>= 1; } value >>= 4; // send the RW and DI of the secound 4 bits(from for (i=RW; i <= DI; i++) {

136

137 digitalWrite(i,value & 01); value >>= 1;

} digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet } void LcdDataWrite(int value) { int i = 0; int value1 = 0; digitalWrite(DI, HIGH); digitalWrite(RW, LOW); value1 =value; value1 >>= 4; //send the first 4 databits (from for (i=DB[0]; i <= DB[3]; i++) { digitalWrite(i,value1 & 01); value1 >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet delay(1); digitalWrite(DI, HIGH); digitalWrite(RW, LOW); for (i=DB[0]; i <= DB[3]; i++) { digitalWrite(i,value & 01); value >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet } // this funktion help us to write number over 9, easyely in the lcd display void LcdNumberWrite(int nr) { int n1 = 0; int n2 = 0; n1 = n2 = nr; n1 = n1 / 100; LcdCommandWrite(560 + n1); character modul) n2 = (n2 - n1 * 100) / 10; //512 used to wirte data (see commands for

137

138 LcdCommandWrite(560 + n2); //512 used to wirte data (see commands for character modul) nr = nr - n1 *100 - n2 * 10; LcdCommandWrite(560 + nr); //512 used to wirte data (see commands for character modul) } void LcdNumberWrite2digits(long N) { long display1 = 0; long display2 = 0; long display3 = 0; long display4 = 0; long display1a = 0; long display1b = 0; long display1c = 0; //display1 = display2 = display 3 = display4 = N; /* display1c = (N/1000000); N = N - (display1c * 1000000); LcdCommandWrite(560 + display1c); //512 used to wirte data display1b = (N/100000); N = N - (display1b * 100000); LcdCommandWrite(560 + display1b); //512 used to wirte data display1a = (N/10000); N = N - (display1a * 10000); LcdCommandWrite(560 + display1a); //512 used to wirte data display1 = (N/1000); N = N - (display1 * 1000); LcdCommandWrite(560 + display1); //512 used to wirte data display2 = (N/100); N = N - (display2 * LcdCommandWrite(560 */ display3 = (N/10); N = N - (display3 * LcdCommandWrite(560 100); + display2); //512 used to wirte data 10); + display3); //512 used to wirte data

display4 = N; LcdCommandWrite(560 + display4); //512 used to wirte data } void setup (void) { int i = 0; for (i=Enable; i <= DI; i++) { pinMode(i,OUTPUT); } delay(100); // initiatize lcd after a short pause // needed by the LCDs controller

138

139 ///////////////////////////////////////////////////// 4 pin initialization LcdCommandWrite(0x03); // function set: // 4 pin initialization delay(64); LcdCommandWrite(0x03); // function set: // 4 pin initialization delay(50); LcdCommandWrite(0x03); // function set: // 4 pin initialization delay(50); LcdCommandWrite(0x02); // function set: // 4 pin initialization delay(50); LcdCommandWrite(0x2C); // function set: // 4-bit interface, 1 display lines, 5x7 font ///////////////////////////////////////////////////// end of 4 pin initialization delay(20); LcdCommandWrite(0x06); // entry mode set: // increment automatically, no display shift delay(20); LcdCommandWrite(0x0E); // display control: // turn display on, cursor on, no blinking delay(20); LcdCommandWrite(0x01); // clear display, set cursor position to zero delay(100); LcdCommandWrite(0x80); // display control: delay(20); //////// unter this line are the special stuff you don't need for a initialitzation LcdCommandWrite(0x0F); // delay(10); } void loop (void) { //>>>>>>>>>>>>>>>>>>>>>>>>>>>possible commands for the Lcd Display>>>>>>><< able to use for LcdDisplays with 4 or with 8 DataPins //LcdCommandWrite(0x01); // clear display, set the cursor to home position //LcdCommandWrite(0x02); // set cursor position to zero //LcdCommandWrite(0x0A); // set the display off //LcdCommandWrite(0x0E); // set the display on and with out cursor blink //LcdCommandWrite(0x0F); // set the display on and with cursor blink //LcdCommandWrite(0x0F); // cursor blink LcdCommandWrite(0x0E); // cursor not blink //LcdCommandWrite(0x18); // shift display and cursor to the left //LcdCommandWrite(0x1c); // shift display and cursor to the right //LcdCommandWrite(0x14); // shift cursor to the right //LcdCommandWrite(0x10); // shift cursor to the left cursor blink

139

140 //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> example <<<<<<<<< LcdCommandWrite(0x02); // set cursor position to zero delay(10); /* for ( count = 1; count<=10; count++) { LcdNumberWrite2digits(count); } for ( count = 1; count<=10; count++) { LcdNumberWrite2digits(count); } for ( count = 1; count<=10; count++) { LcdNumberWrite2digits(count); } for ( count = 1; count<=10; count++) { LcdNumberWrite2digits(count); } for ( count = 1; count<=3; count++) { int wrote [] = { 'o', 'n', 'e'}; LcdDataWrite(wrote[count]); } for ( count = 1; count<=16; count++) { LcdDataWrite(' '); } for ( count1 = 1; count1<=3; count1++) { int wrote1 [] = { 't', 'w', 'o' , }; LcdDataWrite(wrote1[count1]); } for ( count = 1; count<=16; count++) { LcdDataWrite(' '); } for ( count2 = 1; count2<=5; count2++) { int wrote2 [] = { 't', 'h', 'r','e','e',}; LcdDataWrite(wrote2[count2]); } for ( count = 1; count<=16; count++) { LcdDataWrite(' '); } for ( count = 1; count<=4; count++) { int wrote [] = { 'f', 'o', 'u','r'}; LcdDataWrite(wrote[count]); } for ( count = 1; count<=16; count++) { LcdDataWrite(' '); } LcdDataWrite('o') n e '); LcdDataWrite('two '); LcdDataWrite('three '); LcdDataWrite('four '); for ( count = 1; count<=20; count++) { LcdDataWrite(' '); }

140

141

for ( count = 1; count<=10; count++) { LcdNumberWrite2digits(count); } LcdDataWrite('w'); LcdDataWrite('i'); LcdDataWrite('t'); LcdDataWrite('h'); LcdDataWrite(' '); // and Number over 9 easyely like this LcdDataWrite('4'); LcdDataWrite('P'); LcdDataWrite('i'); LcdDataWrite('n'); LcdDataWrite('s'); */ for ( count = 0; count<=2; count++) { int wrote [] = { 'O', 'n', 'e',}; LcdDataWrite(wrote[count]); } for ( count = 0; count<=36; count++) { LcdDataWrite(' '); } for ( count = 0; count<=2; count++) { int wrote [] = { 'T','w','o',}; LcdDataWrite(wrote[count]); } delay(1000); for ( count = 0; count<=36; count++) { LcdDataWrite(' '); } for ( count = 0; count<=3; count++) { int wrote [] = { 'T','r','e','e',}; LcdDataWrite(wrote[count]); } delay(1000); for ( count = 0; count<=35; count++) { LcdDataWrite(' '); } for ( count = 0; count<=3; count++) { int wrote [] = { 'F','o','r','t',}; LcdDataWrite(wrote[count]); }

141

142

delay(1000); }

//example use of LCD4Bit library #include <LCD4Bit.h> //create object to control an LCD. //number of lines in display=1 LCD4Bit lcd = LCD4Bit(2); //some messages to display on the LCD char msgs[6][15] = {"apple", "banana", "pineapple", "mango", "watermelon", "pear"}; int NUM_MSGS = 6;

void setup() { pinMode(13, OUTPUT);

//we'll use the debug LED to output a heartbeat

lcd.init(); //optionally, now set up our application-specific display settings, overriding whatever the lcd did in lcd.init() lcd.commandWrite(0x0F);//cursor on, display on, blink on. (nasty!) } void loop() { digitalWrite(13, HIGH);

//light the debug LED

//pick a random message from the array int pick = random(NUM_MSGS); char* msg = msgs[pick]; lcd.clear(); lcd.printIn(msg); delay(1000); digitalWrite(13, LOW); //print some dots individually for (int i=0; i<3; i++){ lcd.print('.'); delay(100); } //print something on the display's second line. //uncomment this if your display HAS two lines! /* lcd.cursorTo(2, 0); //line=2, x=0. lcd.printIn("Score: 6/7"); delay(1000); */

142

143 //scroll entire display 20 chars to left, delaying 50ms each inc lcd.leftScroll(20, 50);

/* * LCD 4bit interface example * 2006 Massimo Banzi * Based on code written by Craig Lee 1998 * */ //COLOCAR ESSES CODIFICACAO DOS WIRES PARA FUNCIONAR COM ESSE CODIGO #define #define #define #define #define #define LCD_RS LCD_EN LCD_D4 LCD_D5 LCD_D6 LCD_D7 8 9 // // // // // Register select // Enable Data bits Data bits Data bits Data bits

10 11 12 13

void lcd_strobe() { digitalWrite(LCD_EN,HIGH); digitalWrite(LCD_EN,LOW); } /* write a byte to the LCD in 4 bit mode */ void lcd_write(byte c) { if(c & 0x80) digitalWrite(LCD_D7,HIGH); digitalWrite(LCD_D7,LOW); if(c & 0x40) digitalWrite(LCD_D6,HIGH); digitalWrite(LCD_D6,LOW); if(c & 0x20) digitalWrite(LCD_D5,HIGH); digitalWrite(LCD_D5,LOW); if(c & 0x10) digitalWrite(LCD_D4,HIGH); digitalWrite(LCD_D4,LOW); lcd_strobe(); if(c & 0x08) digitalWrite(LCD_D7,HIGH); digitalWrite(LCD_D7,LOW); if(c & 0x04) digitalWrite(LCD_D6,HIGH); digitalWrite(LCD_D6,LOW); if(c & 0x02) digitalWrite(LCD_D5,HIGH); digitalWrite(LCD_D5,LOW); if(c & 0x01) digitalWrite(LCD_D4,HIGH); digitalWrite(LCD_D4,LOW); lcd_strobe(); delayMicroseconds(40); } /* * Clear and home the LCD

else else else else else else else else

143

144 */ void lcd_clear(void) { digitalWrite(LCD_RS,LOW); lcd_write(0x1); delay(2); } /* write a string of chars to the LCD */ void lcd_puts(const char * s) { digitalWrite(LCD_RS,HIGH); while(*s) lcd_write(*s++); } /* write one character to the LCD */ void lcd_putch(byte c) { digitalWrite(LCD_RS,HIGH); // write characters lcd_write(c); } /* * Go to the specified position */ void lcd_goto(byte pos) { digitalWrite(LCD_RS,0); } lcd_write(0x80 + pos);

// write characters

/* initialise the LCD - put into 4 bit mode */ void lcd_init(void) { pinMode(LCD_D7,OUTPUT); pinMode(LCD_D6,OUTPUT); pinMode(LCD_D5,OUTPUT); pinMode(LCD_D4,OUTPUT); pinMode(LCD_EN,OUTPUT); pinMode(LCD_RS,OUTPUT); digitalWrite(LCD_RS, LOW); // write control bytes

144

145

delay(15);// power on delay digitalWrite(LCD_D4, HIGH); // init! digitalWrite(LCD_D5, HIGH); // lcd_strobe(); delay(5); lcd_strobe();// init! delayMicroseconds(100); lcd_strobe();// init! delay(5); digitalWrite(LCD_D4, LOW); lcd_strobe(); delayMicroseconds(40); lcd_write(0x28);// lcd_write(0x0C);// lcd_write(0x06);// lcd_write(0x01);// // set 4 bit mode

4 bit mode, 1/16 duty, 5x8 font, 2lines display on entry mode advance cursor clear display and reset cursor

void setup() { lcd_init(); } void loop() { lcd_puts("hello world"); }

145

146

MOTO
#define LED 13 #define BUTTON 10 int int int int int int int int int int int led3 = led4 = led5 = led6 = led7 = led8 = led9 = led10= time1= time2= time3= 3; 4; 5; 6; 7; 8; 9; 10; 90; 500; 1000;

int val = 0; int var = 0; void F1() { digitalWrite(led3, HIGH); digitalWrite(led4, HIGH); digitalWrite(led5, HIGH); digitalWrite(led6, HIGH); digitalWrite(led7, HIGH); digitalWrite(led8, HIGH); digitalWrite(led9, HIGH); digitalWrite(led10,HIGH); delay(time1); } void F2() { digitalWrite(led3, LOW); digitalWrite(led4, LOW); digitalWrite(led5, LOW); digitalWrite(led6, LOW); digitalWrite(led7, LOW); digitalWrite(led8, LOW); digitalWrite(led9, LOW); digitalWrite(led10,LOW); delay(time1); } void setup() { pinMode(LED, OUTPUT); pinMode(BUTTON, INPUT); pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(led5, OUTPUT);

146

147 pinMode(led6, OUTPUT); pinMode(led7, OUTPUT); pinMode(led8, OUTPUT); pinMode(led9, OUTPUT); pinMode(led10,OUTPUT); } void loop() { val = digitalRead(BUTTON); if (val == LOW) { // digitalWrite(LED, HIGH); var = var + 1; switch (var) { case 1: F1(); //break; // break is optional case 2: F2(); // break; var = 0; } }

} /*

if (val == HIGH) { digitalWrite(LED, HIGH); } else { }

digitalWrite(LED, LOW);

*/

147

148 EXEMPLO 2 // Example 05: Turn on LED when the button is pressed // and keep it on after it is released // including simple de-bouncing. // If the button is held, brightness changes. // // Copy and paste this example into an empty Arduino sketch #define LED 13 // the pin for the LED #define BUTTON 10 // input pin of the pushbutton int int int int int int int int int int int led3 = led4 = led5 = led6 = led7 = led8 = led9 = led10= time1= time2= time3= 3; 4; 5; 6; 7; 8; 9; 10; 100; 500; 1000; // stores the state of the input pin // stores the previous value of "val" // 0 = LED off while 1 = LED on

int val = 0; int var = 0;

int old_val = 0; int state = 0;

void F1() { digitalWrite(led3, HIGH); digitalWrite(led4, HIGH); digitalWrite(led5, HIGH); digitalWrite(led6, HIGH); digitalWrite(led7, HIGH); digitalWrite(led8, HIGH); digitalWrite(led9, HIGH); digitalWrite(led10,HIGH); } delay(time1);

void F2() { digitalWrite(led3, LOW); digitalWrite(led4, LOW); digitalWrite(led5, LOW); digitalWrite(led6, LOW); digitalWrite(led7, LOW); digitalWrite(led8, LOW); digitalWrite(led9, LOW); digitalWrite(led10,LOW); } delay(time1);

148

149

void setup() { Serial.begin(9600); pinMode(LED, OUTPUT); // tell Arduino LED is an output pinMode(BUTTON, INPUT); // and BUTTON is an input pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(led5, OUTPUT); pinMode(led6, OUTPUT); pinMode(led7, OUTPUT); pinMode(led8, OUTPUT); pinMode(led9, OUTPUT); pinMode(led10,OUTPUT); } void loop() { val = digitalRead(BUTTON); // read input value and store it // check if there was a transition if ((val == HIGH) && (old_val == LOW)) { state = 1 - state; // change the state from off to on // or vice-versa if (val != old_val){ var++; if (var > 2) var = 1; }

Serial.print(var); delay(10); old_val = val; if (state == 1) { analogWrite(LED, 255); // turn LED ON at the level } else { analogWrite(LED, 0); // turn LED OFF } } // current brightness

149

150 EXEMPLO 3 // Example 05: Turn on LED when the button is pressed // and keep it on after it is released // including simple de-bouncing. // If the button is held, brightness changes. // // Copy and paste this example into an empty Arduino sketch #define LED 13 // the pin for the LED #define BUTTON 10 // input pin of the pushbutton int int int int int int int int int int int led3 = led4 = led5 = led6 = led7 = led8 = led9 = led10= time1= time2= time3= 3; 4; 5; 6; 7; 8; 9; 10; 100; 500; 1000; // stores the state of the input pin // stores the previous value of "val" // 0 = LED off while 1 = LED on

int val = 0; int var = 0;

int old_val = 0; int state = 0;

void F1() { digitalWrite(led3, HIGH); digitalWrite(led4, HIGH); digitalWrite(led5, HIGH); digitalWrite(led6, HIGH); digitalWrite(led7, HIGH); digitalWrite(led8, HIGH); digitalWrite(led9, HIGH); digitalWrite(led10,HIGH); delay(time1); } void F2() { digitalWrite(led3, LOW); digitalWrite(led4, LOW); digitalWrite(led5, LOW); digitalWrite(led6, LOW); digitalWrite(led7, LOW); digitalWrite(led8, LOW); digitalWrite(led9, LOW); digitalWrite(led10,LOW); Serial.print(8); } delay(time1);

150

151

void setup() { Serial.begin(9600); pinMode(LED, OUTPUT); // tell Arduino LED is an output pinMode(BUTTON, INPUT); // and BUTTON is an input pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(led5, OUTPUT); pinMode(led6, OUTPUT); pinMode(led7, OUTPUT); pinMode(led8, OUTPUT); pinMode(led9, OUTPUT); pinMode(led10,OUTPUT); } void loop() { val = digitalRead(BUTTON); // read input value and store it // check if there was a transition if ((val == HIGH) && (old_val == LOW)) { state = 1 - state; // change the state from off to on or vice-versa if (val != old_val){ var++; if (var > 2) var = 1; }

Serial.print(var); delay(20); old_val = val; if (state == 1) { analogWrite(LED, 255); // turn LED ON at the level } else { analogWrite(LED, 0); // turn LED OFF } }

// current brightness

151

152 EXEMPLO 4 // Example 05: Turn on LED when the button is pressed // and keep it on after it is released // including simple de-bouncing. // If the button is held, brightness changes. // // Copy and paste this example into an empty Arduino sketch #define LED 13 // the pin for the LED #define BUTTON 10 // input pin of the pushbutton int int int int int int int int int int int led3 = led4 = led5 = led6 = led7 = led8 = led9 = led10= time1= time2= time3= 3; 4; 5; 6; 7; 8; 9; 10; 100; 500; 1000; // stores the state of the input pin // stores the previous value of "val" // 0 = LED off while 1 = LED on

int val = 0; int var = 0;

int old_val = 0; int state = 0;

void F1() { digitalWrite(led3, HIGH); digitalWrite(led4, HIGH); digitalWrite(led5, HIGH); digitalWrite(led6, HIGH); digitalWrite(led7, HIGH); digitalWrite(led8, HIGH); digitalWrite(led9, HIGH); digitalWrite(led10,HIGH); } delay(time1);

void F2() { digitalWrite(led3, LOW); digitalWrite(led4, LOW); digitalWrite(led5, LOW); digitalWrite(led6, LOW); digitalWrite(led7, LOW); digitalWrite(led8, LOW); digitalWrite(led9, LOW); digitalWrite(led10,LOW); } delay(time1);

152

153

void setup() { Serial.begin(9600); pinMode(LED, OUTPUT); // tell Arduino LED is an output pinMode(BUTTON, INPUT); // and BUTTON is an input pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(led5, OUTPUT); pinMode(led6, OUTPUT); pinMode(led7, OUTPUT); pinMode(led8, OUTPUT); pinMode(led9, OUTPUT); pinMode(led10,OUTPUT); } void loop() { val = digitalRead(BUTTON); // read input value and store it // check if there was a transition if ((val == HIGH) && (old_val == LOW)) { state = 1 - state; // change the state from off to on // or vice-versa if (val != old_val){ var++; if (var > 2) var = 1; }

Serial.print(var); delay(10); old_val = val; if (state == 1) { analogWrite(LED, 255); // turn LED ON at the level } else { analogWrite(LED, 0); // turn LED OFF } } // current brightness

153

154 EXEMPLO 5 // Example 05: Turn on LED when the button is pressed // and keep it on after it is released // including simple de-bouncing. // If the button is held, brightness changes. // // Copy and paste this example into an empty Arduino sketch #define LED 13 // the pin for the LED #define BUTTON 10 // input pin of the pushbutton int int int int int int int int int int int led3 = led4 = led5 = led6 = led7 = led8 = led9 = led10= time1= time2= time3= 3; 4; 5; 6; 7; 8; 9; 10; 100; 500; 1000; // stores the state of the input pin // stores the previous value of "val" // 0 = LED off while 1 = LED on

int val = 0; int var = 0;

int old_val = 0; int state = 0;

void F1() { digitalWrite(led3, HIGH); digitalWrite(led4, HIGH); digitalWrite(led5, HIGH); digitalWrite(led6, HIGH); digitalWrite(led7, HIGH); digitalWrite(led8, HIGH); digitalWrite(led9, HIGH); digitalWrite(led10,HIGH); delay(time1); } void F2() { digitalWrite(led3, LOW); digitalWrite(led4, LOW); digitalWrite(led5, LOW); digitalWrite(led6, LOW); digitalWrite(led7, LOW); digitalWrite(led8, LOW); digitalWrite(led9, LOW); digitalWrite(led10,LOW); Serial.print(8); } delay(time1);

154

155

void setup() { Serial.begin(9600); pinMode(LED, OUTPUT); // tell Arduino LED is an output pinMode(BUTTON, INPUT); // and BUTTON is an input pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(led5, OUTPUT); pinMode(led6, OUTPUT); pinMode(led7, OUTPUT); pinMode(led8, OUTPUT); pinMode(led9, OUTPUT); pinMode(led10,OUTPUT); } void loop() { val = digitalRead(BUTTON); // read input value and store it // check if there was a transition if ((val == HIGH) && (old_val == LOW)) { state = 1 - state; // change the state from off to on or vice-versa if (val != old_val){ var++; if (var > 2) var = 1; }

Serial.print(var); delay(20); old_val = val; if (state == 1) { analogWrite(LED, 255); // turn LED ON at the level } else { analogWrite(LED, 0); // turn LED OFF } }

// current brightness

155

156 EXEMPLO 6 #define LED 13 #define BUTTON 10 int int int int int int int int int int int led3 = led4 = led5 = led6 = led7 = led8 = led9 = led10= time1= time2= time3= 3; 4; 5; 6; 7; 8; 9; 10; 90; 500; 1000;

int val = 0; int var = 0; void F1() { digitalWrite(led3, HIGH); digitalWrite(led4, HIGH); digitalWrite(led5, HIGH); digitalWrite(led6, HIGH); digitalWrite(led7, HIGH); digitalWrite(led8, HIGH); digitalWrite(led9, HIGH); digitalWrite(led10,HIGH); delay(time1); } void F2() { digitalWrite(led3, LOW); digitalWrite(led4, LOW); digitalWrite(led5, LOW); digitalWrite(led6, LOW); digitalWrite(led7, LOW); digitalWrite(led8, LOW); digitalWrite(led9, LOW); digitalWrite(led10,LOW); delay(time1); } void setup() { pinMode(LED, OUTPUT); pinMode(BUTTON, INPUT); pinMode(led3, pinMode(led4, pinMode(led5, pinMode(led6, pinMode(led7, pinMode(led8, OUTPUT); OUTPUT); OUTPUT); OUTPUT); OUTPUT); OUTPUT);

156

157 pinMode(led9, OUTPUT); pinMode(led10,OUTPUT);

void loop() { val = digitalRead(BUTTON); if (val == LOW) { // digitalWrite(LED, HIGH); var = var + 1; switch (var) { case 1: F1(); //break; // break is optional case 2: F2(); // break; var = 0; } }

} /* if (val == HIGH) { digitalWrite(LED, HIGH); } else { } */ digitalWrite(LED, LOW);

157

158

POV
/* ???????????????????????????????????????????? persistence of vision typography with arduino michael zoellner - march 2006 http://i.document.m05.de connect anodes (+) of 5 leds to digital ports of the arduino board and put 20-50 ohm resistors from the cathode (-) to ground. the letters are lookup tables consisting arrays width the dot status in y rows. ???????????????????????????????????????????? */ // defining the alphabet int _[] = {0,0,0,0,0, 0,0,0,0,0, int A[] = {0,1,1,1,1, 1,0,1,0,0, int B[] = {1,1,1,1,1, 1,0,1,0,1, int C[] = {0,1,1,1,0, 1,0,0,0,1, int D[] = {1,1,1,1,1, 1,0,0,0,1, int E[] = {1,1,1,1,1, 1,0,1,0,1, int F[] = {1,1,1,1,1, 1,0,1,0,0, int G[] = {0,1,1,1,0, 1,0,1,0,1, int H[] = {1,1,1,1,1, 0,0,1,0,0, int I[] = {0,0,0,0,1, 1,0,1,1,1, int J[] = {1,0,0,0,0, 1,0,0,0,1, int K[] = {1,1,1,1,1, 0,0,1,0,0, int L[] = {1,1,1,1,1, 0,0,0,0,1, int M[] = {1,1,1,1,1, 0,1,1,0,0, int N[] = {1,1,1,1,1, 1,0,0,0,0, int O[] = {0,1,1,1,0, 1,0,0,0,1, int P[] = {1,1,1,1,1, 1,0,1,0,0, int Q[] = {0,1,1,1,1, 1,0,0,1,1, int R[] = {1,1,1,1,1, 1,0,1,0,0, int S[] = {0,1,0,0,1, 1,0,1,0,1, int T[] = {1,0,0,0,0, 1,1,1,1,1, int U[] = {1,1,1,1,1, 0,0,0,0,1, int V[] = {1,1,1,1,0, 0,0,0,0,1, int W[] = {1,1,1,1,0, 0,0,1,1,0, int X[] = {1,1,0,1,1, 0,0,1,0,0, int Y[] = {1,1,0,0,0, 0,0,1,0,0, int Z[] = {1,0,0,1,1, 1,0,1,0,1, int letterSpace; int dotTime; void setup() { // setting the ports of the leds to OUTPUT pinMode(2, OUTPUT); pinMode(3, OUTPUT);

0,0,0,0,0}; 0,1,1,1,1}; 0,1,0,1,0}; 1,0,0,0,1}; 0,1,1,1,0}; 1,0,1,0,1}; 1,0,1,0,0}; 0,0,1,1,0}; 1,1,1,1,1}; 0,0,0,0,1}; 1,1,1,1,1}; 0,1,0,1,1}; 0,0,0,0,1}; 0,1,1,1,1}; 0,1,1,1,1}; 0,1,1,1,0}; 0,1,0,0,0}; 0,1,1,1,1}; 0,1,0,1,1}; 1,0,0,1,0}; 1,0,0,0,0}; 1,1,1,1,1}; 1,1,1,1,0}; 1,1,1,1,0}; 1,1,0,1,1}; 1,1,1,1,1}; 1,1,0,0,1};

158

159 pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); // defining the space between the letters (ms) letterSpace = 6; // defining the time dots appear (ms) dotTime = 3; } void printLetter(int letter[]) { int y; // printing the first y row of the letter for (y=0; y<5; y++) { digitalWrite(y+2, letter[y]); } delay(dotTime); // printing the second y row of the letter for (y=0; y<5; y++) { digitalWrite(y+2, letter[y+5]); } delay(dotTime); // printing the third y row of the letter for (y=0; y<5; y++) { digitalWrite(y+2, letter[y+10]); } delay(dotTime); // printing the sspace between the letters for (y=0; y<5; y++) { digitalWrite(y+2, 0); } delay(letterSpace);

void loop() { // printing some letters printLetter(N); printLetter(E); printLetter(R); printLetter(D); printLetter(S); printLetter(_); }

159

160 EXEMPLO 2 #define time 500 int greenPin1 = 13; 11 int bluePin1 = 12; 10 int redPin1 = 11; int greenPin2 = 10; 11 int bluePin2 = 9; int redPin2 = 8; int greenPin3 = 7; 11 int bluePin3 = 6; 10 int redPin3 = 5; int greenPin4 = 4; 11 int bluePin4 = 3; 10 int redPin4 = 2; int bluePin5 10 int redPin5 = 1; = 0; // Green LED connected to digital pin // Green LED connected to digital pin // Red LED connected to digital pin 12 // Green LED connected to digital pin // Green LED connected to digital pin 10 // Red LED connected to digital pin 12 // Green LED connected to digital pin // Green LED connected to digital pin // Red LED connected to digital pin 12 // Green LED connected to digital pin // Green LED connected to digital pin // Red LED connected to digital pin 12 // Green LED connected to digital pin // Red LED connected to digital pin 12 // run once, when the sketch starts // sets the digital pin as output // sets the digital pin as output // sets the digital pin as output // sets the digital pin as output // sets the digital pin as output // sets the digital pin as output // sets the digital pin as output // sets the digital pin as output // sets the digital pin as output // sets the digital pin as output // sets the digital pin as output // sets the digital pin as output // sets the digital pin as output // sets the digital pin as output // sets the Red LED on // sets the Red LED on // sets the Red LED on // sets the Red LED on

void setup() { pinMode(redPin1, OUTPUT); pinMode(greenPin1, OUTPUT); pinMode(bluePin1, OUTPUT); pinMode(redPin2, OUTPUT); pinMode(greenPin2, OUTPUT); pinMode(bluePin2, OUTPUT); pinMode(redPin3, OUTPUT); pinMode(greenPin3, OUTPUT); pinMode(bluePin3, OUTPUT); pinMode(redPin4, OUTPUT); pinMode(greenPin4, OUTPUT); pinMode(bluePin4, OUTPUT); pinMode(bluePin5, pinMode(redPin5, OUTPUT); OUTPUT); HIGH); HIGH); HIGH); HIGH);

digitalWrite(redPin1, digitalWrite(greenPin1, digitalWrite(bluePin1, digitalWrite(redPin2,

160

161 digitalWrite(greenPin2, digitalWrite(bluePin2, digitalWrite(redPin3, digitalWrite(greenPin3, digitalWrite(bluePin3, digitalWrite(redPin4, digitalWrite(greenPin4, digitalWrite(bluePin4, digitalWrite(bluePin5, digitalWrite(redPin5, } void loop() { digitalWrite(redPin1, delay(time); digitalWrite(redPin1, // run over and over again LOW); // sets the Red LED on // waits for half a second HIGH); // sets the Red LED on HIGH); HIGH); HIGH); HIGH); HIGH); HIGH); HIGH); HIGH); HIGH); HIGH); // sets the Red LED on // sets the Red LED on // sets the Red LED on // sets the Red LED on // sets the Red LED on // sets the Red LED on // sets the Red LED on // sets the Red LED on // sets the Red LED on // sets the Red LED on

digitalWrite(greenPin1, LOW); // sets the Green LED on delay(time); // waits for half a second digitalWrite(greenPin1, HIGH); // sets the Green LED on digitalWrite(bluePin1, LOW); // sets the Green LED on delay(time); // waits for half a second digitalWrite(bluePin1, HIGH); // sets the Green LED on //-------------------------------------------------------digitalWrite(redPin2, delay(time); digitalWrite(redPin2, LOW); // sets the Red LED on // waits for half a second HIGH); // sets the Red LED on

digitalWrite(greenPin2, LOW); // sets the Green LED on delay(time); // waits for half a second digitalWrite(greenPin2, HIGH); // sets the Green LED on digitalWrite(bluePin2, LOW); // sets the Green LED on delay(time); // waits for half a second digitalWrite(bluePin2, HIGH); // sets the Green LED on //-------------------------------------------------------digitalWrite(redPin3, delay(time); digitalWrite(redPin3, LOW); // sets the Red LED on // waits for half a second HIGH); // sets the Red LED on

digitalWrite(greenPin3, LOW); // sets the Green LED on delay(time); // waits for half a second digitalWrite(greenPin3, HIGH); // sets the Green LED on digitalWrite(bluePin3, LOW); // sets the Green LED on delay(time); // waits for half a second digitalWrite(bluePin3, HIGH); // sets the Green LED on //-------------------------------------------------------digitalWrite(redPin4, LOW); // sets the Red LED on

161

162 delay(time); digitalWrite(redPin4, // waits for half a second // sets the Red LED on

HIGH);

digitalWrite(greenPin4, LOW); // sets the Green LED on delay(time); // waits for half a second digitalWrite(greenPin4, HIGH); // sets the Green LED on digitalWrite(bluePin4, LOW); // sets the Green LED on delay(time); // waits for half a second digitalWrite(bluePin4, HIGH); // sets the Green LED on //-----------------------------------------------digitalWrite(bluePin5, delay(time); digitalWrite(bluePin5, digitalWrite(redPin5, delay(time); digitalWrite(redPin5, } LOW); HIGH); LOW); HIGH); // sets the Red LED on // waits for half a second // sets the Red LED on // sets the Red LED on // waits for half a second // sets the Red LED on

162

163 EXEMPLO 3 //============================================================ // Arduino POV Display // // Author: Carlos Asmat // Last Modified: August 17, 2007 // // Description: this is a quick code for a POV display // implemented using the Arduino. It used 6 LEDs // connected to the pins. // See http://carlitoscontraptions.blogspot.com // for more details. //============================================================ int pins[] = {13,12,11,10,9,8,7,6,5,4,3,2}; int col_len = 12; // column lenght // an array of pin numbers

// customizable parameters int timer1 = 3; // time between columns int timer2 = 15; // time between frames int timer3 = 0; // time between drawings int frame_len = 5; // frame length int frame_num = 1; // number of frames // data corresponding to the image to be displayed //int data[] = {1,0,0,0,0,1,1,1,1,1,1,1, 1,1,0,0,1,1,1,1,1,1,1,1, 0,1,1,1,1,0,1,1,1,1,1,1, 0,0,1,1,0,0,1,1,1,1,1,1}; int data[] = {1,1,1,1,1,1,1,1,1,1,1,1, 1,1,0,0,0,1,1,0,0,0,0,0, 1,1,0,0,0,1,1,0,0,0,0,0, 1,1,0,0,0,1,1,0,0,0,0,0, 1,1,0,0,0,1,1,0,0,0,0,0}; void setup() { int i; for (i = 0; i < col_len; i++) pinMode(pins[i], OUTPUT); } void loop() { int a,b,c; // go through all data for all columns in each frame. for (a = 0; a < frame_num; a++) { for (b = 0; b < frame_len; b++) { for (c = 0; c < col_len; c++) { if (data[a*frame_len*col_len + b*col_len + c] == 0) {digitalWrite(pins[c], LOW);} else {digitalWrite(pins[c], HIGH);} } delay(timer1); } for (c = 0; c < col_len; c++) {digitalWrite(pins[c], LOW);}

// set each pin as an output

163

164 delay(timer2); } delay(timer3); }

164

165 EXEMPLO 4 //============================================================ // Arduino POV Display // // Author: Carlos Asmat // Last Modified: August 17, 2007 // // Description: this is a quick code for a POV display // implemented using the Arduino. It used 6 LEDs // connected to the pins. // See http://carlitoscontraptions.blogspot.com // for more details. //============================================================ int pins[] = {13,12,11,10,9,8,7,6,5,4,3,2}; int col_len = 12; // column lenght // an array of pin numbers

// customizable parameters int timer1 = 3; // time between columns int timer2 = 15; // time between frames 15 int timer3 = 20; // time between drawings int frame_len = 5; // frame length int frame_num = 3; // number of frames // data corresponding to the image to be displayed //int data[] = {1,0,0,0,0,1,1,1,1,1,1,1, 1,1,0,0,1,1,1,1,1,1,1,1, 0,1,1,1,1,0,1,1,1,1,1,1, 0,0,1,1,0,0,1,1,1,1,1,1}; int data[] = {1,1,1,1,1,1,1,1,1,1,1,1, 1,1,0,0,0,1,1,0,0,0,0,0, 1,1,0,0,0,1,1,0,0,0,0,0, 1,1,0,0,0,1,1,0,0,0,0,0, 1,1,0,0,0,1,1,0,0,0,0,0, 0,0,0,0,0,1,1,1,1,1,1,1, 1,1,1,1,1,0,0,0,0,0,0,0, 1,1,0,0,0,1,0,0,0,0,0,0, 1,1,1,1,1,0,0,0,0,0,0,0, 0,0,0,0,0,1,1,1,1,1,1,1, 0,0,0,0,0,1,1,0,0,0,0,0, 0,0,0,0,1,0,0,1,0,0,0,0, 1,1,1,1,0,0,0,0,1,1,1,1, 0,0,0,0,1,0,0,1,0,0,0,0, 0,0,0,0,0,1,1,0,0,0,0,0}; void setup() { int i; for (i = 0; i < col_len; i++) pinMode(pins[i], OUTPUT); } void loop() { int a,b,c; // go through all data for all columns in each frame. for (a = 0; a < frame_num; a++) { for (b = 0; b < frame_len; b++) { for (c = 0; c < col_len; c++) { if (data[a*frame_len*col_len + b*col_len + c] == 0) {digitalWrite(pins[c], LOW);}

// set each pin as an output

165

166 else {digitalWrite(pins[c], HIGH);} } delay(timer1); } for (c = 0; c < col_len; c++) {digitalWrite(pins[c], LOW);} delay(timer2); } delay(timer3); }

166

167 EXEMPLO 5 //============================================================ // Arduino POV Display // // Author: Carlos Asmat // Last Modified: August 17, 2007 // // Description: this is a quick code for a POV display // implemented using the Arduino. It used 6 LEDs // connected to the pins. // See http://carlitoscontraptions.blogspot.com // for more details. //============================================================ int pins[] = {13,12,11,10,9,8,7,6,5,4,3,2}; int col_len = 12; // column lenght // an array of pin numbers

// customizable parameters int timer1 = 3; // time between columns int timer2 = 15; // time between frames int timer3 = 0; // time between drawings int frame_len = 5; // frame length int frame_num = 1; // number of frames // data corresponding to the image to be displayed //int data[] = {1,0,0,0,0,1,1,1,1,1,1,1, 1,1,0,0,1,1,1,1,1,1,1,1, 0,1,1,1,1,0,1,1,1,1,1,1, 0,0,1,1,0,0,1,1,1,1,1,1}; int data[] = {1,1,1,1,1,1,1,1,1,1,1,1, 1,1,0,0,0,1,1,0,0,0,0,0, 1,1,0,0,0,1,1,0,0,0,0,0, 1,1,0,0,0,1,1,0,0,0,0,0, 1,1,0,0,0,1,1,0,0,0,0,0}; void setup() { int i; for (i = 0; i < col_len; i++) pinMode(pins[i], OUTPUT); } void loop() { int a,b,c; // go through all data for all columns in each frame. for (a = 0; a < frame_num; a++) { for (b = 0; b < frame_len; b++) { for (c = 0; c < col_len; c++) { if (data[a*frame_len*col_len + b*col_len + c] == 0) {digitalWrite(pins[c], LOW);} else {digitalWrite(pins[c], HIGH);} } delay(timer1); }

// set each pin as an output

167

168 for (c = 0; c < col_len; c++) {digitalWrite(pins[c], LOW);} delay(timer2); } delay(timer3); }

168

169

TEMPERATURA
/* Analog in to LCD 4 bits * --------* Adapted from the "analog_read_send" and "lcd_8bits" tutorials. * This example uses 4 less pins on the Arduino than the 8 bit example. * It will take a reading from a 'K' Type thermocouple ice point reference chip * on Analog Input 2 and display the temperature in degrees Centigrade on the LCD. * One can also set a target temperature for turning a relay off, say for a heater, * at a given setpoint temperature. This is done on digital pin 4. * * These are the pins used on the LCD: * * - DI(register select), RW, DB4..DB7, Enable (7 in total) * * the pinout for LCD displays is standard and there is plenty * of documentation to be found on the internet. * * 2006, Dave Sopchak glasspusher at outofoptions dot net * */ #define ProximaLeituraTemp int int int int int int led DI RW DB[] Enable count = = = = = = 13; 12; 11; {7, 8, 9, 10}; 6; 0; // analogic select the input pin for the // pin for the LED // variavel para armazenar o valor analogico lido //sensor de temperatura 4000

int analogPin = 0; temperature int ledPin = 13; int valAnalog ; int temperatura ; int v_lcd = 0;

//************************ //***** S P A C O S ****** //************************ void Spacos(int _spaces) { LcdCommandWrite(0x02); //move cursor to home postion delay(5); for (int i = 1;i < _spaces;++i) { LcdCommandWrite(0x14); delay(5); }

169

170 } //**************************************************** //**************** I m p r i m e LCD ***************** //**************************************************** void ImprimeLCD(int _linha, int _coluna, char msg[], int _tamanho) { if (_linha==1) Spacos(_coluna); else if (_linha==2) Spacos(_coluna+40); for (int i=0;i<_tamanho;++i) LcdDataWrite(msg[i]); } //**************************************************** //************* I m p r i m e LCD Numero ************* //**************************************************** void ImprimeLCDnumber(int _linha, int _coluna, int numero) { if (_linha==1) Spacos(_coluna); else if (_linha==2) Spacos(_coluna+40); LcdNumberWrite(numero); } //******************************* //**** C O M A N D W R I T E *** //******************************* void LcdCommandWrite(int value) { int i = 0; int value1 = 0; value1 = value; value1 >>= 4; //send the first 4 databits (from 8) + RW and DI for (i=DB[0]; i <= DI; i++) { digitalWrite(i,value1 & 01); value1 >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet delay(1); for (i=DB[0]; i <= DB[3]; i++) { // secound part of the secound 4 bits (from 8) digitalWrite(i,value & 01); value >>= 1; } value >>= 4; // send the RW and DI of the secound 4 bits(from 8) for (i=RW; i <= DI; i++) {

170

171 digitalWrite(i,value & 01); value >>= 1;

} digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet } //**************************** //**** D A T A W R I T E **** //**************************** void LcdDataWrite(int value) { int i = 0; int value1 = 0; digitalWrite(DI, HIGH); digitalWrite(RW, LOW); value1 =value; value1 >>= 4; //send the first 4 databits (from 8) for (i=DB[0]; i <= DB[3]; i++) { digitalWrite(i,value1 & 01); value1 >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet delay(1); digitalWrite(DI, HIGH); digitalWrite(RW, LOW); for (i=DB[0]; i <= DB[3]; i++) { digitalWrite(i,value & 01); value >>= 1; } digitalWrite(Enable,LOW); // send a pulse to enable delayMicroseconds(1); digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delayMicroseconds(1); // pause 1 ms according to datasheet } //**************************************************************** //********************* N U M B E R W R I T E ******************* //**************************************************************** // this funktion help us to write number over 9, easyely in the lcd display void LcdNumberWrite(int nr) { int n1 = 0; int n2 = 0; n1 = n2 = nr;

171

172

n1 = n1 / 100; LcdCommandWrite(560 + n1); //512 used to wirte data (see commands for character modul) n2 = (n2 - n1 * 100) / 10; LcdCommandWrite(560 + n2); //512 used to wirte data (see commands for character modul) nr = nr - n1 *100 - n2 * 10; LcdCommandWrite(560 + nr); //512 used to wirte data (see commands for character modul) } //*************** void piscaLed() { digitalWrite(ledPin, HIGH); delay(50) ; digitalWrite(ledPin, LOW); } //******************* int busca_lcd (void) { v_lcd = analogRead(5); return v_lcd; } //******************* int busca_temp (void) { valAnalog = analogRead(analogPin); 0

// Liga o led // Desliga o Led

// Le o pino de entrada analogica

temperatura= ( 5 * valAnalog * 100) / 1024 ; // calcula a temperatura // Serial.print(temperatura,BYTE) ; // envia um byte com a temperatura //Serial.println(temperatura) ; // envia uma string de dois caracteres com a temperatura delay(ProximaLeituraTemp) ; // aguarda 5 minutos para a proxima leitura de temperatura piscaLed() ; return temperatura-2; } //************************* char * IntToString(int num) { int i=0; int j=0; int k=0; int ones=0; char temp[5]; //5=num digits in 32676 char ans[5]; while (num!=0) { ones=num%10; //get current ones digit temp[i]=(char)(ones+48); //48=(int)'0'; num=num/10; //remove current ones digit

172

173 i++; //length of number } for(j=i-1;j>=0;j--) { ans[k]=temp[j]; //reorder string correctly k++; } ans[i]='\0'; //add null char for end of string return (char *)ans; } //*************** void setup (void) { int i = 0; for (i=Enable; i <= DI; i++) { pinMode(i,OUTPUT); } delay(100); // initiatize lcd after a short pause // needed by the LCDs controller ///////////////////////////////////////////////////// 4 pin initialization LcdCommandWrite(0x03); // function set: // 4 pin initialization delay(64); LcdCommandWrite(0x03); // function set: // 4 pin initialization delay(50); LcdCommandWrite(0x03); // function set: // 4 pin initialization delay(50); LcdCommandWrite(0x02); // function set: // 4 pin initialization delay(50); ///////////////////////////////////////////////////////////////////////// //// LcdCommandWrite(0x28); // function set: // 4-bit interface, 2 display lines, 5x7 font //LcdCommandWrite(0x2C); // function set: // 4-bit interface, 1 display lines, 5x7 font ///////////////////////////////////////////////////// end of 4 pin initialization delay(20); LcdCommandWrite(0x06); // entry mode set: // increment automatically, no display shift delay(20); LcdCommandWrite(0x0E); // display control: // turn display on, cursor on, no blinking delay(20); LcdCommandWrite(0x01); // clear display, set cursor position to zero delay(100);

173

174

LcdCommandWrite(0x80); // display control: delay(20); //////// unter this line are the special stuff you don't need for a initialitzation LcdCommandWrite(0x0F); // delay(10); cursor blink

LcdCommandWrite(0x01); // clear display, set the cursor to home position delay(1000); LcdCommandWrite(0x0E); // cursor not blink delay(10); LcdCommandWrite(0x02); // set cursor position to zero delay(10); } //************** void loop (void) { //>>>>>>>>>>>>>>>>>>>>>>>>>>>possible commands for the Lcd Display>>>>>>><< able to use for LcdDisplays with 4 or with 8 DataPins //LcdCommandWrite(0x01); // clear display, set the cursor to home position //LcdCommandWrite(0x02); // set cursor position to zero //LcdCommandWrite(0x0A); // set the display off //LcdCommandWrite(0x0E); // set the display on and with out cursor blink //LcdCommandWrite(0x0F); // set the display on and with cursor blink //LcdCommandWrite(0x0F); // cursor blink //LcdCommandWrite(0x0E); // cursor not blink //LcdCommandWrite(0x18); // shift display and cursor to the left //LcdCommandWrite(0x1c); // shift display and cursor to the right //LcdCommandWrite(0x14); // shift cursor to the right //LcdCommandWrite(0x10); // shift cursor to the left ImprimeLCD(1,1,"Temp: ",6); ImprimeLCDnumber(1,7,busca_temp()); ImprimeLCD(1,11,"L: ",5); ImprimeLCDnumber(1,14,busca_lcd()); ImprimeLCD(2,1,"Fabio Brandespim",16); //LcdCommandWrite(0x01); //limpa a tela e posiciona cursor no inicio //delay(10);

174

175 EXEMPLO 2 TEMP SENSOR 1 // // // // // int int int int Leitura de temperatura Arduino monitorando temperatura com LM35 atraves da funo analogRead() Autor: Jeronimo Avelar Filho 01/07/2007 ledPin = 13; analogPin = 5; valAnalog ; temperatura ; // LED ligado ao pino digital 13 // lm35 est ligado ao a entrada analogica 5 // variavel para armazenar o valor analogico lido

void setup() { pinMode(ledPin, OUTPUT); Serial.begin(9600); 9600 bps }

// programa o pino 13 como saida digital // programa a serial para comunicao em

void loop() { valAnalog = analogRead(analogPin); // Le o pino de entrada analogica 5 temperatura= ( 5 * valAnalog * 100) / 1024 ; // calcula a temperatura // Serial.print(temperatura,BYTE) ; // envia um byte com a temperatura Serial.println(temperatura) ; // envia uma string de dois caracteres com a temperatura delay( 300000) ; // aguarda 5 minutos para a proxima leitura de temperatura piscaLed() ; // chama a funcao para piscar o led } void piscaLed() { digitalWrite(ledPin, HIGH); delay(50) ; digitalWrite(ledPin, LOW); } // Liga o led // Desliga o Led

175

176 EXEMPLO 3 TEMP SENSOR 2 /** * Analog In * by <a href="http://itp.jtnimoy.com">Josh Nimoy</a>. * * Reads a value from the serial port and sets the background color. * Running this example requires you have a BX-24 microcontroller * and peripheral hardware. More information can be found on the tutorial * pages of Tom Igoe: http://stage.itp.nyu.edu/~tigoe/pcomp/examples.shtml * Because this program uses the serial port, it will not work within a web browser. * * Created 8 February 2003. * Updated 2 April 2005 * Updated 08 August 2077 by Jeronimo Avelar Filho: Temperature collecting and writing to a text file */ import processing.serial.*; String buff = ""; int val = 0; int NEWLINE = 10; int i = 0 ; PFont font; Serial port; PrintWriter output; void setup() { size(250, 200); background(255, 204, 0); font = loadFont("UniversLTStd-Light-48.vlw"); textFont(font, 32); // Print a list in case COM1 doesn't work out println("Available serial ports:"); println(Serial.list()); //port = new Serial(this, "COM1", 19200); // Uses the first available port port = new Serial(this, Serial.list()[0], 9600); output = createWriter("temperaturas.txt"); // cria arquivo para armazenar as temperaturas } void draw() { while (port.available() > 0) { serialEvent(port.read()); }

176

177 } void keyPressed() output.flush(); output.close(); exit(); // Stop } void { // // // // { // Press a key to save the data // Write the remaining data // Finish the file the program

serialEvent(int serial) If the variable "serial" is not equal to the value for a new line, add the value to the variable "buff". If the value "serial" is equal to the value for a new line, save the value of the buffer into the variable "val". println(serial) ; val=serial ; // Escreve a temperatura e a hora // output.println(hour() + ":" + minute() + ":" + second() + "," + val); //line(i,200,i,200-(val*4)) ; // funciona bem para a linha fill(102,0,153) ; rect(i,200-(val*4),2,val*4) ; // desenha a barra temperatura fill(255, 204, 0) ; noStroke() ; // nao desenha a borda do retangulo . rect(110,5,50,30) ; // apaga o texto anterior fill(102,0,153) ; text(val, 125, 30); fill(0, 102, 153);

i+=6 ; // se chegar ao limite da area de desenho , apaga tudo e recomea if(i>=250) { i=0 ; background(255, 204, 0); } }

177

178 EXEMPLO 4 TEMP SENSOR 3 /* An open-source LM35DZ Temperature Sensor for Arduino. This project will be enhanced on a regular basis (cc) by Daniel Spillere Andrade , http://www.danielandrade.net http://creativecommons.org/license/cc-gpl */ int int int int int pin = 0; // analog pin tempc = 0,tempf=0; // temperature variables samples[8]; // variables to make a better precision maxi = -100,mini = 100; // to start max/min temperature i;

void setup() { Serial.begin(9600); // start serial communication } void loop() { for(i = 0;i<=7;i++){ // gets 8 samples of temperature samples[i] = ( 5.0 * analogRead(pin) * 100.0) / 1024.0; tempc = tempc + samples[i]; delay(1000); } tempc = tempc/8.0; // better precision tempf = (tempc * 9)/ 5 + 32; // converts to fahrenheit if(tempc > maxi) {maxi = tempc;} // set max temperature if(tempc < mini) {mini = tempc;} // set min temperature Serial.print(tempc,DEC); Serial.print(" Celsius, "); Serial.print(tempf,DEC); Serial.print(" fahrenheit -> "); Serial.print(maxi,DEC); Serial.print(" Max, "); Serial.print(mini,DEC); Serial.println(" Min"); tempc = 0; delay(1000); // delay before loop }

178

179 EXEMPLO 5 TEMP SENSOR 4 NTC /* * * * * * * * * * * */ ap_ReadAnalog Reads an analog input from the input pin and sends the value followed by a line break over the serial port. This file is part of the Arduino meets Processing Project: For more information visit http://www.arduino.cc. copyleft 2005 by Melvin Ochsmann for Malm University

// variables for input pin and control LED int analogInput = 0; int LEDpin = 13; // variable to store the value int value = 0; // a threshold to decide when the LED turns on int threshold = 100; void setup(){ // declaration of pin modes pinMode(analogInput, INPUT); pinMode(LEDpin, OUTPUT); // begin sending over serial port beginSerial(9600); } void loop(){ // read the value on analog input value = analogRead(analogInput); // if value greater than threshold turn on LED if (value < threshold) digitalWrite(LEDpin, HIGH); else digitalWrite(LEDpin, LOW); // print out value over the serial port Serial.print(value); // printInteger(value); // and a signal that serves as seperator between two values Serial.print(10,BYTE); // wait for a bit to not overload the port delay(10); }

179

180 EXEMPLO 6 TEMP SENSOR 5 /* Temperature proof of concept. Using a LM35 and Arduino to read Temp to LCD. Eventual use for weather station and/or home automation routines. Need to redesign to eliminate useage of delay() Author: Brutus */ #define ledPin 13 #define lm35 0 //Defines will use less memory. sketches. // LED connected to digital pin 13 // LM35 on Analog 0 Not as crucial here, but future

void sendlcd(byte command) //Quick function to send LCD commands. { Serial.print(command, BYTE); } void setup() { analogReference(INTERNAL); pinMode(ledPin, OUTPUT); pinMode(lm35, INPUT); digitalWrite(ledPin, HIGH); digitalWrite(lm35, LOW); delay(1000); // run once, when the sketch starts // sets the digital pin as output

Serial.begin(9600); delay(1000); //Let Ports Stabilize //Reset Command For LCD sendlcd(27); sendlcd(122); delay(500); //Full Reset takes a bit //Backlight Command For LCD sendlcd(27); sendlcd(42); sendlcd(75); delay(50); //Clear and Go Home on LCD sendlcd(254); sendlcd(1); digitalWrite(ledPin, LOW); delay(250); // run over and over again

void loop() { long temp; long temp1; long temp2;

180

181 long temp_x; int lm35_val=0; digitalWrite(ledPin,HIGH); delay(500); //After digital write, delay to allow stabilized analog read lm35_val=analogRead(lm35); //temp = ((long)lm35_val*1100/1024); // Above changed.. using internal ref the read value seems closer to the truth temp = lm35_val; temp1=temp/10; temp2=temp%10; if (temp2 >= 5) { temp_x++; } //Clear LCD Screen sendlcd(254); sendlcd(1); //Print Obligitory Message Serial.println("brutusweb.com"); //Print Temp Serial.print(temp1); Serial.print("."); Serial.print(temp2); sendlcd(223); Serial.print("C"); digitalWrite(ledPin,LOW); delay(9500); }

181

182

ARDUINO CODIGO SERIAL (LER E ESCREVE NA SERIAL E PISCA LED)


void setup() { // initialize the digital pin as an output. // Pin 13 has an LED connected on most Arduino boards: pinMode(13, OUTPUT); Serial.begin(2400); } void loop() { // // digitalWrite(13, HIGH); // set the LED on delay(1000); // wait for a second Serial.println(70,BYTE); // digitalWrite(13, LOW); // set the LED off delay(1000); // wait for a second Serial.println(71,BYTE); delay(300); while (Serial.available() > 0) { int a; a = Serial.read(); Serial.println(a); if (a == 111) { // letra o digitalWrite(13, HIGH); // set the LED on delay(1000); // wait for a second digitalWrite(13, LOW); // set the LED on } // //ENVIA LETRA PARA SERIAL RECEBE NUMERO ASC Serial.println(Serial.read(),DEC); //ENVIA LETRA PARA SERIAL RECEBE LETRA Serial.println(a);

// } }

182

183

BLUETOOTH
void setup() { pinMode(13,OUTPUT); pinMode(12,OUTPUT); pinMode(11,OUTPUT); Serial.begin(115200); } void loop() { // digitalWrite(13, LOW); // delay(1000); // Serial.println(71,BYTE); //Serial.println('F');

//IMPORTANTE * Modulo bluesmirf funciona na //velocidade de 115200

// set the LED off // wait for a second

if (Serial.available() > 0) { char c = Serial.read(); Serial.println(c); if if if if if if (c (c (c (c (c (c == == == == == == '1') '2') '3') 'a') 'b') 'c') digitalWrite(13,HIGH); //49 digitalWrite(12,HIGH); digitalWrite(11,HIGH); digitalWrite(13,LOW); //65 digitalWrite(12,LOW); digitalWrite(11,LOW);

delay(1000); }

183

184

ARDUINO SERIAL
void setup() { // initialize the digital pin as an output. // Pin 13 has an LED connected on most Arduino boards: pinMode(13, OUTPUT); Serial.begin(2400); } void loop() { // // digitalWrite(13, HIGH); // set the LED on delay(1000); // wait for a second Serial.println(70,BYTE); // digitalWrite(13, LOW); // set the LED off delay(1000); // wait for a second Serial.println(71,BYTE); delay(300); while (Serial.available() > 0) { int a; a = Serial.read(); Serial.println(a); if (a == 111) { // letra o digitalWrite(13, HIGH); // set the LED on delay(1000); // wait for a second digitalWrite(13, LOW); // set the LED on } // //ENVIA LETRA PARA SERIAL RECEBE NUMERO ASC Serial.println(Serial.read(),DEC); //ENVIA LETRA PARA SERIAL RECEBE LETRA Serial.println(a);

// } }

184

185

BLUETOOTH COM 2 MOTORES


// Motor Shield test // by NKC Electronics // Test Motor B //Motor A int dirbpinA = 13; // Direction pin for motor B is Digital 13 int speedbpinA = 10; // Speed pin for motor B is Digital 10 (PWM) //Motor B int dirbpinB = 12; // Direction pin for motor B is Digital 12 int speedbpinB = 9; // Speed pin for motor B is Digital 9 (PWM) int speed = 100; int dir = 0; void setup() { pinMode(dirbpinA, OUTPUT); pinMode(dirbpinB, OUTPUT); Serial.begin(115200); } void loop() { if (Serial.available() > 0) { char c = Serial.read(); Serial.println(c); if (c == '1') { //Motor A ---------------------------------digitalWrite(dirbpinA, 0); // set direction analogWrite(speedbpinA, speed); // set speed (PWM) } if (c == '2') { //Motor A ---------------------------------digitalWrite(dirbpinA, 1); // set direction analogWrite(speedbpinA, speed); // set speed (PWM) } if (c == '3') { //Motor B ---------------------------------digitalWrite(dirbpinB, 0); // set direction analogWrite(speedbpinB, speed); // set speed (PWM) } if (c == '4') { //Motor B ---------------------------------digitalWrite(dirbpinB, 1); // set direction analogWrite(speedbpinB, speed); // set speed (PWM) } if (c == '0') { //Motor A ----------------------------------

185

186 digitalWrite(dirbpinA, 0); // set direction analogWrite(speedbpinA, 0); // set speed (PWM) //Motor B ---------------------------------digitalWrite(dirbpinB, 1); // set direction analogWrite(speedbpinB, 0); // set speed (PWM) if if if if if if (c (c (c (c (c (c == == == == == == '1') '2') '3') 'a') 'b') 'c') digitalWrite(13,HIGH); digitalWrite(12,HIGH); digitalWrite(11,HIGH); digitalWrite(13,LOW); digitalWrite(12,LOW); digitalWrite(11,LOW);

} // // // // // //

delay(1000); }

//dir = ((dir == 0) ? 1 : 0); // change direction // delay(20000); // 5 seconds }

186

187

SENSOR GRAPH AMARINO


/* */ Sends sensor data to Android (needs SensorGraph and Amarino app installed and running on Android)

#include <MeetAndroid.h> MeetAndroid meetAndroid; int sensor = A5; void setup() { // use the baud rate your bluetooth module is configured to // not all baud rates are working well, i.e. ATMEGA168 works best with 57600 Serial.begin(115200); // we initialize pin 5 as an input pin pinMode(sensor, INPUT); } void loop() { meetAndroid.receive(); // you need to keep this in your loop() to receive events // read input pin and send result to Android meetAndroid.send(analogRead(sensor)); // add a little delay otherwise the phone is pretty busy delay(100); }

187

You might also like