2016-08-26 70 views
2

我想使用USB端口從c#程序向arduino Uno發送整數(101和1616之間)。 我知道如何使用arduino Uno的寄存器,並想知道在通過USB端口恢復數據時是否有中斷。 目前我正在使用這個,但它不工作。如何通過USB端口將數字從C#發送到Arduino Uno?

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

而且在我使用這個代碼的C#程序:

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

我怎樣才能發送C#程序和Arduino的UNO之間更大的數字? 是否有接收這些類型的數字的特殊中斷?

回答

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轉換成字符,按字節發送字節和在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 

} 

} 
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 
       } 
+0

請提供除了代碼一些解釋。 – Jan

+0

當然,你不瞭解@Jan – rhsn

相關問題