diff --git a/9781430250166.jpg b/9781430250166.jpg new file mode 100644 index 0000000..a1054d3 Binary files /dev/null and b/9781430250166.jpg differ diff --git a/9781430250166_Color Figures.zip b/9781430250166_Color Figures.zip new file mode 100644 index 0000000..5f1f3bc Binary files /dev/null and b/9781430250166_Color Figures.zip differ diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..24fb675 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,27 @@ +Freeware License, some rights reserved + +Copyright (c) 2013 Michael McRoberts + +Permission is hereby granted, free of charge, to anyone obtaining a copy +of this software and associated documentation files (the "Software"), +to work with the Software within the limits of freeware distribution and fair use. +This includes the rights to use, copy, and modify the Software for personal use. +Users are also allowed and encouraged to submit corrections and modifications +to the Software for the benefit of other users. + +It is not allowed to reuse, modify, or redistribute the Software for +commercial use in any way, or for a user’s educational materials such as books +or blog articles without prior permission from the copyright holder. + +The above copyright notice and this permission notice need to be included +in all copies or substantial portions of the software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + diff --git a/Project_01/Project_01.ino b/Project_01/Project_01.ino new file mode 100644 index 0000000..94b9af4 --- /dev/null +++ b/Project_01/Project_01.ino @@ -0,0 +1,11 @@ +// Project 1 - LED Flasher +int ledPin = 10; +void setup() { +pinMode(ledPin, OUTPUT); +} +void loop() { +digitalWrite(ledPin, HIGH); +delay(1000); +digitalWrite(ledPin, LOW); +delay(1000); +} diff --git a/Project_02/Project_02.ino b/Project_02/Project_02.ino new file mode 100644 index 0000000..40f028e --- /dev/null +++ b/Project_02/Project_02.ino @@ -0,0 +1,47 @@ +// Project 2 - SOS Morse Signaller +// LED connected to digital pin 10 +int ledPin = 10; + +// run once, when the sketch starts +void setup() +{ +// sets the digital pin as output +pinMode(ledPin, OUTPUT); +} + +// run over and over again +void loop() +{ +// 3 dits +for (int x=0; x<3; x++) { +digitalWrite(ledPin, HIGH); // sets the LED on +delay(150); // waits for 150ms +digitalWrite(ledPin, LOW); // sets the LED off +delay(100); // waits for 100ms + } + + // 100ms delay to cause slight gap between letters + delay(100); + // 3 dahs + for (int x=0; x<3; x++) { + digitalWrite(ledPin, HIGH); // sets the LED on + delay(400); // waits for 400ms + digitalWrite(ledPin, LOW); // sets the LED off + delay(100); // waits for 100ms + } + + // 100ms delay to cause slight gap between letters + delay(100); + + // 3 dits again + for (int x=0; x<3; x++) { + digitalWrite(ledPin, HIGH); // sets the LED on + delay(150); // waits for 150ms + digitalWrite(ledPin, LOW); // sets the LED off + delay(100); // waits for 100ms + } + +// wait 5 seconds before repeating the SOS signal +delay(5000); +} + diff --git a/Project_03/Project_03.ino b/Project_03/Project_03.ino new file mode 100644 index 0000000..184bbba --- /dev/null +++ b/Project_03/Project_03.ino @@ -0,0 +1,35 @@ +// Project 3 - Traffic Lights + +int ledDelay = 10000; // delay in between changes +int redPin = 10; +int yellowPin = 9; +int greenPin = 8; + +void setup() { + pinMode(redPin, OUTPUT); + pinMode(yellowPin, OUTPUT); +pinMode(greenPin, OUTPUT); +} + +void loop() { + + digitalWrite(redPin, HIGH); // turn the red light on + delay(ledDelay); // wait 5 seconds + + digitalWrite(yellowPin, HIGH); // turn on yellow + delay(2000); // wait 2 seconds + + digitalWrite(greenPin, HIGH); // turn green on + digitalWrite(redPin, LOW); // turn red off + digitalWrite(yellowPin, LOW); // turn yellow off + delay(ledDelay); // wait ledDelay milliseconds + + digitalWrite(yellowPin, HIGH); // turn yellow on + digitalWrite(greenPin, LOW); // turn green off + delay(2000); // wait 2 seconds + + digitalWrite(yellowPin, LOW); // turn yellow off + // now our loop repeats + +} + diff --git a/Project_04/Project_04.ino b/Project_04/Project_04.ino new file mode 100644 index 0000000..b149625 --- /dev/null +++ b/Project_04/Project_04.ino @@ -0,0 +1,68 @@ +// Project 4 - Interactive Traffic Lights + +int carRed = 12; // assign the car lights +int carYellow = 11; +int carGreen = 10; +int pedRed = 9; // assign the pedestrian lights +int pedGreen = 8; +int button = 2; // button pin +int crossTime = 5000; // time allowed to cross +unsigned long changeTime = 0; // time last pedestrian cycle completed + +void setup() { + pinMode(carRed, OUTPUT); + pinMode(carYellow, OUTPUT); + pinMode(carGreen, OUTPUT); + pinMode(pedRed, OUTPUT); + pinMode(pedGreen, OUTPUT); + pinMode(button, INPUT); // button on pin 2 + // turn on the green light + digitalWrite(carGreen, HIGH); + digitalWrite(pedRed, HIGH); +} + +void loop() { + int state = digitalRead(button); + /* check if button is pressed and it is over 5 seconds since last button press */ + if (state == HIGH && (millis() - changeTime) > 5000) { + // Call the function to change the lights + changeLights(); + } +} + + +void changeLights() { + digitalWrite(carGreen, LOW); // green off + digitalWrite(carYellow, HIGH); // yellow on + delay(2000); // wait 2 seconds + + digitalWrite(carYellow, LOW); // yellow off + digitalWrite(carRed, HIGH); // red on + delay(1000); // wait 1 second till its safe + + digitalWrite(pedRed, LOW); // ped red off + digitalWrite(pedGreen, HIGH); // ped green on + delay(crossTime); // wait for preset time period + + // flash the ped green + for (int x=0; x<10; x++) { + digitalWrite(pedGreen, HIGH); + delay(250); + digitalWrite(pedGreen, LOW); + delay(250); + } + // turn ped red on + digitalWrite(pedRed, HIGH); + delay(500); + + digitalWrite(carYellow, HIGH); // yellow on + digitalWrite(carRed, LOW); // red off + delay(1000); + digitalWrite(carGreen, HIGH); + digitalWrite(carYellow, LOW); // yellow off + + // record the time since last change of lights + changeTime = millis(); + // then return to the main program loop +} + diff --git a/Project_05/Project_05.ino b/Project_05/Project_05.ino new file mode 100644 index 0000000..f68d481 --- /dev/null +++ b/Project_05/Project_05.ino @@ -0,0 +1,31 @@ +// Project 5 - LED Chase Effect +byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; // Create array for LED pins +int ledDelay = 65; // delay between changes +int direction = 1; +int currentLED = 0; +unsigned long changeTime; + +void setup() { + for (int x=0; x<10; x++) { // set all pins to output + pinMode(ledPin[x], OUTPUT); } + changeTime = millis(); +} + +void loop() { + if ((millis() - changeTime) > ledDelay) { // if it has been ledDelay ms since last change + changeLED(); + changeTime = millis(); + } +} + +void changeLED() { + for (int x=0; x<10; x++) { // turn off all LED's + digitalWrite(ledPin[x], LOW); + } + digitalWrite(ledPin[currentLED], HIGH); // turn on the current LED + currentLED += direction; // increment by the direction value + // change direction if we reach the end + if (currentLED == 9) {direction = -1;} + if (currentLED == 0) {direction = 1;} +} + diff --git a/Project_06/Project_06.ino b/Project_06/Project_06.ino new file mode 100644 index 0000000..d5007ae --- /dev/null +++ b/Project_06/Project_06.ino @@ -0,0 +1,34 @@ +// Project 6 - Interactive LED Chase Effect + +byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; // Create array for LED pins +int ledDelay; // delay between changes +int direction = 1; +int currentLED = 0; +unsigned long changeTime; +int potPin = 2; // select the input pin for the potentiometer + +void setup() { +for (int x=0; x<10; x++) { // set all pins to output + pinMode(ledPin[x], OUTPUT); } + changeTime = millis(); +} + +void loop() { +ledDelay = analogRead(potPin); // read the value from the pot +if ((millis() - changeTime) > ledDelay) { // if it has been ledDelay ms since last change + changeLED(); + changeTime = millis(); + } +} + +void changeLED() { + for (int x=0; x<10; x++) { // turn off all LED's + digitalWrite(ledPin[x], LOW); + } + digitalWrite(ledPin[currentLED], HIGH); // turn on the current LED +currentLED += direction; // increment by the direction value + // change direction if we reach the end + if (currentLED == 9) {direction = -1;} + if (currentLED == 0) {direction = 1;} +} + diff --git a/Project_07/Project_07.ino b/Project_07/Project_07.ino new file mode 100644 index 0000000..9d0fd97 --- /dev/null +++ b/Project_07/Project_07.ino @@ -0,0 +1,20 @@ +// Project 7 - Pulsating lamp + +int ledPin = 11; +float sinVal; +int ledVal; + +void setup() { + pinMode(ledPin, OUTPUT); +} + +void loop() { + for (int x=0; x<180; x++) { + // convert degrees to radians then obtain sin value + sinVal = (sin(x*(3.1412/180))); + ledVal = int(sinVal*255); + analogWrite(ledPin, ledVal); + delay(25); + } +} + diff --git a/Project_08/Project_08.ino b/Project_08/Project_08.ino new file mode 100644 index 0000000..37a874e --- /dev/null +++ b/Project_08/Project_08.ino @@ -0,0 +1,54 @@ +// Project 8 - Mood Lamp + +float RGB1[3]; +float RGB2[3]; +float INC[3]; + +int red, green, blue; + +int RedPin = 11; +int GreenPin = 10; +int BluePin = 9; + +void setup() +{ + Serial.begin(9600); + randomSeed(analogRead(0)); + + RGB1[0] = 0; + RGB1[1] = 0; + RGB1[2] = 0; + + RGB2[0] = random(256); + RGB2[1] = random(256); + RGB2[2] = random(256); +} + +void loop() +{ + randomSeed(analogRead(0)); + + for (int x=0; x<3; x++) { + INC[x] = (RGB1[x] - RGB2[x]) / 256; } + + for (int x=0; x<256; x++) { + red = int(RGB1[0]); + green = int(RGB1[1]); + blue = int(RGB1[2]); + + analogWrite (RedPin, red); + analogWrite (GreenPin, green); + analogWrite (BluePin, blue); + delay(100); + + RGB1[0] -= INC[0]; + RGB1[1] -= INC[1]; + RGB1[2] -= INC[2]; + } + for (int x=0; x<3; x++) { + RGB2[x] = random(556)-300; + RGB2[x] = constrain(RGB2[x], 0, 255); + delay(1000); + } +} + diff --git a/Project_09/Project_09.ino b/Project_09/Project_09.ino new file mode 100644 index 0000000..2febe9e --- /dev/null +++ b/Project_09/Project_09.ino @@ -0,0 +1,21 @@ +// Project 9 - LED Fire Effect + +int ledPin1 = 9; +int ledPin2 = 10; +int ledPin3 = 11; + +void setup() +{ + pinMode(ledPin1, OUTPUT); + pinMode(ledPin2, OUTPUT); + pinMode(ledPin3, OUTPUT); +} + +void loop() +{ +analogWrite(ledPin1, random(120)+135); +analogWrite(ledPin2, random(120)+135); +analogWrite(ledPin3, random(120)+135); +delay(random(100)); +} + diff --git a/Project_10/Project_10.ino b/Project_10/Project_10.ino new file mode 100644 index 0000000..7f23ff9 --- /dev/null +++ b/Project_10/Project_10.ino @@ -0,0 +1,76 @@ +// Project 10 - Serial controlled mood lamp + +char buffer[18]; +int red, green, blue; + +int RedPin = 11; +int GreenPin = 10; +int BluePin = 9; + +void setup() +{ + Serial.begin(9600); +while(Serial.available()) + Serial.read(); +pinMode(RedPin, OUTPUT); + pinMode(GreenPin, OUTPUT); + pinMode(BluePin, OUTPUT); +} + +void loop() +{ + if (Serial.available() > 0) { + int index=0; + delay(100); // let the buffer fill up + int numChar = Serial.available(); + if (numChar>15) { + numChar=15; + } + while (numChar--) { + buffer[index++] = Serial.read(); + } + splitString(buffer); + } +} + +void splitString(char* data) { + Serial.print("Data entered: "); + Serial.println(data); + char* parameter; + parameter = strtok (data, " ,"); // Note that this is a space before the comma in " , " + while (parameter != NULL) { + setLED(parameter); + parameter = strtok (NULL, " ,"); // space before the comma in " , " +} + + // Clear the text and serial buffers + for (int x=0; x<16; x++) { + buffer[x]='\0'; + } + while(Serial.available()) +Serial.read();} + +void setLED(char* data) { + if ((data[0] == 'r') || (data[0] == 'R')) { + int Ans = strtol(data+1, NULL, 10); + Ans = constrain(Ans,0,255); + analogWrite(RedPin, Ans); + Serial.print("Red is set to: "); + Serial.println(Ans); + } + if ((data[0] == 'g') || (data[0] == 'G')) { + int Ans = strtol(data+1, NULL, 10); + Ans = constrain(Ans,0,255); + analogWrite(GreenPin, Ans); + Serial.print("Green is set to: "); + Serial.println(Ans); + } + if ((data[0] == 'b') || (data[0] == 'B')) { + int Ans = strtol(data+1, NULL, 10); + Ans = constrain(Ans,0,255); + analogWrite(BluePin, Ans); + Serial.print("Blue is set to: "); + Serial.println(Ans); + } +} + diff --git a/Project_11/Project_11.ino b/Project_11/Project_11.ino new file mode 100644 index 0000000..aa8bfb3 --- /dev/null +++ b/Project_11/Project_11.ino @@ -0,0 +1,20 @@ +// Project 11 - Piezo Sounder Alarm + +float sinVal; +int toneVal; + +void setup() { + pinMode(8, OUTPUT); +} + +void loop() { + for (int x=0; x<180; x++) { + // convert degrees to radians then obtain sin value + sinVal = (sin(x*(3.1412/180))); +// generate a frequency from the sin value + toneVal = 2000+(int(sinVal*1000)); + tone(8, toneVal); + delay(2); + } +} + diff --git a/Project_12/Project_12.ino b/Project_12/Project_12.ino new file mode 100644 index 0000000..be8ead0 --- /dev/null +++ b/Project_12/Project_12.ino @@ -0,0 +1,54 @@ +// Project 12 - Piezo Sounder Melody Player + +#define NOTE_C3 131 +#define NOTE_CS3 139 +#define NOTE_D3 147 +#define NOTE_DS3 156 +#define NOTE_E3 165 +#define NOTE_F3 175 +#define NOTE_FS3 185 +#define NOTE_G3 196 +#define NOTE_GS3 208 +#define NOTE_A3 220 +#define NOTE_AS3 233 +#define NOTE_B3 247 +#define NOTE_C4 262 +#define NOTE_CS4 277 +#define NOTE_D4 294 +#define NOTE_DS4 311 +#define NOTE_E4 330 +#define NOTE_F4 349 +#define NOTE_FS4 370 +#define NOTE_G4 392 +#define NOTE_GS4 415 +#define NOTE_A4 440 +#define NOTE_AS4 466 +#define NOTE_B4 494 + +#define WHOLE 1 +#define HALF 0.5 +#define QUARTER 0.25 +#define EIGHTH 0.125 +#define SIXTEENTH 0.0625 + +int tune[] = { + NOTE_F3, NOTE_F3, NOTE_F3, NOTE_C3, NOTE_A3,NOTE_A3,NOTE_A3,NOTE_F3, NOTE_F3, NOTE_A3, NOTE_C4, NOTE_C4, NOTE_AS3, NOTE_A3, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_AS3, NOTE_AS3, NOTE_A3, NOTE_G3, NOTE_A3, NOTE_F3, NOTE_F3, NOTE_A3, NOTE_G3, NOTE_C3, NOTE_E3, NOTE_G3, NOTE_F3}; + +float duration[] = {EIGHTH+SIXTEENTH, SIXTEENTH, QUARTER, QUARTER, EIGHTH+SIXTEENTH, SIXTEENTH, QUARTER, QUARTER, EIGHTH+SIXTEENTH, SIXTEENTH, QUARTER+EIGHTH, EIGHTH, EIGHTH, EIGHTH, HALF, EIGHTH, SIXTEENTH, QUARTER, QUARTER, EIGHTH+SIXTEENTH, SIXTEENTH, QUARTER, QUARTER, EIGHTH+SIXTEENTH, SIXTEENTH, QUARTER+EIGHTH, EIGHTH, EIGHTH, SIXTEENTH, HALF}; + +int length; + +void setup() { + pinMode(8, OUTPUT); + length = sizeof(tune) / sizeof(tune[0]); +} + +void loop() { + for (int x=0; x= threshold) { // If knock detected set brightness to max + ledValue = 255; + } + analogWrite(ledPin, int(ledValue) ); // Write brightness value to LED + ledValue = ledValue - 0.05; // Dim the LED slowly + if (ledValue <= 0) { ledValue = 0;} // Make sure value does not go below zero +} + diff --git a/Project_14/Project_14.ino b/Project_14/Project_14.ino new file mode 100644 index 0000000..7a1fe52 --- /dev/null +++ b/Project_14/Project_14.ino @@ -0,0 +1,18 @@ +// Project 14 - Light Sensor + +int piezoPin = 8; // Piezo on Pin 8 +int ldrPin = 0; // LDR on Analog Pin 0 +int ldrValue = 0; // Value read from the LDR + +void setup() { + // nothing to do here +} + +void loop() { + ldrValue = analogRead(ldrPin); // read the value from the LDR + tone(piezoPin,1000); // play a 1000Hz tone from the piezo + delay(25); // wait a bit + noTone(piezoPin); // stop the tone + delay(ldrValue); // wait the amount of milliseconds in ldrValue +} + diff --git a/Project_15/Project_15.ino b/Project_15/Project_15.ino new file mode 100644 index 0000000..8ec42ab --- /dev/null +++ b/Project_15/Project_15.ino @@ -0,0 +1,18 @@ +// Project 15 - Simple Motor Control + +int potPin = 0; // Analog in 0 connected to the potentiometer +int transistorPin = 9; // PWM Pin 9 connected to the base of the transistor +int potValue = 0; // value returned from the potentiometer + +void setup() { + // set the transistor pin as output: + pinMode(transistorPin, OUTPUT); +} + +void loop() { + // read the potentiometer, convert it to 0 - 255: + potValue = analogRead(potPin) / 4; + // use that to control the transistor: + analogWrite(transistorPin, potValue); +} + diff --git a/Project_16/Project_16.ino b/Project_16/Project_16.ino new file mode 100644 index 0000000..b19d37a --- /dev/null +++ b/Project_16/Project_16.ino @@ -0,0 +1,32 @@ +// Project 16 - Using an L293D Motor Driver IC + +#define switchPin 2 // switch input +#define motorPin1 3 // L293D Input 1 +#define motorPin2 4 // L293D Input 2 +#define speedPin 9 // L293D enable pin 1 +#define potPin 0 // Potentiometer on analog Pin 0 +int Mspeed = 0; // a variable to hold the current speed value + +void setup() { +//set switch pin as INPUT +pinMode(switchPin, INPUT); + +// set remaining pins as outputs +pinMode(motorPin1, OUTPUT); +pinMode(motorPin2, OUTPUT); +pinMode(speedPin, OUTPUT); +} + +void loop() { + Mspeed = analogRead(potPin)/4; // read the speed value from the potentiometer + analogWrite (speedPin, Mspeed); // write speed to Enable 1 pin + if (digitalRead(switchPin)) { // If the switch is HIGH, rotate motor clockwise + digitalWrite(motorPin1, LOW); // set Input 1 of the L293D low + digitalWrite(motorPin2, HIGH); // set Input 2 of the L293D high + } + else { // if the switch is LOW, rotate motor anti-clockwise + digitalWrite(motorPin1, HIGH); // set Input 1 of the L293D low + digitalWrite(motorPin2, LOW); // set Input 2 of the L293D high + } +} + diff --git a/Project_17/Project_17.ino b/Project_17/Project_17.ino new file mode 100644 index 0000000..27a243a --- /dev/null +++ b/Project_17/Project_17.ino @@ -0,0 +1,47 @@ +// Project 17 + +int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch) +int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock) +int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data) + +void setup() { +//set pins to output +pinMode(latchPin, OUTPUT); +pinMode(clockPin, OUTPUT); +pinMode(dataPin, OUTPUT); +} + +void loop() { +//count from 0 to 255 +for (int i = 0; i < 256; i++) { +shiftDataOut(i); +//set latchPin low then high to send data out +digitalWrite(latchPin, LOW); +digitalWrite(latchPin, HIGH); +delay(1000); +} +} + +void shiftDataOut(byte dataOut) { +// Shift out 8 bits LSB first, clocking each with a rising edge of the clock line +boolean pinState; + +for (int i=0; i<=7; i++) { // for each bit in dataOut send out a bit +digitalWrite(clockPin, LOW); //set clockPin to LOW prior to sending bit + + // if the value of DataOut and (logical AND) a bitmask +// are true, set pinState to 1 (HIGH) + if ( dataOut & (1< // Install the library first or the code won’t work + +int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch) +int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock) +int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data) + +byte led[8]; // 8 element unsigned integer array to hold the sprite + +void setup() { + // set the 3 digital pins to outputs + pinMode(latchPin, OUTPUT); + pinMode(clockPin, OUTPUT); + pinMode(dataPin, OUTPUT); + + // Load the binary representation of the image into the array + led[0] = B11111111; + led[1] = B10000001; + led[2] = B10111101; + led[3] = B10100101; + led[4] = B10100101; + led[5] = B10111101; + led[6] = B10000001; + led[7] = B11111111; + + // set a timer of length 10000 microseconds (1/100th of a second) + // and attach the screenUpdate function to the interrupt timer + Timer1.initialize(10000); + Timer1.attachInterrupt(screenUpdate); +} + +// invert each row of the binary image and wait 1/4 second +void loop() { + + for (int i=0; i<8; i++) { + led[i]= ~led[i]; + } + delay (250); +} + +// Display the image +void screenUpdate() { + byte row = B10000000; // row 1 + for (byte k = 0; k < 8; k++) { + + shiftOut(dataPin, clockPin, LSBFIRST, led[k] ); // LED array + shiftOut(dataPin, clockPin, LSBFIRST, ~row); // row binary number (active low) + + // latch low to high to output data + digitalWrite(latchPin, LOW); + digitalWrite(latchPin, HIGH); + + // bitshift right + row = row >> 1; + } + +// Turn all rows off until next interrupt + shiftOut(dataPin, clockPin, LSBFIRST, 0); + shiftOut(dataPin, clockPin, LSBFIRST, ~0); + + // latch low to high to output data + digitalWrite(latchPin, LOW); + digitalWrite(latchPin, HIGH); +} + + diff --git a/Project_20/Project_20.ino b/Project_20/Project_20.ino new file mode 100644 index 0000000..1e1044e --- /dev/null +++ b/Project_20/Project_20.ino @@ -0,0 +1,60 @@ +// Project 20 - LED Dot Matrix Display - Scrolling Sprite + +#include + +int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch) +int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock) +int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data) +byte frame = 0; // variable to store the current frame being displayed + +byte led[8][8] = { {0, 56, 92, 158, 158, 130, 68, 56}, // 8 frames of an animation + {0, 56, 124, 186, 146, 130, 68, 56}, + {0, 56, 116, 242, 242, 130, 68, 56}, + {0, 56, 68, 226, 242, 226, 68, 56}, + {0, 56, 68, 130, 242, 242, 116, 56}, + {0, 56, 68, 130, 146, 186, 124, 56}, + {0, 56, 68, 130, 158, 158, 92, 56}, + {0, 56, 68, 142, 158, 142, 68, 56} }; + +void setup() { + pinMode(latchPin, OUTPUT); // set the 3 digital pins to outputs + pinMode(clockPin, OUTPUT); + pinMode(dataPin, OUTPUT); + + Timer1.initialize(10000); // set a timer of length 10000 microseconds + Timer1.attachInterrupt(screenUpdate); // attach the screenUpdate function +} + +void loop() { + for (int i=0; i<8; i++) { // loop through all 8 frames of the animation + for (int j=0; j<8; j++) { // loop through the 8 rows per frame + led[i][j]= led[i][j] << 1 | led[i][j] >> 7; // bitwise rotation + } + } + frame++; // go to the next frame in the animation + if (frame>7) { frame =0;} // make sure we go back to frame 0 once past 7 + delay(100); // wait a bit between frames +} + +void screenUpdate() { // function to display image + byte row = B10000000; // row 1 + for (byte k = 0; k < 8; k++) { + + shiftOut(dataPin, clockPin, LSBFIRST, led[frame][k] ); // LED array + shiftOut(dataPin, clockPin, LSBFIRST, ~row); // row select (active low) + + // create a low to high transition on latchPin to transfer output to display + digitalWrite(latchPin, LOW); + digitalWrite(latchPin, HIGH); + row = row >> 1; // bitshift right + } + // turn all rows off until next timer interrupt so last row isn't on longer than others + shiftOut(dataPin, clockPin, LSBFIRST, 0 ); // column doesn't matter w/ all rows off + shiftOut(dataPin, clockPin, LSBFIRST, ~0); // select no row + + // create a low to high transition on latchPin to transfer output to display + digitalWrite(latchPin, LOW); + digitalWrite(latchPin, HIGH); +} + + diff --git a/Project_21/Project_21.ino b/Project_21/Project_21.ino new file mode 100644 index 0000000..cda524f --- /dev/null +++ b/Project_21/Project_21.ino @@ -0,0 +1,201 @@ +// Project 21 - LED Dot Matrix Display - Scrolling Message + +#include +#include + +int DataPin = 2; // Pin 1 on MAX +int LoadPin = 3; // Pin 12 on MAX +int ClockPin = 4; // Pin 13 on MAX +byte buffer[8]; + +#define SCAN_LIMIT_REG 0x0B +#define DECODE_MODE_REG 0x09 +#define SHUTDOWN_REG 0x0C +#define INTENSITY_REG 0x0A + +static byte font[][8] PROGMEM = { +// The printable ASCII characters only (32-126) +{B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000}, +{B00000100, B00000100, B00000100, B00000100, B00000100, B00000100, B00000000, B00000100}, +{B00001010, B00001010, B00001010, B00000000, B00000000, B00000000, B00000000, B00000000}, +{B00000000, B00001010, B00011111, B00001010, B00011111, B00001010, B00011111, B00001010}, +{B00000111, B00001100, B00010100, B00001100, B00000110, B00000101, B00000110, B00011100}, +{B00011001, B00011010, B00000010, B00000100, B00000100, B00001000, B00001011, B00010011}, +{B00000110, B00001010, B00010010, B00010100, B00001001, B00010110, B00010110, B00001001}, +{B00000100, B00000100, B00000100, B00000000, B00000000, B00000000, B00000000, B00000000}, +{B00000010, B00000100, B00001000, B00001000, B00001000, B00001000, B00000100, B00000010}, +{B00001000, B00000100, B00000010, B00000010, B00000010, B00000010, B00000100, B00001000}, +{B00010101, B00001110, B00011111, B00001110, B00010101, B00000000, B00000000, B00000000}, +{B00000000, B00000000, B00000100, B00000100, B00011111, B00000100, B00000100, B00000000}, +{B00000000, B00000000, B00000000, B00000000, B00000000, B00000110, B00000100, B00001000}, +{B00000000, B00000000, B00000000, B00000000, B00001110, B00000000, B00000000, B00000000}, +{B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000100}, +{B00000001, B00000010, B00000010, B00000100, B00000100, B00001000, B00001000, B00010000}, +{B00001110, B00010001, B00010011, B00010001, B00010101, B00010001, B00011001, B00001110}, +{B00000100, B00001100, B00010100, B00000100, B00000100, B00000100, B00000100, B00011111}, +{B00001110, B00010001, B00010001, B00000010, B00000100, B00001000, B00010000, B00011111}, +{B00001110, B00010001, B00000001, B00001110, B00000001, B00000001, B00010001, B00001110}, +{B00010000, B00010000, B00010100, B00010100, B00011111, B00000100, B00000100, B00000100}, +{B00011111, B00010000, B00010000, B00011110, B00000001, B00000001, B00000001, B00011110}, +{B00000111, B00001000, B00010000, B00011110, B00010001, B00010001, B00010001, B00001110}, +{B00011111, B00000001, B00000001, B00000001, B00000010, B00000100, B00001000, B00010000}, +{B00001110, B00010001, B00010001, B00001110, B00010001, B00010001, B00010001, B00001110}, +{B00001110, B00010001, B00010001, B00001111, B00000001, B00000001, B00000001, B00000001}, +{B00000000, B00000100, B00000100, B00000000, B00000000, B00000100, B00000100, B00000000}, +{B00000000, B00000100, B00000100, B00000000, B00000000, B00000100, B00000100, B00001000}, +{B00000001, B00000010, B00000100, B00001000, B00001000, B00000100, B00000010, B00000001}, +{B00000000, B00000000, B00000000, B00011110, B00000000, B00011110, B00000000, B00000000}, +{B00010000, B00001000, B00000100, B00000010, B00000010, B00000100, B00001000, B00010000}, +{B00001110, B00010001, B00010001, B00000010, B00000100, B00000100, B00000000, B00000100}, +{B00001110, B00010001, B00010001, B00010101, B00010101, B00010001, B00010001, B00011110}, +{B00001110, B00010001, B00010001, B00010001, B00011111, B00010001, B00010001, B00010001}, +{B00011110, B00010001, B00010001, B00011110, B00010001, B00010001, B00010001, B00011110}, +{B00000111, B00001000, B00010000, B00010000, B00010000, B00010000, B00001000, B00000111}, +{B00011100, B00010010, B00010001, B00010001, B00010001, B00010001, B00010010, B00011100}, +{B00011111, B00010000, B00010000, B00011110, B00010000, B00010000, B00010000, B00011111}, +{B00011111, B00010000, B00010000, B00011110, B00010000, B00010000, B00010000, B00010000}, +{B00001110, B00010001, B00010000, B00010000, B00010111, B00010001, B00010001, B00001110}, + {B00010001, B00010001, B00010001, B00011111, B00010001, B00010001, B00010001, B00010001}, +{B00011111, B00000100, B00000100, B00000100, B00000100, B00000100, B00000100, B00011111}, +{B00011111, B00000100, B00000100, B00000100, B00000100, B00000100, B00010100, B00001000}, +{B00010001, B00010010, B00010100, B00011000, B00010100, B00010010, B00010001, B00010001}, +{B00010000, B00010000, B00010000, B00010000, B00010000, B00010000, B00010000, B00011111}, +{B00010001, B00011011, B00011111, B00010101, B00010001, B00010001, B00010001, B00010001}, +{B00010001, B00011001, B00011001, B00010101, B00010101, B00010011, B00010011, B00010001}, +{B00001110, B00010001, B00010001, B00010001, B00010001, B00010001, B00010001, B00001110}, +{B00011110, B00010001, B00010001, B00011110, B00010000, B00010000, B00010000, B00010000}, +{B00001110, B00010001, B00010001, B00010001, B00010001, B00010101, B00010011, B00001111}, +{B00011110, B00010001, B00010001, B00011110, B00010100, B00010010, B00010001, B00010001}, +{B00001110, B00010001, B00010000, B00001000, B00000110, B00000001, B00010001, B00001110}, +{B00011111, B00000100, B00000100, B00000100, B00000100, B00000100, B00000100, B00000100}, +{B00010001, B00010001, B00010001, B00010001, B00010001, B00010001, B00010001, B00001110}, +{B00010001, B00010001, B00010001, B00010001, B00010001, B00010001, B00001010, B00000100}, +{B00010001, B00010001, B00010001, B00010001, B00010001, B00010101, B00010101, B00001010}, +{B00010001, B00010001, B00001010, B00000100, B00000100, B00001010, B00010001, B00010001}, +{B00010001, B00010001, B00001010, B00000100, B00000100, B00000100, B00000100, B00000100}, +{B00011111, B00000001, B00000010, B00000100, B00001000, B00010000, B00010000, B00011111}, +{B00001110, B00001000, B00001000, B00001000, B00001000, B00001000, B00001000, B00001110}, +{B00010000, B00001000, B00001000, B00000100, B00000100, B00000010, B00000010, B00000001}, +{B00001110, B00000010, B00000010, B00000010, B00000010, B00000010, B00000010, B00001110}, +{B00000100, B00001010, B00010001, B00000000, B00000000, B00000000, B00000000, B00000000}, +{B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00011111}, +{B00001000, B00000100, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000}, +{B00000000, B00000000, B00000000, B00001110, B00010010, B00010010, B00010010, B00001111}, +{B00000000, B00010000, B00010000, B00010000, B00011100, B00010010, B00010010, B00011100}, +{B00000000, B00000000, B00000000, B00001110, B00010000, B00010000, B00010000, B00001110}, +{B00000000, B00000001, B00000001, B00000001, B00000111, B00001001, B00001001, B00000111}, +{B00000000, B00000000, B00000000, B00011100, B00010010, B00011110, B00010000, B00001110}, +{B00000000, B00000011, B00000100, B00000100, B00000110, B00000100, B00000100, B00000100}, +{B00000000, B00001110, B00001010, B00001010, B00001110, B00000010, B00000010, B00001100}, +{B00000000, B00010000, B00010000, B00010000, B00011100, B00010010, B00010010, B00010010}, +{B00000000, B00000000, B00000100, B00000000, B00000100, B00000100, B00000100, B00000100}, +{B00000000, B00000010, B00000000, B00000010, B00000010, B00000010, B00000010, B00001100}, +{B00000000, B00010000, B00010000, B00010100, B00011000, B00011000, B00010100, B00010000}, +{B00000000, B00010000, B00010000, B00010000, B00010000, B00010000, B00010000, B00001100}, +{B00000000, B00000000, B00000000, B00001010, B00010101, B00010001, B00010001, B00010001}, +{B00000000, B00000000, B00000000, B00010100, B00011010, B00010010, B00010010, B00010010}, +{B00000000, B00000000, B00000000, B00001100, B00010010, B00010010, B00010010, B00001100}, +{B00000000, B00011100, B00010010, B00010010, B00011100, B00010000, B00010000, B00010000}, +{B00000000, B00001110, B00010010, B00010010, B00001110, B00000010, B00000010, B00000001}, +{B00000000, B00000000, B00000000, B00001010, B00001100, B00001000, B00001000, B00001000}, +{B00000000, B00000000, B00001110, B00010000, B00001000, B00000100, B00000010, B00011110}, +{B00000000, B00010000, B00010000, B00011100, B00010000, B00010000, B00010000, B00001100}, +{B00000000, B00000000, B00000000, B00010010, B00010010, B00010010, B00010010, B00001100}, +{B00000000, B00000000, B00000000, B00010001, B00010001, B00010001, B00001010, B00000100}, +{B00000000, B00000000, B00000000, B00010001, B00010001, B00010001, B00010101, B00001010}, +{B00000000, B00000000, B00000000, B00010001, B00001010, B00000100, B00001010, B00010001}, +{B00000000, B00000000, B00010001, B00001010, B00000100, B00001000, B00001000, B00010000}, +{B00000000, B00000000, B00000000, B00011111, B00000010, B00000100, B00001000, B00011111}, +{B00000010, B00000100, B00000100, B00000100, B00001000, B00000100, B00000100, B00000010}, +{B00000100, B00000100, B00000100, B00000100, B00000100, B00000100, B00000100, B00000100}, +{B00001000, B00000100, B00000100, B00000100, B00000010, B00000100, B00000100, B00001000}, +{B00000000, B00000000, B00000000, B00001010, B00011110, B00010100, B00000000, B00000000} +}; + +void clearDisplay() { + for (byte x=0; x<8; x++) { + buffer[x] = B00000000; + } + screenUpdate(); +} + +void initMAX7219() { + pinMode(DataPin, OUTPUT); + pinMode(LoadPin, OUTPUT); + pinMode(ClockPin, OUTPUT); + clearDisplay(); + writeData(SCAN_LIMIT_REG, B00000111); // scan limit set to 0:7 + writeData(DECODE_MODE_REG, B00000000); // decode mode off + writeData(SHUTDOWN_REG, B00000001); // Set shutdown register to normal operation + intensity(15); // Values 0 to 15 only (4 bit) +} + +void intensity(int intensity) { + writeData(INTENSITY_REG, intensity); //B0001010 is the Intensity Register +} + +void writeData(byte msb, byte lsb) { + digitalWrite(LoadPin, LOW); // set loadpin ready to receive data + shiftOut(DataPin, ClockPin, MSBFIRST, (msb)); + shiftOut(DataPin, ClockPin, MSBFIRST, (lsb)); + digitalWrite(LoadPin, HIGH); // latch the data +} + +void scroll(char myString[], int rate) { + +byte firstChrRow, secondChrRow; +byte ledOutput; +byte chrIndex = 0; // Initialise the string position index +byte Char1, Char2; +byte scrollBit = 0; +byte strLength = 0; + +unsigned long time; +unsigned long counter; + + while (myString[strLength]) { // Increment count till we reach the end of the string + strLength++;} + counter = millis(); + while (chrIndex < (strLength)) { + time = millis(); + if (time > (counter + rate)) { + Char1 = constrain(myString[chrIndex],32,126); + Char2 = constrain(myString[chrIndex+1],32,126); + for (byte y= 0; y<8; y++) { + firstChrRow = pgm_read_byte(&font[Char1 - 32][y]); + secondChrRow = (pgm_read_byte(&font[Char2 - 32][y])) << 1; + + ledOutput = (firstChrRow << scrollBit) + | (secondChrRow >> (8 - scrollBit) ); + buffer[y] = ledOutput; + } + scrollBit++; + if (scrollBit > 6) { + scrollBit = 0; + chrIndex++; + } + counter = millis(); + } + } +} + +void screenUpdate() { + for (byte row = 0; row < 8; row++) { + writeData(row+1, buffer[row]); + } +} + +void setup() { + initMAX7219(); + Timer1.initialize(10000); // initialize timer1 and set interrupt period + Timer1.attachInterrupt(screenUpdate); + Serial.begin(9600); +} + +void loop() { + clearDisplay(); + scroll(" BEGINNING ARDUINO ", 45); + scroll(" Chapter 7 - LED Displays ", 45); + scroll(" HELLO WORLD!!! :) ", 45); +} + diff --git a/Project_22/Project_22.ino b/Project_22/Project_22.ino new file mode 100644 index 0000000..d642795 --- /dev/null +++ b/Project_22/Project_22.ino @@ -0,0 +1,62 @@ +// Project 22 - LED Dot Matrix Display - Pong Game + +LedControl myMatrix = LedControl(2, 4, 3, 1); // create an instance of a Matrix + +int column = 0, row = random(8); +int directionX = 1, directionY = 1; +int paddle1 = 5, paddle1Val; +int movement_interval = 300; +int counter = 0; + +void setup() +{ + myMatrix.shutdown(0,false); + /* Set the brightness to a medium values */ + myMatrix.setIntensity(0,8); + randomSeed(analogRead(0)); + oops(); +} + + +void loop() +{ + paddle1Val = analogRead(paddle1); + paddle1Val = map(paddle1Val, 0, 1024, 0,6); + if (column == 6 && (paddle1Val == row || + paddle1Val+1 == row || paddle1Val+2 == row)) {directionX = -1;} + if (column == 0) {directionX = 1;} + if (row == 7) {directionY = -1;} + if (row == 0) {directionY = 1;} + if (column == 7) { oops();} + column += directionX; + row += directionY; + displayDashAndDot(); + counter++; +} + +void oops() { + for (int x=0; x<3; x++) { + myMatrix.clearDisplay(0); + delay(250); + for (int y=0; y<8; y++) { + myMatrix.setRow(0, y, 255); + } + delay(150); + } + counter=0; + movement_interval=300; + column=0; + row = random(8); + displayDashAndDot(); +} + +void displayDashAndDot() { + myMatrix.clearDisplay(0); + myMatrix.setLed(0, column, row, HIGH); + myMatrix.setLed(0, 7, paddle1Val, HIGH); + myMatrix.setLed(0, 7, paddle1Val+1, HIGH); + myMatrix.setLed(0, 7, paddle1Val+2, HIGH); + if (!(counter % 10)) {movement_interval -= 5;} + delay(movement_interval); +} + diff --git a/Project_23/Project_23.ino b/Project_23/Project_23.ino new file mode 100644 index 0000000..b69769f --- /dev/null +++ b/Project_23/Project_23.ino @@ -0,0 +1,143 @@ +// Project 23 - basic LCD Control + +#include + +// initialize the library with the numbers of the interface pins +LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // create an lcd object and assign the pins + +void setup() { + lcd.begin(16, 2); // Set the display to 16 columns and 2 rows +} + +void loop() { + // run the 7 demo routines + basicPrintDemo(); + displayOnOffDemo(); + setCursorDemo(); + scrollLeftDemo(); + scrollRightDemo(); + cursorDemo(); + createGlyphDemo(); +} + +void basicPrintDemo() { + lcd.clear(); // Clear the display + lcd.print("Basic Print"); // print some text + delay(2000); +} + +void displayOnOffDemo() { + lcd.clear(); // Clear the display + lcd.print("Display On/Off"); // print some text + for(int x=0; x < 3; x++) { // loop 3 times + lcd.noDisplay(); // turn display off + delay(1000); + lcd.display(); // turn it back on again + delay(1000); + } +} + +void setCursorDemo() { + lcd.clear(); // Clear the display + lcd.print("SetCursor Demo"); // print some text + delay(1000); + lcd.clear(); // Clear the display + lcd.setCursor(5,0); // cursor at column 5 row 0 + lcd.print("5,0"); + delay(2000); + lcd.setCursor(10,1); // cursor at column 10 row 1 + lcd.print("10,1"); + delay(2000); + lcd.setCursor(3,1); // cursor at column 3 row 1 + lcd.print("3,1"); + delay(2000); +} + +void scrollLeftDemo() { + lcd.clear(); // Clear the display + lcd.print("Scroll Left Demo"); + delay(1000); + lcd.clear(); // Clear the display + lcd.setCursor(7,0); + lcd.print("Beginning"); + lcd.setCursor(9,1); + lcd.print("Arduino"); + delay(1000); + for(int x=0; x<16; x++) { + lcd.scrollDisplayLeft(); // scroll display left 16 times + delay(250); + } +} + +void scrollRightDemo() { + lcd.clear(); // Clear the display + lcd.print("Scroll Right"); + lcd.setCursor(0,1); + lcd.print("Demo"); + delay(1000); + lcd.clear(); // Clear the display + lcd.print("Beginning"); + lcd.setCursor(0,1); + lcd.print("Arduino"); + delay(1000); + for(int x=0; x<16; x++) { + lcd.scrollDisplayRight(); // scroll display right 16 times + delay(250); + } +} + +void cursorDemo() { + lcd.clear(); // Clear the display + lcd.cursor(); // Enable cursor visible + lcd.print("Cursor On"); + delay(3000); + lcd.clear(); // Clear the display + lcd.noCursor(); // cursor invisible + lcd.print("Cursor Off"); + delay(3000); + lcd.clear(); // Clear the display + lcd.cursor(); // cursor visible + lcd.blink(); // cursor blinking + lcd.print("Cursor Blink On"); + delay(3000); + lcd.noCursor(); // cursor invisible + lcd.noBlink(); // blink off +} + + +void createGlyphDemo() { + lcd.clear(); + + byte happy[8] = { // create byte array with happy face + B00000, + B00000, + B10001, + B00000, + B10001, + B01110, + B00000, + B00000}; + + byte sad[8] = { // create byte array with sad face + B00000, + B00000, + B10001, + B00000, + B01110, + B10001, + B00000, + B00000}; + + lcd.createChar(0, happy); // create custom character 0 + lcd.createChar(1, sad); // create custom character 1 + + for(int x=0; x<5; x++) { // loop animation 5 times + lcd.setCursor(8,0); + lcd.write((byte)0); // write custom char 0 + delay(1000); + lcd.setCursor(8,0); + lcd.write(1); // write custom char 1 + delay(1000); + } +} + diff --git a/Project_24/Project_24.ino b/Project_24/Project_24.ino new file mode 100644 index 0000000..42f2f2d --- /dev/null +++ b/Project_24/Project_24.ino @@ -0,0 +1,74 @@ +// Project 24 - LCD Temperature Display + +#include + +// initialize the library with the numbers of the interface pins +LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // create an lcd object and assign the pins +int maxC=0, minC=100, maxF=0, minF=212; +int scale = 1; +int buttonPin=8; + +void setup() { + lcd.begin(16, 2); // Set the display to 16 columns and 2 rows + analogReference(INTERNAL); + // analogReference(INTERNAL1V1); If you have an Arduino Mega + pinMode(buttonPin, INPUT); +lcd.clear(); +} + +void loop() { + lcd.setCursor(0,0); // set cursor to home position + int sensor = analogRead(0); // read the temp from sensor + int buttonState = digitalRead(buttonPin); // check for button press + switch (buttonState) { // change scale state if pressed + case HIGH: + scale=-scale; // invert scale + lcd.clear(); + } + + switch (scale) { // decide if C or F scale + case 1: + celsius(sensor); + break; + case -1: + fahrenheit(sensor); + } + delay(250); +} + +void celsius(int sensor) { + lcd.setCursor(0,0); + int temp = sensor * 0.1074188; // convert to C + lcd.print(temp); + lcd.write(B11011111); // degree symbol + lcd.print("C "); + if (temp>maxC) {maxC=temp;} + if (tempmaxF) {maxF=temp;} + if (temp + +Servo servo1; // Create a servo object + +void setup() +{ + servo1.attach(5); // Attaches the servo on Pin 5 to the servo object +} + +void loop() +{ + int angle = analogRead(0); // Read the pot value + angle=map(angle, 0, 1023, 0, 180); // Map the values from 0 to 180 degrees + servo1.write(angle); // Write the angle to the servo + delay(15); // Delay of 15ms to allow servo to reach position +} + diff --git a/Project_26/Project_26.ino b/Project_26/Project_26.ino new file mode 100644 index 0000000..40eca49 --- /dev/null +++ b/Project_26/Project_26.ino @@ -0,0 +1,69 @@ +// Project 26 - Dual Servo Control + +#include + +char buffer[11]; +Servo servo1; // Create a servo object +Servo servo2; // Create a second servo object + +void setup() +{ + servo1.attach(5); // Attaches the servo on pin 5 to the servo1 object + servo2.attach(6); // Attaches the servo on pin 6 to the servo2 object + Serial.begin(9600); + while(Serial.available()) + Serial.read(); + servo1.write(90); // Put servo1 at home position + servo2.write(90); // Put servo2 at home postion + Serial.println("STARTING..."); +} + +void loop() +{ + if (Serial.available() > 0) { // Check if data has been entered + int index=0; + delay(100); // Let the buffer fill up + int numChar = Serial.available(); // Find the string length + if (numChar>10) { + numChar=10; + } + while (numChar--) { + // Fill the buffer with the string + buffer[index++] = Serial.read(); + } +buffer[index]='\0'; + splitString(buffer); // Run splitString function + } +} + +void splitString(char* data) { + Serial.print("Data entered: "); + Serial.println(data); + char* parameter; + parameter = strtok (data, " ,"); //String to token + while (parameter != NULL) { // If we haven't reached the end of the string... + setServo(parameter); // ...run the setServo function + parameter = strtok (NULL, " ,"); + } +while(Serial.available()) + Serial.read(); +} + + +void setServo(char* data) { + if ((data[0] == 'L') || (data[0] == 'l')) { + int firstVal = strtol(data+1, NULL, 10); // String to long integer + firstVal = constrain(firstVal,0,180); // Constrain values + servo1.write(firstVal); + Serial.print("Servo1 is set to: "); + Serial.println(firstVal); + } + if ((data[0] == 'R') || (data[0] == 'r')) { + int secondVal = strtol(data+1, NULL, 10); // String to long integer + secondVal = constrain(secondVal,0,255); // Constrain the values + servo2.write(secondVal); + Serial.print("Servo2 is set to: "); + Serial.println(secondVal); + } +} + diff --git a/Project_27/Project_27.ino b/Project_27/Project_27.ino new file mode 100644 index 0000000..5a49f9b --- /dev/null +++ b/Project_27/Project_27.ino @@ -0,0 +1,29 @@ +// Project 27 - Joystick Servo Control + +#include + +Servo servo1; // Create a servo object +Servo servo2; // Create a second servo object +int pot1, pot2; + +void setup() +{ + servo1.attach(5); // Attaches the servo on pin 5 to the servo1 object + servo2.attach(6); // Attaches the servo on pin 6 to the servo2 object + + servo1.write(90); // Put servo1 at home position + servo2.write(90); // Put servo2 at home postion + +} + +void loop() +{ + pot1 = analogRead(3); // Read the X-Axis + pot2 = analogRead(4); // Read the Y-Axis + pot1 = map(pot1,0,1023,0,180); + pot2=map(pot2,0,1023,0,180); + servo1.write(pot1); + servo2.write(pot2); + delay(15); +} + diff --git a/Project_28/Project_28.ino b/Project_28/Project_28.ino new file mode 100644 index 0000000..52d538a --- /dev/null +++ b/Project_28/Project_28.ino @@ -0,0 +1,24 @@ +// Project 28 - Basic Stepper Control + +#include + +// steps value is 360 / degree angle of motor +#define STEPS 200 + +// create a stepper object on pins 4, 5, 6 and 7 +Stepper stepper(STEPS, 4, 5, 6, 7); + +void setup() +{ +} + +void loop() +{ + stepper.setSpeed(60); + stepper.step(200); + delay(100); + stepper.setSpeed(20); + stepper.step(-50); + delay(100); +} + diff --git a/Project_29/Project_29.ino b/Project_29/Project_29.ino new file mode 100644 index 0000000..1bad25f --- /dev/null +++ b/Project_29/Project_29.ino @@ -0,0 +1,66 @@ +// Project 29 - Using a motor shield +#define QUARTER_SPEED 64 +#define HALF_SPEED 128 +#define FULL_SPEED 255 + +// Set the pins for speed and direction of each motor +int speed1 = 3; +int speed2 = 11; +int direction1 = 12; +int direction2 = 13; + +void stopMotor() { + // turn both motors off + analogWrite(speed1, 0); + analogWrite(speed2, 0); +} + +void setup() +{ + // set all the pins to outputs + pinMode(speed1, OUTPUT); + pinMode(speed2, OUTPUT); + pinMode(direction1, OUTPUT); + pinMode(direction2, OUTPUT); +} + +void loop() +{ + // Both motors forward at 50% speed for 2 seconds + digitalWrite(direction1, HIGH); + digitalWrite(direction2, HIGH); + analogWrite(speed1, HALF_SPEED); + analogWrite(speed2, HALF_SPEED); + delay(2000); + + stopMotor(); delay(1000); // stop + + // Left turn for 1 second + digitalWrite(direction1, LOW); + digitalWrite(direction2, HIGH); + analogWrite(speed1, HALF_SPEED); + analogWrite(speed2, HALF_SPEED); + delay(1000); + + stopMotor(); delay(1000); // stop + + // Both motors forward at 50% speed for 2 seconds + digitalWrite(direction1, HIGH); + digitalWrite(direction2, HIGH); + analogWrite(speed1, HALF_SPEED); + analogWrite(speed2, HALF_SPEED); + delay(2000); + + stopMotor(); delay(1000); // stop + + // rotate right at 25% speed + digitalWrite(direction1, HIGH); + digitalWrite(direction2, LOW); + analogWrite(speed1, QUARTER_SPEED); + analogWrite(speed2, QUARTER_SPEED); + delay(2000); + + stopMotor(); delay(1000); // stop + +} + diff --git a/Project_30/Project_30.ino b/Project_30/Project_30.ino new file mode 100644 index 0000000..50ac92d --- /dev/null +++ b/Project_30/Project_30.ino @@ -0,0 +1,111 @@ +// Project 30 - Line Following Robot + +int LDR1, LDR2, LDR3; // sensor values + +// calibration offsets +int leftOffset = 0, rightOffset = 0, center = 0; +// pins for motor speed and direction +int speed1 = 10, speed2 = 11, direction1 = 12, direction2 = 13; +// starting speed and rotation offset +int startSpeed = 70, rotate = 30; +// sensor threshold +int threshhold = 5; +int left = startSpeed, right = startSpeed; + +int button = 2; // button pin (optional) +int motorsOff = true; // motors initially off until button pressed. + // change the initial value to false if you + // don’t have a pushbutton on your robot + +// Sensor calibration routine +void calibrate() { + + for (int x=0; x<10; x++) { // run this 10 times to obtain average + digitalWrite(9, HIGH); // lights on + delay(100); + LDR1 = analogRead(0); // read the 3 sensors + LDR2 = analogRead(1); + LDR3 = analogRead(2); + leftOffset = leftOffset + LDR1; // add value of left sensor to total + center = center + LDR2; // add value of center sensor to total + rightOffset = rightOffset + LDR3; // add value of right sensor to total + + delay(100); + digitalWrite(9, LOW); // lights off + delay(100); + } + // obtain average for each sensor + leftOffset = leftOffset / 10; + rightOffset = rightOffset / 10; + center = center /10; + // calculate offsets for left and right sensors + leftOffset = center - leftOffset; + rightOffset = center - rightOffset; + +} + +void setup() +{ + pinMode(button, INPUT_PULLUP); // button on pin 2 (optional) + // set the motor pins to outputs + pinMode(9, OUTPUT); + pinMode(speed1, OUTPUT); + pinMode(speed2, OUTPUT); + pinMode(direction1, OUTPUT); + pinMode(direction2, OUTPUT); + // calibrate the sensors + calibrate(); + delay(3000); + + digitalWrite(9, HIGH); // lights on + delay(100); + + // set motor direction to forward + digitalWrite(direction1, HIGH); + digitalWrite(direction2, HIGH); + // set speed of both motors + analogWrite(speed1,left); + analogWrite(speed2,right); +} + +void loop() { + if ( !digitalRead(button) ){ + // button is pressed. Toggle motors on or off. + motorsOff = !motorsOff; + if (motorsOff) { + analogWrite(speed1, 0); // turn motors off by setting speed to zero + analogWrite(speed2, 0); + } + delay(500); // give time for human to let go of the buttton, + // and to ignore any switch bounce. + } + + // make both motors same speed + left = startSpeed; + right = startSpeed; + + // read the sensors and add the offsets + LDR1 = analogRead(0) + leftOffset; + LDR2 = analogRead(1); + LDR3 = analogRead(2) + rightOffset; + + // if LDR1 is greater than the centre sensor + threshold turn right + if (LDR1 > (LDR2+threshhold)) { + left = startSpeed + rotate; + right = startSpeed - rotate; + } + + // if LDR3 is greater than the centre sensor + threshold turn left + if (LDR3 > (LDR2+threshhold)) { + left = startSpeed - rotate; + right = startSpeed + rotate; + } + + // send the speed values to the motors + if (!motorsOff) { + analogWrite(speed1, left); + analogWrite(speed2,right); + } + +} + diff --git a/Project_31/Project_31.ino b/Project_31/Project_31.ino new file mode 100644 index 0000000..a8d873a --- /dev/null +++ b/Project_31/Project_31.ino @@ -0,0 +1,126 @@ +// Project 31 - Digital Pressure Sensor +// Based on the One Shot example by Henry Lahr + +#include // so we can use I2C communication +#define MYALTITUDE 262 //define altitude at your location to calculate mean sea level pressure in meters + +// Register addresses +const int SENSORADDRESS = 0x60; // MPL3115A1 address from the datasheet +#define SENSOR_CONTROL_REG_1 0x26 +#define SENSOR_DR_STATUS 0x00 // Address of DataReady status register +#define SENSOR_OUT_P_MSB 0x01 // Starting address of Pressure Data registers + +float baroAltitudeCorrectionFactor = 1/(pow(1-MYALTITUDE/44330.77,5.255877)); + +byte I2Cdata[5] = {0,0,0,0,0}; //buffer for sensor data + +void setup(){ + Wire.begin(); // join i2c bus + Serial.begin(9600); // start serial for output at 9600 baud + Serial.println("Setup"); + I2C_Write(SENSOR_CONTROL_REG_1, 0b00000000); // put in standby mode + // these upper bits of the control register + // can only be changed while in standby + I2C_Write(SENSOR_CONTROL_REG_1, 0b00111000); // set oversampling to 128 + Serial.println("Done."); +} + +void loop(){ + float temperature, pressure, baroPressure; + + Read_Sensor_Data(); + temperature = Calc_Temperature(); + pressure = Calc_Pressure(); + baroPressure = pressure * baroAltitudeCorrectionFactor; + Serial.print("Absolute pressure: "); + Serial.print(pressure); // in Pascal + Serial.print(" Pa, Barometer: "); + Serial.print(baroPressure); // in Pascal + Serial.print(" Pa, Temperature: "); + + Serial.print(temperature); // in degrees C + Serial.println(" C"); + delay(1000); +} + + // Read the pressure and temperature readings from the sensor +void Read_Sensor_Data(){ + + // request a single measurement from the sensor + I2C_Write(SENSOR_CONTROL_REG_1, 0b00111010); //bit 1 is one shot mode + + // Wait for measurement to complete. + // One-shot bit will clear when it is done. + // Rread the current (sensor control) register + // repeat until sensor clears OST bit + do { + Wire.requestFrom(SENSORADDRESS,1); + } while ((Wire.read() & 0b00000010) != 0); + + I2C_ReadData(); //reads registers from the sensor +} + + // This function assembles the pressure reading + // from the values in the read buffer + // The two lowest bits are fractional so divide by 4 +float Calc_Pressure(){ + unsigned long m_pressure = I2Cdata[0]; + unsigned long c_pressure = I2Cdata[1]; + float l_pressure = (float)(I2Cdata[2]>>4)/4; + return((float)(m_pressure<<10 | c_pressure<<2)+l_pressure); +} + +// This function assembles the temperature reading +// from the values in the read buffer +float Calc_Temperature(){ + int m_temp; + float l_temp; + m_temp = I2Cdata[3]; //temperature in whole degrees C + l_temp = (float)(I2Cdata[4]>>4)/16.0; //fractional portion of temperature + return((float)(m_temp + l_temp)); +} + +// Read Barometer and Temperature data (5 bytes) +void I2C_ReadData(){ + byte readUnsuccessful; + do { + byte i=0; + byte dataStatus = 0; + + Wire.beginTransmission(SENSORADDRESS); + Wire.write(SENSOR_OUT_P_MSB); + Wire.endTransmission(false); + + // read 5 bytes. 3 for pressure, 2 for temperature. + Wire.requestFrom(SENSORADDRESS,5); + while(Wire.available()) I2Cdata[i++] = Wire.read(); + + // in some modes it is possible for the sensor + // to update the pressure reading + // while we were in the middle of reading it, + // in which case our copy is garbage + // (parts of two different readings) + // We can check bits in the DR (data ready) + // register to see if this happened. + + Wire.beginTransmission(SENSORADDRESS); + Wire.write(SENSOR_DR_STATUS); + Wire.endTransmission(false); + + Wire.requestFrom(SENSORADDRESS,1); //read 5 bytes. 3 for pressure, 2 for temperature. + dataStatus = Wire.read(); + readUnsuccessful = (dataStatus & 0x60) != 0; + // This will be unsuccessful if overwrite happened + // while we were reading the pressure or temp data. + // So keep reading until we get a successful clean read + } while (readUnsuccessful); +} + +// This function writes one byte over I2C +void I2C_Write(byte regAddr, byte value){ + Wire.beginTransmission(SENSORADDRESS); + Wire.write(regAddr); + Wire.write(value); + Wire.endTransmission(true); +} + diff --git a/Project_32/Project_32.ino b/Project_32/Project_32.ino new file mode 100644 index 0000000..863546c --- /dev/null +++ b/Project_32/Project_32.ino @@ -0,0 +1,208 @@ +// Project 32 - Digital Barograph + +#include +#include "fonts/allFonts.h" +#include // so we can use I2C communication + +// The altitude at your location is needed to calculate the mean sea +// level pressure in meters +#define MYALTITUDE 262 +#define SENSORADDRESS 0x60 // The address of the MPL3115A1 +#define SENSOR_CONTROL_REG_1 0x26 +#define SENSOR_DR_STATUS 0x00 // Address of DataReady status register +#define SENSOR_OUT_P_MSB 0x01 // Starting address of Pressure Data registers + + // Time interval in seconds (approx.) per graph tic +// Scale to deduct from hPa reading to fit within the 40 pixels graph 990-1030 +#define INTERVAL 900 + +float baroAltitudeCorrectionFactor = 1/(pow(1-MYALTITUDE/44330.77,5.255877)); + +byte I2Cdata[5] = {0,0,0,0,0}; //buffer for sensor data +float pressure, temperature, buffer[30], baroPressure; +int dots[124], dotCursor = 0, counter = 0, index = 0, numReadingsBuffered = 0; + +void setup() +{ + Wire.begin(); // join i2c bus + I2C_Write(SENSOR_CONTROL_REG_1, 0b00000000); // put in standby mode + // these upper bits of the control register + // can only be changed while in standby + +// Set oversampling to 128. Then trigger first reading + I2C_Write(SENSOR_CONTROL_REG_1, 0b00111010); + + GLCD.Init(); // initialise the library + GLCD.ClearScreen(); + GLCD.SelectFont(System5x7, BLACK); // load the font + + GLCD.DrawRect(1,1,125,44); // Draw a rectangle + for (int x=0; x<46; x+=11) { // Draw vertical scale + GLCD.SetDot(0,1+x, BLACK); + GLCD.SetDot(127,1+x, BLACK); + } + for (int x=0; x<128; x+=5) { // Draw horizontal scale + GLCD.SetDot(1+x,0, BLACK); + } + +// Clear the array to standard sea level + for (byte x=0; x<124; x++) {dots[x]=1013;} + + Read_Sensor_Data(); + drawPoints(dotCursor); +} + +void loop() +{ + Read_Sensor_Data(); + + GLCD.CursorToXY(0, 49); // print pressure + GLCD.print("hPa:"); + GLCD.CursorToXY(24,49); + GLCD.print(baroPressure/100); + GLCD.print(" "); // erase any old value longer than new value + + float tempF = (temperature*1.8) + 32; + + GLCD.CursorToXY(0,57); // print temperature + GLCD.print("Temp:"); + GLCD.CursorToXY(28, 57); +// GLCD.print(temperature); // change to temperature for Centigrade + GLCD.print(tempF); + GLCD.print(" "); // erase any old value longer than new value + + delay(1000); + + GLCD.CursorToXY(84,49); // print trend + GLCD.print("TREND:"); + GLCD.CursorToXY(84,57); + printTrend(); + + counter++; + if (counter==INTERVAL) { + drawPoints(dotCursor); + counter = 0; + } +} + +void drawPoints(int position) { + dots[dotCursor] = int(baroPressure/100); + int midscale = dots[dotCursor]; // center graph scale on current reading + GLCD.FillRect(2, 2, 123, 40, WHITE); // clear graph area + for (int x=0; x<124; x++) { + // limit to graph boundary + int y = constrain(22-((dots[position]- midscale)), 0,44); + GLCD.SetDot(125-x,y, BLACK); + position--; + if (position<0) {position=123;} + } + dotCursor++; + if (dotCursor>123) {dotCursor=0;} +} + +// calculate trend since last data point and print +void printTrend() { + int dotCursor2=dotCursor-1; + if (dotCursor2<0) {dotCursor2=123;} + int val1=dots[dotCursor2]; + int dotCursor3=dotCursor2-1; + if (dotCursor3<0) {dotCursor3=123;} + int val2=dots[dotCursor3]; + if (val1>val2) {GLCD.print("RISING ");} + if (val1==val2) {GLCD.print("STEADY ");} + if (val1 29) index = 0; // at end of buffer, wrap around to start. + numReadingsBuffered++; + if (numReadingsBuffered > 30) numReadingsBuffered = 30; + + float mean = 0; + for (int i=0; i>6)/4; + return((float)(m_pressure<<10 | c_pressure<<2)+l_pressure); +} + +// This function assembles the temperature reading +// from the values in the read buffer +float Calc_Temperature(){ + int m_temp; + float l_temp; + m_temp = I2Cdata[3]; //temperature in whole degrees C + l_temp = (float)(I2Cdata[4]>>4)/16.0; //fractional portion of temperature + return((float)(m_temp + l_temp)); +} +void I2C_ReadData(){ //Read Barometer and Temperature data (5 bytes) + byte readUnsuccessful; + do { + byte i=0; + byte dataStatus = 0; + + Wire.beginTransmission(SENSORADDRESS); + Wire.write(SENSOR_OUT_P_MSB); + Wire.endTransmission(false); + + //read 5 bytes. 3 for pressure, 2 for temperature. + Wire.requestFrom(SENSORADDRESS,5); + while(Wire.available()) I2Cdata[i++] = Wire.read(); + + // in some modes it is possible for the sensor to + // update the pressure reading while we were in + // the middle of reading it, in which case our copy is garbage + // because it has parts of two different readings. + // We can check some status bits in the DR (data ready) + // register to see if this happened. + + Wire.beginTransmission(SENSORADDRESS); + Wire.write(SENSOR_DR_STATUS); + Wire.endTransmission(false); + + //read 1 byte to get status value + Wire.requestFrom(SENSORADDRESS,1); + dataStatus = Wire.read(); + readUnsuccessful = (dataStatus & 0x60) != 0; + // unsuccessful if overwrite happened while we + // were reading the pressure or temp data + // keep reading until we get a successful clean read + } while (readUnsuccessful); +} + +// This function writes one byte over I2C +void I2C_Write(byte regAddr, byte value){ +Wire.beginTransmission(SENSORADDRESS); + Wire.write(regAddr); + Wire.write(value); + Wire.endTransmission(true); +} + diff --git a/Project_33/Project_33.ino b/Project_33/Project_33.ino new file mode 100644 index 0000000..d650fea --- /dev/null +++ b/Project_33/Project_33.ino @@ -0,0 +1,72 @@ +// Project 33 - Basic Touch Screen + +// Power connections +#define Left 8 // Left (X1) to digital pin 8 +#define Bottom 9 // Bottom (Y2) to digital pin 9 +#define Right 10 // Right (X2) to digital pin 10 +#define Top 11 // Top (Y1) to digital pin 11 + +// Analog connections +#define topInput 0 // Top (Y1) to analog pin 0 +#define rightInput 1 // Right (X2) to analog pin 1 + +int coordX = 0, coordY = 0; + +void setup() +{ + Serial.begin(38400); +} + +void loop() +{ + if (touch()) // If screen touched, print co-ordinates + { + Serial.print(coordX); + Serial.print(" "); + Serial.println(coordY); + delay(250); + } +} + +// return TRUE if touched, and set coordinates to touchX and touchY +boolean touch() +{ + boolean touch = false; + + // get horizontal co-ordinates + + pinMode(Top, INPUT); // Top and Bottom to high impedance + pinMode(Bottom, INPUT); + + pinMode(Left, OUTPUT); + digitalWrite(Left, LOW); // Set Left to low + + pinMode(Right, OUTPUT); // Set right to +5v + digitalWrite(Right, HIGH); + + + delay(3); + coordX = analogRead(topInput); + + // get vertical co-ordinates + + pinMode(Right, INPUT); // left and right to high impedance + pinMode(Left, INPUT); + + pinMode(Bottom, OUTPUT); // set Bottom to Gnd + digitalWrite(Bottom, LOW); + + pinMode(Top, OUTPUT); // set Top to +5v + digitalWrite(Top, HIGH); + + + delay(3); + coordY = analogRead(rightInput); + + // if co-ordinates read are less than 1000 and greater than 24 + // then the screen has been touched + if(coordX < 1000 && coordX > 24 && coordY < 1000 && coordY > 24) {touch = true;} + + return touch; +} + diff --git a/Project_34/Project_34.ino b/Project_34/Project_34.ino new file mode 100644 index 0000000..4a82b65 --- /dev/null +++ b/Project_34/Project_34.ino @@ -0,0 +1,95 @@ +// Project 34 - Touch Screen Keypad + +#include + +LiquidCrystal lcd(2, 3, 4, 5, 6, 7); // create an lcd object and assign the pins + +// Power connections +#define Left 8 // Left (X1) to digital pin 8 +#define Bottom 9 // Bottom (Y2) to digital pin 9 +#define Right 10 // Right (X2) to digital pin 10 +#define Top 11 // Top (Y1) to digital pin 11 + +// Analog connections +#define topInput 0 // Top (Y1) to analog pin 0 +#define rightInput 1 // Right (X2) to analog pin 1 + +int coordX = 0, coordY = 0; +char buffer[16]; + +void setup() +{ + lcd.begin(16, 2); // Set the display to 16 columns and 2 rows + lcd.clear(); +} + +void loop() +{ + if (touch()) + { + if ((coordX>110 && coordX<300) && (coordY>170 && coordY<360)) {lcd.print("3");} + if ((coordX>110 && coordX<300) && (coordY>410 && coordY<610)) {lcd.print("2");} + if ((coordX>110 && coordX<300) && (coordY>640 && coordY<860)) {lcd.print("1");} + if ((coordX>330 && coordX<470) && (coordY>170 && coordY<360)) {lcd.print("6");} + if ((coordX>330 && coordX<470) && (coordY>410 && coordY<610)) {lcd.print("5");} + if ((coordX>330 && coordX<470) && (coordY>640 && coordY<860)) {lcd.print("4");} + if ((coordX>490 && coordX<710) && (coordY>170 && coordY<360)) {lcd.print("9");} + if ((coordX>490 && coordX<710) && (coordY>410 && coordY<610)) {lcd.print("8");} + if ((coordX>490 && coordX<710) && (coordY>640 && coordY<860)) {lcd.print("7");} + if ((coordX>760 && coordX<940) && (coordY>170 && coordY<360)) {scrollLCD();} + if ((coordX>760 && coordX<940) && (coordY>410 && coordY<610)) {lcd.print("0");} + if ((coordX>760 && coordX<940) && (coordY>640 && coordY<860)) {lcd.clear();} + delay(250); + } +} + +// return TRUE if touched, and set coordinates to touchX and touchY +boolean touch() +{ + boolean touch = false; + + // get horizontal co-ordinates + + pinMode(Top, INPUT); // Top and Bottom to high impedance + pinMode(Bottom, INPUT); + + pinMode(Left, OUTPUT); + digitalWrite(Left, LOW); // Set Left to low + + pinMode(Right, OUTPUT); // Set right to +5v + digitalWrite(Right, HIGH); + + + delay(3); + coordX = analogRead(topInput); + + // get vertical co-ordinates + + pinMode(Right, INPUT); // left and right to high impedance + pinMode(Left, INPUT); + + pinMode(Bottom, OUTPUT); // set Bottom to Gnd + digitalWrite(Bottom, LOW); + + pinMode(Top, OUTPUT); // set Top to +5v + digitalWrite(Top, HIGH); + + + delay(3); + coordY = analogRead(rightInput); + + // if co-ordinates read are less than 1000 and greater than 24 + // then the screen has been touched + if(coordX < 1000 && coordX > 24 && coordY < 1000 && coordY > 24) {touch = true;} + + return touch; +} + +void scrollLCD() { + for (int scrollNum=0; scrollNum<16; scrollNum++) { + lcd.scrollDisplayLeft(); + delay(100); + } + lcd.clear(); +} + diff --git a/Project_35/Project_35.ino b/Project_35/Project_35.ino new file mode 100644 index 0000000..a03d2af --- /dev/null +++ b/Project_35/Project_35.ino @@ -0,0 +1,115 @@ +// Project 34 - Touch Screen Light Controller + +// Power connections +#define Left 8 // Left (X1) to digital pin 8 +#define Bottom 9 // Bottom (Y2) to digital pin 9 +#define Right 10 // Right (X2) to digital pin 10 +#define Top 11 // Top (Y1) to digital pin 11 + +// Analog connections +#define topInput 0 // Top (Y1) to analog pin 0 +#define rightInput 1 // Right (X2) to analog pin 1 + +// RGB pins +#define pinR 3 +#define pinG 5 +#define pinB 6 + +int coordX = 0, coordY = 0; +boolean ledState = true; +int red = 100, green = 100, blue = 100; + +void setup() +{ + pinMode(pinR, OUTPUT); + pinMode(pinG, OUTPUT); + pinMode(pinB, OUTPUT); +} + +void loop() +{ + if (touch()) { + if ((coordX>0 && coordX<270) && (coordY>0 && coordY<460)) + { + ledState = true; delay(50); + } + + if ((coordX>0 && coordX<270) && (coordY>510 && coordY< 880)) + { + ledState = false; delay(50); + } + + if ((coordX>380 && coordX<930) && (coordY>0 && coordY<300)) + { + red=map(coordX, 380, 930, 0, 255); + } + + if ((coordX>380 && coordX<930) && (coordY>350 && coordY<590)) + { + green=map(coordX, 380, 930, 0, 255); + } + + if ((coordX>380 && coordX<930) && (coordY>640 && coordY<880)) + { + blue=map(coordX, 380, 930, 0, 255); + } + + delay(10); +} + + if (ledState) { + analogWrite(pinR, red); + analogWrite(pinG, green); + analogWrite(pinB, blue); + } + else { + analogWrite(pinR, 0); + analogWrite(pinG, 0); + analogWrite(pinB, 0); + } +} + +// return TRUE if touched, and set coordinates to touchX and touchY +boolean touch() +{ + boolean touch = false; + + // get horizontal co-ordinates + + pinMode(Top, INPUT); // Top and Bottom to high impedance + pinMode(Bottom, INPUT); + + pinMode(Left, OUTPUT); + digitalWrite(Left, LOW); // Set Left to low + + pinMode(Right, OUTPUT); // Set right to +5v + digitalWrite(Right, HIGH); + + + delay(3); + coordX = analogRead(topInput); + + // get vertical co-ordinates + + pinMode(Right, INPUT); // left and right to high impedance + pinMode(Left, INPUT); + + pinMode(Bottom, OUTPUT); // set Bottom to Gnd + digitalWrite(Bottom, LOW); + + pinMode(Top, OUTPUT); // set Top to +5v + digitalWrite(Top, HIGH); + + + delay(3); + coordY = analogRead(rightInput); + + // if co-ordinates read are less than 1000 and greater than 24 + // then the screen has been touched + if(coordX < 1000 && coordX > 24 && coordY < 1000 && coordY > 24) {touch = true;} + + return touch; +} + + + diff --git a/Project_36/Project_36.ino b/Project_36/Project_36.ino new file mode 100644 index 0000000..a54102b --- /dev/null +++ b/Project_36/Project_36.ino @@ -0,0 +1,32 @@ +// Project 36 - Serial Temperature Sensdor + +#define sensorPin 0 + +float Celsius, Fahrenheit, Kelvin; +int sensorValue; + +void setup() { +Serial.begin(9600); +Serial.println("Initialising....."); +} + +void loop() { + + GetTemp(); + Serial.print("Celsius: "); + Serial.println(Celsius); + Serial.print("Fahrenheit: "); + Serial.println(Fahrenheit); + Serial.println(); + + delay(2000); +} + +void GetTemp() +{ + sensorValue = analogRead(sensorPin); // read the sensor + Kelvin = (((float(sensorValue) / 1023) * 5) * 100); // convert to Kelvin + Celsius = Kelvin - 273.15; // convert to Celsius + Fahrenheit = (Celsius * 1.8) +32; // convert to Fahrenheit +} + diff --git a/Project_37/Project_37.ino b/Project_37/Project_37.ino new file mode 100644 index 0000000..a5fd78a --- /dev/null +++ b/Project_37/Project_37.ino @@ -0,0 +1,100 @@ +Project 37 – One-Wire Digital Temperature Sensor + +#include +#include + +// Data line goes to digital pin 3 +#define ONE_WIRE_BUS 3 + +// Setup a oneWire instance to communicate with any +// OneWire devices (not just Maxim/Dallas temperature ICs) +OneWire oneWire(ONE_WIRE_BUS); + +// Pass our oneWire reference to Dallas Temperature. +DallasTemperature sensors(&oneWire); + +// arrays to hold device addresses +DeviceAddress insideThermometer, outsideThermometer; + +void setup() +{ + // start serial port + Serial.begin(9600); + + // Start up the library + sensors.begin(); + + // locate devices on the bus + Serial.print("Locating devices..."); + Serial.print("Found "); + Serial.print(sensors.getDeviceCount(), DEC); + Serial.println(" devices."); + + if (!sensors.getAddress(insideThermometer, 0)) + { + Serial.println("Unable to find address for Device 0"); + } + + if (!sensors.getAddress(outsideThermometer, 1)) + { + Serial.println("Unable to find address for Device 1"); + } + + // print the addresses of both devices + Serial.print("Device 0 Address: "); + printAddress(insideThermometer); + Serial.println(); + + Serial.print("Device 1 Address: "); + printAddress(outsideThermometer); + Serial.println(); + Serial.println(); +} + +// function to print a device address +void printAddress(DeviceAddress deviceAddress) +{ + for (int i = 0; i < 8; i++) + { + // zero pad the address if necessary + if (deviceAddress[i] < 16) Serial.print("0"); + Serial.print(deviceAddress[i], HEX); + } +} + +// function to print the temperature for a device +void printTemperature(DeviceAddress deviceAddress) +{ + float tempC = sensors.getTempC(deviceAddress); + Serial.print("Temp C: "); + Serial.print(tempC); + Serial.print(" Temp F: "); + Serial.print(DallasTemperature::toFahrenheit(tempC)); +} + +// main function to print information about a device +void printData(DeviceAddress deviceAddress) +{ + Serial.print("Device Address: "); + printAddress(deviceAddress); + Serial.print(" "); + printTemperature(deviceAddress); + Serial.println(); +} + +void loop() +{ + // call sensors.requestTemperatures() to issue a global temperature + // request to all devices on the bus + Serial.print("Requesting temperatures..."); + sensors.requestTemperatures(); + Serial.println("DONE"); + delay(750); + + // print the device information + printData(insideThermometer); + printData(outsideThermometer); + Serial.println(); + delay(1000); +} + diff --git a/Project_38/Project_38.ino b/Project_38/Project_38.ino new file mode 100644 index 0000000..9290b47 --- /dev/null +++ b/Project_38/Project_38.ino @@ -0,0 +1,26 @@ +Project 38 – Simple Ultrasonic Rangefinder + +#define sensorPin 9 + +long pwmRange, inch, cm; + +void setup() { + // Start serial communications + Serial.begin(115200); + pinMode(sensorPin, INPUT); +} + +void loop() { +pwmRange = pulseIn(sensorPin, HIGH); + + // 147uS per inch according to datasheet + inch = pwmRange / 147; + // convert inch to cm + cm = inch * 2.54; + + Serial.print(inch); + Serial.print(" inches "); + Serial.print(cm); + Serial.println(" cm"); +} + diff --git a/Project_39/Project_39.ino b/Project_39/Project_39.ino new file mode 100644 index 0000000..85df796 --- /dev/null +++ b/Project_39/Project_39.ino @@ -0,0 +1,56 @@ +Project 39 – Ultrasonic Distance Display + +#include "LedControl.h" + +#define sensorPin 9 +#define switchPin 7 +#define DataIn 2 +#define CLK 4 +#define LOAD 3 +#define NumChips 1 +#define samples 5.0 + +float pwmRange, averageReading, inch, cm; +LedControl lc=LedControl(DataIn,CLK,LOAD,NumChips); + +void setup() { + // Wakeup the MAX7219 + lc.shutdown(0,false); + // Set it to medium brightness + lc.setIntensity(0,8); + // clear the display + lc.clearDisplay(0); + pinMode(sensorPin, INPUT); + pinMode(switchPin, INPUT); +} + +void loop() { + averageReading = 0; + for (int i = 0; i + +File File1; + +void setup() +{ + Serial.begin(9600); + while (!Serial) { } // wait for serial port to connect. + // Needed for Leonardo only + + Serial.println("Initializing the SD Card..."); + + if (!SD.begin()) { + Serial.println("Initialization Failed!"); + return; + } + Serial.println("Initialization Complete.\n"); + + Serial.println("Looking for file 'testfile.txt'...\n"); + + if (SD.exists("testfile.txt")) { + Serial.println("testfile.txt already exists.\n"); + } + else { + Serial.println("testfile.txt doesn't exist."); + Serial.println("Creating file testfile.txt...\n"); + } + + File1 = SD.open("testfile.txt", FILE_WRITE); + File1.close(); + + + Serial.println("Writing text to file....."); + String dataString; + File1 = SD.open("testfile.txt", FILE_WRITE); + if (File1) { + for (int i=1; i<11; i++) { + dataString = "Test Line "; + dataString += i; + File1.println(dataString); + } + Serial.println("Text written to file.....\n"); + } + File1.close(); + + Serial.println("Reading contents of textfile.txt..."); + File1 = SD.open("testfile.txt"); + + if (File1) { + while (File1.available()) { + Serial.write(File1.read()); + } + File1.close(); + } + // if the file isn't open, pop up an error: + else { + Serial.println("error opening testfile.txt"); + } + + // delete the file: + Serial.println("\nDeleting testfile.txt...\n"); + SD.remove("testfile.txt"); + + if (SD.exists("testfile.txt")){ + Serial.println("testfile.txt still exists."); + } + else { + Serial.println("testfile.txt has been deleted."); + } +} + +void loop() +{ + // Nothing to see here +} + diff --git a/Project_43/Project_43.ino b/Project_43/Project_43.ino new file mode 100644 index 0000000..cc082b6 --- /dev/null +++ b/Project_43/Project_43.ino @@ -0,0 +1,100 @@ +Project 43 – Temperature SD Datalogger + +// DS1307 library by Henning Karlsen + +#include +#include +#include +#include // written by Henningh Karlsen + +#define ONE_WIRE_BUS 3 +#define TEMPERATURE_PRECISION 12 + +File File1; + +// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) +OneWire oneWire(ONE_WIRE_BUS); +// Pass our oneWire reference to Dallas Temperature. +DallasTemperature sensors(&oneWire); + +// arrays to hold device addresses +DeviceAddress insideThermometer = { 0x28, 0x44, 0x12, 0xC2, 0x03, 0x00, 0x00, 0x92 }; +DeviceAddress outsideThermometer = { 0x28, 0xA5, 0x02, 0xC2, 0x03, 0x00, 0x00, 0xF0 }; + + float tempC, tempF; + + // Init the DS1307 +DS1307 rtc(4, 5); + +void setup() { + Serial.println("Initializing the SD Card..."); + + if (!SD.begin()) { + Serial.println("Initialization Failed!"); + return; + } + Serial.println("Initialization Complete.\n"); + + // Set the clock to run-mode + rtc.halt(false); + + Serial.begin(9600); + Serial.println("Type any character to start"); + while (!Serial.available()); + Serial.println(); + + // Start up the sensors library + sensors.begin(); + Serial.println("Initialising Sensors.\n"); + + // set the resolution + sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION); + sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION); + delay(100); + + // Set the time on the RTC. + // Comment out this section if you have already set the time and have a battery backup + // The following lines can be commented out to use the values already stored in the DS1307 + rtc.setDOW(TUESDAY); // Set Day-of-Week to TUESDAY + rtc.setTime(9, 27, 00); // Set the time HH,MM,SS + rtc.setDate(30, 04, 2013); // Set the date DD,MM,YYYY +} + +void getTemperature(DeviceAddress deviceAddress) +{ + sensors.requestTemperatures(); + tempC = sensors.getTempC(deviceAddress); + tempF = DallasTemperature::toFahrenheit(tempC); +} + +void loop() { + File1 = SD.open("TEMPLOG.txt", FILE_WRITE); + Serial.println("File Opened."); + if (File1) { + File1.print(rtc.getDateStr()); + Serial.print(rtc.getDateStr()); + File1.print(", "); + Serial.print(", "); + File1.print(rtc.getTimeStr()); + Serial.print(rtc.getTimeStr()); + File1.print(": Inside: "); + Serial.print(": Inside: "); + getTemperature(insideThermometer); + File1.print(tempC); + Serial.print(tempC); + File1.print("C Outside: "); + Serial.print("C Outside: "); + getTemperature(outsideThermometer); + File1.print(tempC); + Serial.print(tempC); + File1.println(" C"); + Serial.println(" C"); + Serial.println("Data written to file."); + } + File1.close(); + Serial.println("File Closed.\n"); + Serial.println(“Safe to disconnect card”); + delay(10000); + Serial.println(“Card in use, do not disconnect!!”); +} + diff --git a/Project_44/Project_44.ino b/Project_44/Project_44.ino new file mode 100644 index 0000000..165f690 --- /dev/null +++ b/Project_44/Project_44.ino @@ -0,0 +1,16 @@ +Project 44 – Simple RFID Reader + +char val = 0; // value read for serial port + +void setup() { + Serial.begin(9600); +} + +void loop () { + + if(Serial.available() > 0) { + val = Serial.read(); // read from the serial port + Serial.write(val); // and print it to the monitor + } +} + diff --git a/Project_45/Project_45.ino b/Project_45/Project_45.ino new file mode 100644 index 0000000..2174d13 --- /dev/null +++ b/Project_45/Project_45.ino @@ -0,0 +1,107 @@ +//Project 45 — Access Control System + +#define lockPin 7 +#define speakerPin 9 +#define tx 3 +#define rx 2 +#define unlockLength 2000 + +#include + +SoftwareSerial rfidReader = SoftwareSerial(rx, tx); + +int users = 3; + +char* cards[] = { // valid cards + "3D00768B53", + "3D00251C27", + "3D0029E6BF", +}; + +char* names[] = { // cardholder names + "Tom Smith", + "Dick Jones", + "Harry Roberts" +}; + +void setup() { + pinMode (lockPin, OUTPUT); + pinMode (speakerPin, OUTPUT); + digitalWrite(lockPin, LOW); + Serial.begin(9600); + rfidReader.begin(9600); +} + +void loop() { + char cardNum[10]; // array to hold card number + byte cardBytes[6]; // byte version of card number + checksum + int index=0; // current digit + byte byteIn=0; // byte read from RFID + byte lastByte=0; // the last byte read + byte checksum = 0; // checksum result stored here + + if (rfidReader.read()==2) { // read the RFID reader + while(index<12) { // 12 digits in unique serial number + byteIn = rfidReader.read(); // store value in byteIn + if ((byteIn==1) || (byteIn==2) || (byteIn==10) || (byteIn==13)) {return;} + // if STX, ETX, CR or LF break + if (index<10) {cardNum[index]=byteIn;} // store first 10 HEX digits only (last 2 are checksum) + // convert ascii hex to integer hex value + if ((byteIn>='0') && (byteIn<='9')) { + byteIn -= '0'; + } + else if ((byteIn>='A') && (byteIn<='F')) { + byteIn = (byteIn+10)-'A'; + } + if ((index & 1) == 1) { // if odd number merge 2 4 bit digits into 8 bit byte +// move the last digit 4 bits left and add new digit +cardBytes[index/2]= (byteIn | (lastByte<<4)); + if (index<10) {checksum ^= cardBytes[index/2];} // tot up the checksum value + } + lastByte=byteIn; // store the last byte read + index++; // increment the index + // if we have reached the end of all digits add a null terminator + if (index==12) {cardNum[10] = '\0';} + } + + Serial.println(cardNum); // print the card number + int cardIndex =checkCard(cardNum); // check if card is valid and return index number + if(cardIndex>=0 && (cardBytes[5]==checksum)) { // if card number and checksum are valid + Serial.println("Card Validated"); + Serial.print("User: "); + Serial.println(names[cardIndex]); // print the relevant name + unlock(); // unlock the door + Serial.println(); + } + else { + Serial.println("Card INVALID"); + tone(speakerPin, 250, 250); + delay(250); + tone(speakerPin, 150, 250); + Serial.println(); + } + } +} + +// Check the detected card against all known to be valid card numbers +// Return the array index number of a matched card number +// or a negative value to indicate a non matching card number +int checkCard(char cardNum[10]) +{ + for (int x=0; x<=users; x++) + { + if(strcmp(cardNum, cards[x])==0) + { + return (x); + } + } + return (-1); +} + +void unlock() { + tone(speakerPin, 1000, 500); + digitalWrite(lockPin, HIGH); + delay(unlockLength); + digitalWrite(lockPin, LOW); +} + diff --git a/Project_46/Project_46.ino b/Project_46/Project_46.ino new file mode 100644 index 0000000..d8ceea9 --- /dev/null +++ b/Project_46/Project_46.ino @@ -0,0 +1,114 @@ +//Project 46 – Ethernet Shield +// Project 46 – Based on the Arduino Webserver example by David A. Mellis and Tom Igoe + +#include +#include +#include +#include + +// Data wire is plugged into pin 3 on the Arduino +#define ONE_WIRE_BUS 3 +#define TEMPERATURE_PRECISION 12 + +float tempC, tempF; + +// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) +OneWire oneWire(ONE_WIRE_BUS); +// Pass our oneWire reference to Dallas Temperature. +DallasTemperature sensors(&oneWire); + +// arrays to hold device addresses +DeviceAddress insideThermometer = { 0x10, 0x7A, 0x3B, 0xA9, 0x01, 0x08, 0x00, 0xBF }; +DeviceAddress outsideThermometer = { 0x10, 0xCD, 0x39, 0xA9, 0x01, 0x08, 0x00, 0xBE}; + +byte mac[] = { 0x48, 0xC2, 0xA1, 0xF3, 0x8D, 0xB7 }; +byte ip[] = { 192,168,0, 104 }; + +// Start the server on port 80 +EthernetServer server(80); + +void setup() +{ + // Begin ethernet and server + Ethernet.begin(mac, ip); + server.begin(); + // Start up the sensors library + sensors.begin(); + // set the resolution + sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION); + sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION); +} + +// function to get the temperature for a device +void getTemperature(DeviceAddress deviceAddress) +{ + tempC = sensors.getTempC(deviceAddress); + tempF = DallasTemperature::toFahrenheit(tempC); +} +void loop() +{ + sensors.requestTemperatures(); + + // listen for incoming clients + EthernetClient client = server.available(); + if (client) { + // an http request ends with a blank line + boolean BlankLine = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + + // If line is blank and end of line is newline character '\n' = end of HTTP request + if (c == '\n' && BlankLine) { + getTemperature(insideThermometer); + getTemperature(outsideThermometer); + // Display internal temp + client.println("HTTP/1.1 200 OK\n"); // Standard HTTP response + client.println("Content-Type: text/html\n"); + client.println("\n"); + client.println(""); + client.println(""); + client.println(""); + + client.println("Arduino Web Server"); + client.println(""); + client.println(""); + client.println("

