[英]Parsing data from I2C
我正在使用I2C将数据从Raspberry Pi发送到Arduino。 我正在使用线库,并基于slavereceiver和slavesender示例的代码。 我正在尝试解析来自Raspberry Pi的以下数据:
13:0&8:0
因此,13将是我的引脚,0将是预期值。 下一组数据是引脚8,其预期值也为0。
我似乎无法使我尝试过的任何东西都能正常工作,所以现在我只是将数据打印到串行监视器上。 这是我的代码:
#include <Wire.h>
int motion = 6;
int relay1 = 8;
int relay2 = 9;
int onBoardLED = 13;
void setup()
{
Wire.begin(3);
Wire.onRequest(requestEvent);
Wire.onReceive(receiveEvent);
pinMode(motion, INPUT);
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
pinMode(onBoardLED, OUTPUT);
Serial.begin(9600);
}
void loop()
{
delay(100);
digitalWrite(onBoardLED, HIGH);
}
void receiveEvent(int howMany)
{
while (Wire.available()){
char json = Wire.read();
Serial.print(json);
}
}
void requestEvent()
{
char myStuff[80];
int motionState = digitalRead(motion);
sprintf(myStuff, "{\"motion\": %i}", motionState);
Wire.write(myStuff);
}
串行监视器显示数据,但是我无法终生解析它来获取值和引脚。
任何帮助将不胜感激!
更新 :因此,这是基于paulsm4建议的新代码,但是当我尝试打印inData的长度时,它返回为0:
void receiveEvent(int howMany)
{
char inData[80];
byte index = 0;
while (Wire.available()){
char aChar = Wire.read();
if(aChar == '\n')
{
// End of record detected. Time to parse
index = 0;
inData[index] = NULL;
}
else
{
inData[index] = aChar;
index++;
inData[index] = '\0'; // Keep the string NULL terminated
}
}
Serial.println(strlen(inData));
char* command = strtok(inData, "&");
while (command != 0) {
// Split the command in two values
char* separator = strchr(command, ':');
if (separator != 0) {
// Actually split the string in 2: replace ':' with 0
*separator = 0;
int servoId = atoi(command);
++separator;
int position = atoi(separator);
// Do something with servoId and position
Serial.print(servoId);
}
// Find the next command in input string
command = strtok(NULL, "&");
}
}
这是您需要“解析”您的输入(与I2C不同的I / O设备;示例原理)的一种很好的例子:
http://forum.arduino.cc/index.php?topic=48925.0
char inData[80];
byte index = 0;
void loop() {
while(Serial.available() > 0) {
char aChar = Serial.read();
if(aChar == '\n') {
// End of record detected. Parse this line
...
// When you're done parsing, clear the array and reset the index
inData[index] = NULL;
index = 0;
}
else {
inData[index] = aChar;
index++;
inData[index] = '\0'; // Keep the string NULL terminated
}
}
}
“解析”的一种选择可能是使用strtok() 。 这是一个很好的例子:
https://arduino.stackexchange.com/questions/1013/how-do-i-split-an-incoming-string
char* command = strtok(inData, "&");
while (command != 0) {
// Split the command in two values
char* separator = strchr(command, ':');
if (separator != 0) {
// Actually split the string in 2: replace ':' with 0
*separator = 0;
int servoId = atoi(command);
++separator;
int position = atoi(separator);
// Do something with servoId and position
}
// Find the next command in input string
command = strtok(NULL, "&");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.