Hello everyone,
I am having trouble figuring out where the bug is in my code.
I have two functions which are used to access a serial port.
When i combine then it works correctly ,but when i split them into smaller functions i get "INVALID_FILE_HANDLE"(getlasterror code number : 6)
IN serial_functions
Code:
#include <serial_functions.h>
void serialport_init(HANDLE hSerial)
{
hSerial = CreateFile("COM3",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");
exit(1);
}
printf("Some other error occured.\n");
exit(1);
}
//printf("%d\n",GetHandleInformation(hSerial, lpdwFlags));
//getch();
printf("Port opened succesfully.\n");
if (!GetCommState(hSerial, &dcbSerialParams))
{
printf("Error getting state.\n");
exit(2);
}
dcbSerialParams.BaudRate=CBR_19200;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
if(!SetCommState(hSerial, &dcbSerialParams))
{
printf("Error setting serial port state.\n");
}
printf("Parameters set.\n");
timeouts.ReadIntervalTimeout=50;
timeouts.ReadTotalTimeoutConstant=50;
timeouts.ReadTotalTimeoutMultiplier=10;
timeouts.WriteTotalTimeoutConstant=50;
timeouts.WriteTotalTimeoutMultiplier=10;
if(!SetCommTimeouts(hSerial, &timeouts))
{
printf("Error setting timeouts.\n");
exit(3);
}
printf("Timeouts set.\n");
}
void writedata(HANDLE hSerial,char *b,int n)
{
if(!WriteFile(hSerial, *b, n, &dwBytesRead, NULL))
{
printf("Error occured while writting data.\n");
//printf("%d\n",GetHandleInformation(hSerial, lpdwFlags));
//system("pause");
exit(5);
}
printf("Data Sent.\n");
}
/*
void readdata(int n)
{
if(!ReadFile(hSerial, rzBuff, n, &dwBytesRead, NULL))
{
printf("Error occured while reading data.\n");
exit(4);
}
}
*/
And in my main.c
Code:
#include "main.h"
#include "serial_functions.h"
int main()
{
printf("\n");
serialport_init(hSerial);
pointer_xyz = xyz;
writedata(hSerial,pointer_xyz,1);
return 0;
}
The program compiles and runs fine but i am not able to get the desired result in "writedata(hSerial,pointer_xyz,1);"
When i merge the two functions they work perfectly
Any help would be appreciated.