3
A
回答
5
有幾種方法可以從Serial
讀一個整數,在很大程度上取決於如何發送時的數據進行編碼。 Serial.read()
只能用於讀取單個字節,從而需要被髮送的數據能夠從這些字節重建。
下面的代碼可能會爲你工作。它假定串行連接已被配置爲9600波特,該數據被髮送作爲ASCII文本,並且每個整數分隔換行符(\n
):
// 12 is the maximum length of a decimal representation of a 32-bit integer,
// including space for a leading minus sign and terminating null byte
byte intBuffer[12];
String intData = "";
int delimiter = (int) '\n';
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available()) {
int ch = Serial.read();
if (ch == -1) {
// Handle error
}
else if (ch == delimiter) {
break;
}
else {
intData += (char) ch;
}
}
// Copy read data into a char array for use by atoi
// Include room for the null terminator
int intLength = intData.length() + 1;
intData.toCharArray(intBuffer, intLength);
// Reinitialize intData for use next time around the loop
intData = "";
// Convert ASCII-encoded integer to an int
int i = atoi(intBuffer);
}
+1
我不得不改變字節intBuffer [12]; char charBuffer [12];它編譯 – fersarr 2014-04-27 19:44:40
5
您可以使用Serial.parseInt()功能,在這裏看到:http://arduino.cc/en/Reference/ParseInt
+0
不知道什麼上述方法的好處是,但這完全爲我工作。 – 2016-01-26 19:22:20
相關問題
- 1. arduino上的串行數據輸出GPIO
- 2. 串行消息分離
- 3. Arduino串行中斷
- 4. 串行python到arduino
- 5. Arduino串行寫入
- 6. Arduino串行讀取
- 7. GUI消息隊列(消息泵 - 並行或串行)
- 8. Arduino的寫入字符串到串行
- 9. Arduino的巨型多串行字符串
- 10. Arduino - Qt C++串行接口
- 11. Arduino Uno串行監視器
- 12. Arduino - 處理串行通信
- 13. Xbee和Arduino串行通信
- 14. Arduino串行通訊問題
- 15. Matlab arduino串行通信
- 16. 消息框上的不同消息
- 17. 將消息發送到在Arduino中以字符串形式存儲的號碼
- 18. 用多行在ios上的Toast消息
- 19. 上的HTML消息
- 20. 結算的Arduino的串行緩衝器
- 21. Arduino的按鈕上沒有連續的串行 「1」
- 22. 爲什麼我的Arduino上沒有可用的串行數據?
- 23. Arduino的串行通信輸出
- 24. 閱讀python中的arduino串行連接
- 25. 寫入Arduino的串行監視器框
- 26. 基本的Arduino串行通信
- 27. C++與Arduino的串行通信超時
- 28. 的Arduino和Visual C++串行通信
- 29. 如何使用Arduino的串行打印
- 30. C++與Arduino的libserial串行連接
是整型字符固定數量還是會由一個非數字被終止? – walrii 2013-04-21 07:29:00
嗯...'Serial.read()'已經返回'int' ... – angelatlarge 2013-04-21 07:54:35
@angelatlarge'Serial.read()'不會返回'int'但只有這樣調用代碼可以成功讀取區分和一個錯誤。在檢查它沒有返回「-1」(表示錯誤)後,正確的用法將返回值視爲一個「byte」。 – 2013-04-22 11:29:46