Manual Geral Arduino

265
Arduino 1 1

Transcript of Manual Geral Arduino

Page 1: Manual Geral Arduino

Arduino

1

1

Page 2: Manual Geral Arduino

Fabio [email protected]

Sunnyvale, CaSugestions and errors are welcome.

2

2

Page 3: Manual Geral Arduino

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.

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.

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!

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.

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 .

6 Publish your revised schematics and circuit board files so that others can modify them. The cycle begins again.

3

3

Page 4: Manual Geral Arduino

Attiny13

Atmega168

Resistor Chart

4

4

Page 5: Manual Geral Arduino

Arduino Breadboard

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

5

5

Page 6: Manual Geral Arduino

USB to Serial Communication Board

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

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

Atmega328

Flash memory 30KRAM 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.

6

6

Page 7: Manual Geral Arduino

Push Button Control LED

Componentes:

Resistor 10kInterruptor

#define LED 13#define BUTTON 7

int val = 0;

void setup() { pinMode(LED, OUTPUT); pinMode(BUTTON, INPUT);}

void loop(){ val = digitalRead(BUTTON); if (val == HIGH) { digitalWrite(LED, HIGH); } else { digitalWrite(LED, LOW); }}

7

7

Page 8: Manual Geral Arduino

LCD Sensor

Exemplo 1

//Blink LED at rate specified by the value of the analogue input

#define LED 13

int val = 0;

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

void loop(){ val = analogRead(0); digitalWrite(13, HIGH); delay(val); digitalWrite(13,LOW); Serial.println(val); delay(val); }

Componentes

Led Lcd light sensor 10k Resistor

8

8

Page 9: Manual Geral Arduino

Exemplo 2

int ledPin = 9; // PWM pin for the LEDint analogPin = 0; // variable resistor on analog pin 0void setup(){} // no setup neededvoid loop(){for (int i=0; i<=255; i++) // ascending value for i{analogWrite(ledPin, i); // sets brightess level to idelay(delayVal()); // gets time value and pauses}for (int i=255; i>=0; i--) // descending value for i{analogWrite(ledPin, i); // sets brightess level to idelay(delayVal()); // gets time value and pauses}}int delayVal(){int v; // create temporary variablev = analogRead(analogPin); // read analog valuev /= 8; // convert 0-1024 to 0-128return v; // returns final value}

9

9

Page 10: Manual Geral Arduino

Exemplo 3

//Set the brightness of LED to a brightness specified by the value of //the analogue input

#define LED 9

int val = 0;

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

void loop(){ val = analogRead(0); analogWrite(LED, val/4); Serial.println(val); delay(10);}

Componentes:

LCD light sensor 2 10k Resistor led

10

10

Page 11: Manual Geral Arduino

Fade LED in and out

Componetes

Led 10k Resistor

Exemplo 1

//Fade an LED in and out

#define LED 9

int i = 0;

int val = 0;

void setup() { pinMode(LED, OUTPUT);}

void loop(){ for (i=0; i < 255; i++) { analogWrite(LED, i); delay(10); } for (i = 255; i > 0; i --) { analogWrite(LED, i); delay(10); }}

11

11

Page 12: Manual Geral Arduino

Exemplo 2

//Fade an LED in and out

#define LED 9#define BUTTON 7

int val = 0;int old_val = 0;int state = 0;int brightness = 128;unsigned long startTime = 0;

void setup() { pinMode(LED, OUTPUT); pinMode(BUTTON,INPUT);}

