serial port communication using c++
sir,
i have been asked to do serial port programming using C++
it should include opening port, close and view the status of the serial port. You should also be able to control speed, timeout,start bit,stop bit,parity bit and stuff like that
please provide me some solution in the form of sample programs,books or techniques..
since i am new to programming,i dont know from where and how should i start
regards,
mayuri
serial port communication using c++
Code:
// serial.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
#undef UNICODE
#include "stdafx.h"
#include <windows.h>
void PrintError( LPCSTR str)
{
LPVOID lpMessageBuffer;
int error = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //The user default language
(LPTSTR) &lpMessageBuffer,
0,
NULL
);
printf("%s: (%d) %s\n\n",str,error,lpMessageBuffer);
LocalFree( lpMessageBuffer );
}
int main(int argc, char* argv[])
{
// open port for I/O
HANDLE h = CreateFile(argv[1],
GENERIC_READ|GENERIC_WRITE,
0,NULL,
OPEN_EXISTING,0,NULL);
if(h == INVALID_HANDLE_VALUE) {
PrintError("E012_Failed to open port");
} else {
// set timeouts
COMMTIMEOUTS cto = { 1, 100, 1000, 0, 0 };
DCB dcb;
if(!SetCommTimeouts(h,&cto))
PrintError("E013_SetCommTimeouts failed");
// set DCB
memset(&dcb,0,sizeof(dcb));
dcb.DCBlength = sizeof(dcb);
dcb.BaudRate = 19200;
dcb.fBinary = 1;
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
dcb.fOutxCtsFlow = 1;
dcb.fRtsControl = DTR_CONTROL_HANDSHAKE;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.ByteSize = 8;
if(!SetCommState(h,&dcb))
PrintError("E014_SetCommState failed");
char buf[7];
DWORD read = 0;
DWORD write=1; // Number of bytes to write to serial port
buf[0] = 72; // Decmial value to write to serial port
WriteFile(h,buf,write,&write,NULL); // write is updated with the number of bytes written
ReadFile(h,buf,sizeof(buf),&read,NULL); // read is updated with the number of bytes read
DWORD i;
for (i=0; i<read; i++)
printf("%i ", (unsigned char)buf[i]);
CloseHandle(h);
}
return 0;
}
hey dis is d program for serial port communication..i was able to compile it but i hav a problem wid o/p
i am getting this error after compilation
E012_Failed to open port: <5> Access is denied.
i have connected serial port also to the pc and set all d parameters in COM1
pls resolve my query..
regards,
mayuri
serial port communication using c++
Quote:
Originally Posted by
vart
what are you passing as argv[1] to your program?
i m passng COM1 as argument..i m doong dat in project properties
- Configuration Properties - Debugging - Command Arguments, in Visual Studio
is it correct?
if not den pls provide some solution instead of teasing me