The following code was programmed into my Metro M4 Express using the Arduino IDE, version 1.8.12. In summary, it waits to receive a newline character over the serial port, and echos it back. It also sets the board's LED high as a sign that it is responding.
Code: Select all
bool ledState = false;
String inputString = ""; //buffer for received string
boolean stringComplete = false; //set this tr
void setup() {
Serial.begin(9600);
inputString.reserve(32);
pinMode(13,OUTPUT); //led
digitalWrite(13,LOW);
}
void loop() {
while (Serial.available()) {
char inChar = (char)Serial.read();
inputString += inChar;
if (inChar == '\n') {
stringComplete = true;
}
}
if(stringComplete)
{
digitalWrite(13,HIGH);
Serial.print("ECHO: "+inputString);
delay(500);
digitalWrite(13,LOW);
inputString = "";
stringComplete = false;
}
}
However, the following C# code, which I would expect to work given a fair amount of experience with C#, .NET, and this class, does not work:
Code: Select all
SerialPort pn;
void Main()
{
pn = new SerialPort("COM26", 9600);
pn.Open();
Thread.Sleep(1000);
pn.WriteLine("VER");
Thread.Sleep(1000);
var cx = pn.BytesToRead;
var buff = new byte[cx];
pn.Read(buff, 0, cx);
Console.WriteLine($"Read {cx} bytes");
pn.Close();
}
I understand that this may be a .NET issue, which may be outside of the scope of this forum. But I'm migrating from an old Metro 328 to a Metro M4 Express, and this code works just fine on the Metro 328.
Thanks in advance.