I have to use the jSerialComm-API to get my arduino sensor data through my COM-port.
This is my Sensor-Class that displays the sensor data on my eclipse-terminal.
Now I want to use the method (extractDataFromCOM()
) to provide the sensor-data to other classes.
import com.fazecast.jSerialComm.*;
public class Sensor {
public void connect() {
SerialPort comPort = SerialPort.getCommPorts()[0];
comPort.openPort();
comPort.addDataListener(new SerialPortDataListener() {
public int getListeningEvents() {
return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
}
public void serialEvent(SerialPortEvent event) {
byte[] newData = event.getReceivedData();
for (int i = 0; i < newData.length; ++i)
System.out.print((char)newData[i]); //Terminal output
}
});
}
public String extractDataFromCOM(String data) {
//? ? ?
return data;
}
}
In the TextDatabase.java class I want to invoke the method (Sensor.extractDataFromCOM()
) to retrieve the data and then store it in a textfile:
public class TextDatabase {
public static void main(String[] args) throws IOException {
Sensor s1 = new Sensor();
//endless loop to get flow of sensor data?
while (true) {
String mydata = s1.extractDataFromCOM();
//store it in a database or textfile:
FileWriter fw = new FileWriter("mydata.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(mydata);
//(...)
}
}
}
Question: How do I access the class 'Sensor' from class 'TextDatabase' and retrieve the sensor data to store it in a textfile?
question from:
https://stackoverflow.com/questions/65642021/how-can-i-retrieve-the-arudino-sensor-data-from-com-port-and-save-it-in-a-textfi 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…