void loop(){ val = digitalRead(BUTTON); if ((val == HIGH) && (old_val == LOW)) { state = 1 - state; startTime = millis(); delay(10); //Check whether the button is being held down if ((val == HIGH) && (old_val == HIGH)) { if (state == 1 && (millis() - startTime) > 500) { brightness++; delay(10); if (brightness > 255) { brightness = 0; } } } old_val = val; if (state == 1) { analogWrite(LED, brightness); } else { analogWrite(LED,0); }}}

12

12

Page 13: Manual Geral Arduino

NTC temp sensor

Componentes:

NTC Temp sensor 1 1k Resistor Led

/** 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(){

13

13

Page 14: Manual Geral Arduino

// 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 LEDif (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);}

14

14

Page 15: Manual Geral Arduino

Piezo Buzzer

Componetes

1 x Piezo Buzzer

Exemplo 1

int speakerPin = 9;

int length = 15; // the number of noteschar notes[] = "ccggaagffeeddc "; // a space represents a restint 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); } }}

15

15

Page 16: Manual Geral Arduino

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); }}

Exemplo 2

//Second version, with volume control set using analogWrite()

/* Play Melody * ----------- * * Program to play melodies stored in an array, it requires to know * about timing issues and about how to play tones. * * The calculation of the tones is made following the mathematical * operation: * * timeHigh = 1/(2 * toneFrequency) = period / 2 * * where the different tones are described as in the table: * * note frequency period PW (timeHigh) * c 261 Hz 3830 1915 * d 294 Hz 3400 1700 * e 329 Hz 3038 1519 * f 349 Hz 2864 1432 * g 392 Hz 2550 1275 * a 440 Hz 2272 1136 * b 493 Hz 2028 1014 * C 523 Hz 1912 956 * * (cleft) 2005 D. Cuartielles for K3 */

int ledPin = 13;int speakerOut = 9; byte names[] = {'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C'}; int tones[] = {1915, 1700, 1519, 1432, 1275, 1136, 1014, 956};byte melody[] = "2d2a1f2c2d2a2d2c2f2d2a2c2d2a1f2c2d2a2a2g2p8p8p8p";// count length: 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0

16

16

Page 17: Manual Geral Arduino

// 10 20 30int count = 0;int count2 = 0;int count3 = 0;int MAX_COUNT = 24;int statePin = LOW;

void setup() { pinMode(ledPin, OUTPUT); }

void loop() { analogWrite(speakerOut, 0); for (count = 0; count < MAX_COUNT; count++) { statePin = !statePin; digitalWrite(ledPin, statePin); for (count3 = 0; count3 <= (melody[count*2] - 48) * 30; count3++) { for (count2=0;count2<8;count2++) { if (names[count2] == melody[count*2 + 1]) { analogWrite(speakerOut,500); delayMicroseconds(tones[count2]); analogWrite(speakerOut, 0); delayMicroseconds(tones[count2]); } if (melody[count*2 + 1] == 'p') { // make a pause of a certain size analogWrite(speakerOut, 0); delayMicroseconds(500); } } } }}

Exemplo 3

/* Play Melody * ----------- * * Program to play a simple melody * * Tones are created by quickly pulsing a speaker on and off * using PWM, to create signature frequencies. * * Each note has a frequency, created by varying the period of * vibration, measured in microseconds. We'll use pulse-width * modulation (PWM) to create that vibration.

* We calculate the pulse-width to be half the period; we pulse * the speaker HIGH for 'pulse-width' microseconds, then LOW * for 'pulse-width' microseconds. * This pulsing creates a vibration of the desired frequency. *

17

17

Page 18: Manual Geral Arduino

* (cleft) 2005 D. Cuartielles for K3 * Refactoring and comments 2006 [email protected] * See NOTES in comments at end for possible improvements */

// TONES ==========================================// Start by defining the relationship between // note, period, & frequency. int c = 3830; // 261 Hz int d = 3400; // 294 Hz int e = 3038; // 329 Hz int f = 2864; // 349 Hz int g = 2550; // 392 Hz int a = 2272; // 440 Hz int b = 2028; // 493 Hz int C = 1912; // 523 Hz // Definea special note, 'R', to represent a restint R = 0;

// SETUP ============================================// Set up speaker on a PWM pin (digital 9, 10 or 11)int speakerOut = 9;// Do we want debugging on serial out? 1 for yes, 0 for noint DEBUG = 1;

void setup() { pinMode(speakerOut, OUTPUT); if (DEBUG) { Serial.begin(9600); // Set serial out if we want debugging } }

// MELODY and TIMING =======================================// melody[] is an array of notes, accompanied by beats[], // which sets each note's relative length (higher #, longer note) int melody[] = { C, b, g, C, b, e, R, C, c, g, a, C };int beats[] = { 16, 16, 16, 8, 8, 16, 32, 16, 16, 16, 8, 8 }; int MAX_COUNT = sizeof(melody) / 2; // Melody length, for looping.

// Set overall tempolong tempo = 10000;// Set length of pause between notesint pause = 1000;// Loop variable to increase Rest lengthint rest_count = 100; //<-BLETCHEROUS HACK; See NOTES

// Initialize core variablesint tone = 0;int beat = 0;long duration = 0;

// PLAY TONE ==============================================// Pulse the speaker to play a tone for a particular durationvoid playTone() { long elapsed_time = 0; if (tone > 0) { // if this isn't a Rest beat, while the tone has // played less long than 'duration', pulse speaker HIGH and LOW

18

18

Page 19: Manual Geral Arduino

while (elapsed_time < duration) {

digitalWrite(speakerOut,HIGH); delayMicroseconds(tone / 2);

// DOWN digitalWrite(speakerOut, LOW); delayMicroseconds(tone / 2);

// Keep track of how long we pulsed elapsed_time += (tone); } } else { // Rest beat; loop times delay for (int j = 0; j < rest_count; j++) { // See NOTE on rest_count delayMicroseconds(duration); } } }

// LET THE WILD RUMPUS BEGIN =============================void loop() { // Set up a counter to pull from melody[] and beats[] for (int i=0; i<MAX_COUNT; i++) { tone = melody[i]; beat = beats[i];

duration = beat * tempo; // Set up timing

playTone(); // A pause between notes... delayMicroseconds(pause);

if (DEBUG) { // If debugging, report loop, tone, beat, and duration Serial.print(i); Serial.print(":"); Serial.print(beat); Serial.print(" "); Serial.print(tone); Serial.print(" "); Serial.println(duration); } }}

/* * NOTES * The program purports to hold a tone for 'duration' microseconds. * Lies lies lies! It holds for at least 'duration' microseconds, _plus_ * any overhead created by incremeting elapsed_time (could be in excess of * 3K microseconds) _plus_ overhead of looping and two digitalWrites() * * As a result, a tone of 'duration' plays much more slowly than a rest * of 'duration.' rest_count creates a loop variable to bring 'rest' beats * in line with 'tone' beats of the same length.

19

19

Page 20: Manual Geral Arduino

* * rest_count will be affected by chip architecture and speed, as well as * overhead from any program mods. Past behavior is no guarantee of future * performance. Your mileage may vary. Light fuse and get away. * * This could use a number of enhancements: * ADD code to let the programmer specify how many times the melody should * loop before stopping * ADD another octave * MOVE tempo, pause, and rest_count to #define statements * RE-WRITE to include volume, using analogWrite, as with the second program at * http://www.arduino.cc/en/Tutorial/PlayMelody * ADD code to make the tempo settable by pot or other input device * ADD code to take tempo or volume settable by serial communication * (Requires 0005 or higher.) * ADD code to create a tone offset (higer or lower) through pot etc * REPLACE random melody with opening bars to 'Smoke on the Water' */

20

20

Page 21: Manual Geral Arduino

LM35 Temp Sensor

Componetes:LM35 Temp Sensor100K ResistorLed

Exemplo 1

// Leitura de temperatura // Arduino monitorando temperatura com LM35 atraves da função analogRead() // Autor: Fabio Brandespim

int ledPin = 13; // LED ligado ao pino digital 13int analogPin = 5; // lm35 está ligado ao a entrada analogica 5int valAnalog ; // variavel para armazenar o valor analogico lidoint temperatura ;

void setup(){ pinMode(ledPin, OUTPUT); // programa o pino 13 como saida digital Serial.begin(9600); // programa a serial para comunicação em 9600 bps}

21

21

Page 22: Manual Geral Arduino

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); // Liga o led delay(50) ; digitalWrite(ledPin, LOW); // Desliga o Led}

22

22

Page 23: Manual Geral Arduino

Ping Ultrasonic Range Finder

//The 5V pin of the PING))) is connected to the 5V pin on the Arduino, the GND pin is connected to the GND //pin, and the SIG (signal) pin is connected to digital pin 7 on the Arduino.

Exemplo 1

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

23

23

Page 24: Manual Geral Arduino

// 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;}

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);

24

24

Page 25: Manual Geral Arduino

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. }

25

25

Page 26: Manual Geral Arduino

GPS

26

26

Page 27: Manual Geral Arduino

Exemplo 1

//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; // LED test pin int rxPin = 0; // RX PIN int txPin = 1; // TX TX 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); // 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]=' '; } } 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++; }

27

27

Page 28: Manual Geral Arduino

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

28

28

Page 29: Manual Geral Arduino

LCD

/* 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;

//************************

29

29

Page 30: Manual Geral Arduino

//***** 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) {int i = 0;int value1 = 0;value1 = value;

value1 >>= 4; //send the first 4 databits (from 8) + RW and DIfor (i=DB[0]; i <= DI; i++) { digitalWrite(i,value1 & 01); value1 >>= 1;}digitalWrite(Enable,LOW); // send a pulse to enabledelayMicroseconds(1);digitalWrite(Enable,HIGH);delayMicroseconds(1);digitalWrite(Enable,LOW);delayMicroseconds(1); // pause 1 ms according to datasheetdelay(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;}

30

30

Page 31: Manual Geral Arduino

digitalWrite(Enable,LOW); // send a pulse to enabledelayMicroseconds(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 enabledelayMicroseconds(1);digitalWrite(Enable,HIGH);delayMicroseconds(1);digitalWrite(Enable,LOW);delayMicroseconds(1); // pause 1 ms according to datasheetdelay(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 enabledelayMicroseconds(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 displayvoid LcdNumberWrite(int nr) {

int n1 = 0;int n2 = 0;

n1 = n2 = nr;

n1 = n1 / 100;

31

31

Page 32: Manual Geral Arduino

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 initializationLcdCommandWrite(0x03); // function set:// 4 pin initializationdelay(64);LcdCommandWrite(0x03); // function set:// 4 pin initializationdelay(50);LcdCommandWrite(0x03); // function set:// 4 pin initializationdelay(50);LcdCommandWrite(0x02); // function set:// 4 pin initializationdelay(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 shiftdelay(20);LcdCommandWrite(0x0E); // display control:// turn display on, cursor on, no blinkingdelay(20);LcdCommandWrite(0x01); // clear display, set cursor position to zerodelay(100);

32

32

Page 33: Manual Geral Arduino

LcdCommandWrite(0x80); // display control:delay(20);

//////// unter this line are the special stuff you don't need for a initialitzation

LcdCommandWrite(0x0F); // cursor blinkdelay(10);

LcdCommandWrite(0x01); // clear display, set the cursor to home positiondelay(1000);

LcdCommandWrite(0x0E); // cursor not blinkLcdCommandWrite(0x02); // set cursor position to zerodelay(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 //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

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 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);

33

33

Page 34: Manual Geral Arduino

ImprimeLCD(2,30," ",1);LcdCommandWrite(0x01);

//FAZER FUNCAO PARA MENSAGEM RODAR USANDO ARRAY}

/*// Write the message//like thisLcdDataWrite('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', 'p', 'i', 'm'}; LcdDataWrite(wrote[count]);}

//espacosfor ( count = 1; count<=(40-16); count++) { LcdDataWrite(' ');}

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 thisLcdNumberWrite(999);

delay(2000);

*/

34

34

Page 35: Manual Geral Arduino

OPB804 - Slotted Optical Switch

35

35

Page 36: Manual Geral Arduino

WIZnet Ethernet W5100 (Web Server)

//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 pinsit 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++)

36

36

Page 37: Manual Geral Arduino

{ 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>"); 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++;

37

37

Page 38: Manual Geral Arduino

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){ 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'){

38

38

Page 39: Manual Geral Arduino

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; } 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>");}

39

39

Page 40: Manual Geral Arduino

POV (Persitence of Vision)

Exemplo 1

//============================================================// 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}; // an array of pin numbersint col_len = 12; // column lenght

// customizable parametersint timer1 = 3; // time between columnsint timer2 = 15; // time between framesint timer3 = 0; // time between drawingsint 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); // set each pin as an 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);

40

40

Page 41: Manual Geral Arduino

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

}delay(timer3);

}

Exemplo 2

/*????????????????????????????????????????????persistence of vision typography with arduinomichael zoellner - march 2006http://i.document.m05.de

connect anodes (+) of 5 leds to digital ports of the arduino boardand 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 alphabetint _[] = {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0};int A[] = {0,1,1,1,1, 1,0,1,0,0, 0,1,1,1,1};int B[] = {1,1,1,1,1, 1,0,1,0,1, 0,1,0,1,0};int C[] = {0,1,1,1,0, 1,0,0,0,1, 1,0,0,0,1};int D[] = {1,1,1,1,1, 1,0,0,0,1, 0,1,1,1,0};int E[] = {1,1,1,1,1, 1,0,1,0,1, 1,0,1,0,1};int F[] = {1,1,1,1,1, 1,0,1,0,0, 1,0,1,0,0};int G[] = {0,1,1,1,0, 1,0,1,0,1, 0,0,1,1,0};int H[] = {1,1,1,1,1, 0,0,1,0,0, 1,1,1,1,1};int I[] = {0,0,0,0,1, 1,0,1,1,1, 0,0,0,0,1};int J[] = {1,0,0,0,0, 1,0,0,0,1, 1,1,1,1,1};int K[] = {1,1,1,1,1, 0,0,1,0,0, 0,1,0,1,1};int L[] = {1,1,1,1,1, 0,0,0,0,1, 0,0,0,0,1};int M[] = {1,1,1,1,1, 0,1,1,0,0, 0,1,1,1,1};int N[] = {1,1,1,1,1, 1,0,0,0,0, 0,1,1,1,1};int O[] = {0,1,1,1,0, 1,0,0,0,1, 0,1,1,1,0};int P[] = {1,1,1,1,1, 1,0,1,0,0, 0,1,0,0,0};int Q[] = {0,1,1,1,1, 1,0,0,1,1, 0,1,1,1,1};int R[] = {1,1,1,1,1, 1,0,1,0,0, 0,1,0,1,1};int S[] = {0,1,0,0,1, 1,0,1,0,1, 1,0,0,1,0};int T[] = {1,0,0,0,0, 1,1,1,1,1, 1,0,0,0,0};int U[] = {1,1,1,1,1, 0,0,0,0,1, 1,1,1,1,1};int V[] = {1,1,1,1,0, 0,0,0,0,1, 1,1,1,1,0};int W[] = {1,1,1,1,0, 0,0,1,1,0, 1,1,1,1,0};int X[] = {1,1,0,1,1, 0,0,1,0,0, 1,1,0,1,1};int Y[] = {1,1,0,0,0, 0,0,1,0,0, 1,1,1,1,1};int Z[] = {1,0,0,1,1, 1,0,1,0,1, 1,1,0,0,1};

int letterSpace;int dotTime;

41

41

Page 42: Manual Geral Arduino

void setup(){ // setting the ports of the leds to OUTPUT pinMode(2, OUTPUT); pinMode(3, OUTPUT); 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(_);}

42

42

Page 43: Manual Geral Arduino

Motor Shield (SN754410NE motor driver)

Motor A Direction Arduino Digital pin 13Motor A Speed (PWM) Arduino Digital pin 10Motor B Direction Arduino Digital pin 12Motor B Speed (PWM) Arduino Digital pin 9

// by NKC Electronics

//Motor Aint dirbpinA = 13; // Direction pin for motor B is Digital 13int speedbpinA = 10; // Speed pin for motor B is Digital 10 (PWM)

//Motor Bint dirbpinB = 12; // Direction pin for motor B is Digital 12int 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 directionanalogWrite(speedbpinA, speed); // set speed (PWM)

//Motor B ----------------------------------digitalWrite(dirbpinB, dir); // set directionanalogWrite(speedbpinB, speed); // set speed (PWM)

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

43

43

Page 44: Manual Geral Arduino

A program to illustrate one way to implement a PWM loop

/* PWMallPins.pde Paul Badger 2007 A program to illustrate one way to implement a PWM loop. This program fades LED's on Arduino digital pins 2 through 13 in a sinewave pattern. It could be modified to also modulate pins 0 & 1 and the analog pins. I didn't modulate pins 0 & 1 just because of the hassle of disconnecting the LEDs on the RX and TX pins (0 & 1).

The PWM loop, as written, operates at about 175 HZ and is flicker-free. The trick to this of course is not doing too much math in between the PWM loop cycles. Long delays between the loops are going to show up as flicker. This is true especially of "Serial.print" debug statements which seem to hog the processor during transmission. Shorter (timewise) statements will just dim the maximum brightness of the LED's. There are a couple of lines of code (commented out) that implement a potentiometer as a speed control for the dimming.

How it works: The PWM loop turns on all LED's whose values are greater than 0 at the start of the PWM loop. It then turns off the LED's as the loop variable is equal to the channel's PWM modulation value. Because the values are limited to 255 (just by the table), all LED's are turned off at the end of the PWM loop. This has the side effect of making any extra math, sensor reading. etc. will increase the "off" period of the LED's duty cycle. Consequently the brightest LED value (255), which is supposed to represent a "100%" duty cycle (on all the time), dosesn't really do that. More math, sensor reading etc will increase the "off time", dimming the LED's max brightness. You can (somewhat) make up for this dimming with smaller series resistors, since LED's can be overrated if they aren't on all of the time.

The up side of this arrangement is that the LED's stay flicker free. Note that this program could easily be used to modulate motor speeds with the addition of driver transistors or MOSFET's. */

long time; // variable for speed debugfloat pwmSpeed[14] = { 0, 0, 1.2, 1.3, 1.4, 1.9, .9, .8, .5, 1.2, 1.37, 1.47, .3, 3.2}; // these constants set the rate of dimmingint pwmVal[14]; // PWM values for 12 channels - 0 & 1 included but not usedfloat pwmFloats[14];int i, j, k, l, x, y, z, bufsize, pot; // variables for various counters

44

44

Page 45: Manual Geral Arduino

unsigned char sinewave[] = //256 values{ 0x80,0x83,0x86,0x89,0x8c,0x8f,0x92,0x95,0x98,0x9c,0x9f,0xa2,0xa5,0xa8,0xab,0xae,

0xb0,0xb3,0xb6,0xb9,0xbc,0xbf,0xc1,0xc4,0xc7,0xc9,0xcc,0xce,0xd1,0xd3,0xd5,0xd8,

0xda,0xdc,0xde,0xe0,0xe2,0xe4,0xe6,0xe8,0xea,0xec,0xed,0xef,0xf0,0xf2,0xf3,0xf5,

0xf6,0xf7,0xf8,0xf9,0xfa,0xfb,0xfc,0xfc,0xfd,0xfe,0xfe,0xff,0xff,0xff,0xff,0xff,

0xff,0xff,0xff,0xff,0xff,0xff,0xfe,0xfe,0xfd,0xfc,0xfc,0xfb,0xfa,0xf9,0xf8,0xf7,

0xf6,0xf5,0xf3,0xf2,0xf0,0xef,0xed,0xec,0xea,0xe8,0xe6,0xe4,0xe2,0xe0,0xde,0xdc,

0xda,0xd8,0xd5,0xd3,0xd1,0xce,0xcc,0xc9,0xc7,0xc4,0xc1,0xbf,0xbc,0xb9,0xb6,0xb3,

0xb0,0xae,0xab,0xa8,0xa5,0xa2,0x9f,0x9c,0x98,0x95,0x92,0x8f,0x8c,0x89,0x86,0x83,

0x80,0x7c,0x79,0x76,0x73,0x70,0x6d,0x6a,0x67,0x63,0x60,0x5d,0x5a,0x57,0x54,0x51,

0x4f,0x4c,0x49,0x46,0x43,0x40,0x3e,0x3b,0x38,0x36,0x33,0x31,0x2e,0x2c,0x2a,0x27,

0x25,0x23,0x21,0x1f,0x1d,0x1b,0x19,0x17,0x15,0x13,0x12,0x10,0x0f,0x0d,0x0c,0x0a,

0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x03,0x02,0x01,0x01,0x00,0x00,0x00,0x00,0x00,

0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x02,0x03,0x03,0x04,0x05,0x06,0x07,0x08,

0x09,0x0a,0x0c,0x0d,0x0f,0x10,0x12,0x13,0x15,0x17,0x19,0x1b,0x1d,0x1f,0x21,0x23,

45

45

Page 46: Manual Geral Arduino

0x25,0x27,0x2a,0x2c,0x2e,0x31,0x33,0x36,0x38,0x3b,0x3e,0x40,0x43,0x46,0x49,0x4c,

0x4f,0x51,0x54,0x57,0x5a,0x5d,0x60,0x63,0x67,0x6a,0x6d,0x70,0x73,0x76,0x79,0x7c

};

void setup(){ Serial.begin(9600); DDRD=0xFC; // direction variable for port D - make em all outputs except serial pins 0 & 1 DDRB=0xFF; // direction variable for port B - all outputs

}

void loop(){

// time = millis(); // this was to test the loop speed // for (z=0; z<1000; z++){ // ditto

// pot = analogRead(0); // this implemented a potentiometer speed control to control speed of fading

for (y=0; y<14; y++){ // calculate one new pwm value every time through the control loop j = (j + 1) % 12; // calculate a new j every time - modulo operator makes it cycle back to 0 after 11 k = j + 2; // add 2 tp tje result - this yields a cycle of 2 to 13 for the channel (pin) select numbers

pwmFloats[k] = (pwmFloats[k] + pwmSpeed[k]); // pwmFloats[k] = (pwmFloats[k] + ((pwmSpeed[k] * 15 * (float)pot) / 1023)); // implements potentiometer speed control - see line above

if (pwmFloats[k] >= 256){ // wrop around sinewave table index values that are larger than 256 pwmFloats[k] = pwmFloats[k] - 256; } else if (pwmFloats[k] < 0){ pwmFloats[k] = pwmFloats[k] + 256; // wrop around sinewave table index values that are less than 0 }

pwmVal[k] = sinewave[(int)pwmFloats[k]]; // convert the float value to an integer and get the value out of the sinewave index }

PORTD = 0xFC; // all outputs except serial pins 0 & 1 PORTB = 0xFF; // turn on all pins of ports D & B

46

46

Page 47: Manual Geral Arduino

for (z=0; z<3; z++){ // this loop just adds some more repetitions of the loop below to cut down on the time overhead of loop above // increase this until you start to preceive flicker - then back off - decrease for more responsive sensor input reads for (x=0; x<256; x++){ for( i=2; i<14; i++){ // start with 2 to avoid serial pins if (x == pwmVal[i]){ if (i < 8){ // corresponds to PORTD // bitshift a one into the proper bit then reverse the whole byte // equivalent to the line below but around 4 times faster // digitalWrite(i, LOW); PORTD = PORTD & (~(1 << i)); } else{ PORTB = PORTB & (~(1 << (i-8))); // corresponds to PORTB - same as digitalWrite(pin, LOW); - on Port B pins }

} } }} // } // Serial.println((millis() - time), DEC); // speed test code

}

47

47

Page 48: Manual Geral Arduino

The first program is an animation of a single line motion using a 8 x 8 Led Matrix

int CLOCK = 12;int LATCH = 13;int DATA = 11;byte matrix[8];int idx = 0;

void setup() { pinMode(CLOCK, OUTPUT); pinMode(LATCH, OUTPUT); pinMode(DATA, OUTPUT); digitalWrite(CLOCK, LOW); digitalWrite(LATCH, LOW); digitalWrite(DATA, LOW); initLED(); clearLED();}

void loop() { for (int j=0;j<8;j++) { updateLED(idx, j, true); } refreshLED(); delay(200); for (int j=0;j<8;j++) { updateLED(idx, j, false); } refreshLED(); delay(100);

48

48

Page 49: Manual Geral Arduino

idx++; idx %= 8;}

void ledOut(int n) { digitalWrite(LATCH, LOW); shiftOut(DATA, CLOCK, MSBFIRST, (n>>8)); shiftOut(DATA, CLOCK, MSBFIRST, (n)); digitalWrite(LATCH, HIGH); delay(1); digitalWrite(LATCH, LOW);}

void initLED() { ledOut(0x0B07); ledOut(0x0A0C); ledOut(0x0900); ledOut(0x0C01);}

void clearLED() { for (int i=0;i<8;i++) { matrix[i] = 0x00; } refreshLED();}

void refreshLED() { int n1, n2, n3; for (int i=0;i<8;i++) { n1 = i+1; n2 = matrix[i]; n3 = (n1<<8)+n2; ledOut(n3); }}

void updateLED(int i, int j, boolean b) { int t = 1; int n = 0; int m = 0; if (j==0) { m = 7; } else { m = j-1; } n = t<<m; if (b) { matrix[i] = n | matrix[i]; } else { n = ~n; matrix[i] = n & matrix[i]; }}

49

49

Page 50: Manual Geral Arduino

Potentiometer

Componetes10k PotentiometerLED

//Led Blink de acordo com o potenciometroint potPin = 2;int ledPin = 13;

void setup() { pinMode(ledPin, OUTPUT);}

void loop() { digitalWrite(ledPin, HIGH); delay(analogRead(potPin)); digitalWrite(ledPin, LOW); delay(analogRead(potPin));}

50

50

Page 51: Manual Geral Arduino

LED as a light sensor

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);

51

51

Page 52: Manual Geral Arduino

pinMode(LED_P_SIDE,OUTPUT); digitalWrite(LED_N_SIDE,HIGH); digitalWrite(LED_P_SIDE,LOW);

// 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}

52

52

Page 53: Manual Geral Arduino

TIP 120/121/122 Motor Driver

Componentes:

Tip120/121/1221k resistor1N4001 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:"); }}

53

53

Page 54: Manual Geral Arduino

54

54

Page 55: Manual Geral Arduino

SN754410 Motor Driver

/** 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:

55

55

Page 56: Manual Geral Arduino

* 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 potentiometerint speedPin = 3; // H-bridge enable pin for speed controlint motor1Pin = 6; // H-bridge leg 1int motor2Pin = 7; // H-bridge leg 2int ledPin = 13; // status LEDint 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 }}

56

56

Page 57: Manual Geral Arduino

Parallel Port Programmer

(2x) 470 ohm resistor (yellow-purple-brown) (1x) 220 ohm resistor (red-red-brown) (1x) parallel port cable or parallel-to-serial adapter (2x) three wire cables with female connectors on one end, unattached wires on the other

http://www.arduino.cc/en/Hacking/ParallelProgrammer

57

57

Page 58: Manual Geral Arduino

Burning the Bootloader without external AVR-Writer

http://www.geocities.jp/arduino_diecimila/bootloader/index_en.html

58

58

Page 59: Manual Geral Arduino

WIZnet WIZ811MJ VER 1.0

1) 3.3V2) GND3) MISO4) MOSI5) SCLK6) SS or SCS7) INT8) RESET

59

59

Page 60: Manual Geral Arduino

WIZnet WIZ810MJ

1) 3.3V2) GND3) MISO4) MOSI5) SCLK6) SS or SCS7) INT8) RESET

60

60

Page 61: Manual Geral Arduino

Pyro Sensor

#define LED 13#define PYRO 9int 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); }

61

61

Page 62: Manual Geral Arduino

VDIP1 Module

http://www.saelig.com/miva/merchant.mvc?Screen=PROD&Product_Code=UI1E3&Category_Code=UI1Ehttp://www.arduino.cc/playground/Main/UsbMemoryhttp://www.vinculum.com/documents/schematics/VDIP1%20Schematic%20Prints.pdfhttp://www.dontronics-shop.com/ftdi-vdip1.htmlhttp://www.picbasic.co.uk/forum/showthread.php?t=7700http://www.vinculum.com/prd_vnc1l.htmlhttp://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.

62

62

Page 63: Manual Geral Arduino

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

63

63

Page 64: Manual Geral Arduino

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.

64

64

Page 65: Manual Geral Arduino

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); // opens serial port, sets

data rate to 9600 bps Serial.print("IPA"); // sets the vdip to use ascii numbers //(so I can read them in the code easily!) Serial.print(13, BYTE); // return character to tell vdip its end of message}

void loop() { if (Serial.available() > 0) { // read the incoming byte

incomingByte = Serial.read();

if (incomingByte=='1'){ // if it receives a 1 Serial.print("OPW LOG%"); // open to write creates a file - named Serial.print(fileNumber); // LOG%1.TXT first time round - .TXT is for the computer Serial.print(".TXT"); // I have used the % sign in the name so I can //search the disk for log files that it has created //so as not to overwrite any that may be on already Serial.print(13, BYTE); // return character

}

if (incomingByte=='2'){ // if it receives a 2 Serial.print("CLF LOG%"); // it closes the file Serial.print(fileNumber); // LOG%1.TXT Serial.print(".TXT"); Serial.print(13, BYTE); // return character

}

if (incomingByte=='3'){ // if it receives 3 Serial.print("DIR"); // lists the directory on the memory stick Serial.print(13, BYTE); // which will now include the file LOG%1.TXT

}

if (incomingByte=='5'){ activityToLog='P'; // I will be using different letters to label my time stamps

65

65

Page 66: Manual Geral Arduino

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 "); //write to file (file needs to have been opened to write first) Serial.print(noOfChars); //needs to then be told how many characters will be written Serial.print(13, BYTE); //return to say command is finished Serial.print(activityToLog); //followed by the info to write Serial.print(valToWrite); Serial.print(13, BYTE); //write a return to the contents of the file (so each entry appears on a new line)

}

if (incomingByte=='6'){ fileNumber++; //so we can create other files}

if (incomingByte=='7'){ if (fileNumber>0){ //and look at previous ones fileNumber--; }}

if (incomingByte=='8'){ Serial.print("RD LOG%"); //reads the contents of named file Serial.print(fileNumber); Serial.print(".TXT"); Serial.print(13, BYTE);

}}

if (incomingByte=='9'){ startLogTime=millis(); // reset timing}

}

66

66

Page 67: Manual Geral Arduino

Color Mixing

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

/*

67

67

Page 68: Manual Geral Arduino

* 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 <[email protected]> */

// Output

int a = 9;int b = 10;int c = 11;

int redPin = 6; // Red LED, connected to digital pin 9int greenPin = 5; // Green LED, connected to digital pin 10int bluePin = 3; // Blue LED, connected to digital pin 11

// Program variablesint redVal = 255; // Variables to store the values to send to the pinsint greenVal = 1; // Initial values are Red full, Green and Blue offint blueVal = 1;

int i = 0; // Loop counter int wait = 15; // 50ms (.05 second) delay; shorten for faster fadesint DEBUG = 0; // DEBUG counter; if set to 1, will write values back via serial

void setup(){ pinMode(redPin, OUTPUT); // sets the pins as output pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); pinMode(a, OUTPUT); pinMode(b, OUTPUT); pinMode(c, OUTPUT); if (DEBUG) { // If we want to see the pin values for debugging... Serial.begin(9600); // ...set up the serial ouput on 0004 style }}

// Main programvoid 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 {

68

68

Page 69: Manual Geral Arduino

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" instead of just "redVal" because the // LEDs are hooked up to +5V instead of Gnd analogWrite(redPin, 255 - redVal); // Write current values to LED pins analogWrite(greenPin, 255 - greenVal); analogWrite(bluePin, 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}

69

69

Page 70: Manual Geral Arduino

USB

70

70

Page 71: Manual Geral Arduino

Interfacing SD / MMC Card with SPI

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

71

71

Page 72: Manual Geral Arduino

72

72

Page 73: Manual Geral Arduino

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.

73

73

Page 74: Manual Geral Arduino

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

http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1191209057/15http://www.glacialwanderer.com/hobbyrobotics/?p=12http://em.typodemon.com/wordpress/?p=149http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1198881858http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1233375650http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1235070596/9http://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 decimalbyte decToBcd(byte val){ return ( (val/10*16) + (val%10) );}

// Convert binary coded decimal to normal decimal numbersbyte 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);

74

74

Page 75: Manual Geral Arduino

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 numbersvoid 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 ds1307void 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());}

75

75

Page 76: Manual Geral Arduino

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);}

76

76

Page 77: Manual Geral Arduino

Writing a Library for ArduinoThis 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:

77

77

Page 78: Manual Geral Arduino

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:

78

78

Page 79: Manual Geral Arduino

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(){

79

79

Page 80: Manual Geral Arduino

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:

80

80

Page 81: Manual Geral Arduino

Morse KEYWORD1dash KEYWORD2dot 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.

81

81

Page 82: Manual Geral Arduino

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.

82

82

Page 83: Manual Geral Arduino

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

83

83

Page 84: Manual Geral Arduino

Simple IR Distance Sensor Tutorial

http://www.arduino.cc/playground/Main/PanasonicIrSensor

Paralax books:Robotics with the Boe-Bot pag. 238Understanding Signals pag.137

Programming Robot Controllers pag. 229

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

Hardware Requirments1. IR led (1) 2. 1.1 ohm brown-brown-red3. 2 ohm red-black-red

4. Panasonic pna4602m IR sensor (1) 5. 220 ohm red-red-brown

Theory and circuitsFor 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.

84

84

Page 85: Manual Geral Arduino

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

85

85

Page 86: Manual Geral Arduino

} return digitalRead(readPin);}

