简体   繁体   中英

C# GUI to Arduino: Serial Data Not Working

I'm trying to send an integer through the usb connection to my arduino. When using the sketch monitor I can verify that the code works; However, when using the C# .NET GUI, I'm unable to get anything working.

I do know that the data is sending via the LEDs lighting up on the arduino.

I'm typing an RPM into a text box, converting it to 4 bytes (integer) and writing it. Here is the GUI code:

RPMMove = Convert.ToInt32(tbRPM.Text);
byte[] bRPM = BitConverter.GetBytes(RPMMove);
port.Write(bRPM, 0, 4);

On the arduino:

void setup()
{
Serial.begin(9600);
Serial.setTimeout(100);
}
void loop()
{
while (Serial.available() > 0)
  {
      i = Serial.parseInt();
      stepper.setRPM(i); //move motor of other library
      //Serial.println(i); //I get the correct integer via the arduino monitor here.
  }
}
    

parseInt and the fact that it works when you type the number into the console both indicate that the device wants the string sent as text. So do not use BitConverter , instead:

byte[] bRPM = Encoding.Ascii.GetBytes($"{RPMMove}\r\n");

You may need to adjust the line ending, naturally using the same one configured in your terminal emulator ("console") should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM