2017-05-11 234 views
-1
/* 
    String to Integer conversion 

Reads a serial input string until it sees a newline, then converts 
the string to a number if the characters are digits. 

The circuit: 
No external components needed. 

created 29 Nov 2010 
by Tom Igoe 

This example code is in the public domain. 
*/ 
#include <LiquidCrystal.h> 
LiquidCrystal lcd(23, 22,13,12,11,10); 
String inString = ""; // string to hold input 

void setup() { 
    // Open serial communications and wait for port to open: 
    Serial.begin(19200); 
    while (!Serial) { 
    ; // wait for serial port to connect. Needed for native USB port only 
    } 
    lcd.begin(20, 4); 

    // send an intro: 
    //println("\n\nString toInt():"); 
    //Serial.println(); 
} 

void loop() { 
    // Read serial input: 
    while (Serial.available() > 0) { 
    lcd.setCursor(0,0); 
    lcd.print("welcome"); 
    int inChar = Serial.read(); 
    if (isDigit(inChar)) { 
     // convert the incoming byte to a char 
     // and add it to the string: 
     inString += (char)inChar; 
    } 
    // if you get a newline, print the string, 
    // then the string's value: 
    if (inChar == '\n') { 
     int data = inString.toInt() ; 
     lcd.setCursor(0,1); 
     lcd.print("speed: "); 
     lcd.println(data); 
     if(data > 50){ 
     lcd.setCursor(0,2); 
     lcd.print("Over speed"); 
     } 
     else{ 
     lcd.setCursor(0,2); 
     lcd.print("Under speed limit "); 
     } 

    // Serial.print("Value:"); 
     //Serial.println(inString.toInt()); 
     //Serial.print("String: "); 
     //Serial.println(inString); 
     // clear the string for new input: 
     inString = ""; 
    } 
    } 
} 

Python code for serial interfacingArduino的與樹莓Pi的串行接口技術來傳送2個數據

在使用串行監控用的Arduino此代碼的工作,但與樹莓裨運行接口的Arduino時,僅「歡迎」信息來在LCD上而不是我通過Raspberry Pi傳輸的數據(2位數字),可能是由於Raspberry Pi上的Python程序或其他原因。

+0

難道你真的只花了屏幕的照片,而不是僅僅簡單地複製粘貼代碼?爲什麼? –

+0

因爲我無法從R pi複製粘貼python代碼到我的筆記本電腦= D;) – Saddaqat

回答

1

您正在檢查「\ n」,但從未發送過一個。所以你永遠不會觸發

如果(INCHAR ==「\ n」)

+0

謝謝。我剛在這裏發佈問題後解決了這個問題,就像你說的那樣是問題.. – Saddaqat

+0

需要一些幫助,我會感謝你 'speed =「70 \ r \ n」 arduino.write(speed)' 此代碼工作正常,並給出了把在LCD上的Arduino像 「速度= 70 超速」 但是,當我使用這個語句 「速度= 70 arduino.write(‘速度\ r \ n’)」 它將在LCD上顯示 「speed = 0 欠速限制」。爲什麼?我正在做這個速度限制監控系統,當代碼找到它的速度存儲在「lastlimit」 arduino.write(「lastlimit \ r \ n」)給出了上述問題..我不是很熟悉python,我試過但沒有找到任何解決方案 – Saddaqat

+0

arduino.write(「speed \ r \ n」)'將寫入需要寫入的文本字符串「speed \ r \ n」而不是「70 \ r \ n」(speed +「\ r的\ n「)。或者更可能是(str(speed)+「\ r \ n」),因爲速度是一個整數。這有幫助嗎?如果不是,請發佈一個新問題,並讓我知道 – JeffUK