How to Send and Receive Data From UART in dspic30f and dspic33f

Updated on June 13, 2017
alikhan3 profile image

The author completed his final year engineering project with the dsPic micro-controllers, gaining extensive insight in these devices.

UART is the most commonly used communication protocol in microcontrollers due to its simplicity, easy implementation, and minumum hardware requirements.

This tutorial and example code implementation will walk you through the process of achieving successful UART communication between a dspic micro-controller and PC.

Things Needed for UART Communication

The first step should be to gather all the required things necessary for UART communication. The list below summarizes these hardware and software requirements:

  1. UART communication software for PC

    Option 1:

    I would prefer the Arduino IDE for this purpose. The Arduino IDE has a serial monitor which can be used to monitor sent data from the micro-controller. It also has an excellent graphical monitor to plot the received data. The same IDE can be used to send serial data also.

    Option 2:

    The PicKit™ tool also has a serial monitor to send and receive data but it does not have a serial plotter. It also does not supports high baud rates up to 115000 which the Arduino IDE can support.

  2. USB to serial Converter / Transciever

    Option 1:

    The PL2302 USB to TTL converter can be very conveniently used as the transceiver between the USB serial port of the PC and the uart TX/RX pins of the micro-controller. It is very cheap and readily available on the internet and local electronic stores (at least in my area).

    Option 2:

    The programming tool of the Pic micro-controllers, the PicKit™ also has an inbuilt UART transceiver. Advantage of using this is that you will not need to purchase any extra hardware as PicKit will do the job. (Assuming that you already have it since you are programming the Pics.) Downside is that you cannot put the PicKit inside your finished projects as you might need it for later use. In this case the USB to ttl converter is a better option.

    Option 3:

    A UART to RS232 conversion circuit might be fabricated with the help of MAX232 ICs and RS232 cable. ICs are usually cheap but it will cost you more time to fabricate the circuit. This used to be the legacy solution before the advent of usb to ttl converter modules.

  3. dsPic microcontroller and its programmer

    A pic device and its programmer to load the code.

  4. A few jumper wires.

    To make the required connections between the TX/RX pins of the micro-controller and the USB to TTL converter

  5. USB extension cable (optional).

    In case you need to wire the usb to ttl converter far from your PC when you are finally assembling your project.

PL2302 USB to ttl converter module.
PL2302 USB to ttl converter module.

After going through the list of things required you can proceed with the steps 1 through X below

1) Install the Required Software and Drivers

Install the serial monitor of your choice on your PC as I stated earlier I prefer the Arduino IDE.

If Using USB to TTL Converter:

You will need to download its driver and install them before you can make the module to work. The drivers are available on the Prolific Systems website and elsewhere on the internet. Make sure the drivers you download are compatible with Windows 7, otherwise it will not work. Search for a separate tutorial for driver installation if you are having problems.

After installing the driver you must test the TTL converter to make sure it is working properly. It is recommended that you do not proceed ahead before testing the converter.

To test the converter:

  1. First install the required driver and reboot the system.
  2. Plug in the converter module and the PC should notice a new device connection.
  3. Short the TX and RX pins on the TTl converter with the help of a jumper.
  4. Open Arduino IDE and select the correct serial port to which the converter is connected.
  5. Send any data over the serial monitor.
  6. If you receive the same sent data back in the serial monitor then the module is working correctly.

If Using PicKit:

Just dwonload the Pickit program and connect the PicKit device to your PC.

Short the TX and RX pins with a jumper or wire to test the module.
Short the TX and RX pins with a jumper or wire to test the module.

2) Wire the Connections.

For TTL Converter:

Pin Name on the Converter
Corresponding PIN name on the Micro-controller
TX
RX
RX
TX
GND
GND, Vss
5 V (optional)
Vdd, Vcc
How to connect the PL2303 USB to TTL converter with the dspic micro-controller
  • Pin names are printed on the back side of the converter.
  • Exact pin numbers corresponding to their pin names must be found from the datasheet as they change from device to device.
  • A 5 V or 3.3 V supply from the converter may optionally be used to power the micro-controller.
  • It is mandatory to make the ground of the controller and converter common.

For PicKit:

The PicKit has a 6 pin connector with pin number 1 marked with a white arrow on the device.

Pin number on the 6-pin header
Corresponding Pin Name on the MCU
2
Vcc, Vdd
3
Gnd, Vss
4
TX
5
RX
  • Additionally the wiring schematic is also shown in an inset inside the PicKit's UART tool.

3) Send Data from dspic through UART

After wiring the connections and testing the the TTL Converter module to make sure it has started working, upload the code for sending data through UART.

  • Text can be sent using the printf() function in the stdio.h library.
  • Variables can be sent by first converting them into array and then using printf() to print them.

Example Code to Send Data through UART

#define FCY 30000000

#include <xc.h>
#include <stdio.h>
#include <delay.h>
#include <libpic30.h>
#include <math.h>
#include <p30F4011.h>


_FOSC(CSW_FSCM_OFF & FRC_PLL16);  // Fosc=16x7.5MHz, i.e. 30 MIPS
_FWDT(WDT_OFF);                  // Watchdog timer off
_FBORPOR(MCLR_DIS);

void UART_Init ( void )
{
    _TRISF3 = 0;           //Look for the exact TX/RX pins of your pic device
    _TRISF2 = 1;           //TX pin must be set as output port and RX input
    
    
    U1BRG = 7;             // 115000 baud rate @ 30 MIPS
    U1MODEbits.UARTEN = 1; // Enable UART
}

int main( void )
{
    UART_Init();

    while( 1 )
    {
         //To print a variable
         sprintf(array,"%d",variable);
         printf(array);
         printf("\r\n");

         //To print text
         printf("Greetings from Pakistan\r\n");

         __delay_ms(1000);
    }
}

4) Receive Data through UART in dspic

To receive data from UART you will have to utilize a UART receive interrupt that will trigger every time a data packet is received in the UART receive registers (U1RXREG). This data is transferred to another variable and the receive buffer is cleared if full. You can use the following example code.

  • To make sure that the interrupt is actually triggering, an LED has been connected at Port D0 which will blink once when the interrupt is triggered.
  • If the LED blinks immediately after you send some data from the serial monitor, assume the code is working correctly.
  • The value of variable 'data' might also be checked in the debug mode.

Example Code to Receive Data from UART

#define FCY 30000000

#include <xc.h>
#include <stdio.h>
#include <libpic30.h>
#include <uart.h>
#include <delay.h>
#include <p30F4011.h>
 
// Configuration settings
_FOSC(CSW_FSCM_OFF & FRC_PLL16); // Fosc=16x7.5MHz, Fcy=30MHz
_FWDT(WDT_OFF);                  // Watchdog timer off
_FBORPOR(MCLR_DIS);              // Disable reset pin

 char data;

void Interrupt_Init( void )
{
    IEC0bits.U1RXIE = 1;
}

void __attribute__((interrupt, auto_psv)) _U1RXInterrupt( void )               
{
    _LATD0 = 1;
    __delay_ms(500);
    _LATD0 = 0;
        
    data = U1RXREG;
    
    if ( U1STAbits.OERR = 1 )
    {
        U1STAbits.OERR = 0;
    }
    IFS0bits.U1RXIF = 0;
}

int main()
{
     // Set all port D pins as outputs
    _TRISD0 = 0;
 
    // Setup UART - most default options are fine
    UART_Init();  
    Interrupt_Init();
 
    while(1)
    {
        __delay_ms(1000);
       
    }
 
    return 0;
}

© 2017 StormsHalted

Comments

    0 of 8192 characters used
    Post Comment

    • alikhan3 profile imageAUTHOR

      StormsHalted 

      6 months ago from Karachi, Pakistan

      @Jeremy

      Please see the table in the article which shows pin names of the UART module and their corresponding pin names on PIC.

      Actual pin numbers are to vary, depending on the model and series of PIC used but pin names will always work.

    • profile image

      Jeremy 

      6 months ago

      This is fantastic content!

      Do you think you could please upload a circuit diagram of how you connected your dsPIC33F and Arduino?

      Thank you

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, turbofuture.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://turbofuture.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)