在NetBeans中通过Arduino获取串口信号时遇到问题求助
Hey there, let’s work through the issues you’re hitting with your Arduino-NetBeans sensor project. I’ve looked over your code and setup, and here are the key fixes and troubleshooting steps to get your sensor readings plotting correctly:
Problem Recap
You’re using a potentiometer with Arduino to send analog readings to a NetBeans GUI, where you want to plot the values with JFreeChart. But you’re running into issues getting the data to display properly (or at all).
Your Provided Code (With Critical Fixes)
NetBeans Java Code
I’ve marked the key fixes with comments so you can see exactly what was changed:
package hirikattaproject; import com.fazecast.jSerialComm.SerialPort; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Scanner; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class HirikattaProject { static SerialPort chosenPort; public static void main(String[] args) { //Create configuration window JFrame window=new JFrame(); window.setTitle("Sensor value"); window.setSize(600,400); window.setLayout(new BorderLayout()); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //create a dropdown list and button JComboBox<String> portList=new JComboBox<String>(); JButton connectionButton=new JButton("connect"); JPanel topPanel=new JPanel(); topPanel.add(portList); topPanel.add(connectionButton); window.add(topPanel,BorderLayout.NORTH); //populate the dropdown list SerialPort[] portNames=SerialPort.getCommPorts(); for(int i=0;i<portNames.length;i++){ portList.addItem(portNames[i].getSystemPortName()); } //create line Graph XYSeries series=new XYSeries("Sensor Reading"); XYSeriesCollection dataset=new XYSeriesCollection(); dataset.addSeries(series); // FIX 1: You forgot to add the series to the dataset! JFreeChart chart=ChartFactory.createXYLineChart( "SensorReading", "time(Second)", "Reading", dataset, PlotOrientation.HORIZONTAL, true, true, true); window.add(new ChartPanel(chart),BorderLayout.CENTER); //configure the connection button and use another thread to listen for data connectionButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0){ if(connectionButton.getText().equals("connect")){ //attempt to connect serial port chosenPort =SerialPort.getCommPort(portList.getSelectedItem().toString()); chosenPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0); if(chosenPort.openPort()){ connectionButton.setText("Disconnect"); portList.setEnabled(false); } //create new thread that listens for incoming text and populates the graph Thread thread=new Thread(){ @Override public void run(){ try { Scanner scanner = new Scanner(chosenPort.getInputStream()); int x=0; while(scanner.hasNextLine()){ String line=scanner.nextLine().trim(); // FIX 2: Trim stray whitespace/newlines try { int number =Integer.parseInt(line); series.add(x++,number); // FIX 3: Update chart on Swing's Event Dispatch Thread (EDT) javax.swing.SwingUtilities.invokeLater(() -> dataset.fireDatasetChanged()); } catch (NumberFormatException e) { // Handle bad data (prevents program crash) System.err.println("Got invalid data from serial: " + line); } } } catch (Exception e) { // Catch any other errors (like port disconnects) e.printStackTrace(); } } }; thread.start(); }else{ //disconnect serial port chosenPort.closePort(); portList.setEnabled(true); connectionButton.setText("connect"); } } }); //show window window.setVisible(true); } }
Arduino Code (With Minor Fix)
void setup() { Serial.begin(9600); } void loop() { // Read potentiometer value int s= analogRead(A0); Serial.println(s); delay(100); // FIX: Slow down data rate to prevent serial buffer overflow }
Breakdown of the Fixes & Troubleshooting Tips
Let’s walk through why these changes matter:
Dataset-Series Link
- Your original code created the series and dataset but never connected them. Without
dataset.addSeries(series);, the chart has no data source to plot—so even if you were receiving values, nothing would show up.
- Your original code created the series and dataset but never connected them. Without
Serial Data Stability
- Sending data as fast as Arduino can loop (no delay) floods the serial port, leading to partial lines or corrupted data. The
delay(100)slows it to 10 readings per second, which is manageable for both Arduino and NetBeans.
- Sending data as fast as Arduino can loop (no delay) floods the serial port, leading to partial lines or corrupted data. The
Swing Thread Safety
- Swing components (including JFreeChart) must be updated on the Event Dispatch Thread. Using
SwingUtilities.invokeLaterensures the chart refreshes correctly without GUI freezes or glitches.
- Swing components (including JFreeChart) must be updated on the Event Dispatch Thread. Using
Error Handling
- Serial communication can send garbage characters (especially when connecting/disconnecting). The
try-catcharoundInteger.parseIntstops your program from crashing and logs the issue so you can debug.
- Serial communication can send garbage characters (especially when connecting/disconnecting). The
Circuit & Serial Checks
- Double-check your potentiometer wiring: one end to 5V, one to GND, middle pin to A0. Loose connections cause unstable readings.
- Use the Arduino IDE’s Serial Monitor first to confirm values are being sent (you should see 0-1023 as you turn the knob).
- Make sure you’re selecting the correct COM port in NetBeans—Arduino ports sometimes change after a reset.
- Verify you have the
jSerialCommandJFreeChartlibraries added correctly to your NetBeans project (missing libraries cause runtime errors).
内容的提问来源于stack exchange,提问作者Randika Wanninayaka

