I made a thread earlier today in which i didnt really get my point across and miscommunicated on several levels and therefore im trying again with actual proper explanation.
Im currently working on serial communicatain from my arduino to a C++ program that is running on my PC.
Currently i just want to send a binary value to the PC when i press a button on my board, however ive found some inconsistencies when i go for anything larger than 2 digits.
My arduino code - which is basically just the original debounce example with an added serial.print():
int inPin = 2; // the number of the input pin
int outPin = 13; // the number of the output pin
int state = HIGH; // the current state of the output pin
int reading; // the current reading from the input pin
int previous = LOW; // the previous reading from the input pin
long time = 0; // the last time the output pin was toggled
long debounce = 200; // the debounce time, increase if the output flickers
void setup()
{
pinMode(inPin, INPUT);
pinMode(outPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
reading = digitalRead(inPin);
if (reading == HIGH && previous == LOW && millis() - time > debounce) {
if (state == HIGH){
state = LOW;
}
else {
state = HIGH;
}
Serial.print("1234"); // For showcasing of the example ive not only used 0 and 1.
// This way it is easier to actually see what is going on.
time = millis();
}
digitalWrite(outPin, state);
previous = reading;
}
This example just sends out the value 1234 whenever i press my button (i know this isnt binary, but it is easier to see where it goes from when we have more different symbols).
Now my C++ code is based off of this serial communications class:
http://playground.arduino.cc/Interfacing/CPPWindows
And my main loop looks like this:
int main() {
Serial* SP = new Serial("\\\\.\\COM3");
if (SP->IsConnected())
{
cout << "We're connected" << endl;
cout << "________________" << endl;
}
char incomingData[256] = "";
int readResult = 0;
while (SP->IsConnected())
{
readResult = SP->ReadData(incomingData);
incomingData[readResult] = 0;
if (strlen(incomingData) > 0)
{
string str(incomingData);
cout << endl << "String: " << str << endl;
for (int i = 0; i < strlen(incomingData); i++)
{
cout << "Char on place " << i << ": " << incomingData[i] << endl;
}
cout << "________________" << endl;
}
}
}
If we now take a look at the desired console output with an example where i only send the number 1 from the arduino when i press a key it will look something like this:
As we see it registers it completely fine, however, if i use the example from the actual arduino code posted the console looks something more like this:
So as you see it somehow doesnt always put the entire char array into the string before it prints and moves on. I dont know if this is because the char array isnt filled up yet, and i dont know how to account for this.
I hope someone have an idea as to how i can receive the entire string of data every time.