Friday, February 1, 2008

PhysComp Lab 2 - The Arduino

Today this handheld device, in one fell swoop, was to help me create a blinker, a switchlight and a combo lock-driven light, and it supplied USB power to my breadboard, rendering the DC power unnecessary for this lab.

Still, I kept the LED on the far end of my board to indicate that the board was indeed powered when I plugged in the Arduino. I also put an LED in the digital output and ground of my Arduino to make sure power worked in that as well.



Once power was determined on all fronts, I created an LED circuit much like in the first lab, but also wrote a simple program to create a blinker with .5 sec delay.





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

void loop() {
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}


I was now ready to try a toggle switch light with the Arduino. This was done in the 1st lab without code, but it's more satisfying to make something work with it.



void setup() {
pinMode(13, OUTPUT);
pinMode(2, INPUT);
}

void loop() {
// check the digial input. If it's high, do something:
if (digitalRead(2) == HIGH) {
// set the digital output HIGH (turn on the LED):
digitalWrite(13, HIGH);
}
else {
// turn off the LED:
digitalWrite(13, LOW);
}
}


I furthered the code in a 3rd application by adding one LED and allowing for the switch between one light being on while the other was off, and vice versa:


void setup() {
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(2, INPUT);
}

void loop() {
// check the digial input. If it's high, do something:
if (digitalRead(2) == HIGH) {
// set the digital output HIGH (turn on the LED):
digitalWrite(13, HIGH);
}
else {
// turn off the LED:
digitalWrite(13, LOW);
}
// check the digial input. If it's high, do something:
if (digitalRead(2) == HIGH) {
// set the digital output HIGH (turn on the LED):
digitalWrite(12, LOW);
}
else {
// turn off the LED:
digitalWrite(12, HIGH);
}
}




Finally, my combo application was a simple recursion in the code - an "if" statement inside an "if" statement - that allowed the 1st switch pressed followed by the 2nd to cause the LED to light up.

void setup() {
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(2, INPUT);
pinMode(3, INPUT);
}

void loop() {
// check the digial input. If it's high, do something:
if (digitalRead(2) == HIGH) {
if (digitalRead(3) == HIGH)
{
// set the digital output HIGH (turn on the LED):
digitalWrite(13, HIGH);}
}
else {
// turn off the LED:
digitalWrite(13, LOW);
}
}




The venture was a success, and I was pleased to realize this could imply much more than powering lights. Motors and sound cues could be the stuff that dreams are made of from here on out.

No comments: