RS232 to WinApi 2
#include <windows.h>
#include "RS232.h"
extern HANDLE hSerial; // Global Handle
bool OpenSerialPort(HWND hwnd,LPCSTR _PortName)
{
hSerial = CreateFile(_PortName, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); // OPEN PORT
if(hSerial == INVALID_HANDLE_VALUE)
{
if(GetLastError() == ERROR_FILE_NOT_FOUND) MessageBox(hwnd, "Port not avalible", "ERROR", MB_OK);
return false;
}
DCB SPort = {0}; //
SPort.DCBlength = sizeof(DCB);
if(GetCommState(hSerial, & SPort))
{
SPort.BaudRate=CBR_115200; // SerilPort Baudrate
SPort.ByteSize=8; // Byte size 8
SPort.StopBits=ONESTOPBIT;
SPort.Parity=NOPARITY;
}
else
{
MessageBox(hwnd, "COM_Error_103", "ERROR", MB_OK);
return false;
}
if (!SetCommMask(hSerial, EV_RXCHAR)) MessageBox(hwnd, "COM_Error_103", "ERROR", MB_OK);
return true;
}
//----------------------------------
//----------------------------------
bool CloseSerialPort(void)
{
if(CloseHandle(hSerial)) return 1; // Closed OK - return 1
else return 0; // Closed FX - return 0 -> Error
}
//----------------------------------
//----------------------------------
bool WriteABuffer(HWND hwnd, BYTE * lpBuf, DWORD dwToWrite)
{
OVERLAPPED osWrite = {0};
DWORD dwWritten;
DWORD dwRes;
BOOL fRes;
osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!WriteFile(hSerial,(LPCVOID) lpBuf, dwToWrite, &dwWritten, &osWrite))
{
if (GetLastError() != ERROR_IO_PENDING) fRes = FALSE;
else
dwRes = WaitForSingleObject(osWrite.hEvent, INFINITE);
switch(dwRes)
{
case WAIT_OBJECT_0:
if (!GetOverlappedResult(hSerial, &osWrite, &dwWritten, FALSE)) fRes = FALSE;
else fRes = TRUE;
default: fRes = FALSE;
}
}
else
{
MessageBox(hwnd, "OK", "OK", MB_OK);
fRes = true;
}
CloseHandle(osWrite.hEvent);
return fRes;
}
Event = CreateEvent(NULL, TRUE, FALSE, NULL);
Overlapped.hEvent = Event;
char lpBuf;
DWORD value;
DWORD dwCommEvent;
while(1)
{
Result=MsgWaitForMultipleObjects(1,&Event,FALSE,INFINITE, QS_ALLEVENTS | QS_ALLPOSTMESSAGE | QS_SENDMESSAGE);
if (Result==WAIT_OBJECT_0)
{
GetOverlappedResult(hSerial, &Overlapped, &value , FALSE);
if(WaitCommEvent(hSerial, &dwCommEvent, NULL))
{
do {
ReadFile(hSerial, &chRead, 1, &dwRead, &Overlapped);
MessageBox(hwnd, "ok", "oko", MB_OK);
}while (dwRead);
}
}
if (Result==WAIT_OBJECT_0+1){
{
while (PeekMessage(&messages, NULL, 0, 0, PM_REMOVE))
{
if (messages.message == WM_QUIT){
break;
}
TranslateMessage(&messages);
DispatchMessage(&messages);
}
}
}
}
....
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
...
case ID_BUTTON_CONNECT:
OpenSerialPort(hwnd,"COM3");
break;
case ID_BUTTON_SEND:
WriteABuffer(hwnd,&a,1);
if(bSet == true) ReadFile(hSerial, &chRead, 1, &dwRead, &Overlapped);
bSet = false;
break;
...
}
http://forum.root.cz/index.php?topic=8440.0