[英]Read String from Arduino serial port with JAVA and jssc lib
字符串Serial_Input必須包含序列號卡RFID(MIFARE),例如A45F45A7(8字節)。 有時,當我將卡靠近arduino的RFID讀取器時,字符串像這樣的A45F45(被截斷),會漏掉任何字符。 有一個更好的解決方案,而while循環? (更優雅,更有效)使用Arduino IDE串行監視器,卡的序列號正確。
public static void connectionToCom(SerialPort serialPort, ComboBox<String> cbxComPort, TextArea txaMessages) throws SerialPortException
{
int baudrate = 9600; int databits = 8; int stopbits = 1; int parity = 0;
serialPort.openPort() ;
serialPort.setParams(baudrate, databits, stopbits, parity) ;
String Serial_Input = null;
try {
while (true)
{
if (serialPort.readString() != null)
{
Serial_Input = serialPort.readString(8);
System.out.println("Card Serial: " + Serial_Input + "\n");
//serialPort.closePort();
}
}
}
catch (SerialPortException ex){
txaMessages.appendText(ex.toString());
}
}
您可以使用方法addEventListener(SerialPortEventListener偵聽器,整數掩碼)。 每當您通過serialPort接收到字節時,它將調用回調方法。
字符串不完整的問題可能是2個問題
在接收到整個字符串之前,代碼正在執行。 要解決此問題,您必須添加代碼以驗證所接收的字符串的長度。
您使用readString兩次。 初次使用時,您可能會丟失字符串的某些字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.