如何从蓝牙到arduino接收2字节的十进制数

时间:2015-05-12 13:32:48

标签: bluetooth arduino

我可以轻松地通过arduino发送1byte十进制数(0-256),但我无法将其用于2字节数。

这里的代码用于在0-256之间发送数据,这很有用。

#include <SoftwareSerial.h>

#include <Servo.h> 
Servo myservo;

int bluetoothTx = 10;
int bluetoothRx = 11;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  myservo.attach(9);
  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}

void loop()
{
  //Read from bluetooth and write to usb serial
  if(bluetooth.available()> 0 )
  {
    int servopos = bluetooth.read();
    Serial.println(servopos); 
    myservo.write(servopos);
  }


}

我尝试编程为2个字节的数字,但我无法成功,MSB和LSB数据没有正确移位。任何有关此代码的帮助对我来说都会有很大帮助。

#include <SoftwareSerial.h>

#include <Servo.h> 
Servo myservo;

int bluetoothTx = 7;
int bluetoothRx = 8;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  myservo.attach(9);
  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}

void loop()
{
  //Read from bluetooth and write to usb serial
  if(bluetooth.available()>= 2 )
  {
    int servopos = bluetooth.read() << 8;
    servopos |= bluetooth.read();
    Serial.println(servopos); 
    myservo.write(servopos);
  }


}

0 个答案:

没有答案