Im doing my thesis right now, Arduino Automatic Telescope. And im stuck at a problem cant control my servo motors from my Java program, LED light for debugging works but my motors dont move.
void loop() {
if (Serial.available() > 0) {
// Turn on LED when receiving data
digitalWrite(ledPin, HIGH);
// Read the incoming data
String receivedData = Serial.readStringUntil('\n');
int position = receivedData.toInt();
// Move servos
altitude.write(position);
azimuth.write(position);
delay(1000);
// Return to zero
altitude.write(0);
azimuth.write(0);
// Turn off LED when done processing
digitalWrite(ledPin, LOW);
}
}
Java code
public static void main(String[] args) {
SerialPort arduinoPort = SerialPort.getCommPort("COM4");
if(arduinoPort.openPort()){
System.out.println("Port opened successfully");
}else{
System.out.println("Port couldnt be opened");
return;
}
//Configure Port
arduinoPort.setComPortParameters(9600, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
arduinoPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 1000, 0);
sendIntToArduino(arduinoPort,90);
// Add delay to ensure data is sent
try {
Thread.sleep(2000); // Wait 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
arduinoPort.closePort();
}
public static void sendIntToArduino(SerialPort port, int degrees) {
// Convert to string with newline
String command = degrees + "\n";
byte[] buffer = command.getBytes();
port.writeBytes(buffer, buffer.length);
System.out.println("Data was SENT: " + degrees);
}
Manually everything works fine all cables are correctly connected. I think the problem is the data type im sending my data. If you got any advices im all ears.