├── 9781430232407.jpg ├── Beginning Arduino ├── Ch02 │ ├── Project01.pde │ ├── Project02.pde │ ├── Project03.pde │ └── Project04.pde ├── Ch03 │ ├── Project05.pde │ ├── Project06.pde │ ├── Project07.pde │ ├── Project08.pde │ ├── Project09.pde │ └── Project10.pde ├── Ch04 │ ├── Project11.pde │ ├── Project12.pde │ ├── Project13.pde │ └── Project14.pde ├── Ch05 │ ├── Project15.pde │ └── Project16.pde ├── Ch06 │ ├── Project17.pde │ └── Project18.pde ├── Ch07 │ ├── Project19.pde │ ├── Project20.pde │ ├── Project21.pde │ └── Project22.pde ├── Ch08 │ ├── Project23.pde │ └── Project24.pde ├── Ch09 │ ├── Project25.pde │ ├── Project26.pde │ └── Project27.pde ├── Ch10 │ ├── Project28.pde │ ├── Project29.pde │ └── Project30.pde ├── Ch11 │ ├── Project31.pde │ └── Project32.pde ├── Ch12 │ ├── Project33.pde │ ├── Project34.pde │ └── Project35.pde ├── Ch13 │ ├── Project36.pde │ ├── Project37Part1.pde │ └── Project37Part2.pde ├── Ch14 │ ├── Project38.pde │ ├── Project39.pde │ ├── Project40.pde │ └── Project41.pde ├── Ch15 │ ├── Project42.pde │ └── Project43.pde ├── Ch16 │ ├── Project44.pde │ └── Project45.pde ├── Ch17 │ ├── Project46.pde │ ├── Project47.pde │ ├── Project48.pde │ ├── Project49.pde │ └── Project50.pde └── Color Insert images │ ├── McRoberts32407f0201.png │ ├── McRoberts32407f0206.png │ ├── McRoberts32407f0207.png │ ├── McRoberts32407f0208.png │ ├── McRoberts32407f0212.png │ ├── McRoberts32407f0301.png │ ├── McRoberts32407f0302.png │ ├── McRoberts32407f0303.jpg │ ├── McRoberts32407f0304.png │ ├── McRoberts32407f0305.png │ ├── McRoberts32407f0306.png │ ├── McRoberts32407f0401.png │ ├── McRoberts32407f0403.png │ ├── McRoberts32407f0404.png │ ├── McRoberts32407f0501.png │ ├── McRoberts32407f0503.png │ ├── McRoberts32407f0601.png │ ├── McRoberts32407f0604.png │ ├── McRoberts32407f0605.png │ ├── McRoberts32407f0701.png │ ├── McRoberts32407f0704.png │ ├── McRoberts32407f0708.png │ ├── McRoberts32407f0801.png │ ├── McRoberts32407f0802.png │ ├── McRoberts32407f0903.png │ ├── McRoberts32407f0905.png │ ├── McRoberts32407f0906.png │ ├── McRoberts32407f1001.png │ ├── McRoberts32407f1009.png │ ├── McRoberts32407f1102.png │ ├── McRoberts32407f1105.png │ ├── McRoberts32407f1201.png │ ├── McRoberts32407f1204.png │ ├── McRoberts32407f1206.png │ ├── McRoberts32407f1207.png │ ├── McRoberts32407f1301.png │ ├── McRoberts32407f1303.png │ ├── McRoberts32407f1401.png │ ├── McRoberts32407f1403.png │ ├── McRoberts32407f1405.png │ ├── McRoberts32407f1501.png │ ├── McRoberts32407f1502.png │ ├── McRoberts32407f1601.png │ ├── McRoberts32407f1603.png │ ├── McRoberts32407f1707.jpg │ └── Thumbs.db ├── LICENSE.txt ├── README.md └── contributing.md /9781430232407.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/9781430232407.jpg -------------------------------------------------------------------------------- /Beginning Arduino/Ch02/Project01.pde: -------------------------------------------------------------------------------- 1 | // Project 1 - LED Flasher 2 | int ledPin = 10; 3 | void setup() { 4 | pinMode(ledPin, OUTPUT); 5 | } 6 | void loop() { 7 | digitalWrite(ledPin, HIGH); 8 | delay(1000); 9 | digitalWrite(ledPin, LOW); 10 | delay(1000); 11 | } 12 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch02/Project02.pde: -------------------------------------------------------------------------------- 1 | // LED connected to digital pin 10 2 | int ledPin = 10; 3 | 4 | // run once, when the sketch starts 5 | void setup() 6 | { 7 | // sets the digital pin as output 8 | pinMode(ledPin, OUTPUT); 9 | } 10 | 11 | // run over and over again 12 | void loop() 13 | { 14 | // 3 dits 15 | for (int x=0; x<3; x++) { 16 | digitalWrite(ledPin, HIGH); // sets the LED on 17 | delay(150); // waits for 150ms 18 | digitalWrite(ledPin, LOW); // sets the LED off 19 | delay(100); // waits for 100ms 20 | } 21 | 22 | // 100ms delay to cause slight gap between letters 23 | delay(100); 24 | // 3 dahs 25 | for (int x=0; x<3; x++) { 26 | digitalWrite(ledPin, HIGH); // sets the LED on 27 | delay(400); // waits for 400ms 28 | digitalWrite(ledPin, LOW); // sets the LED off 29 | delay(100); // waits for 100ms 30 | } 31 | 32 | // 100ms delay to cause slight gap between letters 33 | delay(100); 34 | 35 | // 3 dits again 36 | for (int x=0; x<3; x++) { 37 | digitalWrite(ledPin, HIGH); // sets the LED on 38 | delay(150); // waits for 150ms 39 | digitalWrite(ledPin, LOW); // sets the LED off 40 | delay(100); // waits for 100ms 41 | } 42 | 43 | // wait 5 seconds before repeating the SOS signal 44 | delay(5000); 45 | } 46 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch02/Project03.pde: -------------------------------------------------------------------------------- 1 | // Project 3 - Traffic Lights 2 | 3 | int ledDelay = 10000; // delay in between changes 4 | int redPin = 10; 5 | int yellowPin = 9; 6 | int greenPin = 8; 7 | 8 | void setup() { 9 | pinMode(redPin, OUTPUT); 10 | pinMode(yellowPin, OUTPUT); 11 | pinMode(greenPin, OUTPUT); 12 | } 13 | 14 | void loop() { 15 | 16 | digitalWrite(redPin, HIGH); // turn the red light on 17 | delay(ledDelay); // wait 5 seconds 18 | 19 | digitalWrite(yellowPin, HIGH); // turn on yellow 20 | delay(2000); // wait 2 seconds 21 | 22 | digitalWrite(greenPin, HIGH); // turn green on 23 | digitalWrite(redPin, LOW); // turn red off 24 | digitalWrite(yellowPin, LOW); // turn yellow off 25 | delay(ledDelay); // wait ledDelay milliseconds 26 | 27 | digitalWrite(yellowPin, HIGH); // turn yellow on 28 | digitalWrite(greenPin, LOW); // turn green off 29 | delay(2000); // wait 2 seconds 30 | 31 | digitalWrite(yellowPin, LOW); // turn yellow off 32 | // now our loop repeats 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch02/Project04.pde: -------------------------------------------------------------------------------- 1 | // Project 4 - Interactive Traffic Lights 2 | 3 | int carRed = 12; // assign the car lights 4 | int carYellow = 11; 5 | int carGreen = 10; 6 | int pedRed = 9; // assign the pedestrian lights 7 | int pedGreen = 8; 8 | int button = 2; // button pin 9 | int crossTime = 5000; // time allowed to cross 10 | unsigned long changeTime; // time since button pressed 11 | 12 | void setup() { 13 | pinMode(carRed, OUTPUT); 14 | pinMode(carYellow, OUTPUT); 15 | pinMode(carGreen, OUTPUT); 16 | pinMode(pedRed, OUTPUT); 17 | pinMode(pedGreen, OUTPUT); 18 | pinMode(button, INPUT); // button on pin 2 19 | // turn on the green light 20 | digitalWrite(carGreen, HIGH); 21 | digitalWrite(pedRed, HIGH); 22 | } 23 | 24 | void loop() { 25 | int state = digitalRead(button); 26 | /* check if button is pressed and it is over 5 seconds since last button press */ 27 | if (state == HIGH && (millis() - changeTime) > 5000) { 28 | // Call the function to change the lights 29 | changeLights(); 30 | } 31 | } 32 | 33 | 34 | void changeLights() { 35 | digitalWrite(carGreen, LOW); // green off 36 | digitalWrite(carYellow, HIGH); // yellow on 37 | delay(2000); // wait 2 seconds 38 | 39 | digitalWrite(carYellow, LOW); // yellow off 40 | digitalWrite(carRed, HIGH); // red on 41 | delay(1000); // wait 1 second till its safe 42 | 43 | digitalWrite(pedRed, LOW); // ped red off 44 | digitalWrite(pedGreen, HIGH); // ped green on 45 | delay(crossTime); // wait for preset time period 46 | 47 | // flash the ped green 48 | for (int x=0; x<10; x++) { 49 | digitalWrite(pedGreen, HIGH); 50 | delay(250); 51 | digitalWrite(pedGreen, LOW); 52 | delay(250); 53 | } 54 | // turn ped red on 55 | digitalWrite(pedRed, HIGH); 56 | delay(500); 57 | 58 | digitalWrite(carYellow, HIGH); // yellow on 59 | digitalWrite(carRed, LOW); // red off 60 | delay(1000); 61 | digitalWrite(carGreen, HIGH); 62 | digitalWrite(carYellow, LOW); // yellow off 63 | 64 | // record the time since last change of lights 65 | changeTime = millis(); 66 | // then return to the main program loop 67 | } 68 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch03/Project05.pde: -------------------------------------------------------------------------------- 1 | // Project 5 - LED Chase Effect 2 | byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; // Create array for LED pins 3 | int ledDelay(65); // delay between changes 4 | int direction = 1; 5 | int currentLED = 0; 6 | unsigned long changeTime; 7 | 8 | void setup() { 9 | for (int x=0; x<10; x++) { // set all pins to output 10 | pinMode(ledPin[x], OUTPUT); } 11 | changeTime = millis(); 12 | } 13 | 14 | void loop() { 15 | if ((millis() - changeTime) > ledDelay) { // if it has been ledDelay ms since last change 16 | changeLED(); 17 | changeTime = millis(); 18 | } 19 | } 20 | 21 | void changeLED() { 22 | for (int x=0; x<10; x++) { // turn off all LED's 23 | digitalWrite(ledPin[x], LOW); 24 | } 25 | digitalWrite(ledPin[currentLED], HIGH); // turn on the current LED 26 | currentLED += direction; // increment by the direction value 27 | // change direction if we reach the end 28 | if (currentLED == 9) {direction = -1;} 29 | if (currentLED == 0) {direction = 1;} 30 | } 31 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch03/Project06.pde: -------------------------------------------------------------------------------- 1 | byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; // Create array for LED pins 2 | int ledDelay; // delay between changes 3 | int direction = 1; 4 | int currentLED = 0; 5 | unsigned long changeTime; 6 | int potPin = 2; // select the input pin for the potentiometer 7 | 8 | void setup() { 9 | for (int x=0; x<10; x++) { // set all pins to output 10 | pinMode(ledPin[x], OUTPUT); } 11 | changeTime = millis(); 12 | } 13 | void loop() { 14 | ledDelay = analogRead(potPin); // read the value from the pot 15 | if ((millis() - changeTime) > ledDelay) { // if it has been ledDelay ms since last change 16 | changeLED(); 17 | changeTime = millis(); 18 | } 19 | } 20 | 21 | void changeLED() { 22 | for (int x=0; x<10; x++) { // turn off all LED's 23 | digitalWrite(ledPin[x], LOW); 24 | } 25 | digitalWrite(ledPin[currentLED], HIGH); // turn on the current LED 26 | currentLED += direction; // increment by the direction value 27 | // change direction if we reach the end 28 | if (currentLED == 9) {direction = -1;} 29 | if (currentLED == 0) {direction = 1;} 30 | } 31 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch03/Project07.pde: -------------------------------------------------------------------------------- 1 | // Project 7 - Pulsating lamp 2 | int ledPin = 11; 3 | float sinVal; 4 | int ledVal; 5 | 6 | void setup() { 7 | pinMode(ledPin, OUTPUT); 8 | } 9 | 10 | void loop() { 11 | for (int x=0; x<180; x++) { 12 | // convert degrees to radians then obtain sin value 13 | sinVal = (sin(x*(3.1412/180))); 14 | ledVal = int(sinVal*255); 15 | analogWrite(ledPin, ledVal); 16 | delay(25); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch03/Project08.pde: -------------------------------------------------------------------------------- 1 | // Project 8 - Mood Lamp 2 | float RGB1[3]; 3 | float RGB2[3]; 4 | float INC[3]; 5 | 6 | int red, green, blue; 7 | 8 | int RedPin = 11; 9 | int GreenPin = 10; 10 | int BluePin = 9; 11 | 12 | void setup() 13 | { 14 | randomSeed(analogRead(0)); 15 | 16 | RGB1[0] = 0; 17 | RGB1[1] = 0; 18 | RGB1[2] = 0; 19 | 20 | RGB2[0] = random(256); 21 | RGB2[1] = random(256); 22 | RGB2[2] = random(256); 23 | } 24 | 25 | void loop() 26 | { 27 | randomSeed(analogRead(0)); 28 | 29 | for (int x=0; x<3; x++) { 30 | INC[x] = (RGB1[x] - RGB2[x]) / 256; } 31 | 32 | for (int x=0; x<256; x++) { 33 | red = int(RGB1[0]); 34 | green = int(RGB1[1]); 35 | blue = int(RGB1[2]); 36 | 37 | analogWrite (RedPin, red); 38 | analogWrite (GreenPin, green); 39 | analogWrite (BluePin, blue); 40 | delay(100); 41 | 42 | RGB1[0] -= INC[0]; 43 | RGB1[1] -= INC[1]; 44 | RGB1[2] -= INC[2]; 45 | } 46 | for (int x=0; x<3; x++) { 47 | RGB2[x] = random(556)-300; 48 | RGB2[x] = constrain(RGB2[x], 0, 255); 49 | delay(1000); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch03/Project09.pde: -------------------------------------------------------------------------------- 1 | // Project 9 - LED Fire Effect 2 | int ledPin1 = 9; 3 | int ledPin2 = 10; 4 | int ledPin3 = 11; 5 | 6 | void setup() 7 | { 8 | pinMode(ledPin1, OUTPUT); 9 | pinMode(ledPin2, OUTPUT); 10 | pinMode(ledPin3, OUTPUT); 11 | } 12 | 13 | void loop() 14 | { 15 | analogWrite(ledPin1, random(120)+135); 16 | analogWrite(ledPin2, random(120)+135); 17 | analogWrite(ledPin3, random(120)+135); 18 | delay(random(100)); 19 | } 20 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch03/Project10.pde: -------------------------------------------------------------------------------- 1 | // Project 10 - Serial controlled mood lamp 2 | char buffer[18]; 3 | int red, green, blue; 4 | 5 | int RedPin = 11; 6 | int GreenPin = 10; 7 | int BluePin = 9; 8 | 9 | void setup() 10 | { 11 | Serial.begin(9600); 12 | Serial.flush(); 13 | pinMode(RedPin, OUTPUT); 14 | pinMode(GreenPin, OUTPUT); 15 | pinMode(BluePin, OUTPUT); 16 | } 17 | 18 | void loop() 19 | { 20 | if (Serial.available() > 0) { 21 | int index=0; 22 | delay(100); // let the buffer fill up 23 | int numChar = Serial.available(); 24 | if (numChar>15) { 25 | numChar=15; 26 | } 27 | while (numChar--) { 28 | buffer[index++] = Serial.read(); 29 | } 30 | splitString(buffer); 31 | } 32 | } 33 | 34 | void splitString(char* data) { 35 | Serial.print("Data entered: "); 36 | Serial.println(data); 37 | char* parameter; 38 | parameter = strtok (data, " ,"); 39 | while (parameter != NULL) { 40 | setLED(parameter); 41 | parameter = strtok (NULL, " ,"); 42 | } 43 | 44 | // Clear the text and serial buffers 45 | for (int x=0; x<16; x++) { 46 | buffer[x]='\0'; 47 | } 48 | Serial.flush(); 49 | } 50 | 51 | void setLED(char* data) { 52 | if ((data[0] == 'r') || (data[0] == 'R')) { 53 | int Ans = strtol(data+1, NULL, 10); 54 | Ans = constrain(Ans,0,255); 55 | analogWrite(RedPin, Ans); 56 | Serial.print("Red is set to: "); 57 | Serial.println(Ans); 58 | } 59 | if ((data[0] == 'g') || (data[0] == 'G')) { 60 | int Ans = strtol(data+1, NULL, 10); 61 | Ans = constrain(Ans,0,255); 62 | analogWrite(GreenPin, Ans); 63 | Serial.print("Green is set to: "); 64 | Serial.println(Ans); 65 | } 66 | if ((data[0] == 'b') || (data[0] == 'B')) { 67 | int Ans = strtol(data+1, NULL, 10); 68 | Ans = constrain(Ans,0,255); 69 | analogWrite(BluePin, Ans); 70 | Serial.print("Blue is set to: "); 71 | Serial.println(Ans); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch04/Project11.pde: -------------------------------------------------------------------------------- 1 | // Project 11 - Piezo Sounder Alarm 2 | 3 | float sinVal; 4 | int toneVal; 5 | 6 | void setup() { 7 | pinMode(8, OUTPUT); 8 | } 9 | 10 | void loop() { 11 | for (int x=0; x<180; x++) { 12 | // convert degrees to radians then obtain sin value 13 | sinVal = (sin(x*(3.1412/180))); 14 | // generate a frequency from the sin value 15 | toneVal = 2000+(int(sinVal*1000)); 16 | tone(8, toneVal); 17 | delay(2); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch04/Project12.pde: -------------------------------------------------------------------------------- 1 | // Project 12 - Piezo Sounder Melody Player 2 | 3 | #define NOTE_C3 131 4 | #define NOTE_CS3 139 5 | #define NOTE_D3 147 6 | #define NOTE_DS3 156 7 | #define NOTE_E3 165 8 | #define NOTE_F3 175 9 | #define NOTE_FS3 185 10 | #define NOTE_G3 196 11 | #define NOTE_GS3 208 12 | #define NOTE_A3 220 13 | #define NOTE_AS3 233 14 | #define NOTE_B3 247 15 | #define NOTE_C4 262 16 | #define NOTE_CS4 277 17 | #define NOTE_D4 294 18 | #define NOTE_DS4 311 19 | #define NOTE_E4 330 20 | #define NOTE_F4 349 21 | #define NOTE_FS4 370 22 | #define NOTE_G4 392 23 | #define NOTE_GS4 415 24 | #define NOTE_A4 440 25 | #define NOTE_AS4 466 26 | #define NOTE_B4 494 27 | 28 | #define WHOLE 1 29 | #define HALF 0.5 30 | #define QUARTER 0.25 31 | #define EIGHTH 0.125 32 | #define SIXTEENTH 0.0625 33 | 34 | int tune[] = { NOTE_C4, NOTE_C4, NOTE_C4, NOTE_C4, NOTE_C4, NOTE_B3, NOTE_G3, NOTE_A3, NOTE_C4, NOTE_C4, NOTE_G3, NOTE_G3, NOTE_F3, NOTE_F3, NOTE_G3, NOTE_F3, NOTE_E3, NOTE_G3, NOTE_C4, NOTE_C4, NOTE_C4, NOTE_C4, NOTE_A3, NOTE_B3, NOTE_C4, NOTE_D4}; 35 | 36 | float duration[] = { EIGHTH, QUARTER+EIGHTH, SIXTEENTH, QUARTER, QUARTER, HALF, HALF, HALF, QUARTER, QUARTER, HALF+QUARTER, QUARTER, QUARTER, QUARTER, QUARTER+EIGHTH, EIGHTH, QUARTER, QUARTER, QUARTER, EIGHTH, EIGHTH, QUARTER, QUARTER, QUARTER, QUARTER, HALF+QUARTER}; 37 | 38 | int length; 39 | 40 | void setup() { 41 | pinMode(8, OUTPUT); 42 | length = sizeof(tune) / sizeof(tune[0]); 43 | } 44 | 45 | void loop() { 46 | for (int x=0; x= threshold) { // If knock detected set brightness to max 20 | ledValue = 255; 21 | } 22 | analogWrite(ledPin, int(ledValue) ); // Write brightness value to LED 23 | ledValue = ledValue - 0.05; // Dim the LED slowly 24 | if (ledValue <= 0) { ledValue = 0;} // Make sure value does not go below zero 25 | } 26 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch04/Project14.pde: -------------------------------------------------------------------------------- 1 | // Project 14 - Light Sensor 2 | 3 | int piezoPin = 8; // Piezo on Pin 8 4 | int ldrPin = 0; // LDR on Analog Pin 0 5 | int ldrValue = 0; // Value read from the LDR 6 | 7 | void setup() { 8 | // nothing to do here 9 | } 10 | 11 | void loop() { 12 | ldrValue = analogRead(ldrPin); // read the value from the LDR 13 | tone(piezoPin,1000); // play a 1000Hz tone from the piezo 14 | delay(25); // wait a bit 15 | noTone(piezoPin); // stop the tone 16 | delay(ldrValue); // wait the amount of milliseconds in ldrValue 17 | } 18 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch05/Project15.pde: -------------------------------------------------------------------------------- 1 | // Project 15 - Simple Motor Control 2 | 3 | int potPin = 0; // Analog in 0 connected to the potentiometer 4 | int transistorPin = 9; // PWM Pin 9 connected to the base of the transistor 5 | int potValue = 0; // value returned from the potentiometer 6 | 7 | void setup() { 8 | // set the transistor pin as output: 9 | pinMode(transistorPin, OUTPUT); 10 | } 11 | 12 | void loop() { 13 | // read the potentiometer, convert it to 0 - 255: 14 | potValue = analogRead(potPin) / 4; 15 | // use that to control the transistor: 16 | analogWrite(transistorPin, potValue); 17 | } 18 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch05/Project16.pde: -------------------------------------------------------------------------------- 1 | // Project 16 - Using an L293D Motor Driver IC 2 | #define switchPin 2 // switch input 3 | #define motorPin1 3 // L293D Input 1 4 | #define motorPin2 4 // L293D Input 2 5 | #define speedPin 9 // L293D enable pin 1 6 | #define potPin 0 // Potentiometer on analog Pin 0 7 | int Mspeed = 0; // a variable to hold the current speed value 8 | 9 | void setup() { 10 | //set switch pin as INPUT 11 | pinMode(switchPin, INPUT); 12 | 13 | // set remaining pins as outputs 14 | pinMode(motorPin1, OUTPUT); 15 | pinMode(motorPin2, OUTPUT); 16 | pinMode(speedPin, OUTPUT); 17 | } 18 | 19 | void loop() { 20 | Mspeed = analogRead(potPin)/4; // read the speed value from the potentiometer 21 | analogWrite(speedPin, Mspeed); // write speed to Enable 1 pin 22 | if (digitalRead(switchPin)) { // If the switch is HIGH, rotate motor clockwise 23 | digitalWrite(motorPin1, LOW); // set Input 1 of the L293D low 24 | digitalWrite(motorPin2, HIGH); // set Input 2 of the L293D high 25 | } 26 | else { // if the switch is LOW, rotate motor anti-clockwise 27 | digitalWrite(motorPin1, HIGH); // set Input 1 of the L293D low 28 | digitalWrite(motorPin2, LOW); // set Input 2 of the L293D high 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch06/Project17.pde: -------------------------------------------------------------------------------- 1 | // Project 17 2 | 3 | int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch) 4 | int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock) 5 | int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data) 6 | 7 | void setup() { 8 | //set pins to output 9 | pinMode(latchPin, OUTPUT); 10 | pinMode(clockPin, OUTPUT); 11 | pinMode(dataPin, OUTPUT); 12 | } 13 | 14 | void loop() { 15 | //count from 0 to 255 16 | for (int i = 0; i < 256; i++) { 17 | //set latchPin low to allow data flow 18 | digitalWrite(latchPin, LOW); 19 | shiftOut(i); 20 | //set latchPin to high to lock and send data 21 | digitalWrite(latchPin, HIGH); 22 | delay(1000); 23 | } 24 | } 25 | 26 | void shiftOut(byte dataOut) { 27 | // Shift out 8 bits LSB first, on rising edge of clock 28 | boolean pinState; 29 | digitalWrite(dataPin, LOW); //clear shift register ready for sending data 30 | digitalWrite(clockPin, LOW); 31 | 32 | for (int i=0; i<=7; i++) { // for each bit in dataOut send out a bit 33 | digitalWrite(clockPin, LOW); //set clockPin to LOW prior to sending bit 34 | 35 | // if the value of DataOut and (logical AND) a bitmask 36 | // are true, set pinState to 1 (HIGH) 37 | if ( dataOut & (1< 3 | 4 | int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch) 5 | int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock) 6 | int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data) 7 | 8 | byte led[8]; // 8 element unsigned integer array to store the sprite 9 | 10 | void setup() { 11 | pinMode(latchPin, OUTPUT); // set the 3 digital pins to outputs 12 | pinMode(clockPin, OUTPUT); 13 | pinMode(dataPin, OUTPUT); 14 | led[0] = B11111111; // enter the binary representation of the image 15 | led[1] = B10000001; // into the array 16 | led[2] = B10111101; 17 | led[3] = B10100101; 18 | led[4] = B10100101; 19 | led[5] = B10111101; 20 | led[6] = B10000001; 21 | led[7] = B11111111; 22 | // set a timer of length 10000 microseconds (1/100th of a second) 23 | Timer1.initialize(10000); 24 | // attach the screenUpdate function to the interrupt timer 25 | Timer1.attachInterrupt(screenUpdate); 26 | } 27 | 28 | void loop() { 29 | for (int i=0; i<8; i++) { 30 | led[i]= ~led[i]; // invert each row of the binary image 31 | } 32 | delay(500); 33 | } 34 | 35 | void screenUpdate() { // function to display image 36 | byte row = B10000000; // row 1 37 | for (byte k = 0; k < 9; k++) { 38 | digitalWrite(latchPin, LOW); // open latch ready to receive data 39 | shiftIt(~led[k] ); // shift out the LED array (inverted) 40 | shiftIt(row ); // shift out row binary number 41 | 42 | // Close the latch, sending the data in the registers out to the matrix 43 | digitalWrite(latchPin, HIGH); 44 | row = row << 1; // bitshift left 45 | } 46 | } 47 | 48 | void shiftIt(byte dataOut) { // Shift out 8 bits LSB first, on rising edge of clock 49 | 50 | boolean pinState; 51 | digitalWrite(dataPin, LOW); //clear shift register read for sending data 52 | 53 | for (int i=0; i<8; i++) { // for each bit in dataOut send out a bit 54 | digitalWrite(clockPin, LOW); //set clockPin to LOW prior to sending bit 55 | 56 | // if the value of DataOut and (logical AND) a bitmask 57 | // are true, set pinState to 1 (HIGH) 58 | if ( dataOut & (1< 3 | 4 | int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch) 5 | int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock) 6 | int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data) 7 | byte frame = 0; // variable to store the current frame being displayed 8 | 9 | byte led[8][8] = { {0, 56, 92, 158, 158, 130, 68, 56}, // 8 frames of an animation 10 | {0, 56, 124, 186, 146, 130, 68, 56}, 11 | {0, 56, 116, 242, 242, 130, 68, 56}, 12 | {0, 56, 68, 226, 242, 226, 68, 56}, 13 | {0, 56, 68, 130, 242, 242, 116, 56}, 14 | {0, 56, 68, 130, 146, 186, 124, 56}, 15 | {0, 56, 68, 130, 158, 158, 92, 56}, 16 | {0, 56, 68, 142, 158, 142, 68, 56} }; 17 | 18 | void setup() { 19 | pinMode(latchPin, OUTPUT); // set the 3 digital pins to outputs 20 | pinMode(clockPin, OUTPUT); 21 | pinMode(dataPin, OUTPUT); 22 | 23 | Timer1.initialize(10000); // set a timer of length 10000 microseconds 24 | Timer1.attachInterrupt(screenUpdate); // attach the screenUpdate function 25 | } 26 | 27 | void loop() { 28 | for (int i=0; i<8; i++) { // loop through all 8 frames of the animation 29 | for (int j=0; j<8; j++) { // loop through the 8 rows per frame 30 | led[i][j]= led[i][j] << 1 | led[i][j] >> 7; // bitwise rotation 31 | } 32 | } 33 | frame++; // go to the next frame in the animation 34 | if (frame>7) { frame =0;} // make sure we go back to frame 0 once past 7 35 | delay(100); // wait a bit between frames 36 | } 37 | 38 | void screenUpdate() { // function to display image 39 | byte row = B10000000; // row 1 40 | for (byte k = 0; k < 9; k++) { 41 | digitalWrite(latchPin, LOW); // open latch ready to receive data 42 | 43 | shiftIt(~led[frame][k] ); // LED array (inverted) 44 | shiftIt(row); // row binary number 45 | 46 | // Close the latch, sending the data in the registers out to the matrix 47 | digitalWrite(latchPin, HIGH); 48 | row = row >> 1; // bitshift right 49 | } 50 | } 51 | 52 | void shiftIt(byte dataOut) { 53 | // Shift out 8 bits LSB first, on rising edge of clock 54 | 55 | boolean pinState; 56 | 57 | //clear shift register read for sending data 58 | digitalWrite(dataPin, LOW); 59 | 60 | // for each bit in dataOut send out a bit 61 | for (int i=0; i<8; i++) { 62 | //set clockPin to LOW prior to sending bit 63 | digitalWrite(clockPin, LOW); 64 | 65 | // if the value of DataOut and (logical AND) a bitmask 66 | // are true, set pinState to 1 (HIGH) 67 | if ( dataOut & (1< 2 | #include 3 | 4 | int DataPin = 2; // Pin 1 on MAX 5 | int LoadPin = 3; // Pin 12 on MAX 6 | int ClockPin = 4; // Pin 13 on MAX 7 | byte buffer[8]; 8 | 9 | static byte font[][8] PROGMEM = { 10 | // The printable ASCII characters only (32-126) 11 | {B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000}, 12 | {B00000100, B00000100, B00000100, B00000100, B00000100, B00000100, B00000000, B00000100}, 13 | {B00001010, B00001010, B00001010, B00000000, B00000000, B00000000, B00000000, B00000000}, 14 | {B00000000, B00001010, B00011111, B00001010, B00011111, B00001010, B00011111, B00001010}, 15 | {B00000111, B00001100, B00010100, B00001100, B00000110, B00000101, B00000110, B00011100}, 16 | {B00011001, B00011010, B00000010, B00000100, B00000100, B00001000, B00001011, B00010011}, 17 | {B00000110, B00001010, B00010010, B00010100, B00001001, B00010110, B00010110, B00001001}, 18 | {B00000100, B00000100, B00000100, B00000000, B00000000, B00000000, B00000000, B00000000}, 19 | {B00000010, B00000100, B00001000, B00001000, B00001000, B00001000, B00000100, B00000010}, 20 | {B00001000, B00000100, B00000010, B00000010, B00000010, B00000010, B00000100, B00001000}, 21 | {B00010101, B00001110, B00011111, B00001110, B00010101, B00000000, B00000000, B00000000}, 22 | {B00000000, B00000000, B00000100, B00000100, B00011111, B00000100, B00000100, B00000000}, 23 | {B00000000, B00000000, B00000000, B00000000, B00000000, B00000110, B00000100, B00001000}, 24 | {B00000000, B00000000, B00000000, B00000000, B00001110, B00000000, B00000000, B00000000}, 25 | {B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000100}, 26 | {B00000001, B00000010, B00000010, B00000100, B00000100, B00001000, B00001000, B00010000}, 27 | {B00001110, B00010001, B00010011, B00010001, B00010101, B00010001, B00011001, B00001110}, 28 | {B00000100, B00001100, B00010100, B00000100, B00000100, B00000100, B00000100, B00011111}, 29 | {B00001110, B00010001, B00010001, B00000010, B00000100, B00001000, B00010000, B00011111}, 30 | {B00001110, B00010001, B00000001, B00001110, B00000001, B00000001, B00010001, B00001110}, 31 | {B00010000, B00010000, B00010100, B00010100, B00011111, B00000100, B00000100, B00000100}, 32 | {B00011111, B00010000, B00010000, B00011110, B00000001, B00000001, B00000001, B00011110}, 33 | {B00000111, B00001000, B00010000, B00011110, B00010001, B00010001, B00010001, B00001110}, 34 | {B00011111, B00000001, B00000001, B00000001, B00000010, B00000100, B00001000, B00010000}, 35 | {B00001110, B00010001, B00010001, B00001110, B00010001, B00010001, B00010001, B00001110}, 36 | {B00001110, B00010001, B00010001, B00001111, B00000001, B00000001, B00000001, B00000001}, 37 | {B00000000, B00000100, B00000100, B00000000, B00000000, B00000100, B00000100, B00000000}, 38 | {B00000000, B00000100, B00000100, B00000000, B00000000, B00000100, B00000100, B00001000}, 39 | {B00000001, B00000010, B00000100, B00001000, B00001000, B00000100, B00000010, B00000001}, 40 | {B00000000, B00000000, B00000000, B00011110, B00000000, B00011110, B00000000, B00000000}, 41 | {B00010000, B00001000, B00000100, B00000010, B00000010, B00000100, B00001000, B00010000}, 42 | {B00001110, B00010001, B00010001, B00000010, B00000100, B00000100, B00000000, B00000100}, 43 | {B00001110, B00010001, B00010001, B00010101, B00010101, B00010001, B00010001, B00011110}, 44 | {B00001110, B00010001, B00010001, B00010001, B00011111, B00010001, B00010001, B00010001}, 45 | {B00011110, B00010001, B00010001, B00011110, B00010001, B00010001, B00010001, B00011110}, 46 | {B00000111, B00001000, B00010000, B00010000, B00010000, B00010000, B00001000, B00000111}, 47 | {B00011100, B00010010, B00010001, B00010001, B00010001, B00010001, B00010010, B00011100}, 48 | {B00011111, B00010000, B00010000, B00011110, B00010000, B00010000, B00010000, B00011111}, 49 | {B00011111, B00010000, B00010000, B00011110, B00010000, B00010000, B00010000, B00010000}, 50 | {B00001110, B00010001, B00010000, B00010000, B00010111, B00010001, B00010001, B00001110}, 51 | {B00010001, B00010001, B00010001, B00011111, B00010001, B00010001, B00010001, B00010001}, 52 | {B00011111, B00000100, B00000100, B00000100, B00000100, B00000100, B00000100, B00011111}, 53 | {B00011111, B00000100, B00000100, B00000100, B00000100, B00000100, B00010100, B00001000}, 54 | {B00010001, B00010010, B00010100, B00011000, B00010100, B00010010, B00010001, B00010001}, 55 | {B00010000, B00010000, B00010000, B00010000, B00010000, B00010000, B00010000, B00011111}, 56 | {B00010001, B00011011, B00011111, B00010101, B00010001, B00010001, B00010001, B00010001}, 57 | {B00010001, B00011001, B00011001, B00010101, B00010101, B00010011, B00010011, B00010001}, 58 | {B00001110, B00010001, B00010001, B00010001, B00010001, B00010001, B00010001, B00001110}, 59 | {B00011110, B00010001, B00010001, B00011110, B00010000, B00010000, B00010000, B00010000}, 60 | {B00001110, B00010001, B00010001, B00010001, B00010001, B00010101, B00010011, B00001111}, 61 | {B00011110, B00010001, B00010001, B00011110, B00010100, B00010010, B00010001, B00010001}, 62 | {B00001110, B00010001, B00010000, B00001000, B00000110, B00000001, B00010001, B00001110}, 63 | {B00011111, B00000100, B00000100, B00000100, B00000100, B00000100, B00000100, B00000100}, 64 | {B00010001, B00010001, B00010001, B00010001, B00010001, B00010001, B00010001, B00001110}, 65 | {B00010001, B00010001, B00010001, B00010001, B00010001, B00010001, B00001010, B00000100}, 66 | {B00010001, B00010001, B00010001, B00010001, B00010001, B00010101, B00010101, B00001010}, 67 | {B00010001, B00010001, B00001010, B00000100, B00000100, B00001010, B00010001, B00010001}, 68 | {B00010001, B00010001, B00001010, B00000100, B00000100, B00000100, B00000100, B00000100}, 69 | {B00011111, B00000001, B00000010, B00000100, B00001000, B00010000, B00010000, B00011111}, 70 | {B00001110, B00001000, B00001000, B00001000, B00001000, B00001000, B00001000, B00001110}, 71 | {B00010000, B00001000, B00001000, B00000100, B00000100, B00000010, B00000010, B00000001}, 72 | {B00001110, B00000010, B00000010, B00000010, B00000010, B00000010, B00000010, B00001110}, 73 | {B00000100, B00001010, B00010001, B00000000, B00000000, B00000000, B00000000, B00000000}, 74 | {B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00011111}, 75 | {B00001000, B00000100, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000}, 76 | {B00000000, B00000000, B00000000, B00001110, B00010010, B00010010, B00010010, B00001111}, 77 | {B00000000, B00010000, B00010000, B00010000, B00011100, B00010010, B00010010, B00011100}, 78 | {B00000000, B00000000, B00000000, B00001110, B00010000, B00010000, B00010000, B00001110}, 79 | {B00000000, B00000001, B00000001, B00000001, B00000111, B00001001, B00001001, B00000111}, 80 | {B00000000, B00000000, B00000000, B00011100, B00010010, B00011110, B00010000, B00001110}, 81 | {B00000000, B00000011, B00000100, B00000100, B00000110, B00000100, B00000100, B00000100}, 82 | {B00000000, B00001110, B00001010, B00001010, B00001110, B00000010, B00000010, B00001100}, 83 | {B00000000, B00010000, B00010000, B00010000, B00011100, B00010010, B00010010, B00010010}, 84 | {B00000000, B00000000, B00000100, B00000000, B00000100, B00000100, B00000100, B00000100}, 85 | {B00000000, B00000010, B00000000, B00000010, B00000010, B00000010, B00000010, B00001100}, 86 | {B00000000, B00010000, B00010000, B00010100, B00011000, B00011000, B00010100, B00010000}, 87 | {B00000000, B00010000, B00010000, B00010000, B00010000, B00010000, B00010000, B00001100}, 88 | {B00000000, B00000000, B00000000, B00001010, B00010101, B00010001, B00010001, B00010001}, 89 | {B00000000, B00000000, B00000000, B00010100, B00011010, B00010010, B00010010, B00010010}, 90 | {B00000000, B00000000, B00000000, B00001100, B00010010, B00010010, B00010010, B00001100}, 91 | {B00000000, B00011100, B00010010, B00010010, B00011100, B00010000, B00010000, B00010000}, 92 | {B00000000, B00001110, B00010010, B00010010, B00001110, B00000010, B00000010, B00000001}, 93 | {B00000000, B00000000, B00000000, B00001010, B00001100, B00001000, B00001000, B00001000}, 94 | {B00000000, B00000000, B00001110, B00010000, B00001000, B00000100, B00000010, B00011110}, 95 | {B00000000, B00010000, B00010000, B00011100, B00010000, B00010000, B00010000, B00001100}, 96 | {B00000000, B00000000, B00000000, B00010010, B00010010, B00010010, B00010010, B00001100}, 97 | {B00000000, B00000000, B00000000, B00010001, B00010001, B00010001, B00001010, B00000100}, 98 | {B00000000, B00000000, B00000000, B00010001, B00010001, B00010001, B00010101, B00001010}, 99 | {B00000000, B00000000, B00000000, B00010001, B00001010, B00000100, B00001010, B00010001}, 100 | {B00000000, B00000000, B00010001, B00001010, B00000100, B00001000, B00001000, B00010000}, 101 | {B00000000, B00000000, B00000000, B00011111, B00000010, B00000100, B00001000, B00011111}, 102 | {B00000010, B00000100, B00000100, B00000100, B00001000, B00000100, B00000100, B00000010}, 103 | {B00000100, B00000100, B00000100, B00000100, B00000100, B00000100, B00000100, B00000100}, 104 | {B00001000, B00000100, B00000100, B00000100, B00000010, B00000100, B00000100, B00001000}, 105 | {B00000000, B00000000, B00000000, B00001010, B00011110, B00010100, B00000000, B00000000} 106 | }; 107 | 108 | void clearDisplay() { 109 | for (byte x=0; x<8; x++) { 110 | buffer[x] = B00000000; 111 | } 112 | screenUpdate(); 113 | } 114 | 115 | void initMAX7219() { 116 | pinMode(DataPin, OUTPUT); 117 | pinMode(LoadPin, OUTPUT); 118 | pinMode(ClockPin, OUTPUT); 119 | clearDisplay(); 120 | writeData(B00001011, B00000111); // scan limit set to 0:7 121 | writeData(B00001001, B00000000); // decode mode off 122 | writeData(B00001100, B00000001); // Set shutdown register to normal operation 123 | intensity(15); // Values 0 to 15 only (4 bit) 124 | } 125 | 126 | void intensity(int intensity) { 127 | writeData(B00001010, intensity); //B0001010 is the Intensity Register 128 | } 129 | 130 | void writeData(byte MSB, byte LSB) { 131 | byte mask; 132 | digitalWrite(LoadPin, LOW); // set loadpin ready to receive data 133 | // Send out MSB 134 | for (mask = B10000000; mask>0; mask >>= 1) { //iterate through bit mask 135 | digitalWrite(ClockPin, LOW); 136 | if (MSB & mask){ // if bitwise AND resolves to true 137 | digitalWrite(DataPin,HIGH); // send 1 138 | } 139 | else{ //if bitwise and resolves to false 140 | digitalWrite(DataPin,LOW); // send 0 141 | } 142 | digitalWrite(ClockPin, HIGH); // clock high, data gets input 143 | } 144 | // send out LSB for data 145 | for (mask = B10000000; mask>0; mask >>= 1) { //iterate through bit mask 146 | digitalWrite(ClockPin, LOW); 147 | if (LSB & mask){ // if bitwise AND resolves to true 148 | digitalWrite(DataPin,HIGH); // send 1 149 | } 150 | else{ //if bitwise and resolves to false 151 | digitalWrite(DataPin,LOW); // send 0 152 | } 153 | digitalWrite(ClockPin, HIGH); // clock high, data gets input 154 | } 155 | digitalWrite(LoadPin, HIGH); // latch the data 156 | digitalWrite(ClockPin, LOW); 157 | } 158 | 159 | 160 | void scroll(char myString[], int speed) { 161 | byte firstChrRow, secondChrRow; 162 | byte ledOutput; 163 | byte chrPointer = 0; // Initialise the string position pointer 164 | byte Char1, Char2; // the two characters that will be displayed 165 | byte scrollBit = 0; 166 | byte strLength = 0; 167 | unsigned long time; 168 | unsigned long counter; 169 | 170 | // Increment count till we reach the string 171 | while (myString[strLength]) {strLength++;} 172 | 173 | counter = millis(); 174 | while (chrPointer < (strLength-1)) { 175 | time = millis(); 176 | if (time > (counter + speed)) { 177 | Char1 = myString[chrPointer]; 178 | Char2 = myString[chrPointer+1]; 179 | for (byte y= 0; y<8; y++) { 180 | firstChrRow = pgm_read_byte(&font[Char1 - 32][y]); 181 | secondChrRow = (pgm_read_byte(&font[Char2 - 32][y])) << 1; 182 | ledOutput = (firstChrRow << scrollBit) | (secondChrRow >> 183 | (8 - scrollBit) ); 184 | buffer[y] = ledOutput; 185 | } 186 | scrollBit++; 187 | if (scrollBit > 6) { 188 | scrollBit = 0; 189 | chrPointer++; 190 | } 191 | counter = millis(); 192 | } 193 | } 194 | } 195 | 196 | void screenUpdate() { 197 | for (byte row = 0; row < 8; row++) { 198 | writeData(row+1, buffer[row]); 199 | } 200 | } 201 | 202 | void setup() { 203 | initMAX7219(); 204 | Timer1.initialize(10000); // initialize timer1 and set interrupt period 205 | Timer1.attachInterrupt(screenUpdate); 206 | } 207 | 208 | void loop() { 209 | clearDisplay(); 210 | scroll(" BEGINNING ARDUINO ", 45); 211 | scroll(" Chapter 7 - LED Displays ", 45); 212 | scroll(" HELLO WORLD!!! :) ", 45); 213 | } 214 | 215 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch07/Project22.pde: -------------------------------------------------------------------------------- 1 | //Project 22 2 | #include "LedControl.h" 3 | 4 | LedControl myMatrix = LedControl(2, 4, 3, 1); // create an instance of a Matrix 5 | 6 | int column = 1, row = random(8)+1; // decide where the ball will start 7 | int directionX = 1, directionY = 1; // make sure it heads from left to right first 8 | int paddle1 = 5, paddle1Val; // Pot pin and value 9 | int speed = 300; 10 | int counter = 0, mult = 10; 11 | 12 | void setup() 13 | { 14 | myMatrix.shutdown(0, false); // enable display 15 | myMatrix.setIntensity(0, 8); // Set the brightness to medium 16 | myMatrix.clearDisplay(0); // clear the display 17 | randomSeed(analogRead(0)); 18 | } 19 | 20 | void loop() 21 | { 22 | paddle1Val = analogRead(paddle1); 23 | paddle1Val = map(paddle1Val, 200, 1024, 1,6); 24 | column += directionX; 25 | row += directionY; 26 | if (column == 6 && directionX == 1 && (paddle1Val == row || paddle1Val+1 == 27 | row || paddle1Val+2 == row)) {directionX = -1;} 28 | if (column == 0 && directionX == -1 ) {directionX = 1;} 29 | if (row == 7 && directionY == 1 ) {directionY = -1;} 30 | if (row == 0 && directionY == -1 ) {directionY = 1;} 31 | if (column == 7) { oops();} 32 | myMatrix.clearDisplay(0); // clear the screen for next animation frame 33 | myMatrix.setLed(0, column, row, HIGH); 34 | myMatrix.setLed(0, 7, paddle1Val, HIGH); 35 | myMatrix.setLed(0, 7, paddle1Val+1, HIGH); 36 | myMatrix.setLed(0, 7, paddle1Val+2, HIGH); 37 | if (!(counter % mult)) {speed -= 5; mult * mult;} 38 | delay(speed); 39 | counter++; 40 | } 41 | 42 | void oops() { 43 | for (int x=0; x<3; x++) { 44 | myMatrix.clearDisplay(0); 45 | delay(250); 46 | for (int y=0; y<8; y++) { 47 | myMatrix.setRow(0, y, 255); 48 | } 49 | delay(250); 50 | } 51 | counter=0; // reset all the values 52 | speed=300; 53 | column=1; 54 | row = random(8)+1; // choose a new starting location 55 | } 56 | 57 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch08/Project23.pde: -------------------------------------------------------------------------------- 1 | // PROJECT 23 2 | #include 3 | 4 | // initialize the library with the numbers of the interface pins 5 | LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // create an lcd object and assign the pins 6 | 7 | void setup() { 8 | lcd.begin(16, 2); // Set the display to 16 columns and 2 rows 9 | } 10 | 11 | void loop() { 12 | // run the 7 demo routines 13 | basicPrintDemo(); 14 | displayOnOffDemo(); 15 | setCursorDemo(); 16 | scrollLeftDemo(); 17 | scrollRightDemo(); 18 | cursorDemo(); 19 | createGlyphDemo(); 20 | } 21 | 22 | void basicPrintDemo() { 23 | lcd.clear(); // Clear the display 24 | lcd.print("Basic Print"); // print some text 25 | delay(2000); 26 | } 27 | 28 | void displayOnOffDemo() { 29 | lcd.clear(); // Clear the display 30 | lcd.print("Display On/Off"); // print some text 31 | for(int x=0; x < 3; x++) { // loop 3 times 32 | lcd.noDisplay(); // turn display off 33 | delay(1000); 34 | lcd.display(); // turn it back on again 35 | delay(1000); 36 | } 37 | } 38 | 39 | void setCursorDemo() { 40 | lcd.clear(); // Clear the display 41 | lcd.print("SetCursor Demo"); // print some text 42 | delay(1000); 43 | lcd.clear(); // Clear the display 44 | lcd.setCursor(5,0); // cursor at column 5 row 0 45 | lcd.print("5,0"); 46 | delay(2000); 47 | lcd.setCursor(10,1); // cursor at column 10 row 1 48 | lcd.print("10,1"); 49 | delay(2000); 50 | lcd.setCursor(3,1); // cursor at column 3 row 1 51 | lcd.print("3,1"); 52 | delay(2000); 53 | } 54 | 55 | void scrollLeftDemo() { 56 | lcd.clear(); // Clear the display 57 | lcd.print("Scroll Left Demo"); 58 | delay(1000); 59 | lcd.clear(); // Clear the display 60 | lcd.setCursor(7,0); 61 | lcd.print("Beginning"); 62 | lcd.setCursor(9,1); 63 | lcd.print("Arduino"); 64 | delay(1000); 65 | for(int x=0; x<16; x++) { 66 | lcd.scrollDisplayLeft(); // scroll display left 16 times 67 | delay(250); 68 | } 69 | } 70 | 71 | void scrollRightDemo() { 72 | lcd.clear(); // Clear the display 73 | lcd.print("Scroll Right"); 74 | lcd.setCursor(0,1); 75 | lcd.print("Demo"); 76 | delay(1000); 77 | lcd.clear(); // Clear the display 78 | lcd.print("Beginning"); 79 | lcd.setCursor(0,1); 80 | lcd.print("Arduino"); 81 | delay(1000); 82 | for(int x=0; x<16; x++) { 83 | lcd.scrollDisplayRight(); // scroll display right 16 times 84 | delay(250); 85 | } 86 | } 87 | 88 | void cursorDemo() { 89 | lcd.clear(); // Clear the display 90 | lcd.cursor(); // Enable cursor visible 91 | lcd.print("Cursor On"); 92 | delay(3000); 93 | lcd.clear(); // Clear the display 94 | lcd.noCursor(); // cursor invisible 95 | lcd.print("Cursor Off"); 96 | delay(3000); 97 | lcd.clear(); // Clear the display 98 | lcd.cursor(); // cursor visible 99 | lcd.blink(); // cursor blinking 100 | lcd.print("Cursor Blink On"); 101 | delay(3000); 102 | lcd.noCursor(); // cursor invisible 103 | lcd.noBlink(); // blink off 104 | } 105 | 106 | 107 | void createGlyphDemo() { 108 | lcd.clear(); 109 | 110 | byte happy[8] = { // create byte array with happy face 111 | B00000, 112 | B00000, 113 | B10001, 114 | B00000, 115 | B10001, 116 | B01110, 117 | B00000, 118 | B00000}; 119 | 120 | byte sad[8] = { // create byte array with sad face 121 | B00000, 122 | B00000, 123 | B10001, 124 | B00000, 125 | B01110, 126 | B10001, 127 | B00000, 128 | B00000}; 129 | lcd.createChar(0, happy); // create custom character 0 130 | lcd.createChar(1, sad); // create custom character 1 131 | 132 | for(int x=0; x<5; x++) { // loop animation 5 times 133 | lcd.setCursor(8,0); 134 | lcd.write(0); // write custom char 0 135 | delay(1000); 136 | lcd.setCursor(8,0); 137 | lcd.write(1); // write custom char 1 138 | delay(1000); 139 | } 140 | } 141 | 142 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch08/Project24.pde: -------------------------------------------------------------------------------- 1 | // PROJECT 24 2 | #include 3 | 4 | // initialize the library with the numbers of the interface pins 5 | LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // create an lcd object and assign the pins 6 | int maxC=0, minC=100, maxF=0, minF=212; 7 | int scale = 1; 8 | int buttonPin=8; 9 | void setup() { 10 | lcd.begin(16, 2); // Set the display to 16 columns and 2 rows 11 | analogReference(INTERNAL); 12 | pinMode(buttonPin, INPUT); 13 | lcd.clear(); 14 | } 15 | 16 | void loop() { 17 | lcd.setCursor(0,0); // set cursor to home position 18 | int sensor = analogRead(0); // read the temp from sensor 19 | int buttonState = digitalRead(buttonPin); // check for button press 20 | switch (buttonState) { // change scale state if pressed 21 | case HIGH: 22 | scale=-scale; // invert scale 23 | lcd.clear(); 24 | } 25 | 26 | delay(250); 27 | switch (scale) { // decide if C or F scale 28 | case 1: 29 | celsius(sensor); 30 | break; 31 | case -1: 32 | fahrenheit(sensor); 33 | } 34 | } 35 | 36 | void celsius(int sensor) { 37 | lcd.setCursor(0,0); 38 | int temp = sensor * 0.09765625; // convert to C 39 | lcd.print(temp); 40 | lcd.write(B11011111); // degree symbol 41 | lcd.print("C "); 42 | if (temp>maxC) {maxC=temp;} 43 | if (tempmaxF) {maxF=temp;} 61 | if (temp 3 | 4 | Servo servo1; // Create a servo object 5 | 6 | void setup() 7 | { 8 | servo1.attach(5); // attaches the servo on pin 5 to the servo object 9 | } 10 | 11 | void loop() 12 | { 13 | int angle = analogRead(0); // read the pot value 14 | angle=map(angle, 0, 1023, 0, 180); // map the values from 0 to 180 degrees 15 | servo1.write(angle); // write the angle to the servo 16 | delay(15); // delay of 15ms to allow servo to reach position 17 | } 18 | 19 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch09/Project26.pde: -------------------------------------------------------------------------------- 1 | // Project 26 2 | #include 3 | 4 | char buffer[10]; 5 | Servo servo1; // Create a servo object 6 | Servo servo2; // Create a second servo object 7 | 8 | void setup() 9 | { 10 | servo1.attach(5); // attaches the servo on pin 5 to the servo1 object 11 | servo2.attach(6); // attaches the servo on pin 6 to the servo2 object 12 | Serial.begin(9600); 13 | Serial.flush(); 14 | servo1.write(90); // put servo1 at home position 15 | servo2.write(90); // put servo2 at home postion 16 | Serial.println("STARTING..."); 17 | } 18 | 19 | void loop() 20 | { 21 | if (Serial.available() > 0) { // check if data has been entered 22 | int index=0; 23 | delay(100); // let the buffer fill up 24 | int numChar = Serial.available(); // find the string length 25 | if (numChar>10) { 26 | numChar=10; 27 | } 28 | while (numChar--) { 29 | // fill the buffer with the string 30 | buffer[index++] = Serial.read(); 31 | } 32 | splitString(buffer); // run splitString function 33 | } 34 | } 35 | 36 | void splitString(char* data) { 37 | Serial.print("Data entered: "); 38 | Serial.println(data); 39 | char* parameter; 40 | parameter = strtok (data, " ,"); //string to token 41 | while (parameter != NULL) { // if we haven't reached the end of the string... 42 | setServo(parameter); // ...run the setServo function 43 | parameter = strtok (NULL, " ,"); 44 | } 45 | // Clear the text and serial buffers 46 | for (int x=0; x<9; x++) { 47 | buffer[x]='\0'; 48 | } 49 | Serial.flush(); 50 | } 51 | 52 | 53 | void setServo(char* data) { 54 | if ((data[0] == 'L') || (data[0] == 'l')) { 55 | int firstVal = strtol(data+1, NULL, 10); // string to long integer 56 | firstVal = constrain(firstVal,0,180); // constrain values 57 | servo1.write(firstVal); 58 | Serial.print("Servo1 is set to: "); 59 | Serial.println(firstVal); 60 | } 61 | if ((data[0] == 'R') || (data[0] == 'r')) { 62 | int secondVal = strtol(data+1, NULL, 10); // string to long integer 63 | secondVal = constrain(secondVal,0,255); // constrain the values 64 | servo2.write(secondVal); 65 | Serial.print("Servo2 is set to: "); 66 | Serial.println(secondVal); 67 | } 68 | } 69 | 70 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch09/Project27.pde: -------------------------------------------------------------------------------- 1 | // Project 27 2 | #include 3 | 4 | Servo servo1; // Create a servo object 5 | Servo servo2; // Create a second servo object 6 | int pot1, pot2; 7 | 8 | void setup() 9 | { 10 | servo1.attach(5); // attaches the servo on pin 5 to the servo1 object 11 | servo2.attach(6); // attaches the servo on pin 6 to the servo2 object 12 | 13 | servo1.write(90); // put servo1 at home position 14 | servo2.write(90); // put servo2 at home postion 15 | 16 | } 17 | 18 | void loop() 19 | { 20 | pot1 = analogRead(3); // read the X-Axis 21 | pot2 = analogRead(4); // read the Y-Axis 22 | pot1 = map(pot1,0,1023,0,180); 23 | pot2=map(pot2,0,1023,0,180); 24 | servo1.write(pot1); 25 | servo2.write(pot2); 26 | delay(15); 27 | } 28 | 29 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch10/Project28.pde: -------------------------------------------------------------------------------- 1 | // Project 28 2 | #include 3 | 4 | // steps value is 360 / degree angle of motor 5 | #define STEPS 200 6 | 7 | // create a stepper object on pins 4, 5, 6 and 7 8 | Stepper stepper(STEPS, 4, 5, 6, 7); 9 | 10 | void setup() 11 | { 12 | } 13 | 14 | void loop() 15 | { 16 | stepper.setSpeed(60); 17 | stepper.step(200); 18 | delay(100); 19 | stepper.setSpeed(20); 20 | stepper.step(-50); 21 | delay(100); 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch10/Project29.pde: -------------------------------------------------------------------------------- 1 | // Project 29 - Using a motor shield 2 | 3 | // Set the pins for speed and direction of each motor 4 | int speed1 = 3; 5 | int speed2 = 11; 6 | int direction1 = 12; 7 | int direction2 = 13; 8 | 9 | void stopMotor() { 10 | // turn both motors off 11 | analogWrite(speed1, 0); 12 | analogWrite(speed2, 0); 13 | } 14 | 15 | void setup() 16 | { 17 | // set all the pins to outputs 18 | pinMode(speed1, OUTPUT); 19 | pinMode(speed2, OUTPUT); 20 | pinMode(direction1, OUTPUT); 21 | pinMode(direction2, OUTPUT); 22 | } 23 | 24 | void loop() 25 | { 26 | // Both motors forwaard at 50% speed for 2 seconds 27 | digitalWrite(direction1, HIGH); 28 | digitalWrite(direction2, HIGH); 29 | analogWrite(speed1,128); 30 | analogWrite(speed2,128); 31 | delay(2000); 32 | 33 | stopMotor(); delay(1000); // stop 34 | 35 | // Left turn for 1 second 36 | digitalWrite(direction1, LOW); 37 | digitalWrite(direction2, HIGH); 38 | analogWrite(speed1, 128); 39 | analogWrite(speed2, 128); 40 | delay(1000); 41 | 42 | stopMotor(); delay(1000); // stop 43 | 44 | // Both motors forward at 50% speed for 2 seconds 45 | digitalWrite(direction1, HIGH); 46 | digitalWrite(direction2, HIGH); 47 | analogWrite(speed1,128); 48 | analogWrite(speed2,128); 49 | delay(2000); 50 | 51 | stopMotor(); delay(1000); // stop 52 | 53 | // rotate right at 25% speed 54 | digitalWrite(direction1, HIGH); 55 | digitalWrite(direction2, LOW); 56 | analogWrite(speed1, 64); 57 | analogWrite(speed2, 64); 58 | delay(2000); 59 | 60 | stopMotor(); delay(1000); // stop 61 | 62 | } 63 | 64 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch10/Project30.pde: -------------------------------------------------------------------------------- 1 | // Project 30 - Line Following Robot 2 | 3 | #define lights 9 4 | int LDR1, LDR2, LDR3; // sensor values 5 | 6 | // calibration offsets 7 | int leftOffset = 0, rightOffset = 0, centre = 0; 8 | // pins for motor speed and direction 9 | int speed1 = 3, speed2 = 11, direction1 = 12, direction2 = 13; 10 | // starting speed and rotation offset 11 | int startSpeed = 70, rotate = 30; 12 | // sensor threshold 13 | int threshhold = 5; 14 | // initial speeds of left and right motors 15 | int left = startSpeed, right = startSpeed; 16 | 17 | // Sensor calibration routine 18 | void calibrate() { 19 | 20 | for (int x=0; x<10; x++) { // run this 10 times to obtain average 21 | digitalWrite(lights, HIGH); // lights on 22 | delay(100); 23 | LDR1 = analogRead(0); // read the 3 sensors 24 | LDR2 = analogRead(1); 25 | LDR3 = analogRead(2); 26 | leftOffset = leftOffset + LDR1; // add value of left sensor to total 27 | centre = centre + LDR2; // add value of centre sensor to total 28 | rightOffset = rightOffset + LDR3; // add value of right sensor to total 29 | 30 | delay(100); 31 | digitalWrite(lights, LOW); // lights off 32 | delay(100); 33 | } 34 | // obtain average for each sensor 35 | leftOffset = leftOffset / 10; 36 | rightOffset = rightOffset / 10; 37 | centre = centre /10; 38 | // calculate offsets for left and right sensors 39 | leftOffset = centre - leftOffset; 40 | rightOffset = centre - rightOffset; 41 | } 42 | 43 | void setup() 44 | { 45 | // set the motor pins to outputs 46 | pinMode(lights, OUTPUT); // lights 47 | pinMode(speed1, OUTPUT); 48 | pinMode(speed2, OUTPUT); 49 | pinMode(direction1, OUTPUT); 50 | pinMode(direction2, OUTPUT); 51 | // calibrate the sensors 52 | calibrate(); 53 | delay(3000); 54 | 55 | digitalWrite(lights, HIGH); // lights on 56 | delay(100); 57 | 58 | // set motor direction to forward 59 | digitalWrite(direction1, HIGH); 60 | digitalWrite(direction2, HIGH); 61 | // set speed of both motors 62 | analogWrite(speed1,left); 63 | analogWrite(speed2,right); 64 | } 65 | 66 | void loop() { 67 | 68 | // make both motors same speed 69 | left = startSpeed; 70 | right = startSpeed; 71 | 72 | // read the sensors and add the offsets 73 | LDR1 = analogRead(0) + leftOffset; 74 | LDR2 = analogRead(1); 75 | LDR3 = analogRead(2) + rightOffset; 76 | 77 | // if LDR1 is greater than the centre sensor + threshold turn right 78 | if (LDR1 > (LDR2+threshhold)) { 79 | left = startSpeed + rotate; 80 | right = startSpeed - rotate; 81 | } 82 | 83 | // if LDR3 is greater than the centre sensor + threshold turn left 84 | if (LDR3 > (LDR2+threshhold)) { 85 | left = startSpeed - rotate; 86 | right = startSpeed + rotate; 87 | } 88 | // send the speed values to the motors 89 | analogWrite(speed1,left); 90 | analogWrite(speed2,right); 91 | } 92 | 93 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch11/Project31.pde: -------------------------------------------------------------------------------- 1 | /* 2 | SCP1000 Mega 3 | DRDY N/A 4 | CSB 53 via Logic Level Convertor 5 | MISO 50 (straight through) 6 | MOSI 51 via Logic Level Convertor 7 | SCK 52 via Logic Level Convertor 8 | 3.3v 3.3v 9 | GND GND 10 | TRIG GND 11 | PD GND 12 | */ 13 | 14 | // SPI PINS 15 | #define SLAVESELECT 53 16 | #define SPICLOCK 52 17 | #define DATAOUT 51 //MOSI 18 | #define DATAIN 50 //MISO 19 | #define UBLB(a,b) ( ( (a) << 8) | (b) ) 20 | #define UBLB19(a,b) ( ( (a) << 16 ) | (b) ) 21 | 22 | //Addresses 23 | #define PRESSURE 0x1F //Pressure 3 MSB 24 | #define PRESSURE_LSB 0x20 //Pressure 16 LSB 25 | #define TEMP 0x21 //16 bit temp 26 | 27 | char rev_in_byte; 28 | int temp_in; 29 | unsigned long pressure_lsb; 30 | unsigned long pressure_msb; 31 | unsigned long temp_pressure; 32 | unsigned long pressure; 33 | 34 | void setup() 35 | { 36 | byte clr; 37 | pinMode(DATAOUT, OUTPUT); 38 | pinMode(DATAIN, INPUT); 39 | pinMode(SPICLOCK, OUTPUT); 40 | pinMode(SLAVESELECT, OUTPUT); 41 | digitalWrite(SLAVESELECT, HIGH); //disable device 42 | 43 | SPCR = B01010011; // SPi Control Register 44 | //MPIE=0, SPE=1 (on), DORD=0 (MSB first), MSTR=1 (master), CPOL=0 (clock idle when 45 | low), CPHA=0 (samples MOSI on rising edge), SPR1=0 & SPR0=0 (500kHz) 46 | clr=SPSR; // SPi Status Register 47 | clr=SPDR; // SPi Data Register 48 | delay(10); 49 | Serial.begin(38400); 50 | delay(500); 51 | 52 | write_register(0x03,0x09); // High Speed Read Mode 53 | write_register(0x03,0x0A); // High Resolution Measurement Mode 54 | } 55 | 56 | void loop() 57 | { 58 | pressure_msb = read_register(PRESSURE); 59 | pressure_msb &= B00000111; 60 | pressure_lsb = read_register16(PRESSURE_LSB); 61 | pressure_lsb &= 0x0000FFFF; 62 | pressure = UBLB19(pressure_msb, pressure_lsb); 63 | pressure /= 4; 64 | Serial.print("Pressure (hPa): "); 65 | float hPa = float(pressure)/100; 66 | Serial.println(hPa); 67 | 68 | Serial.print("Pressure (Atm): "); 69 | float pAtm = float(pressure)/101325.0; 70 | Serial.println(pAtm, 3); 71 | 72 | temp_in = read_register16(TEMP); 73 | float tempC = float(temp_in)/20.0; 74 | Serial.print("Temp. C: "); 75 | Serial.println(tempC); 76 | float tempF = (tempC*1.8) + 32; 77 | Serial.print("Temp. F: "); 78 | Serial.println(tempF); 79 | Serial.println(); 80 | delay(1000); 81 | } 82 | 83 | char spi_transfer(char data) 84 | { 85 | SPDR = data; // Start transmission 86 | while (!(SPSR & (1< 15 | 16 | #include "fonts/allFonts.h" 17 | 18 | // SPI PINS 19 | #define SLAVESELECT 53 20 | #define SPICLOCK 52 21 | #define DATAOUT 51 //MOSI 22 | #define DATAIN 50 //MISO 23 | #define UBLB(a,b) ( ( (a) << 8) | (b) ) 24 | #define UBLB19(a,b) ( ( (a) << 16 ) | (b) ) 25 | 26 | //Addresses 27 | #define PRESSURE 0x1F //Pressure 3 MSB 28 | #define PRESSURE_LSB 0x20 //Pressure 16 LSB 29 | #define TEMP 0x21 //16 bit temp 30 | #define INTERVAL 900 // Time interval in seconds (approx.) 31 | 32 | int dots[124], dotCursor = 0, counter = 0;; 33 | char rev_in_byte; 34 | int temp_in; 35 | float hPa; 36 | unsigned long pressure_lsb; 37 | unsigned long pressure_msb; 38 | unsigned long temp_pressure; 39 | unsigned long pressure; 40 | 41 | void setup() 42 | { 43 | GLCD.Init(); // initialise the library 44 | GLCD.ClearScreen(); 45 | GLCD.SelectFont(System5x7, BLACK); // load the font 46 | 47 | byte clr; 48 | pinMode(DATAOUT, OUTPUT); 49 | pinMode(DATAIN, INPUT); 50 | pinMode(SPICLOCK,OUTPUT); 51 | pinMode(SLAVESELECT,OUTPUT); 52 | digitalWrite(SLAVESELECT,HIGH); //disable device 53 | 54 | SPCR = B01010011; // SPi Control Register 55 | //MPIE=0, SPE=1 (on), DORD=0 (MSB first), MSTR=1 (master), CPOL=0 (clock idle when low), 56 | CPHA=0 (samples MOSI on rising edge), SPR1=1 & SPR0=1 (250kHz) 57 | clr=SPSR;// SPi Status Register 58 | clr=SPDR; // SPi Data Register 59 | delay(10); 60 | 61 | write_register(0x03,0x09); // High Speed Read Mode 62 | write_register(0x03,0x0A); // High Resolution Measurement Mode 63 | 64 | GLCD.DrawRect(1,1,125,44); // Draw a rectangle 65 | for (int x=0; x<46; x+=11) { // Draw vertical scale 66 | GLCD.SetDot(0,1+x, BLACK); 67 | GLCD.SetDot(127,1+x, BLACK); 68 | } 69 | for (int x=0; x<128; x+=5) { // Draw horizontal scale 70 | GLCD.SetDot(1+x,0, BLACK); 71 | } 72 | 73 | for (int x; x<124; x++) {dots[x]=1023;} // clear the array 74 | getPressure(); 75 | drawPoints(dotCursor); 76 | } 77 | 78 | void loop() 79 | { 80 | getPressure(); 81 | 82 | GLCD.CursorToXY(0, 49); // print pressure 83 | GLCD.print("hPa:"); 84 | GLCD.CursorToXY(24,49); 85 | GLCD.print(hPa); 86 | 87 | temp_in = read_register16(TEMP); 88 | float tempC = float(temp_in)/20.0; 89 | float tempF = (tempC*1.8) + 32; 90 | 91 | GLCD.CursorToXY(0,57); // print temperature 92 | GLCD.print("Temp:"); 93 | GLCD.CursorToXY(28, 57); 94 | GLCD.print(tempC); // change to tempF for Fahrenheit 95 | 96 | delay(1000); 97 | 98 | GLCD.CursorToXY(84,49); // print trend 99 | GLCD.print("TREND:"); 100 | GLCD.CursorToXY(84,57); 101 | printTrend(); 102 | 103 | counter++; 104 | if (counter==INTERVAL) {drawPoints(dotCursor);} 105 | 106 | } 107 | 108 | void drawPoints(int position) { 109 | counter=0; 110 | dots[dotCursor] = int(hPa); 111 | GLCD.FillRect(2, 2, 123, 40, WHITE); // clear graph area 112 | for (int x=0; x<124; x++) { 113 | GLCD.SetDot(125-x,44-((dots[position]-980)), BLACK); 114 | position--; 115 | if (position<0) {position=123;} 116 | } 117 | dotCursor++; 118 | if (dotCursor>123) {dotCursor=0;} 119 | } 120 | 121 | void getPressure() { 122 | pressure_msb = read_register(PRESSURE); 123 | pressure_msb &= B00000111; 124 | pressure_lsb = read_register16(PRESSURE_LSB); 125 | pressure_lsb &= 0x0000FFFF; 126 | pressure = UBLB19(pressure_msb, pressure_lsb); 127 | pressure /= 4; 128 | hPa = float(pressure)/100; 129 | } 130 | 131 | void printTrend() { // calculate trend since last data point and print 132 | int dotCursor2=dotCursor-1; 133 | if (dotCursor2<0) {dotCursor2=123;} 134 | int val1=dots[dotCursor2]; 135 | int dotCursor3=dotCursor2-1; 136 | if (dotCursor3<0) {dotCursor3=123;} 137 | int val2=dots[dotCursor3]; 138 | if (val1>val2) {GLCD.print("RISING ");} 139 | if (val1==val2) {GLCD.print("STEADY ");} 140 | if (val1 0 && coordY < 1000 && coordY > 0) {touch = true;} 64 | 65 | return touch; 66 | } 67 | 68 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch12/Project34.pde: -------------------------------------------------------------------------------- 1 | // Project 34 2 | 3 | #include 4 | 5 | LiquidCrystal lcd(2, 3, 4, 5, 6, 7); // create an lcd object and assign the pins 6 | 7 | // Power connections 8 | #define Left 8 // Left (X1) to digital pin 8 9 | #define Bottom 9 // Bottom (Y2) to digital pin 9 10 | #define Right 10 // Right (X2) to digital pin 10 11 | #define Top 11 // Top (Y1) to digital pin 11 12 | // Analog connections 13 | #define topInput 0 // Top (Y1) to analog pin 0 14 | #define rightInput 1 // Right (X2) to analog pin 1 15 | 16 | int coordX = 0, coordY = 0; 17 | char buffer[16]; 18 | 19 | void setup() 20 | { 21 | lcd.begin(16, 2); // Set the display to 16 columns and 2 rows 22 | lcd.clear(); 23 | } 24 | 25 | void loop() 26 | { 27 | if (touch()) 28 | { 29 | if ((coordX>110 && coordX<300) && (coordY>170 && coordY<360)) {lcd.print("3");} 30 | if ((coordX>110 && coordX<300) && (coordY>410 && coordY<610)) {lcd.print("2");} 31 | if ((coordX>110 && coordX<300) && (coordY>640 && coordY<860)) {lcd.print("1");} 32 | if ((coordX>330 && coordX<470) && (coordY>170 && coordY<360)) {lcd.print("6");} 33 | if ((coordX>330 && coordX<470) && (coordY>410 && coordY<610)) {lcd.print("5");} 34 | if ((coordX>330 && coordX<470) && (coordY>640 && coordY<860)) {lcd.print("4");} 35 | if ((coordX>490 && coordX<710) && (coordY>170 && coordY<360)) {lcd.print("9");} 36 | if ((coordX>490 && coordX<710) && (coordY>410 && coordY<610)) {lcd.print("8");} 37 | if ((coordX>490 && coordX<710) && (coordY>640 && coordY<860)) {lcd.print("7");} 38 | if ((coordX>760 && coordX<940) && (coordY>170 && coordY<360)) {scrollLCD();} 39 | if ((coordX>760 && coordX<940) && (coordY>410 && coordY<610)) {lcd.print("0");} 40 | if ((coordX>760 && coordX<940) && (coordY>640 && coordY<860)) {lcd.clear();} 41 | delay(250); 42 | } 43 | } 44 | 45 | // return TRUE if touched, and set coordinates to touchX and touchY 46 | boolean touch() 47 | { 48 | boolean touch = false; 49 | 50 | // get horizontal co-ordinates 51 | pinMode(Left, OUTPUT); 52 | digitalWrite(Left, LOW); // Set Left to Gnd 53 | 54 | pinMode(Right, OUTPUT); // Set right to +5v 55 | digitalWrite(Right, HIGH); 56 | 57 | pinMode(Top, INPUT); // Top and Bottom to high impedence 58 | pinMode(Bottom, INPUT); 59 | 60 | delay(3); // short delay 61 | coordX = analogRead(topInput); 62 | 63 | // get vertical co-ordinates 64 | pinMode(Bottom, OUTPUT); // set Bottom to Gnd 65 | digitalWrite(Bottom, LOW); 66 | 67 | pinMode(Top, OUTPUT); // set Top to +5v 68 | digitalWrite(Top, HIGH); 69 | 70 | pinMode(Right, INPUT); // left and right to high impedence 71 | pinMode(Left, INPUT); 72 | 73 | delay(3); // short delay 74 | coordY = analogRead(rightInput); 75 | 76 | // if co-ordinates read are less than 1000 and greater than 0 then the screen has 77 | been touched 78 | if(coordX < 1000 && coordX > 0 && coordY < 1000 && coordY > 0) {touch = true;} 79 | 80 | return touch; 81 | } 82 | 83 | void scrollLCD() { 84 | for (int scrollNum=0; scrollNum<16; scrollNum++) { 85 | lcd.scrollDisplayLeft(); 86 | delay(100); 87 | } 88 | lcd.clear(); 89 | } 90 | 91 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch12/Project35.pde: -------------------------------------------------------------------------------- 1 | // Project 35 2 | 3 | // Power connections 4 | #define Left 8 // Left (X1) to digital pin 8 5 | #define Bottom 9 // Bottom (Y2) to digital pin 9 6 | #define Right 10 // Right (X2) to digital pin 10 7 | #define Top 11 // Top (Y1) to digital pin 11 8 | 9 | // Analog connections 10 | #define topInput 0 // Top (Y1) to analog pin 0 11 | #define rightInput 1 // Right (X2) to analog pin 1 12 | // RGB pins 13 | #define pinR 3 14 | #define pinG 5 15 | #define pinB 6 16 | 17 | int coordX = 0, coordY = 0; 18 | boolean ledState = true; 19 | int red = 100, green = 100, blue = 100; 20 | 21 | void setup() 22 | { 23 | pinMode(pinR, OUTPUT); 24 | pinMode(pinG, OUTPUT); 25 | pinMode(pinB, OUTPUT); 26 | } 27 | 28 | void loop() 29 | { 30 | if (touch()) { 31 | if ((coordX>0 && coordX<270) && (coordY>0 && coordY<460)) {ledState = 32 | true; delay(50);} 33 | if ((coordX>0 && coordX<270) && (coordY>510 && coordY< 880)) {ledState = 34 | false; delay(50);} 35 | if ((coordX>380 && coordX<930) && (coordY>0 && coordY<300)) {red= 36 | map(coordX, 380, 930, 0, 255);} 37 | if ((coordX>380 && coordX<930) && (coordY>350 && coordY<590)) 38 | {green=map(coordX, 380, 930, 0, 255);} 39 | if ((coordX>380 && coordX<930) && (coordY>640 && coordY<880)) 40 | {blue=map(coordX, 380, 930, 0, 255);} 41 | delay(10); 42 | } 43 | 44 | if (ledState) { 45 | analogWrite(pinR, red); 46 | analogWrite(pinG, green); 47 | analogWrite(pinB, blue); 48 | } 49 | else { 50 | analogWrite(pinR, 0); 51 | analogWrite(pinG, 0); 52 | analogWrite(pinB, 0); 53 | } 54 | } 55 | 56 | // return TRUE if touched, and set coordinates to touchX and touchY 57 | boolean touch() 58 | { 59 | boolean touch = false; 60 | 61 | // get horizontal co-ordinates 62 | pinMode(Left, OUTPUT); 63 | digitalWrite(Left, LOW); // Set Left to Gnd 64 | 65 | pinMode(Right, OUTPUT); // Set right to +5v 66 | digitalWrite(Right, HIGH); 67 | 68 | pinMode(Top, INPUT); // Top and Bottom to high impedence 69 | pinMode(Bottom, INPUT); 70 | 71 | delay(3); // short delay 72 | coordX = analogRead(topInput); 73 | 74 | // get vertical co-ordinates 75 | pinMode(Bottom, OUTPUT); // set Bottom to Gnd 76 | digitalWrite(Bottom, LOW); 77 | 78 | pinMode(Top, OUTPUT); // set Top to +5v 79 | digitalWrite(Top, HIGH); 80 | 81 | pinMode(Right, INPUT); // left and right to high impedence 82 | pinMode(Left, INPUT); 83 | 84 | delay(3); // short delay 85 | coordY = analogRead(rightInput); 86 | 87 | // if co-ordinates read are less than 1000 and greater than 0 then the screen has 88 | been touched 89 | if(coordX < 1000 && coordX > 0 && coordY < 1000 && coordY > 0) {touch = true;} 90 | 91 | return touch; 92 | } 93 | 94 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch13/Project36.pde: -------------------------------------------------------------------------------- 1 | // Project 36 2 | 3 | #define sensorPin 0 4 | 5 | float Celsius, Fahrenheit, Kelvin; 6 | int sensorValue; 7 | 8 | void setup() { 9 | Serial.begin(9600); 10 | Serial.println("Initialising....."); 11 | } 12 | 13 | void loop() { 14 | 15 | GetTemp(); 16 | Serial.print("Celsius: "); 17 | Serial.println(Celsius); 18 | Serial.print("Fahrenheit: "); 19 | Serial.println(Fahrenheit); 20 | Serial.println(); 21 | 22 | delay(2000); 23 | } 24 | 25 | void GetTemp() 26 | { 27 | sensorValue = analogRead(sensorPin); // read the sensor 28 | Kelvin = (((float(sensorValue) / 1023) * 5) * 100); // convert to Kelvin 29 | Celsius = Kelvin - 273.15; // convert to Celsius 30 | Fahrenheit = (Celsius * 1.8) +32; // convert to Fahrenheit 31 | } 32 | 33 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch13/Project37Part1.pde: -------------------------------------------------------------------------------- 1 | // Project 37 - Part 1 2 | 3 | #include 4 | #include 5 | 6 | // Data line goes to digital pin 3 7 | #define ONE_WIRE_BUS 3 8 | 9 | // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas 10 | temperature ICs) 11 | OneWire oneWire(ONE_WIRE_BUS); 12 | 13 | // Pass our oneWire reference to Dallas Temperature. 14 | DallasTemperature sensors(&oneWire); 15 | 16 | // arrays to hold device addresses 17 | DeviceAddress insideThermometer, outsideThermometer; 18 | 19 | void setup() 20 | { 21 | // start serial port 22 | Serial.begin(9600); 23 | 24 | // Start up the library 25 | sensors.begin(); 26 | 27 | // locate devices on the bus 28 | Serial.print("Locating devices..."); 29 | Serial.print("Found "); 30 | Serial.print(sensors.getDeviceCount(), DEC); 31 | Serial.println(" devices."); 32 | 33 | if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address 34 | for Device 0"); 35 | if (!sensors.getAddress(outsideThermometer, 1)) Serial.println("Unable to find address 36 | for Device 1"); 37 | // print the addresses of both devices 38 | Serial.print("Device 0 Address: "); 39 | printAddress(insideThermometer); 40 | Serial.println(); 41 | 42 | Serial.print("Device 1 Address: "); 43 | printAddress(outsideThermometer); 44 | Serial.println(); 45 | Serial.println(); 46 | } 47 | 48 | // function to print a device address 49 | void printAddress(DeviceAddress deviceAddress) 50 | { 51 | for (int i = 0; i < 8; i++) 52 | { 53 | // zero pad the address if necessary 54 | if (deviceAddress[i] < 16) Serial.print("0"); 55 | Serial.print(deviceAddress[i], HEX); 56 | } 57 | } 58 | 59 | // function to print the temperature for a device 60 | void printTemperature(DeviceAddress deviceAddress) 61 | { 62 | float tempC = sensors.getTempC(deviceAddress); 63 | Serial.print("Temp C: "); 64 | Serial.print(tempC); 65 | Serial.print(" Temp F: "); 66 | Serial.print(DallasTemperature::toFahrenheit(tempC)); 67 | } 68 | 69 | // main function to print information about a device 70 | void printData(DeviceAddress deviceAddress) 71 | { 72 | Serial.print("Device Address: "); 73 | printAddress(deviceAddress); 74 | Serial.print(" "); 75 | printTemperature(deviceAddress); 76 | Serial.println(); 77 | } 78 | 79 | void loop() 80 | { 81 | // call sensors.requestTemperatures() to issue a global temperature 82 | // request to all devices on the bus 83 | Serial.print("Requesting temperatures..."); 84 | sensors.requestTemperatures(); 85 | Serial.println("DONE"); 86 | 87 | // print the device information 88 | printData(insideThermometer); 89 | printData(outsideThermometer); 90 | Serial.println(); 91 | delay(1000); 92 | } 93 | 94 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch13/Project37Part2.pde: -------------------------------------------------------------------------------- 1 | // Project 37 - Part 2 2 | 3 | #include 4 | #include 5 | 6 | // Data wire is plugged into pin 3 on the Arduino 7 | #define ONE_WIRE_BUS 3 8 | #define TEMPERATURE_PRECISION 12 9 | 10 | // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas 11 | temperature ICs) 12 | OneWire oneWire(ONE_WIRE_BUS); 13 | 14 | // Pass our oneWire reference to Dallas Temperature. 15 | DallasTemperature sensors(&oneWire); 16 | // arrays to hold device addresses – replace with your sensors addresses 17 | DeviceAddress insideThermometer = { 0x28, 0xCA, 0x90, 0xC2, 0x2, 0x00, 0x00, 0x88 }; 18 | DeviceAddress outsideThermometer = { 0x28, 0x3B, 0x40, 0xC2, 0x02, 0x00, 0x00, 0x93 }; 19 | 20 | void setup() 21 | { 22 | // start serial port 23 | Serial.begin(9600); 24 | 25 | // Start up the library 26 | sensors.begin(); 27 | 28 | Serial.println("Initialising..."); 29 | Serial.println(); 30 | 31 | // set the resolution 32 | sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION); 33 | sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION); 34 | } 35 | 36 | // function to print the temperature for a device 37 | void printTemperature(DeviceAddress deviceAddress) 38 | { 39 | float tempC = sensors.getTempC(deviceAddress); 40 | Serial.print(" Temp C: "); 41 | Serial.print(tempC); 42 | Serial.print(" Temp F: "); 43 | Serial.println(DallasTemperature::toFahrenheit(tempC)); 44 | } 45 | 46 | void loop() 47 | { 48 | // print the temperatures 49 | Serial.print("Inside Temp:"); 50 | printTemperature(insideThermometer); 51 | Serial.print("Outside Temp:"); 52 | printTemperature(outsideThermometer); 53 | Serial.println(); 54 | delay(3000); 55 | } 56 | 57 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch14/Project38.pde: -------------------------------------------------------------------------------- 1 | // Project 38 2 | #define sensorPin 9 3 | 4 | long pwmRange, inch, cm; 5 | 6 | void setup() { 7 | // Start serial communications 8 | Serial.begin(115200); 9 | pinMode(sensorPin, INPUT); 10 | } 11 | 12 | void loop() { 13 | pwmRange = pulseIn(sensorPin, HIGH); 14 | 15 | // 147uS per inch according to datasheet 16 | inch = pwmRange / 147; 17 | // convert inch to cm 18 | cm = inch * 2.54; 19 | 20 | Serial.print(inch); 21 | Serial.print(" inches "); 22 | Serial.print(cm); 23 | Serial.println(" cm"); 24 | } 25 | 26 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch14/Project39.pde: -------------------------------------------------------------------------------- 1 | // Project 39 2 | 3 | #include "LedControl.h" 4 | 5 | #define sensorPin 9 6 | #define switchPin 7 7 | #define DataIn 2 8 | #define CLK 4 9 | #define LOAD 3 10 | #define NumChips 1 11 | #define samples 5.0 12 | float pwmRange, averageReading, inch, cm; 13 | LedControl lc=LedControl(DataIn,CLK,LOAD,NumChips); 14 | 15 | void setup() { 16 | // Wakeup the MAX7219 17 | lc.shutdown(0,false); 18 | // Set it to medium brightness 19 | lc.setIntensity(0,8); 20 | // clear the display 21 | lc.clearDisplay(0); 22 | pinMode(sensorPin, INPUT); 23 | pinMode(switchPin, INPUT); 24 | } 25 | 26 | void loop() { 27 | averageReading = 0; 28 | for (int i = 0; i 5 | #include 6 | 7 | Sd2Card card; 8 | SdVolume volume; 9 | SdFile root; 10 | SdFile file; 11 | 12 | // store error strings in flash to save RAM 13 | #define error(s) error_P(PSTR(s)) 14 | 15 | void error_P(const char* str) { 16 | PgmPrint("error: "); 17 | SerialPrintln_P(str); 18 | if (card.errorCode()) { 19 | PgmPrint("SD error: "); 20 | Serial.print(card.errorCode(), HEX); 21 | Serial.print(','); 22 | Serial.println(card.errorData(), HEX); 23 | } 24 | while(1); 25 | } 26 | 27 | // Write a Carriage Return and Line Feed to the file 28 | void writeCRLF(SdFile& f) { 29 | f.write((uint8_t*)"\r\n", 2); 30 | } 31 | 32 | // Write an unsigned number to file 33 | void writeNumber(SdFile& f, uint32_t n) { 34 | uint8_t buf[10]; 35 | uint8_t i = 0; 36 | do { 37 | i++; 38 | buf[sizeof(buf) - i] = n%10 + '0'; 39 | n /= 10; 40 | } while (n); 41 | f.write(&buf[sizeof(buf) - i], i); 42 | } 43 | 44 | // Write a string to file 45 | void writeString(SdFile& f, char *str) { 46 | uint8_t n; 47 | for (n = 0; str[n]; n++); 48 | f.write((uint8_t *)str, n); 49 | } 50 | 51 | void setup() { 52 | Serial.begin(9600); 53 | Serial.println(); 54 | Serial.println("Type any character to start"); 55 | while (!Serial.available()); 56 | 57 | // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with breadboards. 58 | // Use SPI_FULL_SPEED for better performance if your card an take it. 59 | if (!card.init(SPI_HALF_SPEED)) error("card.init failed"); 60 | 61 | // initialize a FAT volume 62 | if (!volume.init(&card)) error("volume.init failed"); 63 | 64 | // open the root directory 65 | if (!root.openRoot(&volume)) error("openRoot failed"); 66 | 67 | // create a new file 68 | char name[] = "TESTFILE.TXT"; 69 | 70 | file.open(&root, name, O_CREAT | O_EXCL | O_WRITE); 71 | // Put todays date and time here 72 | file.timestamp(2, 2010, 12, 25, 12, 34, 56); 73 | 74 | // write 10 lines to the file 75 | for (uint8_t i = 0; i < 10; i++) { 76 | writeString(file, "Line: "); 77 | writeNumber(file, i); 78 | writeString(file, " Write test."); 79 | writeCRLF(file); 80 | } 81 | // close file and force write of all data to the SD card 82 | file.close(); 83 | Serial.println("File Created"); 84 | 85 | // open a file 86 | if (file.open(&root, name, O_READ)) { 87 | Serial.println(name); 88 | } 89 | else{ 90 | error("file.open failed"); 91 | } 92 | Serial.println(); 93 | 94 | int16_t character; 95 | while ((character = file.read()) > 0) Serial.print((char)character); 96 | 97 | Serial.println("\nDone"); 98 | } 99 | 100 | void loop() { } 101 | 102 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch15/Project43.pde: -------------------------------------------------------------------------------- 1 | // Project 43 2 | // Based on the SD Fat examples by Bill Greiman from sdfatlib 3 | // DS1307 library by Matt Joyce with enhancements by D. Sjunnesson 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include // written by mattt on the Arduino forum and modified by D. Sjunnesson 12 | 13 | // store error strings in flash to save RAM 14 | #define error(s) error_P(PSTR(s)) 15 | // Data wire is plugged into pin 3 on the Arduino 16 | #define ONE_WIRE_BUS 3 17 | #define TEMPERATURE_PRECISION 12 18 | 19 | Sd2Card card; 20 | SdVolume volume; 21 | SdFile root; 22 | SdFile file; 23 | 24 | // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas 25 | temperature ICs) 26 | OneWire oneWire(ONE_WIRE_BUS); 27 | // Pass our oneWire reference to Dallas Temperature. 28 | DallasTemperature sensors(&oneWire); 29 | 30 | // arrays to hold device addresses 31 | DeviceAddress insideThermometer = { 0x10, 0x20, 0x2C, 0xA9, 0x01, 0x08, 0x00, 0x73 }; 32 | DeviceAddress outsideThermometer = { 0x10, 0x22, 0x5B, 0xA9, 0x01, 0x08, 0x00, 0x21 }; 33 | 34 | float tempC, tempF; 35 | int hour, minute, seconds, day, month, year; 36 | 37 | // create a new file name 38 | char name[] = "TEMPLOG.TXT"; 39 | void error_P(const char* str) { 40 | PgmPrint("error: "); 41 | SerialPrintln_P(str); 42 | if (card.errorCode()) { 43 | PgmPrint("SD error: "); 44 | Serial.print(card.errorCode(), HEX); 45 | Serial.print(','); 46 | Serial.println(card.errorData(), HEX); 47 | } 48 | while(1); 49 | } 50 | 51 | void writeCRLF(SdFile& f) { 52 | f.write((uint8_t*)"\r\n", 2); 53 | } 54 | 55 | // Write an unsigned number to file 56 | void writeNumber(SdFile& f, uint32_t n) { 57 | uint8_t buf[10]; 58 | uint8_t i = 0; 59 | do { 60 | i++; 61 | buf[sizeof(buf) - i] = n%10 + '0'; 62 | n /= 10; 63 | } while (n); 64 | f.write(&buf[sizeof(buf) - i], i); 65 | } 66 | 67 | // Write a string to file 68 | void writeString(SdFile& f, char *str) { 69 | uint8_t n; 70 | for (n = 0; str[n]; n++); 71 | f.write((uint8_t *)str, n); 72 | } 73 | 74 | void getTemperature(DeviceAddress deviceAddress) 75 | { 76 | sensors.requestTemperatures(); 77 | tempC = sensors.getTempC(deviceAddress); 78 | tempF = DallasTemperature::toFahrenheit(tempC); 79 | } 80 | 81 | void getTimeDate() { 82 | hour = RTC.get(DS1307_HR,true); //read the hour and also update all the values by 83 | pushing in true 84 | minute = RTC.get(DS1307_MIN,false);//read minutes without update (false) 85 | seconds = RTC.get(DS1307_SEC,false);//read seconds 86 | day = RTC.get(DS1307_DATE,false);//read date 87 | month = RTC.get(DS1307_MTH,false);//read month 88 | year = RTC.get(DS1307_YR,false); //read year 89 | } 90 | 91 | void setup() { 92 | Serial.begin(9600); 93 | Serial.println("Type any character to start"); 94 | while (!Serial.available()); 95 | Serial.println(); 96 | 97 | // Start up the sensors library 98 | sensors.begin(); 99 | Serial.println("Initialising Sensors."); 100 | 101 | // set the resolution 102 | sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION); 103 | sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION); 104 | delay(100); 105 | 106 | // Set the time on the RTC. 107 | // Comment out this section if you have already set the time and have a battery backup 108 | RTC.stop(); 109 | RTC.set(DS1307_SEC,0); //set the seconds 110 | RTC.set(DS1307_MIN,15); //set the minutes 111 | RTC.set(DS1307_HR,14); //set the hours 112 | RTC.set(DS1307_DOW,7); //set the day of the week 113 | RTC.set(DS1307_DATE,3); //set the date 114 | RTC.set(DS1307_MTH,10); //set the month 115 | RTC.set(DS1307_YR,10); //set the year 116 | RTC.start(); 117 | 118 | Serial.println("Initialising SD Card..."); 119 | 120 | // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with breadboards. 121 | // Use SPI_FULL_SPEED for better performance if your card an take it. 122 | if (!card.init(SPI_HALF_SPEED)) error("card.init failed"); 123 | 124 | // initialize a FAT volume 125 | if (!volume.init(&card)) error("volume.init failed"); 126 | 127 | // open the root directory 128 | if (!root.openRoot(&volume)) error("openRoot failed"); 129 | Serial.println("SD Card initialised successfully."); 130 | Serial.println(); 131 | } 132 | void loop() { 133 | 134 | Serial.println("File Opened."); 135 | file.open(&root, name, O_CREAT | O_APPEND | O_WRITE); 136 | getTimeDate(); 137 | file.timestamp(7, year, month, day, hour, minute, seconds); 138 | 139 | getTemperature(insideThermometer); 140 | Serial.print("Inside: "); 141 | Serial.print(tempC); 142 | Serial.print(" C "); 143 | Serial.print(tempF); 144 | Serial.println(" F"); 145 | writeNumber(file, year); 146 | writeString(file, "/"); 147 | writeNumber(file, month); 148 | writeString(file, "/"); 149 | writeNumber(file, day); 150 | writeString(file, " "); 151 | writeNumber(file, hour); 152 | writeString(file, ":"); 153 | writeNumber(file, minute); 154 | writeString(file, ":"); 155 | writeNumber(file, seconds); 156 | writeCRLF(file); 157 | writeString(file, "Internal Sensor: "); 158 | writeNumber(file, tempC); 159 | writeString(file, " C "); 160 | writeNumber(file, tempF); 161 | writeString(file, " F"); 162 | writeCRLF(file); 163 | 164 | getTemperature(outsideThermometer); 165 | Serial.print("Outside: "); 166 | Serial.print(tempC); 167 | Serial.print(" C "); 168 | Serial.print(tempF); 169 | Serial.println(" F"); 170 | writeString(file, "External Sensor: "); 171 | writeNumber(file, tempC); 172 | writeString(file, " C "); 173 | writeNumber(file, tempF); 174 | writeString(file, " F"); 175 | writeCRLF(file); 176 | writeCRLF(file); 177 | Serial.println("Data written."); 178 | // close file and force write of all data to the SD card 179 | file.close(); 180 | Serial.println("File Closed."); 181 | Serial.println(); 182 | delay(10000); 183 | } 184 | 185 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch16/Project44.pde: -------------------------------------------------------------------------------- 1 | // Project 44 2 | 3 | char val = 0; // value read for serial port 4 | 5 | void setup() { 6 | Serial.begin(9600); 7 | } 8 | 9 | void loop () { 10 | 11 | if(Serial.available() > 0) { 12 | val = Serial.read(); // read from the serial port 13 | Serial.print(val, BYTE); // and print it to the monitor 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch16/Project45.pde: -------------------------------------------------------------------------------- 1 | // Project 45 2 | 3 | #define lockPin 7 4 | #define speakerPin 9 5 | #define tx 3 6 | #define rx 2 7 | #define unlockLength 2000 8 | 9 | #include 10 | 11 | SoftwareSerial rfidReader = SoftwareSerial(rx, tx); 12 | 13 | int users = 3; 14 | 15 | char* cards[] = { // valid cards 16 | "3D00768B53", 17 | "3D00251C27", 18 | "3D0029E6BF", 19 | }; 20 | 21 | char* names[] = { // cardholder names 22 | "Tom Smith", 23 | "Dick Jones", 24 | "Harry Roberts" 25 | }; 26 | 27 | void setup() { 28 | pinMode (lockPin, OUTPUT); 29 | pinMode (speakerPin, OUTPUT); 30 | digitalWrite(lockPin, LOW); 31 | Serial.begin(9600); 32 | rfidReader.begin(9600); 33 | } 34 | 35 | void loop() { 36 | char cardNum[10]; // array to hold card number 37 | byte cardBytes[6]; // byte version of card number + checksum 38 | int index=0; // current digit 39 | byte byteIn=0; // byte read from RFID 40 | byte lastByte=0; // the last byte read 41 | byte checksum = 0; // checksum result stored here 42 | 43 | if (rfidReader.read()==2) { // read the RFID reader 44 | while(index<12) { // 12 digits in unique serial number 45 | byteIn = rfidReader.read(); // store value in byteIn 46 | if ((byteIn==1) || (byteIn==2) || (byteIn==10) || (byteIn==13)) {return;} 47 | // if STX, ETX, CR or LF break 48 | if (index<10) {cardNum[index]=byteIn;} // store first 10 HEX digits only 49 | (last 2 are checksum) 50 | // convert ascii hex to integer hex value 51 | if ((byteIn>='0') && (byteIn<='9')) { 52 | byteIn -= '0'; 53 | } 54 | else if ((byteIn>='A') && (byteIn<='F')) { 55 | byteIn = (byteIn+10)-'A'; 56 | } 57 | if ((index & 1) == 1) { // if odd number merge 2 4 bit digits into 8 bit byte 58 | cardBytes[index/2]= (byteIn | (lastByte<<4)); // move the last digit 4 bits 59 | left and add new digit 60 | if (index<10) {checksum ^= cardBytes[index/2];} // tot up the checksum value 61 | } 62 | lastByte=byteIn; // store the last byte read 63 | index++; // increment the index 64 | if (index==12) {cardNum[10] = '\0';} // if we have reached the end of all digits 65 | add a null terminator 66 | } 67 | 68 | Serial.println(cardNum); // print the card number 69 | int cardIndex =checkCard(cardNum); // check if card is valid and return index number 70 | if(cardIndex>=0 && (cardBytes[5]==checksum)) { // if card number and checksum are valid 71 | Serial.println("Card Validated"); 72 | Serial.print("User: "); 73 | Serial.println(names[cardIndex]); // print the relevant name 74 | unlock(); // unlock the door 75 | Serial.println(); 76 | } 77 | else { 78 | Serial.println("Card INVALID"); 79 | tone(speakerPin, 250, 250); 80 | delay(250); 81 | tone(speakerPin, 150, 250); 82 | Serial.println(); 83 | } 84 | } 85 | } 86 | 87 | int checkCard(char cardNum[10]) { 88 | for (int x=0; x<=users; x++) { // check all valid cards 89 | if(strcmp(cardNum, cards[x])==0) { // compare with last read card number 90 | return (x); // return index of card number 91 | } 92 | } 93 | return (-1); // negative value indicates no match 94 | } 95 | 96 | void unlock() { 97 | tone(speakerPin, 1000, 500); 98 | digitalWrite(lockPin, HIGH); 99 | delay(unlockLength); 100 | digitalWrite(lockPin, LOW); 101 | } 102 | 103 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch17/Project46.pde: -------------------------------------------------------------------------------- 1 | // Project 46 – Based on the Arduino Webserver example by David A. Mellis and Tom Igoe 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | // Data wire is plugged into pin 3 on the Arduino 9 | #define ONE_WIRE_BUS 3 10 | #define TEMPERATURE_PRECISION 12 11 | 12 | float tempC, tempF; 13 | // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) 14 | OneWire oneWire(ONE_WIRE_BUS); 15 | // Pass our oneWire reference to Dallas Temperature. 16 | DallasTemperature sensors(&oneWire); 17 | 18 | // arrays to hold device addresses 19 | DeviceAddress insideThermometer = { 0x10, 0x7A, 0x3B, 0xA9, 0x01, 0x08, 0x00, 0xBF }; 20 | DeviceAddress outsideThermometer = { 0x10, 0xCD, 0x39, 0xA9, 0x01, 0x08, 0x00, 0xBE}; 21 | 22 | byte mac[] = { 0x48, 0xC2, 0xA1, 0xF3, 0x8D, 0xB7 }; 23 | byte ip[] = { 192,168,0, 104 }; 24 | 25 | // Start the server on port 80 26 | Server server(80); 27 | 28 | void setup() 29 | { 30 | // Begin ethernet and server 31 | Ethernet.begin(mac, ip); 32 | server.begin(); 33 | // Start up the sensors library 34 | sensors.begin(); 35 | // set the resolution 36 | sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION); 37 | sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION); 38 | } 39 | 40 | // function to get the temperature for a device 41 | void getTemperature(DeviceAddress deviceAddress) 42 | { 43 | tempC = sensors.getTempC(deviceAddress); 44 | tempF = DallasTemperature::toFahrenheit(tempC); 45 | } 46 | void loop() 47 | { 48 | sensors.requestTemperatures(); 49 | 50 | // listen for incoming clients 51 | Client client = server.available(); 52 | if (client) { 53 | // an http request ends with a blank line 54 | boolean BlankLine = true; 55 | while (client.connected()) { 56 | if (client.available()) { 57 | char c = client.read(); 58 | // If line is blank and end of line is newline character '\n' = end of HTTP request 59 | if (c == '\n' && BlankLine) { 60 | getTemperature(insideThermometer); 61 | client.println("HTTP/1.1 200 OK"); // Standard HTTP response 62 | client.println("Content-Type: text/html\n"); 63 | client.println("\n"); 64 | client.println("Arduino Web Server"); 65 | client.println("\n"); 66 | client.println("

