我正在尝试从 android读取方向传感器值并将它们发送到 Arduino。android 将以字节为单位发送 valueX、valueY 和 valueZ。
每个值将以 x、y 和 z 字符结尾(from.java)。
String valueX = xPosition + "x";
btSocket.getOutputStream().write(valueX.toString().getBytes());
当我旋转手机时,该值将只读取一个值,即 valueZ。
#include <SoftwareSerial.h>
SoftwareSerial mySerial(6, 5);
// Pin 13 - LED
int ledG = 13;
int ledR = 12;
int ledW = 11;
int state;
String value,value1,valueZ,valueY,valueX;
void setup() {
// initialize the digital pin as an output.
pinMode(ledG, OUTPUT);
pinMode(ledR, OUTPUT);
pinMode(ledW, OUTPUT);
// initialize serial communication at 9600 bits per second:
mySerial.begin(9600);
}
void loop() {
if(mySerial.available() > 0){
state = ((byte)mySerial.read());}
if (state == 'z') {
int state = valueZ.toInt();
//state = state + valueZ;
digitalWrite(ledG, HIGH);} // turn the LED on (HIGH is the voltage level)
else if (state != 'z' && state!=0) {
digitalWrite(ledG, LOW);} // turn the LED off by making the voltage LOW
else if ( state == 'y') {
int casted2 = valueY.toInt();
digitalWrite(ledR, HIGH);}
else if (state != 'y') {
digitalWrite(ledR, LOW);}
else if (state == 'x') {
int casted = valueX.toInt();
digitalWrite(ledW, HIGH);}
else if (state != 'x') {
digitalWrite(ledW, LOW);}
delay(1); // wait for 100ms
//For debugging purpose
//Serial.println(state);
}