86

86

Page 87: Manual Geral Arduino

Infra Red + led –

Componentes:

IR Receiver BlackTransistor 2n3904Resistor: marrom/preto/vermelho 1k Laranja/laranja/marrom 300

#define LED 13#define BUTTON 7int val = 0;

void setup() { Serial.begin(9600); // start serial communication pinMode(LED, OUTPUT); pinMode(BUTTON, INPUT);}

void loop(){ val = digitalRead(BUTTON); if (val == HIGH) { //Serial.print(tempc,DEC); Serial.print("Luz"); digitalWrite(LED, HIGH); } else { Serial.print("Escuridao"); digitalWrite(LED, LOW); }}

87

87

Page 88: Manual Geral Arduino

Regra Para descobrir a Resistencia necessaria para reduziar a voltagem

R = (B - V)/I = (4.5 - 3.6) / .02 = 45 ohm

88

88

Page 89: Manual Geral Arduino

PIR Motion Sensorsku: SEN-08630

http://www.sparkfun.com/commerce/product_info.php?products_id=8630http://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 [email protected].

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); }}

89

89

Page 90: Manual Geral Arduino

Exemplo 2http://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-NonCommercial-ShareAlike 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 impulselong unsigned int lowIn;

//the amount of milliseconds the sensor has to be low //before we assume all motion has stoppedlong unsigned int pause = 5000;

