0% found this document useful (0 votes)
61 views

Embedded Systems Lab04 USART

The document summarizes a lab session on using the USART of an ATmega328P microcontroller to establish asynchronous serial communication between the microcontroller and a PC. It discusses the basics of serial communication including synchronous vs asynchronous transmission and serial communication protocols. It also describes the serial port pins and registers of the ATmega328P that are used for serial communication, and how to connect the microcontroller to a PC's serial port. The objective is to program the microcontroller to transmit and receive data over its USART.

Uploaded by

Aiman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Embedded Systems Lab04 USART

The document summarizes a lab session on using the USART of an ATmega328P microcontroller to establish asynchronous serial communication between the microcontroller and a PC. It discusses the basics of serial communication including synchronous vs asynchronous transmission and serial communication protocols. It also describes the serial port pins and registers of the ATmega328P that are used for serial communication, and how to connect the microcontroller to a PC's serial port. The objective is to program the microcontroller to transmit and receive data over its USART.

Uploaded by

Aiman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Embedded Systems Lab Lab 04 Serial Port Programming of AVR

NED University of Engineering & Technology Electrical Engineering Department

LAB SESSION 04
OBJECTIVE:
To utilize the USART (Universal Synchronous / Asynchronous Receiver /Transmitter) of ATmega328P for
transmitting and receiving data though asynchronous serial communication with PC

LAB OUTCOMES:
By the end of this lab, you should be able to:
1) Recognize the basics of serial communication protocol; baud-rate, stop bit, data bits, parity etc. and
the importance of required connectors (RS-232)
2) Identify the AVR ATmega328P pins associated with the USART
3) Identify the purpose of different fields of USART registers
4) Program ATmega328P for initializing the USART with given baud-rate
5) Program ATmega328P in C-language to establish serial communication with PC
6) Test and verify data (character, string, integer and float) transmission and reception for given
conditions using a Serial Terminal Emulator like TeraTerm

“The single biggest problem in communication is the illusion that it has taken place.”
– George Bernard Shaw

BACKGROUND:
Microcontrollers are provided with ability to communicate with external devices like computer, other
micro-controllers and peripherals. This communication is done through different protocols to allow
microcontrollers to send and receive data. ATmega328P is provided with USART (Universal
Synchronous/Asynchronous Transmitter/Receiver). In this lab, we will be exploring Asynchronous
Transmitter and Receiver (UART). It is not only used as a communications link to external device but
also as a debugging port to send status messages. This is one of the 3 communication options that can be
established with ATmga328P. The other two are SPI and I2C which will be explored later. Before
discussing the working of relevant pins and registers, we first need to understand the different types and
basics of communication protocols.

Figure 1: Serial Communication of Microcontroller with PC for Troubleshooting


1
Embedded Systems Lab Lab 04 Serial Port Programming of AVR
NED University of Engineering & Technology Electrical Engineering Department

Basics of Serial Communication


Parallel Vs Serial Data Transfer: Computers transfer data in two ways: parallel and serial.

Figure 2: Serial and Parallel Data Transfer Representation


