User`s manual

Table Of Contents
UC-7400-CE User’s Manual Programming Examples
5-2
Example #1MOXA UART Supporting RS-232/422/485
The following C/C++ code shows a sample application transmitting data from port “COM3” to
port “COM4” using the RS-232 operation mode. After these ports have been opened, the
application generates a thread to receive data from port “COM3” and then the application itself
executes as a main thread to transmit data to port “COM4”.
#include "stdafx.h"
#include <stdio.h>
#include <moxa/devices.h>
#define MAX_DATA_LEN 128
//======================================================================
static HANDLE createComHandle(WCHAR *comPort, unsigned int baudrate)
{
HANDLE hCom;
DCB dcb;
COMMTIMEOUTS to;
hCom = CreateFile(comPort, GENERIC_READ | GENERIC_WRITE,
0, // exclusive access, until the handle is closed
NULL, // no security
OPEN_EXISTING,
0, // no overlapped I/O
NULL); // null template
if (hCom==INVALID_HANDLE_VALUE )
return NULL;
// set serial setting
GetCommState(hCom, &dcb);
dcb.BaudRate = baudrate;
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;
dcb.Parity = NOPARITY;
dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
dcb.fOutxCtsFlow = TRUE;
SetCommState(hCom, &dcb);
// set timeout parameter
to.ReadIntervalTimeout = 0;
to.ReadTotalTimeoutMultiplier = 0;
to.ReadTotalTimeoutConstant = 0;
to.WriteTotalTimeoutMultiplier = 0;
to.WriteTotalTimeoutConstant = 0;
if (!SetCommTimeouts(hCom,&to))
{
printf("SetCommTimeouts error!\n");