I've been working on communication between java and arduino lately because I have a project that needs it, so I've been reading a lot about it and started making some progress with it such as sending String from java and reading it in the arduino and using it then sending outputs to java again , anyways after that I had to set a slider in java so I can send values between 0 and 1023 to the arduino while moving it but the problems started to appear here, I created the slider (using JSlider) and used stateChanged method to send the values to the arduino and then the arduino should read the data and report back to java, I've set MinorTickSpacing to 100 so whenever you click on the slider it goes from 0 to 100 and so, the arduino reads data correctly(it reads it 3 times and I don't know why) until it reaches 300 this is the output I see in java (Reading the output from arduino using serialEvent and BufferReader):
COM port found:COM3
Port open succesful: COM3
100
100
200
200
200
44
44
44
65533
65533
65533
244
244
I clicked 5 times on the slider so it should read 100, 200, 300, 400 & 500 but I see those strange numbers and I don't know why. Here is my programs for both Java (Used RXTX Library and Eclipse IDE) & Arduino.
Java Program:
import java.io.BufferedReader; //BufferedReader makes reading operation efficient
import java.io.IOException;
import java.io.InputStreamReader; //InputStreamReader decodes a stream of bytes into a character set
import java.io.OutputStream; //writes stream of bytes into serial port
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent; //deals with possible events in serial port (eg: data received)
import gnu.io.SerialPortEventListener; //listens to the a possible event on serial port and notifies when it does
import java.util.Enumeration;
import gnu.io.PortInUseException; //all the exceptions.Never mind them for now
import gnu.io.UnsupportedCommOperationException;
import java.util.Scanner; //to get user input of name
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.*;
public class TestingGUI implements SerialPortEventListener,ActionListener, ChangeListener {
private SerialPort serialPort ; //defining serial port object
private CommPortIdentifier portId = null; //my COM port
private static final int TIME_OUT = 2000; //time in milliseconds
private static final int BAUD_RATE = 9600; //baud rate to 9600bps
private BufferedReader input; //declaring my input buffer
private OutputStream output; //declaring output stream
private String name; //user input name string
public static String status;
JFrame frame;
JPanel panel;
JLabel label,label1;
JSlider slide;
JProgressBar progress;
JButton onButton,offButton,blinkButton;
Scanner inputName; //user input name
public TestingGUI()
{
frame = new JFrame();
frame.setSize(700, 150);
frame.setTitle("Arduino Test");
panel = new JPanel();
frame.add(panel);
slide = new JSlider();
slide.setMinimum(0);
slide.setMajorTickSpacing(5);
slide.setMaximum(1023);
slide.setMinorTickSpacing(100);
slide.setPaintLabels(true);
slide.setPaintTicks(true);
slide.setSnapToTicks(true);
slide.setToolTipText("Move the slider to desired location.");
slide.setValue(0);
slide.setValueIsAdjusting(true);
slide.addChangeListener(this);
panel.setLayout(null);
slide.setBounds(10,10, 650, 50);
panel.add(slide);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//method initialize
private void initialize()
{
CommPortIdentifier ports = null; //to browse through each port identified
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers(); //store all available ports
while(portEnum.hasMoreElements()) //browse through available ports
{
ports = (CommPortIdentifier)portEnum.nextElement();
//following line checks whether there is the port i am looking for and whether it is serial
if(ports.getPortType() == CommPortIdentifier.PORT_SERIAL&&ports.getName().equals("COM3"))
{
System.out.println("COM port found:COM3");
portId = ports; //initialize my port
break;
}
}
//if serial port am looking for is not found
if(portId==null)
{
System.out.println("COM port not found");
System.exit(1);
}
}
//end of initialize method
//connect method
private void portConnect()
{
//connect to port
try
{
serialPort = (SerialPort)portId.open(this.getClass().getName(),TIME_OUT); //down cast the comm port to serial port
//time to wait
System.out.println("Port open succesful: COM3");
//set serial port parameters
serialPort.setSerialPortParams(BAUD_RATE,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
}
catch(PortInUseException e){
System.out.println("Port already in use");
System.exit(1);
}
catch(NullPointerException e2){
System.out.println("COM port maybe disconnected");
}
catch(UnsupportedCommOperationException e3){
System.out.println(e3.toString());
}
//input and output channels
try
{
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
//adding listeners to input and output streams
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort.notifyOnOutputEmpty(true);
//defining reader and output stream
}
catch(Exception e){
System.out.println(e.toString());
}
}
//end of portConncet method
@Override
public void stateChanged(ChangeEvent e)
{
if(e.getSource() == slide)
{
try {
int out = slide.getValue();
output.write(out);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@Override
public void actionPerformed(ActionEvent event) {
}
//readWrite method
@Override
public void serialEvent(SerialPortEvent evt)
{
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) //if data available on serial port
{
try {
if(input.ready())
{
int testInt = input.read();
System.out.println(testInt);
}
} catch (Exception e)
{
System.err.println(e.toString());
}
}
}
//end of serialEvent method
//main method
public static void main(String[] args)
{
TestingGUI myTest = new TestingGUI(); //creates an object of the class
myTest.initialize();
myTest.portConnect();
}//end of main method
}// end of SerialTest
and Arduino Program:
void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
}
void loop() {
while(Serial.available() == 0)
{
}
int test2 = Serial.read();
Serial.write(test2);
}
What should I do to get the correct number and exceed the limit that the arduino shows? (apparently only numbers between 0 and 255 is read correctly)
According to Arduino Serial.Read()
documentation: https://www.arduino.cc/en/Serial/Read calling it returns:
the first byte of incoming serial data available (or -1 if no data is available) - int
By definition, a byte can have a value between 0 and 225, which is why those values work correctly.
When you send value of 300, you experience something called "Arithmetic overflow" - imagine that you count from 0 to 300, but at 255 you start from 0 again, and then you reach 44. Same goes for 500.
I'm not sure why do you get 65533 for 400, it should be 144 (400 modulo 256). I'll update the answer if I find out.
Summing up - you shouldn't send or expect values outside 0-255 range. If you want to sent bigger number, divide it into bytes and assemble back on the other side of communication channel.