I need help interfacing a java program with an arduino using jSerialComm.SerialPort or via the COM port. I know the arduino code works fine, because of the serial monitor. It takes the number provided from the COM port and subtracts 10 to set the angle of a servo. However, my java code doesn't work. The Arduino blinks as if the port opens, but the servo remains stationary. I've tweeked the java code a bit, using the serialPort.writeBytes but got the same result. If anyone knows how to fix my code, or a working alternative to jSerialComm, that would be greatly appreciated.
Java code:
package com.company;
import com.fazecast.jSerialComm.SerialPort;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
public class Main {
public static SerialPort serialPort;
public static void main(String[] args) throws Exception {
serialPort = SerialPort.getCommPort("COM5");
serialPort.setComPortParameters(9600,8,1,0);
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_NONBLOCKING,0,0);
serialPort.openPort(20);
PrintWriter out = new PrintWriter(serialPort.getOutputStream(),true);
out.println("50");
out.flush();
}
}
Arduino Code:
#include <Servo.h>
// Declare the Servo pin
int servoPin = 3;
long incomingByte; // for incoming serial data
// Create a servo object
Servo Servo1;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
Servo1.attach(servoPin);
Servo1.write(0);
}
void loop(){
if (Serial.available())
{
int state = Serial.parseInt();
if (state < 10)
{
Serial.print(">");
Serial.println(state);
Serial.println("cannost execute command, too low number");
}
if (state >= 10 && state <= 190)
{
state -= 10;
Serial.println(state);
Servo1.write(state);
}
}
}