Jump to: navigation, search

Εργαστήριο Arduino - Αρχάριους

Εργαστήριο Arduino - Αρχάριους

Γιατί πεινασμένο Arduino δεν ανάβει...

Περιγραφή[edit]

Στο εργαστήριο αυτό μαθαίνουμε πως να χρησιμοποιούμε το Arduino και να φτιάχνουμε απλές εφαρμογές με αυτό. Το εργαστήριο απευθύνεται σε άτομα με ελάχιστο υπόβαθρο ηλεκτρονικών. Καλό θα ήταν να οι παρευρισκόμενοι να έχουν βασικές γνώσεις προγραμματισμού χωρίς να το κάνει απαγορευτικό αν δεν υπάρχουν.

Πρόγραμμα εργαστηρίου[edit]

Η ροή του εργαστηρίου είναι:

  • Προβολή της ομιλίας του Massimo Banzi στο TEDtalk [1]
  • Σύντομη εισαγωγή παρουσίαση από τον ομιλητή.
    • Σύντομη περιγραφή της ιστορίας και της ιδεολογίας του Arduino
    • Περιγραφή του Arduino Hardware (UNO, mega, ATmega)
    • Περιγραφή του Arduino Software (IDE, language, libraries)
  • Παραδείγματα μαζί με τους παρευρισκόμενους
    • Blink: Το απλούστερο παράδειγμα για να γνωρίσουμε την διαδικασία προγραμματισμού
    • Blink x2: Προσθέτουμε ένα δεύτερο LEDακι ώστε να γνωρίσουμε πως πειράζουμε την πλακέτα καθώς και τον κώδικα.
    • DigitalRead: Χρησιμοποιούμε τα pin του Arduino για είσοδο και το κάνουμε να αντιδρά. Επίσης μαθαίνουμε για την σειριακή και κάποιες επιπλέον απαραίτητες γνώσεις ηλεκτρονικών (floating current)
    • AnalogRead: Χρησιμοποιούμε τον ροοστάτη που έχουμε πάνω στην πλακέτα και μαθαίνουμε πως να διαβάζουμε αναλογικές τιμές.
    • ToneMelody: Παίζουμε μία μελωδία με το ηχείο.
    • TonePitchFollower: Αλλάζουμε τον τόνο βάση της τιμής του ροοστάτη.
  • Προβολή κάποιον επιπλέον αισθητήρων καθώς και ενός servo από τον ομιλητή.

Παραδείγματα[edit]

Παραδείγματα χρήσης arduino

Blink[edit]

 /*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.
 
  This example code is in the public domain.
 */
  
 // Pin 13 has an LED connected on most Arduino boards.
 // give it a name:
 int led = 13;
 
 // 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() {
  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
 }


DigitalReadSerial[edit]

  /*
  DigitalReadSerial
 Reads a digital input on pin 2, prints the result to the serial monitor 
  
 This example code is in the public domain.
  */
  
 // digital pin 2 has a pushbutton attached to it. Give it a name:
 int pushButton = 2;
 
 // the setup routine runs once when you press reset:
 void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
 }
  
 // the loop routine runs over and over again forever:
 void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(1);        // delay in between reads for stability
 }

AnalogReadSerial[edit]

 /*
  AnalogReadSerial
  Reads an analog input on pin 0, prints the result to the serial monitor.
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
  
 This example code is in the public domain.
 */
 
 // the setup routine runs once when you press reset:
 void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
 }
 
 // the loop routine runs over and over again forever:
 void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
 }

