2016-06-28 64 views
0

我想从arduino发送一个int到android通过蓝牙,但如果我发送让我说56,我在android端收到8 ...有反正我可以接受56,因为它是和优选以字符串形式包括字符停止转换十进制ascii

Arduino的代码:

int level = 56; 
Serial.write(level); 

的Android代码:

public void run() { 
     byte[] buffer = new byte[128]; 
     int bytes; 


     while (true) { 
      try { 
       bytes = connectedInputStream.read(buffer); 
       String strReceived = new String(buffer, 0,bytes); 
       final String msgReceived =/* String.valueOf(bytes) + 
         " bytes received: " 
         + */strReceived; 



       runOnUiThread(new Runnable(){ 

        @Override 
        public void run() { 
         textStatus.setText(msgReceived); 
         value = msgReceived ; 
        }}); 

值被定义为静态字符串作为一个类变量

+3

您的代码正在将字节转换为字符串。如果你不想这样做,不要......如果你不想将接收到的字节转换为文本,你为什么要调用字符串构造函数并不清楚。 –

+0

我将需要在应用程序的未来阶段的字符,所以这就是为什么我会优先考虑 –

+1

警告:[新的字符串(字节[],int,int)](https://docs.oracle.com/javase/8/ docs/api/java/lang/String.html#String-byte:A-int-int-)使用平台的默认字符集和编码。相反,您应该在两个系统上明确使用相同的内容。 –

回答

1

你正在将字节转换为字符串,因此你得到'8'这是(char)56;。如果你不想要,只需按照以下步骤操作即可。

bytes = connectedInputStream.read(buffer); 
String tmp = ""; 
for(int i=0;i<bytes;i++) 
    tmp += Byte.toString(buffer[i]); 
final String msgReceived = tmp; 

编辑

如果发送如下,例如。

Serial.write(56); 
Serial.write(76); 

您将收到msgReceived会有什么5676,如果这两个字节读取。你可以明显改变这种行为,无论你想要的方式。

+0

可以编辑一个循环的例子...?// //我也不能从运行函数访问变量 –

+0

这取决于你想用接收字节做什么。等等,我会编辑代码并提及它会给出的输出。 –

+0

@PuneetSharma检查编辑。 –

相关问题