如何用usb端口从c#发送数字到Arduino Uno

本文关键字:数字 Arduino Uno usb 何用 | 更新日期: 2023-09-27 18:04:07

我想使用usb端口从c#程序发送整数(101和1616之间)到arduino Uno。我知道如何使用arduino Uno的寄存器,并想知道在此USB端口上恢复数据时是否有中断。目前我正在使用这个,但它不工作。

if(Serial.available()!=0) { input= (unsigned char)Serial.read(); }

在c#程序中,我使用以下代码:

 byte[] b = BitConverter.GetBytes(MyIntx);
                SerialPort.Write(b, 0, 4);

我如何在c#程序和arduino之间发送更大的数字?接收这些类型的号码是否有特殊的中断?

如何用usb端口从c#发送数字到Arduino Uno

你需要做的是一个字节一个字节地发送。有复杂的解决方案,也有简单的解决方案Complex: from https://www.baldengineer.com/arduino-multi-digit-integers.html

 void setup() {
  Serial.begin(9600);
}
unsigned int integerValue=0;  // Max value is 65535
char incomingByte;
void loop() {
  if (Serial.available() > 0) {   // something came across serial
    integerValue = 0;         // throw away previous integerValue
    while(1) {            // force into a loop until 'n' is received
      incomingByte = Serial.read();
      if (incomingByte == ''n') break;   // exit the while(1), we're done receiving
      if (incomingByte == -1) continue;  // if no characters are in the buffer read() returns -1
      integerValue *= 10;  // shift left 1 decimal place
      // convert ASCII to integer, add, and shift left 1 decimal place
      integerValue = ((incomingByte - 48) + integerValue);
    }
    Serial.println(integerValue);   // Do something with the value
  }
}

我的版本:将Int转换为Char,逐字节发送,然后在Arduino中将其转换回Int.

    int x=150;
    string x_char = x.ToString();
for(int i=0;i<x_char.length();i++)
{
//Send Each Character to Arduino  "c_char[i]".
}
//Send a new line or any special character to mark the break. For Instance "'n";
在Arduino:

String a;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
while(Serial.available()) {
a= Serial.readStringUntil(''n'); //Read until new line 
x = Serial.parseInt(); //This is your Integer value
}
}
 Connect();
            if (serialPort1.IsOpen)
            {
                int MyInt = ToInt32(lblMixerCase.Text);
                byte[] b = GetBytes(MyInt);
                serialPort1.Write(b, 0, 1);
                int MyInt2 = ToInt32(txtRPM.Text);
                if (MyInt2<=255)
                {
                    byte[] z = GetBytes(MyInt2);
                    serialPort1.Write(z, 0, 1); //For first 1 byte numbers
                }
                else if (MyInt2<=510)
                {
                    byte[] r = GetBytes(MyInt2);
                    serialPort1.Write(r, 0, 2); for 2 byte numbers
                }
                else if (MyInt2<=765)
                {
                    byte[] a = GetBytes(MyInt2);
                    serialPort1.Write(a, 0, 3); //for 3 byte numbers
                }
                else if (MyInt2<=1020)
                {
                    byte[] q = GetBytes(MyInt2);
                    serialPort1.Write(q, 0, 4); //for 4 byte numbers
                }