A trivial example of a UART comm. Works on all Nucleos.

Dependencies:   mbed

main.cpp

Committer:
Foxnec
Date:
2015-03-19
Revision:
3:d470d455b369
Parent:
2:bdc32e32f6f1

File content as of revision 3:d470d455b369:

/**********************************************************************************
* @file    main.cpp
* @author  Petr Dousa, Daniel Toms
* @version V0.1
* @date    05-March-2015
* @brief   Nucleo UART example - sends and receives data over serial
***********************************************************************************/

/* Includes ----------------------------------------------------------------------*/
#include "mbed.h"
#include <string>

#define INPUT_BUFFER_SIZE 256

void flushSerialPort();

Serial pc(SERIAL_TX, SERIAL_RX);

DigitalOut myled(LED1);

int main()
{
    int i;
    char text[INPUT_BUFFER_SIZE];       //input buffer
    
    //------------------------------------
    // Hyperterminal configuration
    // 9600 bauds, 8-bit data, no parity
    // --------------------------------
    // Communication settings:
    // pc.format(bits,parity,stop_bits)
    //      bits: 5-8
    //      parity: SerialBase::None, SerialBase::Odd, SerialBase::Even, SerialBase::Forced1, SerialBase::Forced0
    //      stop_bits: 1 or 2
    // pc.baudrate(baud)
    //      baud: The desired baudrate (speed)
    // --------------------------------
    
    pc.format(8,SerialBase::None,1);    // This is the default setting
    pc.baud(9600);                      // This is the default setting
    
    //Sends a welcome message over UART (Serial port)
    //Checks if the port is writeable first
    if (pc.writeable())
        pc.printf("Hello World !\n-----------------\nWrite something...\n");
    
    while(1) {
        
        wait(1);
        
        myled = !myled;                             //blinking led indicates activity
                
        //NOTE: the data must be terminated with CR(Carriage return) '\r'
        //      You can however choose a different terminating character.
        
        i=0;
        while ((text[i-1] != '\r') && (i<0xFF))
        {
            if (pc.readable())                      //Checks if there are data to be received and stores them into the input buffer
            {    
                text[i++] = getc(pc);               //Note: you could use pc.scanf() instead of getc.
                                                    //pc.scanf() has the same syntax like in regular C apps.
            }           
        }
        
        if (pc.writeable()) 
        {
            pc.printf("Received data: %s", text);   //Sends the data back for confirmation.
            memset(&text, 0, i);
        }
        
        //flushSerialPort(pc);                      //Erases all the data waiting to be received
        
    }
}

//Erases all the data waiting to be received
void flushSerialPort()
{

    while(pc.readable()) 
        pc.getc();
    
    return;
}