【问题标题】:control a servo with android and arduino用android和arduino控制伺服
【发布时间】:2013-09-26 21:14:56
【问题描述】:

我正在尝试通过蓝牙用安卓手机和 arduino 控制伺服,但 arduino 中的数据以 char 形式接收,而 arduino 不知道何时收到所有数据而伺服不'正确移动。 arduino 代码是这样的: #包括

Servo myservo;

char val; // variable to receive data from the serial port
int ledpin = 13; // LED connected to pin 48 (on-board LED)

void setup() {

  pinMode(ledpin, OUTPUT);  // pin 48 (on-board LED) as OUTPUT
  Serial.begin(9600);       // start serial communication at 9600bps
    myservo.attach(9);  
}

void loop() {

  if( Serial.available() )       // if data is available to read
  {
    val = Serial.read();         // read it and store it in 'val'
  }
   if( val - 0 >= 0 && val - 0 <= 180){
 }
   // Serial.print("Recibido");

  delay(100);                    // wait 100ms for next reading
}    

如何从“val”中获取正确的值来控制伺服?

【问题讨论】:

  • val 的预期范围是多少?是 0 到 255(一个 8 位字节)吗?
  • @Robert Harvey val 是以度为单位的伺服位置,我应该减去 - '0' 在任何字符上得到数字,但显然代码是错误的

标签: android bluetooth controls arduino


【解决方案1】:

如果需要,您可以发送多个字符。简单地将每个新字符存储到一个数组中,然后对你的 android 程序进行编程以发送一个特定的字节来指示 val 读取的结束。

每次执行从串行读取时检查此“结束”字节将告诉您此字符是要存储还是将先前存储的字符转换为整数或您需要的任何数据类型。

比简单地转换该数组会告诉你正确的值。

【讨论】:

  • 你的意思是这样的吗:
  • 是的。类似的东西。但是你不应该使用这些while's。当您停止循环方法时。把你的循环()想象成一个永远不会结束的时间。请记住,从 char 中减去零会将当前数字返回为 int ;)
猜你喜欢
  • 2023-03-30
  • 1970-01-01
  • 2019-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多