Workshops/Arduino for beginners 2/Code

From London Hackspace Wiki

Arduino Workshop

London Hackspace

22nd/23rd January 2011

Mike McRoberts

LED Flasher

// Project 1 - LED Flasher

int ledPin = 10;

void setup() {
	 pinMode(ledPin, OUTPUT);
}

void loop() {
	digitalWrite(ledPin, HIGH);
	delay(1000);
	digitalWrite(ledPin, LOW);
	delay(1000);
}

Interactive Traffic Lights

// Project 2 - Interactive Traffic Lights

int carRed = 12; // assign the car lights
int carYellow = 11;
int carGreen = 10;
int pedRed = 9; // assign the pedestrian lights
int pedGreen = 8;
int button = 2; // button pin
int crossTime = 5000; // time alloyoud to cross
unsigned long changeTime; // time since button pressed

void setup() {
        pinMode(carRed, OUTPUT);
        pinMode(carYellow, OUTPUT);
        pinMode(carGreen, OUTPUT);
        pinMode(pedRed, OUTPUT);
        pinMode(pedGreen, OUTPUT);
        pinMode(button, INPUT); // button on pin 2
        // turn on the green light
        digitalWrite(carGreen, HIGH); 
        digitalWrite(pedRed, HIGH);
}

void loop() {
        int state = digitalRead(button);
        /* check if button is pressed and it is over 5 seconds since last button press */
        if (state == HIGH && (millis() - changeTime) > 5000) {
                // Call the function to change the lights
                changeLights();
        }
}


void changeLights() {
        digitalWrite(carGreen, LOW); // green off
        digitalWrite(carYellow, HIGH); // yellow on
        delay(2000); // wait 2 seconds
  
        digitalWrite(carYellow, LOW); // yellow off
        digitalWrite(carRed, HIGH); // red on
        delay(1000); // wait 1 second till its safe
  
        digitalWrite(pedRed, LOW); // ped red off
        digitalWrite(pedGreen, HIGH); // ped green on
        delay(crossTime); // wait for preset time period
    // flash the ped green
        for (int x=0; x<10; x++) {
                digitalWrite(pedGreen, HIGH);
                delay(250);
                digitalWrite(pedGreen, LOW);
                delay(250);
        }
        // turn ped red on
        digitalWrite(pedRed, HIGH);
        delay(500);
  
        digitalWrite(carYellow, HIGH); // yellow on
        digitalWrite(carRed, LOW); // red off
        delay(1000);
        digitalWrite(carGreen, HIGH);
        digitalWrite(carYellow, LOW); // yellow off 
  
        // record the time since last change of lights
        changeTime = millis();
        // then return to the main program loop
}

LED chaser

// Project 3

byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13};    // Create array for LED pins
int ledDelay; // delay between changes
int direction = 1;
int currentLED = 0;
unsigned long changeTime;
int potPin = 2;    // select the input pin for the potentiometer

void setup() {
for (int x=0; x<10; x++) {   // set all pins to output
    		pinMode(ledPin[x], OUTPUT); }
    	changeTime = millis();
}

void loop() {
ledDelay = analogRead(potPin); // read the value from the pot 
	if ((millis() - changeTime) > ledDelay) {      // if it has been ledDelay ms since
                                                          last change
    		changeLED();
   		changeTime = millis();
  	}
}

void changeLED() {
    	for (int x=0; x<10; x++) {   // turn off all LED's
    		digitalWrite(ledPin[x], LOW);
  	}
    	digitalWrite(ledPin[currentLED], HIGH); // turn on the current LED
        currentLED += direction; // increment by the direction value
  	// change direction if we reach the end
 	if (currentLED == 9) {direction = -1;}
  	if (currentLED == 0) {direction = 1;}
}

Mood Lamp

// Project 4 - Mood Lamp
float RGB1[3];
float RGB2[3];
float INC[3];

int red, green, blue;

int RedPin = 11;
int GreenPin = 10;
int BluePin = 9;

