int i; // counter variable
int j; // pgm outputs codes 00000 to 00111 in portd 2-4 bits
int count=7;
int SW1=8; //Set SW1 to Pin 8
int SW2=9; //Set SW2 to Pin 9
void setup(){
DDRD = DDRD | B00011100; // set direction bits for pins 2 to 4, leave 0 and 1 untouched
//(xx | 00 = xx) same as pinMode(pin, OUTPUT) for pins 2 to 4
Serial.begin(9600);
Serial.println ("Question 7");
Serial.println ("Current Limiting Resistor = 5-3/0.04=75, 5-3/0.01=200");
Serial.println("Therefore, using a 220 ohm resistor so bright enough to use and don't exceed 200mA maximum");
Serial.println ("Yellow switch = Up Counter, Green Switch = Down Counter");
pinMode(SW1,INPUT);
pinMode(SW2,INPUT);
digitalWrite(SW1, HIGH); //enable pullup. Switch connected to ground
digitalWrite(SW2, HIGH); //enable pullup. Switch connected to ground
}
void loop(){
while (digitalRead(SW1)==LOW) // check if COUNT_UP switch is released
{
count++;
if (count>7)
{
count=0;
}
// 3 bits manipulated 0 to 7
PORTD = PORTD & B11100011; // clear out bits 2 -4, leave pins 0 and 1 untouched (xx & 11 = xx)
j = (count << 2); // shift variable up to pins 2 - 7 - to avoid pins 0 and 1
PORTD = PORTD | j; // combine the port information with the new information for LED pins
Serial.print("PORTD in Binary=");
Serial.print(PORTD, BIN); // debug to show masking
Serial.print(", Count=");
Serial.println(count);
delay(200);
}
while (digitalRead(SW2)==LOW) // check if COUNT_DOWN switch is released
{
count--;
if (count<0) // Restart after 7
{
count=7;
}
// 3 bits manipulated 0 to 7
PORTD = PORTD & B11100011; // clear out bits 2 -4, leave pins 0 and 1 untouched (xx & 11 = xx)
j = (count << 2); // shift variable up to pins 2 - 7 - to avoid pins 0 and 1
PORTD = PORTD | j; // combine the port information with the new information for LED pins
Serial.print("PORTD in Binary=");
Serial.print(PORTD, BIN); // debug to show masking
Serial.print(", Count=");
Serial.println(count);
delay(200);
}
delay(200);
}