├── .gitattributes ├── 9781484239599.jpg ├── Chapter 1 ├── Listing1-1 │ └── Listing1-1.ino └── Listing1-2 │ └── Listing1-2.ino ├── Chapter 10 ├── Listing10-1 │ └── Listing10-1.ino ├── Listing10-2 │ └── Listing10-2.ino ├── Listing10-3 │ └── Listing10-3.ino ├── Listing10-4 │ └── Listing10-4.ino └── Listing10-5 │ └── Listing10-5.ino ├── Chapter 11 ├── Listing11-1 │ └── Listing11-1.ino ├── Listing11-2 │ └── Listing11-2.ino ├── Listing11-3 │ └── Listing11-3.ino └── Listing11-4 │ └── Listing11-4.ino ├── Chapter 12 ├── Listing12-1 │ └── Listing12-1.ino ├── Listing12-2 │ └── Listing12-2.ino ├── Listing12-3 │ └── Listing12-3.ino ├── Listing12-4 │ └── Listing12-4.ino ├── Listing12-5 │ └── Listing12-5.ino └── Listing12-6 │ └── Listing12-6.ino ├── Chapter 13 ├── Listing13-1 │ └── Listing13-1.ino ├── Listing13-2 │ └── Listing13-2.ino ├── Listing13-3 │ └── Listing13-3.ino └── Listing13-4 │ └── Listing13-4.ino ├── Chapter 14 ├── Listing14-1 │ └── Listing14-1.ino ├── Listing14-2 │ └── Listing14-2.ino └── Listing14-3 │ └── Listing14-3.ino ├── Chapter 16 ├── Bluetooth_devleoper │ └── Bluetooth_developer.ino ├── Listing16-1 │ └── Listing16-1.ino ├── Listing16-2 │ └── Listing16-2.ino ├── Listing16-3 │ └── Listing16-3.ino ├── Listing16-4 │ └── Listing16-4.ino ├── Listing16-5 │ └── Listing16-5.ino ├── Listing16-6 │ └── Listing16-6.ino └── Listing16-7 │ └── Listing16-7.ino ├── Chapter 17 ├── Listing17-1 │ └── Listing17-1.ino ├── Listing_receive_in_Table17-1 │ └── Listing_receive_in_Table17-1.ino ├── Listing_receive_transmit_in_Table17-3 │ └── Listing_receive_transmit_in_Table17-3.ino ├── Listing_receive_transmit_in_Table17-4 │ └── Listing_receive_transmit_in_Table17-4.ino ├── Listing_transmit_in_Table17-1 │ └── Listing_transmit_in_Table17-1.ino ├── Listing_transmit_receive_in_Table17-3 │ └── Listing_transmit_receive_in_Table17-3.ino └── Listing_transmit_receive_in_Table17-4 │ └── Listing_transmit_receive_in_Table17-4.ino ├── Chapter 19 ├── Listing19-1 │ └── Listing19-1.ino ├── Listing19-3 │ └── Listing19-3.ino ├── Listing19-4 │ └── Listing19-4.ino ├── Listing19-5 │ └── Listing19-5.ino └── Listing19-6 │ └── Listing19-6.ino ├── Chapter 2 ├── Listing2-1 │ └── Listing2-1.ino ├── Listing2-2 │ └── Listing2-2.ino ├── Listing2-3 │ └── Listing2-3.ino ├── Listing2-4 │ └── Listing2-4.ino └── Listing2-5 │ └── Listing2-5.ino ├── Chapter 20 ├── Listing20-1 │ └── Listing20-1.ino ├── Listing20-2 │ └── Listing20-2.ino ├── Listing20-3 │ └── Listing20-3.ino ├── Listing20-4 │ └── Listing20-4.ino ├── Listing20-5 │ └── Listing20-5.ino ├── Listing20-6 │ └── Listing20-6.ino ├── Listing20-7 │ └── Listing20-7.ino ├── Listing20-8 │ └── Listing20-8.ino └── Listing20-9 │ └── Listing20-9.ino ├── Chapter 21 ├── Listing21-1 │ └── Listing21-1.ino └── Listing21-3 │ └── Listing21-3.ino ├── Chapter 22 ├── Listing22-1 │ └── Listing22-1.ino ├── Listing22-10 │ └── Listing22-10.ino ├── Listing22-4 │ ├── Listing22-4.ino │ └── notes.h ├── Listing22-5 │ └── Listing22-5.ino ├── Listing22-6 │ └── Listing22-6.ino ├── Listing22-7 │ └── Listing22-7.ino ├── Listing22-8 │ └── Listing22-8.ino └── Listing22-9 │ └── Listing22-9.ino ├── Chapter 23 ├── Listing23-1 │ └── Listing23-1.ino ├── Listing23-2 │ └── Listing23-2.ino ├── Listing23-3 │ └── Listing23-3.ino ├── Listing23-4 │ └── Listing23-4.ino ├── Listing23-5 │ └── Listing23-5.ino ├── Listing23-6 │ └── Listing23-6.ino ├── Listing23-7_and_23-8 │ └── Listing23-7_and_23-8.ino ├── Listing23-9 │ └── Listing23-9.ino ├── Listing_Timerone_in_Table23-5 │ └── Listing_Timerone_in_Table23-5.ino └── Listing_millis_in_Table23-5 │ └── Listing_millis_in_Table23-5.ino ├── Chapter 24 ├── Listing24-1 │ └── Listing24-1.ino ├── Listing24-2 │ └── Listing24-2.ino ├── Listing24-3 │ └── Listing24-3.ino ├── Listing24-4 │ └── Listing24-4.ino └── Listing24-5 │ └── Listing24-5.ino ├── Chapter 25 ├── Listing25-1 │ └── Listing25-1.ino ├── Listing25-2 │ └── Listing25-2.ino ├── Listing25-3 │ └── Listing25-3.ino ├── Listing25-4 │ └── Listing25-4.ino ├── Listing25-5 │ ├── Listing25-5.ino │ └── htmlCode.h ├── Listing25-6 │ └── Listing25-6.ino ├── Listing25-7 │ └── Listing25-7.ino └── Listing25-8 │ └── Listing25-8.ino ├── Chapter 3 ├── Listing3-1 │ └── Listing3-1.ino ├── Listing3-10 │ └── Listing3-10.ino ├── Listing3-11 │ └── Listing3-11.ino ├── Listing3-12 │ └── Listing3-12.ino ├── Listing3-13 │ └── Listing3-13.ino ├── Listing3-2 │ └── Listing3-2.ino ├── Listing3-3 │ └── Listing3-3.ino ├── Listing3-4 │ └── Listing3-4.ino ├── Listing3-5 │ └── Listing3-5.ino ├── Listing3-6 │ └── Listing3-6.ino ├── Listing3-7 │ └── Listing3-7.ino ├── Listing3-8 │ └── Listing3-8.ino └── Listing3-9 │ └── Listing3-9.ino ├── Chapter 4 ├── Listing4-1 │ └── Listing4-1.ino ├── Listing4-2 │ └── Listing4-2.ino ├── Listing4-3 │ └── Listing4-3.ino ├── Listing4-4 │ └── Listing4-4.ino ├── Listing4-5 │ └── Listing4-5.ino ├── Listing4-6 │ └── Listing4-6.ino ├── Listing4-7 │ └── Listing4-7.ino └── Listing4-8 │ └── Listing4-8.ino ├── Chapter 5 ├── Listing5-1 │ └── Listing5-1.ino ├── Listing5-2 │ └── Listing5-2.ino ├── Listing5-3 │ └── Listing5-3.ino ├── Listing5-4 │ └── Listing5-4.ino └── Listing_in_Table5.2 │ └── Listing_in_Table5.2.ino ├── Chapter 6 ├── Listing6-1 │ └── Listing6-1.ino ├── Listing6-4 │ └── Listing6-4.ino └── Listing6-5 │ └── Listing6-5.ino ├── Chapter 7 ├── Listing7-1 │ └── Listing7-1.ino ├── Listing7-2 │ └── Listing7-2.ino ├── Listing7-3 │ └── Listing7-3.ino └── Listing7-4 │ ├── Listing7-4.ino │ └── letters.h ├── Chapter 8 ├── Listing8-1 │ └── Listing8-1.ino ├── Listing8-2 │ └── Listing8-2.ino ├── Listing8-3 │ └── Listing8-3.ino ├── Listing8-4 │ └── Listing8-4.ino ├── Listing8-5 │ └── Listing8-5.ino └── Listing8-7 │ └── Listing8-7.ino ├── Chapter 9 ├── Listing9-1 │ └── Listing9-1.ino └── Listing9-2 │ └── Listing9-2.ino ├── Contributing.md ├── LICENSE.txt ├── README.md └── Updates ├── Arduino Applied corrections.pdf └── Arduino Applied updates.pdf /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /9781484239599.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/arduino-applied/b81f3caabce3869b21680bc544296fab5b7836f4/9781484239599.jpg -------------------------------------------------------------------------------- /Chapter 1/Listing1-1/Listing1-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: Sketch to blink an LED 3 | * Description: Blinks an LED on pin 11 4 | * Created on: October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 1 - Introduction 8 | ******************************************************************************/ 9 | 10 | int LEDpin = 11; // define LEDpin with integer value 11 11 | void setup() // setup function runs once 12 | { 13 | pinMode(LEDpin, OUTPUT); // define LEDpin as output 14 | } 15 | 16 | void loop() // loop function runs continuously 17 | { 18 | digitalWrite(LEDpin, HIGH); // set pin state HIGH to turn LED on 19 | delay(1000); // wait for a second = 1000 ms 20 | digitalWrite(LEDpin, LOW); // set pin state LOW to turn LED off 21 | delay(1000); 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Chapter 1/Listing1-2/Listing1-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: LED brightness and PWM 3 | * Description: LED brightness changed by PWM with controlled rate of change 4 | * Created on: October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 1 - Introduction 8 | ******************************************************************************/ 9 | 10 | int LEDpin = 11; // define LED pin 11 | int bright = 0; // initial value for LED brightness 12 | int increm = 5; // incremental change in PWM frequency 13 | int time = 25; // define time period between changes 14 | 15 | void setup() // setup function runs once 16 | { 17 | pinMode(LEDpin, OUTPUT); // LED pin as output 18 | } 19 | 20 | void loop() // loop function runs continuously 21 | { 22 | analogWrite(LEDpin, bright); // set LED brightness with PWM 23 | delay(time); // wait for the time period 24 | bright = bright + increm; // increment LED brightness 25 | // reverse increment at brightness = 0 or 255 26 | if(bright <=0 || bright >= 255) increm = - increm; 27 | } 28 | 29 | 30 | -------------------------------------------------------------------------------- /Chapter 10/Listing10-1/Listing10-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: infrared signal 3 | * Description: read infrared signal and display hexadecimal code of signal 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 10 - Infrared sensor 8 | ******************************************************************************/ 9 | 10 | #include // include IRremote library 11 | int IRpin = 6; // IR sensor pin 12 | IRrecv irrecv(IRpin); // associate irrecv with IRremote library 13 | decode_results reading; // IRremote reading 14 | 15 | void setup() 16 | { 17 | Serial.begin(9600); // set baud rate for Serial Monitor 18 | irrecv.enableIRIn(); // initialise the IR receiver 19 | } 20 | 21 | void loop() 22 | { 23 | if(irrecv.decode(&reading)) // read pulsed signal 24 | { 25 | Serial.print("0x"); // print leading 0x for hexadecimal 26 | Serial.println(reading.value, HEX); // print HEX code to Serial Monitor 27 | irrecv.resume(); // receive the next infrared signal 28 | } 29 | delay(1000); // delay before next remote control input 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Chapter 10/Listing10-2/Listing10-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: IR signal and LEDs 3 | * Description: use infrared signals to control switching of LEDs 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 10 - Infrared sensor 8 | ******************************************************************************/ 9 | 10 | #include // include IR library 11 | int IRpin = 6; // IR sensor pin 12 | IRrecv irrecv(IRpin); // map IR receiver to pin 13 | decode_results reading; // IRremote reading 14 | int redLED = 8; 15 | int amberLED = 9; // LED pins 16 | int greenLED = 10; 17 | int colour; 18 | 19 | void setup() 20 | { 21 | irrecv.enableIRIn(); // initialise the IR receiver 22 | pinMode(redLED, OUTPUT); // define LED pins as output 23 | pinMode(amberLED, OUTPUT); 24 | pinMode(greenLED, OUTPUT); 25 | } 26 | 27 | void loop() 28 | { 29 | if(irrecv.decode(&reading)) // read the IR signal 30 | { 31 | switch(reading.value) // switch ... case for button signals 32 | { 33 | case 0xFF30CF: colour = redLED; break; // associate IR codes with LED pins 34 | case 0xFF18E7: colour = amberLED; break; 35 | case 0xFF7A85: colour = greenLED; break; 36 | } 37 | digitalWrite(colour,HIGH); // turn on and off corresponding LED 38 | delay(1000); 39 | digitalWrite(colour,LOW); 40 | } 41 | irrecv.resume(); // receive the next infrared signal 42 | delay(1000); // delay before next remote control input 43 | } 44 | 45 | -------------------------------------------------------------------------------- /Chapter 10/Listing10-3/Listing10-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: IR sensor and LCD display 3 | * Description: display text on LCD based on infrared signal 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 10 - Infrared sensor 8 | ******************************************************************************/ 9 | 10 | #include // include Wire library 11 | #include // include LiquidCrystal_I2C library 12 | #include // include IRremote library 13 | int I2Caddress = 0x3F; // address of I2C bus 14 | int LCDcol = 16; // define the number of LCD columns 15 | int LCDrow = 4; // define the number of LCD rows 16 | // associate lcd with LiquidCrystal_I2C library 17 | LiquidCrystal_I2C lcd(I2Caddress,LCDcol,LCDrow); // define LCD address, size 18 | int IRpin = A0; // IR sensor pin 19 | IRrecv irrecv(IRpin); // associate irrecv with IRremote library 20 | decode_results reading; // IRremote reading 21 | 22 | void setup() 23 | { 24 | lcd.init(); // initialise LCD 25 | irrecv.enableIRIn(); // initialise the IR receiver 26 | } 27 | 28 | void loop() 29 | { 30 | if(irrecv.decode(&reading)) // read the IR signal 31 | { 32 | translateIR(); // function to map signal to display string 33 | irrecv.resume(); // receive the next infrared signal 34 | delay(1000); // delay before next IR signal 35 | } 36 | } 37 | 38 | void translateIR() // function to determine display string 39 | { 40 | switch(reading.value) // switch ... case rather than a series 41 | { // of if ... else instructions 42 | // example IR codes 43 | case 0xFF6897: displ("Outcome "+String(millis()/1000)); break; // string of millis() 44 | case 0xFF30CF: displ("Result "+String(reading.value,HEX)); break; // string of signal 45 | case 0xFF18E7: displ("Event "+String(reading.value,DEC)); break; 46 | default: displ("Not valid"); // default display 47 | } 48 | } 49 | 50 | void displ(String s) // function to display string on LCD 51 | { 52 | lcd.print(s); // display string on LCD 53 | delay(2000); // delay 2000ms 54 | lcd.clear(); // clear LCD display and move cursor to zero position 55 | } 56 | 57 | -------------------------------------------------------------------------------- /Chapter 10/Listing10-4/Listing10-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: IR transmitter 3 | * Description: transmit infrared signals 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 10 - Infrared sensor 8 | ******************************************************************************/ 9 | 10 | #include // include IRremote library 11 | long signal[ ] = {0xFF6897, 0xFF30CF, 0xFF18E7, 0xFF7A85, 0xFF10EF}; 12 | IRsend irsend; // associate irsend with IRremote library 13 | int LEDpin = 7; 14 | 15 | void setup() // nothing in void setup function 16 | { 17 | pinMode(LEDpin, OUTPUT); 18 | } 19 | 20 | void loop() 21 | { 22 | for (int i=0; i<5; i++) // transmit each of the five signals 23 | { 24 | irsend.sendSony(signal[i], 24); // transmit signal with 24 bit length 25 | delay(1000); // delay 1s between signals 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /Chapter 10/Listing10-5/Listing10-5.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: IR emitter and receiver 3 | * Description: determine distance between infrared emitter and receiver 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 10 - Infrared sensor 8 | ******************************************************************************/ 9 | 10 | int IRpin = A5; // IR receiver pin 11 | int reading, dist; 12 | 13 | void setup() 14 | { 15 | Serial.begin(9600); // set Serial Monitor baud rate 16 | } 17 | 18 | void loop() 19 | { 20 | reading = analogRead(IRpin); // reading from IR receiver 21 | if (reading<970) dist = 605*pow(reading, -0.53); // convert reading to distance 22 | else dist =409 - 0.406 * reading; 23 | Serial.print(reading);Serial.print("\t"); // print reading, tab and 24 | Serial.println(dist); // distance to Serial Monitor 25 | delay(100); // delay between readings 26 | } 27 | 28 | -------------------------------------------------------------------------------- /Chapter 11/Listing11-1/Listing11-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: content of MIFARE contactless card 3 | * Description: read and display content of MIFARE contactless card 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 11 - Radio frequency identification 8 | ******************************************************************************/ 9 | 10 | #include // include SPI library 11 | #include // include MFRC522 library 12 | int RSTpin = 9; // reset pin for MFRC522 13 | int SDApin = 10; // serial data pin 14 | // associate mfrc522 with MFRC522 library 15 | MFRC522 mfrc522(SDApin, RSTpin); 16 | 17 | void setup() 18 | { 19 | Serial.begin(9600); // Serial output at 9600 baud 20 | SPI.begin(); // initialise SPI bus 21 | mfrc522.PCD_Init(); // initialise card reader 22 | } 23 | 24 | void loop() 25 | { 26 | if(!mfrc522.PICC_IsNewCardPresent()>0) return; // wait for a new card 27 | if(!mfrc522.PICC_ReadCardSerial()>0) return; // read card content 28 | mfrc522.PICC_DumpToSerial(&(mfrc522.uid)); // print to Serial Monitor 29 | } 30 | 31 | -------------------------------------------------------------------------------- /Chapter 11/Listing11-2/Listing11-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: RFID for accessing a secure site 3 | * Description: identify validity of RFID card and control LEDs 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 11 - Radio frequency identification 8 | ******************************************************************************/ 9 | 10 | #include // include SPI library 11 | #include // include MFRC522 library 12 | int RSTpin = 9; // reset pin for MFRC522 13 | int SDApin = 10; // serial data pin 14 | MFRC522 mfrc522(SDApin, RSTpin); // associate mfrc522 with MFRC522 library 15 | int redLED = 4; // red LED pin 16 | int greenLED = 3; // green LED pin 17 | int nuid = 1; // number of valid cards 18 | String uids[20]; // list of valid UIDs – maximum 20 19 | String uid; 20 | int cardOK, pin, piccType; 21 | int cardRead; // ** for add/delete card sketch 22 | 23 | void setup() 24 | { 25 | Serial.begin(9600); // define Serial output baud rate 26 | SPI.begin(); // initialise SPI bus 27 | mfrc522.PCD_Init(); // initialise MFRC522 28 | pinMode (redLED, OUTPUT); // define LED pins as output 29 | pinMode (greenLED, OUTPUT); 30 | uids[0] = "c049275"; // UIDs of valid cards 31 | } 32 | 33 | void loop() 34 | { 35 | if(!mfrc522.PICC_IsNewCardPresent()>0) return; // wait for a new card 36 | if(!mfrc522.PICC_ReadCardSerial()>0) return; // read new card content 37 | cardID(mfrc522.uid.uidByte, mfrc522.uid.size); // function to read card UID 38 | Serial.print("\nCard UID\t"); // print "card UID" and a tab 39 | Serial.println(uid); // print card UID 40 | piccType = mfrc522.PICC_GetType(mfrc522.uid.sak); // card PICC type 41 | Serial.print("PICC type\t"); // print PICC type 42 | Serial.println(mfrc522.PICC_GetTypeName(piccType)); // card SAK HEX code 43 | Serial.print("SAK code\t"); // print "SAK code" and a tab 44 | Serial.println(mfrc522.uid.sak); // print SAK HEX code 45 | cardOK = 0; 46 | pin = redLED; 47 | for (int i=0; i // include SPI library 11 | #include // include SD library 12 | File file; // associate file with SD library 13 | String filename = "data.csv"; // filename 14 | int CSpin = 10; // chip select pin 15 | int lightPin = A0; // LDR light intensity pin 16 | int tempPin = A1; // temperature sensor pin 17 | int i = 0; // data record counter 18 | int light; 19 | float temp; 20 | String data; 21 | 22 | void setup() 23 | { 24 | Serial.begin(9600); // define Serial output baud rate 25 | Serial.println("checking SD card"); // print message to Serial Monitor 26 | if(SD.begin(CSpin) == 0) // check for presence of SD card 27 | { 28 | Serial.println("Card fail"); // return to void setup() if SD card not found 29 | return; 30 | } 31 | Serial.println("Card OK"); 32 | if(SD.exists(filename)>0) SD.remove(filename); // delete existing file 33 | file = SD.open(filename, FILE_WRITE); // create new file 34 | if(file == 1) // file opened 35 | { 36 | String header = "i, light, temp"; // create column headers 37 | file.println(header); // write column header to SD card 38 | file.close(); // close file after writing to SD card 39 | } 40 | else Serial.println("Couldn't access file"); // file not opened 41 | } 42 | 43 | void loop() 44 | { 45 | i++; // increase data record counter 46 | Serial.print("record ");Serial.println(i); // print record number to Serial Monitor 47 | light = analogRead(lightPin); // light reading 48 | temp = (500.0*analogRead(tempPin))/1023; // temp reading referenced to 5V 49 | data = String(i) + "," + String(light) + "," + String(temp); // create string from readings 50 | file = SD.open(filename, FILE_WRITE); // open data file before writing 51 | file.println(data); // write data string to file 52 | file.close(); // close file after writing to SD card 53 | delay(5000); // delay 5s before next reading 54 | } 55 | 56 | -------------------------------------------------------------------------------- /Chapter 12/Listing12-2/Listing12-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: display content of file 3 | * Description: display content of file data.csv stored on SD card 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 12 - SD card module 8 | ******************************************************************************/ 9 | 10 | #include // include SPI library 11 | #include // include SD library 12 | File file; // associate file with SD library 13 | String filename = "data.csv"; // filename 14 | int CSpin = 10; // chip select pin 15 | 16 | void setup() 17 | { 18 | Serial.begin(9600); // define Serial output baud rate 19 | if(SD.begin(CSpin) == 0) // check for presence of SD card 20 | { 21 | Serial.println("Card fail"); // return to void setup() if SD card not found 22 | return; 23 | } 24 | Serial.println("Card OK"); 25 | file = SD.open(filename); // open file to read 26 | while (file.available()>0) Serial.write(file.read()); // display contents of file 27 | file.close(); // close file after reading 28 | } 29 | 30 | void loop() 31 | { } 32 | -------------------------------------------------------------------------------- /Chapter 12/Listing12-3/Listing12-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: real-time clock module 3 | * Description: display weekday, date and time and temperature with DS3231 RTC 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 12 - SD card module 8 | ******************************************************************************/ 9 | 10 | #include // include DS3231 library 11 | DS3231 rtc(SDA, SCL); // associate rtc with DS3231 library 12 | Time t; 13 | 14 | void setup() 15 | { 16 | Serial.begin(9600); // define Serial output baud rate 17 | rtc.begin(); // start rtc 18 | // rtc.setDOW(THURSDAY) // set weekday 19 | // rtc.setTime(10, 23, 20); // set the time to hh mm ss 20 | // rtc.setDate(10, 5, 2018); // set the date to dd mm yyyy 21 | } 22 | 23 | void loop() 24 | { 25 | Serial.print(rtc.getDOWStr());Serial.print(" "); // weekday 26 | Serial.print(rtc.getDateStr());Serial.print(" "); // date 27 | Serial.print(rtc.getTimeStr());Serial.print("\t"); // time 28 | t = rtc.getTime(); // components of date and time 29 | Serial.print(t.date);Serial.print(" "); // day 30 | Serial.print(rtc.getMonthStr());Serial.print(" (month "); // month as text 31 | Serial.print(t.mon);Serial.print(") "); // month 32 | Serial.print(t.year);Serial.print("\t"); // year 33 | Serial.print(t.hour);Serial.print(":"); // hour 34 | Serial.print(t.min);Serial.print(":"); // minute 35 | Serial.print(t.sec);Serial.print("\t"); // second 36 | Serial.print(rtc.getTemp(),1);Serial.println(" C"); // temperature to 1DP 37 | delay (1000); 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Chapter 12/Listing12-4/Listing12-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: weather station 3 | * Description: stores date and time stamped weather station data on SD card 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 12 - SD card module 8 | ******************************************************************************/ 9 | 10 | #include // include SD library 11 | File file; // associate file with SD library 12 | String filename = "data.csv"; // filename 13 | #include // include DS3231 library 14 | DS3231 rtc(SDA, SCL); // associate rtc with DS3231 library 15 | #include // include dht library 16 | dht DHT; // associate DHT with dht library 17 | int CSpin = 10; // chip select pin for SD card 18 | int lightPin = A3; // light dependent resistor pin 19 | int PCBpin = 6; // PCB mounted DHT11 pin 20 | int i = 0; // data record counter 21 | int check, light, temp, humid; 22 | String data, date, time; 23 | 24 | void setup() 25 | { 26 | Serial.begin(9600); // define Serial output baud rate 27 | rtc.begin(); // start rtc 28 | Serial.println("checking SD card"); // check for presence of SD card 29 | if(SD.begin(CSpin) == 0) 30 | { 31 | Serial.println("Card fail"); // return to void setup() if SD card not found 32 | return; 33 | } 34 | Serial.println("Card OK"); 35 | if(SD.exists(filename)>0) SD.remove(filename); // delete old file 36 | file = SD.open(filename, FILE_WRITE); // create new file 37 | if(file == 1) 38 | { 39 | String header = "record, time, light, temp, humid, on "; // column headers 40 | header = header + String(rtc.getDateStr()); // ... and date 41 | file.println(header); // write column headers to file 42 | file.close(); // close file after writing to SD card 43 | } 44 | else Serial.println("Couldn't access file"); // file not opened 45 | } 46 | 47 | void loop() 48 | { 49 | i++; // increase data record counter 50 | Serial.print("record ");Serial.println(i); // print record number to Serial Monitor 51 | light= analogRead(lightPin); // light intensity reading 52 | check = DHT.read11(PCBpin); 53 | temp = DHT.temperature; // temperature reading 54 | humid = DHT.humidity; // humidity reading 55 | time = rtc.getTimeStr(); // time stamp 56 | // combine measurements into a string 57 | data = String(i) + "," + String(time) + "," + String(light); 58 | data = data + "," + String(temp)+ "," + String(humid); 59 | file = SD.open(filename, FILE_WRITE); // open data file before writing 60 | file.println(data); // write data string to file 61 | file.close(); // close file after writing to SD card 62 | delay(1000);// delay 1s before next reading 63 | } 64 | 65 | -------------------------------------------------------------------------------- /Chapter 12/Listing12-5/Listing12-5.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: incrementing filename 3 | * Description: increment dataN.csv filename when storing file on SD card 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 12 - SD card module 8 | ******************************************************************************/ 9 | 10 | #include // include SPI library 11 | #include // include SD library 12 | File file; // associate file with SD library 13 | int CSpin = 10; // chip select pin for SD card 14 | String filename; 15 | String basefile = "data"; // default filename is data.csv 16 | bool filefound = false; 17 | int filecount = 0; // for incrementing filename 18 | int count = 0; 19 | String data; // data to write to SD card 20 | 21 | void setup() 22 | { 23 | Serial.begin(9600); // define Serial output baud rate 24 | if(SD.begin(CSpin) == 0) 25 | { 26 | Serial.println("Card fail"); // return to void loop() if SD card not found 27 | return; 28 | } 29 | Serial.println("Card OK"); 30 | filename=basefile + ".csv"; // generate filename 31 | // if(SD.exists(filename)>0) SD.remove(filename); // delete and replace file on SD card 32 | while (filefound == 0) // search for file with filename 33 | { 34 | if(SD.exists(filename)>0) // if filename already exists on SD card, 35 | { 36 | filecount++; // then increment filename counter 37 | filename = basefile + String(filecount) + ".csv"; // generate new filename 38 | } 39 | else filefound = true; // flag file with filename located on SD card 40 | } 41 | file = SD.open(filename, FILE_WRITE); // open file on SD card 42 | if(file == 1) 43 | { 44 | Serial.print(filename);Serial.println(" created"); 45 | data = "Count"; // column header 46 | file.println(data); // write column header to file on SD card 47 | file.close(); // close file after writing to SD card 48 | } 49 | else Serial.println("Couldn't access file"); // file not opened 50 | } 51 | 52 | void loop() 53 | { 54 | count = count + 1; // incremental counter 55 | data = String(count); // convert counter to string 56 | File file = SD.open(filename, FILE_WRITE); // open file on SD card 57 | if(file == 1) file.println(data); // write data string to file on SD card 58 | file.close(); // close file on SD card 59 | delay(1000); // delay 1s before next count 60 | } 61 | 62 | -------------------------------------------------------------------------------- /Chapter 12/Listing12-6/Listing12-6.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: display contents of SD card 3 | * Description: display content(directories and file names) of SD card 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 12 - SD card module 8 | ******************************************************************************/ 9 | 10 | #include // include SPI library 11 | #include // include SD library 12 | File file; // associate file with SD library 13 | int CSpin = 10; // chip select pin 14 | 15 | void setup() 16 | { 17 | Serial.begin(9600); // define Serial output baud rate 18 | if(SD.begin(CSpin) == 0) // check for presence of SD card 19 | { 20 | Serial.println("Card fail"); // return to void setup() if SD card not found 21 | return; 22 | } 23 | Serial.println("Card OK"); 24 | file = SD.open("/"); // open SD directory of file information 25 | list(file, 0); // function to display file information 26 | } 27 | 28 | void loop() // nothing in void loop() function 29 | { } 30 | 31 | void list(File direct, int nfiles) // function to display file information 32 | { 33 | while (1) 34 | { 35 | File entry = direct.openNextFile(); // next file in directory 36 | if (entry == 0) break; // stop at end of directory 37 | if (entry.isDirectory()) 38 | { 39 | Serial.print(entry.name());Serial.println("\tis a directory"); 40 | list(entry, nfiles+1); // only list details of files 41 | } 42 | else 43 | { 44 | Serial.print(entry.name());Serial.print("\t"); // display file name 45 | Serial.println(entry.size()); // display file size (bytes) 46 | } 47 | entry.close(); 48 | } 49 | } 50 | 51 | -------------------------------------------------------------------------------- /Chapter 13/Listing13-1/Listing13-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: display shapes and colours 3 | * Description: display shapes of different colours on ST7735 TFT LCD screen 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 13 - Screen displays 8 | ******************************************************************************/ 9 | 10 | #include // include ST7735 library 11 | #include // include GTX library 12 | int TFT_CS = 6; // screen chip select pin 13 | int DCpin = 9; // screen DC pin 14 | int RSTpin = 7; // screen reset pin 15 | // associate tft with Adafruit_ST7735 library 16 | Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, DCpin, RSTpin); 17 | unsigned int BLACK = 0x0000; 18 | unsigned int BLUE = 0x001F; 19 | unsigned int RED = 0xF800; 20 | unsigned int GREEN = 0x07E0; 21 | unsigned int CYAN = 0x07FF; // HEX codes for colours 22 | unsigned int MAGENTA = 0xF81F; 23 | unsigned int YELLOW = 0xFFE0; 24 | unsigned int WHITE = 0xFFFF; 25 | unsigned int GREY = 0xC618; 26 | String texts[ ] = 27 | {"BLUE","RED","GREEN","CYAN","MAGENTA","YELLOW","WHITE","GREY"}; 28 | String text; 29 | unsigned int colours[ ] = 30 | {BLUE, RED, GREEN, CYAN, MAGENTA, YELLOW, WHITE, GREY}; 31 | unsigned int colour; 32 | 33 | void setup() 34 | { 35 | tft.initR(INITR_BLACKTAB); // initialize screen 36 | tft.fillScreen(BLACK); // fill screen in black 37 | tft.drawRect(0,0,128,160,WHITE); // draw white frame line 38 | tft.drawRect(1,1,126,158,WHITE); // and second frame line 39 | tft.setTextSize(2); // set text size 40 | } 41 | 42 | void loop() 43 | { 44 | tft.fillRect(2,2,124,156,BLACK); // clear screen apart from frame 45 | for (int i=0; i<8; i++) // for each colour 46 | { 47 | colour = colours[i]; // set colour 48 | text = texts[i]; // set text 49 | tft.setTextColor(colour); // set text colour 50 | tft.setCursor(20, 20 * i + 2); // position cursor(20, y) 51 | tft.print(text); // print colour name 52 | delay(250); // delay 250ms between colours 53 | } 54 | delay(500); 55 | for (int i=0; i<8; i++) // for each colour 56 | { 57 | tft.fillRect(2,2,124,156,BLACK); // clear screen apart from frame 58 | colour = colours[i]; 59 | text = texts[i]; 60 | tft.setCursor(20,25); // move cursor position to (20, 25) 61 | tft.setTextColor(colour); // set text colour 62 | tft.print(text); // print colour name 63 | // draw filled-in triangle 64 | if ((i+1) % 3 == 0) tft.fillTriangle(20,134,64,55,107,134,colour); 65 | // draw open rectangle 66 | else if ((i+1) % 2 == 0) tft.drawRect(20,55,88,80,colour); 67 | else tft.fillCircle(64,95,39,colour); // draw filled-in circle 68 | delay(500); 69 | } 70 | tft.fillRect(2,2,124,156,BLACK); // clear screen apart from frame 71 | tft.drawLine(2,78,125,78,RED); // draw horizontal line (x0,y) to (x1, y) 72 | tft.drawLine(2,80,125,80,RED); 73 | tft.drawLine(62,2,62,157,RED); // draw vertical line (x,y0) to (x, y1) 74 | tft.drawLine(64,2,64,157,RED); 75 | delay(500); 76 | } 77 | 78 | -------------------------------------------------------------------------------- /Chapter 13/Listing13-3/Listing13-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: OLED display 3 | * Description: display text and numbers on OLED display 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 13 - Screen displays 8 | ******************************************************************************/ 9 | 10 | #include // include Adafruit GFX library 11 | #include // include Adafruit SSD1306 library 12 | // associate oled with Adafruit_SSD1306 library 13 | Adafruit_SSD1306 oled(-1); // no need to define Reset pin 14 | 15 | void setup() 16 | { // OLED display and I2C address 17 | oled.begin(SSD1306_SWITCHCAPVCC, 0x3C); 18 | oled.clearDisplay(); // clear OLED display 19 | oled.setTextColor(WHITE); // set font colour 20 | oled.setTextSize(2); // set font size (1, 2 3 or 4) 21 | oled.setCursor(0,0); // position cursor at (0, 0) 22 | oled.println("Arduino"); // print text with carriage return 23 | oled.print("Applied"); // starting on new line print text 24 | oled.display(); // start display instructions 25 | delay(2000); // delay 2s 26 | 27 | oled.clearDisplay(); 28 | oled.setTextSize(1); // font size 1 characters 68 pixels 29 | oled.setCursor(0,0); 30 | oled.println("Arduino"); 31 | oled.print("Applied"); 32 | oled.setCursor(45,16); // position cursor at (x, y) 33 | oled.print("Arduino"); // at top left hand corner of text 34 | oled.setCursor(45,24); 35 | oled.print("Applied"); 36 | oled.display(); 37 | delay(2000); 38 | 39 | oled.clearDisplay(); 40 | oled.setTextSize(3); // font size 3 characters 1824 pixels 41 | oled.setCursor(0,8); // maximum of 7 characters per row 42 | oled.print("1234567"); 43 | oled.display(); 44 | } 45 | 46 | void loop() // nothing in void loop() function 47 | { } 48 | 49 | -------------------------------------------------------------------------------- /Chapter 14/Listing14-1/Listing14-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: RGB LED 3 | * Description: control colours of RGB LED with incremental changes 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 14 - Sensing colours 8 | ******************************************************************************/ 9 | 10 | int redLED = 3; // LEDs on PWM pins 11 | int greenLED = 5; 12 | int blueLED = 6; 13 | int steps = 63; // number of increments 14 | int oldR = 0; // pixel value difference = 255 or 128 15 | int oldG = 0; // so steps of size 4 or 2 16 | int oldB = 0; 17 | int incR, incG, incB; // incremental changes 18 | String colour[ ] = {"White","Red","Lime","Blue","Yellow","Cyan","Magenta","Grey","Maroon", 19 | "Olive","Green","Purple","Teal","Navy"}; 20 | int R[ ] = {255, 255, 0, 0, 255, 0, 255, 128, 128, 128, 0, 128, 0, 0}; 21 | int G[ ] = {255, 0, 255, 0, 255, 255, 0, 128, 0, 128, 128, 0, 128, 0}; 22 | int B[ ] = {255, 0, 0, 255, 0, 255, 255, 128, 0, 0, 0, 128, 128, 128}; 23 | 24 | void setup() 25 | { } // nothing in void setup() 26 | 27 | void loop() 28 | { 29 | int i = random(14); // randomly select next colour, between 0 and 13 30 | incR = (R[i]-oldR)/steps; // calculate the incremental amount 31 | incG = (G[i]-oldG)/steps; 32 | incB = (B[i]-oldB)/steps; 33 | for (int n = 0; n0) // when data in Serial buffer 24 | { 25 | c = Serial.read(); // read character from Serial buffer 26 | switch (c) // use switch…case for options 27 | { 28 | case 'R': 29 | digitalWrite(redLED, HIGH); // red LED on 30 | Serial.println("red LED on"); // and print message to Serial 31 | break; 32 | case 'G': 33 | digitalWrite(greenLED, HIGH); // green LED on 34 | Serial.println("green LED on"); 35 | break; 36 | case 'O': 37 | digitalWrite(redLED, LOW); // Both LEDs off 38 | digitalWrite(greenLED, LOW); 39 | Serial.println("both LEDs off"); 40 | break; 41 | default: break; // Instruction letter other than R, G or O 42 | } 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Chapter 16/Listing16-2/Listing16-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: control sequence of ArduDroid app 3 | * Description: display control sequences of ArduDroid app 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 16 - Bluetooth communication 8 | ******************************************************************************/ 9 | 10 | char c; // character input from ArduDroid app 11 | int val[3]; // command, Arduino pin and pin value 12 | const int bufferSz = 30; // const int required to define array size 13 | char data[bufferSz]; // alphanumeric data including | and # 14 | int flag = 0; 15 | int index; 16 | 17 | void setup() 18 | { 19 | Serial.begin(9600); // set baud rate for Serial Monitor 20 | } 21 | 22 | void loop() 23 | { 24 | readSerial(); // function to read control sequence 25 | if(flag == 1) // if control sequence read 26 | { 27 | for (int i=0; i<3; i++) 28 | { 29 | Serial.print(val[i]);Serial.print(" "); // display three control variables 30 | } 31 | for (int i=0; i0) // when character in Serial buffer 42 | { 43 | if(flag == 0) // new control sequence 44 | { 45 | c = Serial.read(); // read character from Serial buffer 46 | for (int i=0; i<3; i++) val[i]=Serial.parseInt(); // parse three control variables 47 | flag = 1; // control sequence read 48 | } 49 | c = Serial.read(); // read character from Serial buffer 50 | delay(5); // delay 5ms between characters 51 | if(c != '|' && c != '#') data[index++] = c; // increment data, add next character 52 | } 53 | } 54 | 55 | -------------------------------------------------------------------------------- /Chapter 16/Listing16-3/Listing16-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: ArduDroid app (2) 3 | * Description: ArduDroid app to control LEDs 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 16 - Bluetooth communication 8 | ******************************************************************************/ 9 | 10 | char c; // character input from ArduDroid app 11 | int val[3]; // command, Arduino pin and pin value 12 | const int bufferSz = 30; // const int required to define array size 13 | char data[bufferSz]; // alphanumeric data including | and # 14 | int flag = 0; 15 | int index; 16 | int redLED = 3; // red and green LED pins 17 | int greenLED = 4; 18 | 19 | 20 | void setup() 21 | { 22 | Serial.begin(9600); // set baud rate for Serial Monitor 23 | pinMode(redLED, OUTPUT); // define LED pins as output 24 | pinMode(greenLED, OUTPUT); 25 | 26 | } 27 | 28 | void loop() 29 | { 30 | readSerial(); // function to read control sequence 31 | if(flag == 1) // if control sequence read 32 | { 33 | switch (val[0]) // switch ... case based on instruction 34 | { 35 | case 10: // turn red or green LED on or off 36 | digitalWrite(val[1],!digitalRead(val[1])); 37 | break; 38 | case 11: 39 | analogWrite(val[1],val[2]); // change red LED brightness 40 | break; 41 | case 12: 42 | if(data[0] == 'R') digitalWrite(redLED, HIGH); // R: turn red LED on 43 | else if (data[0] == 'G') digitalWrite(greenLED, HIGH); // G: turn green LED on 44 | else if (data[0] == 'O') // O: turn both LEDs off 45 | { 46 | digitalWrite(redLED, LOW); 47 | digitalWrite(greenLED, LOW); 48 | } 49 | break; 50 | default: break; // default case 51 | } 52 | } 53 | flag = 0; // reset flag to zero 54 | for (int i=0; i<10; i++) data[i]='\0'; // overwrite previous data 55 | index = 0; // reset data index to zero 56 | } 57 | 58 | void readSerial() // function to read control sequence 59 | { 60 | while (Serial.available()>0) // when character in Serial buffer 61 | { 62 | if(flag == 0) // new control sequence 63 | { 64 | c = Serial.read(); // read character from Serial buffer 65 | for (int i=0; i<3; i++) val[i]=Serial.parseInt(); // parse three control variables 66 | flag = 1; // control sequence read 67 | } 68 | c = Serial.read(); // read character from Serial buffer 69 | delay(5); // delay 5ms between characters 70 | if(c != '|' && c != '#') data[index++] = c; // increment data, add next character 71 | } 72 | } 73 | 74 | -------------------------------------------------------------------------------- /Chapter 16/Listing16-4/Listing16-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: ArduDroid app (3) 3 | * Description: ArduDroid app to control LEDs 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 16 - Bluetooth communication 8 | ******************************************************************************/ 9 | 10 | char c; // character input from ArduDroid app 11 | int val[3]; // command, Arduino pin and pin value 12 | const int bufferSz = 30; // const int required to define array size 13 | char data[bufferSz]; // alphanumeric data including | and # 14 | int flag = 0; 15 | int index; 16 | int redLED = 3; // red and green LED pins 17 | int greenLED = 4; 18 | 19 | 20 | void setup() 21 | { 22 | Serial.begin(9600); // set baud rate for Serial Monitor 23 | pinMode(redLED, OUTPUT); // define LED pins as output 24 | pinMode(greenLED, OUTPUT); 25 | 26 | } 27 | 28 | void loop() 29 | { 30 | readSerial(); // function to read control sequence 31 | if(flag == 1) // if control sequence read 32 | { 33 | switch (val[0]) // switch ... case based on instruction 34 | { 35 | case 10: // turn LED 3 or 4 on or off 36 | if(val[1] == 3 || val[1] == 4) digitalWrite(val[1],!digitalRead(val[1])); 37 | else if(val[1] == 5) 38 | { 39 | for (int i=0;i<10;i++) 40 | { // turn greenLED on and off 41 | digitalWrite(greenLED, !digitalRead(greenLED)); // five times 42 | delay(500); // delay 500ms 43 | } 44 | } 45 | break; 46 | case 11: 47 | analogWrite(val[1],val[2]); // change red LED brightness 48 | break; 49 | case 12: 50 | if(data[0] == 'R') digitalWrite(redLED, HIGH); // R: turn red LED on 51 | else if (data[0] == 'G') digitalWrite(greenLED, HIGH); // G: turn green LED on 52 | else if (data[0] == 'O') // O: turn both LEDs off 53 | { 54 | digitalWrite(redLED, LOW); 55 | digitalWrite(greenLED, LOW); 56 | } 57 | break; 58 | default: break; // default case 59 | } 60 | } 61 | flag = 0; // reset flag to zero 62 | for (int i=0; i<10; i++) data[i]='\0'; // overwrite previous data 63 | index = 0; // reset data index to zero 64 | } 65 | 66 | void readSerial() // function to read control sequence 67 | { 68 | while (Serial.available()>0) // when character in Serial buffer 69 | { 70 | if(flag == 0) // new control sequence 71 | { 72 | c = Serial.read(); // read character from Serial buffer 73 | for (int i=0; i<3; i++) val[i]=Serial.parseInt(); // parse three control variables 74 | flag = 1; // control sequence read 75 | } 76 | c = Serial.read(); // read character from Serial buffer 77 | delay(5); // delay 5ms between characters 78 | if(c != '|' && c != '#') data[index++] = c; // increment data, add next character 79 | } 80 | } 81 | 82 | -------------------------------------------------------------------------------- /Chapter 17/Listing17-1/Listing17-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: channel scanning 3 | * Description: scan transmission channles for activity 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 17 - Wireless communication 8 | ******************************************************************************/ 9 | 10 | #include // include SPI library 11 | #include // include RF24 library 12 | RF24 radio(7, 8); // associate radio with RF24 library 13 | const int nChan = 126; // 126 channels available 14 | int chan[nChan]; // store counts per channel 15 | int nScan = 100; // number of scans per channel 16 | int scan; 17 | 18 | void setup() 19 | { 20 | Serial.begin(9600); // define Serial output baud rate 21 | radio.begin(); // start radio 22 | } 23 | 24 | void loop() 25 | { 26 | for (int i=0;i0) chan[i]=chan[i]+1; // a carrier on the channel 36 | } 37 | } // format in HEX for values up to 16 rather than 10 38 | for (int i=0; i 11 | #include 12 | RF24 radio(7, 8); 13 | byte addresses[ ][6] = {"12"}; 14 | typedef struct 15 | { 16 | int number; 17 | float value; 18 | char text[26]; 19 | } dataStruct; 20 | dataStruct data; 21 | 22 | void setup() 23 | { 24 | Serial.begin(9600); 25 | radio.begin(); 26 | radio.openReadingPipe(0, addresses[0]); 27 | radio.startListening(); 28 | } 29 | 30 | void loop() 31 | { 32 | if(radio.available()) 33 | { 34 | radio.read(&data, sizeof(data)); 35 | Serial.print(data.text);Serial.print("\t"); 36 | Serial.print(data.number);Serial.print("\t"); 37 | Serial.println(data.value); 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /Chapter 17/Listing_receive_transmit_in_Table17-3/Listing_receive_transmit_in_Table17-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: receive then transmit in Table 17-3 3 | * Description: receive then transmit data structures 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 17 - Wireless communication 8 | ******************************************************************************/ 9 | 10 | #include 11 | #include 12 | RF24 radio(7, 8); 13 | byte addresses[ ][6] = {"12", "14"}; 14 | typedef struct 15 | { 16 | int number = 1; 17 | float value; 18 | char text[26]; 19 | } dataStruct; 20 | dataStruct data; 21 | int led = 1; 22 | 23 | void setup() 24 | { 25 | Serial.begin(9600); 26 | radio.begin(); 27 | radio.openReadingPipe(1, addresses[0]); 28 | radio.openWritingPipe(addresses[1]); 29 | } 30 | 31 | void loop() 32 | { 33 | radio.startListening(); 34 | if(radio.available()) 35 | { 36 | radio.read(&data, sizeof(data)); 37 | Serial.print(data.text);Serial.print("\t"); 38 | Serial.print(data.number);Serial.print("\t"); 39 | Serial.println(data.value); 40 | } 41 | delay(500); 42 | radio.stopListening(); 43 | led = 1-led; 44 | radio.write(&led, sizeof(led)); 45 | delay(500); 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Chapter 17/Listing_receive_transmit_in_Table17-4/Listing_receive_transmit_in_Table17-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: receive then transmit in Table 17-4 3 | * Description: receive then transmit data structures with potentiometer reading 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 17 - Wireless communication 8 | ******************************************************************************/ 9 | 10 | #include 11 | #include 12 | RF24 radio(7, 8); 13 | byte addresses[ ][6] = {"12", "14"}; 14 | typedef struct 15 | { 16 | int number = 1; 17 | int angle; 18 | float value; 19 | char text[26]; 20 | } dataStruct; 21 | dataStruct data; 22 | int led = 1; 23 | #include // include the servo motor library 24 | Servo servo; // associate servo with Servo library 25 | int servoPin = 4; // servo motor pin 26 | 27 | 28 | void setup() 29 | { 30 | Serial.begin(9600); 31 | radio.begin(); 32 | radio.openReadingPipe(1, addresses[0]); 33 | radio.openWritingPipe(addresses[1]); 34 | servo.attach(servoPin); // initialise servo motor 35 | } 36 | 37 | void loop() 38 | { 39 | radio.startListening(); 40 | if(radio.available()) 41 | { 42 | radio.read(&data, sizeof(data)); 43 | Serial.print(data.text);Serial.print("\t"); 44 | Serial.print(data.number);Serial.print("\t"); 45 | Serial.println(data.value); 46 | servo.write(data.angle); // rotate servo motor 47 | } 48 | delay(500); 49 | radio.stopListening(); 50 | led = 1-led; 51 | radio.write(&led, sizeof(led)); 52 | delay(500); 53 | } 54 | 55 | -------------------------------------------------------------------------------- /Chapter 17/Listing_transmit_in_Table17-1/Listing_transmit_in_Table17-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: transmit in Table 17-1 3 | * Description: transmit data structure 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 17 - Wireless communication 8 | ******************************************************************************/ 9 | 10 | #include 11 | #include 12 | #include 13 | RF24 radio(7, 8); 14 | byte addresses[ ][6] = {"12"}; 15 | typedef struct 16 | { 17 | int number; 18 | float value; 19 | char text[26] = "Transmission"; 20 | } dataStruct; 21 | dataStruct data; 22 | 23 | void setup() 24 | { 25 | radio.begin(); 26 | radio.openWritingPipe(addresses[0]); 27 | printf_begin(); 28 | Serial.begin(9600); 29 | } 30 | 31 | void loop() 32 | { 33 | data.number = data.number+1; 34 | data.value = data.value+0.1; 35 | radio.write(&data, sizeof(data)); 36 | radio.printDetails(); 37 | delay(1000); 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Chapter 17/Listing_transmit_receive_in_Table17-3/Listing_transmit_receive_in_Table17-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: transmit then receive in Table 17-3 3 | * Description: transmit then receive data structures 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 17 - Wireless communication 8 | ******************************************************************************/ 9 | 10 | #include 11 | #include 12 | RF24 radio(7, 8); 13 | byte addresses[ ][6] = {"12", "14"}; 14 | typedef struct 15 | { 16 | int number; 17 | float value; 18 | char text[26] = "Transmission"; 19 | } dataStruct; 20 | dataStruct data; 21 | int led; 22 | int ledPin = 5; 23 | 24 | void setup() 25 | { 26 | radio.begin(); 27 | radio.openWritingPipe(addresses[0]); 28 | radio.openReadingPipe(1, addresses[1]); 29 | pinMode(ledPin, OUTPUT); 30 | } 31 | 32 | void loop() 33 | { 34 | radio.stopListening(); 35 | data.number = data.number+1; 36 | data.value = data.value+0.1; 37 | radio.write(&data, sizeof(data)); 38 | delay(500); 39 | radio.startListening(); 40 | while(!radio.available()); 41 | radio.read(&led, sizeof(led)); 42 | if(led == 1) digitalWrite(ledPin, HIGH); 43 | else digitalWrite(ledPin, LOW); 44 | delay(500); 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Chapter 17/Listing_transmit_receive_in_Table17-4/Listing_transmit_receive_in_Table17-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: transmit then receive in Table 17-4 3 | * Description: transmit then receive data structures with potentiometer reading 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 17 - Wireless communication 8 | ******************************************************************************/ 9 | 10 | #include 11 | #include 12 | RF24 radio(7, 8); 13 | byte addresses[ ][6] = {"12", "14"}; 14 | typedef struct 15 | { 16 | int number; 17 | int angle; 18 | float value; 19 | char text[24] = "Transmission"; 20 | } dataStruct; 21 | dataStruct data; 22 | int led; 23 | int ledPin = 5; 24 | 25 | void setup() 26 | { 27 | radio.begin(); 28 | radio.openWritingPipe(addresses[0]); 29 | radio.openReadingPipe(1, addresses[1]); 30 | pinMode(ledPin, OUTPUT); 31 | } 32 | 33 | void loop() 34 | { 35 | radio.stopListening(); 36 | data.number = data.number+1; 37 | data.value = data.value+0.1; 38 | int potent = analogRead(A0); 39 | data.angle = map(potent, 0, 1023, 0, 180); 40 | radio.write(&data, sizeof(data)); 41 | delay(500); 42 | radio.startListening(); 43 | while(!radio.available()); 44 | radio.read(&led, sizeof(led)); 45 | if(led == 1) digitalWrite(ledPin, HIGH); 46 | else digitalWrite(ledPin, LOW); 47 | delay(500); 48 | } 49 | 50 | -------------------------------------------------------------------------------- /Chapter 19/Listing19-4/Listing19-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: reset GNSS message settings 3 | * Description: reset message settings before use of NeoGPS library 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 19 - Global navigation satellite system 8 | ******************************************************************************/ 9 | 10 | #include // include AltSoftSerial library 11 | AltSoftSerial AltSoft; // associate AltSoft with AltSoftSerial library 12 | // matrix of UTX – CFG – MSG message settings 13 | const unsigned char ublox[ ] PROGMEM = { 14 | 181,98,6,1,8,0,240,0,0,0,0,0,0,1,0,36, // GGA message off 15 | 181,98,6,1,8,0,240,1,0,0,0,0,0,1,1,43, // GLL message off 16 | 181,98,6,1,8,0,240,2,0,0,0,0,0,1,2,50, // GSA message off 17 | 181,98,6,1,8,0,240,3,0,0,0,0,0,1,3,57, // GSV message off 18 | 181,98,6,1,8,0,240,4,0,0,0,0,0,1,4,64, // RMC message off 19 | 181,98,6,1,8,0,240,5,0,0,0,0,0,1,5,71, // VTG message off 20 | 181,98,6,1,8,0,240,0,0,1,0,0,0,1,1,41, // GGA message on 21 | 181,98,6,1,8,0,240,1,0,1,0,0,0,1,2,48, // GLL message on 22 | 181,98,6,1,8,0,240,2,0,1,0,0,0,1,3,55, // GSA message on 23 | 181,98,6,1,8,0,240,3,0,1,0,0,0,1,4,62, // GSV message on 24 | 181,98,6,1,8,0,240,4,0,1,0,0,0,1,5,69, // RMC message on 25 | 181,98,6,1,8,0,240,5,0,1,0,0,0,1,6,76, // VTG message on 26 | 181,98,6,62,36,0,0,0,22,4,0,4,255,0,0,0,0,1,1,1,3, // GPS and GLONASS both off 27 | 0,0,0,0,1,5,0,3,0,0,0,0,1,6,8,255,0,0,0,0,1,163,9, 28 | 181,98,6,62,36,0,0,0,22,4,0,4,255,0,1,0,0,1,1,1,3, // GPS on 29 | 0,0,0,0,1,5,0,3,0,0,0,0,1,6,8,255,0,0,0,0,1,164,37 30 | //181,98,6,62,36,0,0,0,22,4,0,4,255,0,0,0,0,1,1,1,3, // GLONASS on 31 | // 0,0,0,0,1,5,0,3,0,0,0,0,1,6,8,255,0,1,0,0,1,164,13 32 | }; 33 | 34 | void setup() 35 | { 36 | Serial.begin(9600); // baud rate for Serial Monitor 37 | AltSoft.begin(9600); // serial connection to GPS module 38 | for(int i = 0; i < sizeof(ublox); i++) 39 | { 40 | AltSoft.write(pgm_read_byte(ublox+i)); // send message settings to GPS module 41 | delay(5); 42 | } 43 | Serial.println("NMEA messages all on"); 44 | } 45 | 46 | void loop() // nothing in void loop function 47 | { } 48 | 49 | -------------------------------------------------------------------------------- /Chapter 19/Listing19-5/Listing19-5.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: logging GNSS data with an SD card 3 | * Description: extend Listing 19-3 to store positional data on SD card 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 19 - Global navigation satellite system 8 | ******************************************************************************/ 9 | 10 | #include // include AltSoftSerial library 11 | AltSoftSerial AltSoft; // associate AltSoft with AltSoftSerial library 12 | #include // include NeoGPS library 13 | NMEAGPS nmea; // associate nmea with NMEAGPS library 14 | gps_fix gps; // associate gps with NMEAGPS library 15 | #include // include SPI library 16 | #include // include SD library 17 | File file; // associate file with SD library 18 | String filename = "data.csv"; // filename 19 | int CSpin = 10; // chip select pin for SD card 20 | int i = 0; // data record counter 21 | String header, data, hr, mn, s; 22 | 23 | void setup() 24 | { 25 | Serial.begin(9600); // define Serial output baud rate 26 | if(SD.begin(CSpin) == 0) // check for presence of SD card 27 | { 28 | Serial.println("Card fail"); // return if SD card not found 29 | return; 30 | } 31 | Serial.println("Card OK"); 32 | if(SD.exists(filename)) SD.remove(filename); // delete existing file 33 | file = SD.open(filename, FILE_WRITE); // create new file 34 | if(file == 1) // file opened 35 | { 36 | header = "Time, Latitude, Longitude, Altitude, Speed, Satellites"; // column headers 37 | file.println(header); // write column headers to SD card 38 | file.close(); // close file after writing to SD card 39 | } 40 | else Serial.println("Couldn't access file"); // file not opened 41 | AltSoft.begin(9600); // serial connection to GPS module 42 | } 43 | 44 | void loop() 45 | { 46 | while (nmea.available(AltSoft)) // GPS data available 47 | { 48 | i++; // increase data record counter 49 | Serial.print("record ");Serial.println(i); // print record number to Serial Monitor 50 | gps = nmea.read(); // latest satellite message 51 | hr = String(gps.dateTime.hours); // leading zeros for time 52 | if(gps.dateTime.hours<10) hr = "0"+hr; 53 | mn = String(gps.dateTime.minutes); 54 | if(gps.dateTime.minutes<10) mn="0"+mn; 55 | s = String(gps.dateTime.seconds); 56 | if(gps.dateTime.seconds<10) s="0"+s; 57 | data = hr + mn+ s; // create string of readings 58 | data = data + "," + String(gps.latitude(),4) + "," + String(gps.longitude(),4); 59 | data = data + "," + String(gps.altitude(),1) + "," + String(gps.speed_kph(), 1); 60 | data = data + "," + String(gps.satellites); 61 | file = SD.open(filename, FILE_WRITE); // open file on SD card 62 | file.println(data); // write data to SD card 63 | file.close(); // close file on SD card 64 | } 65 | } 66 | 67 | -------------------------------------------------------------------------------- /Chapter 2/Listing2-1/Listing2-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: LED switch 3 | * Description: turns LED on or off when switch is pressed or not pressed 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 2 - Switches 8 | ******************************************************************************/ 9 | 10 | int switchPin = 8; // define switch pin 11 | int LEDpin = 4; // define LED pin 12 | int reading; // define reading as integer 13 | 14 | void setup() 15 | { 16 | pinMode(LEDpin, OUTPUT); // LED pin as output 17 | } 18 | 19 | void loop() 20 | { 21 | reading = digitalRead(switchPin); // read switch pin 22 | digitalWrite(LEDpin, reading); // turn LED on if switch is HIGH 23 | } // turn LED off if switch is LOW 24 | 25 | -------------------------------------------------------------------------------- /Chapter 2/Listing2-2/Listing2-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: LED switch only when pressed 3 | * Description: turns LED on or off when switch is pressed 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 2 - Switches 8 | ******************************************************************************/ 9 | 10 | int switchPin = 8; // define switch pin 11 | int LEDpin = 4; // define LED pin 12 | int reading; // define reading as an integer 13 | int switchState = LOW; // set switch state to LOW 14 | int LEDState = LOW; // set LED state to LOW 15 | 16 | void setup() 17 | { 18 | pinMode(LEDpin, OUTPUT); // LED pin as output 19 | } 20 | 21 | void loop() 22 | { 23 | reading = digitalRead(switchPin); // read switch pin 24 | if(reading != switchState) // if state of switch has changed 25 | { 26 | if (reading == HIGH && switchState == LOW) LEDState =!LEDState; 27 | digitalWrite(LEDpin, LEDState); 28 | switchState = reading; 29 | } 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /Chapter 2/Listing2-3/Listing2-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: LED switch with debounce time 3 | * Description: switch debounced by checking switch status after time delay 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 2 - Switches 8 | ******************************************************************************/ 9 | 10 | int switchPin = 8; // define switch pin 11 | int LEDpin = 4; // define LED pin 12 | int reading; // define reading as an integer 13 | int switchState = LOW; // set switch state to LOW 14 | int LEDState = LOW; // set LED state to LOW 15 | 16 | void setup() 17 | { 18 | pinMode(LEDpin, OUTPUT); // LED pin as output 19 | } 20 | 21 | void loop() 22 | { 23 | reading = digitalRead(switchPin); // read switch pin 24 | if(reading != switchState) // if state of switch has changed 25 | { 26 | delay(50); // debounce time of 50ms 27 | reading = digitalRead(switchPin); // read switch pin again 28 | if(reading != switchState) // compare switch state again 29 | { 30 | if (reading == HIGH && switchState == LOW) LEDState =!LEDState; 31 | digitalWrite(LEDpin, LEDState); 32 | switchState = reading; 33 | } 34 | } 35 | } 36 | 37 | 38 | -------------------------------------------------------------------------------- /Chapter 2/Listing2-4/Listing2-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: debounced LED switch with continue delay 3 | * Description: switch debounced by checking for no change in switch state 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 2 - Switches 8 | ******************************************************************************/ 9 | 10 | int switchPin = 8; // define switch pin 11 | int LEDpin = 4; // define LED pin 12 | int reading; // define reading as an integer 13 | int switchState = LOW; // set switch state to LOW 14 | int LEDState = LOW; // set LED state to LOW 15 | unsigned long switchTime; // define time as unsigned long 16 | int lastSwitch = LOW; // set last switch press in debounce time 17 | int debounceTime = 50; // define debounce time in ms 18 | 19 | void setup() 20 | { 21 | pinMode(LEDpin, OUTPUT); // LED pin as output 22 | } 23 | 24 | void loop() 25 | { 26 | reading = digitalRead(switchPin); // read switch pin 27 | if(reading != lastSwitch) // if reading different from last reading 28 | { 29 | switchTime = millis(); // time switch state change in debounce time 30 | lastSwitch = reading; // update last switch state 31 | } // is switch state the same for required time 32 | if((millis() - switchTime) > debounceTime) 33 | { 34 | if(reading !=switchState) 35 | { 36 | if (reading == HIGH && switchState == LOW) LEDState =!LEDState; 37 | digitalWrite(LEDpin, LEDState); 38 | switchState = reading; 39 | } 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /Chapter 2/Listing2-5/Listing2-5.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: LED and ball switch 3 | * Description: switch LED on and off with ball switch 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 2 - Switches 8 | ******************************************************************************/ 9 | 10 | int switchPin = 8; // define switch pin 11 | int LEDpin = 4; // define LED pin 12 | int reading; 13 | 14 | void setup() 15 | { 16 | pinMode(LEDpin,OUTPUT); // LED pin as output 17 | } 18 | 19 | void loop() 20 | { 21 | reading = digitalRead(switchPin); // read switch pin 22 | if(reading == LOW) digitalWrite(LEDpin ,HIGH); // if ball switch tips-over, turn led on 23 | else digitalWrite(LEDpin, LOW); // ball switch not tipped-over, turn led off 24 | } 25 | 26 | -------------------------------------------------------------------------------- /Chapter 20/Listing20-1/Listing20-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: switch and LED 3 | * Description: illustrate switch not detecting change during delay 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 20 - Interrupts and timed events 8 | ******************************************************************************/ 9 | 10 | int LEDpin = 7; // LED pin 11 | int switchPin = 3; // switch pin 12 | int switchState = LOW; // initial switch state 13 | 14 | void setup() 15 | { 16 | Serial.begin(9600); // define Serial output baud rate 17 | pinMode(LEDpin, OUTPUT); // LED pin as output 18 | } 19 | 20 | void loop() 21 | { 22 | Serial.println(millis()); // display time (ms) on Serial Monitor 23 | delay(1000); // delay 1s 24 | if(digitalRead(switchPin) != switchState) State(); // change of switch state 25 | } 26 | 27 | void State() // can't use switch as a function name 28 | { 29 | switchState = digitalRead(switchPin); // update switch state 30 | if(switchState == HIGH) digitalWrite(LEDpin, !digitalRead(LEDpin)); // turn LED on or off 31 | } 32 | 33 | -------------------------------------------------------------------------------- /Chapter 20/Listing20-2/Listing20-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: interrupt switch and LED 3 | * Description: include interrupt to "override" delay 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 20 - Interrupts and timed events 8 | ******************************************************************************/ 9 | 10 | int LEDpin = 7; // LED pin 11 | int switchPin = 3; // switch pin 12 | volatile int switchState = LOW; // initial switch state 13 | 14 | void setup() 15 | { 16 | Serial.begin(9600); // define Serial output baud rate 17 | pinMode(LEDpin, OUTPUT); // LED pin as output 18 | attachInterrupt(1, State, CHANGE); 19 | } 20 | 21 | void loop() 22 | { 23 | Serial.println(millis()); // display time (ms) on Serial Monitor 24 | delay(1000); // delay 1s 25 | // if(digitalRead(switchPin) != switchState) State(); // change of switch state 26 | } 27 | 28 | void State() // can't use switch as a function name 29 | { 30 | switchState = digitalRead(switchPin); // update switch state 31 | if(switchState == HIGH) digitalWrite(LEDpin, !digitalRead(LEDpin)); // turn LED on or off 32 | } 33 | 34 | -------------------------------------------------------------------------------- /Chapter 20/Listing20-3/Listing20-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: rotary encoder with LED in interrupt 3 | * Description: include interrupt to detect all turns of rotary encoder 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 20 - Interrupts and timed events 8 | ******************************************************************************/ 9 | 10 | int DTpin= 9; // pin B or data pin 11 | int SWpin= 2 ; // switch pin 12 | int LEDpin = 11; // LED on PWM pin 13 | volatile int bright = 120; // initial LED value 14 | int fade = 10; // amount to change LED 15 | int rotate = 0; // number of rotary turns 16 | volatile int SW = 0; 17 | volatile int change; 18 | 19 | void setup() 20 | { 21 | Serial.begin(9600); // define Serial output baud rate 22 | pinMode(LEDpin, OUTPUT); // LED pin as output 23 | pinMode(SWpin, INPUT_PULLUP); // switch pin uses internal pull-up resistor 24 | attachInterrupt(1, encoder, FALLING); // detect change in rotary encoder 25 | attachInterrupt(0, turnOff, FALLING); // detect switch change 26 | } 27 | 28 | void loop() 29 | { 30 | rotate = rotate + abs(change); // number of turns of rotary encoder 31 | bright = bright + change*fade; // change LED brightness 32 | bright = constrain(bright, 0, 255); // constrain LED brightness 33 | if(change != 0) 34 | { 35 | Serial.print(rotate);Serial.print("\t"); // display number of rotary turns 36 | Serial.println(bright); // and LED brightness 37 | } 38 | analogWrite(LEDpin, bright); // update LED brightness 39 | change = 0; // reset change 40 | delay(3000); // delay to verify interrupt functioning 41 | } 42 | 43 | void encoder() // interrupt to detect rotations 44 | { 45 | int newB = digitalRead(DTpin); // state of (DAT) pin B 46 | change = change + (2*newB - 1); // number of changes and direction of rotation 47 | } 48 | 49 | void turnOff() // interrupt for switch 50 | { 51 | bright = 0; 52 | analogWrite(LEDpin, bright); 53 | } 54 | 55 | -------------------------------------------------------------------------------- /Chapter 20/Listing20-4/Listing20-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: timed events with millis() 3 | * Description: schedule event based on time sketch has been running 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 20 - Interrupts and timed events 8 | ******************************************************************************/ 9 | 10 | int LEDpin = 7; // LED pin 11 | unsigned long LEDtime = 0; // event time 12 | 13 | void setup() 14 | { 15 | pinMode(LEDpin, OUTPUT); // LED pin as OUTPUT 16 | } 17 | 18 | void loop() 19 | { 20 | if(millis()-LEDtime > 1000) // 1s since event time 21 | { 22 | digitalWrite(LEDpin, !digitalRead(LEDpin)); // turn LED on or off 23 | LEDtime = millis(); // reset time that event last occurred 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /Chapter 20/Listing20-5/Listing20-5.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: timed events with millis() and one LED 3 | * Description: schedule events based on time sketch has been running 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 20 - Interrupts and timed events 8 | ******************************************************************************/ 9 | 10 | int Atime = 2000; // time for event A: LED off 11 | int Aevent = LOW; 12 | int Btime = 100; // time for event B: LED on 13 | int Bevent = HIGH; 14 | unsigned long lastEvent = 0; // time event last occurred 15 | unsigned long timeNow; // elapsed time in ms 16 | int LED = 7; // LED pin 17 | 18 | void setup() 19 | { 20 | pinMode(LED, OUTPUT); // LED pin as output 21 | } 22 | 23 | void loop() 24 | { 25 | timeNow = millis(); 26 | if(timeNow >= (lastEvent + Atime) && digitalRead(LED) == Aevent) changeLED(Bevent); 27 | else if(timeNow >= (lastEvent + Btime) && digitalRead(LED) == Bevent) changeLED(Aevent); 28 | } 29 | 30 | void changeLED(int event) // function to turn LED on or off 31 | { 32 | digitalWrite(LED, event); // change LED state 33 | lastEvent = timeNow; // reset time that event last occurred 34 | } 35 | 36 | -------------------------------------------------------------------------------- /Chapter 20/Listing20-6/Listing20-6.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: timed events with millis() and two LEDs 3 | * Description: schedule events based on time sketch has been running 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 20 - Interrupts and timed events 8 | ******************************************************************************/ 9 | 10 | int Atime = 2900; // time for event A: LED1 off 11 | int Aevent = LOW; 12 | int Btime = 100; // time for event B: LED1 on 13 | int Bevent = HIGH; 14 | int Ctime = 500; // time for event C: LED2 off 15 | int Cevent = LOW; 16 | int Dtime = 500; // time for event D: LED2 on 17 | int Devent = HIGH; 18 | unsigned long lastEvent[ ] = {0, 0}; // time event last occurred 19 | unsigned long timeNow; // elapsed time in ms 20 | int LED1 = 7; // LED pins 21 | int LED2 = 8; 22 | int LD; 23 | 24 | void setup() 25 | { 26 | pinMode(LED1, OUTPUT); // define LED pins as output 27 | pinMode(LED2, OUTPUT); 28 | } 29 | 30 | void loop() 31 | { 32 | timeNow = millis(); 33 | if(timeNow >= (lastEvent[0] + Atime) && digitalRead(LED1) == Aevent) 34 | changeLED(Bevent, LED1, 1); 35 | else if(timeNow >= (lastEvent[0] + Btime) && digitalRead(LED1) == Bevent) 36 | changeLED(Aevent, LED1, 1); 37 | else if(timeNow >= (lastEvent[1] + Ctime) && digitalRead(LED2) == Cevent) 38 | changeLED(Devent, LED2, 2); 39 | else if(timeNow >= (lastEvent[1] + Dtime) && digitalRead(LED2) == Devent) 40 | changeLED(Cevent, LED2, 2); 41 | } 42 | 43 | void changeLED(int event, int LED, int LD) // function to turn LED on or off 44 | { 45 | digitalWrite(LED, event); // change LED state 46 | lastEvent[LD-1] = timeNow; // reset time that event last occurred 47 | } 48 | 49 | -------------------------------------------------------------------------------- /Chapter 20/Listing20-7/Listing20-7.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: timed events with Timer1 3 | * Description: schedule event based on overflow of Timer1 register 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 20 - Interrupts and timed events 8 | ******************************************************************************/ 9 | 10 | #include // include TIimerOne library 11 | int LEDpin = 11; // LED pin 12 | int PWMpin = 9; // must be pin 9 or 10 13 | int freq = 20; // frequency of 20Hz 14 | unsigned long sec = pow(10,6); // setup one second 15 | unsigned long interval; 16 | volatile int count = 0; 17 | int countCopy, oldCount; 18 | 19 | void setup() 20 | { 21 | Serial.begin(9600); // define Serial output baud rate 22 | pinMode(LEDpin, OUTPUT); // LED pin as output 23 | interval = sec/(2*freq); // define time period 24 | Timer1.initialize(interval); // initialize timer 25 | Timer1.pwm(PWMpin, 0.5*1024); // PWM duty cycle (50%) 26 | Timer1.attachInterrupt(LED); // ISR as timer overflow interrupt 27 | } 28 | 29 | void loop() 30 | { 31 | noInterrupts(); // stop the interrupt 32 | countCopy = count/2; // make copy of counter 33 | interrupts(); // restart the interrupt 34 | if(countCopy > oldCount) Serial.println(countCopy); // display count 35 | oldCount = countCopy; // update count 36 | } 37 | 38 | void LED() 39 | { 40 | digitalWrite(LEDpin, !digitalRead(LEDpin)); // change LED status 41 | count = count + 1; // increment counter 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Chapter 20/Listing20-8/Listing20-8.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: Timer1 registers 3 | * Description: schedule an event based on overflow of Timer1 register with pre-scalar 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 20 - Interrupts and timed events 8 | ******************************************************************************/ 9 | 10 | int LEDpin = 11; // LED pin 11 | 12 | void setup() 13 | { 14 | Serial.begin(9600); // define Serial output baud rate 15 | pinMode(LEDpin, OUTPUT); // LED pin as output 16 | TCCR1A = 0; // initialise register TCCR1A 17 | TCCR1B = 0; // initialise register TCCR1B 18 | TCNT1 = 65511; // define TCNT1 in setup and ISR 19 | TCCR1B |= (1< // include avr/sleep library 11 | int LEDpin = 11; 12 | int wakePin = 2; // pin connected to interrupt 0 13 | 14 | void setup() 15 | { 16 | pinMode(LEDpin, OUTPUT); // LED pin as OUTPUT 17 | pinMode(LED_BUILTIN, OUTPUT); // turn off built-in LED 18 | } 19 | 20 | void loop() 21 | { 22 | delay(500); 23 | digitalWrite(LEDpin, LOW); // turn LED on and off after sleep mode 24 | sleep(); // function to set sleep mode 25 | } 26 | 27 | void sleep() 28 | { 29 | attachInterrupt(0, wake, RISING); // interrupt wake function 30 | set_sleep_mode(SLEEP_MODE_PWR_DOWN); // define sleep mode 31 | //sleep_enable(); // set sleep enable bit 32 | //sleep_cpu(); // initiate sleep 33 | sleep_mode(); // set sleep enable bit, initiate sleep and reset 34 | // sketch resumes here when interrupt triggered 35 | //sleep_disable(); // reset sleep enable bit 36 | detachInterrupt(0); // effectively debounces switch interrupt 37 | } 38 | 39 | void wake() // wake interrupt function 40 | { 41 | digitalWrite(LEDpin, HIGH); // turn LED on 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Chapter 21/Listing21-3/Listing21-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: power saving with PIR sensor interrupt 3 | * Description: microcontroller in sleep mode with motion activated interrupt to wake 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 21 - Power saving 8 | ******************************************************************************/ 9 | 10 | #include // include LowPower library 11 | int LEDpin = 11; // LED pin 12 | int PIRpin = 2; // interrupt on pin 2 (INT0 or interrupt 0) 13 | int detect = 0; // movement flag 14 | 15 | void setup() 16 | { 17 | // Serial.begin(9600); // Serial output baud rate 18 | pinMode(LEDpin, OUTPUT); // LED pin as output 19 | // pinMode(LED_BUILTIN, OUTPUT); // turn off built-in LED 20 | } 21 | 22 | void loop() 23 | { 24 | if(detect == 1) // if movement detected 25 | { 26 | delay(3000); // delay 30s as LED is ON 27 | digitalWrite(LEDpin, LOW); // turn LED off 28 | delay(1000); // delay 1s 29 | } 30 | detect = 0; // reset movement flag 31 | digitalWrite(LEDpin, LOW); // turn LED off 32 | for (int i = 0; i<4; i++) 33 | { // four steps for turning LED 34 | digitalWrite(LEDpin, !digitalRead(LEDpin)); // on and off twice 35 | delay(1000); // LED on or off for 1s 36 | } 37 | sleep(); // call sleep function 38 | } 39 | 40 | void sleep() // sleep function 41 | { 42 | // Serial.println("sleep"); // print message to Serial Monitor 43 | // delay(10); // time required to print before sleep 44 | attachInterrupt(0, wake, RISING); // interrupt pin, wake function and mode 45 | LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); // power down 46 | detachInterrupt(0); // detach interrupt 47 | } 48 | 49 | void wake() // wake interrupt function 50 | { 51 | // Serial.println("Movement detected"); // print message to Serial Monitor 52 | digitalWrite(LEDpin, HIGH); // turn LED on 53 | detect = 1; // set movement flag 54 | } 55 | 56 | -------------------------------------------------------------------------------- /Chapter 22/Listing22-1/Listing22-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: piezo transducer 3 | * Description: repeated sound of fixed frequency and duration 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 22 - Sound and sound waves 8 | ******************************************************************************/ 9 | 10 | int piezoPin = 6; // define PWM pin for piezo transducer 11 | float freq = 440; // sound frequency (Hz) 12 | int duration = 50; // duration of sound (ms) 13 | int interval = 500; // sound duration plus pause (ms) 14 | int pause; 15 | int gap = 1000; 16 | int reps = 5; 17 | int cycles = (duration*freq)/pow(10,3); // number of cycles for sound duration (s) 18 | int timeHigh = pow(10,6)/(2.0*freq); // time (microsecs) that square wave is HIGH 19 | 20 | void setup() 21 | { 22 | pinMode(piezoPin, OUTPUT); // define piezo pin as output 23 | pause = interval-duration; // pause between sounds 24 | } 25 | 26 | void loop() 27 | { 28 | for (int j=0; j= 750) Serial.println("Bright"); 36 | else if(LDR >= 500) Serial.println("Light"); // display light intensity class 37 | else if(LDR >= 250) Serial.println("Dim"); 38 | else Serial.println("Dark"); 39 | delay(1000); // delay 1s 40 | } 41 | 42 | -------------------------------------------------------------------------------- /Chapter 22/Listing22-7/Listing22-7.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: electro-Theremin 3 | * Description: imitate an electro-Theremin 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 22 - Sound and sound waves 8 | ******************************************************************************/ 9 | 10 | #include // include toneAC library 11 | int LDRFpin = A2; // LDR for frequency 12 | int LDRVpin = A3; // LDR for volume 13 | int LDRF, LDRV, freq, volume; 14 | 15 | void setup() 16 | { } // nothing in void setup() function 17 | 18 | void loop() 19 | { 20 | LDRF = analogRead(LDRFpin); // LDR for frequency 21 | LDRV = analogRead(LDRVpin); // LDR for volume 22 | freq = map(LDRF, 0, 900, 523, 1047); // map sound frequency C5 to C6 23 | freq = constrain (freq, 523, 1047); // constrain sound frequency 24 | volume = map(LDRV, 0, 900, 0, 10); // map LDRV to volume 25 | volume = constrain (volume, 0, 10); // constrain volume 26 | toneAC (freq, volume, 0); // play sound with frequency and volume 27 | } 28 | 29 | -------------------------------------------------------------------------------- /Chapter 22/Listing22-8/Listing22-8.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: square wave with PWM 3 | * Description: square wave with duty cycle controlled by potentiometer 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 22 - Sound and sound waves 8 | ******************************************************************************/ 9 | 10 | #include // include PWM library 11 | unsigned long freq =10000; // required frequency (Hz) 12 | int potPin = A0; // potentiometer pin 13 | int PWMpin = 10; // use pin 9 or 10 (Timer1) 14 | int setFreq; 15 | 16 | void setup() 17 | { 18 | pinMode(PWMpin, OUTPUT); // define PWMpin as OUTPUT 19 | InitTimersSafe(); // does not impact Timer0 20 | setFreq = SetPinFrequencySafe(PWMpin, freq); // does not impact Timer0 21 | } 22 | 23 | void loop() 24 | { 25 | pwmWrite(PWMpin, analogRead(potPin)/4); // output square wave with duty 26 | } 27 | 28 | -------------------------------------------------------------------------------- /Chapter 22/Listing22-9/Listing22-9.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: square wave with Timer1 fast PWM 8-bit mode 3 | * Description: square wave with duty cycle controlled by potentiometer 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 22 - Sound and sound waves 8 | ******************************************************************************/ 9 | 10 | int PWMpin = 10; // define PWM pin on Arduino pin 10 11 | int potPin = A0; // define potentiometer on pin A0 12 | 13 | void setup() 14 | { 15 | pinMode(PWMpin, OUTPUT); // define PWMpin as OUTPUT 16 | TCCR1A = 0; // initialise register TCCR1A 17 | TCCR1B = 0; // initialise register TCCR1B 18 | // set compare output mode and set pre-scalar to 1 with Fast PWM 8-bit mode 19 | TCCR1A |= (1< // include IRemote library 11 | int IRpin = 2; // IR sensor pin 12 | IRrecv irrecv(IRpin); // associate irrecv with IRremote library 13 | decode_results reading; // IRremote reading 14 | int IN1 = 8; // left motor forward pin 15 | int IN2 = 7; // backward pin 16 | int IN3 = 6; // right motor forward pin 17 | int IN4 = 5; // backward pin 18 | int ENA = 9; // control pin left motor 19 | int ENB = 10; // control pin right motor 20 | 21 | void setup() 22 | { 23 | Serial.begin(9600); 24 | pinMode(IN1, OUTPUT); // define motor pins as OUTPUT 25 | pinMode(IN2, OUTPUT); 26 | pinMode(IN3, OUTPUT); 27 | pinMode(IN4, OUTPUT); 28 | pinMode(ENA, OUTPUT); // define motor enable pins as OUTPUT 29 | pinMode(ENB, OUTPUT); 30 | irrecv.enableIRIn(); 31 | } 32 | 33 | void loop() 34 | { 35 | if(irrecv.decode(&reading)) // read the IR signal 36 | { 37 | Serial.println(reading.value, HEX); 38 | switch(reading.value) // switch … case for button signals 39 | { 40 | case 0xC0E014D: direction("forward",500); break; // move forward 41 | case 0x9FFCDC4D: direction("backward", 500); break; // move backward 42 | case 0x348ADD0F: direction("right", 500); break; // turn right 43 | case 0x7E57898D: direction("left", 500); break; // turn left 44 | case 0x4B0AA72C: direction("stop", 500); break; // stop 45 | } 46 | irrecv.resume(); // receive the next infrared signal 47 | } 48 | } 49 | 50 | void direction(String direct, int runTime) // function to set motor direction 51 | { 52 | if(direct == "forward") motor(1, 0, 1, 0, "fast"); // both motors forward 53 | else if(direct == "backward") motor(0, 1, 0, 1, "fast"); // both motors backward 54 | else if(direct == "right") motor(1, 0, 0, 1, "slow"); // left forward, right backward 55 | else if(direct == "left") motor(0, 1, 1, 0, "slow"); // left backward, right forward 56 | else if(direct == "stop") motor(0, 0, 0, 0, " "); // both motors stop 57 | delay(runTime); // run time (ms) for motors 58 | } 59 | 60 | void motor(int leftF, int leftB, int rightF ,int rightB, String speed) // motor function 61 | { 62 | float bias = 1.0; // bias on motor speed 63 | digitalWrite(IN1, leftF); // control pin IN1 left motor forward 64 | digitalWrite(IN2, leftB); // control pin IN2 left motor backward 65 | digitalWrite(IN3, rightF); // control pin IN3 right motor forward 66 | digitalWrite(IN4, rightB); // control pin IN4 right motor backward 67 | if(speed == "fast") 68 | { 69 | analogWrite(ENA, 100); // higher speed when moving 70 | analogWrite(ENB, 100*bias); // forward or backward 71 | } 72 | else 73 | { 74 | analogWrite(ENA, 80); // lower speed when turning 75 | analogWrite(ENB, 80*bias); // compensation on right motor 76 | } 77 | } 78 | 79 | -------------------------------------------------------------------------------- /Chapter 23/Listing23-4/Listing23-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: joystick and transmitting nRF24L01 3 | * Description: transmitted joystick value by nRF24L01 module 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 23 - DC motors 8 | ******************************************************************************/ 9 | 10 | #include // include SPI library 11 | #include // include RF24 library 12 | RF24 radio(7, 8); // associate radio with RF24 library 13 | byte addresses[ ][6] = {"12"}; 14 | typedef struct // define a structure 15 | { 16 | int right, left; // to contain PWM values for the 17 | } dataStruct; // left and right motors 18 | dataStruct data; // name the structure 19 | int LRpin = A5; // Uno A4 (horizontal) left-right (X-axis) 20 | int FBpin = A6; // Uno A3 (vertical) forward-backward (Y-axis) 21 | int LR, FB; 22 | int minPWM = 50; // minimum PWM value 23 | int LRscalar = 2; // scalars for joystick sensitivity 24 | int FBscalar = 2; 25 | 26 | void setup() 27 | { 28 | radio.begin(); // initialise radio 29 | radio.openWritingPipe(addresses[0]); // open transmitting pipe 30 | } 31 | 32 | void loop() 33 | { 34 | LR = map(analogRead(LRpin), 0, 1023, -255, 255); // joystick left = 0 35 | FB = map(analogRead(FBpin), 0, 1023, 255, -255); // joystick forward = 0 36 | data.left = FB/FBscalar + LR/LRscalar; // sum of scaled readings 37 | data.right = FB/FBscalar - LR/LRscalar; // difference of scaled readings 38 | data.left = constrain(data.left, -255, 255); // constrain PWM values (-255, 255) 39 | data.right = constrain(data.right, -255, 255); 40 | if(abs(data.left) < minPWM) data.left = 0; // zero PWM value < minimum value 41 | if(abs(data.right) < minPWM) data.right = 0; 42 | radio.write(&data, sizeof(data)); // transmit PWM values 43 | delay(50); // delay 50ms 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Chapter 23/Listing23-5/Listing23-5.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: DC motors and receiving nRF24L01 3 | * Description: motor rotation controlled by transmitted joystick value 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 23 - DC motors 8 | ******************************************************************************/ 9 | 10 | #include // include SPI library 11 | #include // include RF24 library 12 | RF24 radio(7, 8); // associate radio with RF24 library 13 | byte addresses[ ][6] = {"12"}; 14 | typedef struct // define a structure 15 | { 16 | int right, left; // structure to contain PWM values 17 | } dataStruct; // for the left and right motors 18 | dataStruct data; // name the structure 19 | int IN1 = 10; // left motor forward on PWM pins 20 | int IN2 = 9; // backward 21 | int IN3 = 6; // right motor forward 22 | int IN4 = 5; // backward 23 | 24 | void setup() 25 | { 26 | radio.begin(); // initialise radio 27 | radio.openReadingPipe(0, addresses[0]); // open receiving pipe 28 | radio.startListening(); // initialise receive 29 | } 30 | 31 | void loop() 32 | { 33 | if(radio.available()) // signal received 34 | { 35 | radio.read(&data,sizeof(data)); // read data values 36 | if(data.left>0 && data.right>0) motor(data.left, 0, data.right, 0); // forward 37 | else if(data.left<0 && data.right<0) motor(0, -data.left, 0, -data.right); // backward 38 | else if(data.left<0 && data.right>0) motor(0, -data.left, data.right, 0); // turn left 39 | else if(data.left>0 && data.right<0) motor(data.left, 0, 0, -data.right); // turn right 40 | else motor(0, 0, 0, 0); // stop 41 | } 42 | } 43 | 44 | void motor(int leftF, int leftB, int rightF ,int rightB) // control motors by PWM 45 | { 46 | analogWrite(IN1, leftF); // control pin IN1 left motor forward 47 | analogWrite(IN2, leftB); // control pin IN2 left motor backward 48 | analogWrite(IN3, rightF); // control pin IN3 right motor forward 49 | analogWrite(IN4, rightB); // control pin IN4 right motor backward 50 | } 51 | 52 | -------------------------------------------------------------------------------- /Chapter 23/Listing23-6/Listing23-6.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: GY-521 and transmitting nRF24L01 3 | * Description: transmitted GY-521 values by nRF24L01 module 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 23 - DC motors 8 | ******************************************************************************/ 9 | 10 | #include // include Wire library 11 | int I2Caddress = 0x68; // I2C address of MPU-6050 12 | float accelX, accelY, accelZ; // values from MPU-6050 13 | float roll, pitch, sumsquare; 14 | #include // include SPI library 15 | #include // include RF24 library 16 | RF24 radio(7, 8); // associate radio with RF24 library 17 | byte addresses[ ][6] = {"12"}; 18 | typedef struct // define a structure 19 | { 20 | int right, left; // PWM values for the DC motors 21 | } dataStruct; 22 | dataStruct data; 23 | int minPWM = 50; // minimum PWM value 24 | int FB, LR; 25 | int LRscalar = 1; // scalar for accelerometer sensitivity 26 | 27 | void setup() 28 | { 29 | Serial.begin(9600); 30 | Wire.begin(); // initiate I2C bus 31 | Wire.beginTransmission(I2Caddress); // transmit to device at I2Caddress 32 | Wire.write(0x6B); // PWR_MGMT_1 register 33 | Wire.write(0); // set to zero to wake up MPU-6050 34 | Wire.endTransmission(1); // end of transmission 35 | radio.begin(); // initialise radio 36 | radio.openWritingPipe(addresses[0]); // open transmitting pipe 37 | } 38 | 39 | void loop() 40 | { 41 | Wire.beginTransmission(I2Caddress); // transmit to device at I2Caddress 42 | Wire.write(0x3B); // start reading from register 0x3B 43 | Wire.endTransmission(0); // transmission not finished 44 | Wire.requestFrom(I2Caddress,6,true); // request data from 6 registers 45 | accelX=Wire.read()<<8|Wire.read(); // combine AxHigh and AxLow values 46 | accelY=Wire.read()<<8|Wire.read(); // combine AyHigh and AyLow values 47 | accelZ=Wire.read()<<8|Wire.read(); // combine AzHigh and AzLow values 48 | accelX = accelX/pow(2,14); 49 | accelY = accelY/pow(2,14); // scale X, Y and Z measurements 50 | accelZ = accelZ/pow(2,14); 51 | sumsquare = sqrt(accelX*accelX+accelY*accelY+accelZ*accelZ); 52 | accelX = accelX/sumsquare; 53 | accelY = accelY/sumsquare; // adjusted accelerometer measurements 54 | accelZ = accelZ/sumsquare; 55 | roll = atan2(accelY, accelZ)*180/PI; // roll angle 56 | pitch = -asin(accelX)*180/PI; // pitch angle 57 | LR = map(pitch, -90, 90, -255, 255); // tilt module left or right 58 | FB = map(roll, -90, 90, -255, 255); // tilt module forward or backward 59 | data.left = FB + LR/LRscalar; // sum of scaled readings 60 | data.right = FB - LR/LRscalar; // difference of scaled readings 61 | data.left = constrain(data.left, -255, 255); // constrain PWM values (-255, 255) 62 | data.right = constrain(data.right, -255, 255); 63 | if(abs(data.left) < minPWM) data.left = 0; // zero PWM value < minimum value 64 | if(abs(data.right) < minPWM) data.right = 0; 65 | radio.write(&data, sizeof(data)); // transmit PWM values 66 | delay(50); // delay 50ms 67 | } 68 | 69 | -------------------------------------------------------------------------------- /Chapter 23/Listing_Timerone_in_Table23-5/Listing_Timerone_in_Table23-5.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: DC motors and photoelectric encoders Table 23-5 3 | * Description: motors controlled by interrupts using the TimerOne library 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 23 - DC motors 8 | ******************************************************************************/ 9 | 10 | #include 11 | float fixTime = 0.5; 12 | float rpm; 13 | int count=0; 14 | int IN1 = 6; 15 | int IN2 = 5; 16 | int slot = 20; 17 | 18 | void setup() 19 | { 20 | Serial.begin(9600); 21 | Timer1.initialize(500000); 22 | attachInterrupt(0, counter, RISING); 23 | Timer1.attachInterrupt(timerISR); 24 | analogWrite(IN1, 60); 25 | analogWrite(IN2, 0); 26 | } 27 | 28 | void loop() 29 | { } 30 | 31 | void timerISR() 32 | { 33 | noInterrupts(); 34 | rpm = 60*count/(slot*fixTime); 35 | Serial.print("rpm = "); 36 | Serial.println(rpm, 0); 37 | count = 0; 38 | interrupts(); 39 | } 40 | 41 | void counter() 42 | { 43 | count++; 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Chapter 23/Listing_millis_in_Table23-5/Listing_millis_in_Table23-5.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: DC motors and photoelectric encoders Table 23-5 3 | * Description: motors controlled by interrupts using the millis function 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 23 - DC motors 8 | ******************************************************************************/ 9 | 10 | unsigned long Atime = 0; 11 | int fixTime = 500; 12 | float chkTime; 13 | float rpm; 14 | volatile int count = 0; 15 | int IN1 = 6; 16 | int IN2 = 5; 17 | int slot = 20; 18 | 19 | void setup() 20 | { 21 | Serial.begin(9600); 22 | attachInterrupt(0, counter, RISING); 23 | analogWrite(IN1, 60); 24 | analogWrite(IN2, 0); 25 | } 26 | 27 | void loop() 28 | { 29 | if (millis() - Atime >= fixTime) 30 | { 31 | noInterrupts(); 32 | chkTime = (millis() - Atime)/1000.0; 33 | rpm = 60*count/(slot*chkTime); 34 | Serial.print("rpm = "); 35 | Serial.println(rpm, 0); 36 | count = 0; 37 | Atime = millis(); 38 | interrupts(); 39 | } 40 | } 41 | 42 | void counter() 43 | { 44 | count++; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Chapter 24/Listing24-2/Listing24-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: PID controller with LDR and LED 3 | * Description: maintain constant incident light with PID control of LED brightness 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 24 - Robot car 8 | ******************************************************************************/ 9 | 10 | #include // include PID library 11 | double Kp=0; 12 | double Ki=0; // PID coefficients 13 | double Kd=0; 14 | double input, output, setpoint; // PID variables 15 | // associate pid with PID_v1 library 16 | PID pid(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT); 17 | int PIDtime = 20; // time (ms) between PID evaluations 18 | int LDRpin = A0; // LDR pin 19 | int KpPin = A4; // Kp potentiometer pin 20 | int KiPin = A5; // Ki potentiometer pin 21 | int LEDpin = 11; // LED on a PWM pin 22 | unsigned long chkTime; 23 | 24 | void setup() 25 | { 26 | pid.SetMode(AUTOMATIC); // initiate PID 27 | pid.SetSampleTime(PIDtime); // constant PID evaluation time interval 28 | setpoint = 500; // constant PID setpoint 29 | chkTime = millis(); 30 | } 31 | 32 | void loop() 33 | { 34 | if(millis()-chkTime > PIDtime) 35 | { 36 | Kp = analogRead(KpPin) *3.0/1023; // Kp (0 to 3) from potentiometer 37 | Ki = analogRead(KiPin) *15.0/1023; // Ki (0 to 15) from potentiometer 38 | input = analogRead(LDRpin); // read LDR value as PID input 39 | pid.SetTunings(Kp, Ki, Kd); // update PID coefficients 40 | pid.Compute(); // evaluate PID 41 | analogWrite(LEDpin, output); // LED brightness as PID output 42 | chkTime = millis(); 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Chapter 24/Listing24-3/Listing24-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: PID controller with variable setpoint 3 | * Description: maintain constant incident light with PID control of LED brightness 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 24 - Robot car 8 | ******************************************************************************/ 9 | 10 | float Kp=0; 11 | float Ki=0; // PID coefficients 12 | float Kd=0; 13 | float input, output, setpoint; // PID variables 14 | int PIDtime = 20; // time (ms) between PID evaluations 15 | int LDRpin = A0; // LDR pin 16 | int setPin = A4; // setpoint potentiometer pin 17 | int KiPin = A5; // Ki potentiometer pin 18 | int LEDpin = 11; // LED on a PWM pin 19 | unsigned long chkTime; 20 | float pTime, error, lastError, integral, derivative; 21 | 22 | void setup() 23 | { 24 | pTime = PIDtime/1000.0; // PID evaluation time (s) 25 | chkTime = millis(); 26 | } 27 | 28 | void loop() 29 | { 30 | if(millis()-chkTime > PIDtime) 31 | { 32 | setpoint = analogRead(setPin); // setpoint from potentiometer 33 | Ki = analogRead(KiPin)*15.0/1023; // Ki (0 to 15) from potentiometer 34 | input = analogRead(LDRpin); // read LDR value as PID input 35 | error = setpoint-input; // PID error 36 | integral = constrain(integral,0,255) + error*Ki*pTime; // PID integral and error 37 | derivative = (error - lastError)/pTime; // PID derivative 38 | lastError = error; // retain last error 39 | output = Kp*error + constrain(integral,0,255) + Kd*derivative; // evaluate PID output 40 | output = constrain(output, 0, 255); // constrain PID output 41 | analogWrite(LEDpin, output); // LED brightness is PID output 42 | chkTime = millis(); // reset time to next PID evaluation 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Chapter 25/Listing25-1/Listing25-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: connect to Wi-Fi network and update webpage 3 | * Description: connect to Wi-Fi network and update webpage 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 25 - Wi-Fi communication 8 | ******************************************************************************/ 9 | 10 | #include // library to connect to WiFi network 11 | #include // library for webserver functionality 12 | ESP8266WebServer server; // declare webserver 13 | char* ssid = "xxxx"; // change xxxx to your Wi-Fi ssid 14 | char* password = "xxxx"; // change xxxx to your Wi-Fi password 15 | 16 | void setup() 17 | { 18 | Serial.begin(115200); // define Serial output at 115200 baud 19 | WiFi.begin(ssid, password); // initialise WiFI 20 | while (WiFi.status() != WL_CONNECTED) delay(500); // wait for WiFi connection 21 | Serial.print("IP address: "); 22 | Serial.println(WiFi.localIP()); // display IP address of WiFi network 23 | server.on("/", message); // message function when webpage loaded 24 | server.begin(); // initialise server 25 | } 26 | 27 | void message() // function for main webpage 28 | { 29 | String msg = "webserver connected"; // define msg as string 30 | server.send (200, "text/plain", msg); // send response with plain text 31 | } 32 | 33 | void loop() 34 | { 35 | server.handleClient(); // manage incoming HTTP requests 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Chapter 25/Listing25-2/Listing25-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: void LED() function 3 | * Description: extend Listing 25-1 to control built-in and external LEDs 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 25 - Wi-Fi communication 8 | ******************************************************************************/ 9 | 10 | #include // library to connect to WiFi network 11 | #include // library for webserver functionality 12 | ESP8266WebServer server; // declare webserver 13 | char* ssid = "xxxx"; // change xxxx to your Wi-Fi ssid 14 | char* password = "xxxx"; // change xxxx to your Wi-Fi password 15 | int LEDpin = 16; // built-in LED on GPIO 16 16 | int LED2pin = D8; // second LED on pin D8 or GPIO 15 17 | 18 | void setup() 19 | { 20 | Serial.begin(115200); // define Serial output at 115200 baud 21 | WiFi.begin(ssid, password); // initialise WiFI 22 | while (WiFi.status() != WL_CONNECTED) delay(500); // wait for WiFi connection 23 | Serial.print("IP address: "); 24 | Serial.println(WiFi.localIP()); // display IP address of WiFi network 25 | server.on("/",message); // message function when webpage loaded 26 | server.begin(); // initialise server 27 | server.on("/LED", LED); // turn LED on or off when website loads 28 | pinMode(LEDpin, OUTPUT); // LED pin as output 29 | pinMode(LED2pin, OUTPUT); // LED2 pin as output 30 | } 31 | 32 | void message() // function for main webpage 33 | { 34 | String msg = "webserver connected"; // define msg as string 35 | server.send (200, "text/plain",msg); // send response with plain text 36 | } 37 | 38 | void LED() 39 | { 40 | digitalWrite(LEDpin, !digitalRead(LEDpin)); // turn built-in LED on or off 41 | digitalWrite(LED2pin, !digitalRead(LEDpin)); // turn LED2 on or off 42 | String msg; // define msg as string 43 | if (digitalRead(LEDpin) == HIGH) msg = "LEDs off"; // GPIO16 active LOW 44 | else msg = "LEDs on"; 45 | server.send(200,"text/plain", msg); // send response in plain text 46 | } 47 | 48 | void loop() 49 | { 50 | server.handleClient(); // manage incoming HTTP requests 51 | } 52 | 53 | -------------------------------------------------------------------------------- /Chapter 25/Listing25-3/Listing25-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: ESP8266 with LED, LDR and BMP280 sensor 3 | * Description: display requested measurement on webpage 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 25 - Wi-Fi communication 8 | ******************************************************************************/ 9 | 10 | #include // library to connect to WiFi network 11 | #include // library for webserver functionality 12 | ESP8266WebServer server; // associate server with ESP8266WebServer library 13 | char* ssid = "xxxx"; // change xxxx to your Wi-Fi ssid 14 | char* password = "xxxx"; // change xxxx to your Wi-Fi password 15 | #include // include Wire library 16 | #include // include Unified Sensor library 17 | #include // include BMP280 library 18 | Adafruit_BMP280 bmp; // associate bmp with Adafruit_BMP280 library 19 | int BMPaddress = 0x76; // I2C address of BMP280 20 | float reading; 21 | String letter, msg; 22 | 23 | void setup() 24 | { 25 | Serial.begin(115200); // define Serial output at 115200 baud 26 | WiFi.begin(ssid, password); // initialise WiFI 27 | while (WiFi.status() != WL_CONNECTED) delay(500); // wait for WiFi connection 28 | Serial.print("IP address: "); 29 | Serial.println(WiFi.localIP()); // display IP address of WiFi network 30 | server.on("/BMP", BMP); // display temperature, pressure or altitude 31 | server.begin(); // initialise server 32 | bmp.begin(BMPaddress); // initialise BMP280 sensor 33 | } 34 | 35 | void BMP() // function for /BMP webpage 36 | { // looks for string "sensor=" in URL with value: T, P or A 37 | letter = server.arg("sensor"); // T entered on browser, read temperature 38 | if(letter == "T") reading = bmp.readTemperature(); 39 | // P entered on browser, read pressure 40 | else if(letter == "P") reading = bmp.readPressure()/100.0; 41 | else if(letter == "A") // A entered on browser, read altitude 42 | { 43 | reading = 10.0 + bmp.readPressure()/100.0; // assumed sea level pressure 44 | reading = bmp.readAltitude(reading); // predicted altitude 45 | } 46 | msg = letter +": "+ String(reading); // string "T" or "P" or "A" and reading 47 | server.send(200,"text/plain", msg); // activated by /BMP?sensor=T or 48 | } // /BMP?sensor=P or 49 | // /BMP?sensor=A 50 | void loop() 51 | { 52 | server.handleClient(); 53 | } 54 | 55 | -------------------------------------------------------------------------------- /Chapter 25/Listing25-4/Listing25-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: HTML code for webpage as string literal 3 | * Description: htmlCode.h file used in Listing 25-5 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 25 - Wi-Fi communication 8 | ******************************************************************************/ 9 | 10 | R"( 11 | 12 | 13 | 14 | Arduino Applied 15 | 19 | 20 | 21 |

