-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathultrasonic_microservo_twitter_alarm.ino
134 lines (103 loc) · 2.22 KB
/
ultrasonic_microservo_twitter_alarm.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <SPI.h>
#include <Ethernet.h>
#include <Twitter.h>
#include <Servo.h>
// micro servo
Servo ms;
byte servoP = 2;
int pos = 0;
// ultrasonic
byte trigP = 7;
byte echoP = 6;
long distcm = 0;
// buzzer
byte buzzerP = 5;
// led
byte redP = 9;
byte greenP = 8;
//Ethernet Shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 0, 250 };
// Twitter
Twitter twitter("<<< token >>>");
boolean sendTweet = false;
void setup()
{
Serial.begin(9600);
Ethernet.begin(mac, ip);
ms.attach(servoP);
pinMode(trigP, OUTPUT);
pinMode(echoP, INPUT);
pinMode(buzzerP, OUTPUT);
pinMode(redP, OUTPUT);
pinMode(greenP, OUTPUT);
}
void loop()
{
for (pos = 0; pos <= 180; pos += 1)
{
ms.write(pos);
delay(50);
checkDist();
}
sendTweet = false;
for (pos = 180; pos >= 0; pos -= 1)
{
ms.write(pos);
delay(50);
checkDist();
}
sendTweet = false;
}
void checkDist(void){
long distRadar = radar();
if(distRadar <= 30){
tone(buzzerP, 440, 300);
digitalWrite(redP, HIGH);
digitalWrite(greenP, LOW);
if(!sendTweet){
sendTweet = tweet(distRadar);
}
}
else {
noTone(buzzerP);
digitalWrite(redP, LOW);
digitalWrite(greenP, HIGH);
}
Serial.println(distRadar);
}
long radar(void)
{
digitalWrite(trigP, LOW);
delayMicroseconds(5);
digitalWrite(trigP, HIGH);
delayMicroseconds(10);
digitalWrite(trigP, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
long dur = pulseIn(echoP, HIGH);
// Convert the time into a distance (cm)
distcm = (dur/2)/29.1;
return distcm;
}
boolean tweet(long dist){
boolean success = false;
Serial.println("Establishing connection Twitter ...");
char buffer[80];
sprintf(buffer, "Intruder approaching: %d cm", dist);
// Publish tweet. Return true or false.
if (twitter.post(buffer)) {
int status = twitter.wait(&Serial);
if (status == 200) { // Connection success
success = true;
Serial.println("OK.");
}
else { // Connection error
Serial.print("Error : code ");
Serial.println(status);
}
}
else {
Serial.println("Failed connection.");
}
return success;
}