void setup() 
{ 
  	randomSeed(analogRead(0));
  
  	RGB1[0] = 0;
  	RGB1[1] = 0;
  	RGB1[2] = 0;
  
  	RGB2[0] = random(256);
  	RGB2[1] = random(256);
  	RGB2[2] = random(256);  
} 
 
void loop() 
{ 
  	randomSeed(analogRead(0));
  
  	for (int x=0; x<3; x++) {
    		INC[x] = (RGB1[x] - RGB2[x]) / 256; } 
  
  	for (int x=0; x<256; x++) {
    		red = int(RGB1[0]);
    		green = int(RGB1[1]);
    		blue = int(RGB1[2]);

    		analogWrite (RedPin, red);  
    		analogWrite (GreenPin, green);   
    		analogWrite (BluePin, blue);     
   		delay(100);   
    
    		RGB1[0] -= INC[0];
    		RGB1[1] -= INC[1];    
    		RGB1[2] -= INC[2];    
  	}
		for (int x=0; x<3; x++) {
  		RGB2[x] = random(556)-300;
  		RGB2[x] = constrain(RGB2[x], 0, 255); 
  		delay(1000);
        }
}

Serial controlled mood lamp

// Project 5 - Serial controlled mood lamp
char buffer[18];
int red, green, blue;

int RedPin = 11;
int GreenPin = 10;
int BluePin = 9;

void setup() 
{ 
  	Serial.begin(9600);
  	Serial.flush();
  	pinMode(RedPin, OUTPUT);
  	pinMode(GreenPin, OUTPUT);
  	pinMode(BluePin, OUTPUT);
} 

void loop() 
{ 
  	if (Serial.available() > 0) {
    		int index=0;
    		delay(100); // let the buffer fill up
    		int numChar = Serial.available();
    		if (numChar>15) {
      			numChar=15;
   		 }
    		while (numChar--) {
      			buffer[index++] = Serial.read();
    		}
    		splitString(buffer);
  	}
}

void splitString(char* data) {
  	Serial.print("Data entered: ");
  	Serial.println(data);
  	char* parameter; 
	parameter = strtok (data, " ,");
  	while (parameter != NULL) {
    		setLED(parameter);
    		parameter = strtok (NULL, " ,");
}

 	 // Clear the text and serial buffers
  	for (int x=0; x<16; x++) {
    		buffer[x]='\0';
 	 }
  	Serial.flush();
}

void setLED(char* data) {
  	if ((data[0] == 'r') || (data[0] == 'R')) {
    		int Ans = strtol(data+1, NULL, 10);
    		Ans = constrain(Ans,0,255);
    		analogWrite(RedPin, Ans);
    		Serial.print("Red is set to: ");
    		Serial.println(Ans);
  	}
  	if ((data[0] == 'g') || (data[0] == 'G')) {
    		int Ans = strtol(data+1, NULL, 10);
    		Ans = constrain(Ans,0,255);
    		analogWrite(GreenPin, Ans);
    		Serial.print("Green is set to: ");
    		Serial.println(Ans);
  	}
  	if ((data[0] == 'b') || (data[0] == 'B')) {
    		int Ans = strtol(data+1, NULL, 10);
    		Ans = constrain(Ans,0,255);
    		analogWrite(BluePin, Ans);
    		Serial.print("Blue is set to: ");
    		Serial.println(Ans);
  	}
}

Piezo Sounder Alarm

// Project 6 - Piezo Sounder Alarm

float sinVal;
int toneVal;

void setup() {
        pinMode(8, OUTPUT);
}

void loop() {
        for (int x=0; x<180; x++) {
                // convert degrees to radians then obtain sin value
                sinVal = (sin(x*(3.1412/180)));
                // generate a frequency from the sin value
                toneVal = 2000+(int(sinVal*1000));
                tone(8, toneVal);
                delay(2);
        }
}

Light Sensor


// Project 7 - Light Sensor

int piezoPin = 8;  // Piezo on Pin 8
int ldrPin = 0;   // LDR on Analog Pin 0
int ldrValue = 0;  // Value read from the LDR