Arduino Web Server

"); 67 | client.println("

Internal Temperature

"); 68 | client.println("Temp C:"); 69 | client.println(tempC); 70 | client.println("
"); 71 | client.println("Temp F:"); 72 | client.println(tempF); 73 | client.println("
"); 74 | getTemperature(outsideThermometer); 75 | client.println("

External Temperature

"); 76 | client.println("Temp C:"); 77 | client.println(tempC); 78 | client.println("
"); 79 | client.println("Temp F:"); 80 | client.println(tempF); 81 | client.println("
"); 82 | 83 | break; 84 | } 85 | if (c == '\n') { 86 | // Starting a new line 87 | BlankLine = true; 88 | } 89 | else if (c != '\r') { 90 | // Current line has a character in it 91 | BlankLine = false; 92 | } 93 | } 94 | } 95 | // Allow time for the browser to receive data 96 | delay(10); 97 | // Close connection 98 | client.stop(); 99 | } 100 | } 101 | 102 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch17/Project47.pde: -------------------------------------------------------------------------------- 1 | // Project 47 - Based on the Pachube Arduino examples 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define SHARE_FEED_ID 10722 // this is your Pachube feed ID 8 | #define UPDATE_INTERVAL 10000 // if the connection is good wait 10 seconds before updating again - should not be less than 5 9 | #define RESET_INTERVAL 10000 // if connection fails/resets wait 10 seconds before trying again - should not be less than 5 10 | #define PACHUBE_API_KEY "066ed6ea1d1073600e5b44b35e8a399697d66532c3e736c77dc11123dfbfe12f" // fill in your API key 11 | 12 | // Data wire is plugged into pin 3 on the Arduino 13 | #define ONE_WIRE_BUS 3 14 | #define TEMPERATURE_PRECISION 12 15 | 16 | // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) 17 | OneWire oneWire(ONE_WIRE_BUS); 18 | 19 | // Pass our oneWire reference to Dallas Temperature. 20 | DallasTemperature sensors(&oneWire); 21 | 22 | // arrays to hold device addresses 23 | DeviceAddress insideThermometer = { 0x10, 0x7A, 0x3B, 0xA9, 0x01, 0x08, 0x00, 0xBF }; 24 | DeviceAddress outsideThermometer = { 0x10, 0xCD, 0x39, 0xA9, 0x01, 0x08, 0x00, 0xBE}; 25 | 26 | byte mac[] = { 0xCC, 0xAC, 0xBE, 0xEF, 0xFE, 0x91 }; // make sure this is unique on your network 27 | byte ip[] = { 192, 168, 0, 104 }; // no DHCP so we set our own IP address 28 | byte remoteServer[] = { 173, 203, 98, 29 }; // pachube.com 29 | 30 | Client localClient(remoteServer, 80); 31 | 32 | unsigned int interval; 33 | char buff[64]; 34 | int pointer = 0; 35 | char pachube_data[70]; 36 | char *found; 37 | boolean ready_to_update = true; 38 | boolean reading_pachube = false; 39 | boolean request_pause = false; 40 | boolean found_content = false; 41 | unsigned long last_connect; 42 | int content_length; 43 | int itempC, itempF, etempC, etempF; 44 | 45 | void setupEthernet(){ 46 | resetEthernetShield(); 47 | delay(500); 48 | interval = UPDATE_INTERVAL; 49 | Serial.println("setup complete"); 50 | } 51 | 52 | void clean_buffer() { 53 | pointer = 0; 54 | memset(buff,0,sizeof(buff)); 55 | } 56 | 57 | void resetEthernetShield(){ 58 | Serial.println("reset ethernet"); 59 | Ethernet.begin(mac, ip); 60 | } 61 | 62 | void pachube_out(){ 63 | getTemperatures(); 64 | if (millis() < last_connect) last_connect = millis(); 65 | 66 | if (request_pause){ 67 | if ((millis() - last_connect) > interval){ 68 | ready_to_update = true; 69 | reading_pachube = false; 70 | request_pause = false; 71 | } 72 | } 73 | 74 | if (ready_to_update){ 75 | Serial.println("Connecting..."); 76 | if (localClient.connect()) { 77 | 78 | sprintf(pachube_data,"%d,%d,%d,%d",itempC, itempF, etempC, etempF); 79 | Serial.print("Sending: "); 80 | Serial.println(pachube_data); 81 | content_length = strlen(pachube_data); 82 | 83 | Serial.println("Updating."); 84 | localClient.print("PUT /v1/feeds/"); 85 | localClient.print(SHARE_FEED_ID); 86 | localClient.print(".csv HTTP/1.1\nHost: api.pachube.com\nX-PachubeApiKey: "); 87 | localClient.print(PACHUBE_API_KEY); 88 | localClient.print("\nUser-Agent: Beginning Arduino – Project 47"); 89 | localClient.print("\nContent-Type: text/csv\nContent-Length: "); 90 | localClient.print(content_length); 91 | localClient.print("\nConnection: close\n\n"); 92 | localClient.print(pachube_data); 93 | localClient.print("\n"); 94 | 95 | ready_to_update = false; 96 | reading_pachube = true; 97 | request_pause = false; 98 | interval = UPDATE_INTERVAL; 99 | 100 | } 101 | else { 102 | Serial.print("connection failed!"); 103 | ready_to_update = false; 104 | reading_pachube = false; 105 | request_pause = true; 106 | last_connect = millis(); 107 | interval = RESET_INTERVAL; 108 | setupEthernet(); 109 | } 110 | } 111 | 112 | while (reading_pachube){ 113 | while (localClient.available()) { 114 | checkForResponse(); 115 | } 116 | if (!localClient.connected()) { 117 | disconnect_pachube(); 118 | } 119 | } 120 | } 121 | 122 | void disconnect_pachube(){ 123 | Serial.println("disconnecting.\n===============\n\n"); 124 | localClient.stop(); 125 | ready_to_update = false; 126 | reading_pachube = false; 127 | request_pause = true; 128 | last_connect = millis(); 129 | resetEthernetShield(); 130 | } 131 | 132 | void checkForResponse(){ 133 | char c = localClient.read(); 134 | buff[pointer] = c; 135 | if (pointer < 64) pointer++; 136 | if (c == '\n') { 137 | found = strstr(buff, "200 OK"); 138 | buff[pointer]=0; 139 | clean_buffer(); 140 | } 141 | } 142 | 143 | // function to get the temperature for a device 144 | void getTemperatures() 145 | { 146 | sensors.requestTemperatures(); 147 | itempC = sensors.getTempC(insideThermometer); 148 | itempF = DallasTemperature::toFahrenheit(itempC); 149 | etempC = sensors.getTempC(outsideThermometer); 150 | etempF = DallasTemperature::toFahrenheit(etempC); 151 | } 152 | 153 | void setup() 154 | { 155 | Serial.begin(57600); 156 | setupEthernet(); 157 | // Start up the sensors library 158 | sensors.begin(); 159 | // set the resolution 160 | sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION); 161 | sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION); 162 | } 163 | 164 | void loop() 165 | { 166 | pachube_out(); 167 | } 168 | 169 | 170 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch17/Project48.pde: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #define time 1000 6 | #define emailInterval 60 7 | #define HighThreshold 40 // Highest temperature allowed 8 | #define LowThreshold 10 // Lowest temperature 9 | 10 | // Data wire is plugged into pin 3 on the Arduino 11 | #define ONE_WIRE_BUS 3 12 | #define TEMPERATURE_PRECISION 12 13 | 14 | float tempC, tempF; 15 | char message1[35], message2[35]; 16 | char subject[] = "ARDUINO: TEMPERATURE ALERT!!\0"; 17 | unsigned long lastMessage; 18 | 19 | // Setup a oneWire instance to communicate with any OneWire devices 20 | OneWire oneWire(ONE_WIRE_BUS); 21 | 22 | // Pass our oneWire reference to Dallas Temperature. 23 | DallasTemperature sensors(&oneWire); 24 | 25 | // arrays to hold device addresses 26 | DeviceAddress insideThermometer = { 0x10, 0x7A, 0x3B, 0xA9, 0x01, 0x08, 0x00, 0xBF }; 27 | 28 | byte mac[] = { 0x64, 0xB9, 0xE8, 0xC3, 0xC7, 0xE2 }; 29 | byte ip[] = { 192,168,0, 105 }; 30 | byte server[] = { 62, 234, 219, 95 }; // Mail server address. Change this to your own mail servers IP. 31 | 32 | Client client(server, 25); 33 | 34 | void sendEmail(char subject[], char message1[], char message2[], float temp) { 35 | Serial.println("connecting..."); 36 | 37 | if (client.connect()) { 38 | Serial.println("connected"); 39 | client.println("EHLO MYSERVER"); delay(time); // log in 40 | client.println("AUTH LOGIN"); delay(time); // authorise 41 | // enter your username here 42 | client.println("caFzLmNvbQaWNZXGluZWVsZWN0cm9uNAZW2FsydGhzd3"); delay(time); 43 | // and password here 44 | client.println("ZnZJh4TYZ2ds"); delay(time); 45 | client.println("MAIL FROM:"); delay(time); 46 | client.println("RCPT TO:"); delay(time); 47 | client.println("DATA"); delay(time); 48 | client.println("From: "); delay(time); 49 | client.println("To: "); delay(time); 50 | client.print("SUBJECT: "); 51 | client.println(subject); delay(time); 52 | client.println(); delay(time); 53 | client.println(message1); delay(time); 54 | client.println(message2); delay(time); 55 | client.print("Temperature: "); 56 | client.println(temp); delay(time); 57 | client.println("."); delay(time); 58 | client.println("QUIT"); delay(time); 59 | Serial.println("Email sent."); 60 | lastMessage=millis(); 61 | } else { 62 | Serial.println("connection failed"); 63 | } 64 | 65 | } 66 | 67 | void checkEmail() { // see if any data is available from client 68 | while (client.available()) { 69 | char c = client.read(); 70 | Serial.print(c); 71 | } 72 | 73 | if (!client.connected()) { 74 | Serial.println(); 75 | Serial.println("disconnecting."); 76 | client.stop(); 77 | } 78 | } 79 | 80 | // function to get the temperature for a device 81 | void getTemperature(DeviceAddress deviceAddress) 82 | { 83 | tempC = sensors.getTempC(deviceAddress); 84 | tempF = DallasTemperature::toFahrenheit(tempC); 85 | } 86 | 87 | void setup() 88 | { 89 | lastMessage = 0; 90 | Ethernet.begin(mac, ip); 91 | Serial.begin(9600); 92 | 93 | // Start up the sensors library 94 | sensors.begin(); 95 | // set the resolution 96 | sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION); 97 | 98 | delay(1000); 99 | } 100 | 101 | void loop() 102 | { 103 | sensors.requestTemperatures(); 104 | getTemperature(insideThermometer); 105 | Serial.println(tempC); 106 | // Is it too hot? 107 | if (tempC >= HighThreshold && (millis()>(lastMessage+(emailInterval*1000)))) { 108 | Serial.println("High Threshhold Exceeded"); 109 | char message1[] = "Temperature Sensor\0"; 110 | char message2[] = "High Threshold Exceeded\0"; 111 | sendEmail(subject, message1, message2, tempC); 112 | } // too cold? 113 | else if (tempC<= LowThreshold && (millis()>(lastMessage+(emailInterval*1000)))) 114 | Serial.println("Low Threshhold Exceeded"); 115 | char message1[] = "Temperature Sensor\0"; 116 | char message2[] = "Low Threshold Exceeded\0"; 117 | sendEmail(subject, message1, message2, tempC); 118 | } 119 | 120 | if (client.available()) {checkEmail();} 121 | } 122 | 123 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch17/Project49.pde: -------------------------------------------------------------------------------- 1 | // Project 49 – Twitterbot 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | // Data wire is plugged into pin 3 on the Arduino 11 | #define ONE_WIRE_BUS 3 12 | #define TEMPERATURE_PRECISION 12 13 | 14 | float itempC, itempF, etempC, etempF; 15 | boolean firstTweet = true; 16 | // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) 17 | OneWire oneWire(ONE_WIRE_BUS); 18 | 19 | // Pass our oneWire reference to Dallas Temperature. 20 | DallasTemperature sensors(&oneWire); 21 | 22 | // arrays to hold device addresses 23 | DeviceAddress insideThermometer = { 0x10, 0x7A, 0x3B, 0xA9, 0x01, 0x08, 0x00, 0xBF }; 24 | DeviceAddress outsideThermometer = { 0x10, 0xCD, 0x39, 0xA9, 0x01, 0x08, 0x00, 0xBE}; 25 | 26 | byte mac[] = { 0x64, 0xB9, 0xE8, 0xC3, 0xC7, 0xE2 }; 27 | 28 | // Your Token to tweet (get it from http://arduino-tweet.appspot.com/) 29 | Twitter twitter("608048201-CxY1yQi8ezhvjz60ZVfPHVdzIHbMOD1h2gvoaAIx"); 30 | 31 | unsigned long interval = 600000; // 10 minutes 32 | unsigned long lastTime; // time since last tweet 33 | 34 | // Message to post 35 | char message[140], serialString[60]; 36 | 37 | // function to get the temperature for a device 38 | void getTemperatures() 39 | { 40 | itempC = sensors.getTempC(insideThermometer); 41 | itempF = DallasTemperature::toFahrenheit(itempC); 42 | etempC = sensors.getTempC(outsideThermometer); 43 | etempF = DallasTemperature::toFahrenheit(etempC); 44 | } 45 | 46 | void tweet(char msg[]) { 47 | Serial.println("connecting ..."); 48 | if (twitter.post(msg)) { 49 | int status = twitter.wait(); 50 | if (status == 200) { 51 | Serial.println("OK. Tweet sent."); 52 | Serial.println(); 53 | lastTime = millis(); 54 | firstTweet = false; 55 | } else { 56 | Serial.print("failed : code "); 57 | Serial.println(status); 58 | } 59 | } else { 60 | Serial.println("connection failed."); 61 | } 62 | } 63 | 64 | void setup() 65 | { 66 | EthernetDHCP.begin(mac); 67 | Serial.begin(9600); 68 | sensors.begin(); 69 | // set the resolution 70 | sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION); 71 | sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION); 72 | 73 | sensors.requestTemperatures() 74 | 75 | getTemperatures(); 76 | // compile the string to be tweeted 77 | while (firstTweet) { 78 | sprintf(message, "Int. Temp: %d C (%d F) Ext. Temp: %d C (%d F). Tweeted from Arduino. %ld", int(itempC), int(itempF), int(etempC), int(etempF), millis()); tweet(message); 79 | } 80 | } 81 | 82 | void loop() 83 | { 84 | EthernetDHCP.maintain(); 85 | sensors.requestTemperatures(); 86 | // compile the string to be printed to the serial monitor 87 | sprintf(serialString, "Internal Temp: %d C %d F. External Temp: %d C %d F", int(itempC), int(itempF), int(etempC), int(etempF)); 88 | delay(500); 89 | Serial.println(serialString); 90 | Serial.println(); 91 | 92 | if (millis() >= (lastTime + interval)) { 93 | // compile the string to be tweeted 94 | sprintf(message, "Int. Temp: %d C (%d F) Ext. Temp: %d C (%d F). Tweeted from Arduino. %ld", int(itempC), int(itempF), int(etempC), int(etempF), millis()); tweet(message); 95 | } 96 | delay(10000); // 10 seconds 97 | } 98 | 99 | 100 | -------------------------------------------------------------------------------- /Beginning Arduino/Ch17/Project50.pde: -------------------------------------------------------------------------------- 1 | // Project 50 2 | // Thanks to Bob S. for original code 3 | // Get current weather observation for Edwards AFB from weather.gov in XML format 4 | 5 | #include 6 | #include 7 | // Max string length may have to be adjusted depending on data to be extracted 8 | #define MAX_STRING_LEN 20 9 | 10 | // Setup vars 11 | char tagStr[MAX_STRING_LEN] = ""; 12 | char dataStr[MAX_STRING_LEN] = ""; 13 | char tmpStr[MAX_STRING_LEN] = ""; 14 | char endTag[3] = {'<', '/', '\0'}; 15 | int len; 16 | // Flags to differentiate XML tags from document elements (ie. data) 17 | boolean tagFlag = false; 18 | boolean dataFlag = false; 19 | 20 | // Ethernet vars 21 | byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 22 | byte ip[] = {172,31,24,232}; 23 | byte server[] = { 140, 90, 113, 200 }; // www.weather.gov 24 | 25 | // Start ethernet client 26 | Client client(server, 80); 27 | 28 | void setup() 29 | { 30 | Serial.begin(9600); 31 | Serial.println("Starting Weather RSS Reader"); 32 | Serial.println("connecting..."); 33 | Ethernet.begin(mac, ip); 34 | delay(1000); 35 | 36 | if (client.connect()) { 37 | Serial.println("connected"); 38 | client.println("GET /xml/current_obs/KEDW.xml HTTP/1.0"); 39 | client.println(); 40 | delay(2000); 41 | } else { 42 | Serial.println("connection failed"); 43 | } 44 | } 45 | 46 | void loop() { 47 | 48 | // Read serial data in from web: 49 | while (client.available()) { 50 | serialEvent(); 51 | } 52 | 53 | if (!client.connected()) { 54 | client.stop(); 55 | 56 | if (int t=0; t<15; t++) { // the feed is updated once every 15 mins 57 | delay(60000); // 1 minute 58 | } 59 | if (client.connect()) { 60 | client.println("GET /xml/current_obs/KEDW.xml HTTP/1.0"); 61 | client.println(); 62 | delay(2000); 63 | } else { 64 | Serial.println("Reconnection failed"); 65 | } 66 | } 67 | } 68 | 69 | // Process each char from web 70 | void serialEvent() { 71 | 72 | // Read a char 73 | char inChar = client.read(); 74 | 75 | if (inChar == '<') { 76 | addChar(inChar, tmpStr); 77 | tagFlag = true; 78 | dataFlag = false; 79 | 80 | } else if (inChar == '>') { 81 | addChar(inChar, tmpStr); 82 | 83 | if (tagFlag) { 84 | strncpy(tagStr, tmpStr, strlen(tmpStr)+1); 85 | } 86 | 87 | // Clear tmp 88 | clearStr(tmpStr); 89 | 90 | tagFlag = false; 91 | dataFlag = true; 92 | 93 | } else if (inChar != 10) { 94 | if (tagFlag) { 95 | // Add tag char to string 96 | addChar(inChar, tmpStr); 97 | 98 | // Check for end tag, ignore it 99 | if ( tagFlag && strcmp(tmpStr, endTag) == 0 ) { 100 | clearStr(tmpStr); 101 | tagFlag = false; 102 | dataFlag = false; 103 | } 104 | } 105 | 106 | if (dataFlag) { 107 | // Add data char to string 108 | addChar(inChar, dataStr); 109 | } 110 | } 111 | 112 | // If a LF, process the line 113 | if (inChar == 10 ) { 114 | 115 | // Find specific tags and print data 116 | if (matchTag("")) { 117 | Serial.print("Temp: "); 118 | Serial.print(dataStr); 119 | } 120 | if (matchTag("")) { 121 | Serial.print(", TempC: "); 122 | Serial.print(dataStr); 123 | } 124 | if (matchTag("")) { 125 | Serial.print(", Humidity: "); 126 | Serial.print(dataStr); 127 | } 128 | if (matchTag("")) { 129 | Serial.print(", Pressure: "); 130 | Serial.print(dataStr); 131 | Serial.println(""); 132 | } 133 | 134 | // Clear all strings 135 | clearStr(tmpStr); 136 | clearStr(tagStr); 137 | clearStr(dataStr); 138 | 139 | // Clear Flags 140 | tagFlag = false; 141 | dataFlag = false; 142 | } 143 | } 144 | 145 | // Function to clear a string 146 | void clearStr (char* str) { 147 | int len = strlen(str); 148 | for (int c = 0; c < len; c++) { 149 | str[c] = 0; 150 | } 151 | } 152 | 153 | //Function to add a char to a string and check its length 154 | void addChar (char ch, char* str) { 155 | char *tagMsg = ""; 156 | char *dataMsg = "-TRUNCATED_DATA-"; 157 | 158 | // Check the max size of the string to make sure it doesn't grow too 159 | // big. If string is beyond MAX_STRING_LEN assume it is unimportant 160 | // and replace it with a warning message. 161 | if (strlen(str) > MAX_STRING_LEN - 2) { 162 | if (tagFlag) { 163 | clearStr(tagStr); 164 | strcpy(tagStr,tagMsg); 165 | } 166 | if (dataFlag) { 167 | clearStr(dataStr); 168 | strcpy(dataStr,dataMsg); 169 | } 170 | 171 | // Clear the temp buffer and flags to stop current processing 172 | clearStr(tmpStr); 173 | tagFlag = false; 174 | dataFlag = false; 175 | 176 | } else { 177 | // Add char to string 178 | str[strlen(str)] = ch; 179 | } 180 | } 181 | 182 | // Function to check the current tag for a specific string 183 | boolean matchTag (char* searchTag) { 184 | if ( strcmp(tagStr, searchTag) == 0 ) { 185 | return true; 186 | } else { 187 | return false; 188 | } 189 | } 190 | 191 | -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0201.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0201.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0206.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0206.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0207.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0207.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0208.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0208.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0212.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0212.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0301.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0301.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0302.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0302.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0303.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0303.jpg -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0304.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0304.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0305.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0305.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0306.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0306.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0401.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0401.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0403.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0403.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0404.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0404.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0501.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0501.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0503.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0503.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0601.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0601.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0604.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0604.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0605.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0605.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0701.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0701.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0704.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0704.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0708.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0708.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0801.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0801.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0802.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0802.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0903.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0903.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0905.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0905.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f0906.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f0906.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1001.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1009.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1009.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1102.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1102.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1105.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1105.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1201.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1201.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1204.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1204.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1206.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1206.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1207.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1207.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1301.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1301.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1303.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1303.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1401.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1401.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1403.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1403.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1405.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1405.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1501.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1501.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1502.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1502.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1601.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1601.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1603.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1603.png -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/McRoberts32407f1707.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/McRoberts32407f1707.jpg -------------------------------------------------------------------------------- /Beginning Arduino/Color Insert images/Thumbs.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/Beginning Arduino/Color Insert images/Thumbs.db -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-arduino/19bf46820b2541b77b6c70f1d93b0e10c856941a/LICENSE.txt -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Beginning Arduino*](http://www.apress.com/9781430232407) by Michael McRoberts (Apress, 2010). 4 | 5 | ![Cover image](9781430232407.jpg) 6 | 7 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 8 | 9 | ## Releases 10 | 11 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 12 | 13 | ## Contributions 14 | 15 | See the file Contributing.md for more information on how you can contribute to this repository. 16 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! --------------------------------------------------------------------------------