以下代码使Arduino和Processing通过' A'像烫手山芋一样来回:
处理事件' A'到ARDUINO
import processing.serial.*; //import the Serial library
Serial mySerial; //the Serial port object
void setup()
{
mySerial = new Serial(this, Serial.list()[7], 9600); //Pick whichever works
mySerial.bufferUntil('\n');
}
void serialEvent( Serial mySerial)
{
println("writing A...");
delay(1000); //How I defined this is not relevant. Trust me.
mySerial.write('A'); //Send 'A' to Arduino
}
ARDUINO SENDS' A'返回加工
void setup()
{
Serial.begin(9600);
}
void loop()
{
delay(1000);
Serial.println('A'); //Send 'A' back to Processing
}
会发生什么? 好吧......游戏适用于大约十次交流(我怎么知道?好吧,我得到了#34;写了A ..."消息五次,我使用bufferUntil()告诉我每个这些消息是通过从Arduino接收Serial.println(' A') BUT 然后处理中断而出现以下错误:
Error, disabling serialEvent() for /dev/tty.usbmodem1421
null
java.lang.RuntimeException: Error reading from serial port /dev/tty.usbmodem1421: Port not opened
at processing.serial.Serial.serialEvent(Unknown Source)
at jssc.SerialPort$LinuxEventThread.run(SerialPort.java:1299)
Could not run the sketch (Target VM failed to initialize).
For more information, read revisions.txt and Help → Troubleshooting.
发生了什么?
答案 0 :(得分:2)
Port not opened
是错误消息中的关键字:串行端口随时随机关闭。解决办法是不断强制它在平局中打开:
Serial serial;
boolean serialInited;
void draw () {
if (serialInited) {
// serial is up and running
try {
byte b = serial.read();
// fun with serial here...
} catch (RuntimeException e) {
// serial port closed :(
serialInited = false;
}
} else {
// serial port is not available. bang on it until it is.
initSerial();
}
}
void initSerial () {
try {
serial = new Serial(this, Serial.list()[0], BAUD_RATE);
serialInited = true;
} catch (RuntimeException e) {
if (e.getMessage().contains("<init>")) {
System.out.println("port in use, trying again later...");
serialInited = false;
}
}
}