Was bored in the Project room the other day and wrote this simple program that can count from 0 to 15 in binary using 4 LEDs on pins 13,12,11 and 10:
int onePin = 13;
int twoPin = 12;
int fourPin = 11;
int eightPin = 10;
int del =1000;
int one = 0;
int two = 0;
int four = 0;
int eight = 0;
void setup() {
pinMode(onePin, OUTPUT);
pinMode(twoPin, OUTPUT);
pinMode(fourPin, OUTPUT);
pinMode(eightPin, OUTPUT);
}
void loop()
{
if (one == 1)
{
one = 0;
if (two == 1)
{
two = 0;
if (four == 1)
{
four = 0;
if (eight == 1)
{
eight = 0;
}
else
{
eight = 1;
}
}
else
{
four = 1;
}
}
else
{
two = 1;
}
}
else
{
one = 1;
}
if (one == 1) { digitalWrite(onePin, HIGH); } else { digitalWrite(onePin, LOW); }
if (two == 1) { digitalWrite(twoPin, HIGH); } else { digitalWrite(twoPin, LOW); }
if (four == 1) { digitalWrite(fourPin, HIGH); } else { digitalWrite(fourPin, LOW); }
if (eight == 1) { digitalWrite(eightPin, HIGH); } else { digitalWrite(eightPin,LOW); }
delay(del);
}
The code is written with nested if statements. A way to re-write this code so it would look a lot cleaner and easier to read is to use a case statement (it doesn't help that blogger doesn't carry over my code indentation either).
Sunday, February 28, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment