我正在尝试读取 RFID 的 UID 并将其发送到 Netbeans,但是当我尝试显示字符串时,它只显示最后一位。 例如,当我扫描RFID时,UID是C945AA2A,但是当显示在文本字段上时,它只显示2A或有时只显示A。我应该怎么做才能在文本字段中显示完整的 uid?我希望 arduino 发送数据一次,即使扫描到新的 rfid,也不会发送任何内容
这是 Arduino 代码:
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
//mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
//Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}
void loop() {
// Look for new cards
String code = "";
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
for (byte i = 0; i < mfrc522.uid.size; i++) {
code += String(mfrc522.uid.uidByte[i] < 0x10 ? "0" :"");
code += String(mfrc522.uid.uidByte[i], HEX);
}
code.toUpperCase();
Serial.println(code);
mfrc522.PICC_HaltA();
}
这是 Netbeans 代码:
public void detectPort(){
String ports = getPortNames();
SerialPort sPort = new SerialPort(ports);
try{
sPort.openPort();
sPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
sPort.setEventsMask(MASK_RXCHAR);
sPort.addEventListener((SerialPortEvent serialPortEvent) -> {
if(serialPortEvent.isRXCHAR()){
try{
String st = sPort.readString();
jTextField1.setText(st);
jLabel2.setText(st);
}catch(SerialPortException ex){
Logger.getLogger(SerialTest.class.getName())
.log(Level.SEVERE, null, ex);
}
}
});
}catch(Exception e){
System.out.print(e);
}
}
public String getPortNames(){
String defport = "";
String[] ports = SerialPortList.getPortNames();
for(String name: ports){
for(int i = 0; i < ports.length; i++){
jLabel1.setText(ports[i]);
defport = ports[i];
}
}
return defport;
}
最佳答案
我认为您的问题在于:
jTextField1.setText(st);
您可能希望将其添加到现有文本中,而不是设置文本。
jTextField1.setText(jTextField1.getText()+st);
关于java - setText() 显示和串行通信 (jSSC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42375458/