Melody[edit]

 /*
  Melody
  
  Plays a melody 
  
  circuit:
  * 8-ohm speaker on digital pin 8
  
  created 21 Jan 2010
  modified 30 Aug 2011
  by Tom Igoe
  modified 20 Apr 2013
  by Jann Eike  Kruse
 
  This example code is in the public domain.
  
  http://arduino.cc/en/Tutorial/Tone
  
 */
  
 #include "pitches.h"
 
 // notes in the melody:
 int melody[] = {
  NOTE_C5, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_G4, 0, NOTE_B4, NOTE_C5};
 
 // note durations: 4 = quarter note, 8 = eighth note, etc.:
 int noteDurations[] = {
  4, 8, 8, 4,4,4,4,4 };
 
 void setup() {
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < 8; 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/noteDurations[thisNote];
    tone(8, 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.50;
    delay(pauseBetweenNotes);
    // stop the tone playing:
    noTone(8);
  }
 }
 
 void loop() {
  // no need to repeat the melody.
 }

 /*
  Melody
  
  Plays a melody 
  
  circuit:
  * 8-ohm speaker on digital pin 8
  
  created 21 Jan 2010
  modified 30 Aug 2011
  by Tom Igoe
  modified 20 Apr 2013
  by Jann Eike  Kruse
 
  This example code is in the public domain.
  
  http://arduino.cc/en/Tutorial/Tone
  
 */
  
 #include "pitches.h"
 
 // notes in the melody:
 int melody[] = {
NOTE_C4, NOTE_CS4, NOTE_D4, NOTE_DS4, NOTE_E4, NOTE_F4, NOTE_FS4, NOTE_G4, NOTE_GS4, NOTE_A4, NOTE_AS4, NOTE_B4,
NOTE_C5, NOTE_CS5, NOTE_D5, NOTE_DS5, NOTE_E5, NOTE_F5, NOTE_FS5, NOTE_G5, NOTE_GS5, NOTE_A5, NOTE_AS5, NOTE_B5,
NOTE_C6, NOTE_CS6, NOTE_D6, NOTE_DS6, NOTE_E6, NOTE_F6, NOTE_FS6, NOTE_G6, NOTE_GS6, NOTE_A6, NOTE_AS6, NOTE_B6,
NOTE_C7, NOTE_CS7, NOTE_D7, NOTE_DS7, NOTE_E7, NOTE_F7, NOTE_FS7, NOTE_G7, NOTE_GS7, NOTE_A7, NOTE_AS7, NOTE_B7}; 
 // note durations: 4 = quarter note, 8 = eighth note, etc.:
 int noteDurations[] = {
  4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4 };
 
 void setup() {
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < 8; 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/noteDurations[thisNote];
    tone(8, 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.50;
    delay(pauseBetweenNotes);
    // stop the tone playing:
    noTone(8);
  }
 }
 
 void loop() {
  // no need to repeat the melody.
 }

Servo Knob[edit]

 // Controlling a servo position using a potentiometer (variable resistor) 
 // by Michal Rinott <http://people.interaction-ivrea.it/m.rinott> 
 
 #include <Servo.h> 
  
 Servo myservo;  // create servo object to control a servo 
  
 int potpin = 0;  // analog pin used to connect the potentiometer
 int val;    // variable to read the value from the analog pin 
  
 void setup() 
 { 
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object 
 } 
  
 void loop() 
 { 
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023) 
  val = map(val, 0, 1023, 0, 179);     // scale it to use it with the servo (value between 0 and 180) 
  myservo.write(val);                  // sets the servo position according to the scaled value 
  delay(15);                           // waits for the servo to get there 
 } 

