Serial Port Communication Help

I have a device that I would like to operate from a computer. The device is connected to the computer through a COM port. What I need to do is send to the device instructions to make a measurement and then receive the results. The device accepts HEX commands, the following is the HEX command to ask the device to wake up, take a measurement, and return a value 0xC1 0xD2 0x21. The device documentation states the response will be “Response (HEX): 0x02, 0x00 (Data Lowbyte), 0x00 (Data Highbyte)”

I have been doing a lot of internet searching to try and piece together the code to make this happen but I’m stuck on how to send and receive the HEX information. Also I’m not even sure what I have is correct. Any help would be appreciated!!

// Communication with Resipod

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
#include <windows.h>
#include <objbase.h>
#include <msxml6.h>

int main()
{
HANDLE Resipod;

Resipod = CreateFile(L"COM4",GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
if(Resipod=INVALID_HANDLE_VALUE)
{
//Serial Port does not exist. Inform user.
abort();
}

//some other error occurred. Inform user.

DCB dcbSerialParams={0};
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
if(!GetCommState(Resipod, &dcbSerialParams))
{
//error getting state
}
dcbSerialParams.BaudRate= CBR_19200;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits= ONESTOPBIT;
dcbSerialParams.Parity= NOPARITY;

COMMTIMEOUTS timeouts={0};
timeouts.ReadIntervalTimeout=50;
timeouts.ReadTotalTimeoutConstant=50;
timeouts.ReadTotalTimeoutMultiplier=10;

if(!SetCommTimeouts(Resipod, &timeouts))
{
//Error occured, Inform user
}

CloseHandle(Resipod);

return 0;
}
Here:
if(Resipod=INVALID_HANDLE_VALUE)

you are assigning INVALID_HANDLE_VALUE to Resipod


Correct:
if(Resipod==INVALID_HANDLE_VALUE) // Note == instead of =
While you are correct in finding that error, that however, is not the overall problem I'm having. I need to communicate with a device connected through the com port.
So, are you sure that you can communicate with the serial port at all? What about handshake?

You need to call SetCommState() before you write data in order to set the changes


For the data. There are two options:

Transmit it as string:
1
2
3
4
5
char data[] = "0xC1 0xD2 0x21";
int size = strlen(data);
DWORD dwWritten = 0;
if(WriteFile(Resipod, data, size, &dwWritten, 0) != FALSE)
  ..


Or as binary:
1
2
3
4
5
char data[] = { 0xC1, 0xD2, 0x21 };
int size = sizeof(data);
DWORD dwWritten = 0;
if(WriteFile(Resipod, data, size, &dwWritten, 0) != FALSE)
  ..


You may try both
Topic archived. No new replies allowed.