· 6 years ago · Dec 21, 2019, 12:50 PM
1
2#include <SPI.h>
3#include <WiFi101.h>
4#include <Servo.h>
5
6#include "arduino_secrets.h"
7///////please enter your sensitive data in the Secret tab/arduino_secrets.h
8char ssid[] = SECRET_SSID; // your network SSID (name)
9char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
10int keyIndex = 0; // your network key Index number (needed only for WEP)
11
12
13#define TIMEOUT 5000 // Timeout for server response.
14#define UPDATE_TIME_INTERVAL 16000 // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
15
16// ThingSpeak information.
17#define NUM_FIELDS 3 // To update more fields, increase this number and add a field label below.
18#define TEMPERATURE_FIELD 1 // ThingSpeak field for temperature measurement.
19#define WIFI_SIGNAL_FIELD 2 // ThingSpeak Field for WiFi Signal measurement.
20#define BUTTON_COUNT_FIELD 3 // ThingSpeak Field for button count measurement.
21
22
23#define THING_SPEAK_ADDRESS "api.thingspeak.com"
24#define TALKBACK_ID 36554 //Change to your talkback ID
25
26
27String writeAPIKey= SECRET_WRITE_API_KEY; // Change this to your channel Write API key.
28String talkbackAPIKey = SECRET_TALKBACK_API_KEY; //Change this to your talkback API key
29
30
31int pinTempSensor = A0;
32
33int pinServo = 5;
34
35int pinButton = 0;
36int buttonCount;
37
38int status = WL_IDLE_STATUS;
39
40WiFiClient client;
41Servo myservo; // create servo object to control a servo
42
43
44void setup() {
45 Serial.begin(9600); // initialize serial communication
46 pinMode(9, OUTPUT); // set the LED pin mode
47 myservo.attach(pinServo); // attach the servo to the servo object
48 myservo.write(90);
49 pinMode(pinButton, INPUT_PULLUP);
50 attachInterrupt(digitalPinToInterrupt(pinButton), updateCounter, RISING);
51
52 // check for the presence of the shield:
53 if (WiFi.status() == WL_NO_SHIELD) {
54 Serial.println("WiFi shield not present");
55 while (true); // don't continue
56 }
57
58 // attempt to connect to WiFi network:
59 while ( status != WL_CONNECTED) {
60 Serial.print("Attempting to connect to Network named: ");
61 Serial.println(ssid); // print the network name (SSID);
62
63 // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
64 status = WiFi.begin(ssid, pass);
65 // wait 10 seconds for connection:
66 delay(10000);
67 }
68
69 printWiFiStatus(); // you're connected now, so print out the status
70}
71
72
73void loop() {
74 // You can fill fieldData with up to 8 values to write to successive fields in your channel.
75 String fieldData[ NUM_FIELDS ];
76
77 // You can write to multiple fields by storing data in the fieldData[] array, and changing numFields.
78 // Write the moisture data to field 1.
79 fieldData[ TEMPERATURE_FIELD ] = String( readTemperatureSensor( ) );
80 Serial.print( "Temperature = " );
81 Serial.println( fieldData[ TEMPERATURE_FIELD ] );
82
83 // Write the RSSI to Field 2.
84 fieldData[ WIFI_SIGNAL_FIELD ] = String( WiFi.RSSI() );
85
86 //Write the button count to Field 3
87
88 fieldData[BUTTON_COUNT_FIELD] = String(buttonCount);
89
90 HTTPPostData( NUM_FIELDS , fieldData );
91
92 HTTPPostCheckTalkBack(); //Uncomment for C4
93
94 buttonCount = 0;
95 delay( UPDATE_TIME_INTERVAL );
96
97
98}
99
100// This function builds the data string for posting to ThingSpeak
101 // and provides the correct format for the wifi client to communicate with ThingSpeak.
102 // It will post "numFields" worth of data entries, and takes the
103 // data from the fieldData parameter passed to it.
104
105int HTTPPostData( int numFields , String fieldData[] ){
106
107 if (client.connect( THING_SPEAK_ADDRESS , 80 )){
108
109 // Build the Posting data string.
110 // If you have multiple fields, make sure the string does not exceed 1440 characters.
111 String postData= "api_key=" + writeAPIKey ;
112 for ( int fieldNumber = 1; fieldNumber < numFields+1; fieldNumber++ ){
113 String fieldName = "field" + String( fieldNumber );
114 postData += "&" + fieldName + "=" + fieldData[ fieldNumber ];
115
116 }
117
118 String postCommand = "POST /update HTTP/1.1";
119 Serial.println(postData);
120 // POST data via HTTP
121 Serial.println( "Connecting to ThingSpeak for channel update..." );
122 Serial.println();
123
124 client.println( postCommand );
125 client.println( "Host: api.thingspeak.com" );
126 client.println( "Connection: close" );
127 client.println( "Content-Type: application/x-www-form-urlencoded" );
128 client.println( "Content-Length: " + String( postData.length() ) );
129 client.println();
130 client.println( postData );
131
132 Serial.println( postData );
133
134 String answer=getResponse();
135
136 client.stop();
137 Serial.println( answer );
138 }
139 else
140 {
141 Serial.println ( "No puedo enviar datos al servidor" );
142 Serial.println ( "Connection Failed" );
143 }
144
145
146
147}
148
149//This function creates the POST call to gather the next command in the TalkBack command queue.
150//Uncomment for C4
151
152int HTTPPostCheckTalkBack(){
153
154 String talkbackID = String(TALKBACK_ID);
155 if (client.connect( THING_SPEAK_ADDRESS , 80 )){
156
157 // Build the Posting data string.
158 String postData= "api_key=" + talkbackAPIKey ;
159
160 String postCommand = "POST /talkbacks/" + talkbackID + "/commands/execute HTTP/1.1";
161
162 // POST data via HTTP
163 Serial.println( "Connecting to ThingSpeak for talkback checking..." );
164 Serial.println();
165
166 client.println( postCommand );
167 client.println( "Host: api.thingspeak.com" );
168 client.println( "Connection: close" );
169 client.println( "Content-Type: application/x-www-form-urlencoded" );
170 client.println( "Content-Length: " + String( postData.length() ) );
171 client.println();
172 client.println( postData );
173
174 Serial.println( postData );
175
176 String answer=getResponse(); //Answer from talkback. You need to parse it to process it.
177
178 client.stop();
179 parseCommand(answer);
180
181 //Serial.println( answer );
182 }
183 else
184 {
185 Serial.println ( "No puedo recoger el talkback" );
186 Serial.println ( "Connection Failed" );
187 }
188
189
190
191}
192
193// Wait for a response from the server to be available,
194//and then collect the response and build it into a string.
195String getResponse(){
196 String response;
197 long startTime = millis();
198
199 delay( 200 );
200 while ( client.available() < 1 && (( millis() - startTime ) < TIMEOUT ) ){
201 delay( 5 );
202 }
203
204 if( client.available() > 0 ){ // Get response from server
205 char charIn;
206 do {
207 charIn = client.read(); // Read a char from the buffer.
208 response += charIn; // Append the char to the string response.
209 } while ( client.available() > 0 );
210 }
211
212
213 return response;
214}
215
216// This function reads the
217float readTemperatureSensor()
218{
219 int tempSensor=0;
220 float tempVoltage=0;
221 float tempDegrees;
222 tempSensor = analogRead(pinTempSensor);
223 tempVoltage = tempSensor * (3300/1024); //in miliVolt
224 tempDegrees = (tempVoltage - 500) / 10;
225 return tempDegrees; // Return the moisture value.
226}
227
228
229void parseCommand(String answer)
230{
231 Serial.println("Respuesta " + answer);
232
233 answer.trim();
234 if (answer.endsWith("TURN ON")) {
235 digitalWrite(9, HIGH); // GET /H turns the LED on
236 }
237 if (answer.endsWith("TURN OFF")) {
238 digitalWrite(9, LOW); // GET /L turns the LED off
239 }
240
241 if (answer.endsWith("TURN LEFT")) {
242 myservo.write(0);
243 }
244
245 if (answer.endsWith("TURN RIGHT")) {
246 myservo.write(179);
247 }
248}
249
250
251void printWiFiStatus() {
252 // print the SSID of the network you're attached to:
253 Serial.print("SSID: ");
254 Serial.println(WiFi.SSID());
255
256 // print your WiFi shield's IP address:
257 IPAddress ip = WiFi.localIP();
258 Serial.print("IP Address: ");
259 Serial.println(ip);
260
261 // print the received signal strength:
262 long rssi = WiFi.RSSI();
263 Serial.print("signal strength (RSSI):");
264 Serial.print(rssi);
265 Serial.println(" dBm");
266 // print where to go in a browser:
267 Serial.print("To see this page in action, open a browser to http://");
268 Serial.println(ip);
269}
270
271void updateCounter(){
272 buttonCount += 1;
273}