0

更新:我使用的代码可以在这里找到:https ://dl.dropbox.com/u/2108381/MyArduinoPlot.java 我希望这有助于理解我的挑战。在此先感谢您的时间。

我想从 Arduino 读取传感器值并使用 Java 库 JFreeChart 绘制它们。

我在互联网上找到了一些代码(见下文),现在,我想将用于绘制动态折线图的代码和用于读取 Arduino 值的代码结合起来。两个代码都单独工作,但我被困在将它们结合起来。

绘制动态折线图的代码来自这里(绘制随机数据): http ://dirtyhandsphp.blogspot.in/2012/07/how-to-draw-dynamic-line-or-timeseries.html

在 Java 中读取 Arduino 值的代码来自这里: http ://arduino.cc/playground/Interfacing/Java

我假设(Java 中的新手,不过)相关部分在这里:

/**
 * Handle an event on the serial port. Read the data and print it.
 */
public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            int available = input.available();
            byte chunk[] = new byte[available];
            input.read(chunk, 0, available);

            // Displayed results are codepage dependent
            System.out.print(new String(chunk));

//              the code I tried

//              String MyValue = new String(chunk);
//              Double Value = Double.valueOf(MyValue); 

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
    // Ignore all the other eventTypes, but you should consider the other ones.
}

和这里:

public void actionPerformed(final ActionEvent e) {


//      Original Code

    final double factor = 0.9 + 0.2*Math.random();
    this.lastValue = this.lastValue * factor;

    final Millisecond now = new Millisecond();
    this.series.add(new Millisecond(), this.lastValue);

    System.out.println("Current Time in Milliseconds = " + now.toString()+", Current Value : "+this.lastValue);

//        my code
//        this.series.add(new Millisecond(), Value);


}

如何使public synchronized void serialEvent返回传感器值以及如何将其添加到this.series.add零件中?

我是Java的新手。

非常感谢任何直接帮助或与其他网站/帖子的链接。谢谢你的时间。

4

1 回答 1

1

在此示例中, ajavax.swing.Timer定期将新值添加到dataset计时器的ActionListener. 你会想从外面做。以下是如何进行的概述:

  1. 向上移动dataset成为newData实例变量

    DynamicTimeSeriesCollection dataset;
    float[] newData = new float[1];
    
  2. 添加一个将数据附加到图表的方法dataset

    public synchronized void addData(byte[] chunk) {
        for (int i = 0; i < chunk.length; i++) {
            newData[0] = chunk[i];
            dataset.advanceTime();
            dataset.appendData(newData);
        }
    }
    
  3. 从 调用方法serialEvent()

    demo.addChunk(chunk);
    
于 2012-08-22T19:12:32.070 回答