In parallel data transfer, the data is sent one byte (or multiple bits) at a time. For this multiple wires are
needed and this is suitable for a short-distance like printers. In serial communication, the data is sent one
bit at a time. It needs lesser number of wires. It is suitable for longer distance communication and is cheaper.
Synchronous vs Asynchronous Communication: Serial data communication can be, asynchronous or
synchronous. The synchronous method transfers a block of data (characters) at a time, whereas the
asynchronous method transfers a single byte at a time. In Synchronous transmission a common clock is
shared by the transmitter and receiver to achieve synchronization while data transmission. In asynchronous
interface, it does not have any separate clock signal. Only the data is sent on the lines and the transmitter
must send the data at an agreed upon rate and in a defined manner.
Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART) is a configurable
peripheral of ATmega328p which supports both Synchronous (SPI) and Asynchronous (Serial)
communication protocols. In our case we will be dealing only with the asynchronous communication.
Asynchronous Communication Protocol
Baud Rate – Data Transfer Rate: The rate of data transfer in serial data communication is stated in bps
(bits per second). Another widely used terminology for bps is baud rate. In the context of microcontroller
USART programming, we will be using the terms bps and baud interchangeably. The maximum data
transfer rate is limited by the hardware ports but the transmitter and receiver must agree on the same baud
rate.
Data Framing: In data framing for asynchronous communications, the data, such as ASCII characters,
are packed between a start bit and a stop bit. The start bit is always one bit, but the stop bit can be one or
two bits. In modern PCs, however, the use of one stop bit is standard. The start bit is always a 0 (low),
and the stop bit(s) is 1 (high). For example, look at Figure in which the ASCII character “A” (8-bit
binary 0100 0001) is framed between the start bit and a single stop bit. Notice that the LSB is sent out
first. There are a total of 10 bits for the character: 8 data bits for the ASCII code, and 1 bit each for the
start and stop bits.

Figure 3: Framing ASCII ‘A’ (41H) with a stop-bit (1) and a start bit (0)
2
Embedded Systems Lab Lab 04 Serial Port Programming of AVR
NED University of Engineering & Technology Electrical Engineering Department

Parity Bit: UART chips allow programming of the parity bit for odd-, even-, and no-parity options. It is a
single bit added to the data frame to maintain data integrity.

ATmega328P Serial Port Pins and Connection with PC


ATmega328P has one serial port. Pin 2 and pin 3 of ATmega328P serve as USART0 transmitter (TxD)
and receiver (RxD) pins. Arduino UNO pin 0 and 1 are therefore marked as TX and RX. These are the
same pins on the chip as I/O ports PD1 and PD0. This means that applications that use the USART0 cannot
also use these two bits in Port D. It is not necessary to set any bits in the DDRD register in order to use the
USART0.
If LEDs placed on the RX and TX pins will flash, they indicate the transmission of data.

Figure 4: Connection of ATmega328P RXD and TXD pins with Arduino UNO for UART

Figure 5: Placement of RX and TX pins and corresponding LEDs with ATmega328P and
ATmega16 on Arduino UNO board
To establish communication between microcontroller (USART pins) with PC, the PC must have a
communication port to support serial data transfer. These are called COM ports. A COM port is simply an
I/O interface that enables the connection of a serial device to a computer. COM ports are also referred to as
serial ports. They are asynchronous interfaces that can transmit one bit of data at a time when connected to
a serial device.

Figure 6: RS-232 Serial Port (DB9)


The AVR serial port can be connected to the COM port of a PC for serial communication. However, USB
interfaces have largely replaced the RS232 serial ports seen in the past as a faster way of performing serial

3
Embedded Systems Lab Lab 04 Serial Port Programming of AVR
NED University of Engineering & Technology Electrical Engineering Department

data transmission. In the absence of a COM port, a COM-to-USB converter module is needed. You can
read more about it here.
Luckily, the Atmega16U2 incorporated on the UNO (R3) board acts as a USB-to-serial converter for serial
communication using USB com drivers. On PC, a software applications is used with it to send data to or
display the received data from the board.

ATmega328P Serial Port Registers


1) UDR0 – USART Data I/O Register
This register is used to hold data to be sent or received.
 The USART Transmit Data Buffer Register and USART Receive Data Buffer Registers share the same
I/O address referred to as USART Data Register or UDR0.
 For data transmission, TXB will be the destination for data written to the UDR0 Register location.
 For data reception, reading the UDR0 Register location will return the contents of RXB.

2) UCSR0A – USART0 Control and Status Register A