boolean lockLow = true;boolean takeLowTime;

int pirPin = 12; //the digital pin connected to the PIR sensor's outputint ledPin = 13;

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

90

90

Page 91: Manual Geral Arduino

//SETUPvoid 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); }

//////////////////////////////LOOPvoid 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");

91

91

Page 92: Manual Geral Arduino

delay(50); } } }

92

92

Page 93: Manual Geral Arduino

I2C EEPROM - 256kbitsku: 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.htmlhttp://lusorobotica.com/index.php/topic,461.msg2738.html-----------------------------------------------------------------------http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1229523445http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1214682544/22http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1233314173/4http://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);

93

93

Page 94: Manual Geral Arduino

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 74HC595http://www.arduino.cc/en/Tutorial/ShiftOuthttp://www.codeproject.com/KB/system/ArduinoShiftRegisters.aspx

Started by Carlyn Maw and Tom Igoe Nov, 06Shifting Out & the 595 chip

94

94

Page 95: Manual Geral Arduino

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.

95

95

Page 96: Manual Geral Arduino

96

96

Page 97: Manual Geral Arduino

97

97

Page 98: Manual Geral Arduino

98

98

Page 99: Manual Geral Arduino

99

99

Page 100: Manual Geral Arduino

100

100

Page 101: Manual Geral Arduino

Arduino + Bluetooth + Android

http://www.sparkfun.com/products/582http://www.sparkfun.com/products/10336http://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/designhttp://www.amarino-toolkit.net/https://github.com/lucasfragomeni/arduino/tree/master/RouchBThttp://lucasfragomeni.com/arduino/http://lucasfragomeni.com/arduino/2011-01/arduino-bluetooth-android/

101

101

Page 102: Manual Geral Arduino

Controlando motores usando o SN754410NEhttp://www.arduino.cc/en/Tutorial/ShiftOuthttp://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 +5VPin 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

102

102

Page 103: Manual Geral Arduino

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

103

103

Page 104: Manual Geral Arduino

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

// ————————————————————————— Motorsint motor_left[] = {2, 3};int motor_right[] = {7, 8};int ledPin = 13; // LED connected to digital pin 13

// ————————————————————————— Setupvoid setup() {Serial.begin(9600);

// Setup motorsint i;for(i = 0; i < 2; i++){pinMode(motor_left[i], OUTPUT);pinMode(motor_right[i], OUTPUT);pinMode(ledPin, OUTPUT);}

}

// ————————————————————————— Loopvoid 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");

104

104

Page 105: Manual Geral Arduino

motor_stop();delay(1000);motor_stop();Serial.println("5");

