Arduino experiments
Planned experiments:
- Hello world (blink that light)
- Running light
- Console
- Servo control
- analog input
- realtime clock
- communication, I2C bus
Hello world
blink LED on pin 13.
/* hello world */
int ledpin = 13;
void setup(){
pinMode(ledpin,OUTPUT);
}
void loop(){
digitalWrite(ledpin,LOW);
delay(500);
// off for 0.5 sec
digitalWrite(ledpin,HIGH);
delay(500);
// on for 0.5 sec
}
Running light
use LED board connected to pin 8,9,10,11,12,13 (six LEDs)
each LED will be on for 250 ms
/* running light */
int ledpin[] = {8,9,10,11,12,13};
void setup(){
int i;
for(i=0; i < 6; i++){
pinMode(ledpin[i],OUTPUT);
digitalWrite(ledpin[i],HIGH);
}
}
void loop(){
int i;
for(i=0; i < 6; i++){
digitalWrite(ledpin[i],LOW);
delay(250);
digitalWrite(ledpin[i],HIGH);
}
}
Push switch to toggle light
push switch (pin 2) to toggle LED pin 13
must debounce the switch signal
#define ledpin 13
#define switch 2
bool state = LOW;
int thisread;
int lastread = HIGH;
long debounce;
void setup(){
pinMode(switch, INPUT);
pinMode(ledpin, OUTPUT);
}
void loop(){
do{
thisread = digitalRead(switch);
if( thisread == lastread) debounce = millis();
} while ( (millis() - debounce) < 50 ); // debounce
period 50 ms
if( thisread == LOW && lastread == HIGH){ // switch
is pushed
digitalWrite(ledpin,state);
state = !state;
// toggle state
}
lastread = thisread ;
// update switch state
}
last update 1 Apr 2018 (no, this is definitely no an April fool)
Wiggle a servo
control position of a servo
use the library ET_SERVO (download
here) unzip and put it in arduino/libraries
#include <ET_SERVO.h>
ET_SERVO servo1; // create a servo object
void setup(){
servo1.attach(9,1000,2000); // control at pin 9
}
void loop(){
servo1.updateDutyCycle(1000); // pulse width 1ms
delay(1000);
// wait one second
servo1.updateDutyCycle(1500); // pulse width 1.5ms
delay(1000);
}
last update 28 Apr 2019 (end of lecture)