处理Arduino通讯比较

时间:2018-08-07 14:46:32

标签: serialization arduino processing

我的处理代码成功打印了从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");
}
}

1 个答案:

答案 0 :(得分:0)

来自the reference

  

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

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

if (val == "ic"){

相反,您应该这样做:

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

退后一步,您应该养成debugging your code的习惯,以了解正在发生的事情。尝试将问题缩小到行为与预期不同的一行,将来找出类似的问题会容易得多。