Skip to content

Instantly share code, notes, and snippets.

@2niuhe
Created May 22, 2019 09:20
Show Gist options
  • Save 2niuhe/b6b6d70bd361cd8081fcd22e069f318f to your computer and use it in GitHub Desktop.
Save 2niuhe/b6b6d70bd361cd8081fcd22e069f318f to your computer and use it in GitHub Desktop.
使用arduino nano的串口来控制继电器作为数字开关
#define VCC 2
#define IN 4
const int HEADER = '@';
const char TAIL = '%';
int flag =-1;
void setup() {
Serial.begin(9600);//打开串口波特率9600
pinMode(VCC,OUTPUT);
pinMode(IN,OUTPUT);
digitalWrite(VCC,HIGH);
digitalWrite(IN,LOW); //default off for safety
}
void loop() {
if (Serial.available())//判读是否串口有数据
{
if (Serial.read() == HEADER)
{
delay(3);
flag = Serial.read();
Serial.print("received");
Serial.print(char(flag));
Serial.print('\n');
if(Serial.read() == TAIL)
{
if(flag== '1')
{
digitalWrite(IN,HIGH);
Serial.println("IN on");
flag = -1;
}
if(flag=='0')
{
digitalWrite(IN,LOW);
Serial.println("IN off");
flag = -1;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment