2016-06-14 62 views
0

我從Arduino的發送整數值,使用pyserial Arduino的代碼,閱讀它Python是:閱讀來自Arduino的整數使用pyserial

Serial.write(integer) 

而且pyserial是:

ser=serial.Serial ('com3',9600,timeout =1) 
X=ser.read(1) 
print(X) 

但不打印除空格外的任何東西 有誰知道如何讀取從Python中的arduino傳入的整數?

+0

'integer'需要什麼值?它的類型究竟是什麼?難道是你傳遞的這些字節可能被解釋爲不可打印的ASCII或空格? –

回答

0

您可能需要使用一個開始位。

問題可能是由於pyserial運行時arduino已經寫入整數了嗎?

所以從pyserial字符寫入Arduino的信號開始喜歡

ser=serial.Serial ('com3',9600,timeout =1) 
    ser.write(b'S') 
    X=ser.read(1) 
    print(X) 

一旦你得到這個起始位來自Arduino的寫整數。

0

這是不正確的方式從Arduino讀取IntegerInteger是一個32位的類型,而串行端口將被設置爲EIGHTBITS(無論是在pyserial和Arduino的。糾正我,如果我錯了)的字節大小,因此,你必須寫Character版本Integer的從Arduino通過串口傳輸時,因爲Character只需要EIGHTBITS,這也是非常容易完成所需工作的便捷方式。

長話短說,在傳輸之前將您的Integer轉換爲StringCharacter陣列。 (機會有可用於轉換的內置功能)。

在一個側面說明這裏是你寧願正確的Python代碼使用方法:

ser = serial.Serial(
     port='COM3', 
     baudrate=9600, 
     parity=serial.PARITY_NONE, 
     stopbits=serial.STOPBITS_ONE, 
     bytesize=serial.EIGHTBITS 
    ) 
    #RxTx 
    ser.isOpen() 
while 1: 
    out = '' 
    while ser.inWaiting() > 0: 
     out += ser.read(1) 
    if out != '': 
     print ">>Received String: %s" % out 
+0

甚至不需要檢查設置btw,'HardwareSerial :: write()'的所有其他整數重載只需執行C風格轉換爲'uint8_t'。 –

+0

@IljaEverilä我不知道arduino部分,因爲我在AT Mega AVR中完成了它,我不知道你剛剛說了什麼。 –

+1

@SiHa編輯,我試圖手動編寫的代碼,應該剛剛複製:) –

0

我測試了一個簡單的程序:

的Arduino:

void setup() { 
    // initialize serial communication at 9600 bits per second: 
    Serial.begin(9600); 
} 

void loop() { 
    int f1=123; 
    // print out the value you read: 
    Serial.println(f1); 
    delay(1000);  
} 

Python:

import serial 
ser = serial.Serial() 
ser.baudrate = 9600 
ser.port = 'COM5' 

ser.open() 
while True: 
    h1=ser.readline() 
    if h1: 
    g3=int(h1); #if you want to convert to float you can use "float" instead of "int" 
    g3=g3+5; 
    print(g3)