我认为's the source of my problem) and a Processing script, and I' m得到了一些意想不到的结果 . 我正在按照串行通信的方法详细说明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));
}
}
}
以及Processing代码的相关部分:
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
...
注意:我知道我从列表中选择了正确的端口,所以这不是问题 .
我已经尝试调试问题并在互联网上搜索类似的问题,但都无济于事 . 非常感谢有关此问题的任何帮助,谢谢!
1 回答
我首先检查是否只是从Arduino发送一条简单的消息到Processing工作 . 在Arduino中尝试这样的事情:
这在处理中:
如果这个简单的设置有效,你可以继续进行下一步并进行双向通信 . 如果上述方法不起作用,那么还会出现串行通信问题(在这种情况下,请报告您收到的错误,如果您遇到任何行为或行为)
如果以上工作,您可以尝试双向通信 . 注意我正在使用
serialEvent()
和bufferUntil
. 尽可能避免阻塞while循环 .Arduino代码:
处理代码: