AVR. VO PORT PROGRAMMING
i it exam-
s chapter describes 1/0 port programming of the AVR vi ae Sa
ples. In Section 1, we describe /O access using byt size data,
2, bit manipulation of the 1/0 ports is discussed in detail.
SECTION 4; 110 PORT PROGRAMMING IN AVR
i ending on
In the AVR family, there are many ports for 16 ere ba soo
Which family member you choose. Examine Figure 1 SoeTA PORTB, PORTC,
chip. A total of 32 pins are set aside for the four pore a aes ARTALL,XTAL2,
and PORTD, The rest of the pins are designated as VCC, ,
RESET, AREF, AGND, and AVCC.
PAO (ADCO)
nan ie PAt (ADC1)
(INT2/AINO) PB2 [3 PA2 foes
(OCO/AIN1) PBS MEGA32 PAS (Al
(SS) PB4 PA4 (ADC4)
(Mos!) PBS PAS (ADCS)
(Miso) PB6 PAG (ADC6)
(SCK) PB7 PAT (ADC7)
RESET AREF
vec AGND.
GND AVCC,
XTAL2 PC7 (TOSC2)
XTAL1 PC6 (TOSC1)
(RXD) PDO PC5 (TDI)
(TXD) PD1 PC4 (TDO)
(INTO) PD2 PC3 (TMS)
(INT1) PD3 PC2 (TCK)
(OC1B) PD4 PC1 (SDA)
(OC1A) PDS. PCo (SCL)
fi (ICP) PD6 PD7 (0C2)
Figure 1. ATmega32 Pin Diagram
oo port pins and their functions
‘The number of ports in the AVR family varies depending on the number of
pins on the chip. The 8-pin AVR has port B only,
while the 64-pin version has ports
A through F, and the 100-pin AVR has ports A.
through L, as shown in Table 1.
The 40-pin AVR has four ports. They are PORTA, PORTB, PORTC, and PORTD.
To use any of these ports as an input or output port, it must be programmed, as we
will explain throughout this section, In addition to being used for simple VO, each >
140AVR 1/0 PORT PROGRAMMING
Table 1: Number of Ports in Some AVR Family Members
Pins 8-pin 28-pin 40-pin 64-pin 100-pin,
x x x
Port B Gite x X X X
Port C. 7 bits x x x
PonD X x x x
Port E x x
Port F X x
Port G Sits 6 bits
Port H x
Port J X
Port K x
Port L x
Note: X indicates that the port is available.
port has some other functions such as ADC, timers, interrupts, and serial commu
nication pins, Figure 1 shows alternate func- ‘Table 2: Register Addresses
tions for the ATmega32 pins. In this chapter We for ATmega32 Ports
focus on the simple I/O function of the AVR fam-
ily. Not all ports have 8 pins. For example, in the Port ___Address_Usage
‘ATmega8, Port C has 7 pins. Each port has three PORTA _$3B__output__
VO registers associated with it, as shown in Table DORA _$3A_direction
PINA $39 input
2. They are designated as PORTx, DDRx, and PVA $2 Be
PIN. For example, for Port B we have PORTB, PORT® S38 Sulit —
DDRB, and PINB. Notice that DDR stands for_ Pry S36 input
ata Direction Register, and PIN stands for Pot poeto 935 ouinat
: PORTO $35____output
TNput pins, Also notice that each of the VO res- DRC $34 direction
Hers is B bits wide, and each port has a maxi- INC $33 input__
‘mum of 8 pins; therefore each bit of the VO reg- PORTD $32 output
inter affects one of te pin (Se Figure 2; the DORE) "S31 dieaion”
content of bit 0 of DDRB represents the direction PIND $30 input
of the PBO pin, and so on). Next, we describe
how to access the 1/0 registers associated with
the ports.
Px7-Px6 x5 Px4 Px3, Px2_Pxt_ Px
Figure 2, Relations Between the Registers and the Pins of AVR
“1AVR /O PORT PROGRAMMING
pe
/ DDRx register role in outputting data
Each of the ports A-D in the ATmega32 can be used for input or output,
The DDRx VO register js used solely for the purpose of making a given port an
input or output port(For example, to make a port an output, we write Is to the
DDRx register. In o ards, to output data to all of the pins of the Port B, we
‘must frst put ObIIIII111 into the DDRB register to make all of the pins outputs
~—~The following code will toggle all 8 bits of Port B forever with some time
delay between “on” and “of states
UDI R1G,OxFF R16 = OxFF = Ob11111111
OUT DDRB,R16 —;make Port B an output port (1111 1111)
Ll: LDI R16,0x55 R16 = 0x55 = 0b01010101
OUT PORTB,RI6 put 0x55 on port B pins
CALL DELAY
UDI R16,0xAA_ R16 = OxAA = 0b10101010
OUT FORTB,RI6 put OxAA on port B pins
CALL DELAY
ROMP 11
It must be noted that unless we set the DDRx bits to one, the data will not
20 from the port register to the pins of the AVR. This means that if we remove the
first two lines ofthe above code, the 0x55 and OxAA values will ot get tothe pins,
They will be sitting in the VO register of Port B inside the CPU,
To see the role of the DDRx register in allowing the data to go from Portx
to the pins, examine Figure 3.
Z
/DDR register role in inputting data
‘To make a port an input port, we must fist put Os into the DDRx register
for that port and then bring in (read) the data present atthe pins. Ag an aid for
‘emmembering thatthe por is input when the DDR bits are 0s, imagine a person
Who has 0 dollars. The person can only get money, not give it. Similarly, when
DDR contains 0s, the port gets data,
Notice that upon reset, all ports have the value Ox
" (00 in their DDR registers.
This means that all ports are configured as input as we
will see next,
'
i
' DDRxn
Pin n of
me PORTxn
i
H >| Pin
Outside the | Inside the
AVR chip |. AVR chip
1
Figure 3. The VO Port in AVR
142 :AVR 0 PORT PROGRAMMING
PIN register role in inputting data
To read the data present at the pins, we should read the PIN register. It must
bbe noted that to bring data into CPU from pins we read the contents of the PINx
register, whereas to send data out to pins we use the PORTx register.
_ PORT register role in inputting data
There is a pull-up
resistor for each of the AVR '
pins. If we put Is into bits of
the PORTx register, the pull-
up resistors are activated. In
cases in which nothing is con-
nected to the pin or the con-
nected devices have high pin of
impedance, the resistor pulls port x
up the pin, See Figure 4.
If we put Os into the
bits of the PORTx register, the
pull-up resistor is inactive.
4 Clese
PORTXI 9 - Open
Pink
side the
1
1 inside the
‘AVRenp 1 AVRchip
t
Figure 4. The Pull-up Resistor
“The following code gets the data present at the pins of port C and sends it
to port B indefinitely, after adding the value 5 to it:
mygf0pe “M32DeF.1Nc"
UDI R16,0x00 R16 = 00000000. (binary)
OUT DRC, R16 make Port C an input port
EDI R16,0xFF RIG = 11111111 (binary)
OUT ' DDRS,RI6 “snake Port B an output port (1 for Out)
12: IN R16,PINC read data from Port C and put in R16
“wr R175.
ADD R16,RI7 add § to it
QuT PORTB/RI6 send it to Port B
RUMP 12 jeontinue forever
If we want to make the pull-up resistors of port C active, we must put 1s
{into the PORTC register. The program becomes as follows:
LINCLUDE —"H32DBF. TNC"
Ppt R16/OxFF7RL6 ~ 12212122 (binary)
tor bore, A16 make Port B an output port
OUT PORTC,RI6
EDI. R16, 0x00
make the pull-up resistors of C active
16 = 00000000 (binary)
ROE Dpnc,al6 Port C an input port (0 for 1)
iz: GN. RIG/PINC move data from Port C to R16
pr R17/5
bp RIG/RI7._— 7add_sone. value to it
abr PORTB,RI6. rend it to Port B
ROMP 12 jeontinue forever
‘Again, it must be noted that unless we clear the DDR bits (by putting Os
nore), the data will not be brought into the registers from the pins of Port C. To
143,AVR I/O PORT PROGRAMMING
see the role of the DDRx register in allowing the data to come into the CPU from
the pins, examine Figure 3,
The pins of the AVR microcontrollers can be in four different states accord-
ing to the values of PORTx and DDRx, as shown in Figure 5.
SS
Figure 5. Different States of a Pin in the AVR Microcontroller
This is one of powerful features of the AVR microcontroller, since most of
the other microcontrollers’ pins (e.g., 8051) have fewer states
Port A
Port A occupies a total of 8 pins (PAO-PA7). To use the pins of Port Aas
input or output ports, each bit of the DDRA register must be set to the proper
value, For example, the following code will continuously send out to Port A the
alternating values of 0x55 and OxAA:
stoggle all bits of PORTA
sINCLUDE —"M32DEF. INC"
DDI R1G,OXFF R16 = 11111112 (binary)
OUT DDRA,RLG make Port A an output port ’
Ll: MDT R16,0x55 R16 = 0x55
OUT PORTA,R1G put 0x55 on Port A pins
CALL DELAY
EDI R1G/OxAA —FR16 = OxAA
OUT PORTA,R16 put OxAA on Port A pins
CALL DELAY
ROMP LI
It must be noted that 0x55 (01010101) when complemented becomes
OxAA (10101010).
} Port Aas input
In order to make all the bits of Port A an input, DDRA must be cleared by
‘writing 0 to all the bits. In the following code, Port Ais configured first as an input
port by writing all Os to register DDRA, and then data is received from Port A and
saved in a RAM location:
SINCLUDE —"M32DEF, TNC
-EQU. MYTEMP 0x10 isave it here
EDI R16,0x00 R16 = 00000000 (binary)
OUT DDRA,RI6—;make Port A an input port (0 for In)
NOP psynchronizer delay
IN R16/PINA ;move from pins of Port A to R16
STS MYTEMP,R16 ;save it in MYTEMPAVR 1/0 PORT PROGRAMMING
SSS
Synchronizer delay
The input circuit of the AVR has a delay of 1 clock cycle. In other words,
the PIN register represents the data that was present at the pins one clock ago. In
the above code, when the instruction “R16, P1115” is executed, the PINA regis-
ter contains the data, which was present at the pins one clock before. That is why
the NOP js put before the “1 R16, prnin” instruction. (If the NOP is omitted, the
read data is the data of the pins when the port was output.)
ort B
Port B occupies a total of 8 pins (PBO-PB7). To use the pins of Port B as
input or output ports, cach bit of the DDRB register must be set to the proper
value.
For example, the following code will continuously send out the alternating,
values of 0x55 and OxAA to Port B:
ftoggle all bite of FORTB
W@finciupe M32DEF. INC"
EDI R16,0xEF ;RI6 = 11111111 (binary)
OUT DDRB,R16. make Port B an output port (1 for Out)
Ll: LI R16,0%55 R16 = 0x55
OUT PORTB,R16 put 0x55 on Port B pins
CALL DELAY
LDI R16,0xAR_ 716 = OxAA
OUT PORTB,R16 put OxAA on Port B pins
CALL DELAY
ROMP Lt
‘ort B as input
In order to make all the bits of Port B an input, DDRB must be cleared by
writing 0 to all the bits. In the following code, Port B is configured first as an input
port by writing all Os to register DDRB, and then data is received from Port B and
saved in some RAM location:
LINCLUDE — "M32DEF. INC"
VEQU MYTEMP=0x100 ;2ave it here
br R16,0x00 7R16 = 00000000 (binary)
Our DDRB,RI6 make Port B an input, port (0 for In)
NOP
In R16,PINB move from pine of Port B.to R16
srs WYTEMP, R16 eave it in MYTEMP
Dual role of Ports A and B
“The AVR multiplexes an analog-to-digital converter through Port A to save
ing, The alternate functions of the pins for Port A are shown in Table 3.
KK
rojects use an ADC, we usually do not use Port A for simple VO
Because many pt
functions. . A
The AVR multiplexes some other functions through Port B to save pins.
145AVR V0 PORT PROGRAMMING
‘The alternate functions of the pins for Port B are shown in Table 4,
Table 3: Port A Alternate Table 4: Port B Alternate
Functions Functions
—_—
Bit Function Bit__ Function
PAO ADCO PBO XCK/TO
PAL ADCI PBI Th
PAZ ADCZ PB2 INT2/AINO
PAZ ADC3 PB3 OCO/AINI
PAG ADC4 PB4 SS
PAS ADCS, PBS MOSI
PAG ADCG PBG MISO.
PAT ‘ADCT PBT SCK
sf ort C
Port C occu
pies a total of 8 pins (PCO-PC7), To use the pins of Port C as
‘input or output ports, each bit of the DDRC register must be set to the proper
value. For example, the following code will continuously send out the alternating
Values of 0x55 and OxAA to Port C:
stoggle all bits of PORTE
CLUDE -"M22DEF THC
LOI R16, 0x8F
OUT pope, R16
Lis Lor R16, 0x55
our Forte, R16
CALL DELAY
LOI P16, 0xnm
ouT rorte,z16
CALL DELAY
PaMe LA
on
#R16 = 11111111 (binary)
imake Port C an output port (1 for out)
FRIG = 0155
put 0x55 on Port C pins
FPL6 = OnRR
#put OxAA on Port © pine
Port C as input
In order to make all the bits of Port
writing 0 to all the bits. n the following c
port by writing all 0s to register DDRC,
saved in a RAM location:
Can input, DDRC must
“ode, Port C is configured
and then data is received
tbe cleared by
first as an input
from Port C and
STNCLUDE —"M32peF. mC"
+200 MITEMP Ox100 ioave it here
Lor 16,0700 R16 = 00000000 (binary)
OUT DDR, RIG
imake Port C an input port (0 for tn)
HOP
TH RIG, FINC
BTS «METEMP, RIG
Port D
Port D oveupies a total of § pins (PDO-PD), To use the pins of Port D ag
input or ouput ports, each bi ofthe DORD regier mex be se tothe ge
smove from pins of m
OFLC to RIG
yeave it in uyreMeAVR VO PORT PROGRAMMING
value. e
value. For example, the following code will continuously send out to Port D the
alternating values of 0x55 and OxAA:
itoagle all bits of
: its of PORT
SINCLUDE —"N32DEF TNC” i
Lor
JOR Rie Ose #RI6 = 11211111 (binary)
i RD/R1G —;make Port D an output port (1 for O
+ MDT R16,0x5S_ FRG = 0x55
OUT PORTD,R2G put 0x55 on Port D pins
ue)
CALL DELAY
EDI RIG,OKAA_—GRL6 = OxAA
our PORTD,RIG
VIG ;put OxAA on Port D pine
CALL DELAY 2a
ROMP LL
/Port D as input
In order to make all the bits of Port D an input, DDRD must be cleared by
‘writing 0 to all the bits. In the following code, Port D is configured first as an input
port by writing all 0s to register DDRD, and then data is received from Port D and
saved ina RAM location:
SINCLUDE "M32DEF.INC"
‘QU MYTEMP 0x100 jsave it here
MDI R16,0x00 R16 = 00000000 (binary)
OUT DDRD,RI6. make Port D an input port (0 for In)
NOP
IN _R16,PIND _;move from pins of Port D to R16
STS MYTEMP,RI6 save it in MYTEMP
_ fost role of Ports C and D
the pins for Port C are shown in Table 5. The
The alternate functions of
re shown in Table 6.
alternate functions of the pins for Port D ar.
‘Table 5: Port C Alternate ‘Table 6: Port D Alternate
Functions Functions
Bit Function Bit__Funetion
Poo SCL PDO___PSPO/CIINE
PCI SDA PDI___ PSPI/CLIN-
$027. TOK PD2___PSP2/C2IN+
Pc3___TMS___—_— PD3___PSP3/C2IN-___
pcs 10 PD4____PSP4/ECCPI/PIA.
Pcs___ TDI PDS PSPS/PIB
G6 TOscL PD6___PSP6/PIC.
PC7 TOSC2 PD7 PSP7/P1D
: 147AVRO PORT PROGRAMMING
Review Questions
— ports in the AT meg:
1
a ihe at
| At the AT mega? ports have
ee ‘On| power-up, the VO pins are configured a rts
; i . 1 are configured as output por
i ‘ on imple program to send 0x99 to Port 8 and Port C.
carrouake He Ban output port, we must place _____ in register ___
S Tomake Fort B an input port, we must place in reg
Fe Tug OF figs: We use a PORT register to send data out to AVE pins.
, ~ We use PINx to bring data into the CPU from AVR. pins.
“
SECTION 2: 1/0 BIT MANIPULATION PROGRAMMING
{n this section we further examine the AVR 1/0 instructions. We pay spe-
cial attention to 1/0 bit manipulation because it is a powerful and widely used fea-
ture of the AVR family,
of VO ports and bit-addressability
Sometimes we need to access only | or 2 bits of the port instead of the
entire 8 bits. A powerful feature of AVR 1/0 ports is their capability to access indi-
vidual bits of the port without altering the rest of the bits in that port. For all AVR
ports, we can access cither all 8 bits or any single bit without altering the rest.
Table 7 lists the single-bit instructions for the AVR. Although the instructions in
Table 7 can be used for any of the lower 32 I/O registers, /O port operations use
them most often. Table 8 shows the lower 32 I/O registers.
Next we describe all these instructions and examine their usage.
Table 7: Single-Bit (Bit-Oriented) Instructions for AVR
Instruction
SBI__ioReg bit
CBI__ioReg,bit
SBIC_ioReg,bit
SBIS_ ioReg,bit
Function
Set Bit in VO rogister (set the bit: bit = 1)
‘Clear Bit in 1/0 register (clear the bit: bit = 0)
Skip if Bit in /O register Cleared (skip next instruction if bit= 0).
Skip if Bit in VO register Set (skip next instruction if bit= 1)
‘Address.
‘Table 8: The Lower 32 1/0 Registers
149AVR I/O PORT PROGRAMMING
ic.
BI (set bit in 1/0 register)
/ To set HIGH a single bit of a given 1/0 register, we use the following syn-
tng =
SBI ioReg, bit_num
where ioReg can be the lower 32 1/0 registers (addresses 0 to 31) and
I bit_num is the desired bit number from 0 to 7. In Table 8 you see the list of the
lower 32 V/O registers. Although the bit-oriented instructions can be used for
manipulation of bits D0-D7 of the lower 32 1/0 registers, they are mostly used for
VO ports. For example the following instruction sets HIGH bit 5 of Port B:
SBI PORTB, 5
In Figure 6, you see the SBI instruction format.
SBI a,b
0
0
31
WIA
oo
AIA
~
{
Figure 6. SBI (Set Bit) Instruction Format
‘CBI (Clear Bit in /0 register)
To clear a single bit of a given VO register, we use the following syntax:
CBI ioReg, bit_nunber
For example, the following code toggles pin PB2 continuously:
SBI DDRB, 2 sbit = 1, make PB2 an output pin
AGAIN:SBI_ FORT, 2 wbit set (PBZ = high)
CALL DELAY
CBI PORTB, 2
CALL. DELAY
ROMP AGAIN
pbit clear (PB2 = low
Remember that for 1/O ports, we must set the appropriate bit in the
DDRx register if we want the pinto be output,
Notice that PB2 is the third bit of Port B (the fist bit is PBO, the second bit
is PBI, etc.). This is shown in Table 9, See Exam cxample of bit
ple 2 for an example of bi
manipulation of /O bits, ple of bit
CBI a,b
0
0
Ligure 7. CBT (Clear Bit) Instruction Format
150AVR 1/0 PORT PROGRAMMING
Table 9: Single-Bit Addressability of Ports for ATmega32/16 a
PORT PORTB PORTC PORTD Port Bit
PAO PBO PCO PDO DO.
ze PBI PCI PDI DI
PA2 PB2 PC2 PD2 D2
PA3 PB3 PC3 PD3 D3
PAd PB4 PC4 PD4 D4
PAS PBS PCS PDS DS
PAG PBG PC6 PD6 Dé
PAT PB7 PCT PD7 D7
Notice in Example 2 that unused portions of Port C are undisturbed. This
single-bit addressability of /O ports is one of the most powerful features of the
AVR microcontroller.
[Example 2
‘An LED is connected to each pin of Port D. Write a program to turn on each LED from
pin DO to pin D7. Call a delay subroutine before turning on the next LED.
| Solution:
Lor
our
LL
our
Lor
our
SBI
CALL
SBI
CALL
SBI
CALL.
SBI
CALL
SBI
CALL
SBT
caLL
io sBr
caLL
SBI
“INCLUDE
32DeF .INC*
R20, RIGH (RAMEND)
SPH, R20
R20, LOW (RAMEND)
SPL, R20
R20, OxFF
PORTD, 20
ORT, 0
DELAY
PORTD, 1
DELAY
PORTD, 2
DELAY
PORTD, 3
DELAY.
EORTD, 4
DELAY
PORTD, 5
DELAY
BORTD, 6
DELAY
PORTD,7
DELAY
sinitialize stack pointer
ymake FORTD an output port
feet bit PDO
idelay before next one
;turn on PDL
delay before next one
peurn on PD2
270
PDO
LED Wo
AVR
270
PO7 Bk:
LeD YA
151AVR 1/0 PORT PROGRAMMING
écking an input pin
eens sae aeons based on the status of a given bit in the file register, we
inter Ses} eee it in 1/0 register Cleared) and SBIS (Skip if Bit in VO reg-
‘Sens. They allowyos These single-bit instructions are widely used for 1/0 opera-
whether it is 0 aaa to monitor a single pin and make a decision depending on
eat be teed | toby i ae suit be noted that the SBIC and SBIS instructions
CD. aniiao'en, 1¢ lower 32 1/0 registers, including the I/O ports A, B,
BAS (Skip if Bit in /0 register Set)
___ To monitor the status ofa single bit for HIGH, we use the SBIS instruction.
his instruction tests the bit and skips the next instruction if it is HIGH. See Figure
'8. Example 4 shows how it is used.
| SBIS a,b
| o
jystandard AVR header
int main (void) J/the code starts from here
t
unsigned char myhist|] = "012345ABCD"?
unsigned char 2 fee
DDRB = OxFF; //PORTB is out
Jirepeat 10 times and increment 2
for(z=0; 2<10; 244)
PORTE = myList{ 2} //send the character to PORTE
while (1); //needed if running on a trainer
return 0;
[Examples
ae ‘an AVR C program to toggle all the bits of Port B 200 times.
‘Solution:
J{toggle PB 200 times
Binclude
ant main (void)
t
| © unsigned long 2;
© DDRB = OxEF; i
‘ox (2=0; 25100000; 244)(
260AVR PROGRAMMING IN C
7s delay
There are three ways to create a time delay in AVR C
1. Using a simple zor loop
2. Using predefined C functions
3. Using AVR timers
In creating a time delay using a for loop, we must be mindful of two fac-
tors that can affect the accuraey of the delay:
1. The crystal frequency connected to the XTALI-XTAL2 input pins is the most
‘important factor in the time delay calculation. The duration of the clock peri-
‘od for the instruction cycle is a function of this crystal frequency.
2. ‘The second factor that affects the time delay is the compiler used to compile
the C program. When we program in Assembly language, we can control the
exact instructions and their sequences used in the delay subroutine. In the case
of C programs, itis the C compiler that converts the C statements and func-
tions to Assembly language instructions. As a result, different compilers pro-
duce different code. In other words, if we compile a given C program with dif-
ferent compilers, each compiler produces different hex code.
For the above reasons, when we use a loop to write time delays for C, we
must use the oscilloscope to measure the exact duration. Look at Example 7.
Notice that most compilers do some code optimization before generating a -hex
file. In this process they may omit the delay loop because it does not do anything
‘other than wasting CPU time. In these compilers, you have to set the level of opti-
mization to zero (none). To see how you can set the level of optimization for
WinAVR and AVR Studio, refer to www.MicroDigitalEd.com.
261262
[AVR PROGRAMMING IN C
h
Anothi Tay isto use predefined functions suc
ler way of generating time delay * ieny_ma( a
a8 _delay_ms() and _delay_us() defined in delay:h in WinAVR or delay
delay_us) defined in de ‘CodeVision, The only drawback of using these
funetions is the portability problem. Because different compilers do not use the
same name for delay functions, you have to change every place in which the delay
functions are used, if you want to compile your program on another compiler. To
overcome this problem, programmers use macro or wrapper function. Wrapper
functions do nothing more than call the predefined delay function. If you use
\wrapper functions and decide to change your compiler, instead of changing all
instances of predefined delay functions, you simply change the wrapper function.
Look at Example 8. Notice that calling a wrapper function may take some
microseconds,
Examples i Tae
Write an AVR C program to toggle all the pins of Port C continuously with a 10'ms
delay. Use a predefined delay function in Win AVR. ree s
Solution:
Hinclude //éelay loop functions
‘include //standerd AVR header
int main(void) Tes
( ae cette a
_ yoid delay ms (int d) //delay in d microseconds
7 ae Sao
“delay ne (a);
ji ee Es
DDRB = OxFF; - {/ORTA ts out
while (1)( DE Da
FORTS = OXF;
delay_ms(10)
PORTE = 0x55;
delay _ms(10);
i
retvrn 07,
Review Questions
1. Give the magnitude of the unsigned char and signed char datatypes,
4, Give the magnitude ofthe unsigned int and signed int datatypes,
3, If we are declaring a variable for a person’s age, we should use the __ data
false. Using predefined functions of compilers to create atime delay is
mmended if you want your code to be portable to other compilers
factors that can affect the delay size.
type.
4, True oF
not reco!
5, Give twoExmrtes
EDs are connected to pins of Port B, Write an AVR C program that shows the count
AVR PROGRAMMING IN C
SECTION 2: (0 PROGRAMMING IN C
All port registers of the AVR are both byte accessible and bit accessible,
In this section we look at C programming of the I/O ports for the AVR. We look at
both byte and bit /O programming.
Byte size 10
To access a PORT register as a byte, we use the PORT label where x indi-
cates the name of the port. We access the data direction registers in the same way,
using DDRx to indicate the data direction of port x. To access a PIN register as @
byte, we use the PINx label where x indicates the name of the port. See Examples
9, 10, and 11.
from 0 to FFH (0000 0000'to 1111 1111 in binary) on the LEDs.
Solution:
‘include: //standard AVR header
int main (void)
i :
DDRE = OxFF: 7/port B is output
wnile G) E
(
BORTB = RORTB + 1;
)
return 0;
i EOS
ee
“Write an AVR C program to get a byte of data from Port B, and then send it to Port C.
[Example 10)
Solution: eee
#include d/standard AVR header
Ant main (void) ©
(
‘unsigned char, temp: ef
7iport Bis input
DAB & 0x00?
pl b /7eext Cis output!
“DRG =" 0xEF)
2 while (1)
i
temp = PINB:— AVR PROGRAMMING INC
: a
itis less than 100, send it
rite an AVR C program to get a byte of data from Port C,Ifit is less
to Port B; otherwise, send it to Port D.
Solution:
Hinclude //standard AVR header
int main (void)
! <
DDR = 0; //Port C is input
DDRE = OxFF; //Rort B is output
DDRD = OxEF; //Port D is output
unsigned char temp;
while (1)
{
temp = PINC; //xead from
if (temp < 100 )
PORT = temp;
else
PORTD = tenp;
)
zeturn 0;
Bit size /0
The VO ports of ATmega32 are bitaccessible. But some AVR C compilers
do not support this feature, andthe others do not havea standard way of using it
For example, the following line of eode can be used in CodeVision to set the fist
pin of Port B to one:
PORTB.0 = 1;
but it cannot be used in other compilers such as WinAVR,
‘To write portable code tht can be compiled on different com;
Se oak 7 it compilers, we
1D and OR bite ti ieee
must use AND and OR bitwise operations to aetesa single Bt ot en regis-
So, you can aceess a single bt without disturbing the
next section you will see how to mask a bit of a by ean wast of the byte. In
te, You a ;
bit-accessible and byte-accessble ports and registers,” “S? M*sking for both
Review Questions
1. Write a short program that toggles all bits of Port c,
2. True or false. All bits of Port B are bit addressable,
3. Write a short program that togeles bit 2 of Pon Cys,
conipilet: sing the functions of your
4, ‘True or fle. To access the data diteetion register of Port We use DDRB,AVR PROGRAMMING IN C
ee
SECTION 3: LOGIC OPERATIONS IN cy
One of the most important and powerful features of the C language is its
ability to perform bit manipulation. Because many books on C do not cover this
important topic, it is appropriate to discuss it in this section. This section describes
the action of it-wise loge operators and provides some ‘examples of how they are
used.
Bit-wise operators in C
While every C programmer is familiar with the logical operators AND
(&&), OR (|), and NOT (1), many C programmers are less familiar with the bit
wise operators AND (&), OR (\), EX-OR ("), inverter (~), shift right (>>), and shift
left (<<). These bit-wise operators are widely used in software engineering for
‘embedded systems and control; consequently, their understanding and mastery are
critical in microcontroller-based system design and interfacing. See Table 2.
‘Table 2: Bit-wise Logic Operators for C
AND OR EX-OR___Inverter
A B_ A&B AIB A‘B Y=~B
oO 0 oO oO oO x
0 1 oO 1 1 0
4 0 0 1 1
x 1 1 1 0
‘The following shows some examples using the C bit-wise operators:
0x35 & OxOF = 0x05 /* ANDing */
0x04 | 0x68 = 0x6C /* ORing */
aeRe
Ox54 “ Ox78 = Ox2C 7 XORing */
~0x55 = OxAA /* Inverting 5H */
Examples 12 through 20 show how the bit-wise operators are used in
C. Run these programs on your simulator and examine the results,
265re
-— AVR PROGRAMMING INC
5 —
Example 13
inuously without disturbing
_/| Wifte an AVR C program to toggle only bit 4 of Port B continuously ZI
the rest of the pins of Port B.
Solution:
include J/standard AVR header
int main (voiay
{
DDRB = OxPr; 7/20RTS is. output
while (1)
1 « i
PORTB = PORTB | 0b00010000; /iset bit 4 (Sth bit) of PORTB
PORTE = PORTE ¢ 0b11101111;, //clear bit 4 (5th bit) ‘of PORTB,
Y
return 07
1 =
[Example 14 % 3
t= an AVR C program to monitor bit 5 of port C. It is HIGH, send 55H to Port By
CHotherwise, send AAH to Port B,
Solution:
finclude //standard AVR header
int main (void)
(
DDRB = DDRB & Obl1111101; //pin 1 of Port B is input
DPRC = DDRC | 0610000000; //pin 7 of Port C is output
white (1)
(
if (PINE & 000000010) //check pin 1 (2nd pin) of PINB
PORTC = PORTC | 0b10000000; //set pin 7 (8th pin) of PORTC
else
PORTC = FORTC & ObO1111111; //clear pin 7 (8th pin) of FORTC
}
return 0;
: LA
fexample 16 2
[eae
‘The data pins of an LCD are connected to Port B. ‘The information is latched into the
LCD whenever its Enable pin goes from HIGH to LOW. The enable pin is connected to
| pin 5 of Port C (6th pin). Write a C program to send “The Earth is but One Country” to
this LCD.
Solution:
#include //standard AVR header
int main(void)
{
| insigned char messagel) "The Earth is but One Countr}
“ungigned char 27
DDRB = OxFF? //Port B is output
DRC = DDRC | 0b00100000; //pin 5 of Port © is output
for (2 = 0; 2 < 28) ttt)
PORTE = mesaagel 2+
| forte = porte | 0b00100000; //pin Lcb_BN of Port C is L
2 Fonte = PORTC & Ob11011111; —//pin LCD_BN of Port C is 0
267
|