serialEvent()
作为串口中断回调函数,需要注意的是,这里的中断与硬件中断有所不同,这个回调函数只会在loop()
执行完后才会执行,所以在loop()
里的程序不能写成阻塞式的,只能写成轮询式的。
/*通过串口控制LED灯的亮灭,输入o开灯,输入f关灯*/
#define led 13
char led_recv_status = 0;
bool stringComplete = false;
void setup()
{
pinMode(led,OUTPUT);
digitalWrite(led, LOW);
Serial.begin(115200);
Serial.println("please select 'o' or 'f' to control led:");
}
void loop()
{
if(stringComplete == true)
{
if(led_recv_status == 'o')
{
digitalWrite(led, HIGH); //led on
Serial.println("led on");
}
else if(led_recv_status == 'f')
{
digitalWrite(led, LOW); //led off
Serial.println("led off");
}
stringComplete = false;
}
}
void serialEvent()
{
while (Serial.available())
{
led_recv_status = (char)Serial.read();
stringComplete = true;
}
}