Hi,
Firstly, the problem:
I cannot find a away to send 2bytes of data via serial to an arduino (that uses Serial.parseInt()) from a windows C++ console app.
The C++ code follows: (it is stripped down for clarity, but the problem still presents itself in a larger version that checks all serial setup function calls are successful and so on)
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
int main()
{
//setup
HANDLE hSerial;
DCB dcbSerialParams = {0};
COMMTIMEOUTS timeouts = {0};
hSerial = CreateFileA("COM3", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
GetCommState(hSerial, &dcbSerialParams);
dcbSerialParams.BaudRate = CBR_19200;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
SetCommState(hSerial, &dcbSerialParams);
//the data to send:
//char dataToSend = '5';
//unsigned int dataToSend = 125;
//(LPVOID)
unsigned short dataToSend = 125;
DWORD bytes_written;
WriteFile(hSerial, &dataToSend, sizeof(dataToSend), &bytes_written, NULL);
fprintf(stderr, "%d bytes written\n", bytes_written);
//CloseHandle(hSerial);
Sleep(3000);
return 0;
}
The above code will not give the results I'm after, using unsigned int I get all zeros (I'm looking at the data as bits in the arduino), I need 2bytes only so i try unsigned short, same thing, all zeros - however when I try char, I will see the binary representation of 0-9 on the arduino, but not for any other ascii values (I thought I was close to a solution then! i.e. I could just cast the 'int' as it's two bytes in ascii...).
Also tried the '(LPVOID)' cast (no idea what it is but it was mentioned in another thread).
The kicker is that I have an LCD connected on the arduino and using the arduino IDE serial monitor and with that I can send any int value I want and it will work as intended (using 'no line ending').
A little context re. why using parseint>> I'm trying to avoid using anything more than 2bytes as 15bits of data is all I need. Arduino has 2byte ints so I figure I can use that data type to send the info (and code/decode the parts I need using bitwise operations at either end). I have no issue with this (that part at least is working).
The arduino code is as simple as:
if (Serial.available()) {servoData = Serial.parseInt();}
As mentioned, I have no issues with this using the arduino serial monitor.
I've tried flipping endianess, but aren't sure I went about it correctly - the 2byte version was:
dataToSend = (dataToSend << 8 ) | ((dataToSend >> 8 ) & 0x00ff);
Something to do with serial, line endings, variable types?
Any hints appreciated