I'm trying to write a program in C that will request data through the CN2 port. I currently have a ROM with John Cui's QuickDatalogger, and I am able to datalog with Cuddle and Freelog, so my hardware is setup properly.
I don't know a whole lot about doing serial communications with windows, so I found some prewritten code to get me started. Here is what I have:
Code:
#include <windows.h>
#include <stdio.h>
#define LOOP 255
int main(int argc, char *argv[])
{
DCB dcb;
HANDLE hCom;
BOOL fSuccess;
char *pcCommPort = "COM1";
hCom = CreateFile( pcCommPort,
GENERIC_READ | GENERIC_WRITE,
0, // must be opened with exclusive-access
NULL, // no security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
0, // not overlapped I/O
NULL // hTemplate must be NULL for comm devices
);
if (hCom == INVALID_HANDLE_VALUE)
{
// Handle the error.
printf ("CreateFile failed with error %d.\n", GetLastError());
return (1);
}
// Build on the current configuration, and skip setting the size
// of the input and output buffers with SetupComm.
fSuccess = GetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
printf ("GetCommState failed with error %d.\n", GetLastError());
return (2);
}
// Fill in DCB: 38,400 bps, 8 data bits, no parity, and 1 stop bit.
dcb.BaudRate = CBR_38400; // set the baud rate
dcb.ByteSize = 8; // data size, xmit, and rcv
dcb.Parity = NOPARITY; // no parity bit
dcb.StopBits = ONESTOPBIT; // one stop bit
fSuccess = SetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
printf ("SetCommState failed with error %d.\n", GetLastError());
return (3);
}
printf ("Serial port %s successfully reconfigured.\n", pcCommPort);
//This is where I began coding
OVERLAPPED osWrite = {1};
OVERLAPPED osRead = {1};
int x,
code = 22; //Ignition Timing
DWORD byteswrittensofar,
bytesreadsofar,
timing = 0;
for(x = 0; x < LOOP; x++)
{
if(!WriteFile(hCom, &code, 2, &byteswrittensofar, &osWrite))
printf("Can't Send Data!\n");
if(!ReadFile(hCom, &timing, 2, &bytesreadsofar, &osRead))
printf("Can't Read Data!\n");
printf("Ignition Timing: %.2f\n", timing);
}
return 0;
}
The program gets caught in the readfile function. I know this is kind of slapped together, if any of you guys know of a more efficient way for me to do this, comments are appreciated. Thanks.
--Darren