digitalWrite(ledPin, HIGH); // set the LED on delay(1000); // wait for a second digitalWrite(ledPin, LOW); // set the LED off delay(1000); // wait for a second

}

// ————————————————————————— 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);}

105

105

Page 106: Manual Geral Arduino

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 potentiometerint speedPin = 3; // H-bridge enable pin for speed controlint motor1Pin = 6; // H-bridge leg 1int motor2Pin = 7; // H-bridge leg 2int ledPin = 13; // status LEDint 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

106

106

Page 107: Manual Geral Arduino

// from 128 to 255 }}

107

107

Page 108: Manual Geral Arduino

3-MOTOR SHILD (SN755410)

// Motor Shield test// by NKC Electronics// Test Motor B

//Motor Aint dirbpinA = 13; // Direction pin for motor B is Digital 13int speedbpinA = 10; // Speed pin for motor B is Digital 10 (PWM)

//Motor Bint dirbpinB = 12; // Direction pin for motor B is Digital 12int 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 directionanalogWrite(speedbpinA, speed); // set speed (PWM)

//Motor B ----------------------------------digitalWrite(dirbpinB, dir); // set directionanalogWrite(speedbpinB, speed); // set speed (PWM)

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

108

108

Page 109: Manual Geral Arduino

4-http://www.smartsurfaces.net/hbridge// Updated from http://itp.nyu.edu/physcomp/Labs/DCMotorControl

int switchPin = 2; // switch inputint motor1Pin = 3; // H-bridge leg 1 (pin 2, 1A)int motor2Pin = 4; // H-bridge leg 2 (pin 7, 2A)int enablePin = 9; // H-bridge enable pinint ledPin = 13; // 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); } }

109

109

Page 110: Manual Geral Arduino

How to program a AVR (arduino) with another arduinohttp://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.

110

110

Page 111: Manual Geral Arduino

111

111

Page 112: Manual Geral Arduino

112

112

Page 113: Manual Geral Arduino

BREAD BOARD

113

113

Page 114: Manual Geral Arduino

114

114

Page 115: Manual Geral Arduino

115

115

Page 116: Manual Geral Arduino

116

116

Page 117: Manual Geral Arduino

Atiny13

// 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...

#define LED 9#define SCK 13#define MISO 12#define MOSI 11#define RESET 10

#define SWVER "23"#define HWVER "10"#define PACE 50

char *DeviceList = "\x01\x56\x76\x5e";byte device=1; // device type, get from avrdudeint here = 0; // current memory locationint 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

117

117

Page 118: Manual Geral Arduino

////////////////////////////////////////////////////////////void spiInit() { 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);}

118

118

Page 119: Manual Geral Arduino

void LeaveProgramMode() { pinMode(MISO, INPUT); 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 EEPROMvoid WriteData(byte b) { spiTransaction(0xC0, (here >> 8) & 0xFF,

119

119

Page 120: Manual Geral Arduino

here & 0xFF, b); 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);

120

120

Page 121: Manual Geral Arduino

Serial.println(); Serial.print("SPCR is "); 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 == '.')

121

121

Page 122: Manual Geral Arduino

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

122

122

Page 123: Manual Geral Arduino

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 pinsit 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>");

123

123

Page 124: Manual Geral Arduino

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){

124

124

Page 125: Manual Geral Arduino

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;

125

125

Page 126: Manual Geral Arduino

} 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>");}

126

126

Page 127: Manual Geral Arduino

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(;;) ; } }

127

127

Page 128: Manual Geral Arduino

128

128

Page 129: Manual Geral Arduino

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()) {

129

129

Page 130: Manual Geral Arduino

char c = client.read(); Serial.print(c); }

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

130

130

Page 131: Manual Geral Arduino

Melody

int speakerPin = 9;

int length = 15; // the number of noteschar notes[] = "ccggaagffeeddc "; // a space represents a restint 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); }}

131

131

Page 132: Manual Geral Arduino

GPS

/*

Example code for connecting a Parallax GPS module to the Arduino

Igor Gonz?lez Mart?n. 05-04-2007 [email protected]

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; // LED test pin int rxPin = 0; // RX PIN int txPin = 1; // TX TX int byteGPS=-1; char linea[300] = ""; char comandoGPR[7] = "$GPRMC"; int cont=0; int bien=0; int conta=0; int indices[13];

// *** 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 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); }}

132

132

Page 133: Manual Geral Arduino

//****************************************************//**************** I m p r i m e LCD *****************//****************************************************//int myLength = sizeof(myArrayvoid 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 DIfor (i=DB[0]; i <= DI; i++) { digitalWrite(i,value1 & 01); value1 >>= 1;}digitalWrite(Enable,LOW); // send a pulse to enabledelayMicroseconds(1);digitalWrite(Enable,HIGH);delayMicroseconds(1);digitalWrite(Enable,LOW);delayMicroseconds(1); // pause 1 ms according to datasheetdelay(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++) {

133

133

Page 134: Manual Geral Arduino

digitalWrite(i,value & 01); value >>= 1;}digitalWrite(Enable,LOW); // send a pulse to enabledelayMicroseconds(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 enabledelayMicroseconds(1);digitalWrite(Enable,HIGH);delayMicroseconds(1);digitalWrite(Enable,LOW);delayMicroseconds(1); // pause 1 ms according to datasheetdelay(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 enabledelayMicroseconds(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 displayvoid LcdNumberWrite(int nr) {

int n1 = 0;int n2 = 0;

n1 = n2 = nr;

134

134

Page 135: Manual Geral Arduino

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

135

135

Page 136: Manual Geral Arduino

///////////////////////////////////////////////////// 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); // cursor blink delay(10);

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 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

136

136

Page 137: Manual Geral Arduino

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void loop() { digitalWrite(ledPin, HIGH);// Serial.print(0x03); 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;

137

137

Page 138: Manual Geral Arduino

} 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;// 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; // Reset the buffer for (int i=0;i<300;i++){ // linea[i]=' '; } } } }

138

138

Page 139: Manual Geral Arduino

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:"); }}

139

139

Page 140: Manual Geral Arduino

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; // LED connected to digital pin 13int value = LOW; // previous value of the LEDlong previousMillis = 0; // will store last time LED was updatedlong interval = 1000; // interval at which to blink (milliseconds)

void setup(){ pinMode(ledPin, OUTPUT); // 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 LED is off turn it on and vice-versa. if (value == LOW) value = HIGH; else value = LOW;

digitalWrite(ledPin, value); }}

140

140

Page 141: Manual Geral Arduino

LED 1

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

int timer = 100; // The higher the number, the slower the timing.int pins[] = {9, 10, 11, 12, 13 }; // an array of pin numbersint 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++) // the array elements are numbered from 0 to num_pins - 1 pinMode(pins[i], OUTPUT); // set each pin as an 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); }}

141

141

Page 142: Manual Geral Arduino

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 = 13; // LED connected to digital pin 13int ledPin12 = 12; // LED connected to digital pin 13int ledPin11 = 11; // LED connected to digital pin 13int ledPin10 = 10; // LED connected to digital pin 13int ledPin9 = 9; // LED connected to digital pin 13int ledPin8 = 8; // LED connected to digital pin 13int ledPin7 = 7; // LED connected to digital pin 13int ledPin6 = 6; // LED connected to digital pin 13int ledPin5 = 5; // LED connected to digital pin 13int ledPin4 = 4; // LED connected to digital pin 13int ledPin3 = 3; // LED connected to digital pin 13int ledPin2 = 2; // LED connected to digital pin 13int ledPin1 = 1; // LED connected to digital pin 13//int ledPin0 = 0; // LED connected to digital pin 13

void setup() // run once, when the sketch starts{ pinMode(ledPin13, OUTPUT); // sets the digital pin as output pinMode(ledPin12, OUTPUT); // sets the digital pin as output pinMode(ledPin11, OUTPUT); // sets the digital pin as output pinMode(ledPin10, OUTPUT); // sets the digital pin as output pinMode(ledPin9, OUTPUT); // sets the digital pin as output pinMode(ledPin8, OUTPUT); // sets the digital pin as output pinMode(ledPin7, OUTPUT); // sets the digital pin as output pinMode(ledPin6, OUTPUT); // sets the digital pin as output pinMode(ledPin5, OUTPUT); // sets the digital pin as output pinMode(ledPin4, OUTPUT); // sets the digital pin as output pinMode(ledPin3, OUTPUT); // sets the digital pin as output pinMode(ledPin2, OUTPUT); // sets the digital pin as output pinMode(ledPin1, OUTPUT); // sets the digital pin as output// pinMode(ledPin0, OUTPUT); // sets the digital pin as output }

void loop() // run over and over again{ digitalWrite(ledPin13, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin13, LOW); // sets the LED off delay(a); // waits for a second

142

142

Page 143: Manual Geral Arduino

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 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(ledPin10, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin10, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin9, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin9, LOW); // sets the LED off delay(a); // waits for a second 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 LED on delay(a); // waits for a second digitalWrite(ledPin7, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin6, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin6, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin5, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin5, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin4, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin4, 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(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(ledPin1, HIGH); // sets the LED on

143

143

Page 144: Manual Geral Arduino

delay(a); // waits for a second digitalWrite(ledPin1, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin0, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin0, LOW); // sets the LED off delay(a); // waits for a 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 LED on delay(a); // waits for a second digitalWrite(ledPin4, LOW); // sets the LED off delay(a); // waits for a 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 LED on delay(a); // waits for a second digitalWrite(ledPin6, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin7, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin7, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin8, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin8, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin9, HIGH); // sets the LED on delay(a); // waits for a second digitalWrite(ledPin9, LOW); // sets the LED off delay(a); // waits for a second digitalWrite(ledPin10, HIGH); // sets the LED on

144

144

Page 145: Manual Geral Arduino

delay(a); // waits for a second 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}

145

145

Page 146: Manual Geral Arduino

LED 3 candle light

/* * CandleLight * ----------- * * Use random numbers to emulate a flickering candle with a PWM'd LED * * 2007 Tod E. Kurt <[email protected]> * http://todbot.com/ * */

int ledPin = 9; // select the pin for the LEDint val = 0; // variable that holds the current LED brightnessint delayval = 0; // variable that holds the current delay time

