HC-05蓝牙模块始终发送-1

时间:2017-06-04 17:08:18

标签: bluetooth arduino

我使用2个HC-05蓝牙模块在2个Arduino Nanos之间进行通信 我已经将HC-05的波特率设置为9600,一个作为主设备,另一个设置为从设备 主设备始终发送值-1,但该值应来自模拟输入 我已经检查了模拟读数,值是正确的 但是当我检查蓝牙串行读数时,值为-1 有人可以帮帮我吗?

主码

#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3);

int state = 0;
const int ledPinon = 8;  //the pin your led is connected to
const int ledPin = 7;  //the pin your led is connected to

int xPin = A1;
int xPosition = 0;
int val = 0;

void setup() {

  Serial.begin(9600);
  mySerial.begin(9600);

  pinMode(xPin, INPUT);
  pinMode(ledPin, OUTPUT);

}

void loop() {
  xPosition = analogRead(xPin);
  val = map(xPosition, 0, 1023, 0, 180);

  if (mySerial.available()){
  if (xPosition > 506) {
    digitalWrite(ledPin, HIGH);
    mySerial.write(val);  //sends a 1 through the bluetooth serial link
  }

  else if ((xPosition <506)||(xPosition >502)){
    mySerial.write('0');
    digitalWrite(ledPin, LOW);
  }

  else if (xPosition <502){
    mySerial.write(val);
    backblink();
  }
  int check = mySerial.read();
  Serial.print(val);
  Serial.print("   |    ");
  Serial.println(check);
  delay(200);
}
}
void ledblink(){
  digitalWrite(ledPinon, HIGH);
  delay(200);
  digitalWrite(ledPinon, LOW);
  delay(200);
}

void backblink(){
  digitalWrite(ledPin, HIGH);
  delay(80);
  digitalWrite(ledPin, LOW);
  delay(80);
}

从属代码

#include <SoftwareSerial.h>
#include <Servo.h>

SoftwareSerial mySerial(2, 3);

int BluetoothData; // the data given from Computer
Servo ESC;

int state;
const int ledPinon = 8;  //the pin your led is connected to
const int ledPin = 7;  //the pin your led is connected to
const int ledPinback = 6;  //the pin your led is connected to

void setup() {
  // initialize digital pin 8 as an output.

  Serial.begin(9600);
  mySerial.begin(9600);

  pinMode(ledPin, OUTPUT);
  ESC.attach(9);

  ledblink();
}

void loop() {
  Serial.println(state);
  if (mySerial.available()>0) { // Checks whether data is comming from the serial port 
    state = mySerial.read(); // Reads the data from the serial port
    BluetoothData = state;
    ESC.write(BluetoothData);
    Serial.println(state);
  }

  // Controlling the LED
  if (BluetoothData > 90) {
    digitalWrite(ledPin, HIGH); // LED ON
  }
  else{
    digitalWrite(ledPin, LOW); // LED ON
    //backblink(); // LED ON
  }

}

void ledblink(){
  digitalWrite(ledPinon, HIGH);
  delay(200);
  digitalWrite(ledPinon, LOW);
  delay(200);
}

void backblink(){
  digitalWrite(ledPin, HIGH);
  delay(100);
  digitalWrite(ledPin, LOW);
  delay(100);
}

1 个答案:

答案 0 :(得分:1)

在主代码中,如果检查Serial.available,那么可能向从属设备发送任何内容的所有行都是INSIDE。但是因为奴隶从不向主人发送任何东西,所以总是会返回0.所以主人可能根本就没有发送任何东西。