You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Arduino与Processing通信时Processing报空指针异常的解决方法

解决Arduino与Processing通信时的NullPointerException问题

嘿,这个问题我之前踩过一模一样的坑!咱们先拆解下问题根源,再一步步搞定它。

问题出在哪?

你看,Arduino端用的是Serial.write(1)和Serial.write(0)——这是直接发送字节数据,既不是字符串,也没有发送Processing代码里期待的换行符\n。但Processing里却用readStringUntil('\n')去读取,这就导致它一直等着换行符出现,读不到的时候就会返回null。当val变成null后,再调用val.equals("0"),自然就抛出NullPointerException了。

两步解决问题

1. 修正Arduino代码:发送带换行的字符串

把Arduino里的Serial.write()改成Serial.println(),因为println会自动在数据末尾加上换行符,正好匹配Processing的读取逻辑:

int switchPin = 4; // Switch connected to pin 4
void setup() {
  pinMode(switchPin, INPUT); // 原注释写错啦,是pin4不是0,顺手纠正下
  Serial.begin(9600); // Initialize serial communications at a 9600 baud rate
}
void loop() {
  if (digitalRead(switchPin) == HIGH) // If switch is ON, send "1" to Processing
  {
    Serial.println("1"); // 发送字符串"1" + 换行符
  } else { // If the switch is not ON, send "0" to Processing
    Serial.println("0"); // 发送字符串"0" + 换行符
  }
  delay(100);
}

2. 优化Processing代码:增加null检查+用回调更高效

给Processing代码加个null判断,避免空指针,同时改用serialEvent回调来处理串口数据(比在draw里轮询更靠谱):

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, 2, etc. to match your port.
  myPort = new Serial(this, portName, 9600);
  myPort.bufferUntil('\n'); // 告诉串口:收到换行符再触发回调
}
void draw() {
  background(255);
  // 先检查val不为null,再判断内容(trim去掉多余的换行/空格)
  if(val != null && val.trim().equals("0")) {
    fill(0);
  } else {
    fill(204);
  }
  rect(50, 50, 100, 100);
}

// 串口收到数据时自动触发这个函数
void serialEvent(Serial myPort) {
  val = myPort.readStringUntil('\n');
  if(val != null) {
    val = val.trim(); // 清除字符串里的换行符和空白
  }
}

额外小提示

  • 运行Processing前,记得关闭Arduino的串口监视器,不然会抢端口导致连接失败;
  • 确认Serial.list()[0]对应的是你的Arduino端口,如果不对,改成1、2之类的索引试试。

内容的提问来源于stack exchange,提问作者user12732513

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:17:32