[7] [6] [5] [4] [3] [2] [1] [0]
UCSR0A
RXC0 TXC0 UDRE0 FE0 DOR0 PE0 U2X0 MPCM0
Bits Function
RXC0 USART Receive Complete
Indicates receive buffer register (RXB) status.
1: Unread data present in receive buffer
0: Receive buffer is empty
TXC0 USART Transmit Complete
1: Entire frame in transmit shift register has been transmitted, no new data
available in transmit data buffer register (TXB)
UDRE0 USART Data Register Empty
1: Transmit data buffer register is ready to receive new data
0: TXB is not empty. Don’t write to UDR if UDRE0 is 0
FE0 Frame Error
1: Frame error occurred in receiving next character in receive buffer
Frame error is detected if first stop bit of character in RXB is 0
DOR0 Data Over-Run
1: Indicates data over-run
Data over-run occurs if RXB and receive shift-register are full and new start bit is detected.
PE0 USART Parity Error
1: Indicates parity error in the receive buffer if Parity Checking UPM01 is enabled.
U2X0 Double the USART Transmission Speed
1: It doubles the transfer rate for asynchronous operation (baud rate divisor
becomes 8 instead of 16)
MPCM0 Multi-processor Communication Mode
Enables the Multi-processor Communication mode. Transmitter is unaffected by it.
The default value of UCSR0A to 0x20 = 0b 0010 0000

4
Embedded Systems Lab Lab 04 Serial Port Programming of AVR
NED University of Engineering & Technology Electrical Engineering Department

3) UCSR0B – USART0 Control and Status Register B


[7] [6] [5] [4] [3] [2] [1] [0]
UCSR0B
RXCIE0 TXCIE0 UDRIE0 RXEN0 TXEN0 UCSZ02 RXB80 TXB80
Bits Function
RXCIE0 RX Complete Interrupt Enable
1: Set 1 to enable the interrupt on the RXC flag in UCSR0A
TXCIE0 TX Complete Interrupt Enable
1: Set to enable the interrupt on the TXC flag in UCSR0A
UDRIE0 USART Data Register Empty Interrupt Enable
1: Set to one enables interrupt on the UDRE0
RXEN0 Receiver Enable
1: Enables the USART Receiver
0: Disables the Receiver. Flushes the RXB.
TXEN0 Transmitter Enable
1: Enables the USART Transmitter
0: Disables the Transmitter; effective once transmission is complete.
UCSZ02 Character Size
The UCSZn2 bits combined with the UCSZn1:0 bit in UCSR0C sets the number of data
bits (Character SiZe) in a frame the Receiver and Transmitter use.
RXB80 Receive Data Bit 8
It is the ninth data bit of the received character when operating with serial frames with nine
data bits. Must be read before reading the low bits from UDR0.
TXB80 Transmit Data Bit 8
It is the ninth data bit in the character to be transmitted when operating with serial frames
with nine data bits. Must be written before writing the low bits to UDR0.

RXEN0, TXEN0 and UCSZ02 are most important here for enabling the receiver, and transmitted and to
set the character size. The interrupt related bits are not needed now. Its default value is 0x00.
4) UCSR0C – USART0 Control and Status Register C
[7] [6] [5] [4] [3] [2] [1] [0]
UCSR0C
UMSEL01 UMSEL00 UPM01 UPM00 USBS0 UCSZ01 UCSZ00 UCPOL0
Bits Function
UMSEL01 USART Mode Select Bits (UMSEL01-00)
00: Asynchronous USART
UMSEL00 01: Synchronous USART
UPM01 USART Parity Mode (UPM01-00)
These enable and set type of parity generation and check. If enabled, the Transmitter will
automatically generate and send the parity of the transmitted data bits within each frame.
The Receiver will generate a parity value for the incoming data and compare it to the UPM0
UPM00 setting. If a mismatch is detected, the UPE0 Flag in UCSR0A will be set.
00: Disabled
10: Enabled, Even Parity
11: Enabled, Odd Parity
USBS0 USART Stop Select Bit
Selects number of stop bits to be inserted by the Transmitter.
0: 1-bit Stop bit
1: 2-bit Stop bits

5
Embedded Systems Lab Lab 04 Serial Port Programming of AVR
NED University of Engineering & Technology Electrical Engineering Department

UCSZ01 Character Size (UCSZ01:00)


The UCSZ01:00 bits combined with the UCSZ02 bit in UCSR0B sets the number of data
bits (Character SiZe) in a frame the Receiver and Transmitter use.

UCSZ00 [UCSZ02,USCZ01,UCSZ00] Character Size


000 5-bit
001 6-bit
010 7-bit
011 8-bit
111 9-bit
UCPOL0 Clock Polarity
0: The bit is cleared when asynchronous mode is used.
In synchronous mode, it is useful for setting relation between data and clock.
Correct initialization of all the UCSR0C bits is important in setting communication protocols. Its default
value is 0x06 = 0b000 0110.
5) UBRR0 – USART0 Baud Rate Register
It is used to set baud-rate by specifying the pre-scalar in its 12 bits.

UBRR[15:12] The 4 bits, reserved, are set to 0. The remaining 12 bits UBRR[11:0] contain the USART0
baud rate (pre-scalar). The UBRR0H contains the four most significant bits, and the UBRR0L contains the
eight least significant bits of the USART0 baud rate.
For required baud rate ‘BAUD’, and oscillator frequency fosc, the value for UBRR0 is calculated by;
𝑓𝑂𝑆𝐶
UBRR0 = −1
16 × 𝐵𝐴𝑈𝐷
For a 16MHz clock, the required values of UBRR0 register are given in the Table below for different baud-
rates. Note: U2X0 is set 0 here. The baud-rates can be doubled by setting U2X0 high for same UBRR0
values. The formula can be applied for verification.
Table 1: UBRR0 Values for Different Baud Rates
Baud Rate (bps) UBRR0
2400 416 = 0x01A0
4800 207 = 0x00CF
9600 103= 0x0067
14400 68 = 0x0044
19200 51 =0x0033
Serial Terminal Emulator – TeraTerm
COM Port (communication port) is the original, yet still common, name of the serial port interface on PC-
compatible computers. It can refer not only to physical ports, but also to emulated ports.
Serial terminal emulators are software applications that replicate physical COM ports. The virtual serial
ports are fully compatible with operating systems and applications and are treated in the same way as a real
port. These are used for the serial communication between the host computer and an embedded system
6
Embedded Systems Lab Lab 04 Serial Port Programming of AVR
NED University of Engineering & Technology Electrical Engineering Department

(Target). It is mainly used as a user interface for debugging embedded system. It is also used for sending
commands, displaying result, loading firmware, logging result, etc.
Tera Term and PuTTY are famous terminal emulator applications. In this lab, we can use Tera Term. It is
an open-source, free, software implemented terminal emulator (communications) program.
1) Download Tera-Term using: https://filehippo.com/download_tera-term/
2) Type Tera Term in Windows search to open it. You will be able to select Serial once you connect
your device to PC USB port (connect Arduino UNO). The Serial and Port options will be enabled.

Figure 7: Tera Term Connection


3) Go to Setup >> Serial port… It allows you to select Baud Rate, Stop Bit, Data Bits, and Parity etc.

Figure 8: Tera Term Serial Port Settings


4) For writing to Serial Terminal window (send character from PC to Microcontroller), turn on echo. Go
to Setup >> Terminal and select Local echo.

Figure 9: Tera Term Terminal Setup


5) Save the settings for later use. Select Setup > Save setup.
7
Embedded Systems Lab Lab 04 Serial Port Programming of AVR
NED University of Engineering & Technology Electrical Engineering Department

ATmega328P Serial Port Programming in C


Programming for USART Initialization
The USART has to be initialized before any communication can take place.

The initialization process consists of the following steps. Relevant Register Values (example) & C-Code

1. Setting-up as Transmitter and / or Receiver


UCSR0B=0b00011000 or,
Enable the TxD and (or) RxD pins using TXEN0 UCSR0B =(1<<TXEN)| (1<<RXEN)
and (or) RXEN0 bits of UCSR0B.
2. Setting-up Frame Rate
UCSR0C=0x06 or,
Load UCSR0C to indicate asynchronous mode with UCSR0C=0b00000110
8-bit data frame, no parity, and one stop bit
UBRR0 = 0x67
3. Set the baud-rate using UBRR. For baud-rate of 9600 bps at 16MHz crystal
frequency at U2X0 =0.
 Subroutine for USART initialization
For ease, we create a subroutine for USART initialization to avoid repeating these lines of code again and
again.
void usart_init (void)
{
UBRR0=0x67; //set pre-scalar to configure baud rate (9600)
UCSR0A &= ~ (1 << U2X0); //Single Speed U2X - 0 (can be set to 1)
UCSR0B = (1 << RXEN0) | (1 << TXEN0); // enable transmitter and receiver
// Async mode, parity mode = disabled, 1 stop bit, character size = 8 bit
clock polarity = 0 for async communication
UCSR0C = (0<<USBS0) | (1 << UCSZ01) | (1 << UCSZ00);
}

Programming for Data Transmission

To program the USART as Transmitter, follow the steps: Relevant Register Values or C-Code

1. Initialize the USART. Call usart_init( );


while (!(UCSR0A & (1<<UDRE0)))
2. Monitor the UDRE bit of UCSR0A to make sure { };
UDR is ready to accept byte to transmit. An empty while loop that waits to check UDR is
empty (indicated by UDRE bit).
UDR0=ch;
3. Write the character to be transmitted to the UDR. Where, ch is an unsigned char for example ‘A’.
4. Wait for complete frame transmission. while(!(UCSR0A &(1 << TXC0))){};
5. To transmit the next character, go to Step 2.
 Subroutine for transmitting character
void usart_putChar(unsigned char data)
{
while (!(UCSR0A & (1 << UDRE0))) {}; //wait for data register to be empty
UDR0 = data; //write data
while (!(UCSR0A & (1 << TXC0)) ) {}; //wait for complete frame transmission
}

8
Embedded Systems Lab Lab 04 Serial Port Programming of AVR
NED University of Engineering & Technology Electrical Engineering Department

Programming for Data Reception

To program the USART as Receiver, follow the steps: Relevant Register Values or C-Code

1. Initialize the USART. Call usart_init( );


While (! (UCSR0A & (1<<RXC0))) ;
2. Monitor the RXC flag bit of the UCSR0A register to An empty while loop that waits for data to be
see if an entire character has been received yet. received. Loop ends when RXC bit turns high as
the given condition is not equal to 0.
ch=UDR;
3. When RXC is high, read the UDR as it has received
Where, ch is an unsigned char type variable to
the byte. store the received character.
4. To receive the next character, go to Step 4.
 Function for receiving character
char usart_getChar()
{
char data;
while ( !(UCSR0A & (1 << RXC0))) {}; // wait for data to receive
data = UDR0;
return data;
}

EXAMPLES
The tested asynchronous communication is polling based and not interrupt based.
Example # 1: Transmitting a Character from ATmega328P to PC through UART
The following code transmits ‘A’ repeatedly with a delay of 1 sec. Note that only one character is sent at a
time. The following example uses usart_init( ) and usart_putChar( ) from the listed 3 sub-routines therefore,
these sub-routines must be defined in the main.c file.

Figure 10: Code for Example#1


See the character ‘A’ is written in quotes. You can write its ASCII code (65). In that case, don’t use ‘ ’ as
we want to transmit a single character ‘A’ through the ASCII code and not the integer 65 (which are 2
characters).
Now, you are able to do Task 1 and Task 2.

9
Embedded Systems Lab Lab 04 Serial Port Programming of AVR
NED University of Engineering & Technology Electrical Engineering Department

Example # 2: Transmitting and Receiving Strings, Integers and Floats


For transmitting a string of characters (instead of a single character), we can write a C subroutine that
transmits one character at a time using the previously described usart_putChar( ). Similarly, to receive a
string of characters, we can makes use of a buffer to hold the received characters in the form of a string.
Look at the following subroutines.
 Subroutines for receiving and transmitting strings
