-
Notifications
You must be signed in to change notification settings - Fork 0
/
RS485.ino
97 lines (88 loc) · 1.55 KB
/
RS485.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const int led = 13;
const int buzzer = 6;
#define TxRx 3
bool mode = LOW; // HIGH = Tx; LOW = Rx
const char START = 44; // 1; // SOH (Start of Header) ,
const char OK = 43; // 6; // ACK (Acknowledge) +
const char END = 35; // EOT (End of Transmission) #
void beep(int times = 1) {
tone(buzzer, 1000, 300);
}
/*ISR (USART_TX_vect)
{
digitalWrite(TxRx, LOW);
}*/
void setup()
{
//UCSR0B |= (1 << TXCIE0);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(TxRx, OUTPUT);
pinMode(buzzer, OUTPUT);
beep();
receive();
Serial.begin(9600);
}
void loop()
{
delay(random(200, 500));
receive();
if (Serial.available() > 0)
{
char c = Serial.read();
if (c == START)
{
Send(OK);
//receive();
String msg = Serial.readStringUntil(END);
Serial.print(msg); //debug;
// Test
if (msg == "LED")
{
//beep();
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
}
}
}
else
{
return;
char temp;
do
{
Send(START);
receive();
temp = Serial.read();
if (temp == START)
{
return;
}
delay(150);
} while (temp != OK);
Send("LED");
Send(END);
}
}
void receive()
{
mode = LOW;
digitalWrite(TxRx, LOW);
delay(200);
}
void transmit()
{
mode = HIGH;
digitalWrite(TxRx, HIGH);
delay(200);
}
void Send(String message){
transmit();
Serial.print(message);
Serial.flush();
}
void Send(char message){
transmit();
Serial.write(message);
Serial.flush();
}