USART Serial Communication

This project shows how to control an I/O pin through serial communication from a PC to the PIC® Microcontroller. The project uses the built-in Universal Synchronous/Asynchronous Receiver Transmitter (USART) on the PIC® Microcontroller.

blockpic.png

Step by Step Instructions

Using the MPLAB® Code Configurator (MCC), this project shows how to use a terminal program running on a PC to control a Light Emitting Diode (LED) through serial commands. The PC sends data to the Enhanced Universal Synchronous Asynchronous Receiver Transmitter (EUSART) on a PIC16F1709 device that has an LED connected to its RB7 output pin. The project is built on a PICDEM™ Lab II development board and uses MCC along with the MPLAB XC8 C compiler to create the software for the project.

uartsch.png



The project uses:


To follow along with these steps, MPLAB X IDE should be open and the programmer/debugger connected to both the computer and the development board. The setup is described in the "Setup and Installation" page of this training module. You should see a screen similar to the one below to move on to step 1:

mplabx.png

1

The PICDEM Lab II board needs to be setup for this project. The connections are shown in the picture and described below. Most of the components including PIC16F1709 MCU and wires are included with the PICDEM Lab II kit. An MCP2221 breakout board is built in.

Note: You can build this on any protoboard but you will need to add an MCP2221 Breakout Module.

Jumpers:

  1. J3 Jumper in place for 5 V from USB connection at J18
jumper.jpg

Connections:

  1. Connect J8 5 V to Red Power Rail of Breadboard
  2. Connect J8 GND to Blue Ground Rail of Breadboard
  3. Connect the 5 V power rail to J19-Vdd pin
  4. Connect 5 V power rail to USB UART interface connector J4 pin 2 (right side)
  5. Connect UART TX interface connector J4 pin 1 (right side) to J20 pin 11
  6. Connect UART RX interface connector J4 pin 6 (left side) to J20 pin 13
  7. Insert LED into breadboard Anode F-21, Cathode F-25
  8. Insert 220 Ω resistor between LED Cathode J-25 and GND Blue Gnd Rail
  9. Connect wire between LED Anode (Breadboard G-21) to J19 pin 10.
  10. 10k Resistor for MCLR function between J19 pin Vdd3 and J19 pin 4
  11. Insert PIC16F1709 into the 20-pin socket U3
  12. Connect mini USB (J18) to PC USB Port
  13. Connect PICkit 3 to ICSP3 connector and then into a second USB port on your PC

Optional:

Connect a wire to J19 pin 4 and leave it unconnected at the other end. This can be used for resetting the PIC16F1709.

UART.png

2

Create a new "stand-alone" project in MPLAB X for a PIC16F1709. Instructions are below if this is your first project.

3

Open MCC under the Tools>Embedded menu of MPLAB X.

mcclaunch.png

4

Select the peripherals for your project.
In this project, these peripherals will need to be selected:

  • System Module
  • Interrupt Module
  • Pin Module
  • EUSART

The System, Interrupt, and Pin Module are all included by default, but the EUSART peripheral must be selected from the Device Resources area.

The result should look like the picture below:

proj12per.png

5

Open the Pin Manager and then click on the PORTB port 4 (RB4) blue lock symbol for the Transmit Output (TX), PORTB port 6 (RB6) for the Receive Input (RX) and then PORTB port 7 (RB7) for the LED output pin. Each one will turn green to lock it in when selected. It should look like the picture below when completed:

proj12io.png

6

Close the Pin Manager. Now the GPIO peripheral needs to be setup. The center section of the MPLAB X screen should show RB7 listed on the I/O chart.

gpio.png
  1. RB7 will be an output and control the LED. Check the Output box to make the pin an output. Also, check the Start High box to make the LED initialize in the "on" state.
  2. Rename the RB7 pin to "LED" by clicking on the Custom Name box and then typing "LED" to replace the default name.

Note: If the GPIO window doesn't appear, click on the GPIO name in the Project Resources list. It should be highlighted in blue when selected.

proj12gpio2.png

7

The System needs to be set up next. Click on the System name in the Project Resources list. It should be highlighted in blue when selected.

system.png

The System section will appear. In this section, the Oscillator settings and the configuration settings are selected.

Oscillator

  1. Select FOSC from the drop-down menu for the System Clock Select.
  2. Select the 8 MHz_HF selection from the Internal Clock drop-down menu.
  3. Check the PLL Enabled box.

This enables the internal 8 MHz internal oscillator as the system clock and with the PLL enabled gives the system a 32 MHz clock.

oscillator.png

8

EUSART needs to be setup. Click on the EUSART label in the Project Resources menu to make the EUSART setup screen appear.

eusart.png

The steps below will setup EUSART:

  1. Check the Enable USART box.
  2. Check the Enable Transmit box.
  3. Set the baudrate to 115200.
  4. Set the Transmission Bits to 8.
  5. Set the Reception Bits to 8.
  6. Select the Non-Inverted dropdown.
  7. Check the Enable Continuous Receive box.
  8. Check the Enable EUSART Interrupts box.
  9. Check the Redirect STDIO to USART box.
  10. Set Software Transmit Buffer Size to 8.
  11. Set Software Receive Buffer Size to 8.

The window should look like the one below after the setup:

usartset.png

9

Click on the Generate Code button to have MCC create the software libraries for this project.

generate.png

10

The project will now have both generated Header Files and Source Files. It should also have a generated main.c file.

Note: MCC may offer to generate a main.c file. Click YES to allow it to complete that task.

proj12file.png

Double click on the main.c file to open it up in the Editor window.

mainfile.png

11

There are two files that need to be modified for this project: main.c and tmr1.c. These are the main code file and the Timer 1 code file. Each are modified as described below:

main.c

The default main.c file automatically has the SYSTEM_Initialize() function defined. This will call all the initialization routines that were created by the MCC and is defined in the mcc.c file. These include:
OSCILLATOR_Initialize();
PIN_MANAGER_Initialize();
EUSART_Initialize();

main.c also requires a few lines to be uncommented for the interrupt to work properly. To enable the interrupt to work, Global Interrupts and Peripheral Interrupts need to be enabled. MCC already has the control commands in the default main.c file, they are just commented out with two forward slashes (//). The forward slashes need to be removed to enable these lines of code.

    // initialize the device
    SYSTEM_Initialize();

    // Enable the Global Interrupts
    INTERRUPT_GlobalInterruptEnable();

    // Enable the Peripheral Interrupts
    INTERRUPT_PeripheralInterruptEnable();

The main loop requires two additional lines: UART_Demo_Initialize() and UART_Demo_Command_INT(). These are both defined in a file UART_Demo.c that needs to be created. That will be done next.

UART_Demo_Initialize();

while (1)
    {
          UART_Demo_Command_INT();
    }
maincode6.png

UART_Demo.c

The UART_Demo.c file will be created using MPLAB X IDE to create C source file capability. Right click on the Source Files folder in the project and select New > C Source File.

Note: If you don't see a "C Source File" option then make on under File>New File from the menu. After that first time, then the right click option will be available.

createc1.png

Then select a name for the file, in this case, we use the name "UART_Demo.c".

createc2.png

This will create a blank file that is added to the project. The next step is to add the code required.

The code begins with an include for the MCC generated files. This is placed at the top of the file, followed by a comment block to define the file. (This is optional and can also contain any information you want to add to the file.)

An 8-bit variable is required for receiving the data so a "char" variable is defined under the name "temp".

#include "mcc_generated_files/mcc.h"

/*
                         UART_Demo.c
 */

unsigned char temp;

The UART_Demo.c file also contains the UART_Demo_Initialize(void) function that sends a few lines of text to the terminal screen. These lines of text define the project and some instructions for controlling the LED.

void UART_Demo_Initialize(void) 
{

    printf("\rPICDEM LAB II - Date 08/11/2015\r\n");  
    printf("UART Communications 8-bit Rx and Tx\r\n\n");
    printf("Keyboard Type H : LED ON   Type L: LED OFF \r\n\n");

}

In addition, the UART_Demo_Command_INT(void) function is created for reading the input from the terminal, responds with a message and then controls the LED. The read is done with the EUSART_Read() function and write is done with EUSART_Write() function. Both of these are defined in the eusart.c file that MCC generated. The code uses a Switch-Case statement to control the LED based on the character received. An "H" lights the LED and an "L" shuts it off.

void UART_Demo_Command_INT(void) 
{    
    if(eusartRxCount!=0) 
    {   

    temp=EUSART_Read();  // read a byte for RX

    EUSART_Write(temp);  // send a byte to TX  (from Rx)

    switch(temp)    // check command  
    {
     case 'H':
     case 'h':
        {
            LED_SetHigh();
            printf(" -> LED On!!      \r");             
            break;
        }
     case 'L':
     case 'l':
        {
            LED_SetLow();
            printf(" -> LED Off!!     \r");   
            break;
        }
     default:
        {
            printf(" -> Fail Command!! \r");            
            break;
        }       
    }
    }
}

Finally the UART_Demo.c file is ended with a comment block indicating the end of the file.

/**
 End of File
 */

12

Click on the Build Project icon (the hammer) to compile the code and you should see a "BUILD SUCCESSFUL" message in the output window of MPLAB X.

Main_Build_Project.png
BUILD SUCCESSFUL (total time: 7s)

13

Make sure your project has the programming tool selected (part of Step 1 above) and connect power to your development board.

The PICkit 3 has limited power capability so we recommend powering the board separately.

The ICD 3 can power a development board, but for simplicity, we recommend powering the board separately.

The REAL ICE cannot power the development board so powering the board separately is required.

Click on the Make and Program Device icon. This will build the project again and launch the programmer. You should see a series of messages in the Output window and, if successful, it will end with a "Programming/Verify complete" message.

Main_Program_Target_Project.png

Output Window:

Connecting to MPLAB PICkit 3...
Firmware Suite Version.....01.34.11
Firmware type..............Enhanced Midrange

Target detected
Device ID Revision = 6

The following memory area(s) will be programmed:
program memory: start address = 0x0, end address = 0x7ff
configuration memory
Device Erased...

Programming...
Programming/Verify complete


If it's the first time the programmer is connected to the board, the programming tool may need to download the proper operating firmware for the exact device. You may see a series of messages if this occurs. This should only happen once.

Downloading Firmware…
Downloading bootloader
Bootloader download complete
Programming download…
Downloading RS…
RS download complete
Programming download…
Downloading AP…
AP download complete
Programming download…
Firmware Suite Version…..01.34.11
Firmware type…………..Enhanced Midrange

14

The Terminal window needs to be set up on your PC. This project description will use the open-source CoolTerm but any terminal application should work. The PICDEM Lab II has an MCP2221 USB to UART convertor on board. You may need to install a USB driver for this to work with your PC. The driver installation instructions can be found on the MCP2221 product page under the "Documents" section.

The first step is to establish communication settings. Click on the Options menu to open the Serial Port Options window. Select the USB port from the drop-down menu, then set the communication to 115200 baud and 8N1 format as seen below.

termsetup.png

Close the Serial Port Options window and then click on the Connect button and the communication should appear as below. You can now control the RB7 LED according to the the H or L sent from the terminal window.

termcontrol.png

Note: If you don't see the message header, then use the wire connected to J19 pin 4 and connect it to ground briefly to reset the device. This should resend the message header to the terminal.

15

The project can be closed in MPLAB X. The project is saved automatically when it is built but any changes to files or configuration may ask to be saved before the project is closed. The project can be closed under File Menu>Close Project.

closeproject.png

Download

If you have any problems with your project, the completed MPLAB X project file can be downloaded from the link below.

Files
© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.