Lab 3A

1 // Lab 3A
2 // lightChaser.ino
3 // CPU used in Arduino Uno
4 #define __AVR_ATmega328P__
5 // CPU frequency in Hz.
6 #define F_CPU 16000000UL
7 // define LED sequence delay
8 #define SEQ_DELAY 100
9 #include <avr/io.h>
10 #include <util/delay.h>
11 int main (void) {
12 // configure PORT B PIN 0~5 as output
13 DDRB = (1 << DDB5) | (1 << DDB4) | (1 << DDB3) |
14 (1 << DDB2) | (1 << DDB1) | (1 << DDB0);
15 DDRD = (1 << DDD7) | (1 << DDD6) | (1 << DDD5) |
16 (1 << DDD4);
17 // forever loop
18 while (1) {
19 for (int i = 0; i < 10; i+=2) {
20 controlLED(i, 1);
21 _delay_ms(SEQ_DELAY);
22 controlLED(i, 0);
23 _delay_ms(5);
24 }
25 for (int i = 9; i >=0; i-=2) {
26 controlLED(i, 1);
27 _delay_ms(SEQ_DELAY);
28 controlLED(i, 0);
29 _delay_ms(5);
30 }
31 }
32 }
33 void controlLED(char led, char onOff) {
34 switch (led) {
35 case 0:
36 if (onOff) PORTD |= 0b00010000;
37 else PORTD &= 0b11101111;
38 break;
39 case 1:
40 if (onOff) PORTD |= 0b00100000;
41 else PORTD &= 0b11011111;
42 break;
43 case 2:
44 if (onOff) PORTD |= 0b01000000;
45 else PORTD &= 0b10111111;
46 break;
47 case 3:
48 if (onOff) PORTD |= 0b10000000;
49 else PORTD &= 0b01111111;
50 break;
51 case 4:
52 if (onOff) PORTB |= 0b00000001;
53 else PORTB &= 0b11111110;
54 break;
55 case 5:
56 if (onOff) PORTB |= 0b00000010;
57 else PORTB &= 0b11111101;
58 break;
59 case 6:
60 if (onOff) PORTB |= 0b00000100;
61 else PORTB &= 0b11111011;
62 break;
63 case 7:
64 if (onOff) PORTB |= 0b00001000;
65 else PORTB &= 0b11110111;
66 break;
67 case 8:
68 if (onOff) PORTB |= 0b00010000;
69 else PORTB &= 0b11101111;
70 break;
71 case 9:
72 if (onOff) PORTB |= 0b00100000;
73 else PORTB &= 0b11011111;
74 break;
75 default:
76 break;
77 }
78 }

Comments

Popular Posts