Arduino串口数据没有变化?

时间:2013-09-26 20:54:12

标签: serial-port arduino processing arduino-ide

我一直在研究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方法中,但它可能完全不同。

2 个答案:

答案 0 :(得分:1)

我有同样的问题;我刚刚将相同的原始Arduino代码的延迟增加到50(即没有SerialEventparseInt,只需设置delay(50))。这解决了这个问题。

根据您的PC,处理读取/解析串行缓冲区的速度可能会变慢,因此请告诉Arduino减速!

答案 1 :(得分:0)

我认为您的处理代码中需要一些名为serialEvent的内容。

看起来像这样:

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

   //do something with your string.
}

希望它有所帮助!