Knock test[edit]

 /* Knock Sensor
  
   This sketch reads a piezo element to detect a knocking sound. 
   It reads an analog pin and compares the result to a set threshold. 
   If the result is greater than the threshold, it writes
   "knock" to the serial port, and toggles the LED on pin 13.
  
   The circuit:
        * + connection of the piezo attached to analog in 1
        * - connection of the piezo attached to ground
        * 1-megohm resistor attached from analog in 1 to ground
 
   Previously on http://www.arduino.cc/en/Tutorial/Knock
   
   created 25 Mar 2007
   by David Cuartielles <http://www.0j0.org>
   modified 30 Aug 2011
   by Tom Igoe
   modified 20 Apr 2013
   by Jann Eike  Kruse
   
   This example code is in the public domain.
 
 */
 
 
 // these constants won't change:
 const int ledPin = 13;      // led connected to digital pin 13
 const int knockSensor = A1; // the piezo is connected to analog pin 1
 const int threshold = 300;  // threshold value to decide when the detected sound is a knock or not
 
 
 // these variables will change:
 int sensorReading = 0;      // variable to store the value read from the sensor pin
 int ledState = LOW;         // variable used to store the last LED status, to toggle the light
 
 void setup() {
  pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
  Serial.begin(9600);       // use the serial port
 }
 
 void loop() {
  // read the sensor and store it in the variable sensorReading:
  sensorReading = analogRead(knockSensor);    
  
  // if the sensor reading is greater than the threshold:
  if (sensorReading >= threshold) {
    // toggle the status of the ledPin:
    ledState = !ledState;   
    // update the LED pin itself:        
    digitalWrite(ledPin, ledState);
    // send the string "Knock!" back to the computer, followed by newline
    Serial.println("Knock!");         
    delay(200);  // delay to avoid overloading the serial port buffer
  }
  Serial.println(sensorReading);         
 }

Knock Lock[edit]

/* Detects patterns of knocks and triggers a motor to unlock
  it if the pattern is correct.
  
  By Steve Hoefer http://grathio.com
  Version 0.1.10.20.10
  Licensed under Creative Commons Attribution-Noncommercial-Share Alike 3.0
  http://creativecommons.org/licenses/by-nc-sa/3.0/us/
  (In short: Do what you want, just be sure to include this line and the four above it, and don't sell it or use it in anything you sell without contacting me.)
  
  Analog Pin 0: Piezo speaker (connected to ground with 1M pulldown resistor)
  Digital Pin 2: Switch to enter a new code.  Short this to enter programming mode.
  Digital Pin 3: DC gear reduction motor attached to the lock. (Or a motor controller or a solenoid or other unlocking mechanisim.)
  Digital Pin 4: Red LED. 
  Digital Pin 5: Green LED. 
  
  Update: Nov 09 09: Fixed red/green LED error in the comments. Code is unchanged. 
  Update: Nov 20 09: Updated handling of programming button to make it more intuitive, give better feedback.
  Update: Jan 20 10: Removed the "pinMode(knockSensor, OUTPUT);" line since it makes no sense and doesn't do anything.
  Update: Jun 1 12: Added pull-up resistor on programming switch
*/
 
// Pin definitions
const int knockSensor = A1;         // Piezo sensor on pin 0.
const int programSwitch = 2;       // If this is high we program a new code.
const int lockMotor = 13;          // Gear motor used to turn the lock.
const int redLED = 8;              // Status LED
const int greenLED = 13;            // Status LED
 
// Tuning constants.  Could be made vars and hoooked to potentiometers for soft configuration, etc.
const int threshold = 250;         // Minimum signal from the piezo to register as a knock
const int rejectValue = 25;        // If an individual knock is off by this percentage of a knock we don't unlock..
const int averageRejectValue = 15; // If the average timing of the knocks is off by this percent we don't unlock.
const int knockFadeTime = 250;     // milliseconds we allow a knock to fade before we listen for another one. (Debounce timer.)
const int lockTurnTime = 1000;      // milliseconds that we run the motor to get it to go a half turn.

const int maximumKnocks = 20;       // Maximum number of knocks to listen for.
const int knockComplete = 1200;     // Longest time to wait for a knock before we assume that it's finished.


// Variables.
int secretCode[maximumKnocks] = {50, 25, 25, 50, 100, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};  // Initial setup: "Shave and a Hair Cut, two bits."
int knockReadings[maximumKnocks];   // When someone knocks this array fills with delays between knocks.
int knockSensorValue = 0;           // Last reading of the knock sensor.
int programButtonPressed = false;   // Flag so we remember the programming button setting at the end of the cycle.

