如何使用USB端口将数字从C#发送到Arduino Uno?

时间:2016-08-26 18:04:14

标签: c# arduino serial-port arduino-uno

我想使用usb端口从c#程序向arduino Uno发送整数(介于101和1616之间)。 我知道如何使用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 uno之间发送更大的数字? 是否有一个特殊的中断来接收这些类型的数字?

2 个答案:

答案 0 :(得分:0)

您需要做的是逐字节发送。有复杂的解决方案,很容易 复杂:来自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,逐字节发送和In 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";

IN 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

}

}

答案 1 :(得分:0)

 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
                }