how can i use c++ to recieve data from mbed through serial port??

19 Oct 2011

hi all, i'm working in a project where i need to send data acquired from the sensors connected to mbed to a computer, and then read the recieved data through the serial usb communication, and then manipulate these values in some way and send them back to the mbed to take ceratin actions.

my problem is that i can't achieve the communication between the mbed and the computer using a custom made c++ code. can any one help writing the code or tell me how i can deal with serial messages comming through serial port using c++?

thank you very much in advance.

best regards, hassan ali.

20 Oct 2011

do you mean on the PC side?

if so then I recomend BORLAND DELPHI (Pascal) or BORLAND BUILDER,

as this is a very easy to use IDE, and produces extreamly reliable code.

with this, you will need a serial widget. the best one I have found is TMS Async

from: http://www.tmssoftware.com/site/async32.asp

Hope This helps

Ceri

20 Oct 2011

Assuming you are using Windows, here is some basic Visual Studio C/C++ code that shows the Microsoft APIs needed to talk to the serial port hardware (virtual or real). COM2 would be replaced with the virtual com port used by mbed and in VS use the help feature to read about each API you don't understand. This is a simple console application (text only - no fancy GUI) and it just echos back what is read in until you type control C.

// SerialIO.cpp : Defines the entry point for the console application.
//
// Serial Port File I/O Demo Program
//
// FOR DEMO: Connect COM2: to PC with null modem cable
// 9600 Baud 8 data bits 1 stop bit 
// no parity and no flow control

#include "stdafx.h"
BOOL ModifyCommSettings (HANDLE hComPort);
HANDLE hSerial;

int _tmain(int argc, TCHAR *argv[], TCHAR *envp[])
{
	DWORD cBytes_out, cBytes_in;
	DWORD dwMask;
	char cBuffer_out[] = "\f\n    Hello Serial World!\n\rType something and watch it echo back\n\rCtrl C to exit\n\r";
	TCHAR cBuffer_in[80];
// Display message on console
	printf("\nOpening COM2: Serial Port - Type ctrl C on other device to exit\n\r");
// Open Serial Port COM2: for Read and Write
	hSerial = CreateFile(_T("COM2:"), GENERIC_READ | GENERIC_WRITE, 0, NULL,
		OPEN_EXISTING, 0, NULL);
// Check for file open errors
	if (hSerial == INVALID_HANDLE_VALUE){
		printf("file open errors\n");
		Sleep(4000);
		return 0;
	}
// Modify Com Port settings (i.e. Baud Rate, #bits, parity etc)
	if(!ModifyCommSettings (hSerial)){
		printf("com port settings errors\n");
		Sleep(4000);
		return 0;
	}

  // Write to title out to serial port.
	if (!WriteFile(hSerial, cBuffer_out, strlen(cBuffer_out), &cBytes_out, NULL)) {
		printf("file write errors\n");
		Sleep(4000);
		return 0;
	}
// Set Communication event mask for WaitCommEvent for rxchar (recieve character) in buffer
	SetCommMask(hSerial, EV_RXCHAR | EV_ERR);

	cBuffer_in[0] = 0;
// Read in characters, copy to console display and Echo
// Loop until ctrl C is typed
	while (cBuffer_in[0] != 0x03){
// Wait for character in input buffer - events are more efficient than looping
		WaitCommEvent(hSerial, &dwMask, 0);
		cBytes_in = 1;
// Loop just in (rare) case more than one character is in UART input buffer
		while (cBytes_in != 0){
// Read back data any serial data and display
		  if (ReadFile(hSerial, cBuffer_in, 79, &cBytes_in, NULL)){
			if (cBytes_in == 0) break;
// Display Data read back
			printf("%s",cBuffer_in, cBytes_in);
// Echo characters back to sender
			if (!WriteFile(hSerial, cBuffer_in, cBytes_in, &cBytes_out, NULL)){
				printf("\rfile write errors\n");
				Sleep(4000);
				return 0;
				}
		  }
		}
	}
	// Close File
	CloseHandle(hSerial);
    return 1;
}
 
BOOL   ModifyCommSettings (HANDLE hComPort)
{
    COMMTIMEOUTS ctos;
	DCB PortDCB;
// Initialize the DCBlength member. 
	PortDCB.DCBlength = sizeof (DCB); 
// Get the default serial port settings DCB information.
	GetCommState (hSerial, &PortDCB);
// Change the common DCB structure settings to modify serial port settings.
PortDCB.BaudRate = 9600;              // Current baud 
PortDCB.fBinary = TRUE;               // Binary mode; no EOF check 
PortDCB.fParity = TRUE;               // Enable parity checking 
PortDCB.fOutxCtsFlow = FALSE;         // No CTS output flow control 
PortDCB.fOutxDsrFlow = FALSE;         // No DSR output flow control 
PortDCB.fDtrControl = DTR_CONTROL_ENABLE; // DTR flow control type 
PortDCB.fDsrSensitivity = FALSE;      // DSR sensitivity 
PortDCB.fTXContinueOnXoff = TRUE;     // XOFF continues Tx 
PortDCB.fOutX = FALSE;                // No XON/XOFF out flow control 
PortDCB.fInX = FALSE;                 // No XON/XOFF in flow control 
PortDCB.fErrorChar = FALSE;           // Disable error replacement 
PortDCB.fNull = FALSE;                // Disable null stripping 
PortDCB.fRtsControl = RTS_CONTROL_ENABLE; // RTS flow control 
PortDCB.fAbortOnError = FALSE;        // Do not abort reads/writes on error
PortDCB.ByteSize = 8;                 // Number of bits/byte, 4-8 
PortDCB.Parity = NOPARITY;            // 0-4=no,odd,even,mark,space 
PortDCB.StopBits = ONESTOPBIT;        // 0,1,2 = 1, 1.5, 2 
// Configure the port settings according to the new specifications  
// of the DCB structure.
	if (!SetCommState (hSerial, &PortDCB)){
	    printf("Unable to configure the serial port"); 
		Sleep(4000);
		return false;
		}
	// Set read time outs 
	ctos.ReadIntervalTimeout = MAXDWORD;
	ctos.ReadTotalTimeoutMultiplier = MAXDWORD;
	ctos.ReadTotalTimeoutConstant = 1;
	ctos.WriteTotalTimeoutMultiplier = 0;
	ctos.WriteTotalTimeoutConstant = 0;
	if(!SetCommTimeouts(hSerial, &ctos)){
	    printf("Unable to configure the serial port"); 
		Sleep(4000);
		return false;
	}
	return true;
	}

If you need a GUI, it is easier to develop GUIs using the VS design tools available for C#. Here is a short C# serial port demo

//C# console application serial port demo
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
namespace Hello_CS_Serial_World
{
 class Program
 {
   static void Main(string[] args)
   {
   SerialPort _serialPort;
// Create a new SerialPort object with desired settings.
   _serialPort = new SerialPort();
//Defaults to ("COM1", 9600, Parity.None, 8, StopBits.One)
   _serialPort.Open();
   _serialPort.WriteLine("Hello CS Serial World");
   _serialPort.Close();
   }
 }
}
28 Aug 2013

Hi,

I'm facing the same problem. I would like to know if that worked or not. For me I'd like to have a code in c/c++ for VC or VC++ so I can use the data in there(VC++) which are being received by usb serial port, sent by mbed.

I would appreciate any help cause it's a bit urgent.

Thank you!

27 Aug 2015

Is that code also the same for MAC? or how should I have to edited to get the same results but for a MAC computer?