Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C Programming for microcontrollers (Joe Pardue, 2005).pdf
Скачиваний:
260
Добавлен:
12.08.2013
Размер:
4.55 Mб
Скачать

Chapter 4: C Types, Operators, and Expressions

Cylon Eye Speed and Polarity Control

In this example we will use port B to input data that we will use to control the Cylon eye movement rate and the LED polarity. By polarity I mean that we will set either all the LEDs on except the sweep LED which will be off, or all the LEDs off and the sweep LED on. We will control the polarity with the switch connected to the port B pin 7, leaving the lower pins to allow us to set the speed increase factor from 0 to 127.

In this example we will use the ~ bitwise operator to invert the LEDs on port D.

Open PortIO.c in Personal Notepad and save it as CylonEyes.c in a new directory CylonEyes. Make the following changes to the main() function

// CylonEyes.c #include <avr/io.h> #include <avr/delay.h>

int main (void)

{

//declare and initialize the scroll delay_count unsigned long delay_count = 10000;

//declare a variable for the speed increase unsigned long increase = 0;

//declare a variable for the polarity

unsigned char polarity = 0;

// Init port pins

DDRB = 0x00; // set port B for input DDRD = 0xFF; // set port D for output

while(1)

{

//read the switches increase = PINB;

//set the polarity if(increase > 127)

{

increase -= 127; polarity = 1;

70

Chapter 4: C Types, Operators, and Expressions

}

else polarity = 0;

// set the delay count

delay_count = 5000 + (increase * 500);

// scroll those eyes

for(int i = 1; i <= 128; i = i*2)

{

if(polarity) PORTD = ~i; else PORTD = i; _delay_loop_2(delay_count);

}

for(int i = 128; i > 1; i -= i/2)

{

if(polarity) PORTD = ~i; else PORTD = i; _delay_loop_2(delay_count);

}

}

}

Open the makefile in the Blinky directory and change TARGET = CylonEyes then save it to the CylonEyes directory. Compile, load, and play.

Figure 15: Bit 7 high

Figure 16: Bit 7 low

71

Chapter 4: C Types, Operators, and Expressions

72