Hello, everyone! I need some help communicating my Arduino with a C# program. I'm using an Arduino PING ranging sensor in order to read a value (an int). I want that value to set the X location of a component (in this case, a picture box) in a C# program. I'm having some issues, however, and I hope you guys can help me out.
My Arduino code is the following:
const int trig = 8;
const int echo = 7;
int info;
void setup()
{
Serial.begin(9600);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
}
void loop()
{
digitalWrite(trig, LOW);
delayMicroseconds(5);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
info = pulseIn(echo, HIGH); // en microsegundos
Serial.write(lowByte(info));
Serial.write(highByte(info));
delay(500);
}
Now, I have no idea if using Serial.write()
and splitting the int is a good way to go, but there are so many ways to do this and I'm very lost.
I am even more lost, however, on my C# program. I created a Serial port and then run getPosicion after every Tick on a timer (which is set to Intervals of 500). When doing this, all I get is 0's.
SerialPort port = new SerialPort("COM3", 9600);
int getPosicion()
{
int posicion = 0;
port.Open();
int bytes = port.BytesToRead;
byte[] byte_buffer = new byte[bytes];
posicion = port.Read(byte_buffer, 0, bytes);
port.Close();
return posicion;
}
I tried using Serial.println()
and port.ReadLine()
, which somehow seems to work, but my program lagged heavily. Even though I'm not sure if performance should be better, I want to send the information as bytes to learn how to use it and to learn.
How can my code be fixed? I guess I'm doing something inherently wrong, after all most of what I display here was a desperate copy-paste attempt. I'm lost. Thanks in advance!