Arduino Project 1 – LED Binary Counter

I’ve always had an interest in electronics although haven’t been good at it.  A couple of my work mates bought http://www.arduino.cc/ and I had to buy one too.  This is my first very simple project, a LED binary counter.

The circuit is boring, each LED is plugged up to a different digital out.

 

The code is a little clever but still simple. Below is a function that converts a number to turn on one of 4 LEDS on. It works by dividing the number by 8,4,2, and 1 in that order. If it is divisible by that number then we turn that light on and deduct it from the original number.

<pre class="Plum_Code_Box"><code class="">void convertIntToBinary(int number) {
int divisible;
divisible = 8;&lt;/code&gt;

if (number / 8) {
number = number - 8;
digitalWrite(LEDVAL8, HIGH);
} else {
digitalWrite(LEDVAL8, LOW);
}

if (number / 4) {
number = number - 4 ;
digitalWrite(LEDVAL4, HIGH);
} else {
digitalWrite(LEDVAL4, LOW);
}

if (number / 2) {
number = number - 2 ;
digitalWrite(LEDVAL2, HIGH);
} else {
digitalWrite(LEDVAL2, LOW);
}

if (number / 1) {
number = number - 1 ;
digitalWrite(LEDVAL1, HIGH);
} else {
digitalWrite(LEDVAL1, LOW);
}

//digitalWrite(number, HIGH);
}</code>
</pre>

The main part of the code links up the LEDs and increments our number between 0 and 16(the max we can do with 4 LEDs)

<pre class="Plum_Code_Box"><code class="">#define LEDVAL1 4
#define LEDVAL2 5
#define LEDVAL4 6
#define LEDVAL8 7&lt;/code&gt;

int counter;

void setup() {
pinMode(LEDVAL1, OUTPUT);
pinMode(LEDVAL2, OUTPUT);
pinMode(LEDVAL4, OUTPUT);
pinMode(LEDVAL8, OUTPUT);
}

void loop() {
counter = counter + 1;
convertIntToBinary(counter);

if (counter == 16) {
counter = -1;
}

delay(1000);
}</code></pre>

The full code:

<pre class="Plum_Code_Box"><code class="">#define LEDVAL1 4
#define LEDVAL2 5
#define LEDVAL4 6
#define LEDVAL8 7&lt;/code&gt;

int counter;

void setup() {
pinMode(LEDVAL1, OUTPUT);
pinMode(LEDVAL2, OUTPUT);
pinMode(LEDVAL4, OUTPUT);
pinMode(LEDVAL8, OUTPUT);
}

void loop() {
counter = counter + 1;
convertIntToBinary(counter);

if (counter == 16) {
counter = -1;
}

delay(1000);
}

void convertIntToBinary(int number) {
int divisible;
divisible = 8;

if (number / 8) {
number = number - 8;
digitalWrite(LEDVAL8, HIGH);
} else {
digitalWrite(LEDVAL8, LOW);
}

if (number / 4) {
number = number - 4 ;
digitalWrite(LEDVAL4, HIGH);
} else {
digitalWrite(LEDVAL4, LOW);
}

if (number / 2) {
number = number - 2 ;
digitalWrite(LEDVAL2, HIGH);
} else {
digitalWrite(LEDVAL2, LOW);
}

if (number / 1) {
number = number - 1 ;
digitalWrite(LEDVAL1, HIGH);
} else {
digitalWrite(LEDVAL1, LOW);
}

//digitalWrite(number, HIGH);
}</code>
					
Sunday, August 14th, 2011 Arduino

Leave a Reply

 
November 2024
M T W T F S S
« Jan    
 123
45678910
11121314151617
18192021222324
252627282930