Arduino Web Server

"); + client.println("

Internal Temperature

"); + client.println("Temp C:"); + client.println(tempC); + client.println("
"); + client.println("Temp F:"); + client.println(tempF); + client.println("
"); + // Display external temp + client.println("

External Temperature

"); + client.println("Temp C:"); + client.println(tempC); + client.println("
"); + client.println("Temp F:"); + client.println(tempF); + client.println("
"); + client.println(""); + client.println(""); + + break; + } + if (c == '\n') { + // Starting a new line + BlankLine = true; + } + elseif (c != '\r') { + // Current line has a character in it + BlankLine = false; + } + } + } + // Allow time for the browser to receive data + delay(10); + // Close connection + client.stop(); + } +} + + diff --git a/Project_47/Project_47.ino b/Project_47/Project_47.ino new file mode 100644 index 0000000..01927fd --- /dev/null +++ b/Project_47/Project_47.ino @@ -0,0 +1,97 @@ +//Project 47 — Internet Weather Display + +// Project 47 - Based on the Xively Arduino examples + +#include +#include +#include +#include +#include +#include + +#define SHARE_FEED_ID 128497 // this is your xively feed ID that you want to share to +#define xivelyKey "_WlvrG2Nw0RxPYKGGDMUNLqHDtl8sDcyXGSAKxvYU1ZtYz0g" // fill in your API key + +char sensorId1[] = "IntTempC"; +char sensorId2[] = "IntTempF"; +char sensorId3[] = "ExtTempC"; +char sensorId4[] = "ExtTempF"; +XivelyDatastream datastreams[] = { + XivelyDatastream(sensorId1, strlen(sensorId1), DATASTREAM_FLOAT), + XivelyDatastream(sensorId2, strlen(sensorId2), DATASTREAM_FLOAT), + XivelyDatastream(sensorId3, strlen(sensorId3), DATASTREAM_FLOAT), + XivelyDatastream(sensorId4, strlen(sensorId4), DATASTREAM_FLOAT) +}; +// Finally, wrap the datastreams into a feed +XivelyFeed feed(SHARE_FEED_ID, datastreams, 4 /* number of datastreams */); + +// Data wire is plugged into pin 3 on the Arduino +#define ONE_WIRE_BUS 3 +#define TEMPERATURE_PRECISION 12 + +// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) +OneWire oneWire(ONE_WIRE_BUS); + +// Pass our oneWire reference to Dallas Temperature. +DallasTemperature sensors(&oneWire); + +// arrays to hold device addresses +DeviceAddress insideThermometer = { 0x28, 0x44, 0x12, 0xC2, 0x03, 0x00, 0x00, 0x92 }; +DeviceAddress outsideThermometer = { 0x28, 0xA5, 0x02, 0xC2, 0x03, 0x00, 0x00, 0xF0 }; + +unsigned int interval; +float itempC, itempF, etempC, etempF; + +byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0xF7, 0x38 }; // make sure this is unique on your network + +EthernetClient localClient; +XivelyClient xivelyclient(localClient); + +void setup() +{ + Serial.begin(9600); + Serial.println("Starting 4 stream data upload to Xively..."); + Serial.println(); + while (Ethernet.begin(mac) != 1) + { + Serial.println("Error getting IP address via DHCP, trying again..."); + delay(15000); + } + // Start up the sensors library + sensors.begin(); + // set the resolution + sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION); + sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION); + delay(100); +} + +void xively_in_out() { + getTemperatures(); + datastreams[0].setFloat(itempC); + datastreams[1].setFloat(itempF); + datastreams[2].setFloat(etempC); + datastreams[3].setFloat(etempF); + xivelyclient.put(feed, xivelyKey); + Serial.println("Read sensor value "); + Serial.println(datastreams[0].getFloat()); + Serial.println(datastreams[1].getFloat()); + Serial.println(datastreams[2].getFloat()); + Serial.println(datastreams[3].getFloat()); + delay(10000); +} + +// function to get the temperature for a device +void getTemperatures() +{ + sensors.requestTemperatures(); + itempC = sensors.getTempC(insideThermometer); + itempF = DallasTemperature::toFahrenheit(itempC); + etempC = sensors.getTempC(outsideThermometer); + etempF = DallasTemperature::toFahrenheit(etempC); +} + +void loop() +{ + xively_in_out(); +} + diff --git a/Project_48/Project_48.ino b/Project_48/Project_48.ino new file mode 100644 index 0000000..e80640f --- /dev/null +++ b/Project_48/Project_48.ino @@ -0,0 +1,124 @@ +//Project 48 — Email Alert System + +#include +#include +#include +#include + +#define time 1000 +#define emailInterval 60 +#define HighThreshold 28 +#define LowThreshold 10 + + +// Data wire is plugged into pin 3 on the Arduino +#define ONE_WIRE_BUS 3 +#define TEMPERATURE_PRECISION 12 + +float tempC, tempF; +char message1[35], message2[35]; +char subject[] = "ARDUINO: TEMPERATURE ALERT!!\0"; +unsigned long lastMessage; + + +// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) +OneWire oneWire(ONE_WIRE_BUS); + +// Pass our oneWire reference to Dallas Temperature. +DallasTemperature sensors(&oneWire); + +// arrays to hold device addresses +DeviceAddress insideThermometer = { 0x28, 0x44, 0x12, 0xC2, 0x03, 0x00, 0x00, 0x92 }; + +byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0xF7, 0x38 }; +byte ip[] = { 192,168,0, 104 }; +byte server[] = { 10, 254, 30, 60 }; // Mail server address. Change this to your own mail servers IP. + +EthernetClient client; + +void sendEmail(char subject[], char message1[], char message2[], float temp) { + Serial.println("connecting..."); + + if (client.connect(server, 25)) { + Serial.println("connected"); + client.println("EHLO MYSERVER"); delay(time); + client.println("AUTH LOGIN"); delay(time); + client.println("lcbWNybbWl2JttnRzLmNvrZSbQ=="); delay(time); + client.println("GV0yVGbjLlnZ2VEw"); delay(time); + client.println("MAIL FROM:"); delay(time); + client.println("RCPT TO:"); delay(time); + client.println("DATA"); delay(time); + client.println("From: < sales@earthshineelectronics.com >"); delay(time); + client.println("To: < fred@crunchytoad.com >"); delay(time); + client.print("SUBJECT: "); + client.println(subject); delay(time); + client.println(); delay(time); + client.println(message1); delay(time); + client.println(message2); delay(time); + client.print("Temperature: "); + client.println(temp); delay(time); + client.println("."); delay(time); + client.println("QUIT"); delay(time); + Serial.println("Email sent."); + lastMessage=millis(); + } else { + Serial.println("connection failed"); + } + +} + +void checkEmail() { + while (client.available()) { + char c = client.read(); + Serial.print(c); + } + + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + } +} + +// function to get the temperature for a device +void getTemperature(DeviceAddress deviceAddress) +{ + tempC = sensors.getTempC(deviceAddress); + tempF = DallasTemperature::toFahrenheit(tempC); +} + +void setup() +{ + lastMessage = 0; + Ethernet.begin(mac, ip); + Serial.begin(9600); + + // Start up the sensors library + sensors.begin(); + // set the resolution + sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION); + + delay(1000); +} + +void loop() +{ + sensors.requestTemperatures(); + getTemperature(insideThermometer); + Serial.println(tempC); + if (tempC >= HighThreshold && (millis()>(lastMessage+(emailInterval*1000)))) { + Serial.println("High Threshhold Exceeded"); + char message1[] = "Temperature Sensor\0"; + char message2[] = "High Threshold Exceeded\0"; + sendEmail(subject, message1, message2, tempC); + } + else if (tempC<= LowThreshold && (millis()>(lastMessage+(emailInterval*1000)))) { + Serial.println("Low Threshhold Exceeded"); + char message1[] = "Temperature Sensor\0"; + char message2[] = "Low Threshold Exceeded\0"; + sendEmail(subject, message1, message2, tempC); + } + + if (client.available()) {checkEmail();} +} + diff --git a/Project_49/Project_49.ino b/Project_49/Project_49.ino new file mode 100644 index 0000000..41e98f2 --- /dev/null +++ b/Project_49/Project_49.ino @@ -0,0 +1,100 @@ +//Project 49 — Twitterbot + +#include +#include +#include +#include +#include + +// Data wire is plugged into pin 3 on the Arduino +#define ONE_WIRE_BUS 3 +#define TEMPERATURE_PRECISION 12 + +float itempC, itempF, etempC, etempF; +boolean firstTweet = true; + +// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) +OneWire oneWire(ONE_WIRE_BUS); + +// Pass our oneWire reference to Dallas Temperature. +DallasTemperature sensors(&oneWire); + +// arrays to hold device addresses + +DeviceAddress insideThermometer = { 0x28, 0x44, 0x12, 0xC2, 0x03, 0x00, 0x00, 0x92 }; +DeviceAddress outsideThermometer = { 0x28, 0xA5, 0x02, 0xC2, 0x03, 0x00, 0x00, 0xF0 }; + +byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0xF7, 0x38 }; + +// Your Token to Tweet (get it from http://arduino-tweet.appspot.com/) +Twitter twitter("19735326-neITsUBnLTZHgN9UGaRkcGvAe9vYuaRP7E55K26J"); // DuinoBot + +unsigned long interval = 600000; // 10 minutes +unsigned long lastTime; // time since last tweet + +// Message to post +char message[140], serialString[60]; + +// function to get the temperature for a device +void getTemperatures() +{ + itempC = sensors.getTempC(insideThermometer); + itempF = DallasTemperature::toFahrenheit(itempC); + etempC = sensors.getTempC(outsideThermometer); + etempF = DallasTemperature::toFahrenheit(etempC); +} + +void tweet(char msg[]) { + Serial.println("connecting ..."); + if (twitter.post(msg)) { + int status = twitter.wait(); + if (status == 200) { + Serial.println("OK. Tweet sent."); + Serial.println(); + lastTime = millis(); + firstTweet = false; + } else { + Serial.print("failed : code "); + Serial.println(status); + } + } else { + Serial.println("connection failed."); + } +} + +void setup() +{ + Ethernet.begin(mac); + Serial.begin(9600); + sensors.begin(); + // set the resolution + sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION); + sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION); + sensors.requestTemperatures(); + + getTemperatures(); + + while (firstTweet) { + 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); + } +} + +void loop() +{ + Ethernet.maintain(); + sensors.requestTemperatures(); + sprintf(serialString, "Internal Temp: %d C %d F. External Temp: %d C %d F", int(itempC), int(itempF), int(etempC), int(etempF)); + delay(500); + Serial.println(serialString); + Serial.println(); + + if (millis() >= (lastTime + interval)) { + 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()); + delay(500); + tweet(message); + } + + delay(10000); // 10 seconds +} + diff --git a/Project_50/Project_50.ino b/Project_50/Project_50.ino new file mode 100644 index 0000000..9537cec --- /dev/null +++ b/Project_50/Project_50.ino @@ -0,0 +1,198 @@ +//Project 50 – RSS Weather Reader + +// Thanks to Bob S. for original code +// Get current weather observation for Edwards AFB from weather.gov in XML format + +// Include description files for other libraries used (if any) +//#include +#include +#include + +// Max string length may have to be adjusted depending on data to be extracted +#define MAX_STRING_LEN 20 + +// Setup vars +char tagStr[MAX_STRING_LEN] = ""; +char dataStr[MAX_STRING_LEN] = ""; +char tmpStr[MAX_STRING_LEN] = ""; +char endTag[3] = {'<', '/', '\0'}; +int len; + +// Flags to differentiate XML tags from document elements (ie. data) +boolean tagFlag = false; +boolean dataFlag = false; + +// Ethernet vars +byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0xF7, 0x38 }; +byte ip[] = {192, 168, 0, 35}; +byte server[] = { 140, 90, 113, 200 }; // www.weather.gov + +// Start ethernet client +EthernetClient client; + +void setup() +{ + Serial.begin(9600); + Serial.println("Starting Weather RSS Reader"); + Serial.println("connecting..."); + Ethernet.begin(mac, ip); + delay(1000); + + if (client.connect(server, 80)) { + Serial.println("connected"); + Serial.println("Current weather at Edwards AFB:"); + client.println("GET /xml/current_obs/KEDW.xml HTTP/1.0"); + client.println(); + delay(2000); + } else { + Serial.println("connection failed"); + } +} + +void loop() { + + // Read serial data in from web: + while (client.available()) { + serialEvent(); + } + + if (!client.connected()) { + + client.stop(); + + for (int t=0; t<15; t++) { + delay(60000); // 1 minute + } + + + if (client.connect(server, 80)) { + client.println("GET /xml/current_obs/KEDW.xml HTTP/1.0"); + client.println(); + delay(2000); + } else { + Serial.println("Reconnection failed"); + } + } +} + +// Process each char from web +void serialEvent() { + // Read a char + char inChar = client.read(); + + if (inChar == '<') { + addChar(inChar, tmpStr); + tagFlag = true; + dataFlag = false; + + } else if (inChar == '>') { + addChar(inChar, tmpStr); + + if (tagFlag) { + strncpy(tagStr, tmpStr, strlen(tmpStr)+1); + } + + // Clear tmp + clearStr(tmpStr); + + tagFlag = false; + dataFlag = true; + + } else if (inChar != 10) { + if (tagFlag) { + // Add tag char to string + addChar(inChar, tmpStr); + + // Check for end tag, ignore it + if ( tagFlag && strcmp(tmpStr, endTag) == 0 ) { + clearStr(tmpStr); + tagFlag = false; + dataFlag = false; + } + } + + if (dataFlag) { + // Add data char to string + addChar(inChar, dataStr); + } + } + + // If a LF, process the line + if (inChar == 10 ) { + + // Find specific tags and print data + if (matchTag("")) { + Serial.print("TempF: "); + Serial.print(dataStr); + } + if (matchTag("")) { + Serial.print(", TempC: "); + Serial.print(dataStr); + } + if (matchTag("")) { + Serial.print(", Humidity: "); + Serial.print(dataStr); + } + if (matchTag("")) { + Serial.print(", Pressure: "); + Serial.print(dataStr); + Serial.println(""); + } + + // Clear all strings + clearStr(tmpStr); + clearStr(tagStr); + clearStr(dataStr); + + // Clear Flags + tagFlag = false; + dataFlag = false; + } +} + +// Function to clear a string +void clearStr (char* str) { + int len = strlen(str); + for (int c = 0; c < len; c++) { + str[c] = 0; + } +} + +//Function to add a char to a string and check its length +void addChar (char ch, char* str) { + char *tagMsg = ""; + char *dataMsg = "-TRUNCATED_DATA-"; + + // Check the max size of the string to make sure it doesn't grow too + // big. If string is beyond MAX_STRING_LEN assume it is unimportant + // and replace it with a warning message. + if (strlen(str) > MAX_STRING_LEN - 2) { + if (tagFlag) { + clearStr(tagStr); + strcpy(tagStr,tagMsg); + } + if (dataFlag) { + clearStr(dataStr); + strcpy(dataStr,dataMsg); + } + + // Clear the temp buffer and flags to stop current processing + clearStr(tmpStr); + tagFlag = false; + dataFlag = false; + + } else { + // Add char to string + str[strlen(str)] = ch; + } +} + +// Function to check the current tag for a specific string +boolean matchTag (char* searchTag) { + if ( strcmp(tagStr, searchTag) == 0 ) { + return true; + } else { + return false; + } +} + diff --git a/README.md b/README.md new file mode 100644 index 0000000..952f50a --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +#Apress Source Code + +This repository accompanies [*Beginning Arduino*](http://www.apress.com/9781430250166) by Michael McRoberts (Apress, 2013). + +![Cover image](9781430250166.jpg) + +Download the files as a zip using the green button, or clone the repository to your machine using Git. + +##Releases + +Release v1.0 corresponds to the code in the published book, without corrections or updates. + +##Contributions + +See the file Contributing.md for more information on how you can contribute to this repository. diff --git a/contributing.md b/contributing.md new file mode 100644 index 0000000..f6005ad --- /dev/null +++ b/contributing.md @@ -0,0 +1,14 @@ +# Contributing to Apress Source Code + +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. + +## How to Contribute + +1. Make sure you have a GitHub account. +2. Fork the repository for the relevant book. +3. Create a new branch on which to make your change, e.g. +`git checkout -b my_code_contribution` +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. +5. Submit a pull request. + +Thank you for your contribution! \ No newline at end of file