【发布时间】:2013-08-05 06:01:28
【问题描述】:
我正在为我的老学校为他们的上课铃创建一个程序,并且我正在使用 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 conenct 程序;
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);
}
}
}
如果您能告诉我我做错了什么,那将非常有帮助。谢谢!
【问题讨论】:
-
您确定该数字是要编码为 text 的吗?
-
我以前也这样做过,但由于硬盘故障,我丢失了那个程序。
-
对于相同的输入?这听起来像是通过串行端口传递数字的一种奇怪的方式......此外,您没有说明出了什么问题。大概它不起作用,但是它以什么方式不起作用?门铃不响吗?响铃太久?响铃时间太短?
-
在 arduino 上,我目前正在使用端口 13 上的内置 LED 进行调试。当我连接时,它会快速闪烁几次,我猜是连接,然后它就再也没有做任何事情了。
-
好吧,如果没有看到在 Arduino 上运行的代码,我们真的不知道为什么会这样......
标签: java serial-port arduino