如何在处理中管理多个串行消息

How to manage several Serial messages in processing

我正在读取我的 RFID 卡的 UID 并将其存储在一个名为 myUID 的变量中。

之后我用工厂密钥授权卡并读取块号 4(之前已写入)并将其存储在字符串中 readBlock

在 Arduino 上,我像这样将变量打印到串行接口上​​。

Serial.println(myUID);
Serial.println(readBlock);

在客户端,我使用 Java 程序读取串行数据。我的程序使用 Processing Library.

Serial mySerial;
PrintWriter output;

void setup() {
 output = createWriter( "data.txt" );
 mySerial = new Serial( this, Serial.list()[0], 9600 );
 mySerial.bufferUntil('\n');
}

void draw(){
  while (mySerial.available() > 0) {
  String inBuffer = mySerial.readString();   
  if (inBuffer != null)
    output.println(inBuffer); 
  }
}
void keyPressed() { // Press a key to save the data
  output.flush(); // Write the remaining data
  output.close(); // Finish the file
  exit(); // Stop the program
}

现在我的 data.txt 应该看起来像

xxx xxx xxx xxx (uid of card)
00 00 00 00 00 00 00 00 ... (read block from card)

但看起来像

237 63 58 1
07
37 37 95
 37 
97 98 50 54 37 5
4 55 102 55 52 
45 98

我在 Processing Library 中尝试了一些类似 readStringUntil('\n'); 的东西,但没有成功。

对于所有感兴趣的人,我已经用很多小时的搜索自己解决了这个问题 Google,所以也许这对以后的人有帮助:

我可以用这段代码修复它:

import processing.serial.*;
int count = 0;
String input = "";
String fileName = dataPath("SET FILEPATH HERE");

Serial mySerial;

import java.io.*;

void setup() {
  mySerial = new Serial(this, Serial.list()[0], 9600);
  mySerial.bufferUntil('\n');

  File f = new File(fileName);
  if (f.exists()) {
    f.delete();
  }
}

void draw(){}

// listen to serial events happening
void serialEvent(Serial mySerial){
  input = mySerial.readStringUntil('\n'); 
  write(input, count);
  count++;
}

// function for writing the data to the file
void write(String inputString, int counter) {
  // should new data be appended or replace any old text in the file?  
  boolean append = false;

  // just for my purpose, because I have got two lines of serial which need to get written to the file 
  //(Line 1: UID of card, Line 2: Read block of card)  
  if(counter < 2){
    append = true;  
  }
  else{
    count = 0;
  }


  try {
    File file = new File("D:/xampp/htdocs/pizza/src/rfid/data.txt");

    if (!file.exists()) {
      file.createNewFile();
    }

    FileWriter fw = new FileWriter(file, append);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter pw = new PrintWriter(bw);

    pw.write(inputString + '\n');
    pw.close();
  }
  catch(IOException ioe) {
    System.out.println("Exception ");
    ioe.printStackTrace();
  }
}