void setup() { randomSeed(0); // initialize the random number generator pinMode(ledPin, OUTPUT); // declare the ledPin as an OUTPUT}

void loop() { val = random(100,255); // pick a random number between 100 and 255 analogWrite(ledPin, val); // set the LED brightness

delayval = random(50,150); // pick a random number between 30 and 100 delay(delayval); // delay that many milliseconds}

146

146

Page 147: Manual Geral Arduino

LED 4 FADING

// Fading LED // by BARRAGAN <http://people.interaction-ivrea.it/h.barragan>

int value = 0; // variable to keep the actual value int ledRed = 11; // light connected to digital pin 9int ledGreen = 10; // light connected to digital pin 9int ledBlue = 9; // light connected to digital pin 9 void setup() { // nothing for setup } void loop() { //Red for(value = 0 ; value <= 255; value+=5) // fade in (from min to max) { analogWrite(ledRed, 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(ledRed, value); delay(17); } //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)

147

147

Page 148: Manual Geral Arduino

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(ledBlue, value); delay(17); } }

148

148

Page 149: Manual Geral Arduino

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 <[email protected]> */

// Output

int a = 9;int b = 10;int c = 11;

int redPin = 6; // Red LED, connected to digital pin 9int greenPin = 5; // Green LED, connected to digital pin 10int bluePin = 3; // Blue LED, connected to digital pin 11

// Program variablesint redVal = 255; // Variables to store the values to send to the pinsint greenVal = 1; // Initial values are Red full, Green and Blue offint blueVal = 1;

int i = 0; // Loop counter int wait = 15; // 50ms (.05 second) delay; shorten for faster fadesint DEBUG = 0; // DEBUG counter; if set to 1, will write values back via serial

void setup(){ pinMode(redPin, OUTPUT); // sets the pins as output pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); pinMode(a, OUTPUT); pinMode(b, OUTPUT); pinMode(c, OUTPUT); if (DEBUG) { // If we want to see the pin values for debugging... Serial.begin(9600); // ...set up the serial ouput on 0004 style }}

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

149

149

Page 150: Manual Geral Arduino

greenVal += 1; // Green up 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" instead of just "redVal" because the // LEDs are hooked up to +5V instead of Gnd analogWrite(redPin, 255 - redVal); // Write current values to LED pins analogWrite(greenPin, 255 - greenVal); analogWrite(bluePin, 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}

150

150

Page 151: Manual Geral Arduino

ULTRASONIC PING

EXEMPLO 1

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;}

151

151

Page 152: Manual Geral Arduino

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

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

152

152

Page 153: Manual Geral Arduino

// 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 3

// * 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.

153

153

Page 154: Manual Geral Arduino

}

154

154

Page 155: Manual Geral Arduino

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;

155

155

Page 156: Manual Geral Arduino

}

156

156

Page 157: Manual Geral Arduino

LCD

EXEMPLO 1

/* 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 selectint RW = 11;int DB[] = {7, 8, 9, 10};int Enable = 6;

int temperaturePin = 2; // select the input pin for the temperatureint ledPin = 13; // pin for the LED

void tickleEnable(){// send a pulse to enabledigitalWrite(Enable,HIGH);delayMicroseconds(1); // pause 1 ms according to datasheetdigitalWrite(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;

157

157

Page 158: Manual Geral Arduino

for (i=DB[3]; i >= DB[0]; i--) // high nybble first { 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 controllerLcdCommandWrite(0x28); // function set: delay(64); // 4-bit interface, 2 display lines, 5x7 font // other interaces: // 0x20 = 4 bit, 1 display line

LcdCommandWrite(0x28); // function set: delay(64); // 4-bit interface, 2 display lines, 5x7 font

158

158

Page 159: Manual Geral Arduino

LcdCommandWrite(0x06); // entry mode set: // increment automatically, no display shiftdelay(20); LcdCommandWrite(0x0E); // display control: // turn display on, cursor on, no blinkingdelay(20); LcdCommandWrite(0x01); // clear display, set cursor position to zero delay(100); LcdCommandWrite(0x80); // display control: // turn display on, cursor on, no blinkingdelay(20); }

void loop (void) { int i, val = 0; for(i = 0; i < 20; ++i) { val += analogRead(temperaturePin); // read the value from the sensor delay(50); } val /= 4.06; // conversion value to millivolts digitalWrite(ledPin, HIGH); // turn the ledPin on delay(500); // stop the program for some time digitalWrite(ledPin, LOW); // turn the ledPin off 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); // set cursor position to zero

delay(10); firstDisplay(val);}

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

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

159

159

Page 160: Manual Geral Arduino

LcdDataWrite(' '); LcdDataWrite('='); LcdDataWrite(' ');

LcdDataWrite(value > 999 ? first + 48 : ' '); // begin onscreen LcdDataWrite(value > 99 ? second + 48 : ' '); LcdDataWrite(third + 48); LcdDataWrite('.'); LcdDataWrite(fourth + 48);

LcdDataWrite(' '); LcdDataWrite('C'); LcdDataWrite(' '); LcdDataWrite(' ');}

160

160

Page 161: Manual Geral Arduino

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) {

161

161

Page 162: Manual Geral Arduino

int i = 0;int value1 = 0;value1 = value;

value1 >>= 4; //send the first 4 databits (from 8) + RW and DIfor (i=DB[0]; i <= DI; i++) { digitalWrite(i,value1 & 01); value1 >>= 1;}digitalWrite(Enable,LOW); // send a pulse to enabledelayMicroseconds(1);digitalWrite(Enable,HIGH);delayMicroseconds(1);digitalWrite(Enable,LOW);delayMicroseconds(1); // pause 1 ms according to datasheetdelay(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 enabledelayMicroseconds(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 enabledelayMicroseconds(1);digitalWrite(Enable,HIGH);delayMicroseconds(1);digitalWrite(Enable,LOW);delayMicroseconds(1); // pause 1 ms according to datasheetdelay(1);

162

162

Page 163: Manual Geral Arduino

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 enabledelayMicroseconds(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 displayvoid 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 initializationLcdCommandWrite(0x03); // function set:// 4 pin initializationdelay(64);LcdCommandWrite(0x03); // function set:// 4 pin initializationdelay(50);

163

163

Page 164: Manual Geral Arduino

LcdCommandWrite(0x03); // function set:// 4 pin initializationdelay(50);LcdCommandWrite(0x02); // function set:// 4 pin initializationdelay(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 shiftdelay(20);LcdCommandWrite(0x0E); // display control:// turn display on, cursor on, no blinkingdelay(20);LcdCommandWrite(0x01); // clear display, set cursor position to zerodelay(100);

LcdCommandWrite(0x80); // display control:delay(20);

//////// unter this line are the special stuff you don't need for a initialitzation

LcdCommandWrite(0x0F); // cursor blinkdelay(10);

LcdCommandWrite(0x01); // clear display, set the cursor to home positiondelay(1000);

LcdCommandWrite(0x0E); // cursor not blinkLcdCommandWrite(0x02); // set cursor position to zerodelay(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

164

164

Page 165: Manual Geral Arduino

//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

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 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 thisLcdDataWrite('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', 'p', 'i', 'm'}; LcdDataWrite(wrote[count]);}

//espacosfor ( count = 1; count<=(40-16); count++) { LcdDataWrite(' ');}

165

165

Page 166: Manual Geral Arduino

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 thisLcdNumberWrite(999);

delay(2000);

*/

166

166

Page 167: Manual Geral Arduino

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 + RW and DIfor (i=DB[0]; i <= DI; i++) { digitalWrite(i,value1 & 01); value1 >>= 1;}digitalWrite(Enable,LOW); // send a pulse to enabledelayMicroseconds(1);digitalWrite(Enable,HIGH);delayMicroseconds(1);digitalWrite(Enable,LOW);delayMicroseconds(1); // pause 1 ms according to datasheetdelay(1);

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++) {

167

167

Page 168: Manual Geral Arduino

digitalWrite(i,value & 01); value >>= 1;}digitalWrite(Enable,LOW); // send a pulse to enabledelayMicroseconds(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 enabledelayMicroseconds(1);digitalWrite(Enable,HIGH);delayMicroseconds(1);digitalWrite(Enable,LOW);delayMicroseconds(1); // pause 1 ms according to datasheetdelay(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 enabledelayMicroseconds(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); //512 used to wirte data (see commands for character modul)n2 = (n2 - n1 * 100) / 10;

168

168

Page 169: Manual Geral Arduino

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 * 100);LcdCommandWrite(560 + display2); //512 used to wirte data*/display3 = (N/10);N = N - (display3 * 10);LcdCommandWrite(560 + 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

169

169

Page 170: Manual Geral Arduino

///////////////////////////////////////////////////// 4 pin initializationLcdCommandWrite(0x03); // function set:// 4 pin initializationdelay(64);LcdCommandWrite(0x03); // function set:// 4 pin initializationdelay(50);LcdCommandWrite(0x03); // function set:// 4 pin initializationdelay(50);LcdCommandWrite(0x02); // function set:// 4 pin initializationdelay(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 shiftdelay(20);LcdCommandWrite(0x0E); // display control:// turn display on, cursor on, no blinkingdelay(20);LcdCommandWrite(0x01); // clear display, set cursor position to zerodelay(100);

LcdCommandWrite(0x80); // display control:delay(20);

//////// unter this line are the special stuff you don't need for a initialitzation

LcdCommandWrite(0x0F); // cursor blinkdelay(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 blinkLcdCommandWrite(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

170

170

Page 171: Manual Geral Arduino

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> example <<<<<<<<<

LcdCommandWrite(0x02); // set cursor position to zerodelay(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')ne');LcdDataWrite('two ');LcdDataWrite('three ');LcdDataWrite('four ');for ( count = 1; count<=20; count++) {LcdDataWrite(' ');}

171

171

Page 172: Manual Geral Arduino

for ( count = 1; count<=10; count++) {LcdNumberWrite2digits(count);}LcdDataWrite('w');LcdDataWrite('i');LcdDataWrite('t');LcdDataWrite('h');LcdDataWrite(' ');

// and Number over 9 easyely like thisLcdDataWrite('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]);}

172

172

Page 173: Manual Geral Arduino

delay(1000);}

EXEMPLO 4 LCD 4 BIT EXAMPLE

//example use of LCD4Bit library

#include <LCD4Bit.h> //create object to control an LCD. //number of lines in display=1LCD4Bit lcd = LCD4Bit(2);

//some messages to display on the LCDchar 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);

173

173

Page 174: Manual Geral Arduino

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

EXEMPLO 5 MASSIMO BANZI CODE

