我正在使用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, "&");
}
}
答案 0 :(得分:0)
这是一个很好的例子,说明你需要解决的问题&#34;您的输入(与I2C不同的I / O设备;采样原理):
http://forum.arduino.cc/index.php?topic=48925.0
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, "&");
}
&#34;解析&#34;的一个选项可能是使用strtok()。这是一个很好的例子:
https://arduino.stackexchange.com/questions/1013/how-do-i-split-an-incoming-string
$("input[type=checkbox]").on("click", function () {
var id = $(this).data("studentcheckboxid");
var button = $("div").find("[data-studentbuttonid='" + id + "']");
if ($(this).is(':checked')) {
$(button).prop('disabled', true);
} else {
$(button).prop('disabled', false);
}
});