How to Read Data From Serial Port C++
This tutorial teaches you to plan your Windows PC to communicate with an external peripheral like data acquisition boards, USB GPIO Boards,Relay boards etc through its series port (Virtual or Real).
Here i am bold that you are using a Virtual COM port based any of the numerous IC'due south bachelor on the market.
The tutorial is aimed at Software/Embedded developers who may want to interface real world sensors similar DAQ's,USB Relays,USB GPIO boards ,Temperature sensors,Humidity sensors etc to Windows PC .
The software is written using C language and communicates with the Serial Port using Win32 API.
All codes have been tested on a 64bit Windows 10 System.
All the codes in this tutorial are licensed nether MIT License making it eligible to be used for developing proprietary software applications.
|
Isolated USB to Serial Converters
1 major issue with interfacing existent word devices with your PC's is that High voltage spurious transients can couple on to your USB or RS232 or RS485 lines.These high voltage transients can cause severe impairment to your figurer or its ports.
It is highly recommended to use an
- Isolated USB port or
- Isolated USB to Serial/RS232/RS485 converter
to protect your PC .
Sourcecodes
- Please note that the source codes on the website show simply the relevant sections to highlight the procedure of programming the series port.
- Contact Us to Enquire almost the full Source codes
Compilers and IDE's used
Since we are developing on Windows platform,
- Recommended IDE is Visual Studio (Professional or Community Edition).
In Visual Studio,in that location is no longer an option for creating a C project.
So create a Win32 C++ project and relieve your source file with a .C extension (Eg: MySourceFile.C).Compiler would automatically do the rest.
GCC/MinGW
You tin also compile the code using GCC or MinGW subsequently a few tweaks.
The Code uses some Microsoft specific safe C functions similar
- strcat_s() and
- scanf_s()
which are used to get the COM number from the user and create the COM port address string (Eg "\\.\COM9" ).The code will compile on GCC after removing those functions.
Make sure that variables referenced by those functions are also changed.
Finding out your COM port Number
A little bit of History,
Serial ports are simple nine pin legacy ports used by the PC to communicate with external peripherals like Printers,Data Acquisition Sytems,Printers etc.
The simple protocol and the 3 pin hardware physical lines (RX,TX,GND) made it quite pop amongst manufacturers who wanted an easy fashion to connect their devices with a computer.
In the 2020's, the old DB9 Serial port is plant only on industrial motherboards and old PC's.The onceubiquitous serial port have been completely replaced by the familiar USB standard.
The arrival of cheap USB to UART fries like FTD FT232RL,TUSB3410,CP2102 have made information technology quite easy to upgrade the existing software that used to talk over serial to USB protocol.These fries provide a virtual serial port that behaves like a real one but transmits the data through USB.
If your PC does not have whatever hardware series ports (RS232 DB9 ports), you lot can use USB to Serial Converter's similarUSB2SERIAL.(non Isolated).
In Windows ,
Serial ports are named asCOM1,COM2 ,COM3.. etc .COM1 andCOM2 commonly refer to thehardware serial ports nowadays in the PC (quite rare now)
while COM numbers in double digits like COM32,COM54,COM24.. etc are given to USB to Serial Converters or PCI serial port extenders.
To find out the COM number corresponding to your serial port,
- Open Device Manager by correct clicking on My Figurer icon and selectingManage → Device Manager. or
- past typing "Device Manager" on the taskbar search box in Windows ten
Nether Ports(COM & LPT) y'all tin can see the parallel and serial ports (COM) detected by your system.
If your PC has any hardware ports, it will be shown either as COM1 or COM2 nether the Ports Section.
I am using a FTDI based USB to Series Converter (USB2SERIAL)which is recognized as COM24(this may be dissimilar under your system).
If you double click on COM24,you lot can see the details of the corresponding port.
Windows10 Accounts
The codes/executables are able to open up the connectedness to the serial port under both Administrator Account and Standard User Business relationship in Windows x.
Opening and Endmost a Serial Port
we use theCreateFileA() function to open up a serial port.
CreateFile() is a Win 32 function which is used to create or open up a file, stream or an IO device similar serial port.
On success CreateFileA() will render a handle which is then used to refer the connection in all subsequent operations.
After opening a serial port using the CreateFileA() role yous should shut it with CloseHandle() office, otherwise port volition become unavailable to other programs.
Now permit's write a small programme to open up and shut a serial port on Windows.
Open a text editor like notepad and type the below code and relieve information technology equally "serial.c".If y'all are using IDE like VS Express, use the one integrated with it.
#include<windows.h>
#include<stdio.h>
int primary()
{
HANDLEhComm;
hComm =CreateFileA("\\\\.\\COM24",//port name
GENERIC_READ | GENERIC_WRITE,//Read/Write
0,// No Sharing
NULL,// No Security
OPEN_EXISTING,// Open up existing port only
0,// Not Overlapped I/O
Zip);// Null for Comm Devices
if (hComm ==INVALID_HANDLE_VALUE)
printf("Error in opening series port");
else
printf("opening series port successful");
CloseHandle( hComm );//Closing the Serial Port
render0;
}
Configuring the DCB Structure
In Windows ,settings like Baud rate ,Number of start/Stop $.25,data formats etc for the serial port are controlled past the DCB construction.
To Configure the DCB structure we apply 2 functions,
GetCommState() function which retrieves the current control settings of the series port and
SetCommState() function which configures the series port with the new values in DCB structure provided past united states of america.
ReadIntervalTimeout Specifies the maximum fourth dimension interval betwixt arrival of two bytes. If the arrival time exceeds these limits the ReadFile() function returns.
ReadTotalTimeoutConstant is used to summate the total time-out flow for read operations. For each read operation, this value is added to the product of the ReadTotalTimeoutMultiplier member and the requested number of bytes.
ReadTotalTimeoutMultiplier is used to calculate the total fourth dimension-out flow for read operations. For each read operation, this value is multiplied by the requested number of bytes to be read.
WriteTotalTimeoutConstant similar to ReadTotalTimeoutConstant but for write operation.
WriteTotalTimeoutMultiplier similar to ReadTotalTimeoutMultiplier just for write operation.
After this you have to set the values using SetCommTimeouts() office.
Writing Data to Serial Port
Writing information to the opened serial port is accomplished past the WriteFile() role. WriteFile() function can be used to write both into the files and I/O ports.
Status =WriteFile( hComm,// Handle to the Serial port
lpBuffer,// Data to exist written to the port
dNoOFBytestoWrite ,//No of bytes to write
& dNoOfBytesWritten , //Bytes written
NULL);
If your PC does not have any hardware serial ports you tin can use any USB to Serial Converters(I am using USB2SERIAL).
Microcontroller Interface
I have interfaced a microcontroller MSP430G2553/ATmega328P to the serial port like this
Y'all tin can utilise whatsoever microcontroller of your selection like 8051,AVR or ARM(LPC2148).
The Controller waits for a character to be received and lights up the corresponding LED.
The lawmaking for interfacing MSP430 is available in the Github repo.
.If you want to know how to configure the MSP430 controller UART you can check this tutorial.
Nosotros accept besides included code for
- interfacing your PC with ATmega328P microcontroller using Series port
in the Repo likewise. The connexion setup is similar to the MSP430.
Please annotation that if you lot are using a DB9 RS232 Serial Port of your PC, yous volition accept to build a RS232 betoken level converter at the microcontroller side to decode the RS232 point.
Directly connecting the PC's RS232 Serial port to MSP430 's pins volition damage the chip.
Here is the screen shot of the Programme writing into serial port of Windows 7 Reckoner
Delight note that i have changed the names of the C files in the latest release.
Use the files in the "PC_Transmits" folder.
Here is the screen shot of the Program writing into serial port of Windows 10Computer
Reading from the Serial Port
Reading from the serial port is accomplished by the ReadFile() function.
One way to practise that is to use polling where the ReadFile() continuously reads from the serial port and checks for any received characters.
Other way is to setup an event and let windows notify u.s. when a grapheme is received.
We are going to use the second method here, following are the steps.
one. Create an Event for a detail action like character reception, change in modem lines etc using SetCommMask() function .
2. Enquire windows to wait for the event set past SetCommMask() function using WaitCommEvent() and notify united states of america when the status happens.
iii. Call ReadFile () to read the received information from the Serial port.
Functions used are
SetCommMask() is used to set the events to be monitored for a advice device
WaitCommEvent() is used to wait for the events set by SetCommMask() to happen, i
Codes running on Windows 7 PC.
Delight note that i accept changed the names of the C files in the latest release.
Employ the files in the "PC_Receives" folder.
Reset the Micro controller to transmit the string "Howdy from MSP430".
Codes running on Windows 10 PC .
Check out our next section,
If yous want to know how to command the RTS and DTR pins of the serial port .
Source: https://www.xanthium.in/Serial-Port-Programming-using-Win32-API
0 Response to "How to Read Data From Serial Port C++"
Post a Comment