7
AVR Programming 2 Robotix, IIT Kharagpur

AVR Programming 2

Embed Size (px)

DESCRIPTION

Contains basic macros: chekcbit, setbit, clearbit and toggle bit to alter binary bits

Citation preview

Page 1: AVR Programming 2

AVR Programming 2Robotix, IIT Kharagpur

Page 2: AVR Programming 2

C Programming : Macros

● #define <identifier> <replacement token list>

● Replaces identifier with replacement token● Example: #define Var_X 100 would replace

Var_X anywhere in the programme with the value 100

● #define RADTODEG(x) ((x) * 57.29578) : Converts radians to degrees. If there is RADTODEG(20) anywhere in the prgramme it will be replaced by 20 * 57.29578

 

Page 3: AVR Programming 2

Checkbit

● A bit can be either 0 or 1

● We check whether the bit is 0 or not.

● var X=PINB;var Y=X & (1<<BIT) //Value of bit is in Y

● Checking the 4rd Bit. The And function returns an non zero binary number. Thus if a bit is 0 it returns 0.

  

0 0 0 1 0 1 1 0

0 0 0 1 0 0 0 0

AND

Page 4: AVR Programming 2

Checkbit

0 0 0 1 0 1 1 0

0 0 0 0 1 0 0 0

AND

● Checking the 3rd Bit. The And function returns 0. Thus if a bit is 0 it returns 0.

● #define CHECK_BIT(var,pos) ((var) & (1<<(pos)))

Page 5: AVR Programming 2

Clearbit

● Clears the bit or sets it to 0.● var X=PINB;

var X=X & ~(1<<BIT);● #define CLEAR_BIT(var,pos) ((var) & ~(1<<(pos)))● Following changes 4th bit to 0. Rest remaining same. 

0 0 0 1 0 1 1 0

1 1 1 0 1 1 1 1

AND

Page 6: AVR Programming 2

Setbit

● Sets the bit or sets it to 1.● var X=PINB;

var X=X | (1<<BIT);● #define SET_BIT(var, pos) ((var) | (1<<(pos)))● Following changes 4th bit to 1. Rest remaining same.  0 1 0 0 0 1 1 0

0 0 0 1 0 0 0 0

OR

Page 7: AVR Programming 2

Toggle Bit

● Uses XOR Operator● XOR returns one only when only 1 of the two inputs is

1.● Thus if a bit is 0 it becomes 1 and if its one it becomes

0. XOR with 0● var X=PINB;

var X=X ^ (1<<BIT);  0 1 0 0 0 1 1 0

0 0 0 1 0 0 0 0

XOR