void setup() {
 pinMode(lockMotor, OUTPUT);
 pinMode(redLED, OUTPUT);
 pinMode(greenLED, OUTPUT);
 pinMode(programSwitch, INPUT_PULLUP);

 
 Serial.begin(9600);               			// Uncomment the Serial.bla lines for debugging.
 Serial.println("Program start.");  			// but feel free to comment them out after it's working right.
 
 digitalWrite(greenLED, HIGH);      // Green LED on, everything is go.
}

void loop() {
 // Listen for any knock at all.
 knockSensorValue = analogRead(knockSensor);
 
 if (digitalRead(programSwitch)==LOW){  // is the program button pressed?
   programButtonPressed = true;          // Yes, so lets save that state
   digitalWrite(redLED, HIGH);           // and turn on the red light too so we know we're programming.
 } else {
   programButtonPressed = false;
   digitalWrite(redLED, LOW);
 }
 
 if (knockSensorValue >=threshold){
   listenToSecretKnock();
 }
} 

// Records the timing of knocks.
void listenToSecretKnock(){
 Serial.println("knock starting");   

 int i = 0;
 // First lets reset the listening array.
 for (i=0;i<maximumKnocks;i++){
   knockReadings[i]=0;
 }
 
 int currentKnockNumber=0;         			// Incrementer for the array.
 int startTime=millis();           			// Reference for when this knock started.
 int now=millis();
 
 digitalWrite(greenLED, LOW);      			// we blink the LED for a bit as a visual indicator of the knock.
 if (programButtonPressed==true){
    digitalWrite(redLED, LOW);                         // and the red one too if we're programming a new knock.
 }
 delay(knockFadeTime);                       	        // wait for this peak to fade before we listen to the next one.
 digitalWrite(greenLED, HIGH);  
 if (programButtonPressed==true){
    digitalWrite(redLED, HIGH);                        
 }
 do {
   //listen for the next knock or wait for it to timeout. 
   knockSensorValue = analogRead(knockSensor);
   if (knockSensorValue >=threshold){                   //got another knock...
     //record the delay time.
     Serial.println(knockSensorValue);
     now=millis();
     knockReadings[currentKnockNumber] = now-startTime;
     currentKnockNumber ++;                             //increment the counter
     startTime=now;          
     // and reset our timer for the next knock
     digitalWrite(greenLED, LOW);  
     if (programButtonPressed==true){
       digitalWrite(redLED, LOW);                       // and the red one too if we're programming a new knock.
     }
     delay(knockFadeTime);                              // again, a little delay to let the knock decay.
     digitalWrite(greenLED, HIGH);
     if (programButtonPressed==true){
       digitalWrite(redLED, HIGH);                         
     }
   }

   now=millis();
   
   //did we timeout or run out of knocks?
 } while ((now-startTime < knockComplete) && (currentKnockNumber < maximumKnocks));
 
 //we've got our knock recorded, lets see if it's valid
 if (programButtonPressed==false){             // only if we're not in progrmaing mode.
   if (validateKnock() == true){
     triggerDoorUnlock(); 
   } else {
     Serial.println("Secret knock failed.");
     digitalWrite(greenLED, LOW);  		// We didn't unlock, so blink the red LED as visual feedback.
     for (i=0;i<4;i++){					
       digitalWrite(redLED, HIGH);
       delay(100);
       digitalWrite(redLED, LOW);
       delay(100);
     }
     digitalWrite(greenLED, HIGH);
   }
 } else { // if we're in programming mode we still validate the lock, we just don't do anything with the lock
   validateKnock();
   // and we blink the green and red alternately to show that program is complete.
   Serial.println("New lock stored.");
   digitalWrite(redLED, LOW);
   digitalWrite(greenLED, HIGH);
   for (i=0;i<3;i++){
     delay(100);
     digitalWrite(redLED, HIGH);
     digitalWrite(greenLED, LOW);
     delay(100);
     digitalWrite(redLED, LOW);
     digitalWrite(greenLED, HIGH);      
   }
 }
}


