简体   繁体   中英

How can I retrieve the arudino sensor data from COM-PORT and save it in a textfile?

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?

Put the data from the SerialPortEvent to a class variable in the serialEvent method. Then pass that to external through the extractDataFromCOM

    public class Sensor {

    final Queue<byte[]> data = new PriorityQueue<byte[]>();
    
    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();
                data.offer(newData);
            }
        });
    }

    public byte[] extractDataFromCOM() {
        //? ? ?
        //convert to String if required
        return data.poll();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM