我正在为我的老学校为他们的学校铃声创建一个程序,并且我正在使用 java。目前在我的 arduino 上,我有一个程序,当它从串口接收到一个数字时,它会打开铃铛,持续多久。该程序可在串行监视器中运行,但不能在 Java 中运行。这些是我的 2 个程序:
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();
}
}
还有我的 Arduino 连接程序;
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;
}
}
这是Arduino代码:
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);
}
}
}
如果你能告诉我我做错了什么,那将非常有帮助。谢谢!