2012-05-04 112 views
5
#include <stdio.h> 

#define LED 13 

void setup() { 
    pinMode(LED, OUTPUT); 
    Serial.begin(9600); 
} 

void loop() { 
    int i; 
    char command[5]; 
    for (i = 0; i < 4; i++) { 
    command[i] = Serial.read(); 
    } 
    command[4] = '\0'; 

    Serial.println(command); 

    if (strcmp(command, "AAAA") == 0) { 
    digitalWrite(LED, HIGH); 
    Serial.println("LED13 is ON"); 
    } else if (strcmp(command, "BBBB") == 0) { 
    digitalWrite(LED, LOW); 
    Serial.println("LED13 is OFF"); 
    } 
} 

我想读取一个4字符长的字符串与Arduino的串行,当它是AAAA打开一个LED,当它是BBBB关闭串行。Arduino从串行读取字符串

但是,当我输入“AAAA”时,它会读取带有许多“ÿ”的“AAAÿ”。

我想我正确地阅读所有内容,但是它不能很好地工作,对我在做什么错误有任何想法?

+0

确认您的波特率,停止位,流量控制和奇偶校验相同的两端。即使你“知道这是真的”,花3分钟时间来验证它。节省自己的时间。 –

+0

你的'Serial.begin()'代码是什么? – qwertz

+0

这是9600,我也发布了它。 –

回答

1
#define numberOfBytes 4 
char command[numberOfBytes]; 

    void serialRX() { 
     while (Serial.available() > numberOfBytes) { 
     if (Serial.read() == 0x00) { //send a 0 before your string as a start byte 
      for (byte i=0; i<numberOfBytes; i++) 
      command[i] = Serial.read(); 
     } 
     } 
    } 
1

你应该检查是否有东西可供阅读。如果不是,则()将返回-1。您可以使用Serial.available()来检查读取缓冲区。

9
String txtMsg = ""; 
char s; 

void loop() { 
    while (serial.available() > 0) { 
     s=(char)serial.read(); 
     if (s == '\n') { 
      if(txtMsg=="HIGH") { digitalWrite(13, HIGH); } 
      if(txtMsg=="LOW") { digitalWrite(13, LOW); } 
      // Serial.println(txtMsg); 
      txtMsg = ""; 
     } else { 
      txtMsg +=s; 
     } 
    } 
} 
1

它读取“Y”,因为没有字符缓冲区中读取。其他字符需要一段时间才能从uart缓冲区中卸载。所以,你不能做一个循环来读取字符。在阅读之前,您必须等待另一个角色可用。

此外,这种等待字符的方式并不是最好的方式,因为它阻止了主循环。

这是我做我的节目:

String command; 

void loop() 
{ 
    if(readCommand()) 
    { 
     parseCommand(); 
     Serial.println(command); 
     command = ""; 
    } 
} 

void parseCommand() 
{ 
    //Parse command here 
} 

int readCommand() { 
    char c; 
    if(Serial.available() > 0) 
    { 
     c = Serial.read(); 
     if(c != '\n') 
     {  
      command += c; 
      return false; 
     } 
     else 
      return true; 

    } 
}