如何从串行监视器读取char数组并相应地命令arduino?

时间:2019-02-11 16:38:56

标签: arduino

当前,我正在一个项目中,从串行监视器读取char输入并命令Arduino打开/关闭特定的引脚。我面临的问题是,我无法读取在串行监视器中输入的完整char数组。谁能告诉我我在做什么错?

#define X 13 //led pin

char txt[15]; 
int i; 
int Status=0;

void setup() {   // put your setup code here, to run once:  
pinMode(X,OUTPUT);// setting the pin flow of control as output

 Serial.begin(9600);  
 while(!Serial)   
 {
    ;  //to wait for pc to connect  
 }   
 Serial.println("\nHome Automation");   
 dashprint();  


}

void loop() {   // put your main code here, to run repeatedly:  
if(Serial.available()>0)    
{   i=0;
    while(Serial.available()>0)   //if serial available
    { char inchar=Serial.read();
      txt[i]=inchar; // add char to txt string
      i++;// increment to where to write next
      txt[i]='\0'; //null termination

     }    
  Serial.print(txt);    
  check();
  } 
  }

void dashprint() //to print dashes 
{
Serial.println("-----------------------------------------------");  
Serial.println("give me some command"); //ask for command    
  }

void check() 
{    if(strncmp(txt,"ON",2)==0)   
      {
         digitalWrite(X,HIGH);
         Status=1;
          }   
      else if(strncmp(txt,"OFF",3)==0)  
       { digitalWrite(X,LOW);
         Status=0;
          }   
      else if(txt=="STATUS")  
       { 
           } 
      else Serial.println("ERROR");
   }

输出:

家庭自动化

给我一​​些命令 错误 错误

错误

预期输出:

家庭自动化

给我一​​些命令 开启

2 个答案:

答案 0 :(得分:1)

您的arduino速度太快,无法在一轮中读取文本“ ON”。

9600是每个字符1毫秒。 一个简单的解决方法是,添加一些延迟

p {max-width:320px; line-height:3em; font-family:Arial; color:#666; font-size:12px;}
span[title] {position:relative; border-bottom: 1px solid currentColor;}
span[title]::after {
  content:attr(title);
  position:absolute; top:0; left:0; right:0; text-align:center; margin-top:.5em;
}

添加: 此外,您显然会收到一个'\ n'(换行符)字符。确保它不会引起麻烦。

如果您期望超过3个字符(“状态”),请增加延迟或总体上采用更好的方法

答案 1 :(得分:0)

struct MYObject {char a[256];};     
//structure works well with EEPROM put and get functions.  
//also lets to input large strings, more then 64 bytes, as http     
void setup() {    
MYObject str ={" "};    
Serial.begin(115200);     
while (!Serial.available()) delay (10); //wait for string   
int i = 0;  
int k= Serial.available();  
while (k  > 0){     
char inchar = Serial.read();  //read one by one character    
str.a[i] = inchar;               
i++;    
if (k < 3) delay (10); //it gives possibility to collect more characters on stream    
k = Serial.available();     
}     
str.a[i]='\0'; //null terminator     
//now lets see result      
Serial.println(str.a);     
//.....      
}