我正在创建一个获取串行输入的程序,将其转换为int然后将引脚设置为HIGH,无论输入多久,例如,如果我将“9000”打印到Arduino串口,它将设置引脚13至HIGH为9000毫秒。但是,它将引脚设置为HIGH,以便在连接开始时进行初始“握手”。有没有办法消除这个,或者反击它?
这是我目前的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
delay(4000);
digitalWrite(Relay, HIGH);
delay(time);
digitalWrite(Relay, LOW);
}
}
}
如果有任何办法可以让我知道我该怎么办?
谢谢:)
编辑1:
int Relay = 13;
//The pin that the relay is attached to
int time;
byte byte_1;
byte byte_2;
//Creates temp variable
void setup() {
pinMode(Relay, OUTPUT);
//Initialize the serial communication:
Serial.begin(9600);
digitalWrite(Relay, LOW);
delay(250);
}
void loop() {
//Check if data has been sent from the computer:
if (Serial.available() == 2) {
byte_1 = Serial.read();
delay(100);
byte_2 = Serial.read();
}
if(byte_1 == 16) {
digitalWrite(Relay, HIGH);
delay(byte_2);
digitalWrite(Relay, LOW);
}
byte_1 = 0;
byte_2 = 0;
}
编辑3:
package net.arduino;
import java.io.OutputStream;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
public class Main {
public static void main(String[] args) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM3");
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(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
OutputStream out = serialPort.getOutputStream();
byte[] buffer = new byte[2];
buffer[0] = (byte) 16;
buffer[1] = (byte) 1000;
out.write(buffer);
out.flush();
Thread.sleep(10000);
out.close();
}else{
System.out.println("ERROR!!! -- This is not normal");
}
}
}
}
答案 0 :(得分:0)
您也没有检查输入的有效性(time = Serial.parseInt()),因此线上的任何噪声都将作为有效输入值。我使用命令协议将我的调用包装到Arduino,这样我就可以确定Arduino获得了发送的值而不是噪声。即首先发送16为GetReadyToReceive,然后是值。这样就可以减少误输入的可能性。
在http://playground.arduino.cc/Csharp/SerialCommsCSharp上查看我的代码