Arduino:在序列上打印更改我的值

时间:2014-12-24 16:55:16

标签: android bluetooth arduino

我对Arduino很新。我有一个简单的arduino + bluethooth模块,我想读取Android手机发送的值。我可以读取值,但在使用这些值时,我得到了奇怪的结果。这是代码:

#include <SoftwareSerial.h>
#define rx 10
#define tx 11

SoftwareSerial BtSerial(rx,tx);


void setup ()
{
  pinMode(rx, INPUT);
  pinMode(tx, OUTPUT);

  //setup bt connection
  BtSerial.begin (38400);

  Serial.begin(9600); 
}

void loop ()
{ 
  int command = 0;
    while(BtSerial.available() > 0) {
                // read the incoming byte:
                int incomingByte = BtSerial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, DEC);
                command+=incomingByte;
        }
    if(command>0){
      Serial.print("sum:");
      Serial.println(command, DEC);
    }
    switch(command){
      case 3090:
        Serial.println("avanti");
        break;
      case 5599:
        Serial.println("avanti destra");
        break;
      case 2266:
        Serial.println("destra");
        break;
      case 5649:
        Serial.println("indietro destra");
        break;
      case 3140:
        Serial.println("indietro");
        break;
      case 5066:
        Serial.println("indietro sinistra");
        break;
      case 1747:
        Serial.println("sinistra");
        break;
      case 5016:
        Serial.println("avanti sinistra");
        break;
      case 1734:
        Serial.println("stop");
        break;
      }
}

此代码有效,当我从手机发送命令时,我看到一定数量的“我收到:xxx”,一个“sum:xxxx”和case内的一个字符串,具体取决于值command

如果我评论这两行,问题就出现了:

Serial.print("I received: ");
Serial.println(incomingByte, DEC);

我希望看到一个“sum:xxxx”和其中一个字符串,而不是我看到一些带有“sum:xxx”的行,并且没有从开关中选择任何情况。

我错过了什么?

感谢

编辑:这是一个明确的例子:我从android发送一个特定值,上面的代码,这是我在串行监视器上得到的:

I received: 128
I received: 128
I received: 120
I received: 254
I received: 248
I received: 120
I received: 224
I received: 128
I received: 120
I received: 254
I received: 248
I received: 120
I received: 30
I received: 0
I received: 120
I received: 224
I received: 128
I received: 120
I received: 0
I received: 128
I received: 248
sum:3090
avanti

如果我评论提到的行并发送相同的值,这就是我得到的:

sum:128
sum:502
sum:720
sum:772
sum:472
sum:248
sum:248

1 个答案:

答案 0 :(得分:0)

感谢@TOMATO我解决了它。看起来在串行上打印会增加延迟,所以我删除了打印件并添加了明确的最小延迟:

 while(BtSerial.available() > 0) {
                // read the incoming byte:
                int incomingByte = BtSerial.read();

                // say what you got:
                //Serial.print("I received: ");
                //Serial.println(incomingByte, DEC);
                command+=incomingByte;
                delay(5);
        }