--- /dev/null
+Andrea's Sketchbook
+=====================
+
+Esempi per i corsi su Arduino.
+Le ultime versioni sono disponibili su: git.andreamanni.com
+
+Per aggiornare il proprio archivio:
+cd sketchbook_andrea/ ; git fetch
+
+
+Note
+------
+
+- head_tails_ino
+Is the code example of C book for control structures (IF)
+
+- loop_match_2_ino
+Is the code example of C book for iterative structures (while - for loop)
+
+
+>-- Copyright note: all these is released into the Public Domain --<
--- /dev/null
+Ottima lezione in italiano:
+- http://www.maffucci.it/2014/09/27/arduino-lezione-09-uso-di-led-rgb-parte-1/
--- /dev/null
+// This is meant for a Common Anodote RGB LED
+// See all those (255 - val).
+
+#define GREEN 9
+#define BLUE 10
+#define RED 11
+#define delayTime 20
+
+void setup() {
+
+ pinMode(GREEN, OUTPUT);
+ pinMode(BLUE, OUTPUT);
+ pinMode(RED, OUTPUT);
+ digitalWrite(GREEN, HIGH);
+ digitalWrite(BLUE, HIGH);
+ digitalWrite(RED, HIGH);
+}
+
+int redVal;
+int blueVal;
+int greenVal;
+
+void loop() {
+
+ int redVal = 255;
+ int blueVal = 0;
+ int greenVal = 0;
+ for( int i = 0 ; i < 255 ; i += 1 ){
+ greenVal += 1;
+ redVal -= 1;
+ analogWrite( GREEN, 255 - greenVal );
+ analogWrite( RED, 255 - redVal );
+
+ delay( delayTime );
+ }
+
+ redVal = 0;
+ blueVal = 0;
+ greenVal = 255;
+ for( int i = 0 ; i < 255 ; i += 1 ){
+ blueVal += 1;
+ greenVal -= 1;
+ analogWrite( BLUE, 255 - blueVal );
+ analogWrite( GREEN, 255 - greenVal );
+
+ delay( delayTime );
+ }
+
+ redVal = 0;
+ blueVal = 255;
+ greenVal = 0;
+ for( int i = 0 ; i < 255 ; i += 1 ){
+ redVal += 1;
+ blueVal -= 1;
+ analogWrite( RED, 255 - redVal );
+ analogWrite( BLUE, 255 - blueVal );
+
+ delay( delayTime );
+ }
+}
--- /dev/null
+ /*
+ Adafruit Arduino - Lesson 3. RGB LED
+ */
+
+ int redPin = 11;
+ int greenPin = 10;
+ int bluePin = 9;
+
+ //uncomment this line if using a Common Anode LED
+ //#define COMMON_ANODE
+
+ void setup()
+ {
+ pinMode(redPin, OUTPUT);
+ pinMode(greenPin, OUTPUT);
+ pinMode(bluePin, OUTPUT);
+ }
+
+ void loop()
+ {
+ setColor(255, 0, 0); // red
+ delay(1000);
+ setColor(0, 255, 0); // green
+ delay(1000);
+ setColor(0, 0, 255); // blue
+ delay(1000);
+ setColor(255, 255, 0); // yellow
+ delay(1000);
+ setColor(80, 0, 80); // purple
+ delay(1000);
+ setColor(0, 255, 255); // aqua
+ delay(1000);
+ }
+
+ void setColor(int red, int green, int blue)
+ {
+ #ifdef COMMON_ANODE
+ red = 255 - red;
+ green = 255 - green;
+ blue = 255 - blue;
+ #endif
+ analogWrite(redPin, red);
+ analogWrite(greenPin, green);
+ analogWrite(bluePin, blue);
+ }
--- /dev/null
+// Chapter 7: Arduino Alarm Clock
+// An alarm clock that uses the Adafruit Industries DS1307 RTC Breakout board
+// and a 16 x 2 Parallel LCD Display
+#include <Wire.h> // I2C Wire Library for communicating with the DS1307 RTC
+#include "RTClib.h" // Date and time functions for the DS1307 RTC connected
+#include <LiquidCrystal.h> // Display functions for the LCD Display
+RTC_DS1307 rtc; // Create a realtime clock called rtc
+LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // Create an LCD called lcd
+
+
+void setup () {
+ Wire.begin(); // Enables the communication for the LCD
+ rtc.begin(); // Enables the RTC
+ lcd.begin(16, 2); // Enables the LCD
+
+ lcd.print(" It's Alive!"); // Print a message, centered, to the LCD to confirm it's working
+ delay(500); // Wait a moment so we can read it
+ lcd.clear(); // Clear the LCD
+}
+void loop(){
+
+}
+
--- /dev/null
+// Chapter 7: Arduino Alarm Clock
+// An alarm clock that uses the Adafruit Industries DS1307 RTC Breakout board
+// and a 16 x 2 Parallel LCD Display
+#include <Wire.h> // I2C Wire Library for communicating with the DS1307 RTC
+#include "RTClib.h" // Date and time functions for the DS1307 RTC connected
+#include <LiquidCrystal.h> // Display functions for the LCD Display
+RTC_DS1307 rtc; // Create a realtime clock called rtc
+LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // Create an LCD called lcd
+
+DateTime now; // Time object
+
+void setup () {
+ Wire.begin(); // Enables the communication for the LCD
+ rtc.begin(); // Enables the RTC
+ lcd.begin(16, 2); // Enables the LCD
+
+ lcd.print(" It's Alive!"); // Print a message, centered, to the LCD to confirm it's working
+ delay(500); // Wait a moment so we can read it
+ lcd.clear(); // Clear the LCD
+}
+void loop(){
+ now = rtc.now(); // Get the current time
+ // Refresh the display
+ updateDisplay();
+}
+
+void updateDisplay(){
+ int h = now.hour(); // Get the hours right now and store them in an integer called h
+ int m = now.minute(); // Get the minutes right now and store them in an integer called m
+ int s = now.second(); // Get the seconds right now and store them in an integer called s
+ lcd.setCursor(0, 0); // Set the cursor at the column zero, upper row...
+ lcd.print(" The time is: "); // ...with spaces to clear characters from setting alarm.
+ lcd.setCursor(4, 1); // Move the cursor to column four, lower row
+ if (h<10){ // Add a zero, if necessary, as above
+ lcd.print(0);
+ }
+ lcd.print(h); // Display the current hour
+ lcd.setCursor(6, 1); // Move to the next column
+ lcd.print(":"); // And print the colon
+ lcd.setCursor(7, 1); // Move to the next column
+ if (m<10){ // Add a zero, if necessary, as above
+ lcd.print(0);
+ }
+ lcd.print(m); // Display the current minute
+ lcd.setCursor(9, 1); // Move to the next column
+ lcd.print(":"); // And print the colon
+ lcd.setCursor(10, 1); // Move to the next column
+ if (s<10){ // Add a zero, if necessary, as above
+ lcd.print(0);
+ }
+ lcd.print(s); // Display the current second
+}
+
--- /dev/null
+This examples are taken from the book:
+= Arduino Projects For Dummies
+ ISBN: 978-1-118-55147-9
+
+Codes and schematics are available from:
+http://www.dummies.com/store/product/Arduino-Projects-For-Dummies.productCd-1118551478,navId-322496,descCd-DOWNLOAD.html
+/ Downloads.
--- /dev/null
+/* Arduino Projects for Dummies
+ * by Brock Craft
+ *
+ * Chapter 4: The All-Seeing Eye
+ * Sequentially lights up a series of LEDs
+ *
+ * v0.3 02.02.2015
+ * Changed delayTime variable so that is is consistent with the
+ * text of the book. (Used to be timeDelay.)
+ * v0.2 03.07.2013
+ * Fixed error: timeChanged = millis(); not within if loop brackets
+ */
+
+// A variable to set a delay time between each LED
+int delayTime = 50;
+
+// A variable to store which LED we are currently working on
+int currentLED = 0;
+
+// A variable to store the direction of travel of LEDs
+int dir = 1;
+
+// A variable to store the last time we changed something
+unsigned long timeChanged = 0;
+
+// Create an array to hold the value for each LED pin
+byte ledPin[] = {
+ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
+
+void setup() {
+ // Set all pins for OUTPUT with a counter
+ for (int x=0; x<10; x++) {
+ pinMode(ledPin[x], OUTPUT);
+ }
+
+ // Set all pins for OUTPUT iterating a pointer
+ // byte *ptr = ledPin ;
+ // while (*ptr) {
+ // pinMode(*ptr++, OUTPUT);
+ // }
+
+ // Set up the
+ timeChanged = millis();
+}
+
+void loop() {
+ // Check whether it has been long enough
+ if ((millis() - timeChanged) > delayTime) {
+ // Turn off all of the LEDs, see next comment
+ for (int x=0; x<10; x++) {
+ digitalWrite(ledPin[x], LOW);
+ }
+ // Turning off just one LED instead on 10 would be more efficient
+ // digitalWrite(ledPin[currentLED - dir], LOW);
+
+ // Turn on the current LED
+ digitalWrite(ledPin[currentLED], HIGH);
+
+ // Increment by the direction value
+ currentLED += dir;
+
+ // If we are at the end of a row, change direction
+ if (currentLED == 9) {
+ dir = -1;
+ }
+ if (currentLED == 0) {
+ dir = 1;
+ }
+
+ // Let's change the speed wit a Pot on pin A5
+ // delayTime = map(analogRead(5),0,1024,20,5 00);
+ // delay(2);
+
+ // Store the current time as the time we last changed LEDs
+ timeChanged = millis();
+ }
+}
+
+
+
+
+
+
+
--- /dev/null
+Sketch 8: Sketch con 4 modi per il LED:
+
+1. OFF
+2. ON
+3. Blink
+4. Fast Blink
+
+
+Si potrebbe fare con una struttura switch per attivare il modo,
+valutare se usare un array per iterare tra i modi.
--- /dev/null
+/*
+ * Alternating switch
+ */
+
+int switchPin = 2; // switch is connected to pin 2
+int val; // variable for reading the pin status
+int buttonState; // variable to hold the last button state
+int lightMode = 0; // State of the light
+int LED = 12;
+
+void setup() {
+ pinMode(switchPin, INPUT_PULLUP); // Set the switch pin as input
+ pinMode(LED, OUTPUT);
+
+ buttonState = digitalRead(switchPin); // read the initial state
+
+}
+
+
+void loop(){
+ val = digitalRead(switchPin); // read input value and store it in val
+ delay(100); // Debounce
+ if ((val != buttonState) && (val == HIGH)) { // check if the button is pressed
+ lightMode = 1 -lightMode ;
+ }
+ digitalWrite(LED,lightMode);
+ buttonState = val; // save the new state in our variable
+}
+
+
+
--- /dev/null
+/*
+ * Turn on / off LED with a switch.
+ When the lightmode is on the LED Blinks
+ */
+
+int switchPin = 2; // switch is connected to pin 2
+int val; // variable for reading the pin status
+int valBounce ; // variable for debouncing
+int buttonState; // variable to hold the last button state
+int lightMode = 0; // State of the light
+int LED = 12;
+
+void setup() {
+ pinMode(switchPin, INPUT_PULLUP); // Set the switch pin as input
+ pinMode(LED, OUTPUT);
+
+ buttonState = digitalRead(switchPin); // read the initial state
+
+}
+
+
+void loop(){
+ val = digitalRead(switchPin); // read input value and store it in val
+ delay(10); // Debounce
+ valBounce = digitalRead(switchPin); // read input value and store it in val
+
+ if ((val == valBounce) && (val != buttonState) && (val == HIGH)) { // check if the button is pressed
+ lightMode = 1 -lightMode ; // Now with DeBounce
+ }
+ if (lightMode) { // Check if light mode is TRUE == 1 or FALSE == 0
+ delay(50); // Keep the LED LOW for 50ms
+ digitalWrite(LED,HIGH); // Blink the LED
+ delay(50); // Keep the LED HIGH for 50ms
+ // digitalWrite(LED,LOW); // We don't need to turn it LOW
+ // It will go off anyway later
+ }
+
+ digitalWrite(LED,LOW); // Almayes turn off the LED
+ // As lightMode is FALSE == 0 turn the LED off
+ // Turn it off
+ buttonState = val; // save the new state in our variable
+}
+
+
+
+
+
+
+
+
--- /dev/null
+/*
+ * Alternating switch
+ */
+
+int switchPin = 2; // switch is connected to pin 2
+int val; // variable for reading the pin status
+int valBounce ; // variable for debouncing
+int buttonState; // variable to hold the last button state
+int lightMode = 0; // State of the light
+int LED = 12;
+
+void setup() {
+ pinMode(switchPin, INPUT_PULLUP); // Set the switch pin as input
+ pinMode(LED, OUTPUT);
+
+ buttonState = digitalRead(switchPin); // read the initial state
+
+}
+
+
+void loop(){
+ val = digitalRead(switchPin); // read input value and store it in val
+ delay(10); // Debounce
+ valBounce = digitalRead(switchPin); // read input value and store it in val
+
+ if ((val == valBounce) && (val != buttonState) && (val == HIGH)) { // check if the button is pressed
+ lightMode = 1 -lightMode ; // Now with DeBounce
+ }
+ digitalWrite(LED,lightMode);
+ buttonState = val; // save the new state in our variable
+}
+
+
+
+
--- /dev/null
+/*
+ * Alternating switch
+ */
+
+int switchPin = 2; // switch is connected to pin 2
+int val; // variable for reading the pin status
+int buttonState; // variable to hold the last button state
+int buttonPresses = 10; // Counter for the button
+
+void setup() {
+ pinMode(switchPin, INPUT_PULLUP); // Set the switch pin as input
+
+ Serial.begin(9600); // Set up serial communication at 9600bps
+ buttonState = digitalRead(switchPin); // read the initial state
+ Serial.println("Don not press the button! :P ");
+}
+
+
+void loop(){
+ val = digitalRead(switchPin); // read input value and store it in val
+ delay(100); // Debounce
+ if ((val != buttonState) && (val == HIGH)) { // check if the button is pressed
+ buttonPresses-- ;
+ Serial.print("Press it an other ");
+ Serial.print(buttonPresses);
+ Serial.println(" times.");
+ }
+ if (buttonPresses == 0) {
+ Serial.println("----- > ExplOdE! <------");
+ // Serial.flush(); // Print out the whole serial buffer
+ // exit(0); // Exit the sketch
+ }
+ buttonState = val; // save the new state in our variable
+}
+
+
--- /dev/null
+/*
+ * Alternating switch
+ */
+
+int switchPin = 2; // switch is connected to pin 2
+int val; // variable for reading the pin status
+int buttonState; // variable to hold the last button state
+int buttonPresses = 0; // Counter for the button
+
+void setup() {
+ pinMode(switchPin, INPUT_PULLUP); // Set the switch pin as input
+
+ Serial.begin(9600); // Set up serial communication at 9600bps
+ buttonState = digitalRead(switchPin); // read the initial state
+}
+
+
+void loop(){
+ val = digitalRead(switchPin); // read input value and store it in val
+ delay(100); // Debounce
+ if ((val != buttonState) && (val == HIGH)) { // check if the button is pressed
+ buttonPresses++ ;
+ Serial.print("Button has been pressed ");
+ Serial.print(buttonPresses);
+ Serial.println(" times.");
+ }
+ buttonState = val; // save the new state in our variable
+}
+
+
--- /dev/null
+/*
+ * Alternating switch
+ */
+
+int switchPin = 2; // switch is connected to pin 2
+int val; // variable for reading the pin status
+int buttonState; // variable to hold the last button state
+
+void setup() {
+ pinMode(switchPin, INPUT); // Set the switch pin as input
+
+ Serial.begin(9600); // Set up serial communication at 9600bps
+ buttonState = digitalRead(switchPin); // read the initial state
+}
+
+
+void loop(){
+ val = digitalRead(switchPin); // read input value and store it in val
+
+ if (val != buttonState) { // the button state has changed!
+ if (val == LOW) { // check if the button is pressed
+ Serial.println("Button just pressed");
+ } else { // the button is -not- pressed...
+ Serial.println("Button just released");
+ }
+ }
+
+ buttonState = val; // save the new state in our variable
+}
--- /dev/null
+void setup() {
+ // put your setup code here, to run once:
+ Serial.begin(9600);
+
+}
+
+void loop() {
+
+ transforma(5); // Leggete i risultati con [CTR]+[SHIFT]+M
+ transforma(255);
+
+ Serial.flush() ;
+ exit(0); // Termina l'esecuzione
+}
+
+// Ignorate pure il resto del listato!
+
+/* Transforma
+
+ Scrive su seriale il valore della variabile a
+ trasformandolo in binario e esadecimale
+ */
+
+void transforma(int var) {
+ Serial.print("Valore in decimanle = ");
+ Serial.println(var); // Serial.println(a, DEC);
+
+ Serial.print("Valore in binario = ");
+ Serial.println(var,BIN);
+
+ Serial.print("Valore in esadecimanle = ");
+ Serial.println(var,HEX);
+
+ Serial.println();
+}
+
+
+
+
+
--- /dev/null
+/*
+ Adafruit Arduino - Lesson 3. RGB LED
+ */
+
+int redPin = 11;
+int greenPin = 10;
+int bluePin = 9;
+int c = 0;
+
+//uncomment this line if using a Common Anode LED
+//#define COMMON_ANODE
+
+void setup()
+{
+ pinMode(redPin, OUTPUT);
+
+}
+
+void loop()
+{
+ for ( c = 0; c < 255 ; c++) {
+ analogWrite(redPin, c) ;
+ delay(5 );
+ }
+}
+
+
--- /dev/null
+/*
+ Fade
+
+ This example shows how to fade an LED on pin 9
+ using the analogWrite() function.
+
+ This example code is in the public domain.
+ */
+
+byte led = 9 ; // the pin that the LED is attached to
+
+byte brightness = 0; // how bright the LED is
+
+// the setup routine runs once when you press reset:
+void setup() {
+ // declare pin 9 to be an output:
+ pinMode(led, OUTPUT);
+}
+
+// the loop routine runs over and over again forever:
+void loop() {
+ // set the brightness of pin 9:
+ analogWrite(led, brightness++);
+ delay(10);
+}
+
+
--- /dev/null
+/*
+ * Switch and LED test program
+ */
+
+int ledPin = 12; // LED is connected to pin 12
+int switchPin = 2; // switch is connected to pin 2
+int val; // variable for reading the pin status
+
+
+void setup() {
+ pinMode(ledPin, OUTPUT); // Set the LED pin as output
+ pinMode(switchPin, INPUT); // Set the switch pin as input
+}
+
+
+void loop(){
+ val = digitalRead(switchPin); // read input value and store it in val
+ if (val == LOW) { // check if the button is pressed
+ digitalWrite(ledPin, HIGH); // turn LED on
+ }
+ if (val == HIGH) { // check if the button is not pressed
+ digitalWrite(ledPin, LOW); // turn LED off
+ }
+}
--- /dev/null
+/*
+ * Switch test program
+ */
+
+int switchPin = 2; // Switch connected to digital pin 2
+
+void setup() // run once, when the sketch starts
+{
+ Serial.begin(9600); // set up Serial library at 9600 bps
+ pinMode(switchPin, INPUT); // sets the digital pin as input to read switch
+}
+
+
+void loop() // run over and over again
+{
+ Serial.print("Read switch input: ");
+ Serial.println(digitalRead(switchPin)); // Read the pin and display the value
+ delay(200);
+}
--- /dev/null
+/*
+ Blink con funzioni.
+
+ Le funzioni sono una sequenza di istruzione raggruppate appunto in un a funzione.
+ Le funzioni possono accettare argomenti e avere questi pre-impostati a valori di default se omessi.
+ Le funzioni possono limitarsi a svolgere istruzionioppure elaborare valori restituendo un risultato.
+
+ */
+
+// Pin 13 has an LED connected on most Arduino boards.
+// give it a name:
+int led = 13;
+void lunga() {
+ digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
+ delay(1000); // wait for a second
+ digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
+ delay(1000); // wait for a second
+}
+
+void breve() {
+ digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
+ delay(200); // wait for a second
+ digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
+ delay(1000); // wait for a second
+
+}
+
+void varia(int a = 1000) { // Varia has a default value, the user can override it with an argument
+ digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
+ delay(a); // wait for a second
+ digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
+ delay(1000); // wait for a second
+
+}
+
+// the setup routine runs once when you press reset:
+void setup() {
+ // initialize the digital pin as an output.
+ pinMode(led, OUTPUT);
+}
+
+// the loop routine runs over and over again forever:
+void loop() {
+ lunga() ;
+ lunga() ;
+ breve();
+ breve();
+ varia(3000);
+
+
+}
+
--- /dev/null
+/*
+ Head tails
+ Generates a random number in order to simulate a coin toss.
+
+
+ Phisical LEDS and serial debug.
+
+ This example code is in the public domain.
+ */
+
+// Pin 13 has an LED connected on most Arduino boards.
+// give it a name:
+const int head = 13 ; // LED for HEAD
+const int tail = 12 ; // LEAD for Tails
+const int PAUSE = 1000 ;
+const int REST = 50 ;
+long randomNumber = 0L; // Use the "L" to tell compiler it's a long data type, not an int.
+int hCount = 0;
+int tCount = 0;
+int runs = 0 ;
+
+// the setup routine runs once when you press reset:
+void setup() {
+ // initialize the digital pin as an output.
+ pinMode(head, OUTPUT);
+ pinMode(tail, OUTPUT);
+ randomSeed(analogRead(0)); // Random initializer
+ Serial.begin(9600);
+ Serial.println("Initializing random sequence, please wait for results.");
+}
+
+// the loop routine runs over and over again forever:
+void loop() {
+ randomNumber = random();
+ digitalWrite(head, LOW);
+ digitalWrite(tail, LOW);
+ delay(REST); // wait a bit
+ if (randomNumber % 2 == 1) {
+ digitalWrite(head, HIGH);// turn the LED on ON
+ hCount++ ;
+ }
+ else {
+ digitalWrite(tail, HIGH);// turn the LED ON
+ tCount++ ;
+ }
+
+ delay(PAUSE); // Long pause
+ runs++;
+
+ if (runs % 10 == 0) { // Each 10 runs print a summary to serial
+ Serial.print("Results after more 10 runs, for a total of: ");
+ Serial.println(runs);
+ Serial.print("Tails: \t") ;
+ Serial.println(tCount);
+ Serial.print("Heads: \t");
+ Serial.println(hCount);
+ }
+}
+
+
+
--- /dev/null
+/**
+ * Program: find out is the user typed in a leap year. The code assumes
+ * the user is not an idiot and only types in numbers that are a valid
+ * year.
+ * Author: Dr. Purdum, Aug. 7, 2012
+ **/
+void setup()
+{
+ Serial.begin(9600);
+}
+void loop()
+{
+ if (Serial.available() > 0) {
+ int bufferCount;
+ int year;
+ char myData[20];
+ bufferCount = ReadLine(myData);
+ year = atoi(myData);
+ Serial.print("Year: ");
+ Serial.print(year);
+ if (IsLeapYear(year)) {
+ Serial.print(" is ");
+ }
+ else {
+ Serial.print(" is not ");
+ }
+ Serial.println("a leap year");
+ }
+}
+// Convert to int
+/*****
+ * Purpose: Determine if a given year is a leap year
+ * Parameters:
+ * int yr
+ * The year to test
+ * Return value:
+ * int
+ * 1 if the year is a leap year, 0 otherwise
+ *****/
+int IsLeapYear(int yr)
+{
+ if (yr % 4 == 0 && yr % 100 != 0 || yr % 400 == 0) {
+ return 1; // It is a leap year
+ }
+ else {
+ return 0;
+ // not a leap year
+ }
+}
+/*****
+ * Purpose: Read data from serial port until a newline character is read ('\n')
+ * Parameters:
+ * char str[]
+ * character array that will be treated as a nul-terminated string
+ * Return value:
+ * int
+ * the number of characters read for the string
+ * CAUTION: This method will sit here forever if no input is read from the serial
+ * port and no newline character is entered.
+ ****/
+int ReadLine(char str[])
+{
+ char c;
+ int index = 0;
+ while (true) {
+ if (Serial.available() > 0) {
+ c = Serial.read();
+ if (c != '\n') {
+ str[index++] = c;
+ }
+ else {
+ str[index] = '\0'; // null termination character
+ break;
+ }
+ }
+ }
+ return index;
+}
+
+
--- /dev/null
+/* Exercise 2, with a WHILE loop
+ Test a random number agains a value
+ Light a led in case
+ Light the other LED if a run of 255 test has gone
+ Log the results (if success) trough serialport
+ */
+
+// Data structure
+
+const byte GREEN = 13 ; // LED for found value
+const byte RED = 12 ; // LEAD for restart
+
+const int TARGET = 200 ;
+long randomNumber = 0L;
+
+// Staff
+const int WAIT = 1000 ;
+const int REST = 10 ;
+byte count = 0 ;
+const byte MAXRUN = 10 ;
+byte totalRun = 0 ;
+
+void setup() {
+ pinMode(RED,OUTPUT);
+ pinMode(GREEN,OUTPUT);
+ // Serial stuff
+ Serial.begin(9600);
+ Serial.println("Initializing random sequence, please wait for results.");
+
+ // Random stuff
+ randomSeed(analogRead(0)); // Random initializer
+
+}
+
+void loop() { // put your main code here, to run repeatedly:
+ digitalWrite(GREEN, LOW);
+ digitalWrite(RED, LOW);
+ // Serial.println(count);
+
+ for (count == 0; count < 255; count++ , delay(REST)) {
+ randomNumber = random(0,255); //Randoom value generated
+ if (randomNumber == TARGET) { // When we catch the value
+ Serial.print("--> Match found! Counter was at: "); // serial message
+ Serial.println(count);
+ digitalWrite(GREEN, HIGH);
+ delay(WAIT * 5);
+ digitalWrite(GREEN, LOW);
+ count++ ;
+ }
+ }
+
+ Serial.println("Counter resetted."); // serial staff
+ digitalWrite(RED, HIGH);
+ delay(WAIT);
+ count++ ;
+ totalRun++ ;
+ if (totalRun == MAXRUN) {
+ Serial.println("10 runs done, exit program.");
+ digitalWrite(RED, HIGH);
+ delay(WAIT);
+ exit(0);
+ }
+}
+
--- /dev/null
+/* Exercise 2, with a WHILE loop
+ Test a random number agains a value
+ Light a led in case
+ Light the other LED if a run of 255 test has gone
+ Log the results (if success) trough serialport
+ */
+
+// Data structure
+
+const byte GREEN = 13 ; // LED for found value
+const byte RED = 12 ; // LEAD for restart
+
+const int TARGET = 200 ;
+long randomNumber = 0L;
+
+// Staff
+const int WAIT = 1000 ;
+const int REST = 10 ;
+byte count = 0 ;
+const byte MAXRUN = 10 ;
+byte totalRun = 0 ;
+
+void setup() {
+ pinMode(RED,OUTPUT);
+ pinMode(GREEN,OUTPUT);
+ // Serial stuff
+ Serial.begin(9600);
+ Serial.println("Initializing random sequence, please wait for results.");
+
+ // Random stuff
+ randomSeed(analogRead(0)); // Random initializer
+
+}
+
+void loop() { // put your main code here, to run repeatedly:
+ digitalWrite(GREEN, LOW);
+ digitalWrite(RED, LOW);
+ // Serial.println(count);
+
+ while (count < 255) {
+ randomNumber = random(0,255); //Randoom value generated
+ if (randomNumber == TARGET) { // When we catch the value
+ Serial.print("--> Match found! Counter was at: "); // serial message
+ Serial.println(count);
+ digitalWrite(GREEN, HIGH);
+ delay(WAIT);
+ count++ ;
+ }
+ //Serial.println(count);
+ count++ ;
+ delay(REST);
+ }
+
+
+ Serial.println("Counter resetted."); // serial staff
+ digitalWrite(RED, HIGH);
+ delay(WAIT);
+ count++ ;
+ totalRun++ ;
+ if (totalRun == MAXRUN) {
+ Serial.println("10 runs done, exit program.");
+ digitalWrite(RED, HIGH);
+ delay(WAIT);
+ exit(0);
+ }
+}
+
--- /dev/null
+Use examples provided with arduino:
+
+EDIT -> Example -> Control -> ...
+
+- SwitchCase: check the range of a (mapped) analog input with a switch loop.
+- SwitchCase2: SerialInput to light up a bunch of LEDS.
--- /dev/null
+
+int *ptrNumber ;
+void setup() {
+ // put your setup code here, to run once:
+ Serial.begin(9600);
+
+}
+
+void loop() {
+ int number = 5;
+
+
+ Serial.print("number is ");
+ Serial.println(number);
+ Serial.print("The lvalue for number is: ");
+ Serial.println((long) &number, DEC);
+
+ Serial.print("---- Pointer was ");
+ Serial.println(*ptrNumber);
+ Serial.print("The lvalue for ptrNumber is: ");
+ Serial.println((long) &ptrNumber, DEC);
+ Serial.print(" and the rvalue is ");
+ Serial.println((long) ptrNumber, DEC);
+
+ ptrNumber = &number ;
+ Serial.println("Assigned!");
+
+ Serial.print("===== Pointer was ");
+ Serial.println(*ptrNumber);
+ Serial.print("The lvalue for ptrNumber is: ");
+ Serial.println((long) &ptrNumber, DEC);
+ Serial.print(" and the rvalue is ");
+ Serial.println((long) ptrNumber, DEC);
+
+ *ptrNumber = 6 ;
+ Serial.print("**** Pointer value is: ");
+ Serial.println(*ptrNumber);
+ Serial.println(number);
+
+ Serial.flush();
+ exit(0);
+
+}
+
+
--- /dev/null
+/*
+Purpose: Illustrate pointer arithmetic
+ Dr. Purdum, August 20, 2012
+ */
+#include <string.h>
+void setup() {
+ Serial.begin(9600);
+}
+void loop() {
+ char buffer[50];
+ char *ptr;
+ int i;
+ int length;
+
+ strcpy(buffer, "When in the course of human events");
+ ptr = buffer;
+ length = strlen(buffer);
+ Serial.print("The lvalue for ptr is: ");
+ Serial.print((unsigned int)&ptr);
+ Serial.print(" and the rvalue is ");
+ Serial.println((unsigned int)ptr);
+ while (*ptr) {
+ Serial.print(*ptr++); // This actually incrementa ptr* + 34
+ }
+ Serial.println("");
+
+ Serial.println("Lenght of the string is: ");
+ Serial.println(length);
+ Serial.println("");
+
+
+ // ptr = ptr - length ; // Whis would roll back ptr
+ for (i = 0; i < length; i++) {
+ Serial.print(*(ptr + i));
+ // Serial.print(*(ptr + i- lenght)); // ptr is one lenght up ahead
+ }
+ // ptr = buffer ; // Right thing to do: reset the pointer before use
+ // for (i = 0; i < length; i++) {
+ // Serial.print(*(ptr + i))
+
+
+ Serial.flush();
+ // Make sure all the data is sent...
+ exit(0);
+}
+
+
+
+
--- /dev/null
+int *ptr; // no rvalue
+
+void setup() {
+ // put your setup code here, to run once:
+ Serial.begin(9600);
+
+}
+
+void loop() {
+ int num =5;
+ ptr = &num ;
+
+ transforma(num); // Leggete i risultati con [CTR]+[SHIFT]+M
+ Serial.println(num);
+
+ Serial.flush() ;
+ exit(0); // Termina l'esecuzione
+}
+
+// Ignorate pure il resto del listato!
+
+/* Transforma
+
+ Scrive su seriale il valore della variabile a
+ trasformandolo in binario e esadecimale
+ */
+
+void transforma(int var) {
+ Serial.print("Valore della variabile = ");
+ Serial.print(var);
+ *ptr = 12 ; // Num is outside the scope of this function
+ // but a pointer can get there
+
+
+ Serial.println();
+}
+
+
+
+
+
--- /dev/null
+
+
+struct RGB {
+ byte r;
+ byte g;
+ byte b;
+}
+myLED ;
+
+void setup() {
+ Serial.begin(9600);
+ // Serial link to PC
+}
+void loop() {
+ myLED = {
+ 100,200,255 }
+ ;
+
+ // Serial.println(myLED.r) ;
+
+ illumina(&myLED);
+ rossa(&myLED);
+ Serial.println();
+ illumina(&myLED);
+
+ Serial.flush();
+ exit(0);
+}
+
+void illumina(struct RGB *tempLED) { // Function with a pointer
+ Serial.println((*tempLED).r) ; // This does not waste STACK space
+ Serial.println((*tempLED).g) ; // Note: indirect operator * has lower priority
+ Serial.println(tempLED->b) ; // than dot . operator , so the parentheses
+ // That is the dereference -> operator
+}
+
+struct RGB rossa(struct RGB *temp) { // Function with a pointer:
+ // This can change directly the original value without the need
+ // to reassign as in: myLED = rossa(myLED)
+ (*temp).r = 255 ;
+ //return *temp;
+}
+
+
+
+
+
--- /dev/null
+// Remote infrared control
+// http://www.instructables.com/id/Arduino-Infrared-Remote-tutorial/
+
+// Requires library: https://github.com/shirriff/Arduino-IRremote
+// Numbers 1->6 mapped with a switch construct
+//
+// Warning: DO NOT coonect the IR sensor to the Arduino without
+// the PCB module
+
+#include <IRremote.h>
+#include <IRremoteInt.h>
+
+int RECV_PIN = 11;
+IRrecv irrecv(RECV_PIN);
+decode_results results;
+
+void setup()
+{
+ Serial.begin(9600);
+ irrecv.enableIRIn(); // Start the receiver
+}
+
+void loop()
+{
+ if (irrecv.decode(&results))
+ {
+ switch (results.value) {
+ case 0xFF30CF:
+ Serial.println("Uno");
+ break;
+ case 0xFF18E7:
+ Serial.println("Due");
+ break;
+ case 0xFF7A85:
+ Serial.println("Tre");
+ break;
+ case 0xFF10EF:
+ Serial.println("Quattro");
+ break;
+ case 0xFF38C7:
+ Serial.println("Cinque");
+ break;
+ case 0xFF5AA5:
+ Serial.println("Sei");
+ break;
+ case 0xFFFFFFFF:
+ Serial.println("Repeat");
+ }
+ //Serial.println(results.value, HEX); // Debug: show value
+ irrecv.resume(); // Receive the next value
+
+ }
+}
+
+
+
+
+
--- /dev/null
+// Remote infrared control
+// http://www.instructables.com/id/Arduino-Infrared-Remote-tutorial/
+
+// Requires library: https://github.com/shirriff/Arduino-IRremote
+// Warning: DO NOT coonect the IR sensor to the Arduino without
+// the PCB module
+
+#include <IRremote.h>
+#include <IRremoteInt.h>
+
+int RECV_PIN = 11;
+IRrecv irrecv(RECV_PIN);
+decode_results results;
+
+void setup()
+{
+ Serial.begin(9600);
+ irrecv.enableIRIn(); // Start the receiver
+}
+
+void loop()
+{
+ if (irrecv.decode(&results))
+ {
+ Serial.println(results.value, HEX);
+ if (results.value == 0xFF30CF) {
+ Serial.println("Uno");
+ }
+ irrecv.resume(); // Receive the next value
+ }
+}
+
+
--- /dev/null
+#include <LiquidCrystal.h>
+
+// initialize the library with the numbers of the interface pins
+LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
+
+void setup() {
+ // set up the LCD's number of columns and rows:
+ lcd.begin(16, 2);
+ // Print a message to the LCD.
+ lcd.print("Funziona benone!");
+}
+
+void loop() {
+ // set the cursor to column 0, line 1
+ // (note: line 1 is the second row, since counting begins with 0):
+ lcd.setCursor(0, 1);
+ // print the number of seconds since reset:
+ lcd.print(millis()/1000);
+}
+
--- /dev/null
+/*
+ LiquidCrystal Library - Hello World
+
+ Demonstrates the use a 16x2 LCD display. The LiquidCrystal
+ library works with all LCD displays that are compatible with the
+ Hitachi HD44780 driver. There are many of them out there, and you
+ can usually tell them by the 16-pin interface.
+
+ This sketch prints "Hello World!" to the LCD
+ and shows the time.
+
+ The circuit:
+ * LCD RS pin to digital pin 12
+ * LCD Enable pin to digital pin 11
+ * LCD D4 pin to digital pin 5
+ * LCD D5 pin to digital pin 4
+ * LCD D6 pin to digital pin 3
+ * LCD D7 pin to digital pin 2
+ * LCD R/W pin to ground
+ * 10K resistor:
+ * ends to +5V and ground
+ * wiper to LCD VO pin (pin 3)
+
+ Library originally added 18 Apr 2008
+ by David A. Mellis
+ library modified 5 Jul 2009
+ by Limor Fried (http://www.ladyada.net)
+ example added 9 Jul 2009
+ by Tom Igoe
+ modified 22 Nov 2010
+ by Tom Igoe
+
+ This example code is in the public domain.
+
+ http://www.arduino.cc/en/Tutorial/LiquidCrystal
+ */
+
+// include the library code:
+#include <LiquidCrystal.h>
+
+// initialize the library with the numbers of the interface pins
+LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
+
+void setup() {
+ // set up the LCD's number of columns and rows:
+ lcd.begin(20, 4);
+ // Print a message to the LCD.
+ lcd.print("Schermo LCD a 4righe per 20 caratteri. Funziona anche bene.");
+}
+
+void loop() {
+ // set the cursor to column 0, line 1
+ // (note: line 1 is the second row, since counting begins with 0):
+ lcd.setCursor(5, 4);
+ // print the number of seconds since reset:
+ //lcd.print(millis()/1000);
+}
+
--- /dev/null
+Info
+====
+
+
+- https://hwstartup.wordpress.com/2013/03/25/how-to-connect-an-arduino-to-the-internet-for-10/
+- http://www.homautomation.org/2014/10/27/how-to-choose-the-right-library-to-add-ethernet-enc28j60-to-your-arduino/
+
+This NIC should also work with KSduino:
+- http://blog.ksduino.org/post/37480815224/welcome-to-ksduino
--- /dev/null
+/*
+ Analog read
+
+ Read a value from a Arduino sensor and publish
+ it in a web page.
+
+ Note: you can set up the NIC with DHCP or static address
+
+ */
+
+#include <EtherCard.h>
+
+// ethernet interface mac address, must be unique on the LAN
+static byte mymac[] = {
+ 0x74,0x69,0x69,0x2D,0x30,0x31 };
+//static byte myip[] = { 192,168,0,100 };
+
+byte Ethernet::buffer[500];
+BufferFiller bfill;
+
+// Analog vars:
+int analogSensor = A0;
+int sensorRead = 0;
+
+void setup () {
+ /* Static IP code
+ if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
+ Serial.println( "Failed to access Ethernet controller");
+ ether.staticSetup(myip);
+
+
+
+ */
+ // DHC code
+ Serial.begin(57600);
+ Serial.println("\n[getDHCPandDNS]");
+ if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
+ Serial.println( "Failed to access Ethernet controller");
+
+ if (!ether.dhcpSetup())
+ Serial.println("DHCP failed");
+}
+
+static word homePage() {
+ bfill = ether.tcpOffset();
+ bfill.emit_p(PSTR(
+ "HTTP/1.0 200 OK\r\n"
+ "Content-Type: text/html\r\n"
+ "Pragma: no-cache\r\n"
+ "\r\n"
+ "<meta http-equiv='refresh' content='1'/>"
+ "<title>Arduino WebServer</title>"
+ "<h1>Arduino analog Read</h1>"
+ "<p>Analog Value from Arduino: $D</p>"),
+ sensorRead );
+ return bfill.position();
+}
+
+void loop () {
+ sensorRead = analogRead(analogSensor);
+
+ word len = ether.packetReceive();
+ word pos = ether.packetLoop(len);
+
+ if (pos) // check if valid tcp data is received
+ ether.httpServerReply(homePage()); // send web page data
+}
+
+
--- /dev/null
+// This is a demo of the RBBB running as webserver with the Ether Card
+// Simple Hello World
+
+#include <EtherCard.h>
+
+// ethernet interface mac address, must be unique on the LAN
+static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
+static byte myip[] = { 192,168,0,100 };
+
+byte Ethernet::buffer[500];
+BufferFiller bfill;
+
+void setup () {
+ if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
+ Serial.println( "Failed to access Ethernet controller");
+ ether.staticSetup(myip);
+}
+
+static word homePage() {
+ bfill = ether.tcpOffset();
+ bfill.emit_p(PSTR(
+ "HTTP/1.0 200 OK\r\n"
+ "Content-Type: text/html\r\n"
+ "Pragma: no-cache\r\n"
+ "\r\n"
+ "<meta http-equiv='refresh' content='1'/>"
+ "<title>RBBB server</title>"
+ "<h1>Hello World 2</h1>"));
+ return bfill.position();
+}
+
+void loop () {
+ word len = ether.packetReceive();
+ word pos = ether.packetLoop(len);
+
+ if (pos) // check if valid tcp data is received
+ ether.httpServerReply(homePage()); // send web page data
+}
--- /dev/null
+//#include <net.h>
+//#include <EtherCard.h>
+//#include <enc28j60.h>
+
+// This is a demo of the RBBB running as webserver with the Ether Card
+// 2010-05-28 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php
+ // https://hwstartup.wordpress.com/2013/03/25/how-to-connect-an-arduino-to-the-internet-for-10/
+
+#include <EtherCard.h>
+
+// ethernet interface mac address, must be unique on the LAN
+static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
+static byte myip[] = { 192,168,0,100 };
+
+byte Ethernet::buffer[500];
+BufferFiller bfill;
+
+void setup () {
+ if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
+ Serial.println( "Failed to access Ethernet controller");
+ ether.staticSetup(myip);
+}
+
+static word homePage() {
+ long t = millis() / 1000;
+ word h = t / 3600;
+ byte m = (t / 60) % 60;
+ byte s = t % 60;
+ bfill = ether.tcpOffset();
+ bfill.emit_p(PSTR(
+ "HTTP/1.0 200 OK\r\n"
+ "Content-Type: text/html\r\n"
+ "Pragma: no-cache\r\n"
+ "\r\n"
+ "<meta http-equiv='refresh' content='1'/>"
+ "<title>RBBB server</title>"
+ "<h1>$D$D:$D$D:$D$D</h1>"),
+ h/10, h%10, m/10, m%10, s/10, s%10);
+ return bfill.position();
+}
+
+void loop () {
+ word len = ether.packetReceive();
+ word pos = ether.packetLoop(len);
+
+ if (pos) // check if valid tcp data is received
+ ether.httpServerReply(homePage()); // send web page data
+}
--- /dev/null
+// 6 axis gyro demo
+// Beware: this does not work on old Uno, requires a r3.
+
+// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
+// 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
+// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
+//
+// Changelog:
+// 2013-05-08 - added seamless Fastwire support
+// - added note about gyro calibration
+// 2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
+// 2012-06-20 - improved FIFO overflow handling and simplified read process
+// 2012-06-19 - completely rearranged DMP initialization code and simplification
+// 2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
+// 2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
+// 2012-06-05 - add gravity-compensated initial reference frame acceleration output
+// - add 3D math helper file to DMP6 example sketch
+// - add Euler output and Yaw/Pitch/Roll output formats
+// 2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
+// 2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
+// 2012-05-30 - basic DMP initialization working
+
+/* ============================================
+I2Cdev device library code is placed under the MIT license
+Copyright (c) 2012 Jeff Rowberg
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+===============================================
+*/
+
+// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
+// for both classes must be in the include path of your project
+#include "I2Cdev.h"
+
+#include "MPU6050_6Axis_MotionApps20.h"
+//#include "MPU6050.h" // not necessary if using MotionApps include file
+
+// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
+// is used in I2Cdev.h
+#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
+ #include "Wire.h"
+#endif
+
+// class default I2C address is 0x68
+// specific I2C addresses may be passed as a parameter here
+// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
+// AD0 high = 0x69
+MPU6050 mpu;
+//MPU6050 mpu(0x69); // <-- use for AD0 high
+
+/* =========================================================================
+ NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
+ depends on the MPU-6050's INT pin being connected to the Arduino's
+ external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
+ digital I/O pin 2.
+ * ========================================================================= */
+
+/* =========================================================================
+ NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
+ when using Serial.write(buf, len). The Teapot output uses this method.
+ The solution requires a modification to the Arduino USBAPI.h file, which
+ is fortunately simple, but annoying. This will be fixed in the next IDE
+ release. For more info, see these links:
+
+ http://arduino.cc/forum/index.php/topic,109987.0.html
+ http://code.google.com/p/arduino/issues/detail?id=958
+ * ========================================================================= */
+
+
+
+// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
+// quaternion components in a [w, x, y, z] format (not best for parsing
+// on a remote host such as Processing or something though)
+//#define OUTPUT_READABLE_QUATERNION
+
+// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
+// (in degrees) calculated from the quaternions coming from the FIFO.
+// Note that Euler angles suffer from gimbal lock (for more info, see
+// http://en.wikipedia.org/wiki/Gimbal_lock)
+//#define OUTPUT_READABLE_EULER
+
+// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
+// pitch/roll angles (in degrees) calculated from the quaternions coming
+// from the FIFO. Note this also requires gravity vector calculations.
+// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
+// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
+#define OUTPUT_READABLE_YAWPITCHROLL
+
+// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
+// components with gravity removed. This acceleration reference frame is
+// not compensated for orientation, so +X is always +X according to the
+// sensor, just without the effects of gravity. If you want acceleration
+// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
+//#define OUTPUT_READABLE_REALACCEL
+
+// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
+// components with gravity removed and adjusted for the world frame of
+// reference (yaw is relative to initial orientation, since no magnetometer
+// is present in this case). Could be quite handy in some cases.
+//#define OUTPUT_READABLE_WORLDACCEL
+
+// uncomment "OUTPUT_TEAPOT" if you want output that matches the
+// format used for the InvenSense teapot demo
+//#define OUTPUT_TEAPOT
+
+
+
+#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
+bool blinkState = false;
+
+// MPU control/status vars
+bool dmpReady = false; // set true if DMP init was successful
+uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
+uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
+uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
+uint16_t fifoCount; // count of all bytes currently in FIFO
+uint8_t fifoBuffer[64]; // FIFO storage buffer
+
+// orientation/motion vars
+Quaternion q; // [w, x, y, z] quaternion container
+VectorInt16 aa; // [x, y, z] accel sensor measurements
+VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
+VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
+VectorFloat gravity; // [x, y, z] gravity vector
+float euler[3]; // [psi, theta, phi] Euler angle container
+float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
+
+// packet structure for InvenSense teapot demo
+uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };
+
+
+
+// ================================================================
+// === INTERRUPT DETECTION ROUTINE ===
+// ================================================================
+
+volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
+void dmpDataReady() {
+ mpuInterrupt = true;
+}
+
+
+
+// ================================================================
+// === INITIAL SETUP ===
+// ================================================================
+
+void setup() {
+ // join I2C bus (I2Cdev library doesn't do this automatically)
+ #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
+ Wire.begin();
+ TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
+ #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
+ Fastwire::setup(400, true);
+ #endif
+
+ // initialize serial communication
+ // (115200 chosen because it is required for Teapot Demo output, but it's
+ // really up to you depending on your project)
+ Serial.begin(115200);
+ while (!Serial); // wait for Leonardo enumeration, others continue immediately
+
+ // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
+ // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
+ // the baud timing being too misaligned with processor ticks. You must use
+ // 38400 or slower in these cases, or use some kind of external separate
+ // crystal solution for the UART timer.
+
+ // initialize device
+ Serial.println(F("Initializing I2C devices..."));
+ mpu.initialize();
+
+ // verify connection
+ Serial.println(F("Testing device connections..."));
+ Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
+
+ // wait for ready
+ Serial.println(F("\nSend any character to begin DMP programming and demo: "));
+ while (Serial.available() && Serial.read()); // empty buffer
+ while (!Serial.available()); // wait for data
+ while (Serial.available() && Serial.read()); // empty buffer again
+
+ // load and configure the DMP
+ Serial.println(F("Initializing DMP..."));
+ devStatus = mpu.dmpInitialize();
+
+ // supply your own gyro offsets here, scaled for min sensitivity
+ mpu.setXGyroOffset(220);
+ mpu.setYGyroOffset(76);
+ mpu.setZGyroOffset(-85);
+ mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
+
+ // make sure it worked (returns 0 if so)
+ if (devStatus == 0) {
+ // turn on the DMP, now that it's ready
+ Serial.println(F("Enabling DMP..."));
+ mpu.setDMPEnabled(true);
+
+ // enable Arduino interrupt detection
+ Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
+ attachInterrupt(0, dmpDataReady, RISING);
+ mpuIntStatus = mpu.getIntStatus();
+
+ // set our DMP Ready flag so the main loop() function knows it's okay to use it
+ Serial.println(F("DMP ready! Waiting for first interrupt..."));
+ dmpReady = true;
+
+ // get expected DMP packet size for later comparison
+ packetSize = mpu.dmpGetFIFOPacketSize();
+ } else {
+ // ERROR!
+ // 1 = initial memory load failed
+ // 2 = DMP configuration updates failed
+ // (if it's going to break, usually the code will be 1)
+ Serial.print(F("DMP Initialization failed (code "));
+ Serial.print(devStatus);
+ Serial.println(F(")"));
+ }
+
+ // configure LED for output
+ pinMode(LED_PIN, OUTPUT);
+}
+
+
+
+// ================================================================
+// === MAIN PROGRAM LOOP ===
+// ================================================================
+
+void loop() {
+ // if programming failed, don't try to do anything
+ if (!dmpReady) return;
+
+ // wait for MPU interrupt or extra packet(s) available
+ while (!mpuInterrupt && fifoCount < packetSize) {
+ // other program behavior stuff here
+ // .
+ // .
+ // .
+ // if you are really paranoid you can frequently test in between other
+ // stuff to see if mpuInterrupt is true, and if so, "break;" from the
+ // while() loop to immediately process the MPU data
+ // .
+ // .
+ // .
+ }
+
+ // reset interrupt flag and get INT_STATUS byte
+ mpuInterrupt = false;
+ mpuIntStatus = mpu.getIntStatus();
+
+ // get current FIFO count
+ fifoCount = mpu.getFIFOCount();
+
+ // check for overflow (this should never happen unless our code is too inefficient)
+ if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
+ // reset so we can continue cleanly
+ mpu.resetFIFO();
+ Serial.println(F("FIFO overflow!"));
+
+ // otherwise, check for DMP data ready interrupt (this should happen frequently)
+ } else if (mpuIntStatus & 0x02) {
+ // wait for correct available data length, should be a VERY short wait
+ while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
+
+ // read a packet from FIFO
+ mpu.getFIFOBytes(fifoBuffer, packetSize);
+
+ // track FIFO count here in case there is > 1 packet available
+ // (this lets us immediately read more without waiting for an interrupt)
+ fifoCount -= packetSize;
+
+ #ifdef OUTPUT_READABLE_QUATERNION
+ // display quaternion values in easy matrix form: w x y z
+ mpu.dmpGetQuaternion(&q, fifoBuffer);
+ Serial.print("quat\t");
+ Serial.print(q.w);
+ Serial.print("\t");
+ Serial.print(q.x);
+ Serial.print("\t");
+ Serial.print(q.y);
+ Serial.print("\t");
+ Serial.println(q.z);
+ #endif
+
+ #ifdef OUTPUT_READABLE_EULER
+ // display Euler angles in degrees
+ mpu.dmpGetQuaternion(&q, fifoBuffer);
+ mpu.dmpGetEuler(euler, &q);
+ Serial.print("euler\t");
+ Serial.print(euler[0] * 180/M_PI);
+ Serial.print("\t");
+ Serial.print(euler[1] * 180/M_PI);
+ Serial.print("\t");
+ Serial.println(euler[2] * 180/M_PI);
+ #endif
+
+ #ifdef OUTPUT_READABLE_YAWPITCHROLL
+ // display Euler angles in degrees
+ mpu.dmpGetQuaternion(&q, fifoBuffer);
+ mpu.dmpGetGravity(&gravity, &q);
+ mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
+ Serial.print("ypr\t");
+ Serial.print(ypr[0] * 180/M_PI);
+ Serial.print("\t");
+ Serial.print(ypr[1] * 180/M_PI);
+ Serial.print("\t");
+ Serial.println(ypr[2] * 180/M_PI);
+ #endif
+
+ #ifdef OUTPUT_READABLE_REALACCEL
+ // display real acceleration, adjusted to remove gravity
+ mpu.dmpGetQuaternion(&q, fifoBuffer);
+ mpu.dmpGetAccel(&aa, fifoBuffer);
+ mpu.dmpGetGravity(&gravity, &q);
+ mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
+ Serial.print("areal\t");
+ Serial.print(aaReal.x);
+ Serial.print("\t");
+ Serial.print(aaReal.y);
+ Serial.print("\t");
+ Serial.println(aaReal.z);
+ #endif
+
+ #ifdef OUTPUT_READABLE_WORLDACCEL
+ // display initial world-frame acceleration, adjusted to remove gravity
+ // and rotated based on known orientation from quaternion
+ mpu.dmpGetQuaternion(&q, fifoBuffer);
+ mpu.dmpGetAccel(&aa, fifoBuffer);
+ mpu.dmpGetGravity(&gravity, &q);
+ mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
+ mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
+ Serial.print("aworld\t");
+ Serial.print(aaWorld.x);
+ Serial.print("\t");
+ Serial.print(aaWorld.y);
+ Serial.print("\t");
+ Serial.println(aaWorld.z);
+ #endif
+
+ #ifdef OUTPUT_TEAPOT
+ // display quaternion values in InvenSense Teapot demo format:
+ teapotPacket[2] = fifoBuffer[0];
+ teapotPacket[3] = fifoBuffer[1];
+ teapotPacket[4] = fifoBuffer[4];
+ teapotPacket[5] = fifoBuffer[5];
+ teapotPacket[6] = fifoBuffer[8];
+ teapotPacket[7] = fifoBuffer[9];
+ teapotPacket[8] = fifoBuffer[12];
+ teapotPacket[9] = fifoBuffer[13];
+ Serial.write(teapotPacket, 14);
+ teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
+ #endif
+
+ // blink LED to indicate activity
+ blinkState = !blinkState;
+ digitalWrite(LED_PIN, blinkState);
+ }
+}
--- /dev/null
+/*
+Measure the lenght of the Loop cycle.
+*/
+
+long lastMillis = 0;
+long loops = 0;
+
+void setup(){
+ Serial.begin(9600);
+}
+
+void loop(){
+ long currentMillis = millis();
+ loops++;
+
+ /* By doing complex math, reading sensors, using the "delay" function,
+ * etc you will increase the time required to finish the loop,
+ * which will decrease the number of loops per second.
+ */
+
+ if(currentMillis - lastMillis > 1000){
+ Serial.print("Loops last second:");
+ Serial.println(loops);
+
+ lastMillis = currentMillis;
+ loops = 0;
+ }
+}
+
+
--- /dev/null
+// See tutotial: http://tronixlabs.com/news/tutorial-using-ds1307-and-ds3231-realtime-clock-modules-with-arduino/
+
+#include "Wire.h"
+#define DS3231_I2C_ADDRESS 0x68
+// Convert normal decimal numbers to binary coded decimal
+byte decToBcd(byte val)
+{
+ return( (val/10*16) + (val%10) );
+}
+// Convert binary coded decimal to normal decimal numbers
+byte bcdToDec(byte val)
+{
+ return( (val/16*10) + (val%16) );
+}
+void setup()
+{
+ Wire.begin();
+ Serial.begin(9600);
+ // set the initial time here:
+ // DS3231 seconds, minutes, hours, day, date, month, year
+ //setDS3231time(30,27,19,2,10,2,15); // Comment again after setting up
+ // or you will rset the clock at each upload
+}
+void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
+dayOfMonth, byte month, byte year)
+{
+ // sets time and date data to DS3231
+ Wire.beginTransmission(DS3231_I2C_ADDRESS);
+ Wire.write(0); // set next input to start at the seconds register
+ Wire.write(decToBcd(second)); // set seconds
+ Wire.write(decToBcd(minute)); // set minutes
+ Wire.write(decToBcd(hour)); // set hours
+ Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
+ Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
+ Wire.write(decToBcd(month)); // set month
+ Wire.write(decToBcd(year)); // set year (0 to 99)
+ Wire.endTransmission();
+}
+void readDS3231time(byte *second,
+byte *minute,
+byte *hour,
+byte *dayOfWeek,
+byte *dayOfMonth,
+byte *month,
+byte *year)
+{
+ Wire.beginTransmission(DS3231_I2C_ADDRESS);
+ Wire.write(0); // set DS3231 register pointer to 00h
+ Wire.endTransmission();
+ Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
+ // request seven bytes of data from DS3231 starting from register 00h
+ *second = bcdToDec(Wire.read() & 0x7f);
+ *minute = bcdToDec(Wire.read());
+ *hour = bcdToDec(Wire.read() & 0x3f);
+ *dayOfWeek = bcdToDec(Wire.read());
+ *dayOfMonth = bcdToDec(Wire.read());
+ *month = bcdToDec(Wire.read());
+ *year = bcdToDec(Wire.read());
+}
+void displayTime()
+{
+ byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
+ // retrieve data from DS3231
+ readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month,
+ &year);
+ // send it to the serial monitor
+ Serial.print(hour, DEC);
+ // convert the byte variable to a decimal number when displayed
+ Serial.print(":");
+ if (minute<10)
+ {
+ Serial.print("0");
+ }
+ Serial.print(minute, DEC);
+ Serial.print(":");
+ if (second<10)
+ {
+ Serial.print("0");
+ }
+ Serial.print(second, DEC);
+ Serial.print(" ");
+ Serial.print(dayOfMonth, DEC);
+ Serial.print("/");
+ Serial.print(month, DEC);
+ Serial.print("/");
+ Serial.print(year, DEC);
+ Serial.print(" Day of week: ");
+ switch(dayOfWeek){
+ case 1:
+ Serial.println("Sunday");
+ break;
+ case 2:
+ Serial.println("Monday");
+ break;
+ case 3:
+ Serial.println("Tuesday");
+ break;
+ case 4:
+ Serial.println("Wednesday");
+ break;
+ case 5:
+ Serial.println("Thursday");
+ break;
+ case 6:
+ Serial.println("Friday");
+ break;
+ case 7:
+ Serial.println("Saturday");
+ break;
+ }
+}
+void loop()
+{
+ displayTime(); // display the real-time clock data on the Serial Monitor,
+ delay(1000); // every second
+}
+
+
--- /dev/null
+/*
+ HC-SR04 Ping distance sensor:
+ VCC to arduino 5v
+ GND to arduino GND
+ Echo to Arduino pin 7
+ Trig to Arduino pin 8
+
+ This sketch originates from Virtualmix: http://goo.gl/kJ8Gl
+ Has been modified by Winkle ink here: http://winkleink.blogspot.com.au/2012/05/arduino-hc-sr04-ultrasonic-distance.html
+ And modified further by ScottC here: http://arduinobasics.blogspot.com.au/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html
+ on 10 Nov 2012.
+ */
+
+
+#define echoPin 7 // Echo Pin
+#define trigPin 8 // Trigger Pin
+#define LEDPin 13 // Onboard LED
+
+int maximumRange = 200; // Maximum range needed
+int minimumRange = 0; // Minimum range needed
+long duration, distance; // Duration used to calculate distance
+
+void setup() {
+ Serial.begin (9600);
+ pinMode(trigPin, OUTPUT);
+ pinMode(echoPin, INPUT);
+ pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
+}
+
+void loop() {
+/* The following trigPin/echoPin cycle is used to determine the
+ distance of the nearest object by bouncing soundwaves off of it. */
+ digitalWrite(trigPin, LOW);
+ delayMicroseconds(2);
+
+ digitalWrite(trigPin, HIGH);
+ delayMicroseconds(10);
+
+ digitalWrite(trigPin, LOW);
+ duration = pulseIn(echoPin, HIGH);
+
+ //Calculate the distance (in cm) based on the speed of sound.
+ distance = duration/58.2;
+
+ if (distance >= maximumRange || distance <= minimumRange){
+ /* Send a negative number to computer and Turn LED ON
+ to indicate "out of range" */
+ Serial.println("-1");
+ digitalWrite(LEDPin, HIGH);
+ }
+ else {
+ /* Send the distance to the computer using Serial protocol, and
+ turn LED OFF to indicate successful reading. */
+ Serial.println(distance);
+ digitalWrite(LEDPin, LOW);
+ }
+
+ //Delay 50ms before next reading.
+ delay(50);
+}
+
+// End Arduino, start Processing
+// Take care of: myPort (for serial comm)
+///*
+///* The following Processing Sketch was created by ScottC on
+// the 10 Nov 2012 : http://arduinobasics.blogspot.com/
+//
+// Inspired by this Processing sketch by Daniel Shiffman:
+// http://processing.org/learning/basics/sinewave.html
+//
+//*/
+//import processing.serial.*;
+//
+//
+//int numOfShapes = 60; // Number of squares to display on screen
+//int shapeSpeed = 2; // Speed at which the shapes move to new position
+// // 2 = Fastest, Larger numbers are slower
+//
+////Global Variables
+//Square[] mySquares = new Square[numOfShapes];
+//int shapeSize, distance;
+//String comPortString;
+//Serial myPort;
+//
+///* -----------------------Setup ---------------------------*/
+//void setup(){
+// size(displayWidth,displayHeight); //Use entire screen size.
+// smooth(); // draws all shapes with smooth edges.
+//
+// /* Calculate the size of the squares and initialise the Squares array */
+// shapeSize = (width/numOfShapes);
+// for(int i = 0; i<numOfShapes; i++){
+// mySquares[i]=new Square(int(shapeSize*i),height-40);
+// }
+//
+// /*Open the serial port for communication with the Arduino
+// Make sure the COM port is correct - I am using COM port 8 */
+// myPort = new Serial(this, "/dev/ttyACM2", 9600);
+// myPort.bufferUntil('\n'); // Trigger a SerialEvent on new line
+//}
+//
+///* ------------------------Draw -----------------------------*/
+//void draw(){
+// background(0); //Make the background BLACK
+// delay(50); //Delay used to refresh screen
+// drawSquares(); //Draw the pattern of squares
+//}
+//
+//
+///* ---------------------serialEvent ---------------------------*/
+//void serialEvent(Serial cPort){
+// comPortString = cPort.readStringUntil('\n');
+// if(comPortString != null) {
+// comPortString=trim(comPortString);
+//
+// /* Use the distance received by the Arduino to modify the y position
+// of the first square (others will follow). Should match the
+// code settings on the Arduino. In this case 200 is the maximum
+// distance expected. The distance is then mapped to a value
+// between 1 and the height of your screen */
+// distance = int(map(Integer.parseInt(comPortString),1,200,1,height));
+// if(distance<0){
+// /*If computer receives a negative number (-1), then the
+// sensor is reporting an "out of range" error. Convert all
+// of these to a distance of 0. */
+// distance = 0;
+// }
+// }
+//}
+//
+//
+///* ---------------------drawSquares ---------------------------*/
+//void drawSquares(){
+// int oldY, newY, targetY, redVal, blueVal;
+//
+// /* Set the Y position of the 1st square based on
+// sensor value received */
+// mySquares[0].setY((height-shapeSize)-distance);
+//
+// /* Update the position and colour of each of the squares */
+// for(int i = numOfShapes-1; i>0; i--){
+// /* Use the previous square's position as a target */
+// targetY=mySquares[i-1].getY();
+// oldY=mySquares[i].getY();
+//
+// if(abs(oldY-targetY)<2){
+// newY=targetY; //This helps to line them up
+// }else{
+// //calculate the new position of the square
+// newY=oldY-((oldY-targetY)/shapeSpeed);
+// }
+// //Set the new position of the square
+// mySquares[i].setY(newY);
+//
+// /*Calculate the colour of the square based on its
+// position on the screen */
+// blueVal = int(map(newY,0,height,0,255));
+// redVal = 255-blueVal;
+// fill(redVal,0,blueVal);
+//
+// /* Draw the square on the screen */
+// rect(mySquares[i].getX(), mySquares[i].getY(),shapeSize,shapeSize);
+// }
+//}
+//
+///* ---------------------sketchFullScreen---------------------------*/
+//// This puts processing into Full Screen Mode
+//boolean sketchFullScreen() {
+// return true;
+//}
+//
+///* ---------------------CLASS: Square ---------------------------*/
+//class Square{
+// int xPosition, yPosition;
+//
+// Square(int xPos, int yPos){
+// xPosition = xPos;
+// yPosition = yPos;
+// }
+//
+// int getX(){
+// return xPosition;
+// }
+//
+// int getY(){
+// return yPosition;
+// }
+//
+// void setY(int yPos){
+// yPosition = yPos;
+// }
+//}
+
--- /dev/null
+/*
+HC-SR04 Ping distance sensor]
+ VCC to arduino 5v GND to arduino GND
+ Echo to Arduino pin 13 Trig to Arduino pin 12
+ Red POS to Arduino pin 11
+ Green POS to Arduino pin 10
+ 560 ohm resistor to both LED NEG and GRD power rail
+ More info at: http://goo.gl/kJ8Gl
+ Original code improvements to the Ping sketch sourced from Trollmaker.com
+ Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar
+ */
+
+#define trigPin 8
+#define echoPin 7
+#define RED 11
+#define GREEN 10
+
+void setup() {
+ Serial.begin (9600);
+ pinMode(trigPin, OUTPUT);
+ pinMode(echoPin, INPUT);
+ pinMode(RED, OUTPUT);
+ pinMode(GREEN, OUTPUT);
+}
+
+void loop() {
+ long duration, distance;
+ digitalWrite(trigPin, LOW); // Prepare for ping
+ delayMicroseconds(2); //
+ digitalWrite(trigPin, HIGH); // Send a ping
+ delayMicroseconds(10); //
+ digitalWrite(trigPin, LOW); // Set down ping
+ duration = pulseIn(echoPin, HIGH);
+ distance = (duration/2) / 29.1; // Speed is ~300m/s,
+ // so it takes ~29.1 milliseconds for a cm.
+ // Distance is half of (out + back)
+ if (distance < 5) { // This is where the LED On/Off happens
+ digitalWrite(RED,HIGH); // When the Red condition is met, the Green LED should turn off
+ digitalWrite(GREEN,LOW);
+ }
+ else {
+ digitalWrite(RED,LOW);
+ digitalWrite(GREEN,HIGH);
+ }
+ if (distance >= 200 || distance <= 0){
+ Serial.println("Out of range");
+ }
+ else {
+ Serial.print(distance);
+ Serial.println(" cm");
+ }
+ delay(500);
+}
+
--- /dev/null
+/*
+ Simple Motor with variable spped from pot input
+
+ This sketch use a transistor and a diode
+ in order to poer a 5v ~150mAh directly from the board.
+ Hard thing is to find a suitable motor!
+
+
+ This version uses a pot as throttle control,
+ serial for debuggin.
+
+ Optimized for a minimum throttle value in order to keep the motor off
+ */
+
+const int analogInPin = A0;
+const int motorPin = 9;
+
+int potValue = 0;
+int motValue = 0;
+const int minMotValue = 50 ; // Minimum power requiement of my own motr,
+ // This is going to differ from motor to motor
+
+void setup() {
+ pinMode(motorPin, OUTPUT);
+ Serial.begin(9600); // Debuggin
+
+}
+void loop() {
+ potValue = analogRead(analogInPin);
+ motValue = potValue / 4 ; // Simple mapping 1024 -> 255
+
+if (motValue > minMotValue) { // Minimum motor spped check
+ analogWrite(motorPin,motValue); // Change the PWM speed of the motor
+} else {
+analogWrite(motorPin,LOW) ;
+}
+
+
+ Serial.print("Pot value = " );
+ Serial.print(potValue);
+ Serial.print("\t Motor speed = ");
+ Serial.println(motValue);
+ delay(3); // Pause, helps to stabilize the input,
+ // slows the serial output
+}
+
+
+
+
+
+
--- /dev/null
+/*
+ Simple Motor with variable spped from pot input
+
+ This sketch use a transistor and a diode
+ in order to poer a 5v ~150mAh directly from the board.
+ Hard thing is to find a suitable motor!
+
+ This version uses a pot as throttle control,
+ serial for debuggin.
+ */
+
+const int analogInPin = A0;
+const int motorPin = 9;
+
+int potValue = 0;
+int motValue = 0;
+
+void setup() {
+ pinMode(motorPin, OUTPUT);
+ Serial.begin(9600); // Debuggin
+
+}
+void loop() {
+ potValue = analogRead(analogInPin);
+ motValue = potValue / 4 ; // Simple mapping 1024 -> 255
+
+ analogWrite(motorPin,motValue); // Change the PWM speed of the motor
+
+ Serial.print("Pot value = " );
+ Serial.print(potValue);
+ Serial.print("\t Motor speed = ");
+ Serial.println(motValue);
+ delay(3); // Pause, helps to stabilize the input
+ // and keeps a brushed motor from over heating ;)
+}
+
+
+
+
+
+
--- /dev/null
+/* Simple Motor
+ This sketch use a transistor and a diode
+ in order to poer a 5v ~150mAh directly from the board.
+ Hard thing is to find a suitable motor!
+
+ This version uses PWM for acceleration / deceleration
+ */
+
+int motorPin = 9;
+void setup() {
+ pinMode(motorPin, OUTPUT);
+}
+void loop() {
+ for(int motorValue = 0 ; motorValue <= 255; motorValue +=5){ // PWM up
+ analogWrite(motorPin, motorValue);
+ delay(60);
+ }
+ for(int motorValue = 255 ; motorValue >= 0; motorValue -=5){ // PWM down
+ analogWrite(motorPin, motorValue);
+ delay(30);
+ }
+delay(900); // Pause
+}
+
+
+
+
--- /dev/null
+/* Simple Motor
+ This sketch use a transistor and a diode
+ in order to power a 5v ~150mAh directly from the board.
+ Hard thing is to find a suitable motor!
+
+ In order to power a more powerfull motor you need to connect
+ the transistor to an other power line.
+ */
+
+int motorPin = 9;
+void setup() {
+ pinMode(motorPin, OUTPUT); // We drive the motor just like a LED
+}
+
+void loop() {
+ digitalWrite(motorPin, HIGH); // Turn on the motor full throttle
+ delay(1000);
+ digitalWrite(motorPin, LOW); // Turn off motor
+ delay(5000);
+}
+
+
+
--- /dev/null
+/*
+ Analog Input
+ Demonstrates analog input by reading an analog sensor on analog pin 0 and
+ turning on and off a light emitting diode(LED) connected to digital pin 13.
+ The amount of time the LED will be on and off depends on
+ the value obtained by analogRead().
+
+ The circuit:
+ * Potentiometer attached to analog input 0
+ * center pin of the potentiometer to the analog pin
+ * one side pin (either one) to ground
+ * the other side pin to +5V
+ * LED anode (long leg) attached to digital output 13
+ * LED cathode (short leg) attached to ground
+
+ * Note: because most Arduinos have a built-in LED attached
+ to pin 13 on the board, the LED is optional.
+
+
+ Created by David Cuartielles
+ modified 30 Aug 2011
+ By Tom Igoe
+
+ This example code is in the public domain.
+
+ http://arduino.cc/en/Tutorial/AnalogInput
+
+ Modified by A.Manni for using a 2.4k Pot with 2 5k resistors
+ Range = (1024 - offset) * 1024 / (1024 - offset)
+ With serial debugging.
+ */
+
+int sensorPin = A0; // select the input pin for the potentiometer
+int ledPin = 13; // select the pin for the LED
+int sensorValue = 0; // variable to store the value coming from the sensor
+
+void setup() {
+ // declare the ledPin as an OUTPUT:
+ pinMode(ledPin, OUTPUT);
+ Serial.begin(9600);
+}
+
+void loop() {
+ // read the value from the sensor:
+ sensorValue = analogRead(sensorPin);
+ // turn the ledPin on
+ digitalWrite(ledPin, HIGH);
+ // stop the program for <sensorValue> milliseconds:
+ delay(sensorValue);
+ // turn the ledPin off:
+ digitalWrite(ledPin, LOW);
+ // stop the program for for <sensorValue> milliseconds:
+ // Range = (1024 - offset) * 1024 / (1024 - offset)
+ delay((sensorValue -723 ) * 3.4); // Range = 723 - 1024
+ Serial.print("Sensor Value: ") ;
+ Serial.println(sensorValue);
+ Serial.print("Adjusted value: ") ;
+ Serial.println((sensorValue -723 ) * 3.4);
+}
--- /dev/null
+/*
+ Analog Input
+ Demonstrates analog input by reading an analog sensor on analog pin 0 and
+ turning on and off a light emitting diode(LED) connected to digital pin 13.
+ The amount of time the LED will be on and off depends on
+ the value obtained by analogRead().
+
+ The circuit:
+ * Potentiometer attached to analog input 0
+ * center pin of the potentiometer to the analog pin
+ * one side pin (either one) to ground
+ * the other side pin to +5V
+ * LED anode (long leg) attached to digital output 13
+ * LED cathode (short leg) attached to ground
+
+ * Note: because most Arduinos have a built-in LED attached
+ to pin 13 on the board, the LED is optional.
+
+
+ Created by David Cuartielles
+ modified 30 Aug 2011
+ By Tom Igoe
+
+ This example code is in the public domain.
+
+ http://arduino.cc/en/Tutorial/AnalogInput
+
+ Modified by A.Manni for using a 2.4k Pot with 2 5k resistors
+ Range = (1024 - offset) * 1024 / (1024 - offset)
+ Range can be defined with map(sensorValue, 724, 0124, 0, 1024)
+ Note: range is inverted
+ With serial debugging.
+ - Added initial limit for delay
+
+ */
+
+int sensorPin = A0; // select the input pin for the potentiometer
+int ledPin = 13; // select the pin for the LED
+int sensorValue = 0; // variable to store the value coming from the sensor
+int calValue = map(sensorValue, 723, 1024, 0, 1024) ; // variable to store calibrated value for the Pot
+// This could be done with a map()
+void setup() {
+
+ pinMode(ledPin, OUTPUT); // declare the ledPin as an OUTPUT:
+ Serial.begin(9600);
+
+}
+
+void loop() {
+ // read the value from the sensor:
+ sensorValue = analogRead(sensorPin);
+
+ // turn the ledPin on
+ digitalWrite(ledPin, HIGH);
+ // stop the program for <sensorValue> milliseconds:
+ delay(sensorValue);
+ // turn the ledPin off:
+ digitalWrite(ledPin, LOW);
+ // stop the program for for <sensorValue> milliseconds:
+ // Range = (1024 - offset) * 1024 / (1024 - offset)
+ // calValue = (sensorValue -723 ) * 3.4 ;
+ delay(calValue);
+ Serial.print("Sensor Value: ") ;
+ Serial.println(sensorValue);
+ Serial.print("Adjusted value: ") ;
+ Serial.println(calValue);
+
+}
+
+
+
--- /dev/null
+There are 4/5 nice sketches bundled with arduino:
+-> Digital : tone*
+-> Sensors: knock
--- /dev/null
+/*
+ Melody keyboard with Input Pullup Serial
+ Plays a pitch that changes based on 3 digital inputs
+
+ This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a
+ digital input on pin 2 and prints the results to the serial monitor.
+
+ Thecircuit:
+ * 3 buttons in pin 2,3,4 with no resistors
+ * Piezo on digital pin 9
+ * Serial debug is available
+
+ This example code is in the public domain
+
+ */
+
+// Please take care of the include path
+#include "/root/arduino/sketchbook-lessons/piezo_mario_tune/pitches.h";
+int input[]= {1,2,3};
+ int notes[] = {
+ NOTE_A4, NOTE_C4,NOTE_E3 };
+
+void setup(){
+ //start serial connection
+ Serial.begin(9600);
+ //configure pin2 as an input and enable the internal pull-up resistor
+ pinMode(2, INPUT_PULLUP);
+ pinMode(3, INPUT_PULLUP);
+ pinMode(4, INPUT_PULLUP);
+ pinMode(9, OUTPUT);
+
+
+}
+
+void loop(){
+ for (int thisSensor = 2; thisSensor < 5; thisSensor++) {
+ int sensorReading = digitalRead(thisSensor);
+ if (sensorReading == LOW) {
+ Serial.println(thisSensor);
+ tone(9, notes[thisSensor -2], 50); // Notes array is translated
+ }
+ //delay(2);
+ }
+}
+
+
+
--- /dev/null
+/*
+ Arduino Mario Bros Tunes
+ With Piezo Buzzer and PWM
+ by: Dipto Pratyaksa
+ last updated: 31/3/13
+*/
+#include <pitches.h>
+
+#define melodyPin 3
+//Mario main theme melody
+int melody[] = {
+ NOTE_E7, NOTE_E7, 0, NOTE_E7,
+ 0, NOTE_C7, NOTE_E7, 0,
+ NOTE_G7, 0, 0, 0,
+ NOTE_G6, 0, 0, 0,
+
+ NOTE_C7, 0, 0, NOTE_G6,
+ 0, 0, NOTE_E6, 0,
+ 0, NOTE_A6, 0, NOTE_B6,
+ 0, NOTE_AS6, NOTE_A6, 0,
+
+ NOTE_G6, NOTE_E7, NOTE_G7,
+ NOTE_A7, 0, NOTE_F7, NOTE_G7,
+ 0, NOTE_E7, 0,NOTE_C7,
+ NOTE_D7, NOTE_B6, 0, 0,
+
+ NOTE_C7, 0, 0, NOTE_G6,
+ 0, 0, NOTE_E6, 0,
+ 0, NOTE_A6, 0, NOTE_B6,
+ 0, NOTE_AS6, NOTE_A6, 0,
+
+ NOTE_G6, NOTE_E7, NOTE_G7,
+ NOTE_A7, 0, NOTE_F7, NOTE_G7,
+ 0, NOTE_E7, 0,NOTE_C7,
+ NOTE_D7, NOTE_B6, 0, 0
+};
+//Mario main them tempo
+int tempo[] = {
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+
+ 9, 9, 9,
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+
+ 9, 9, 9,
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+ 12, 12, 12, 12,
+};
+
+//
+
+//Underworld melody
+int underworld_melody[] = {
+ NOTE_C4, NOTE_C5, NOTE_A3, NOTE_A4,
+ NOTE_AS3, NOTE_AS4, 0,
+ 0,
+ NOTE_C4, NOTE_C5, NOTE_A3, NOTE_A4,
+ NOTE_AS3, NOTE_AS4, 0,
+ 0,
+ NOTE_F3, NOTE_F4, NOTE_D3, NOTE_D4,
+ NOTE_DS3, NOTE_DS4, 0,
+ 0,
+ NOTE_F3, NOTE_F4, NOTE_D3, NOTE_D4,
+ NOTE_DS3, NOTE_DS4, 0,
+ 0, NOTE_DS4, NOTE_CS4, NOTE_D4,
+ NOTE_CS4, NOTE_DS4,
+ NOTE_DS4, NOTE_GS3,
+ NOTE_G3, NOTE_CS4,
+ NOTE_C4, NOTE_FS4,NOTE_F4, NOTE_E3, NOTE_AS4, NOTE_A4,
+ NOTE_GS4, NOTE_DS4, NOTE_B3,
+ NOTE_AS3, NOTE_A3, NOTE_GS3,
+ 0, 0, 0
+};
+//Underwolrd tempo
+int underworld_tempo[] = {
+ 12, 12, 12, 12,
+ 12, 12, 6,
+ 3,
+ 12, 12, 12, 12,
+ 12, 12, 6,
+ 3,
+ 12, 12, 12, 12,
+ 12, 12, 6,
+ 3,
+ 12, 12, 12, 12,
+ 12, 12, 6,
+ 6, 18, 18, 18,
+ 6, 6,
+ 6, 6,
+ 6, 6,
+ 18, 18, 18,18, 18, 18,
+ 10, 10, 10,
+ 10, 10, 10,
+ 3, 3, 3
+};
+
+void setup(void)
+{
+ pinMode(3, OUTPUT);//buzzer
+ pinMode(13, OUTPUT);//led indicator when singing a note
+
+}
+void loop()
+{
+//sing the tunes
+ sing(1);
+ sing(1);
+ sing(2);
+}
+int song = 0;
+
+void sing(int s){
+ // iterate over the notes of the melody:
+ song = s;
+ if(song==2){
+ Serial.println(" 'Underworld Theme'");
+ int size = sizeof(underworld_melody) / sizeof(int);
+ for (int thisNote = 0; thisNote < size; thisNote++) {
+
+ // to calculate the note duration, take one second
+ // divided by the note type.
+ //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
+ int noteDuration = 1000/underworld_tempo[thisNote];
+
+ buzz(melodyPin, underworld_melody[thisNote],noteDuration);
+
+ // to distinguish the notes, set a minimum time between them.
+ // the note's duration + 30% seems to work well:
+ int pauseBetweenNotes = noteDuration * 1.30;
+ delay(pauseBetweenNotes);
+
+ // stop the tone playing:
+ buzz(melodyPin, 0,noteDuration);
+
+ }
+
+ }else{
+
+ Serial.println(" 'Mario Theme'");
+ int size = sizeof(melody) / sizeof(int);
+ for (int thisNote = 0; thisNote < size; thisNote++) {
+
+ // to calculate the note duration, take one second
+ // divided by the note type.
+ //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
+ int noteDuration = 1000/tempo[thisNote];
+
+ buzz(melodyPin, melody[thisNote],noteDuration);
+
+ // to distinguish the notes, set a minimum time between them.
+ // the note's duration + 30% seems to work well:
+ int pauseBetweenNotes = noteDuration * 1.30;
+ delay(pauseBetweenNotes);
+
+ // stop the tone playing:
+ buzz(melodyPin, 0,noteDuration);
+
+ }
+ }
+}
+
+void buzz(int targetPin, long frequency, long length) {
+ digitalWrite(13,HIGH);
+ long delayValue = 1000000/frequency/2; // calculate the delay value between transitions
+ //// 1 second's worth of microseconds, divided by the frequency, then split in half since
+ //// there are two phases to each cycle
+ long numCycles = frequency * length/ 1000; // calculate the number of cycles for proper timing
+ //// multiply frequency, which is really cycles per second, by the number of seconds to
+ //// get the total number of cycles to produce
+ for (long i=0; i < numCycles; i++){ // for the calculated length of time...
+ digitalWrite(targetPin,HIGH); // write the buzzer pin high to push out the diaphram
+ delayMicroseconds(delayValue); // wait for the calculated delay value
+ digitalWrite(targetPin,LOW); // write the buzzer pin low to pull back the diaphram
+ delayMicroseconds(delayValue); // wait again or the calculated delay value
+ }
+ digitalWrite(13,LOW);
+
+}
--- /dev/null
+/*************************************************
+ * Public Constants
+ *************************************************/
+
+#define NOTE_B0 31
+#define NOTE_C1 33
+#define NOTE_CS1 35
+#define NOTE_D1 37
+#define NOTE_DS1 39
+#define NOTE_E1 41
+#define NOTE_F1 44
+#define NOTE_FS1 46
+#define NOTE_G1 49
+#define NOTE_GS1 52
+#define NOTE_A1 55
+#define NOTE_AS1 58
+#define NOTE_B1 62
+#define NOTE_C2 65
+#define NOTE_CS2 69
+#define NOTE_D2 73
+#define NOTE_DS2 78
+#define NOTE_E2 82
+#define NOTE_F2 87
+#define NOTE_FS2 93
+#define NOTE_G2 98
+#define NOTE_GS2 104
+#define NOTE_A2 110
+#define NOTE_AS2 117
+#define NOTE_B2 123
+#define NOTE_C3 131
+#define NOTE_CS3 139
+#define NOTE_D3 147
+#define NOTE_DS3 156
+#define NOTE_E3 165
+#define NOTE_F3 175
+#define NOTE_FS3 185
+#define NOTE_G3 196
+#define NOTE_GS3 208
+#define NOTE_A3 220
+#define NOTE_AS3 233
+#define NOTE_B3 247
+#define NOTE_C4 262
+#define NOTE_CS4 277
+#define NOTE_D4 294
+#define NOTE_DS4 311
+#define NOTE_E4 330
+#define NOTE_F4 349
+#define NOTE_FS4 370
+#define NOTE_G4 392
+#define NOTE_GS4 415
+#define NOTE_A4 440
+#define NOTE_AS4 466
+#define NOTE_B4 494
+#define NOTE_C5 523
+#define NOTE_CS5 554
+#define NOTE_D5 587
+#define NOTE_DS5 622
+#define NOTE_E5 659
+#define NOTE_F5 698
+#define NOTE_FS5 740
+#define NOTE_G5 784
+#define NOTE_GS5 831
+#define NOTE_A5 880
+#define NOTE_AS5 932
+#define NOTE_B5 988
+#define NOTE_C6 1047
+#define NOTE_CS6 1109
+#define NOTE_D6 1175
+#define NOTE_DS6 1245
+#define NOTE_E6 1319
+#define NOTE_F6 1397
+#define NOTE_FS6 1480
+#define NOTE_G6 1568
+#define NOTE_GS6 1661
+#define NOTE_A6 1760
+#define NOTE_AS6 1865
+#define NOTE_B6 1976
+#define NOTE_C7 2093
+#define NOTE_CS7 2217
+#define NOTE_D7 2349
+#define NOTE_DS7 2489
+#define NOTE_E7 2637
+#define NOTE_F7 2794
+#define NOTE_FS7 2960
+#define NOTE_G7 3136
+#define NOTE_GS7 3322
+#define NOTE_A7 3520
+#define NOTE_AS7 3729
+#define NOTE_B7 3951
+#define NOTE_C8 4186
+#define NOTE_CS8 4435
+#define NOTE_D8 4699
+#define NOTE_DS8 4978
+
+
--- /dev/null
+- Simple serial communication 2 arduino: switch 1 and LED 2
+- Serial Parser: Examples -> strings
+- Serial to RGB LED
+
+
+- I2C
+- SPI
+- display lcd , clock, ethernet, gyro,
--- /dev/null
+
+//**************************************************************//
+// Name : shiftOutCode, Hello World
+// Author : Carlyn Maw,Tom Igoe, David A. Mellis
+// Date : 25 Oct, 2006
+// Modified: 23 Mar 2010
+// Version : 2.0
+// Notes : Code for using a 74HC595 Shift Register //
+// : to count from 0 to 255
+//****************************************************************
+
+//Pin connected to ST_CP of 74HC595
+int latchPin = 8;
+//Pin connected to SH_CP of 74HC595
+int clockPin = 12;
+////Pin connected to DS of 74HC595
+int dataPin = 11;
+
+
+
+void setup() {
+ //set pins to output so you can control the shift register
+ pinMode(latchPin, OUTPUT);
+ pinMode(clockPin, OUTPUT);
+ pinMode(dataPin, OUTPUT);
+ // Serial Debug
+ Serial.begin(9600);
+ Serial.print("Decimal");
+ Serial.print("\t");
+ Serial.println("Binary");
+}
+
+void loop() {
+ // count from 0 to 255 and display the number
+ // on the LEDs
+ for (int numberToDisplay = 0; numberToDisplay < 256; numberToDisplay++) {
+ // take the latchPin low so
+ // the LEDs don't change while you're sending in bits:
+ digitalWrite(latchPin, LOW);
+
+ // shift out the bits:
+ shiftOut(dataPin, clockPin, SBFIRST, numberToDisplay);
+
+ //take the latch pin high so the LEDs will light up:
+ digitalWrite(latchPin, HIGH);
+ // Serial Debug
+ Serial.print(numberToDisplay);
+ Serial.print("\t");
+ Serial.println(numberToDisplay, BIN);
+ // pause before next value:
+ delay(200);
+ }
+}
+
+
+
+
--- /dev/null
+//**************************************************************//
+// Name : shiftOutCode, Hello World
+// Author : Carlyn Maw,Tom Igoe, David A. Mellis
+// Date : 25 Oct, 2006
+// Modified: 23 Mar 2010
+// Version : 2.0
+// Notes : Code for using a 74HC595 Shift Register
+//
+// : to count from 0 to 255
+//****************************************************************
+
+
+//Pin connected to ST_CP of 74HC595
+int latchPin = 8;
+//Pin connected to SH_CP of 74HC595
+int clockPin = 12;
+////Pin connected to DS of 74HC595
+int dataPin = 11;
+void setup() {
+ //set pins to output so you can control the shift register
+ pinMode(latchPin, OUTPUT);
+
+pinMode(clockPin, OUTPUT);
+pinMode(dataPin, OUTPUT);
+}
+void loop() {
+ // count from 0 to 255 and display the number
+ // on the LEDs
+ for (int numberToDisplay = 0; numberToDisplay < 256; numberToDisplay++) {
+ // take the latchPin low so
+ // the LEDs don’t change while you’re sending in bits:
+ digitalWrite(latchPin, LOW);
+ // shift out the bits:
+ shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);
+ //take the latch pin high so the LEDs will light up:
+ digitalWrite(latchPin, HIGH);
+ // pause before next value:
+ delay(500);
+ }
+}
+
+
+
--- /dev/null
+
+/*
+ Shift Register Example
+ Turning on the outputs of a 74HC595 using an array
+
+ Hardware:
+ * 74HC595 shift register
+ * LEDs attached to each of the outputs of the shift register
+
+ */
+//Pin connected to ST_CP of 74HC595
+int latchPin = 8;
+//Pin connected to SH_CP of 74HC595
+int clockPin = 12;
+////Pin connected to DS of 74HC595
+int dataPin = 11;
+
+//holders for infromation you're going to pass to shifting function
+byte data;
+byte dataArray[10];
+
+void setup() {
+ //set pins to output because they are addressed in the main loop
+ pinMode(latchPin, OUTPUT);
+ Serial.begin(9600);
+
+ //Arduino doesn't seem to have a way to write binary straight into the code
+ //so these values are in HEX. Decimal would have been fine, too.
+ dataArray[0] = 0xFF; //11111111
+ dataArray[1] = 0xFE; //11111110
+ dataArray[2] = 0xFC; //11111100
+ dataArray[3] = 0xF8; //11111000
+ dataArray[4] = 0xF0; //11110000
+ dataArray[5] = 0xE0; //11100000
+ dataArray[6] = 0xC0; //11000000
+ dataArray[7] = 0x80; //10000000
+ dataArray[8] = 0x00; //00000000
+ dataArray[9] = 0x38; //11100000
+
+ //function that blinks all the LEDs
+ //gets passed the number of blinks and the pause time
+ blinkAll_2Bytes(2,500);
+}
+
+void loop() {
+
+ for (int j = 0; j < 10; j++) {
+ //load the light sequence you want from array
+ data = dataArray[j];
+ //ground latchPin and hold low for as long as you are transmitting
+ digitalWrite(latchPin, 0);
+ //move 'em out
+ shiftOut(dataPin, clockPin, data);
+ //return the latch pin high to signal chip that it
+ //no longer needs to listen for information
+ digitalWrite(latchPin, 1);
+ delay(300);
+ }
+}
+
+
+
+// the heart of the program
+void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
+ // This shifts 8 bits out MSB first,
+ //on the rising edge of the clock,
+ //clock idles low
+
+ //internal function setup
+ int i=0;
+ int pinState;
+ pinMode(myClockPin, OUTPUT);
+ pinMode(myDataPin, OUTPUT);
+
+ //clear everything out just in case to
+ //prepare shift register for bit shifting
+ digitalWrite(myDataPin, 0);
+ digitalWrite(myClockPin, 0);
+
+ //for each bit in the byte myDataOut�
+ //NOTICE THAT WE ARE COUNTING DOWN in our for loop
+ //This means that %00000001 or "1" will go through such
+ //that it will be pin Q0 that lights.
+ for (i=7; i>=0; i--) {
+ digitalWrite(myClockPin, 0);
+
+ //if the value passed to myDataOut and a bitmask result
+ // true then... so if we are at i=6 and our value is
+ // %11010100 it would the code compares it to %01000000
+ // and proceeds to set pinState to 1.
+ if ( myDataOut & (1<<i) ) {
+ pinState= 1;
+ }
+ else {
+ pinState= 0;
+ }
+
+ //Sets the pin to HIGH or LOW depending on pinState
+ digitalWrite(myDataPin, pinState);
+ //register shifts bits on upstroke of clock pin
+ digitalWrite(myClockPin, 1);
+ //zero the data pin after shift to prevent bleed through
+ digitalWrite(myDataPin, 0);
+ }
+
+ //stop shifting
+ digitalWrite(myClockPin, 0);
+}
+
+
+//blinks the whole register based on the number of times you want to
+//blink "n" and the pause between them "d"
+//starts with a moment of darkness to make sure the first blink
+//has its full visual effect.
+void blinkAll_2Bytes(int n, int d) {
+ digitalWrite(latchPin, 0);
+ shiftOut(dataPin, clockPin, 0);
+ shiftOut(dataPin, clockPin, 0);
+ digitalWrite(latchPin, 1);
+ delay(200);
+ for (int x = 0; x < n; x++) {
+ digitalWrite(latchPin, 0);
+ shiftOut(dataPin, clockPin, 255);
+ shiftOut(dataPin, clockPin, 255);
+ digitalWrite(latchPin, 1);
+ delay(d);
+ digitalWrite(latchPin, 0);
+ shiftOut(dataPin, clockPin, 0);
+ shiftOut(dataPin, clockPin, 0);
+ digitalWrite(latchPin, 1);
+ delay(d);
+ }
+}
+
+
+
--- /dev/null
+/* SuperCar like pattern with a shift register.
+ Note: first bit/LED is supposed to be 0 and not 7
+ as in many arduino example sketches.
+
+ Turning on the outputs of a 74HC595 using an array
+
+ Hardware:
+ * 74HC595 shift register
+ * LEDs attached to each of the outputs of the shift register
+ */
+
+int clockPin = 12; //IC Pin 11, Yellow Jumper
+int dataPin = 11; //IC Pin 14, Blue Jumper
+int latchPin = 8; //IC Pin 12, Green Jumper
+
+byte patterns[30] = {
+ B00000001, 100,
+ B00000010, 100,
+ B00000100, 100,
+ B00001000, 100,
+ B00010000, 100,
+ B00100000, 100,
+ B01000000, 100,
+ B10000000, 100,
+ B01000000, 100,
+ B00100000, 100,
+ B00010000, 100,
+ B00001000, 100,
+ B00000100, 100,
+ B00000010, 100
+};
+
+int index = 0;
+int count = sizeof(patterns) / 2;
+
+void setup() {
+ pinMode(latchPin, OUTPUT);
+ pinMode(clockPin, OUTPUT);
+ pinMode(dataPin, OUTPUT);
+}
+
+void loop() {
+ digitalWrite(latchPin, LOW);
+ shiftOut(dataPin, clockPin, MSBFIRST, patterns[index * 2]);
+ digitalWrite(latchPin, HIGH);
+ delay(patterns[(index * 2) + 1]);
+ index++;
+ if (index >= count){
+ index = 0;
+ }
+}
+
--- /dev/null
+
+/*
+ Shift Register Example
+ Turning on the outputs of a 74HC595 using an array
+
+ Hardware:
+ * 74HC595 shift register
+ * LEDs attached to each of the outputs of the shift register
+
+ */
+//Pin connected to ST_CP of 74HC595
+int latchPin = 8;
+//Pin connected to SH_CP of 74HC595
+int clockPin = 12;
+////Pin connected to DS of 74HC595
+int dataPin = 11;
+
+//holders for infromation you're going to pass to shifting function
+byte data;
+byte dataArray[10];
+
+void setup() {
+ //set pins to output because they are addressed in the main loop
+ pinMode(latchPin, OUTPUT);
+ Serial.begin(9600);
+
+ //Arduino doesn't seem to have a way to write binary straight into the code
+ //so these values are in HEX. Decimal would have been fine, too.
+ dataArray[0] = 0xFF; //11111111
+ dataArray[1] = 0xFE; //11111110
+ dataArray[2] = 0xFC; //11111100
+ dataArray[3] = 0xF8; //11111000
+ dataArray[4] = 0xF0; //11110000
+ dataArray[5] = 0xE0; //11100000
+ dataArray[6] = 0xC0; //11000000
+ dataArray[7] = 0x80; //10000000
+ dataArray[8] = 0x00; //00000000
+ dataArray[9] = 0x38; //11100000
+
+ //function that blinks all the LEDs
+ //gets passed the number of blinks and the pause time
+ blinkAll_2Bytes(2,500);
+}
+
+void loop() {
+
+ for (int j = 0; j < 10; j++) {
+ //load the light sequence you want from array
+ data = dataArray[j];
+ //ground latchPin and hold low for as long as you are transmitting
+ digitalWrite(latchPin, 0);
+ //move 'em out
+ shiftOut(dataPin, clockPin, data);
+ //return the latch pin high to signal chip that it
+ //no longer needs to listen for information
+ digitalWrite(latchPin, 1);
+ delay(300);
+ }
+}
+
+
+
+// the heart of the program
+void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
+ // This shifts 8 bits out MSB first,
+ //on the rising edge of the clock,
+ //clock idles low
+
+ //internal function setup
+ int i=0;
+ int pinState;
+ pinMode(myClockPin, OUTPUT);
+ pinMode(myDataPin, OUTPUT);
+
+ //clear everything out just in case to
+ //prepare shift register for bit shifting
+ digitalWrite(myDataPin, 0);
+ digitalWrite(myClockPin, 0);
+
+ //for each bit in the byte myDataOut�
+ //NOTICE THAT WE ARE COUNTING DOWN in our for loop
+ //This means that %00000001 or "1" will go through such
+ //that it will be pin Q0 that lights.
+ for (i=7; i>=0; i--) {
+ digitalWrite(myClockPin, 0);
+
+ //if the value passed to myDataOut and a bitmask result
+ // true then... so if we are at i=6 and our value is
+ // %11010100 it would the code compares it to %01000000
+ // and proceeds to set pinState to 1.
+ if ( myDataOut & (1<<i) ) {
+ pinState= 1;
+ }
+ else {
+ pinState= 0;
+ }
+
+ //Sets the pin to HIGH or LOW depending on pinState
+ digitalWrite(myDataPin, pinState);
+ //register shifts bits on upstroke of clock pin
+ digitalWrite(myClockPin, 1);
+ //zero the data pin after shift to prevent bleed through
+ digitalWrite(myDataPin, 0);
+ }
+
+ //stop shifting
+ digitalWrite(myClockPin, 0);
+}
+
+
+//blinks the whole register based on the number of times you want to
+//blink "n" and the pause between them "d"
+//starts with a moment of darkness to make sure the first blink
+//has its full visual effect.
+void blinkAll_2Bytes(int n, int d) {
+ digitalWrite(latchPin, 0);
+ shiftOut(dataPin, clockPin, 0);
+ shiftOut(dataPin, clockPin, 0);
+ digitalWrite(latchPin, 1);
+ delay(200);
+ for (int x = 0; x < n; x++) {
+ digitalWrite(latchPin, 0);
+ shiftOut(dataPin, clockPin, 255);
+ shiftOut(dataPin, clockPin, 255);
+ digitalWrite(latchPin, 1);
+ delay(d);
+ digitalWrite(latchPin, 0);
+ shiftOut(dataPin, clockPin, 0);
+ shiftOut(dataPin, clockPin, 0);
+ digitalWrite(latchPin, 1);
+ delay(d);
+ }
+}
+
+
+
--- /dev/null
+/*
+ Shift Register Example
+ for 74HC595 shift register
+
+ This sketch turns reads serial input and uses it to set the pins
+ of a 74HC595 shift register.
+
+ Hardware:
+ * 74HC595 shift register attached to pins 2, 3, and 4 of the Arduino,
+ as detailed below.
+ * LEDs attached to each of the outputs of the shift register
+
+ Created 22 May 2009
+ Created 23 Mar 2010
+ by Tom Igoe
+
+ */
+
+//Pin connected to latch pin (ST_CP) of 74HC595
+const int latchPin = 8;
+//Pin connected to clock pin (SH_CP) of 74HC595
+const int clockPin = 12;
+////Pin connected to Data in (DS) of 74HC595
+const int dataPin = 11;
+
+void setup() {
+ //set pins to output because they are addressed in the main loop
+ pinMode(latchPin, OUTPUT);
+ pinMode(dataPin, OUTPUT);
+ pinMode(clockPin, OUTPUT);
+ Serial.begin(9600);
+ Serial.println("reset");
+}
+
+void loop() {
+ if (Serial.available() > 0) {
+ // ASCII '0' through '9' characters are
+ // represented by the values 48 through 57.
+ // so if the user types a number from 0 through 9 in ASCII,
+ // you can subtract 48 to get the actual value:
+ int bitToSet = Serial.read() - 48;
+
+ // write to the shift register with the correct bit set high:
+ registerWrite(bitToSet, HIGH);
+ }
+}
+
+// This method sends bits to the shift register:
+
+void registerWrite(int whichPin, int whichState) {
+// the bits you want to send
+ byte bitsToSend = 0;
+
+ // turn off the output so the pins don't light up
+ // while you're shifting bits:
+ digitalWrite(latchPin, LOW);
+
+ // turn on the next highest bit in bitsToSend:
+ bitWrite(bitsToSend, whichPin, whichState);
+
+ // shift the bits out:
+ shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);
+
+ // turn on the output so the LEDs can light up:
+ digitalWrite(latchPin, HIGH);
+ delay(300);
+
+}
+