【问题标题】:How do I get Arduino to communicate with Processing如何让 Arduino 与 Processing 通信
【发布时间】:2020-01-19 14:34:30
【问题描述】:


我想让我的 Arduino 与 Processing 通信。
在 Arduino 上,我将代码取自 Processing 站点(示例 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);
}

在处理时,我输入了这段代码:

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);
}

程序在处理程序的第 22 行给我错误 NullPointerException。
你知道如何解决它吗?谢谢。

【问题讨论】:

  • 嗨,马可!欢迎来到 StackOverflow!你能编辑你的问题并添加你得到的确切错误吗?可能发生错误是因为您在 if 之外访问val,所以在第一个循环中它可能仍然为空。也许尝试用“0”初始化它,看看会发生什么。让我知道它是否有效,以便我可以发布正确的答案:)
  • 嗨@George!我得到的错误是第 22 行中的“NullPointerException”,对不起,但我忘了提及它。现在我通过输入 String val = "0"; 对您建议的更改进行了更改;但什么都没有改变。他一直在第 22 行给我错误。

标签: arduino serial-port processing


【解决方案1】:

通信有延迟,可能是第一次调用draw函数时,串口没有发送数据,接收到的值为null。这可能是您得到 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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    相关资源
    最近更新 更多