Arduino Applied

22 | LED 23 |
24 | 25 |   26 | 27 | 28 |
29 | 30 | 31 | )" 32 | -------------------------------------------------------------------------------- /Chapter 25/Listing25-5/Listing25-5.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: control an LED with a webpage function 3 | * Description: incorporate Listing 25-4 as htmlCode.h 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 25 - Wi-Fi communication 8 | ******************************************************************************/ 9 | 10 | #include // library to connect to WiFi network 11 | #include // library for webserver functionality 12 | ESP8266WebServer server; // associate server with ESP8266WebServer library 13 | char* ssid = "xxxx"; // change xxxx to your Wi-Fi ssid 14 | char* password = "xxxx"; // change xxxx to your Wi-Fi password 15 | int LEDpin = D8; // LED pin D8 or GPIO 15 16 | String LEDvalue = "OFF"; 17 | char* buildPage = // must be on three lines 18 | #include "htmlCode.h" // html code for webpage without comments 19 | ; // line only includes a semi-colon 20 | 21 | void setup() 22 | { 23 | Serial.begin(115200); // define Serial output at 115200 baud 24 | WiFi.begin(ssid, password); // initialise WiFI 25 | while (WiFi.status() != WL_CONNECTED) delay(500); // wait for WiFi connection 26 | Serial.print("IP address: "); 27 | Serial.println(WiFi.localIP()); // display IP address of WiFi network 28 | pinMode(LEDpin, OUTPUT); // LED pin as output 29 | server.on("/", webpage); // run webpage function as webpage loaded 30 | server.begin(); // initialise server 31 | } 32 | 33 | void webpage() // function to collect data for webpage 34 | { 35 | button(); // obtain LED button status 36 | server.send (200, "text/html", buildPage); // publish webpage 37 | } 38 | 39 | void button() // function of LED button status 40 | { 41 | if (server.hasArg("LED")) LEDvalue = server.arg("LED"); // read LED button state 42 | if (LEDvalue == "ON") digitalWrite(LEDpin, HIGH); // turn LED on or off 43 | else digitalWrite(LEDpin, LOW); 44 | delay(1000); // delay for 1s to retain button colour 45 | } 46 | 47 | void loop() 48 | { 49 | server.handleClient(); 50 | } 51 | 52 | -------------------------------------------------------------------------------- /Chapter 25/Listing25-5/htmlCode.h: -------------------------------------------------------------------------------- 1 | R"( 2 | 3 | 4 | 5 | Arduino Applied 6 | 10 | 11 | 12 |

Arduino Applied

13 | LED 14 |
15 | 16 |   17 | 18 | 19 |
20 | 21 | 22 | )" 23 | -------------------------------------------------------------------------------- /Chapter 25/Listing25-7/Listing25-7.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: Cayenne, ESP8266 with LED, LDR and BMP280 sensor 3 | * Description: display on Cayenne website or app BMP280 measurements, 4 | * a time counter and a button to control a LED over Wi-Fi 5 | * Created : October 2018 6 | * Author: Neil Cameron 7 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 8 | * Chapter : Chapter 25 - Wi-Fi communication 9 | ******************************************************************************/ 10 | 11 | #include // Cayenne MQTT library 12 | char ssid[] = "xxxx"; // change xxxx to your Wi-Fi ssid 13 | char wifipass[] = "xxxx"; // change xxxx to your Wi-Fi password 14 | char username[] = "xxxx"; // change xxxx to your Cayenne username 15 | char mqttpass[] = "xxxx"; // change xxxx to your Cayenne password 16 | char clientID[] = "xxxx"; // change xxxx to your Cayenne client identity 17 | #include // include Adafruit_Sensor library 18 | #include // include Adafruit_BMP280 library 19 | Adafruit_BMP280 bmp; // associate bmp with Adafruit_BMP280 library 20 | int LEDpin = D8; // LED pin 21 | int LDRpin = A0; // light dependent resistor pin 22 | int flashPin = 2; // flashing LED pin GPIO 2 23 | unsigned long count = 0; 24 | int interval = 2000; // 2s interval between MQTT messages 25 | unsigned long lastTime = 0; 26 | float temp, pressure, BasePressure, altitude; 27 | int light; 28 | 29 | void setup() 30 | { 31 | bmp.begin(0x76); // initiate bmp with I2C address 32 | // initiate Cayenne MQTT 33 | Cayenne.begin(username, mqttpass, clientID, ssid, wifipass); 34 | pinMode(LEDpin, OUTPUT); // define LED pins as output 35 | digitalWrite(LEDpin, LOW); 36 | pinMode(flashPin, OUTPUT); 37 | } 38 | 39 | void loop() 40 | { 41 | Cayenne.loop(); // Cayenne loop() function 42 | if(millis()-lastTime > interval) 43 | { 44 | temp = bmp.readTemperature(); // BMP280 temperature and pressure 45 | pressure = bmp.readPressure()/100.0; 46 | BasePressure = pressure + 10.0; // assumed sea level pressure 47 | altitude = bmp.readAltitude(BasePressure); // predicted altitude (m) 48 | light = analogRead(LDRpin); // ambient light intensity 49 | light = constrain(light, 0, 1023); // constrain light reading 50 | count++; // increment counter 51 | if(count>99) count = 0; 52 | digitalWrite(flashPin, LOW); // turn flashing LED on then off 53 | delay(10); 54 | digitalWrite(flashPin, HIGH); 55 | // send readings to Cayenne on virtual channels 56 | Cayenne.virtualWrite(V1, temp, "temp", "c"); // define temperature reading 57 | // channel2 is flashPin so V2 is not used to avoid confusion 58 | Cayenne.virtualWrite(V3, pressure, "bp", "pa");// define pressure reading 59 | Cayenne.virtualWrite(V4, altitude); 60 | Cayenne.virtualWrite(V5, light, "lum", "lux");// define luminosity reading 61 | Cayenne.virtualWrite(V6, count); 62 | lastTime=millis(); // update time 63 | } 64 | } 65 | 66 | CAYENNE_IN(0) // Cayenne virtual channel 0 67 | { 68 | digitalWrite(LEDpin, getValue.asInt()); // turn LED on or off 69 | } 70 | 71 | -------------------------------------------------------------------------------- /Chapter 25/Listing25-8/Listing25-8.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: alarm, LED and light intensity 3 | * Description: trigger an alarm if ambiant light increases and send an email 4 | * and/or text notification over Wi-Fi 5 | * Created : October 2018 6 | * Author: Neil Cameron 7 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 8 | * Chapter : Chapter 25 - Wi-Fi communication 9 | ******************************************************************************/ 10 | 11 | #include // Cayenne MQTT library 12 | char ssid[] = "xxxx"; // change xxxx to your Wi-Fi ssid 13 | char wifipass[] = "xxxx"; // change xxxx to your Wi-Fi password 14 | char username[] = "xxxx"; // change xxxx to your Cayenne username 15 | char mqttpass[] = "xxxx"; // change xxxx to your Cayenne password 16 | char clientID[] = "xxxx"; // change xxxx to your Cayenne client identity 17 | int LEDpin = 15; // LED pin GPIO 15 or D8 18 | int alarmPin = 13; // alarm pin GPIO 13 or D7 19 | int LDRpin = A0; // LDR on pin A0 20 | int flashPin = 2; // flashing LED pin GPIO 2 21 | int reading, alarm; 22 | int interval = 2000; // 2s interval between LDR readings 23 | unsigned long LDRtime = 0; 24 | 25 | void setup() 26 | { 27 | Serial.begin(9600); // initiate Cayenne MQTT 28 | Cayenne.begin(username, mqttpass, clientID, ssid, wifipass); 29 | pinMode(LEDpin, OUTPUT); // define LED pins as output 30 | pinMode(alarmPin, OUTPUT); 31 | pinMode(flashPin, OUTPUT); 32 | alarm = 0; // set alarm as "OFF" 33 | } 34 | 35 | void loop() 36 | { 37 | Cayenne.loop(); // Cayenne loop() function 38 | if(millis()-LDRtime>interval) 39 | { 40 | LDRtime = millis(); 41 | reading = analogRead(LDRpin); 42 | // if alarm ON, then send LDR reading to Cayenne on channel V1, otherwise send zero 43 | if (alarm == 1) Cayenne.virtualWrite(V1, reading, "lum", "lux"); 44 | else Cayenne.virtualWrite(V1, 0, "lum", "lux"); 45 | delay(20); 46 | } 47 | digitalWrite(flashPin, LOW); // LED GPIO 2 active LOW 48 | delay(10); // flash to indicate power on 49 | digitalWrite(flashPin, HIGH); 50 | } 51 | 52 | CAYENNE_IN(0) // Cayenne virtual channel 0 53 | { 54 | digitalWrite(LEDpin, getValue.asInt()); // get LED status 55 | } 56 | CAYENNE_IN(3) // Cayenne virtual channel 3 57 | { 58 | alarm = getValue.asInt(); // get alarm state 59 | digitalWrite(alarmPin, alarm); 60 | } 61 | 62 | -------------------------------------------------------------------------------- /Chapter 3/Listing3-1/Listing3-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: Temperature sensor 3 | * Description: measure temperature with LM35DZ sensor 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 3 - Sensors 8 | ******************************************************************************/ 9 | 10 | int tempPin = A0; // define LM35 signal to analog pin A0 11 | int min =20; // define minimum plot value 12 | int max = 30; // define maximum plot value 13 | int reading; // define reading as an integer 14 | float temp; // define temp as a real number 15 | 16 | void setup() 17 | { 18 | Serial.begin(9600); // define Serial output baud rate 19 | analogReference(INTERNAL); // set ADC voltage to 1.1V rather than 5V 20 | } 21 | 22 | void loop() 23 | { 24 | reading = analogRead(tempPin); // read temperature sensor pin 25 | temp = (reading * 110.0)/1023; // convert reading to temperature 26 | // convert temperature to a string 27 | String axis = String(min) +" "+ String(temp) +" "+ String(max); 28 | Serial.println(axis); // update plot 29 | delay(10); // delay 10ms between readings 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Chapter 3/Listing3-10/Listing3-10.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: infrared sensor 3 | * Description: detect infrared signal with VS1838B infrared sensor 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 3 - Sensors 8 | ******************************************************************************/ 9 | 10 | #include // include IRremote library 11 | int IRpin = 12; // IR sensor pin 12 | IRrecv irrecv(IRpin); // associate irrecv with IRremote library 13 | decode_results reading; // IRremote variable reading 14 | int LEDpin = 4; // LED pin 15 | 16 | void setup() 17 | { 18 | Serial.begin(9600); // set baud rate for Serial Monitor 19 | irrecv.enableIRIn(); // start the infrared receiver 20 | pinMode(LEDpin, OUTPUT); // LED pin as output 21 | } 22 | 23 | void loop() 24 | { 25 | if(irrecv.decode(&reading)) // read pulsed signal 26 | { 27 | if(reading.decode_type == NEC) Serial.print("NEC: "); // NEC IR signal 28 | else if(reading.decode_type == SONY) Serial.print("Sony: "); // Sony IR signal 29 | else if(reading.decode_type == RC5) Serial.print("RC5: "); // RC5 IR signal 30 | else if(reading.decode_type == RC6) Serial.print("RC6: "); // RC6 IR signal 31 | else if(reading.decode_type == AIWA_RC_T501) Serial.print("AIWA_RC_T501: "); // AIWA_RC_T501 signal 32 | else if(reading.decode_type == DENON) Serial.print("DENON: "); // DENON signal 33 | else if(reading.decode_type == DISH) Serial.print("DISH: "); // DISH signal 34 | else if(reading.decode_type == JVC) Serial.print("JVC: "); // JVC signal 35 | else if(reading.decode_type == LG) Serial.print("LG: "); // LG signal 36 | else if(reading.decode_type == MITSUBISHI) Serial.print("MITSUBISHI: "); // MITSUBISHI signal 37 | else if(reading.decode_type == PANASONIC) Serial.print("PANASONIC: "); // Panasonic signal 38 | else if(reading.decode_type == SAMSUNG) Serial.print("SAMSUNG: "); // SAMSUNG signal 39 | else if(reading.decode_type == SANYO) Serial.print("SANYO: "); // SANYO signal 40 | else if(reading.decode_type == SHARP) Serial.print("SHARP: "); // SHARP signal 41 | else if(reading.decode_type == WHYNTER) Serial.print("WHYNTER: "); // WHYNTER signal 42 | else Serial.print("Other: "); 43 | Serial.print(reading.value, HEX); // display device type and HEX code 44 | Serial.print("\tBits: "); // on Serial Monitor 45 | Serial.println(reading.bits); // display number of IR signal bits 46 | digitalWrite(LEDpin, HIGH); // turn LED on 47 | delay(100); // delay before next IR signal 48 | digitalWrite(LEDpin, LOW); // turn LED off 49 | irrecv.resume(); // receive the next infrared signal 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /Chapter 3/Listing3-11/Listing3-11.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: infrared distance sensor 3 | * Description: measure distance with TCRT500 infrared distance sensor 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 3 - Sensors 8 | ******************************************************************************/ 9 | 10 | int IRpin = A0; // IR sensor pin 11 | int threshPin = 7; // threshold pin 12 | int reading, thresh; 13 | 14 | void setup() 15 | { 16 | Serial.begin(9600); // set Serial Monitor baud rate 17 | } 18 | 19 | void loop() 20 | { 21 | reading = analogRead(IRpin); // read IR sensor pin 22 | thresh = 1-digitalRead(threshPin); // read threshold pin 23 | Serial.print("Distance: "); // print "Distance: to Serial Monitor 24 | Serial.print(reading);Serial.print("\t"); // print IR sensor value and a tab 25 | Serial.print("Threshold : ");Serial.println(thresh); // print "Threshold" and value 26 | delay(1000); // delay 1s 27 | } 28 | 29 | 30 | -------------------------------------------------------------------------------- /Chapter 3/Listing3-12/Listing3-12.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: PIR sensor 3 | * Description: detect movement with HR-SC501 passive infrared sensor 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 3 - Sensors 8 | ******************************************************************************/ 9 | 10 | int PIRpin = 11; // PIR sensor pin 11 | int LEDpin = 8; // LED pin 12 | int PIRstate = LOW; // set PIR state to LOW 13 | int reading; 14 | unsigned long detectTime; // time lag on PIR sensor 15 | float moveTime; 16 | 17 | void setup() 18 | { 19 | Serial.begin(9600); // set Serial Monitor baud rate 20 | pinMode(LEDpin, OUTPUT); // LED pin as output 21 | } 22 | 23 | void loop() 24 | { 25 | reading = digitalRead(PIRpin); // read PIR pin 26 | if (reading == HIGH && PIRstate == LOW) // PIR detected new movement 27 | { 28 | Serial.print("New movement detected"); // print to Serial Monitor 29 | detectTime = millis(); // time of movement 30 | PIRstate = HIGH; // update PIR state to HIGH 31 | digitalWrite(LEDpin, PIRstate); // turn LED on 32 | } 33 | else if (reading == LOW && PIRstate == HIGH) // movement no longer detected 34 | { 35 | moveTime = millis() - detectTime; // duration of movement 36 | moveTime = moveTime/1000.0; 37 | Serial.print(" and lasted for "); // print to Serial Monitor 38 | Serial.print(moveTime,1); // print detect time (s) with 1DP 39 | Serial.println(" seconds"); // print text with a new line 40 | PIRstate = LOW; // update PIR state to LOW 41 | digitalWrite(LEDpin, PIRstate);// turn LED off 42 | } 43 | } 44 | 45 | 46 | -------------------------------------------------------------------------------- /Chapter 3/Listing3-13/Listing3-13.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: GY-521 module 3 | * Description: determine object's orientation with GY-521 module 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 3 - Sensors 8 | ******************************************************************************/ 9 | 10 | #include // include Wire library 11 | int I2Caddress = 0x68; // I2C address of the MPU-6050 12 | int frontLED = 13; 13 | int backLED = 11; // define LED pins 14 | int rightLED = 12; 15 | int leftLED = 10; 16 | float accelX,accelY,accelZ; // accelerometer measurements 17 | float roll, pitch, sumsquare; 18 | 19 | void setup() 20 | { 21 | Serial.begin(9600); // define Serial output baud rate 22 | pinMode(frontLED, OUTPUT); 23 | pinMode(backLED, OUTPUT); // define LED pins as OUTPUT 24 | pinMode(rightLED, OUTPUT); 25 | pinMode(leftLED, OUTPUT); 26 | Wire.begin(); // initiate I2C bus 27 | Wire.beginTransmission(I2Caddress); // transmit to device at I2Caddress 28 | Wire.write(0x6B); // PWR_MGMT_1 register 29 | Wire.write(0); // set to zero wakes up MPU-6050 30 | Wire.endTransmission(1); // end of transmission 31 | } 32 | 33 | void loop() 34 | { 35 | Wire.beginTransmission(I2Caddress); // transmit to device at I2Caddress 36 | Wire.write(0x3B); // start reading from register 0x3B 37 | Wire.endTransmission(0); // transmission not finished 38 | Wire.requestFrom(I2Caddress,6,true); // request data from 6 registers 39 | accelX=Wire.read()<<8|Wire.read(); // combine AxHigh and AxLow values 40 | accelY=Wire.read()<<8|Wire.read(); // combine AyHigh and AyLow values 41 | accelZ=Wire.read()<<8|Wire.read(); // combine AzHigh and AzLow values 42 | accelX = accelX/pow(2,14); 43 | accelY = accelY/pow(2,14); // scale X, Y and Z measurements 44 | accelZ = accelZ/pow(2,14); 45 | sumsquare = sqrt(accelX*accelX+accelY*accelY+accelZ*accelZ); 46 | accelX = accelX/sumsquare; 47 | accelY = accelY/sumsquare; // adjusted accelerometer measurements 48 | accelZ = accelZ/sumsquare; 49 | roll = atan2(accelY, accelZ)*180/PI; // roll angle 50 | pitch = -asin(accelX)*180/PI; // pitch angle 51 | LEDs(); // function to control LEDS 52 | } 53 | 54 | void LEDs() // function to control LEDs 55 | { 56 | int front = LOW; 57 | int back = LOW; // turn off all LEDs 58 | int right = LOW; 59 | int left = LOW; 60 | if(roll>10) right = HIGH; // right or left LEDS with roll angle 61 | else if(roll< -10) left = HIGH; 62 | if(pitch>10) front = HIGH; // front or back LEDs with pitch angle 63 | else if(pitch< -10) back = HIGH; 64 | digitalWrite(frontLED, front); // if value = HIGH, LED on 65 | digitalWrite(backLED, back); // if value = LOW, LED off 66 | digitalWrite(rightLED, right); 67 | digitalWrite(leftLED, left); 68 | delay(500); 69 | } 70 | 71 | -------------------------------------------------------------------------------- /Chapter 3/Listing3-2/Listing3-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: DHT11 sensors 3 | * Description: measure temperature and humidity with DHT11 sensor 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 3 - Sensors 8 | ******************************************************************************/ 9 | 10 | #include // include dht library 11 | dht DHT; // associate DHT with dht library 12 | int DHTpin = 12; // DHT11 unit on pin 12 13 | int PCBpin = 7; // PCB mounted DHT11 on pin 7 14 | int check; 15 | 16 | void setup() 17 | { 18 | Serial.begin(9600); // define Serial output baud rate 19 | } 20 | 21 | void loop() 22 | { 23 | check = DHT.read11(DHTpin); // read DHT11 sensor on DHTpin 24 | Serial.print("DHT11 Unit temp: "); // print text followed by a space 25 | Serial.print(DHT.temperature,0); // temperature reading, integer only 26 | Serial.print("\thumidity: "); // print tab then text 27 | Serial.println(DHT.humidity,0); // humidity reading, integer only 28 | 29 | check = DHT.read11(PCBpin); // repeat for the DHT11 on PCB 30 | Serial.print("DHT11 PCB temp: "); 31 | Serial.print(DHT.temperature,0); 32 | Serial.print("\thumidity: "); 33 | Serial.println(DHT.humidity,0); 34 | delay(1000); // delay one second 35 | } 36 | 37 | -------------------------------------------------------------------------------- /Chapter 3/Listing3-3/Listing3-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: light dependent resistor and LED 3 | * Description: light dependent resistor controls LED brightness 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 3 - Sensors 8 | ******************************************************************************/ 9 | 10 | int Vdivid = A0; // voltage divider analog pin 11 | int LEDpin = 11; // LED on PWM pin 12 | int thresh = 500; // threshold light intensity 13 | int reading, bright; 14 | 15 | void setup() 16 | { 17 | pinMode(LEDpin, OUTPUT); // LED pin as output 18 | } 19 | 20 | void loop() 21 | { 22 | reading = analogRead(Vdivid); // voltage divider reading 23 | bright = 0; // set LED brightness to zero 24 | // map reading to LED brightness 25 | if(reading400 || distance<2) Serial.println("Out of range"); 31 | else 32 | { 33 | Serial.print("Distance : "); Serial.print(distance, 1); Serial.println(" cm"); 34 | } 35 | delay(500); 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Chapter 3/Listing3-6/Listing3-6.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: ultrasonic distance sensor and NewPing library 3 | * Description: measure distance with HC-SR04 ultrasonic distance sensor 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 3 - Sensors 8 | ******************************************************************************/ 9 | 10 | #include // include NewPing library 11 | int trigPin = 6; // trigger pin 12 | int echoPin = 7; // echo pin 13 | int maxdist = 100; // set maximum scan distance 14 | int echoTime; // echo time 15 | float distance; // distance 16 | NewPing sonar(trigPin, echoPin, maxdist); // associate sonar with NewPing library 17 | 18 | void setup() 19 | { 20 | Serial.begin(9600); // set baud rate for Serial Monitor 21 | } 22 | 23 | void loop() 24 | { 25 | echoTime = sonar.ping(); // echo time (s) 26 | distance = (echoTime/2.0)*0.0343; // distance between sensor and target 27 | Serial.print("echo time: "); // print text "echo time: " 28 | Serial.print(echoTime); // print echo time 29 | Serial.print(" microsecs\t"); // print text " microsecs" and tab 30 | Serial.print("distance: "); // print text "distance: " 31 | Serial.print(distance,2); // print distance with 2 DP 32 | Serial.println(" cm"); // " cm" followed by a new line 33 | delay(500); 34 | } 35 | 36 | -------------------------------------------------------------------------------- /Chapter 3/Listing3-7/Listing3-7.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: speed of sound 3 | * Description: measure speed of sound with HC-SR04 ultrasonic distance sensor 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 3 - Sensors 8 | ******************************************************************************/ 9 | 10 | #include 11 | int pinTrig = 6; 12 | int pinEcho = 7; 13 | int maxdist = 100; // max distance in cm maxdist ~ 400-500 cm 14 | int echoTime; 15 | float distance = 15; 16 | NewPing sonar(pinTrig, pinEcho, maxdist); 17 | int tempPin = A0; // LM35DZ temperature sensor on analog pin A0 18 | float speed, temp, predict; 19 | 20 | void setup() 21 | { 22 | Serial.begin(9600); // define Serial output baud rate 23 | analogReference(INTERNAL); // set ADC voltage to 1.1V rather than 5V 24 | } 25 | 26 | void loop() 27 | { 28 | echoTime = sonar.ping_median(5); // median echo time (microsecs) 29 | speed = distance*2.0*pow(10,4)/echoTime; // speed of sound (m/s) 30 | Serial.print(echoTime);Serial.print(" microsecs\t"); // print time and a tab 31 | Serial.print("speed "); // print "speed" 32 | Serial.print(speed,1); Serial.print("\t"); // print speed with 1DP, tab 33 | temp = (analogRead(tempPin)*110.0)/1023; // read temperature 34 | predict = 331.3 + 0.606 * temp; // calculate speed of sound 35 | Serial.print("predict "); 36 | Serial.print(predict,1);Serial.println(" m/s"); // print prediction with 1DP 37 | delay(500); 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Chapter 3/Listing3-8/Listing3-8.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: Hall effect sensor 3 | * Description: measure rpm and time per revolution with Hall effect sensor 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 3 - Sensors 8 | ******************************************************************************/ 9 | 10 | int switchPin = 8; // hall effect sensor pin 11 | int switchState = LOW; // set switch to LOW 12 | int revolution = 0; // number of revolutions 13 | float circum = 2.16; // tyre circumference 14 | unsigned long time = 0; // time (ms) per revolution 15 | float speed, rpm; 16 | int reading; 17 | 18 | void setup() 19 | { 20 | pinMode(switchPin, INPUT_PULLUP); // pull-up resistor on hall effect sensor pin 21 | Serial.begin(9600); // set baud rate for Serial Monitor 22 | } 23 | 24 | void loop() 25 | { 26 | reading = digitalRead(switchPin); // read hall switch 27 | if(reading != switchState) // switch state changed 28 | { 29 | if (reading == HIGH && switchState == LOW) 30 | { // update at start of new revolution 31 | revolution = revolution +1; // increment number of revolutions 32 | time = millis() - time; // time (ms) since last revolution 33 | speed = 3600.0*circum/time; // speed calculation in km/h 34 | rpm = 60000.0/time; // revolutions per minute 35 | Serial.print(revolution);Serial.print("\t"); // print number of revolutions 36 | Serial.print(speed,1);Serial.print("km/h\t"); // print speed to 1DP, " km/h" and tab 37 | Serial.print(rpm,0);Serial.println("rpm"); // print rpm, "rpm" and a new line 38 | time = millis(); // update revolution time 39 | } 40 | switchState = reading; // update hall switch state 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Chapter 3/Listing3-9/Listing3-9.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: sound sensor 3 | * Description: detect sound above threshold with LM393 sound sensor 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 3 - Sensors 8 | ******************************************************************************/ 9 | 10 | int soundPin = 11; // sound sensor pin 11 | int LEDpin = 5; // LED pin 12 | int detected = LOW; // sound detect state to LOW 13 | unsigned long detectTime; // time sound detected 14 | int lag = 1000; // time between sounds (ms) 15 | int sound; 16 | 17 | void setup () 18 | { 19 | Serial.begin(9600); // set baud rate for Serial Monitor 20 | pinMode(LEDpin, OUTPUT); // LED pin as output 21 | } 22 | 23 | void loop () 24 | { 25 | sound = digitalRead(soundPin); // read sound pin 26 | if (sound == LOW) // sound detected with LOW, not HIGH 27 | { 28 | detectTime = millis(); // start time of new sound 29 | if (detected == LOW) // if currently no sound 30 | { 31 | Serial.print("new SOUND");Serial.print("\t"); // print "new SOUND" and tab 32 | detected = HIGH; // update sound detect state to HIGH 33 | digitalWrite(LEDpin, detected); // turn LED on 34 | } 35 | } 36 | else if (sound == HIGH) // no sound detected 37 | { // continuous sound no longer detected 38 | if(detected == HIGH && (millis()-detectTime) > lag) 39 | { 40 | Serial.println("now quiet"); // print "now quiet" with a new line 41 | detected = LOW; // update sound detect state to LOW 42 | digitalWrite(LEDpin, detected); // turn LED off 43 | } 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Chapter 4/Listing4-1/Listing4-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: LCD and temperature sensor 3 | * Description: display temperature and time on 16x4 LCD 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 4 - Liquid crystal display 8 | ******************************************************************************/ 9 | 10 | #include // include the LiquidCrystal library 11 | int LCDcol =16; // number of LCD columns 12 | int LCDrow = 4; // number of LCD rows 13 | // associate lcd with LiquidCrystal library 14 | LiquidCrystal lcd (2,3,4,5,6,7); // define LCD pins RS, E and D4 to D7 15 | int tempPin = A0; // LM35 temperature sensor pin 16 | int time = 0; 17 | int reading; 18 | float temp; 19 | 20 | void setup() 21 | { 22 | lcd.begin(LCDcol, LCDrow); // define LCD dimensions 23 | lcd.setCursor(0,0); // move cursor to start of first row 24 | lcd.print("LCD to display"); // print first row "LCD to display" 25 | lcd.setCursor(0,1); // move cursor to start of second row 26 | lcd.print("time and temp"); // print second row "time and temp" 27 | lcd.setCursor(3,2); // move cursor to insert "secs" on third row 28 | lcd.print(" secs"); 29 | lcd.setCursor(5,3); // move cursor to insert "C" in fourth row 30 | lcd.print(" C"); 31 | analogReference(INTERNAL); // set ADC voltage to 1.1V rather than 5V 32 | // int contrast = 9; // PWM pin for contrast 33 | // pinMode(contrast, OUTPUT); // define contrast pin as OUTPUT 34 | // analogWrite(9, 80); // 80% duty cycle 35 | } 36 | 37 | void loop() 38 | { 39 | lcd.setCursor(0,2); // move cursor to start of third row 40 | if(time < 100) lcd.print(" "); // spacing for 10s < time <100s 41 | if(time < 10) lcd.print(" "); // spacing for time < 10s 42 | lcd.print(time); // print time (s) 43 | time++; // increment time 44 | reading = analogRead(tempPin); // read temperature from sensor 45 | temp = (reading * 110.0)/1023; // convert to Celsius given 1.1V range 46 | lcd.setCursor(0,3); // move cursor to start of fourth row 47 | lcd.print(temp); // print temperature 48 | if(time>999) time = 0; // reset time to zero 49 | delay (1000); // delay 1000ms 50 | } 51 | 52 | -------------------------------------------------------------------------------- /Chapter 4/Listing4-2/Listing4-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: scrolling text on LCD 3 | * Description: text is scrolled across 16x4 LCD 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 4 - Liquid crystal display 8 | ******************************************************************************/ 9 | 10 | #include // include the LiquidCrystal library 11 | int LCDcol =16; // number of LCD columns 12 | int LCDrow = 4; // number of LCD rows 13 | // associate lcd with LiquidCrystal library 14 | LiquidCrystal lcd(2,3,4,5,6,7) ; // define LCD pins RS, E and D4 to D7 15 | int first; // position of first letter in 16 character substring 16 | int last = 0; // position of last letter in 16 character substring 17 | int row = 1; // row of LCD to display text 18 | int col; 19 | String text = "The quick brown fox jumps over the lazy dog \ 20 | contains every letter of the alphabet."; 21 | void setup() 22 | { 23 | lcd.begin(LCDcol, LCDrow); // define LCD dimensions 24 | text = text + " "; // add space at end of text as a buffer 25 | } 26 | 27 | void loop() 28 | { 29 | if(last>text.length()+15) last=1; // set first column of substring 30 | if(last<17) first = 0; // substring<17 characters, start character =0 31 | else first = last-16; // substring>=17 characters, start character = last-16 32 | if(last>16) col = 0; // substring>16 characters, start column = 0 33 | else col = 16-last; // substring<=16 characters, start column = last-16 34 | lcd.setCursor(col,row); // set cursor position 35 | lcd.print(text.substring(first, last)); // print substring 36 | last = last +1; // increment last 37 | delay(250); // delay 250ms 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Chapter 4/Listing4-3/Listing4-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: I2C addresses 3 | * Description: display I2C address of connected devices 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 4 - Liquid crystal display 8 | ******************************************************************************/ 9 | 10 | #include // include Wire library 11 | int device = 0; // set device counter to 0 12 | 13 | void setup() 14 | { 15 | Serial.begin (9600); // set Serial output baud rate 16 | Wire.begin(); // start I2C bus 17 | for (int i=8; i<127; i++) // scan through channels 8 to 126 18 | { 19 | Wire.beginTransmission (i); // transmit to device at address i 20 | if (Wire.endTransmission () == 0) // device response to transmission 21 | { 22 | Serial.print("Address 0x"); // print to screen "Address 0x" 23 | Serial.println(i, HEX); // print to screen I2C address in HEX 24 | device++; // increment device count 25 | delay(10); // delay 10ms 26 | } 27 | } 28 | Serial.print(device); // print to screen device count 29 | Serial.println(" device found"); // print to screen " device found" 30 | } 31 | 32 | void loop() 33 | { } 34 | 35 | -------------------------------------------------------------------------------- /Chapter 4/Listing4-5/Listing4-5.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: cursor position on 16x4 LCD 3 | * Description: demsonstrate starting address on third and fourth row of 16x4 LCD 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 4 - Liquid crystal display 8 | ******************************************************************************/ 9 | 10 | #include // include Wire library 11 | #include // include LiquidCrystal_I2C 12 | int I2Caddress = 0x3F; // address of I2C bus 13 | int LCDcol =16; // number of LCD columns 14 | int LCDrow = 4; // number of LCD rows 15 | LiquidCrystal_I2C lcd(I2Caddress,LCDcol,LCDrow); 16 | 17 | void setup() 18 | { 19 | lcd.init(); // initialize the lcd 20 | } 21 | 22 | void loop() 23 | { 24 | for (int col=0; col<16; col++) 25 | { 26 | lcd.clear(); // clear the LCD 27 | lcd.setCursor(col,0); // first row 28 | lcd.print("A"); 29 | lcd.setCursor(col,1); // second row 30 | lcd.print("B"); 31 | lcd.setCursor(col-4,2); // reduce col by 4 in the third row 32 | lcd.print("C"); 33 | lcd.setCursor(col-4,3); // reduce col by 4 in the fourth row 34 | lcd.print("D"); 35 | delay(500); 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Chapter 4/Listing4-6/Listing4-6.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: display on LCD characters entered on keyboard 3 | * Description: display on LCD characters entered on keyboard 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 4 - Liquid crystal display 8 | ******************************************************************************/ 9 | 10 | #include // include Wire library 11 | #include // include LiquidCrystal_I2C library 12 | int I2Caddress = 0x3F; // address of I2C bus 13 | int LCDcol =16; // number of LCD columns 14 | int LCDrow = 4; // number of LCD rows 15 | // associate lcd with LiquidCrystal_I2C library 16 | LiquidCrystal_I2C lcd(I2Caddress,LCDcol,LCDrow); // I2C address and LCD size 17 | 18 | void setup() 19 | { 20 | lcd.init(); // initialize LCD 21 | Serial.begin(9600); // define Serial output baud rate 22 | } 23 | 24 | void loop() 25 | { 26 | if (Serial.available()>0) // if data in Serial input buffer 27 | { 28 | lcd.clear(); // clear the LCD 29 | while (Serial.available()>0) lcd.write(Serial.read()); // read, display input buffer 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /Chapter 4/Listing4-7/Listing4-7.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: display LCD character set 3 | * Description: display LCD character set on 16x4 LCD 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 4 - Liquid crystal display 8 | ******************************************************************************/ 9 | 10 | #include // include Wire library 11 | #include // include LCD with I2C library 12 | int I2Caddress = 0x3F; // I2C address of I2C bus 13 | // associate lcd with LiquidCrystal_I2C library 14 | LiquidCrystal_I2C lcd(I2Caddress,16,4); // I2C address and LCD size 15 | int screen = 1; 16 | int j,start; 17 | 18 | void setup() 19 | { 20 | lcd.init(); // initialise LCD 21 | Serial.begin(9600); // define Serial output baud rate 22 | Serial.print("Enter screen number 1 to 4"); // print message to Serial Monitor 23 | } 24 | 25 | void loop() 26 | { // read screen from Serial buffer 27 | while (Serial.available()>0) screen = Serial.parseInt(); 28 | for (j=(screen-1)*4; j1) lcd.setCursor(0-4,(j%4)); // reduce col by 4 for rows 3 and 4 32 | start = j*16; // 16 characters per row 33 | for (int i=0; i<16; i++) lcd.print(char(i+start)); // display characters by row 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /Chapter 4/Listing4-8/Listing4-8.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: additional characters 3 | * Description: create additional characters and dsiplay on 16x4 LCD 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 4 - Liquid crystal display 8 | ******************************************************************************/ 9 | 10 | #include 11 | #include 12 | int LCDcol =16; // number of LCD columns 13 | int LCDrow = 4; // number of LCD rows 14 | int I2Caddress = 0x3F; // I2C address of bus 15 | LiquidCrystal_I2C lcd(I2Caddress,LCDcol,LCDrow); // associate lcd with LiquidCrystal library 16 | byte clock[8] = {0, 14, 21, 23, 17, 14, 0}; 17 | byte tick[8] = {0, 1, 3, 22, 28, 8, 0}; 18 | byte cross[8] = {0, 27, 14, 4, 14, 27, 0}; 19 | 20 | void setup() 21 | { 22 | lcd.init(); 23 | lcd.createChar(0, clock); 24 | lcd.createChar(1, tick); 25 | lcd.createChar(2, cross); 26 | lcd.setCursor(0,0); 27 | for (int i=0;i<3;i++) lcd.write(i); 28 | } 29 | 30 | void loop() 31 | {} 32 | -------------------------------------------------------------------------------- /Chapter 5/Listing5-1/Listing5-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: 7-segment LED display 3 | * Description: simple display of numbers 2 and 6 on 7-segment LED display 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 5 - Seven segment LED display 8 | ******************************************************************************/ 9 | 10 | int pinA = 2; // yellow wire to display LED a 11 | int pinB = 3; // blue wire to display LED b 12 | int pinC = 4; // yellow wire to display LED c 13 | int pinD = 5; // blue wire to display LED d 14 | int pinE = 6; // yellow wire to display LED e 15 | int pinF = 7; // blue wire to display LED f 16 | int pinG = 8; // yellow wire to display LED g 17 | 18 | void setup() 19 | { 20 | pinMode (pinA, OUTPUT); // define LED pins as output 21 | pinMode (pinB, OUTPUT); 22 | pinMode (pinC, OUTPUT); 23 | pinMode (pinD, OUTPUT); 24 | pinMode (pinE, OUTPUT); 25 | pinMode (pinF, OUTPUT); 26 | pinMode (pinG, OUTPUT); 27 | } 28 | void loop() 29 | { 30 | digitalWrite(pinA, HIGH); // display number two 31 | digitalWrite(pinB, HIGH); 32 | digitalWrite(pinC, LOW); 33 | digitalWrite(pinD, HIGH); 34 | digitalWrite(pinE, HIGH); 35 | digitalWrite(pinF, LOW); 36 | digitalWrite(pinG, HIGH); 37 | delay(1000); 38 | digitalWrite(pinA, HIGH); // display number six 39 | digitalWrite(pinB, LOW); 40 | digitalWrite(pinC, HIGH); 41 | digitalWrite(pinD, HIGH); 42 | digitalWrite(pinE, HIGH); 43 | digitalWrite(pinF, HIGH); 44 | digitalWrite(pinG, HIGH); 45 | delay(1000); 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Chapter 5/Listing5-2/Listing5-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: 7-segment LED display 3 | * Description: efficient display of numbers 2 and 6 on 7-segment LED display 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 5 - Seven segment LED display 8 | ******************************************************************************/ 9 | 10 | int LEDs[ ] = {2,3,4,5,6,7,8}; // define LED pins 11 | int two[ ] = {1,1,0,1,1,0,1}; // LED states to display number two 12 | int six[ ] = {1,0,1,1,1,1,1}; // LED states to display number six 13 | 14 | void setup() 15 | { // define LED pins as OUTPUT 16 | for (int i = 0; i<7; i++) pinMode (LEDs[i], OUTPUT); 17 | } 18 | 19 | void loop() 20 | { 21 | for (int i = 0; i<7; i++) digitalWrite(LEDs[i], two[i]); // display number two 22 | delay(1000); // delay 1s 23 | for (int i = 0; i<7; i++) digitalWrite(LEDs[i], six[i]); // display number six 24 | delay(1000); 25 | } 26 | 27 | -------------------------------------------------------------------------------- /Chapter 5/Listing5-3/Listing5-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: display numbers zero, one, two and seven 3 | * Description: PWM to control LED brightness of numbers on 7-segment LED display 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 5 - Seven segment LED display 8 | ******************************************************************************/ 9 | 10 | int LEDpin[ ] = {9,10,11,5,6,7,8}; // define LED pins with PWM for LEDs a, b and c 11 | int one[ ] = {0,72,72,0,0,0,0}; // LED brightness to display number one 12 | int two[ ] = {1,1,0,1,1,0,1}; // LED states to display number two 13 | int three[ ] = {1,1,1,1,0,0,1}; 14 | int four[ ] = {0,1,1,0,0,1,1}; 15 | int five[ ] = {1,0,1,1,0,1,1}; 16 | int six[ ] = {1,0,1,1,1,1,1}; 17 | int seven[ ] = {109,109,109,0,0,0,0}; // LED brightness to display number seven 18 | int eight[ ] = {1,1,1,1,1,1,1}; 19 | int nine[ ] = {1,1,1,1,0,1,1}; 20 | int zero[ ] = {1,1,1,1,1,1,0}; 21 | 22 | void setup() 23 | { 24 | for (int i = 0; i<7; i++) pinMode (LEDpin[i], OUTPUT); // define LED pins as OUTPUT 25 | } 26 | 27 | void loop() 28 | { 29 | for (int i = 0; i<7; i++) digitalWrite(LEDpin[i],0); // turn off all LEDs 30 | delay(10); 31 | for (int i = 0; i<3; i++) analogWrite(LEDpin[i], one[i]); // display number one 32 | delay(1000); 33 | for (int i = 0; i<7; i++) digitalWrite(LEDpin[i], two[i]); // display number two 34 | delay(1000); 35 | for (int i = 0; i<7; i++) digitalWrite(LEDpin[i],0); // turn off all LEDs 36 | delay(10); 37 | for (int i = 0; i<3; i++) analogWrite(LEDpin[i], seven[i]); // display number seven 38 | delay(1000); 39 | for (int i = 0; i<7; i++) digitalWrite(LEDpin[i], zero[i]); // display number zero 40 | delay(1000); // delay 1s 41 | } 42 | 43 | -------------------------------------------------------------------------------- /Chapter 5/Listing5-4/Listing5-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: display brightness dependent on incident light 3 | * Description: shift register with PWM to control display brightness on 7-segment LED display 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 5 - Seven segment LED display 8 | ******************************************************************************/ 9 | 10 | int clockPin = 2; // shift register CLOCK pin 11 | int latchPin = 3; // shift register LATCH pin 12 | int dataPin = 4; // shift register DATA pin 13 | int num[ ] = {63,6,91,79,102,109,125,7,127,111}; // representation of numbers 0 to 9 14 | int Vdivid = A5; // voltage divider pin 15 | int PWMpin = 11; // shift register OE pin used for PWM 16 | int reading, bright; 17 | 18 | void setup() 19 | { 20 | pinMode (clockPin, OUTPUT); // define shift register CLOCK pin as output 21 | pinMode (latchPin, OUTPUT); // define shift register LATCH pin as output 22 | pinMode (dataPin, OUTPUT); // define shift register DATA pin as output 23 | } 24 | 25 | void loop() 26 | { 27 | for (int i=0; i<10; i++) // for each number 0 to 9 28 | { 29 | reading = analogRead(Vdivid); // voltage divider reading 30 | bright = map(reading, 0, 1023, 255, 0); // map reading to LED brightness 31 | analogWrite(PWMpin, bright); // change LED brightness 32 | digitalWrite(latchPin, LOW); // set the latch to LOW 33 | shiftOut(dataPin,clockPin,MSBFIRST,num[i]); // LED states as a number 34 | digitalWrite(latchPin, HIGH); // change number pattern 35 | delay(1000); // delay 1s 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Chapter 5/Listing_in_Table5.2/Listing_in_Table5.2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: Numbers zero to nine in Table 5.2 3 | * Description: use shift register to display zero to nine on 7-segment LED display 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 5 - Seven segment LED display 8 | ******************************************************************************/ 9 | 10 | int clockPin = 2; // shift register CLOCK pin 11 | int latchPin = 3; // shift register LATCH pin 12 | int dataPin = 4; // shift register DATA pin 13 | int num[ ] = {63,6,91,79,102,109,125,7,127,111}; // representation of numbers 0 to 9 14 | 15 | void setup() 16 | { 17 | pinMode (clockPin, OUTPUT); // define shift register CLOCK pin as output 18 | pinMode (latchPin, OUTPUT); // define shift register LATCH pin as output 19 | pinMode (dataPin, OUTPUT); // define shift register DATA pin as output 20 | } 21 | 22 | void loop() 23 | { 24 | for (int i=0; i<10; i++) // for each number 0 to 9 25 | { 26 | digitalWrite(latchPin, LOW); // set the latch to LOW 27 | shiftOut(dataPin,clockPin,MSBFIRST,num[i]); // LED states as a number 28 | digitalWrite(latchPin, HIGH); // change number pattern 29 | delay(1000); // delay 1s 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /Chapter 6/Listing6-1/Listing6-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: 4-digit 7-segment display as timer 3 | * Description: simple use of 4-digit 7-segment display as timer 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 6 - 4-digit 7-segment LED display 8 | ******************************************************************************/ 9 | 10 | int pins[ ] = {2,3,4,5,6,7,8}; // LED pins 11 | int digits[ ] = {10,11,12,13}; // digit control pins 12 | int zero[ ] ={1,1,1,1,1,1,0}; // LED states for zero 13 | int one[ ] = {0,1,1,0,0,0,0}; // LED states for one 14 | int two[ ] = {1,1,0,1,1,0,1}; 15 | int three[ ] = {1,1,1,1,0,0,1}; 16 | int four[ ] = {0,1,1,0,0,1,1}; 17 | int five[ ] = {1,0,1,1,0,1,1}; 18 | int six[ ] = {1,0,1,1,1,1,1}; 19 | int seven[ ] = {1,1,1,0,0,0,0}; 20 | int eight[ ] = {1,1,1,1,1,1,1}; 21 | int nine[ ] = {1,1,1,1,0,1,1}; 22 | int time, n; 23 | int del = 5; // time delay (ms) 24 | 25 | void setup() 26 | { 27 | for (int i = 0; i<7; i++) pinMode (pins[i], OUTPUT); // define pins and digits as output 28 | for (int i = 0; i<4; i++) pinMode (digits[i], OUTPUT); 29 | } 30 | 31 | void loop() 32 | { 33 | time = millis()/1000; // time is number of seconds 34 | digit(0); // digit D1 for thousands 35 | number(time/1000); // number to be displayed 36 | delay(del); 37 | digit(1); // digit D2 for hundreds 38 | number((time%1000)/100); // modulus(time, 1000)/100 39 | delay(del); 40 | digit(2); // digit D3 for tens 41 | number((time%100)/10); // modulus(time, 100)/10 42 | delay(del); 43 | digit(3); // digit D4 for units 44 | number(time%10); // modulus(time, 10) 45 | delay(del); 46 | } 47 | 48 | void digit(int d) 49 | { 50 | for (int i = 0; i<4; i++) digitalWrite(digits[i], 1); // turn all digits off 51 | digitalWrite(digits[d], 0); // digit pin state is LOW, digit display is on 52 | } 53 | 54 | void number(int n) 55 | { 56 | if (n==0) for (int i = 0; i<7; i++) digitalWrite(pins[i], zero[i]); // display zero 57 | else if (n==1) for (int i = 0; i<7; i++) digitalWrite(pins[i], one[i]); // display one 58 | else if (n==2) for (int i = 0; i<7; i++) digitalWrite(pins[i], two[i]); // display two 59 | else if (n==3) for (int i = 0; i<7; i++) digitalWrite(pins[i], three[i]); 60 | else if (n==4) for (int i = 0; i<7; i++) digitalWrite(pins[i], four[i]); 61 | else if (n==5) for (int i = 0; i<7; i++) digitalWrite(pins[i], five[i]); 62 | else if (n==6) for (int i = 0; i<7; i++) digitalWrite(pins[i], six[i]); 63 | else if (n==7) for (int i = 0; i<7; i++) digitalWrite(pins[i], seven[i]); 64 | else if (n==8) for (int i = 0; i<7; i++) digitalWrite(pins[i], eight[i]); 65 | else if (n==9) for (int i = 0; i<7; i++) digitalWrite(pins[i], nine[i]); 66 | } 67 | 68 | -------------------------------------------------------------------------------- /Chapter 6/Listing6-4/Listing6-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: temperature and time display 3 | * Description: control temperature and time display with one 74HC595 shift register 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 6 - 4-digit 7-segment LED display 8 | ******************************************************************************/ 9 | 10 | int dataPin = 2; // shift register DATA pin 11 | int latchPin = 3; // shift register LATCH pin 12 | int clockPin = 4; // shift register CLOCK pin 13 | int digits[ ] = {10,11,12,13}; // four digit pins 14 | int numbers[ ] = {63,6,91,79,102,109,125,7,127,111}; // "values" of numbers 0 to 9 15 | int del = 5; // delay after turning digit on 16 | int tempPin = A5; // temperature sensor pin 17 | int duration = 5000; // display duration 18 | unsigned long start; 19 | int time, n, temp, reading; 20 | 21 | void setup() 22 | { 23 | pinMode (dataPin, OUTPUT); // define shift register DATA pin as output 24 | pinMode (latchPin, OUTPUT); // define shift register LATCH pin as output 25 | pinMode (clockPin, OUTPUT); // define shift register CLOCK pin as output 26 | for (int i = 0; i<4; i++) pinMode (digits[i], OUTPUT); // four digit pins as output 27 | analogReference (INTERNAL); // set ADC voltage to 1.1V rather than 5V 28 | } 29 | 30 | void loop() 31 | { 32 | start = millis(); // milliseconds elapsed 33 | while (millis()-startduration && millis()-start<2*duration) 45 | { 46 | digit(1, (temp%1000)/100, 0); // digit D2 for tens 47 | digit(2, (temp%100)/10, 1); // digit D3 for units 1 for DP 48 | digit(3, temp%10, 0); // digit D4 for decimal places 49 | } 50 | } 51 | 52 | void digit(int d, int n, int DP) 53 | { 54 | for (int i = 0; i<4; i++) digitalWrite(digits[i], 1); // turn all digits off, digit states are HIGH 55 | digitalWrite(latchPin, LOW); 56 | shiftOut(dataPin, clockPin, MSBFIRST, numbers[n]+DP*128); // add 128 for DP 57 | digitalWrite(latchPin, HIGH); // change display pattern 58 | digitalWrite(digits[d], 0); // turn digit on, digit state LOW 59 | delay(del); // delay del (ms) 60 | } 61 | 62 | -------------------------------------------------------------------------------- /Chapter 6/Listing6-5/Listing6-5.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: second shift register control of digits 3 | * Description: control temperature and time display with two 74HC595 shift registers 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 6 - 4-digit 7-segment LED display 8 | ******************************************************************************/ 9 | 10 | int dataPin = 2; // shift register DATA pin 11 | int latchPin = 3; // shift register LATCH pin 12 | int clockPin = 4; // shift register CLOCK pin 13 | // int digits[ ] = {10,11,12,13}; // four digit pins 14 | int digits[] ={28,26,22,14}; 15 | int numbers[ ] = {63,6,91,79,102,109,125,7,127,111}; // "values" of numbers 0 to 9 16 | int del = 5; // delay after turning digit on 17 | int tempPin = A5; // temperature sensor pin 18 | int duration = 5000; // display duration 19 | unsigned long start; 20 | int time, n, temp, reading; 21 | 22 | void setup() 23 | { 24 | pinMode (dataPin, OUTPUT); // define shift register DATA pin as output 25 | pinMode (latchPin, OUTPUT); // define shift register LATCH pin as output 26 | pinMode (clockPin, OUTPUT); // define shift register CLOCK pin as output 27 | for (int i = 0; i<4; i++) pinMode (digits[i], OUTPUT); // four digit pins as output 28 | analogReference (INTERNAL); // set ADC voltage to 1.1V rather than 5V 29 | } 30 | 31 | void loop() 32 | { 33 | start = millis(); // milliseconds elapsed 34 | while (millis()-startduration && millis()-start<2*duration) 46 | { 47 | digit(1, (temp%1000)/100, 0); // digit D2 for tens 48 | digit(2, (temp%100)/10, 1); // digit D3 for units 1 for DP 49 | digit(3, temp%10, 0); // digit D4 for decimal places 50 | } 51 | } 52 | 53 | void digit(int d, int n, int DP) 54 | { 55 | // for (int i = 0; i<4; i++) digitalWrite(digits[i], 1); // turn all digits off, digit states are HIGH 56 | digitalWrite(latchPin, LOW); 57 | shiftOut(dataPin, clockPin, MSBFIRST, digits[d]); // data from 2nd shift register 58 | shiftOut(dataPin, clockPin, MSBFIRST, numbers[n]+DP*128); // add 128 for DP 59 | digitalWrite(latchPin, HIGH); // change display pattern 60 | // digitalWrite(digits[d], 0); // turn digit on, digit state LOW 61 | delay(del); // delay del (ms) 62 | } 63 | 64 | -------------------------------------------------------------------------------- /Chapter 7/Listing7-1/Listing7-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: display letters A, B and C 3 | * Description: simple display of letters on 8x8 dot matrix display 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 7 - 8x8 dot matrix display 8 | ******************************************************************************/ 9 | 10 | // Arduino to display pins 11 | int pin[ ] = {19,13,12,9,8,11,7,10,17,16,6,5,15,4,14,3,2}; 12 | // dot matrix display columns 13 | int col[ ] = {pin[13],pin[3],pin[4],pin[10],pin[6],pin[11],pin[15],pin[16]}; 14 | // dot matrix display rows 15 | int row[ ] = {pin[9],pin[14],pin[8],pin[12],pin[1],pin[7],pin[2],pin[5]}; 16 | byte val[3][8] = {4,10,17,17,31,17,17,0, // decimal representation of letter A 17 | 15,17,17,15,17,17,15,0, // decimal representation of letter B 18 | 14,17,1,1,1,17,14,0}; // decimal representation of letter C 19 | unsigned long start; 20 | bool pixel; 21 | 22 | void setup() 23 | { 24 | for (int i=1; i<18; i++) pinMode(pin[i], OUTPUT); // display pins as output 25 | for (int i=0;i<8;i++) digitalWrite(col[i], LOW); // set anodes LOW – turn off 26 | for (int i=0;i<8;i++) digitalWrite(row[i], HIGH); // set cathodes HIGH – turn off 27 | } 28 | 29 | void loop() 30 | { 31 | for (int n=0; n<3; n++) // display the letters A, B, C 32 | { 33 | start = millis(); // milliseconds elapsed 34 | while (millis() < start+1000) // display time for each letter 35 | for (int r=0; r<8; r++) 36 | { 37 | digitalWrite(row[r], LOW); // set cathodes to LOW for each row 38 | for (int c=0; c<8; c++) 39 | { 40 | pixel = bitRead(val[n][r], c); // read cth bit in rth row of nth letter 41 | if(pixel == 1) digitalWrite(col[c], HIGH); // set anode (column) HIGH, LED on 42 | delayMicroseconds(200); // delay between LEDs in a row 43 | digitalWrite(col[c], LOW); // reset anode to LOW, LED off 44 | } 45 | digitalWrite(row[r], HIGH); // reset cathode to HIGH 46 | } 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /Chapter 7/Listing7-2/Listing7-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: display letters A, B and C with shift register 3 | * Description: use 74HC595 shift register to display letters on 8x8 dot matrix 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 7 - 8x8 dot matrix display 8 | ******************************************************************************/ 9 | 10 | // Arduino to display pins 11 | int pin[ ] = {19,13,12,9,8,11,7,10,17,16,6,5,15,4,14,3,2}; 12 | // dot matrix display rows 13 | int row[ ] = {pin[9],pin[14],pin[8],pin[12],pin[1],pin[7],pin[2],pin[5]}; 14 | byte val[3][8] = {4,10,17,17,31,17,17,0, // decimal representation of letter A 15 | 15,17,17,15,17,17,15,0, // decimal representation of letter B 16 | 14,17,1,1,1,17,14,0}; // decimal representation of letter C 17 | int dataPin = 2; // shift register DATA pin 18 | int latchPin = 3; // shift register LATCH pin 19 | int clockPin = 4; // shift register CLOCK pin 20 | unsigned long start; 21 | 22 | void setup() 23 | { 24 | pinMode (dataPin, OUTPUT); // define shift register DATA pin as output 25 | pinMode (latchPin, OUTPUT); // define shift register LATCH pin as output 26 | pinMode (clockPin, OUTPUT); // define shift register CLOCK pin as output 27 | for (int i=1; i<17; i++) pinMode(pin[i], OUTPUT); // display pins as output 28 | for (int i=0; i<8; i++) digitalWrite(row[i], HIGH); // set cathodes HIGH, LEDs off 29 | } 30 | 31 | void loop() 32 | { 33 | for (int n=0; n<3; n++) // display the letters A, B, C 34 | { 35 | start = millis(); // milliseconds elapsed 36 | while (millis()0) // message read from Serial Monitor 30 | { 31 | data=Serial.read(); // message read one letter at a time 32 | Serial.print(data); 33 | // decimal representation of letter 34 | for (int lett=0; lett<63 ;lett++) if(data == letters[lett]) n=lett; 35 | for (int i=0; i<8;i++) // convert row to column orientation 36 | { 37 | cols[i]=0; // change to column orientation 38 | for (int j=0; j<8; j++) cols[i]= cols[i] + (bitRead(val[n][j],i)<0) 47 | { 48 | digitalWrite(latchPin,LOW); // change display pattern 49 | shiftOut(dataPin, clockPin, MSBFIRST,~cols[c]); 50 | shiftOut(dataPin, clockPin, MSBFIRST, (1<<7+c-t)); // shift by one column 51 | digitalWrite(latchPin,HIGH); 52 | } 53 | } 54 | } 55 | } 56 | } 57 | 58 | -------------------------------------------------------------------------------- /Chapter 7/Listing7-4/letters.h: -------------------------------------------------------------------------------- 1 | char letters[] ={'A','B','C','D','E','F','G','H','I','J','K','L','M', 2 | 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 3 | 'a','b','c','d','e','f','g','h','i','j','k','l','m', 4 | 'n','o','p','q','r','s','t','u','v','w','x','y','z', 5 | '0','1','2','3','4','5','6','7','8','9',' '}; 6 | 7 | byte val[63][8] = {4,10,17,17,31,17,17,0, 8 | 15,17,17,15,17,17,15,0, 9 | 14,17,1,1,1,17,14,0, 10 | 7,9,17,17,17,9,7,0, 11 | 31,1,1,15,1,1,31,0, 12 | 31,1,1,15,1,1,1,0, 13 | 14,17,1,13,17,25,22,0, 14 | 17,17,17,31,17,17,17,0, 15 | 7,2,2,2,2,2,7,0, 16 | 28,8,8,8,8,9,6,0, 17 | 17,9,5,3,5,9,17,0, 18 | 1,1,1,1,1,1,15,0, 19 | 17,27,21,21,17,17,17,0, 20 | 17,19,19,21,25,25,17,0, 21 | 14,17,17,17,17,17,14,0, 22 | 15,17,17,15,1,1,1,0, 23 | 14,17,17,17,21,9,22,0, 24 | 15,17,17,15,5,9,17,0, 25 | 14,17,1,14,16,17,14,0, 26 | 31,4,4,4,4,4,4,0, 27 | 17,17,17,17,17,17,14,0, 28 | 17,17,17,17,10,10,4,0, 29 | // old W 65,65,65,73,42,42,20,0, 30 | 17,17,17,21,21,27,17,0, 31 | 17,17,10,4,10,17,17,0, 32 | 17,17,17,10,4,4,4,0, 33 | 31,16,8,4,2,1,31,0, // Z 34 | 0,0,6,8,14,9,14,0, // a 35 | 1,1,13,19,17,19,13,0, 36 | 0,0,6,9,1,9,6,0, 37 | 16,16,22,25,17,25,22,0, 38 | 0,0,6,9,7,1,14,0, 39 | 4,10,2,7,2,2,2,0, 40 | 0,0,6,9,9,6,8,7, 41 | 1,1,13,19,17,17,17,0, 42 | 1,0,1,1,1,1,2,0, 43 | 4,0,6,4,4,4,4,3, 44 | 1,1,9,5,3,5,9,0, 45 | 3,2,2,2,2,2,2,0, 46 | 0,0,21,43,41,41,41,0, 47 | 0,0,13,19,17,17,17,0, 48 | 0,0,6,9,9,9,6,0, 49 | 0,0,13,19,19,13,1,1, 50 | 0,0,22,25,25,22,16,16, 51 | 0,0,13,19,1,1,1,0, 52 | 0,0,14,1,6,8,7,0, 53 | 0,2,7,2,2,2,4,0, 54 | 0,0,17,17,17,25,22,0, 55 | 0,0,17,17,17,10,4,0, 56 | 0,0,17,17,21,21,10,0, 57 | 0,0,17,10,4,10,17,0, 58 | 0,0,9,9,9,14,8,6, 59 | 0,0,15,8,6,1,15,0, 60 | 14,17,25,21,19,17,14,0, 61 | 4,6,4,4,4,4,14,0, 62 | 14,17,16,12,2,1,31,0, 63 | 14,17,16,12,16,17,14,0, 64 | 8,12,10,9,31,8,8,0, 65 | 31,1,1,14,16,17,14,0, 66 | 12,2,1,15,17,17,14,0, 67 | 31,16,8,4,2,2,2,0, 68 | 14,17,17,14,17,17,14,0, 69 | 14,17,17,30,16,8,6,0, 70 | 0,0,0,0,0,0,0,0}; 71 | -------------------------------------------------------------------------------- /Chapter 8/Listing8-1/Listing8-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: servo motor 3 | * Description: move servo motor clockwise and anti-clockwise incrementally 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 8 - Servo and stepper motors 8 | ******************************************************************************/ 9 | 10 | #include // include Servo library 11 | Servo servo; // associate servo with Servo library 12 | int servoPin = 11; // servo motor pin 13 | 14 | void setup() 15 | { 16 | servo.attach(servoPin); // define servo motor pin to Servo library 17 | } 18 | 19 | void loop() 20 | { 21 | for (int i=0; i<19; i++) 22 | { 23 | servo.write(10 * i); // rotate to angles 0, 10, 20 … 180 24 | delay(500); // delay 500ms between movements 25 | } 26 | for (int i=8; i>=0; i--) 27 | { 28 | servo.write(20 * i); // rotate to angles 160, 140 … 0 29 | delay(500); // delay 500ms between movements 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /Chapter 8/Listing8-2/Listing8-2.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: updated void loop 3 | * Description: control servo motor rotation with potentiometer 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 8 - Servo and stepper motors 8 | ******************************************************************************/ 9 | 10 | #include // include Servo library 11 | Servo servo; // associate servo with Servo library 12 | int servoPin = 11; // servo motor pin 13 | int potPin = A1; // potentiometer pin 14 | int reading, angle; 15 | 16 | void setup() 17 | { 18 | servo.attach(servoPin); // define servo motor pin to Servo library 19 | } 20 | 21 | void loop() 22 | { 23 | reading = analogRead(potPin); // potentiometer voltage 24 | angle = map(reading, 0, 1023, 5, 175); // map voltage to angle 25 | servo.write(angle); // move servo to angle 26 | delay(10); // delay 10ms 27 | } 28 | 29 | 30 | -------------------------------------------------------------------------------- /Chapter 8/Listing8-3/Listing8-3.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: servo motot with LDR 3 | * Description: control servo motor rotation with light dependent resistor 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 8 - Servo and stepper motors 8 | ******************************************************************************/ 9 | 10 | #include // include servo library 11 | Servo servo; // associate servo with Servo library 12 | int servoPin = 11; // servo motor pin 13 | int LDRpin = A0; // LDR on analog pin A1 14 | int maxLDR = 0; // maximum LDR reading 15 | int reading, maxAngle; 16 | 17 | void setup() 18 | { 19 | servo.attach(servoPin); // define servo motor pin to servo library 20 | Serial.begin(9600); // define Serial output baud rate 21 | } 22 | 23 | void loop() 24 | { 25 | for (int angle=0; angle<190; angle = angle + 10) // scan from angle 0° to 180° 26 | { 27 | servo.write(angle); // rotate servo motor 28 | reading = analogRead(LDRpin); // read light dependent resistor 29 | if (reading>maxLDR) // compare reading to maximum 30 | { 31 | maxLDR = reading; // update maximum light reading 32 | maxAngle = angle; // update angle of max light reading 33 | } 34 | delay(50); // delay 50ms between LDR readings 35 | } 36 | Serial.print("Light source at "); // print text to Serial Monitor 37 | Serial.print(maxAngle); // print angle of incident light 38 | Serial.println(" degrees"); // print " degrees" to Serial Monitor 39 | servo.write(maxAngle); // rotate servo to point at the light source 40 | delay(1000); // delay while pointing at light source 41 | maxLDR=0; // reset maximum light reading 42 | servo.write(0); // rotate to 0° 43 | delay(500); // delay 500ms 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Chapter 8/Listing8-4/Listing8-4.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: stepper motor with Stepper library 3 | * Description: move stepper motor and change motor speed 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 8 - Servo and stepper motors 8 | ******************************************************************************/ 9 | 10 | #include // include Stepper library 11 | int blue = 12; 12 | int pink = 11; // coil activation order on ULN2003 13 | int yellow = 10; // blue, pink, yellow, orange 14 | int orange = 9; 15 | int steps = 2038; // steps per revolution 16 | // associate stepper with Stepper library 17 | Stepper stepper(steps, blue, yellow, pink, orange); // coil pairing order 18 | int direct = 1; // direction of rotation 19 | int revTime; 20 | float secs, revs; 21 | 22 | void setup() 23 | { 24 | Serial.begin(9600); // define Serial output baud rate 25 | Serial.println("rpm time(s) revs"); // print header to Serial Monitor 26 | } 27 | 28 | void loop() 29 | { 30 | for (int i = 2; i<19; i=i+2) // motor speed from 2 to 18 rpm 31 | { 32 | stepper.setSpeed(i); // set motor speed (rpm) 33 | direct = -direct; // change direction of rotation 34 | revTime = millis(); // set start time (ms) 35 | stepper.step(direct * steps/2); // move number of steps 36 | revTime = millis()-revTime; // time for half revolution (ms) 37 | delay(500); // delay 0.5s 38 | secs = revTime/1000.0; // time (s) to move steps 39 | revs = i*secs/60.0; // check number of revolutions 40 | Serial.print(i);Serial.print("\t"); // print speed on Serial Monitor 41 | Serial.print(secs);Serial.print("\t"); // print time 42 | Serial.println(revs,3); // print number of revolutions 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Chapter 8/Listing8-5/Listing8-5.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: stepper motor with Accelstepper library 3 | * Description: move stepper motor and change motor speed with fixed accelaration 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 8 - Servo and stepper motors 8 | ******************************************************************************/ 9 | 10 | #include // include Accelstepper library 11 | int blue = 12; 12 | int pink = 11; // coil activation order on ULN2003 13 | int yellow = 10; // blue, pink, yellow, orange 14 | int orange = 9; 15 | int fullstep = 4; // number of coil activation stages 16 | int halfstep = 8; // with full-step and half-step 17 | int coil = halfstep; // set to full-step or to half-step 18 | // associate stepper with AccelStepper library 19 | AccelStepper stepper(coil, blue, yellow, pink, orange); // coil pairing order 20 | int steps = (coil/4)*2038; // number of steps per revolution 21 | long last = 0; 22 | int lag = 500; //time (ms) interval for display 23 | int direct = 1; // direction of rotation 24 | float rpm, speed, oldspeed, accel; 25 | int nsteps; 26 | 27 | void setup() 28 | { 29 | Serial.begin(9600); // define Serial output baud rate 30 | stepper.setMaxSpeed((coil/4)*700); // max speed 700 or 1400 steps/s 31 | stepper.setAcceleration(600); // acceleration rate (steps/s2) 32 | Serial.println("steps rpm accel"); // print header to Serial Monitor 33 | } 34 | 35 | void loop() 36 | { 37 | stepper.moveTo(direct*steps/2); // move to position ±1019 or ±2038 38 | if(stepper.distanceToGo()==0) direct = -direct; // change direction of rotation 39 | if(millis()>last + lag) // lag time elapsed since last print 40 | { 41 | speed = stepper.speed(); // current motor speed (steps/s) 42 | nsteps = speed*lag/pow(10,3); // steps/s taken during lag time 43 | Serial.print(nsteps);Serial.print("\t"); // display number of steps and a tab 44 | rpm = 60.0*speed/steps; // derive rpm 45 | Serial.print(rpm,2);Serial.print("\t"); // display rpm to 2DP on Serial Monitor 46 | accel = (speed - oldspeed)*1000.0/lag; // derived acceleration rate (steps/s2) 47 | Serial.println(accel,0); // display acceleration 48 | oldspeed = speed; // update speed value 49 | last = millis(); // update last print time 50 | } 51 | stepper.run(); // update motor to move to new position 52 | } 53 | 54 | -------------------------------------------------------------------------------- /Chapter 8/Listing8-7/Listing8-7.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: stepper motor and potentiometer 3 | * Description: control stepper motor rotation with potentiometer 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 8 - Servo and stepper motors 8 | ******************************************************************************/ 9 | 10 | #include // include Accelstepper library 11 | int blue = 12; 12 | int pink = 11; // coil activation order on ULN2003 13 | int yellow = 10; // blue, pink, yellow, orange 14 | int orange = 9; 15 | int fullstep = 4; // number of coil activation stages 16 | int coil = fullstep; // set number of coil activation stages 17 | // associate stepper with AccelStepper library 18 | AccelStepper stepper(coil, blue, yellow, pink, orange); // coil pairing order 19 | int steps = (coil/4)*2038; // number of steps per revolution 20 | int potPin = A1; // potentiometer pin 21 | int LEDpin = 6; // LED on PWM pin 22 | unsigned long revTime = 0; 23 | float rpmMin = 10.0; // minimum and maximum speed in rpm 24 | float rpmMax = 21.0; 25 | float speedMin = rpmMin*steps/60.0; // and in steps/s 26 | float speedMax = rpmMax*steps/60.0; 27 | float rpm; 28 | int reading, speed, bright; 29 | 30 | void setup() 31 | { 32 | Serial.begin(9600); // define Serial output baud rate 33 | pinMode(LEDpin, OUTPUT); // LED pin as output 34 | stepper.setMaxSpeed(1500); // set maximum speed (step/s) 35 | } 36 | 37 | void loop() 38 | { 39 | reading = analogRead(potPin); // potentiometer voltage 40 | // map voltage to speed (step/s) 41 | speed = map(reading, 0, 1023, speedMin, speedMax); 42 | bright = map(reading, 0, 1023, 0, 255); // map voltage to LED brightness 43 | analogWrite(LEDpin, bright); // set LED brightness with PWM 44 | stepper.move(256); // move the internal motor 256 steps 45 | stepper.setSpeed(speed); // set the internal motor speed 46 | stepper.runSpeed(); // run the stepper motor 47 | if((stepper.currentPosition() % steps)==0) // on each complete revolution 48 | { 49 | revTime = millis()-revTime; // time (ms) for one revolution 50 | rpm = stepper.speed()*60.0/steps; // stepper motor rpm 51 | Serial.print(revTime); // print revolution time to Serial Monitor 52 | Serial.print(" ms\t\t"); // print "ms " and two tabs 53 | Serial.print(rpm, 2); // print rpm with 2DP 54 | Serial.print(" rpm\t"); // print " rpm" and a tab 55 | Serial.print(stepper.speed(),0); // print stepper motor speed with 0DP 56 | Serial.println(" steps/s"); // print " steps/s" and a new line 57 | delay(2); // delay 2ms to prevent duplicates 58 | revTime=millis(); // update revolution start time 59 | } 60 | } 61 | 62 | -------------------------------------------------------------------------------- /Chapter 9/Listing9-1/Listing9-1.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Sketch name: rotary encode and LED 3 | * Description: use rotary encoder to control LED brightness 4 | * Created : October 2018 5 | * Author: Neil Cameron 6 | * Book: Applied Arduino: Comprehensive Projects for Everyday Electronics 7 | * Chapter : Chapter 9 - Rotary encoder 8 | ******************************************************************************/ 9 | 10 | int CLKpin= A0; // pin A or clock pin 11 | int DTpin= A1; // pin B or data pin 12 | int SWpin= A2 ; // switch pin 13 | int LEDpin = 6; // LED on PWM pin 14 | int bright = 120; // initial LED value 15 | int fade = 10; // amount to change LED 16 | int rotate = 0; // number of rotary turns 17 | int oldA = HIGH; // status of pin A 18 | int change, result, newA, newB; 19 | 20 | void setup() 21 | { 22 | Serial.begin(9600); // define Serial output baud rate 23 | pinMode(LEDpin, OUTPUT); // LED pin as output 24 | pinMode(SWpin, INPUT_PULLUP); // switch pin uses internal pull-up resistor 25 | } 26 | 27 | void loop() 28 | { 29 | if(digitalRead(SWpin) == LOW) bright = 0; // switch, active LOW, turns off the LED 30 | change = encoder(); // direction of rotation 31 | rotate = rotate + abs(change); // number of turns of rotary encoder 32 | bright = bright + change*fade; // change LED brightness 33 | bright = constrain(bright, 0, 255); // constrain LED brightness 34 | if(change != 0) 35 | { 36 | Serial.print(rotate);Serial.print("\t"); // display number of rotary turns 37 | Serial.println(bright); // and LED brightness 38 | } 39 | analogWrite(LEDpin, bright); // update LED brightness 40 | } 41 | 42 | int encoder() // function to determine direction 43 | { 44 | result = 0; 45 | newA = digitalRead(CLKpin); // state of (CLK) pin A 46 | newB = digitalRead(DTpin); // state of (DT) pin B 47 | // falling edge on (CLK) pin A 48 | if (oldA == HIGH && newA == LOW) result = 2*newB - 1; 49 | oldA = newA; // update state of (CLK) pin A 50 | return result; 51 | } 52 | 53 | -------------------------------------------------------------------------------- /Contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Freeware License, some rights reserved 2 | 3 | Copyright (c) 2018 Neil Cameron 4 | 5 | Permission is hereby granted, free of charge, to anyone obtaining a copy 6 | of this software and associated documentation files (the "Software"), 7 | to work with the Software within the limits of freeware distribution and fair use. 8 | This includes the rights to use, copy, and modify the Software for personal use. 9 | Users are also allowed and encouraged to submit corrections and modifications 10 | to the Software for the benefit of other users. 11 | 12 | It is not allowed to reuse, modify, or redistribute the Software for 13 | commercial use in any way, or for a user’s educational materials such as books 14 | or blog articles without prior permission from the copyright holder. 15 | 16 | The above copyright notice and this permission notice need to be included 17 | in all copies or substantial portions of the software. 18 | 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | SOFTWARE. 26 | 27 | 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Arduino Applied: Comprehensive Projects for Everyday Electronics*](https://www.apress.com/9781484239599) by Neil Cameron (Apress, 2018). 4 | 5 | [comment]: #cover 6 | ![Cover image](9781484239599.jpg) 7 | 8 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 9 | 10 | ## Releases 11 | 12 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 13 | 14 | ## Contributions 15 | 16 | See the file Contributing.md for more information on how you can contribute to this repository. -------------------------------------------------------------------------------- /Updates/Arduino Applied corrections.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/arduino-applied/b81f3caabce3869b21680bc544296fab5b7836f4/Updates/Arduino Applied corrections.pdf -------------------------------------------------------------------------------- /Updates/Arduino Applied updates.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/arduino-applied/b81f3caabce3869b21680bc544296fab5b7836f4/Updates/Arduino Applied updates.pdf --------------------------------------------------------------------------------