首页 > 解决方案 > 处理 Arduino 通信比较

问题描述

我的处理代码成功打印了从 Arduino 发送的字符串数据,但是我无法使用 IF/ELSE 进行比较。例如,在控制台上它打印“ic”但它不运行 if value ==“ic”代码。感谢所有帮助。

import processing.serial.*;

PImage k;  // Declare variable "a" of type PImage
PImage y;
Serial myPort;  // Create object from Serial class
String val; 

void setup() {
  size(1300, 800);
  // The image file must be in the data folder of the current sketch 
  // to load successfully
  k = loadImage("k_ray.png");  // Load the image into the program  
  y = loadImage("y_ray.png");
  String portName = Serial.list()[1]; //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) 
  {
  val = myPort.readString();
  println(val);

    if (val == "ic"){
    println("hop");
    image(y, 398, 600);
  }
  else if(val == "ig"){
    println("hop");
    image(k, 398, 600);
  }
  }



}

所以它只输出“ic”和“ig”,但不输出“hop”。

这里也是 Arduino 代码:

int icount=0;
int rcount=0;


void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:


int bc = analogRead(A2);
int bg = analogRead(A3);
int rc = analogRead(A4);
int ic = analogRead(A5);
int ig = analogRead(A1);
if (ic < 100){
  icount=icount-1;
  rcount=rcount+1;
  Serial.println("ic");
}
if (ig < 100){
  icount=icount+1;
  Serial.println("ig");
}
}

标签: serializationarduinoprocessing

解决方案


参考

要比较两个字符串的内容,请使用equals()方法,如if (a.equals(b)),而不是if (a == b)。字符串是一个对象,因此将它们与 == 运算符进行比较仅比较两个字符串是否存储在相同的内存位置。使用该equals()方法将确保比较实际内容。(故障排除参考有更长的解释。)

换句话说,你不应该这样做:

if (val == "ic"){

相反,您应该这样做:

if (val.equals("ic")){

退后一步,您应该养成调试代码以弄清楚发生了什么的习惯。尝试将您的问题缩小到与您预期的行为不同的一行,并且将来找出此类问题会容易得多。


推荐阅读