Serial port Arduino和Processing之间的接球游戏
以下代码使Arduino和Processing像烫手山芋一样来回传递“A”: 处理向ARDUINO发送“A”Serial port Arduino和Processing之间的接球游戏,serial-port,arduino,processing,Serial Port,Arduino,Processing,以下代码使Arduino和Processing像烫手山芋一样来回传递“A”: 处理向ARDUINO发送“A” 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
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将“A”发送回处理
void setup()
{
Serial.begin(9600);
}
void loop()
{
delay(1000);
Serial.println('A'); //Send 'A' back to Processing
}
发生了什么事?
好。。。该游戏可进行大约10次交换(我怎么知道?我收到了5次“编写A…”消息,我使用BufferTill()告诉我,这些消息中的每一条都是通过从Arduino接收串行.println('A')来提示的)但是然后处理中断,出现以下错误:
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.
发生什么事了
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;
}
}
}
串行;
布尔串行初始化;
无效提款(){
if(serialInited){
//序列号已启动并运行
试一试{
字节b=串行.read();
//有趣的连续剧在这里。。。
}捕获(运行时异常e){
//串行端口关闭:(
serialInited=false;
}
}否则{
//串行端口不可用。请打开它,直到它可用为止。
initSerial();
}
}
void initSerial(){
试一试{
串行=新串行(这是serial.list()[0],波特率);
serialInited=true;
}捕获(运行时异常e){
如果(e.getMessage()包含(“”){
System.out.println(“端口正在使用,稍后再试…”);
serialInited=false;
}
}
}