【发布时间】:2016-01-18 18:19:43
【问题描述】:
我正在尝试在 Ardunio 上的传感器(实际上是基于 AtMega328PU 的克隆建立在面包板上,但我不相信这是我的问题的根源)和处理脚本之间创建数据交换,我得到了一些意想不到的结果。我遵循详细的串行通信方法here,但我遇到了似乎没有实际通过串行连接传输的数据。
Arduino 代码:
int buttonPin = 9, photodiodePin = A0;
char dataToSend;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, OUTPUT);
pinMode(photodiodePin, INPUT);
}
void loop() {
if (Serial.available() > 0)
{
dataToSend = Serial.read();
if (dataToSend == 'B')
{
Serial.println(digitalRead(buttonPin));
}
else if (dataToSend == 'L')
{
Serial.println(analogRead(photodiodePin));
}
}
}
以及处理代码的相关部分:
import processing.serial.*;
Serial myPort;
void setup()
{
size(1600,900);
String portName = Serial.list()[1];
myPort = new Serial(this, portName, 9600);
}
void draw()
{
if(getButtonData() == 1)
{
//Do Stuff
}
}
int getLightData()
{
myPort.write('L');
println("L");
while(!(myPort.available() > 0)){
}
int lightValue = int(myPort.readStringUntil('\n'));
return lightValue;
}
int getButtonData()
{
myPort.write('B');
println("B");
while(!(myPort.available() > 0)){
println("stuck in here");
delay(500);
}
int buttonValue = int(myPort.readStringUntil('\n'));
return buttonValue;
}
在处理中我得到一个输出:
B
stuck in here
stuck in here
stuck in here
stuck in here
...
注意:我知道我从列表中选择了正确的端口,所以这不是问题。
我已尝试调试问题并在互联网上搜索类似问题,但均无济于事。非常感谢您对此问题的任何帮助,谢谢!
【问题讨论】:
-
您不需要将“.available”检查放在一段时间内(在 getButtonData 中),因为在程序停止之前循环调用 draw 方法。你需要摆脱!在可用的情况下检查并仅在数据可用时才执行操作。相应地调整 B 的发送。对 getLightData 执行相同操作。
-
首先测试串行通讯,不要使用其余代码。在 Draw 方法中写入您的串行端口,看看您是否可以在 Arduino 端获得任何东西。另请阅读有关如何在处理中设置串行的一些文档。确保波特率、停止位和其他设置,特别是流量控制。
-
还要确保处理实际上只是将 B 作为一个字节发送,而不是以可能需要多字节的另一种形式发送。
标签: arduino processing