Introduction To C' Programming For Microcontrollers
Introduction To C' Programming For Microcontrollers
To set bit 0 in foo and then store the result back into foo:
Code:
foo = foo | 0x01;
Shorter one:
Code:
foo |= 0x01;
Bit Clearing
• Code:
foo = foo & ~0x01;
Shorter one:
• Code:
foo &= ~0x01;
Bit Testing
• To see if a bit is set or clear just requires
the AND operator, but with no assignment.
• Code:
if(foo & 0x80)
{
}
• The condition will be NON-ZERO when
the bit is set.
Bit Inversion
• Code:
foo = foo ^ 0x01;
Or
• Code:
foo ^= 0x01;
Creating Bit Mask
• The way to build a bit mask with only a bit
number is to LEFT SHIFT a bit by the bit
number.
• To build a bit mask that has bit number 2 set:
Code: (0x01 << 2)
• To build a bit mask that has bit number 7 set:
Code: (0x01 << 7)
• To build a bit mask that has bit number 0 set:
Code: (0x01 << 0)
Macros
• It provides a fast way of understanding what is
happening when reading the code, or it provides
additional functionality.
• Macros are replaced with actual code upon compilation.
• Code:
• #define bit_get(p,m) ((p) & (m))
#define bit_set(p,m) ((p) |= (m))
#define bit_clear(p,m) ((p) &= ~(m))
#define bit_flip(p,m) ((p) ^= (m))
#define bit_write(c,p,m) (c ? bit_set(p,m) : bit_clear(p,m))
#define BIT(x) (0x01 << (x))
#define LONGBIT(x) ((unsigned long)0x00000001 <<
(x))
Macro Examples
• To set a bit:
Code:
bit_set(foo, 0x01);
• To do it with a macro:
Code:
bit_write(bit_get(foo, BIT(4)), bar, BIT(0));
Blinking LED
#include <avr/io.h> int main(void)
{
/// Typedefs ////////// InitPorts();
typedef unsigned char u8;
typedef unsigned int u16; while (forever)
typedef unsigned long u32; {
LEDON; Delay(20000);
/// Defines /////////// LEDOFF; Delay(20000);
#define forever 117 }
#define LEDOFF PORTB |= }
(1<<4)
#define LEDON PORTB &= void InitPorts(void)
~(1<<4) {
DDRB |= 1<<DDB4;
/// Prototypes //////// }
void InitPorts (void);
void Delay (u32 count); void Delay(u32 count)
{
while(count--);
}
Blink with button
• int main(void)
{
u8 btnState;
InitPorts();
LEDOFF;
while (forever)
{
// button pin reading
btnState = ~PINB & (1<<3);
// action
if (btnState)
{
LEDON; Delay(5000);
LEDOFF; Delay(5000);
}
}
}
Blinky
#include <avr/io.h>
#include <avr/delay.h>
int main (void)
{
// set PORTD for output
DDRD = 0xFF;
while(1) {
for(int i = 1; i <= 128; i = i*2)
{
PORTD = i;
_delay_loop_2(30000);
}