使用socket将ascii字符串从Android发送到Arduino时出现乱​​码输出

时间:2015-05-04 14:36:53

标签: android sockets arduino

我正在尝试将数据从Android发送到带有Wifi屏蔽的Arduino。

我在Arduino上收到的数据与我从Android发送的数据不一样。例如,当我发送字符'A'(ASCII 65)时,我在Arduino上收到的是下划线'_'(ASCII 95)。

以下列表显示了我从Android发送的内容以及它如何映射到我在Arduino中收到的内容的一些示例。也许有人可以看到这里发生了什么?

Sent From Android         || Received in Arduino
----------------------------------------------------
Symbol | Dec | Bin        || Symbol | Dec | Bin
----------------------------------------------------
A      | 65  | 01000001   || _      | 95  | 01011111
B      | 66  | 01000010   || /      | 47  | 00101111
C      | 67  | 01000011   || ^      | 94  | 01011110
D      | 68  | 01000100   || ETB    | 23  | 00010111
E      | 69  | 01000101   || ]      | 93  | 01011101
F      | 70  | 01000110   || .      | 46  | 00101110
G      | 71  | 01000111   || \      | 92  | 01011100
H      | 72  | 01001000   || VT     | 11  | 00001011
I      | 73  | 01001001   || [      | 91  | 01011011
J      | 74  | 01001010   || -      | 45  | 00101101
K      | 75  | 01001011   || Z      | 90  | 01011010

我注意到这里形成了几种模式。

查看每个奇数十进制发送值:

65 -> 95
67 -> 94
69 -> 93
71 -> 92
73 -> 91
75 -> 90

查看每个其他偶数编号的十进制发送值:

66 -> 47
70 -> 46
74 -> 45

我以57600的波特率运行此功能,并尝试将其减速至9600,结果相同。

我用于发送和接收的代码如下:

从Android发送

DataOutputStream outStream;

try {
    Socket socket = new Socket("192.168.16.254", 8080);
    outStream = new DataOutputStream(socket.getOutputStream());

    outStream.write(sendString.getBytes("US-ASCII"));
    socket.close();

} catch (IOException e) {
    e.printStackTrace();
}

在Arduino中接收

if(Serial.available()) {
    NowMS = millis();

    // Loop to read data from the Serial buffer into our String
    while(true) {

      // Loop until we have some data or we time out
      while(Serial.available() == false) {
        if (millis() > NowMS + TimeoutMS) {
          // we haven't received any more data for a while.
          timed_out = true;
          break;
        }
      }

      if (timed_out) {
        inputString = "";
        break;
      }

      // We haven't timed out and we have serial data available, so add the next char to our String
      int incomingByte = Serial.read();
      char receivedChar = (char)incomingByte;
      Serial.print("Received Char: ");
      Serial.print(receivedChar);
      Serial.print(" [");
      Serial.print(incomingByte);
      Serial.println("]");

      inputString += receivedChar;

      if (inputString.endsWith("=end")) {
        // we've reached the end of the request
        has_request = true;
        break;
      }
    }

    if (has_request) {
      Serial.print("Received String: ");
      Serial.println(inputString);
      has_request = false;
      inputString = "";
    }
  }  

0 个答案:

没有答案