JAVA - Serial Data receiving illegal character

时间:2017-05-14 06:58:57

标签: java arduino raspberry-pi

I am trying to read a serial data with 4 characters sent from Arduino to the Raspberry Pi using the following codes.

int serialPort = Serial.serialOpen("/dev/ttyACM0",9600);
if(serialPort==-1){
    serialPort = Serial.serialOpen("/dev/ttyACM1",9600);
}    
char[] charArray = {' ', ' ', ' ', ' '}; //Initializing char array     
Serial.serialPuts(serialPort, 8 + "x"); //Sending Request Code to Arduino
int received = 0; 
while(received == 0){ //Wait for input
    for(int i = 0; i < 4; i++){
        charArray[i] = (char)Serial.serialGetchar(serialPort);
        received = 1;
    }
}
String tempString = new String(charArray);
System.out.println(tempString);

However, upon reading the "tempString", it shows this ���� instead of the data sent by the Arduino.

The Arduino is sending the proper data so I don't think the problem is in Arduino. This code works with 1 character data. What do you think is wrong with these codes?

P.S. The codes work if executed in a loop, though the first execution outputs illegal characters

1 个答案:

答案 0 :(得分:0)

由于不兼容的字符集,可能会发生上述问题。

如果您使用pi4j进行串行端口通信,则不推荐使用以下方法。

Serial.serialGetchar(serialPort)

我建议您使用

public static byte[] serialGetBytes(int fd,int length)

然后使用

将字节数组转换为String
public String(byte[] bytes,Charset charset)

我建议使用UTF 8.您可以尝试多种适合您需要的字符集。

[请随时编辑此答案以使其更有用]