我想让我的Arduino与Processing通信。在Arduino上,我把代码取自于 加工 网站(例1A)。
int switchPin = 4; // Switch connected to pin 4
void setup()
{
pinMode(switchPin, INPUT); // Set pin 0 as an input
Serial.begin(9600); //initialize serial communications at a 9600 baud rate
}
void loop()
{
if (digitalRead(switchPin) == HIGH) { // If switch is ON,
Serial.write(1); // send 1 to Processing
} else { // If the switch is not ON,
Serial.write(0); // send 0 to Processing
}
delay(100);
}
在Processing的时候,我放了这段代码。
import processing.serial.*;
Serial myPort; // Create object from Serial class
String val="0"; // Data received from the serial port
void setup()
{
size(200, 200);
frameRate(10);
String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
myPort = new Serial(this, portName, 9600);
}
void draw()
{
if ( myPort.available() > 0)
{ // If data is available,
val = myPort.readStringUntil('\n'); // read it and store it in val
}
background(255);
if(val.equals("0")){
fill(0);
}else{
fill(204);
}
rect(50, 50, 100, 100);
}
在Processing程序的第22行,程序给了我错误的NullPointerException。你知道如何解决吗?谢谢你的帮助。
在通信中有一个延迟,有可能在第一次调用draw函数时,串口没有发送任何数据,收到的值是空的。这可能是你得到NullPointerException的原因。试试这个。
void draw()
{
while ( myPort.available() > 0)
{ // If data is available,
val = myPort.readStringUntil('\n'); // read it and store it in val
}
background(255);
if(val != null) {
if(val.equals("0")){
fill(0);
}else{
fill(204);
}
}
rect(50, 50, 100, 100);
}