/* * 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 LCD_RS 8 // Register select#define LCD_EN 9 // Enable#define LCD_D4 10 // Data bits#define LCD_D5 11 // Data bits#define LCD_D6 12 // Data bits#define LCD_D7 13 // Data bits

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); else digitalWrite(LCD_D7,LOW);

if(c & 0x40) digitalWrite(LCD_D6,HIGH); else digitalWrite(LCD_D6,LOW);

if(c & 0x20) digitalWrite(LCD_D5,HIGH); else digitalWrite(LCD_D5,LOW);

if(c & 0x10) digitalWrite(LCD_D4,HIGH); else digitalWrite(LCD_D4,LOW);

lcd_strobe();if(c & 0x08) digitalWrite(LCD_D7,HIGH); else

digitalWrite(LCD_D7,LOW);if(c & 0x04) digitalWrite(LCD_D6,HIGH); else

digitalWrite(LCD_D6,LOW);if(c & 0x02) digitalWrite(LCD_D5,HIGH); else

digitalWrite(LCD_D5,LOW);if(c & 0x01) digitalWrite(LCD_D4,HIGH); else

digitalWrite(LCD_D4,LOW);lcd_strobe();delayMicroseconds(40);

174

174

Page 175: Manual Geral Arduino

}

/* * Clear and home the LCD */

voidlcd_clear(void){

digitalWrite(LCD_RS,LOW);

lcd_write(0x1);delay(2);

}

/* write a string of chars to the LCD */

voidlcd_puts(const char * s){ digitalWrite(LCD_RS,HIGH); // write characters

while(*s) lcd_write(*s++);}

/* write one character to the LCD */

voidlcd_putch(byte c){ digitalWrite(LCD_RS,HIGH); // write characters

lcd_write(c);}

/* * Go to the specified position */

voidlcd_goto(byte pos){ digitalWrite(LCD_RS,0);

lcd_write(0x80 + pos);}

/* initialise the LCD - put into 4 bit mode */

voidlcd_init(void){

pinMode(LCD_D7,OUTPUT);pinMode(LCD_D6,OUTPUT);pinMode(LCD_D5,OUTPUT);pinMode(LCD_D4,OUTPUT);

175

175

Page 176: Manual Geral Arduino

pinMode(LCD_EN,OUTPUT);pinMode(LCD_RS,OUTPUT);

digitalWrite(LCD_RS, LOW); // write control bytes

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); // set 4 bit modelcd_strobe();delayMicroseconds(40);

lcd_write(0x28);// 4 bit mode, 1/16 duty, 5x8 font, 2lineslcd_write(0x0C);// display onlcd_write(0x06);// entry mode advance cursorlcd_write(0x01);// clear display and reset cursor

}

void setup() { lcd_init();}

void loop() { lcd_puts("hello world");

}

176

176

Page 177: Manual Geral Arduino

MOTO

EXEMPLO 1

#define LED 13#define BUTTON 10

int led3 = 3;int led4 = 4;int led5 = 5;int led6 = 6;int led7 = 7;int led8 = 8;int led9 = 9;int led10= 10;int time1= 90;int time2= 500;int time3= 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);

177

177

Page 178: Manual Geral Arduino

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); 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); }

*/

178

178

Page 179: Manual Geral Arduino

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 led3 = 3;int led4 = 4;int led5 = 5;int led6 = 6;int led7 = 7;int led8 = 8;int led9 = 9;int led10= 10;int time1= 100;int time2= 500;int time3= 1000;

int val = 0; // stores the state of the input pinint var = 0;

int old_val = 0; // stores the previous value of "val" int state = 0; // 0 = LED off while 1 = LED on

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); }

179

179

Page 180: Manual Geral Arduino

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 // current brightness level } else { analogWrite(LED, 0); // turn LED OFF } }

180

180

Page 181: Manual Geral Arduino

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 led3 = 3;int led4 = 4;int led5 = 5;int led6 = 6;int led7 = 7;int led8 = 8;int led9 = 9;int led10= 10;int time1= 100;int time2= 500;int time3= 1000;

int val = 0; // stores the state of the input pinint var = 0;

int old_val = 0; // stores the previous value of "val" int state = 0; // 0 = LED off while 1 = LED on

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); }

181

181

Page 182: Manual Geral Arduino

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 // current brightness level } else { analogWrite(LED, 0); // turn LED OFF } }

182

182

Page 183: Manual Geral Arduino

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 led3 = 3;int led4 = 4;int led5 = 5;int led6 = 6;int led7 = 7;int led8 = 8;int led9 = 9;int led10= 10;int time1= 100;int time2= 500;int time3= 1000;

int val = 0; // stores the state of the input pinint var = 0;

int old_val = 0; // stores the previous value of "val" int state = 0; // 0 = LED off while 1 = LED on

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); }

183

183

Page 184: Manual Geral Arduino

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 // current brightness level } else { analogWrite(LED, 0); // turn LED OFF } }

184

184

Page 185: Manual Geral Arduino

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 led3 = 3;int led4 = 4;int led5 = 5;int led6 = 6;int led7 = 7;int led8 = 8;int led9 = 9;int led10= 10;int time1= 100;int time2= 500;int time3= 1000;

int val = 0; // stores the state of the input pinint var = 0;

int old_val = 0; // stores the previous value of "val" int state = 0; // 0 = LED off while 1 = LED on

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); }

185

185

Page 186: Manual Geral Arduino

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 // current brightness level } else { analogWrite(LED, 0); // turn LED OFF } }

186

186

Page 187: Manual Geral Arduino

EXEMPLO 6

#define LED 13#define BUTTON 10

int led3 = 3;int led4 = 4;int led5 = 5;int led6 = 6;int led7 = 7;int led8 = 8;int led9 = 9;int led10= 10;int time1= 90;int time2= 500;int time3= 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); pinMode(led6, OUTPUT); pinMode(led7, OUTPUT); pinMode(led8, OUTPUT);

187

187

Page 188: Manual Geral Arduino

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); }

*/

188

188

Page 189: Manual Geral Arduino

POV

EXEMPLO 1

/*????????????????????????????????????????????persistence of vision typography with arduinomichael zoellner - march 2006http://i.document.m05.de

connect anodes (+) of 5 leds to digital ports of the arduino boardand 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 alphabetint _[] = {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0};int A[] = {0,1,1,1,1, 1,0,1,0,0, 0,1,1,1,1};int B[] = {1,1,1,1,1, 1,0,1,0,1, 0,1,0,1,0};int C[] = {0,1,1,1,0, 1,0,0,0,1, 1,0,0,0,1};int D[] = {1,1,1,1,1, 1,0,0,0,1, 0,1,1,1,0};int E[] = {1,1,1,1,1, 1,0,1,0,1, 1,0,1,0,1};int F[] = {1,1,1,1,1, 1,0,1,0,0, 1,0,1,0,0};int G[] = {0,1,1,1,0, 1,0,1,0,1, 0,0,1,1,0};int H[] = {1,1,1,1,1, 0,0,1,0,0, 1,1,1,1,1};int I[] = {0,0,0,0,1, 1,0,1,1,1, 0,0,0,0,1};int J[] = {1,0,0,0,0, 1,0,0,0,1, 1,1,1,1,1};int K[] = {1,1,1,1,1, 0,0,1,0,0, 0,1,0,1,1};int L[] = {1,1,1,1,1, 0,0,0,0,1, 0,0,0,0,1};int M[] = {1,1,1,1,1, 0,1,1,0,0, 0,1,1,1,1};int N[] = {1,1,1,1,1, 1,0,0,0,0, 0,1,1,1,1};int O[] = {0,1,1,1,0, 1,0,0,0,1, 0,1,1,1,0};int P[] = {1,1,1,1,1, 1,0,1,0,0, 0,1,0,0,0};int Q[] = {0,1,1,1,1, 1,0,0,1,1, 0,1,1,1,1};int R[] = {1,1,1,1,1, 1,0,1,0,0, 0,1,0,1,1};int S[] = {0,1,0,0,1, 1,0,1,0,1, 1,0,0,1,0};int T[] = {1,0,0,0,0, 1,1,1,1,1, 1,0,0,0,0};int U[] = {1,1,1,1,1, 0,0,0,0,1, 1,1,1,1,1};int V[] = {1,1,1,1,0, 0,0,0,0,1, 1,1,1,1,0};int W[] = {1,1,1,1,0, 0,0,1,1,0, 1,1,1,1,0};int X[] = {1,1,0,1,1, 0,0,1,0,0, 1,1,0,1,1};int Y[] = {1,1,0,0,0, 0,0,1,0,0, 1,1,1,1,1};int Z[] = {1,0,0,1,1, 1,0,1,0,1, 1,1,0,0,1};

int letterSpace;int dotTime;

void setup(){ // setting the ports of the leds to OUTPUT

189

189

Page 190: Manual Geral Arduino

pinMode(2, OUTPUT); pinMode(3, OUTPUT); 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(_);}

190

190

Page 191: Manual Geral Arduino

EXEMPLO 2

#define time 500

int greenPin1 = 13; // Green LED connected to digital pin 11int bluePin1 = 12; // Green LED connected to digital pin 10int redPin1 = 11; // Red LED connected to digital pin 12

int greenPin2 = 10; // Green LED connected to digital pin 11int bluePin2 = 9; // Green LED connected to digital pin 10int redPin2 = 8; // Red LED connected to digital pin 12

int greenPin3 = 7; // Green LED connected to digital pin 11int bluePin3 = 6; // Green LED connected to digital pin 10int redPin3 = 5; // Red LED connected to digital pin 12

int greenPin4 = 4; // Green LED connected to digital pin 11int bluePin4 = 3; // Green LED connected to digital pin 10int redPin4 = 2; // Red LED connected to digital pin 12

int bluePin5 = 1; // Green LED connected to digital pin 10int redPin5 = 0; // Red LED connected to digital pin 12

void setup() // run once, when the sketch starts{ pinMode(redPin1, OUTPUT); // sets the digital pin as output pinMode(greenPin1, OUTPUT); // sets the digital pin as output pinMode(bluePin1, OUTPUT); // sets the digital pin as output

pinMode(redPin2, OUTPUT); // sets the digital pin as output pinMode(greenPin2, OUTPUT); // sets the digital pin as output pinMode(bluePin2, OUTPUT); // sets the digital pin as output

pinMode(redPin3, OUTPUT); // sets the digital pin as output pinMode(greenPin3, OUTPUT); // sets the digital pin as output pinMode(bluePin3, OUTPUT); // sets the digital pin as output pinMode(redPin4, OUTPUT); // sets the digital pin as output pinMode(greenPin4, OUTPUT); // sets the digital pin as output pinMode(bluePin4, OUTPUT); // sets the digital pin as output

pinMode(bluePin5, OUTPUT); // sets the digital pin as output pinMode(redPin5, OUTPUT); // sets the digital pin as output

digitalWrite(redPin1, HIGH); // sets the Red LED on digitalWrite(greenPin1, HIGH); // sets the Red LED on digitalWrite(bluePin1, HIGH); // sets the Red LED on

digitalWrite(redPin2, HIGH); // sets the Red LED on

191

191

Page 192: Manual Geral Arduino

digitalWrite(greenPin2, HIGH); // sets the Red LED on digitalWrite(bluePin2, HIGH); // sets the Red LED on

digitalWrite(redPin3, HIGH); // sets the Red LED on digitalWrite(greenPin3, HIGH); // sets the Red LED on digitalWrite(bluePin3, HIGH); // sets the Red LED on

digitalWrite(redPin4, HIGH); // sets the Red LED on digitalWrite(greenPin4, HIGH); // sets the Red LED on digitalWrite(bluePin4, HIGH); // sets the Red LED on

digitalWrite(bluePin5, HIGH); // sets the Red LED on digitalWrite(redPin5, HIGH); // sets the Red LED on }

void loop() // run over and over again{ digitalWrite(redPin1, LOW); // sets the Red LED on delay(time); // waits for half a second digitalWrite(redPin1, HIGH); // 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, LOW); // sets the Red LED on delay(time); // waits for half a second digitalWrite(redPin2, 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, LOW); // sets the Red LED on delay(time); // waits for half a second digitalWrite(redPin3, 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

192

192

Page 193: Manual Geral Arduino

delay(time); // waits for half a second digitalWrite(redPin4, HIGH); // sets the Red LED on 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, LOW); // sets the Red LED on delay(time); // waits for half a second digitalWrite(bluePin5, HIGH); // sets the Red LED on digitalWrite(redPin5, LOW); // sets the Red LED on delay(time); // waits for half a second digitalWrite(redPin5, HIGH); // sets the Red LED on }

193

193

Page 194: Manual Geral Arduino

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}; // an array of pin numbersint col_len = 12; // column lenght

// customizable parametersint timer1 = 3; // time between columnsint timer2 = 15; // time between framesint timer3 = 0; // time between drawingsint 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); // set each pin as an 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);}

194

194

Page 195: Manual Geral Arduino

delay(timer2);}delay(timer3);

}

195

195

Page 196: Manual Geral Arduino

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}; // an array of pin numbersint col_len = 12; // column lenght

// customizable parametersint timer1 = 3; // time between columnsint timer2 = 15; // time between frames 15int timer3 = 20; // time between drawingsint 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); // set each pin as an 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);}

196

196

Page 197: Manual Geral Arduino

else {digitalWrite(pins[c], HIGH);}}delay(timer1);

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

}delay(timer3);

}

197

197

Page 198: Manual Geral Arduino

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}; // an array of pin numbersint col_len = 12; // column lenght

// customizable parametersint timer1 = 3; // time between columnsint timer2 = 15; // time between framesint timer3 = 0; // time between drawingsint 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); // set each pin as an 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);

}

198

198

Page 199: Manual Geral Arduino

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

}delay(timer3);

}

199

199

Page 200: Manual Geral Arduino

TEMPERATURA

EXEMPLO 1 TEMP COM 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**/

