I am creating a prorgram for my old school for their school bell, and I am using java. Currently on my arduino I have a program which when it receives a number from the serial port it turns on the bell for how ever long it says. This program works in the Serial Monitor, but not in Java. These are my 2 programs:
import java.io.OutputStream;
import gnu.io.SerialPort;
public class Main {
public static void main(String[] args) throws Exception {
SerialPort sP = Arduino.connect("COM3");
Thread.sleep(1500);
OutputStream out = sP.getOutputStream();
Thread.sleep(1500);
out.write("3000".getBytes());
out.flush();
Thread.sleep(1500);
out.close();
}
}
And my Arduino conenct program;
import gnu.io.*;
public class Arduino {
public static SerialPort connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if(portIdentifier.isCurrentlyOwned()) {
System.out.println("ERROR!!! -- Port already in use!");
}else{
CommPort commPort = portIdentifier.open("XBell", 0);
if(commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
return serialPort;
}else{
System.out.println("wait wat");
}
}
return null;
}
}
Here's the Arduino code:
int Relay = 13;
//The pin that the relay is attached to
int time;
//Creates temp variable
void setup() {
//Initialize the Relay pin as an output:
pinMode(Relay, OUTPUT);
//Initialize the serial communication:
Serial.begin(9600);
}
void loop() {
while(true) {
//Check if data has been sent from the computer:
if (Serial.available()) {
//Assign serial value to temp
time = Serial.parseInt();
//Output value to relay
digitalWrite(Relay, HIGH);
delay(time);
digitalWrite(Relay, LOW);
}
}
}
If you could please tell me what I am doing wrong that would be very helpful. Thanks!