【发布时间】:2014-08-09 01:22:40
【问题描述】:
意图:从串口控制arduino uno
工具:
https://github.com/JanStevens/ArduinoPi-Python
我的服务器在我的 mac 和我的 Model b+ Raspberry 上都能正常工作。 在这两种情况下,浏览器的行为如下图所示。
在我看来,服务器似乎成功地向 Arduino 发送了消息。但数据不知何故在途中丢失了。每次我在浏览器中访问 url 时,Arduino 板都会重置。我用谷歌搜索,发现接地和复位引脚之间的 10uF 电容器会阻止复位发生。确实如此,但引脚 3 不会变为“HIGH”。我在引脚 3 上插入了一个 LED+RESISTOR 并相应地接地。每次访问 url 时,我都可以看到 Rx led 闪烁。所以这让我觉得 Arduino 误解了我的 Flask 服务器的命令。
OG Arduino 代码:
String cmd;
bool cmdRec = false;
void setup()
{
//Start the connection with the Raspberry Pi
Serial1.begin(115200);
// Start the connection with the Laptop, for debugging only!
//Serial.begin(115200);
}
void loop()
{
handleCmd();
}
void serialEvent1() {
while(Serial1.available() > 0) {
char inByte = (char)Serial1.read();
if(inByte == ':') {
cmdRec = true;
return;
} else if(inByte == '@') {
cmd = "";
cmdRec = false;
return;
} else {
cmd += inByte;
return;
}
}
}
void handleCmd() {
if(!cmdRec) return;
// If you have problems try changing this value,
// my MEGA2560 has a lot of space
int data[80];
int numArgs = 0;
int beginIdx = 0;
int idx = cmd.indexOf(",");
String arg;
char charBuffer[20];
while (idx != -1) {
arg = cmd.substring(beginIdx, idx);
arg.toCharArray(charBuffer, 16);
data[numArgs++] = atoi(charBuffer);
beginIdx = idx + 1;
idx = cmd.indexOf(",", beginIdx);
}
// And also fetch the last command
arg = cmd.substring(beginIdx);
arg.toCharArray(charBuffer, 16);
data[numArgs++] = atoi(charBuffer);
// Now execute the command
execCmd(data);
cmdRec = false;
}
// For advanced function like switch all the leds in RGB
void execCmd(int* data) {
switch(data[0]) {
case 101:
{
for(int i = 2; i < (data[1]*2)+1; i+=2) {
pinMode(data[i], OUTPUT);
analogWrite(data[i], data[i+1]);
}
}
break;
case 102:
{
pinMode(data[1], INPUT);
int sensor = analogRead(data[1]);
Serial1.println(sensor);
}
break;
case 103:
{
String result = "";
int sensor = 0;
for(int j = 2; j < data[1]+2; j++) {
pinMode(data[j], INPUT);
sensor = analogRead(data[j]);
result += String(sensor)+",";
}
Serial1.println(result);
}
break;
default:
{
pinMode(data[0], OUTPUT);
analogWrite(data[0], data[1]);
}
break;
}
}
它不会以这种方式编译。所以我取消了第二个 Serial.begin 行的注释并删除了所有的“Serial1”。出现在代码上。当我在我的 Mac 上测试 arduino IDE 串行时,我看不到它没有任何动作。
【问题讨论】:
标签: python arduino raspberry-pi