//subroutine for transmitting a character string
void usart_putString(char* StringPtr)
{
while(*StringPtr != 0x00)
{
usart_putChar((unsigned char)*StringPtr);
StringPtr++;
}
}

//subroutine for receiving a character string


void usart_getString(volatile char buffer[], uint8_t len)
{
uint8_t i =0;
for( i = 0; i < len; i++)
{
buffer[i] = usart_getChar();//save the received character
}
buffer[i]=0; //making the received string null terminated, last byte 0

Type Casting
Converting one datatype into another is known as type casting or, type-conversion. To transmit integer or
float data through USART, we first need to convert them into string. There are different approaches to do
so, one simple technique is shown here.
 Integer to String:
The itoa(num,buffer,10) function coverts the integer num into a null-terminated character string. The
string is placed in the buffer passed, which must be large enough to hold the output. The last input shows
number format 10 for decimal. Include <stdlib.h> for itoa( ).
 Float to String:
The dtostrf (val,width,prec,s) function converts the double value passed in val into an ASCII
representation that will be stored under s. Conversion is done in the format '[-]d.ddd'. The minimum field
width of the output string (including the possible '.' and the possible sign for negative values) is given in
width, and prec determines the number of digits after the decimal sign. The dtostrf() function returns the
pointer to the converted string s.

The example code given here shows transmission of strings, float and integers by utilizing the subroutines
and functions discussed above. You can observe that a string is received from PC to AVR too.
10
Embedded Systems Lab Lab 04 Serial Port Programming of AVR
NED University of Engineering & Technology Electrical Engineering Department

Figure 11: Code for Example 2-Transmitting Strings, Float and Integer Data Types
Header File usart.h
For ease, you can include the header and source files (usart.h and usart.c) provided with the manual. Utilize
its simple functions for transmitting and receiving data or use the sub-routines discussed above in your code
to complete the given lab tasks.

LAB TASKS
TASK 1: To test Example 1 for transmitting a character serially at baud-rate of 9600 with 1
stop bit using ATmega328P USART
Test the Example 1 code using Arduino UNO. After building the given code, program the ATmega328P.
Now, disconnect and reconnect Arduino UNO with PC port. Open Serial Terminal Emulator (Tera Term).
Make connection with the required settings and observe the serial terminal. You should see the data
transmitted by AVR (received by the PC) on serial terminal.

1. Is there any impact if you select a different baud rate in Tera Term without changing the baud rate
initialized in the ATmega328P code? Are you able to correctly transmit the characters when
microcontroller and PC work at different baud rate?
________________________________________
2. Add two more lines to the code and comment on the result.
 usart_putChar(65)
 usart_putChar(‘65’)

11
Embedded Systems Lab Lab 04 Serial Port Programming of AVR
NED University of Engineering & Technology Electrical Engineering Department

TASK 2: To program ATmega328P for controlling the status of LED based on the received
character
Modify the previous code to make the microcontroller receive a character sent by PC. If the received
character is ‘A’, turn on the on board LED otherwise turn it off. The data should be received at baud-rate
of 14400 with 1 stop bit.
TASK 3: To transmit the analog voltage across a potentiometer read by the ATmega328P
ADC to PC
Extend the Task 2 of Lab 03 where you used ADC module to measure the voltage across potentiometer.
Send (transmit) the following through USART of the microcontroller to the PC serial terminal.
1) The 10-bit ADC output (in range of 0 to 1023)
2) The analog voltage across potentiometer in Volts

Pay attention to the data-type. You may use any suitable baud rate of your choice.
Vary the voltage and observe the values. Verify the analog voltage reading by ADC module and
transmission through the USART by comparing voltmeter reading and values displayed by Tera Term.
Sample Output:

**********10-bit ADC************
**********5V Reference Voltage****
*****Voltage across Potentiometer***

ADC Value: 307


Output Voltage: 1.5 Volts

ADC Value: 205


Output Voltage: 1.01 Volts

You might also like