我的案例陈述有问题。python脚本serial.writes一个“s”用于传感器信息或“r”用于继电器信息。传感器信息部分完美运行。我无法正确获取继电器信息。python 脚本发出一个“r”,后跟中继信息,该信息应存储在数组 [x] 中。arduino 确认 case 语句中的“r”,但不处理随后的处理数据包。我得到的只是空数组。我在这里查看了尼克·加蒙斯系列页面,但无法弄清楚如何让它在我的情况下工作,我只是没有经验。
任何帮助深表感谢。
阿杜诺代码
void SerialCommunication()
{
if (Serial.available()>0)
{
char inChar = Serial.read();
switch (inChar)
{
case 'r':
Sensors();
break;
case 'w':
Relays();
ProcessRelays();
break;
default:
break;
}
}
}
void Relays()
{
while (Serial.available() ==0);
// Read all serial data available, as fast as possible
while(Serial.available() > 0)
{
char inChar = Serial.read();
if(inChar == SOP)
{
index = 0;
inData[index] = '\0';
started = true;
ended = false;
}
else if(inChar == EOP)
{
ended = true;
break;
}
else
{
if(index < 79)
{
inData[index] = inChar;
index++;
inData[index] = '\0';
}
}
}
// We are here either because all pending serial
// data has been read OR because an end of
// packet marker arrived. Which is it?
if(started && ended)
{
// The end of packet marker arrived. Process the packet
if (strlen(inData) > 0)
{
char *token = strtok(inData, ",");
if(token)
{
index = 0;
array[index] = atoi(token);
while (token = strtok(NULL, ","))
{
array[index++] = atoi(token);
}
}
}
// Reset for the next packet
started = false;
ended = false;
index = 0;
inData[index] = '\0';
}
}
void ProcessRelays()
{
Serial.println(array[0]);
Serial.println(array[1]);
Serial.println(array[2]);
}
蟒蛇代码
#Import libraries
import serial
import string
import MySQLdb
import pprint
from time import strftime
#Connect to arduino
ser = serial.Serial('/dev/ttyACM0', baudrate=9600, timeout = 2)
ser.open()
#Connects to database
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="zzz", # your username
passwd="zzz", # your password
db="zzz") # name of the data base
cur = db.cursor()
with db:
cur = db.cursor()
cur.execute("SELECT * FROM relayschedule WHERE id=1")
rows = cur.fetchall()
for row in rows:
s = str(row)
ser.write("w" + s)
ser.close()
db.close()