处理IDE数据未正确发送到Arduino



我想向Arduino发送处理IDE数据。但是LED不起作用。它曾经起作用一次。但是现在不工作:(串行端口名称在Arduino中完全相同。

处理代码:

import processing.serial.*;
Serial myPort;  // Create object from Serial class
void setup() 
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}
         //send a 1
void draw() {
  if (mousePressed == true) 
  {                           //if we clicked in the window
   myPort.write('1');         //send a 1
   println("1");   
  } else 
  {                           //otherwise
  myPort.write('0');          //send a 0
  }   
}

arduino代码:

 char val='0'; // Data received from the serial port
 int ledPin = 13; // Set the pin to digital I/O 13
 void setup() {
   pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
   Serial.begin(9600); // Start serial communication at 9600 bps
 }
  void loop() {
     //digitalWrite(ledPin, HIGH); // turn the LED on
 if (Serial.available()) 
   { // If data is available to read,
     val = Serial.read(); // read it and store it in val
   }
   if (val == '1') 
   { // If 1 was received
     digitalWrite(ledPin, HIGH); // turn the LED on
   } else {
     digitalWrite(ledPin, LOW); // otherwise turn it off
   }
   delay(10); // Wait 10 milliseconds for next reading
}

处理

您可以简单地说if(mousePressed)...,无需说== true(暗示)

arduino

在尝试使用从那里阅读的任何字符覆盖val之前,您可以正确检查if(Serial.available())。但是,无论此检查如何,loop()内的其余代码正在执行。如果已经存在,则没有理由反复将PIN写入低或高。实际上,如果您仅延迟找到可供阅读的字符的循环,您将更加响应。

我建议您在Arduino代码中添加一些打印语句,以便查看您正在阅读的内容。

另外,是否是您的硬件连接不正确,或者您的LED被烧毁了?

最新更新