pBook‎ > ‎Serial Port Prog. Linux/Windows‎ > ‎Widnows‎ > ‎

Visual Studio Windows Serial Com Prog.

posted Apr 27, 2015, 7:32 AM by Javad Taghia   [ updated Apr 27, 2015, 8:25 AM ]
#include <windows.h>
#include <string.h>
#include <tchar.h>
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdint.h>

#include "serialcomms.h"
HANDLE hCom1;
char Buffer1[256]; // can be variable size too like: char Buffer1[] = "Hello";
unsigned long NumBytes;

int main()
{


//  Open a handle for the specified 9com port.
hCom1 = OpenSerialPort(TEXT("COM7"), CBR_115200, 8, NOPARITY, ONESTOPBIT);

if ((hCom1 == INVALID_HANDLE_VALUE) || (hCom1 == NULL)) 
{
printf("Could not open port1\n");
_getch();
return 1;
}
COMMTIMEOUTS timeouts={0};
timeouts.ReadTotalTimeoutMultiplier=10;
timeouts.WriteTotalTimeoutConstant=50;
if(!SetCommTimeouts(hCom1, &timeouts)){
//error occureed. Inform user
}
std::cout << "Port is Open !" << std::endl;
int i =0;
while (i < 5)
{

std::cout<< i << std::endl; 
Buffer1[0] = 'h';
Buffer1[1] = static_cast<char>(i);
NumBytes = 2;
if(!(WriteFile(hCom1,Buffer1,sizeof(Buffer1),&NumBytes,NULL))) 
{
printf("\nTime out!\n"); 
return (2);
}
Buffer1[0] = 'x';
Buffer1[1] = 'x';
if(!(ReadFile(hCom1,Buffer1,sizeof(Buffer1),&NumBytes,NULL))) 
{
printf("\nTime out!\n"); 
return (2);
}
std::cout << Buffer1[0] << (int)Buffer1[1] << std::endl;
Sleep(1000);
i++;
}
CloseHandle(hCom1);

}

You need to add the header "serialcomms.h" to the main file and "serialcomms.cpp" to your project in Visual Studio.
ċ
SerialComms.cpp
(1k)
Javad Taghia,
Apr 27, 2015, 7:32 AM
Ċ
Javad Taghia,
Apr 27, 2015, 7:32 AM
ċ
serialcomms.h
(0k)
Javad Taghia,
Apr 27, 2015, 7:32 AM
Comments