void setup() {
  // nothing to do here
}
void loop() {
        ldrValue = analogRead(ldrPin); // read the value from the LDR
        tone(piezoPin,1000); // play a 1000Hz tone from the piezo
        delay(25);  // wait a bit
        noTone(piezoPin);  // stop the tone
        delay(ldrValue); // wait the amount of milliseconds in ldrValue
}

Thermometer

// Project 8 - Thermometer

#define sensorPin 0

float Celsius, Fahrenheit, Kelvin;
int sensorValue;

void setup() {
Serial.begin(9600);
Serial.println("Initialising.....");
}

void loop() {

  GetTemp();  
  Serial.print("Celsius: ");
  Serial.println(Celsius);
  Serial.print("Fahrenheit: ");
  Serial.println(Fahrenheit);
  Serial.println();

  delay(2000);
}

void GetTemp()
{
  sensorValue = analogRead(sensorPin); // read the sensor
  Kelvin = (((float(sensorValue) / 1023) * 5) * 100); // convert to Kelvin
  Celsius = Kelvin - 273.15; // convert to Celsius
  Fahrenheit = (Celsius * 1.8) +32;  // convert to Fahrenheit
}

Binary counter using a shift register

// Project 9 - Binary counter using a shift register

int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch)
int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock)
int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data)
void setup() {
        //set pins to output 
        pinMode(latchPin, OUTPUT);
        pinMode(clockPin, OUTPUT);
        pinMode(dataPin, OUTPUT);
}

void loop() {
        //count from 0 to 255
        for (int i = 0; i < 256; i++) {
                //set latchPin low to allow data flow
                digitalWrite(latchPin, LOW);
                shiftIt(i);   
                //set latchPin to high to lock and send data
                digitalWrite(latchPin, HIGH);
                delay(1000);
        }
}

void shiftIt(byte dataOut) {
        // Shift out 8 bits LSB first, on rising edge of clock
        boolean pinState;
        digitalWrite(dataPin, LOW); //clear shift register ready for sending data
        digitalWrite(clockPin, LOW);
  
        for (int i=0; i<=7; i++)  { // for each bit in dataOut send out a bit
                digitalWrite(clockPin, LOW); //set clockPin to LOW prior to sending bit

                // if the value of DataOut and (logical AND) a bitmask 
                // are true, set pinState to 1 (HIGH)
                if ( dataOut & (1<<i) ) {
                        pinState = HIGH;
                }
                else {
                        pinState = LOW;
                }

                //sets dataPin to HIGH or LOW depending on pinState
                digitalWrite(dataPin, pinState); //send bit out on rising edge of clock 
                digitalWrite(clockPin, HIGH);
        }
        digitalWrite(clockPin, LOW); //stop shifting out data
}

LED dot matrix

// Project 10
#include <TimerOne.h>

int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch)
int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock)
int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data)

byte led[8];  // 8 element unsigned integer array to store the sprite

void setup() {
        pinMode(latchPin, OUTPUT);  // set the 3 digital pins to outputs
        pinMode(clockPin, OUTPUT);
        pinMode(dataPin, OUTPUT);
        led[0] = B11111111;  // enter the binary representation of the image
        led[1] = B10000001;  // into the array
        led[2] = B10111101;
        led[3] = B10100101;
        led[4] = B10100101;
        led[5] = B10111101;
        led[6] = B10000001;
        led[7] = B11111111;
        // set a timer of length 10000 microseconds (1/100th of a second)
        Timer1.initialize(10000); 
        // attach the screenUpdate function to the interrupt timer
        Timer1.attachInterrupt(screenUpdate); 
}

void loop() {
        for (int i=0; i<8; i++) {
                led[i]= ~led[i]; // invert each row of the binary image
        }
        delay(500);
}

void screenUpdate() { // function to display image
        byte row = B10000000; // row 1
        for (byte k = 0; k < 9; k++) {
                digitalWrite(latchPin, LOW); // open latch ready to receive data
        shiftIt(~led[k] ); // shift out the LED array (inverted)
        shiftIt(row ); // shift out row binary number 

        // Close the latch, sending the data in the registers out to the matrix
        digitalWrite(latchPin, HIGH);     
        row = row >> 1; // bitshift right
        }
}