// Runs the motor (or whatever) to unlock the door.
void triggerDoorUnlock(){
 Serial.println("Door unlocked!");
 int i=0;
 
 // turn the motor on for a bit.
 digitalWrite(lockMotor, HIGH);
 digitalWrite(greenLED, HIGH);            // And the green LED too.
 
 delay (lockTurnTime);                    // Wait a bit.
 
 digitalWrite(lockMotor, LOW);            // Turn the motor off.
 
 // Blink the green LED a few times for more visual feedback.
 for (i=0; i < 5; i++){   
     digitalWrite(greenLED, LOW);
     delay(100);
     digitalWrite(greenLED, HIGH);
     delay(100);
 }
  
}

// Sees if our knock matches the secret.
// returns true if it's a good knock, false if it's not.
// todo: break it into smaller functions for readability.
boolean validateKnock(){
 int i=0;

 // simplest check first: Did we get the right number of knocks?
 int currentKnockCount = 0;
 int secretKnockCount = 0;
 int maxKnockInterval = 0;          			// We use this later to normalize the times.
 
 for (i=0;i<maximumKnocks;i++){
   if (knockReadings[i] > 0){
     currentKnockCount++;
   }
   if (secretCode[i] > 0){  					//todo: precalculate this.
     secretKnockCount++;
   }
   
   if (knockReadings[i] > maxKnockInterval){ 	// collect normalization data while we're looping.
     maxKnockInterval = knockReadings[i];
   }
 }
 
 // If we're recording a new knock, save the info and get out of here.
 if (programButtonPressed==true){
     for (i=0;i<maximumKnocks;i++){ // normalize the times
       secretCode[i]= map(knockReadings[i],0, maxKnockInterval, 0, 100); 
     }
     // And flash the lights in the recorded pattern to let us know it's been programmed.
     digitalWrite(greenLED, LOW);
     digitalWrite(redLED, LOW);
     delay(1000);
     digitalWrite(greenLED, HIGH);
     digitalWrite(redLED, HIGH);
     delay(50);
     for (i = 0; i < maximumKnocks ; i++){
       digitalWrite(greenLED, LOW);
       digitalWrite(redLED, LOW);  
       // only turn it on if there's a delay
       if (secretCode[i] > 0){                                   
         delay( map(secretCode[i],0, 100, 0, maxKnockInterval)); // Expand the time back out to what it was.  Roughly. 
         digitalWrite(greenLED, HIGH);
         digitalWrite(redLED, HIGH);
       }
       delay(50);
     }
          return false; 	// We don't unlock the door when we are recording a new knock.
 }
 
 if (currentKnockCount != secretKnockCount){
   return false; 
 }
 
 /*  Now we compare the relative intervals of our knocks, not the absolute time between them.
     (ie: if you do the same pattern slow or fast it should still open the door.)
     This makes it less picky, which while making it less secure can also make it
     less of a pain to use if you're tempo is a little slow or fast. 
 */
 int totaltimeDifferences=0;
 int timeDiff=0;
 for (i=0;i<maximumKnocks;i++){ // Normalize the times
   knockReadings[i]= map(knockReadings[i],0, maxKnockInterval, 0, 100);      
   timeDiff = abs(knockReadings[i]-secretCode[i]);
   if (timeDiff > rejectValue){ // Individual value too far out of whack
     return false;
   }
   totaltimeDifferences += timeDiff;
 }
 // It can also fail if the whole thing is too inaccurate.
 if (totaltimeDifferences/secretKnockCount>averageRejectValue){
   return false; 
 }
 
 return true;
 
}

Παρατηρήσεις από το τελευταίο εργαστήριο[edit]

  • Να ανεβάσουμε τους drivers του USB2Serial
  • Να προσθέσουμε μια επεξήγηση για τις breadboard

Αναφορές[edit]

http://learn.adafruit.com/system/assets/assets/000/002/083/medium800/project_3_on_breadboard.jpg?1349167048

https://files.commonsfest.gkiagia.name/public.php?service=files&t=c89879c1eb51243b03b0c8ac6b0e9141

http://osfestival.enallaktika.gr/wiki/index.php/Arduino_Workshop


Περισσότερα παραδείγματα[edit]