#define ProximaLeituraTemp 4000

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

int analogPin = 0; // analogic select the input pin for the temperatureint ledPin = 13; // pin for the LED

int valAnalog ; // variavel para armazenar o valor analogico lidoint temperatura ; int v_lcd = 0; //sensor de temperatura

//************************//***** 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);

200

200

Page 201: Manual Geral Arduino

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]); }

//****************************************************//************* 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 DIfor (i=DB[0]; i <= DI; i++) { digitalWrite(i,value1 & 01); value1 >>= 1;}digitalWrite(Enable,LOW); // send a pulse to enabledelayMicroseconds(1);digitalWrite(Enable,HIGH);delayMicroseconds(1);digitalWrite(Enable,LOW);delayMicroseconds(1); // pause 1 ms according to datasheetdelay(1);

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

201

201

Page 202: Manual Geral Arduino

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 enabledelayMicroseconds(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 enabledelayMicroseconds(1);digitalWrite(Enable,HIGH);delayMicroseconds(1);digitalWrite(Enable,LOW);delayMicroseconds(1); // pause 1 ms according to datasheetdelay(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 enabledelayMicroseconds(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 displayvoid LcdNumberWrite(int nr) {

int n1 = 0;

202

202

Page 203: Manual Geral Arduino

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)}

//***************void piscaLed() { digitalWrite(ledPin, HIGH); // Liga o led delay(50) ; digitalWrite(ledPin, LOW); // Desliga o Led}

//*******************int busca_lcd (void){ v_lcd = analogRead(5); return v_lcd; }

//*******************int busca_temp (void){ valAnalog = analogRead(analogPin); // Le o pino de entrada analogica 0 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 32676char ans[5];

while (num!=0) {

203

203

Page 204: Manual Geral Arduino

ones=num%10; //get current ones digit temp[i]=(char)(ones+48); //48=(int)'0'; num=num/10; //remove current ones digit 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 stringreturn (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 initializationLcdCommandWrite(0x03); // function set:// 4 pin initializationdelay(64);LcdCommandWrite(0x03); // function set:// 4 pin initializationdelay(50);LcdCommandWrite(0x03); // function set:// 4 pin initializationdelay(50);LcdCommandWrite(0x02); // function set:// 4 pin initializationdelay(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 shiftdelay(20);LcdCommandWrite(0x0E); // display control:// turn display on, cursor on, no blinking

204

204

Page 205: Manual Geral Arduino

delay(20);LcdCommandWrite(0x01); // clear display, set cursor position to zerodelay(100);

LcdCommandWrite(0x80); // display control:delay(20);

//////// unter this line are the special stuff you don't need for a initialitzation

LcdCommandWrite(0x0F); // cursor blinkdelay(10);

LcdCommandWrite(0x01); // clear display, set the cursor to home positiondelay(1000);

LcdCommandWrite(0x0E); // cursor not blinkdelay(10);LcdCommandWrite(0x02); // set cursor position to zerodelay(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);}

205

205

Page 206: Manual Geral Arduino

EXEMPLO 2 TEMP SENSOR 1

// Leitura de temperatura // Arduino monitorando temperatura com LM35// atraves da função analogRead() // Autor: Jeronimo Avelar Filho// 01/07/2007

int ledPin = 13; // LED ligado ao pino digital 13int analogPin = 5; // lm35 está ligado ao a entrada analogica 5int valAnalog ; // variavel para armazenar o valor analogico lidoint temperatura ;

void setup(){ pinMode(ledPin, OUTPUT); // programa o pino 13 como saida digital Serial.begin(9600); // programa a serial para comunicação em 9600 bps}

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); // Liga o led delay(50) ; digitalWrite(ledPin, LOW); // Desliga o Led}

206

206

Page 207: Manual Geral Arduino

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()); }

207

207

Page 208: Manual Geral Arduino

}

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

void 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 recomeça if(i>=250) { i=0 ; background(255, 204, 0); } }

208

208

Page 209: Manual Geral Arduino

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.nethttp://creativecommons.org/license/cc-gpl*/

int pin = 0; // analog pinint tempc = 0,tempf=0; // temperature variablesint samples[8]; // variables to make a better precisionint maxi = -100,mini = 100; // to start max/min temperatureint 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 precisiontempf = (tempc * 9)/ 5 + 32; // converts to fahrenheit

if(tempc > maxi) {maxi = tempc;} // set max temperatureif(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}

209

209

Page 210: Manual Geral Arduino

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 LEDif (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);}

210

210

Page 211: Manual Geral Arduino

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 // LED connected to digital pin 13#define lm35 0 // LM35 on Analog 0

//Defines will use less memory. Not as crucial here, but future sketches.

void sendlcd(byte command) //Quick function to send LCD commands.{ Serial.print(command, BYTE);}

void setup() // run once, when the sketch starts{ analogReference(INTERNAL); pinMode(ledPin, OUTPUT); // sets the digital pin as output pinMode(lm35, INPUT); digitalWrite(ledPin, HIGH); digitalWrite(lm35, LOW); delay(1000); 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);}

void loop() // run over and over again{ long temp; long temp1; long temp2;

211

211

Page 212: Manual Geral Arduino

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);}

212

212

Page 213: Manual Geral Arduino

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); }}

213

213

Page 214: Manual Geral Arduino

BLUETOOTH

void setup(){ pinMode(13,OUTPUT); pinMode(12,OUTPUT); pinMode(11,OUTPUT); Serial.begin(115200); //IMPORTANTE * Modulo bluesmirf funciona na //velocidade de 115200 }

void loop(){// digitalWrite(13, LOW); // set the LED off// delay(1000); // wait for a second// Serial.println(71,BYTE); //Serial.println('F'); if (Serial.available() > 0) { char c = Serial.read(); Serial.println(c); if (c == '1') digitalWrite(13,HIGH); //49 if (c == '2') digitalWrite(12,HIGH); if (c == '3') digitalWrite(11,HIGH); if (c == 'a') digitalWrite(13,LOW); //65 if (c == 'b') digitalWrite(12,LOW); if (c == 'c') digitalWrite(11,LOW);

delay(1000); }}

214

214

Page 215: Manual Geral Arduino

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); }}

215

215

Page 216: Manual Geral Arduino

BLUETOOTH COM 2 MOTORES

// Motor Shield test// by NKC Electronics// Test Motor B

//Motor Aint dirbpinA = 13; // Direction pin for motor B is Digital 13int speedbpinA = 10; // Speed pin for motor B is Digital 10 (PWM)

//Motor Bint dirbpinB = 12; // Direction pin for motor B is Digital 12int 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 ----------------------------------

216

216

Page 217: Manual Geral Arduino

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 (c == '1') digitalWrite(13,HIGH); // if (c == '2') digitalWrite(12,HIGH);// if (c == '3') digitalWrite(11,HIGH);// if (c == 'a') digitalWrite(13,LOW); // if (c == 'b') digitalWrite(12,LOW);// if (c == 'c') digitalWrite(11,LOW);

delay(1000); }

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

217

217

Page 218: Manual Geral Arduino

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);}

218

218