OK, Let's make something happen, this LED has to turn on. I'll put it simply, even the greatest project of all times has to have a LED doing something and most likely it started from that.
Was it 0 or 1 for on? 0 I think. On which pin is it? Have a look at the schematic. How do I turn it on? Well, just declare this port pin to be an output and set it to 0. Have a look at the datasheet, you will find an example. Here is how it goes:
#include
int main(void) // program starts here
{
DDRB = 255; // set port B for output
PORTB = 0; // set port B pins to 0
return (0); // return something
}
Compile - Download! Has the LED turned on? Great! No? You press Back three times, by the way is the right code running into the micro?
Now, this code affected all Port B pins, not just the pin the LED is on, not nice. Can you rewrite it not to? Come on. Not to forget, did you check at your project's tree the external dependencies? Where are the registers declared?
Have a look at the datasheet, can you enable the internal pull-up? You supply more current now, can you notice any brightness difference? Great! We can add a delay now. ON Delay OFF Delay, ON Delay OFF Delay, ...
#include
/// Typedefs //////////
typedef unsigned char u8;
typedef unsigned int u16;
typedef unsigned long u32;
/// Defines ///////////
#define forever 117
#define LEDOFF PORTB = (1<<4)
#define LEDON PORTB &= ~(1<<4)
/// Prototypes ////////
void InitPorts (void);
void Delay (u32 count);
int main(void)
{
InitPorts();
while (forever)
{
LEDON; Delay(20000);
LEDOFF; Delay(20000);
}
}
void InitPorts(void)
{
DDRB = 1<
}
void Delay(u32 count)
{
while(count--);
}
Compile - Download! You are happy, aren't you? Experiment with different delays, make delay vary, can you relate Delay values with seconds? You will need to simulate your code with AVRStudio, remember to set the clock speed. How fast can your eyes sense blinking? Why 117? :-D.
Are these typedefs really needed or somewhere there are similar definitions? Can you write generic pin set/reset macros to avoid continuous bit tweaking and make your code more readable?

No comments:
Post a Comment