2013-09-26 53 views
1

我一直在研究Arduino入門工具包的例子,最近我遇到了一個問題,那就是使用電位計來改變電腦屏幕上的標誌顏色。最初出現徽標時,它的顏色與電位計設置的顏色一致,但隨着我移動電位計,顏色不會改變。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方法中,但它可能是完全不同的東西。

+0

你可以將你的代碼格式化爲使用標籤更易讀嗎? – ladislas

回答

0

我認爲你需要在你的處理代碼中叫做serialEvent

它看起來像:

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

    //do something with your string. 
} 

希望它能幫助!

+0

我將處理繪製段更改爲: void serialEvent(Serial myPort){//讀取值並將其存儲在變量中 bgcolor = Integer.parseInt(myPort.readStringUntil('\ n')); //將值打印到狀態窗口 println(bgcolor); } void draw(){ //繪製背景。變量bgcolor //包含Hue,由值 //從串口 background(bgcolor,255,255)確定; //繪製Arduino徽標 image(logo,0,0); } '但有一個IncocationTargetException錯誤。 – aftrumpet

+0

好的,我明白了,如果你想以字符串的形式接收它,你需要''Serial.println(analogRead(A0)/ 4);'在你的Arduino Code中。 你也可以嘗試放一個比較長的'delay();'來啓動。 – ladislas

1

我有同樣的問題;我只是用相同的原始Arduino代碼將延遲增加到50(即沒有0​​或parseInt,只是設置爲delay(50))。這解決了這個問題。

看起來取決於您的PC,處理可能會更慢地讀取/解析串行緩衝區,所以請告訴Arduino放慢速度!