1

我可以从手机向 Arduino 发送数据,但在手机中看不到从 Arduino 发送的数据。我认为程序永远不会进入处理程序部分,但我不知道如何解决它。

这是安卓代码:

void beginListenForData() {
  final Handler handler = new Handler();
  final byte delimiter = 10; //This is the ASCII code for a newline character
  stopWorker = false;
  readBufferPosition = 0;
  readBuffer = new byte[1024];
  workerThread = new Thread(new Runnable() {
    public void run() {
      while(!Thread.currentThread().isInterrupted() && !stopWorker) {
        try {
          int bytesAvailable = mmInputStream.available();
          if(bytesAvailable > 0) {
            byte[] packetBytes = new byte[bytesAvailable];
            mmInputStream.read(packetBytes);
            for(int i=0;i<bytesAvailable;i++) {
              byte b = packetBytes[i];
              if(b == delimiter) {
                ///Here is the problem
                byte[] encodedBytes = new byte[readBufferPosition];
                System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                final String data = new String(encodedBytes, "US-ASCII");
                readBufferPosition = 0;
                handler.post(new Runnable() {
                  public void run() {
                    myLabel.setText(data);
                    texto.setText("data");
                  }
                });
              } else {
                readBuffer[readBufferPosition++] = b;
              }
            }
          }
        }
        catch (IOException ex) {
          stopWorker = true;
        }
      }
    }
  });
  workerThread.start();
}

这是Arduino代码:

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
}
void loop() {
  if(Serial.available()) {
  // if data is available to read
  val = Serial.read();
  // read it and store it in 'val'
}
if(val == 'H') {
  // if 'H' was received
  digitalWrite(ledpin, HIGH);
  // turn ON the LED
  delay(1000);
  Serial.print("Recibido");
} else {
  //digitalWrite(ledpin, LOW);
  // otherwise turn it OFF
}
delay(100);
// wait 100ms for next reading 
}
4

0 回答 0