void shiftIt(byte dataOut) {    // Shift out 8 bits LSB first, on rising edge of clock

        boolean pinState; 
        digitalWrite(dataPin, LOW); //clear shift register read for sending data

        for (int i=0; i<8; i++)  {    // for each bit in dataOut send out a bit
                digitalWrite(clockPin, LOW); //set clockPin to LOW prior to sending bit

                // if the value of DataOut and (logical AND) a bitmask
                // are true, set pinState to 1 (HIGH)
                if ( dataOut & (1<<i) ) {
                        pinState = HIGH;
                }
                else {
                        pinState = LOW;
                }
                //sets dataPin to HIGH or LOW depending on pinState
                digitalWrite(dataPin, pinState); 
                digitalWrite(clockPin, HIGH); //send bit out on rising edge of clock 
                digitalWrite(dataPin, LOW);
        }
digitalWrite(clockPin, LOW); //stop shifting
}

Animated LED dot matrix


// Project 11
#include <TimerOne.h>

int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch)
int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock)
int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data)
byte frame = 0;  // variable to store the current frame being displayed

byte led[8][8] = { {0, 56, 92, 158, 158, 130, 68, 56}, // 8 frames of an animation
                      {0, 56, 124, 186, 146, 130, 68, 56},
                      {0, 56, 116, 242, 242, 130, 68, 56},
                      {0, 56, 68, 226, 242, 226, 68, 56},
                      {0, 56, 68, 130, 242, 242, 116, 56},
                      {0, 56, 68, 130, 146, 186, 124, 56},
                      {0, 56, 68, 130, 158, 158, 92, 56},
                      {0, 56, 68, 142, 158, 142, 68, 56} };

void setup() {
        pinMode(latchPin, OUTPUT);  // set the 3 digital pins to outputs
        pinMode(clockPin, OUTPUT);
        pinMode(dataPin, OUTPUT);

        Timer1.initialize(10000); // set a timer of length 10000 microseconds 
        Timer1.attachInterrupt(screenUpdate); // attach the screenUpdate function
}

void loop() {
        for (int i=0; i<8; i++) { // loop through all 8 frames of the animation
                for (int j=0; j<8; j++) { // loop through the 8 rows per frame
                        led[i][j]= led[i][j] << 1 | led[i][j] >> 7; // bitwise rotation
                }
        }
        frame++; // go to the next frame in the animation
        if (frame>7) { frame =0;} // make sure we go back to frame 0 once past 7
        delay(100); // wait a bit between frames
}

void screenUpdate() { // function to display image
        byte row = B10000000; // row 1
        for (byte k = 0; k < 9; k++) {
                digitalWrite(latchPin, LOW); // open latch ready to receive data

                shiftIt(~led[frame][k] ); // LED array (inverted)
                shiftIt(row); // row binary number

                // Close the latch, sending the data in the registers out to the matrix
                digitalWrite(latchPin, HIGH);
                row = row >> 1; // bitshift right
        }
}

void shiftIt(byte dataOut) {
        // Shift out 8 bits LSB first, on rising edge of clock

        boolean pinState; 
        //clear shift register read for sending data
        digitalWrite(dataPin, LOW);

        // for each bit in dataOut send out a bit
        for (int i=0; i<8; i++)  {
                //set clockPin to LOW prior to sending bit
                digitalWrite(clockPin, LOW);

                // if the value of DataOut and (logical AND) a bitmask
                // are true, set pinState to 1 (HIGH)
                if ( dataOut & (1<<i) ) {
                        pinState = HIGH;
                }
                else {
                        pinState = LOW;
                }

                //sets dataPin to HIGH or LOW depending on pinState
                digitalWrite(dataPin, pinState);
                //send bit out on rising edge of clock 
                digitalWrite(clockPin, HIGH);
                digitalWrite(dataPin, LOW);
        }

digitalWrite(clockPin, LOW); //stop shifting
}