1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
#include "windows.h"
#include <stdio.h>
#include <ctype.h>
#include <io.h>
#include <conio.h>
#include <stdlib.h>
#define maxBytes 111
int main()
{
HANDLE hSerial;
DCB dcbSerialParams = {0};
COMMTIMEOUTS timeouts = {0};
DWORD dwBytesRead = 0;
char szBuff[maxBytes] = {0};
int firstdigit = 0;
FILE *fp;
int i;
//opening the serial port
hSerial = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if(hSerial==INVALID_HANDLE_VALUE)
{
if(GetLastError()==ERROR_FILE_NOT_FOUND)
{
printf("Serial port does not exist\n");
}
printf("Other errors\n");
}
//setting parameters
dcbSerialParams.DCBlength = sizeof (dcbSerialParams);
//GetCommState is to retrieves the current control settings for a specific communications device.
if (!GetCommState(hSerial, &dcbSerialParams))
{
printf("Not GetCommState, not able to retrieves the current control\n");
}
dcbSerialParams.BaudRate = CBR_115200;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
//SetCommState configures a communications device according to the specifications
//in DCB. The function reinitializes all hardware control settings but it does not
//empty output or input queues
if (!SetCommState(hSerial, &dcbSerialParams))
{
printf("Not SetCommState, cannot configures serial port according to DCB specifications set\n");
}
//setting timeouts
timeouts.ReadIntervalTimeout = 40;
timeouts.ReadTotalTimeoutConstant = 40;
timeouts.ReadTotalTimeoutMultiplier = 40;
timeouts.WriteTotalTimeoutConstant = 40;
timeouts.WriteTotalTimeoutMultiplier = 40;
//SetCommTimeouts set the time out parameters for all read and write operation
if (!SetCommTimeouts(hSerial, &timeouts))
{
printf("Not SetCommTimeouts, cannot set the timeout parameters to serial port\n");
}
//reading data
//ReadFile reads data from the specified file or i/o devices.
printf("The content inside the file: \n\n");
if(!ReadFile(hSerial, szBuff, maxBytes, &dwBytesRead, NULL))
{
printf("error\n");
}
else
{
fp = fopen("c:\\new.txt", "w");
while (ReadFile(hSerial, szBuff, maxBytes, &dwBytesRead, NULL))
{
for (i = 0; i < dwBytesRead; i++)
{
if (szBuff[i] == 10 || szBuff[i] == 13)
{
fprintf(fp, "\n");
printf("\n");
break;
}
else
{
fprintf(fp, "%c", szBuff[i]);
printf("%c", szBuff[i]);
}
}
}
fclose(fp);
CloseHandle(hSerial);
}
}
|