donderdag 9 februari 2012

Arduino - Experiment 3a - BCD teller

Het vorige experiment was een beetje omslachtig, dat kan natuurlijk veel beter. Voordat we naar Arduino - Experiment 3b - BCD naar 7-segments display gaan, maken we eerst een BCD teller van 0 t/m 9.


De waarheidstabel hiervoor is:


D
C
B
A
Decimaal
0
0
0
0
0
0
0
0
1
1
0
0
1
0
2
0
0
1
1
3
0
1
0
0
4
0
1
0
1
5
0
1
1
0
6
0
1
1
1
7
1
0
0
0
8
1
0
0
1
9


De code hiervoor is als volgt:

/*
Binary Counter with four LED's

The circuit:
* 4 LED's
       * 1 220ohm resistor
       
Created 09/02/2012
By Reinoud de Lange (reinouddl@gmail.com)
adopted some code from Vito Magnanimo

*/

#define LED1 0    // pin of LED1
#define LED2 1    // pin of LED2
#define LED3 2    // pin of LED3

#define LED4 3    // pin of LED4

int a=0;   // state of LED1
int b=0;   // state of LED2
int c=0;   // state of LED3

int d=0;   // state of LED4

//there are auxiliary variables
int new_a=0;  // used to store new LED1 state
int new_b=0;  // used to store new LED2 state
int new_c=0;  // used to store new LED3 state

int new_d=0;  // used to store new LED4 state

void setup(){
 
 pinMode(LED1,OUTPUT);    //set all pin in OUTPUT mode
 pinMode(LED2,OUTPUT);
 pinMode(LED3,OUTPUT);

 pinMode(LED4,OUTPUT);
 
}
void loop(){
 
 delay(2000);   // wait 2s before to begin every cicle
                // this is useful because if there isnt any
                // delay we will not see anything
               
 if  (!a) new_a=1;
 else new_a=0;
 if( (b && !a) || (!b && a && !d)) new_b=1;
 else new_b=0;
 if( (!c && b && a) || (c && !a) || ( c && !b)) new_c=1;

 else new_c=0;
 if( (!d && c && b && a) || (d && !a)) new_d=1;
 else new_d=0;

 
 a=new_a;   //now new value can be stored in the state variables
 b=new_b;  
 c=new_c;

 d=new_d;
 
 //turn ON or turn OFF  LED 1 2 3 4
 if(a==1) digitalWrite(LED1,HIGH);
 else digitalWrite(LED1,LOW);
 if(b==1) digitalWrite(LED2,HIGH);
 else digitalWrite(LED2,LOW);
 if(c==1) digitalWrite(LED3,HIGH);
 else digitalWrite(LED3,LOW);
 if(d==1) digitalWrite(LED4,HIGH);
 else digitalWrite(LED4,LOW);
}


En dat ziet er dan als volgt uit:



Hierna kunnen we met de BCD to 7-segment driver het display aansturen. Maar dat is voor het volgende experiment: "Arduino - Experiment 3b - BCD naar 7-segments display".