我将Arduino连接到Spark Core,它与Arduino具有相同的代码框架。它们之间的通信大部分时间都很好,但我注意到在某些时候Arduino无法向Spark Core发送消息。 Arduino收到来自Spark Core的消息就好了。即使代码很简单,我也不明白可能导致UART出现问题的原因。
在这种情况下,我有一个连接到Arduino的按钮,每当用户按下它时,它会发送'高'打开一个LED的Spark Core,当它们放开时,它会发送“Low'关闭领导。有人可以帮助我理解为什么有时UART会冻结或者什么?如何检测问题并修复它?
Arduino代码:
#define buttonPin 7
int buttonState = 0; // variable for reading the pushbutton status
int sendonce = 0;
void setup() {
Serial.begin(9600);
// Serial.print("BEGIN\n");
}
void loop() {
isButtonPressed();
}
void isButtonPressed () {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
if (sendonce == 0)
{
Serial.print("High\n");
// ser.write('1');
sendonce = 1;
}
}
else if (buttonState == LOW && sendonce == 1) {
sendonce = 0;
Serial.print("Low\n");
}
}
Spark Core Code:
#include "Serial2/Serial2.h"
// name the pins
int led1 = D7;
int led2 = D1;
String txtMsg = "";
char s;
char lightStatus[20] ;
// This routine runs only once upon reset
void setup()
{
// Configure the pins to be outputs
pinMode(led1, OUTPUT);
// Initialize both the LEDs to be OFF
digitalWrite(led1, LOW);
//Serial1.begin(9600);
Serial2.begin(9600);
//Serial2.println("Hello From Spark");
}
// This routine loops forever
void loop()
{
while (Serial2.available() > 0) {
s=(char)Serial2.read();
if (s == '\n') {
if(txtMsg=="High") {
digitalWrite(led1, 1);
strcpy(lightStatus, "Light On");
}
if(txtMsg=="Low") {
digitalWrite(led1, 0);
strcpy(lightStatus, "Light Off");
}
// Serial.println(txtMsg);
txtMsg = "";
} else {
txtMsg +=s;
}
}
}