1

我一直在研究 Arduino 入门套件示例,最近,我遇到了一个问题,其中一个电位器用于更改计算机屏幕上徽标的颜色。当徽标最初出现时,它是电位器设置的正确颜色,但是当我移动电位器时颜色不会改变。

我尝试将电位器的值输出到串行监视器并且它们正确更改,但是处理代码读取的值在输出到串行监视器时不会更改。

这是Arduino代码:

void setup() {
  // initialize serial communication
  Serial.begin(9600);
}

void loop() {
  // read the value of A0, divide by 4 and 
  // send it as a byte over the serial connection
  Serial.write(analogRead(A0)/4);
  delay(1);
}

这是处理代码:

 // import the serial library
 import processing.serial.*;

 // create an instance of the serial library
 Serial myPort;

 // create an instance of PImage
 PImage logo;

 // a variable to hold the background color
 int bgcolor = 0;

 void setup() {
 // set the color mode to Hue/Saturation/Brightness
 colorMode(HSB, 255);

 // load the Arduino logo into the PImage instance
 logo = loadImage("http://arduino.cc/en/pub/skins/arduinoWide/img/logo.png");

 // make the window the same size as the image
 size(logo.width, logo.height);

 // print a list of available serial ports to the 
 // Processing staus window
 println("Available serial ports:");
 println(Serial.list());

 // Tell the serial object the information it needs to communicate
 // with the Arduno. Change Serial.list()[0] to the correct 
 // port corresponding to your Arduino board.  The last
 // parameter (e.g. 9600) is the speed of the communication.  It
 // has to correspond to the value passed to Serial.begin() in your
 // Arduino sketch.  
 myPort = new Serial(this, Serial.list()[0], 9600);

 // If you know the name of the port used by the Arduino board, you
 // can specify it directly like this.
 // port = new Serial(this, "COM1", 9600);  

 }

 void draw() {
 background(255);
 // if there is information in the serial port
 if ( myPort.available() > 0) {
 // read the value and store it in a variable
 bgcolor = myPort.read();

 // print the value to the status window
 println(bgcolor); 
 }

 // Draw the background. the variable bgcolor
 // contains the Hue, determined by the value
 // from the serial port
 background(bgcolor, 255, 255);

 // draw the Arduino logo
 image(logo, 0, 0);
 }

所以我认为问题在于 Serial.write 或 Serial.read 方法,但它可能完全不同。

4

2 回答 2

1

我遇到过同样的问题; 我只是在相同的原始 Arduino 代码中将延迟增加到 50(即 no SerialEventor parseInt,just set delay(50))。这解决了这个问题。

似乎取决于您的 PC,读取/解析串行缓冲区的处理速度可能会更慢,所以告诉 Arduino 放慢速度!

于 2014-03-25T21:15:30.780 回答
0

我认为你需要serialEvent在你的处理代码中调用一些东西。

它看起来像这样:

void serialEvent(Serial myPort) {
   String inString = myPort.readStringUntil('\n');

   //do something with your string.
}

希望能帮助到你!

于 2013-09-27T07:34:11.360 回答