2014-09-23 38 views
0

我有一个Arduino发送串行数据到Processing。像“3高”,“3低”等...if if based on serial data(processing)

我想处理不断读取数据和使用if语句来触发事件。 EG,如果它看到字符串“4High”,它会做一些事情。

这是我有,但不能找出if语句...

import processing.serial.*; 

Serial myPort; // Create object from Serial class 
String val;  // Data received from the serial port 

void setup() 
{ 
    size(600, 600); 
// Open whatever port is the one you're using. 
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) 
    { // If data is available, 
    val = myPort.readStringUntil('\n');   // read it and store it in val 
    } 
println(val); //print it out in the console 



    if (val == "3High"){ 
    fill(255,200,200); 
    ellipse(60,20,100,100); 
    } 
    if (val == "3Low"){ 
    fill(200); 
    ellipse(250, 250, 100, 100);  
    } 


} 

回答

0

处理是基于Java语言,来比较两个字符串是通过使用equals()功能的正确方法。有关字符串的更多信息,请参阅herehere

if (val.equals("4High")) { 
    println("Yes"); 
} 

要读取串行数据,你应该考虑使用serialEvent找到更多的信息和示例here并针对不同的字符串值,只需使用单独if语句就像在你的例子。

+1

只是为了增加与'String'文字比较的首选样式是'Literal.equals(...)',在这种情况下''4High“.equals(val)'。 – 2014-09-23 11:27:04