· 6 years ago · Dec 18, 2019, 03:56 PM
1#define servo 13
2#include <WiFi.h>
3String apiKey = "UB8GQ0ZJ9TBBB0IA"; // Enter your Write API key from ThingSpeak
4const char *ssid = "st"; // replace with your wifi ssid and wpa2 key
5const char *pass = "12345678";
6const char* server = "api.thingspeak.com";
7WiFiClient client;
8int f = 50;
9int pos;
10void setup()
11{
12 ledcAttachPin(servo, 13);
13 ledcSetup(servo, f, 12);
14 Serial.begin(115200);
15 delay(10);
16 Serial.println("Connecting to ");
17 Serial.println(ssid);
18 WiFi.begin(ssid, pass);
19 while (WiFi.status() != WL_CONNECTED)
20 {
21 delay(500);
22 Serial.print(".");
23 }
24 Serial.println("");
25 Serial.println("WiFi connected");
26
27}
28
29void loop()
30
31{
32 // dealing with 3 variables. Bit, position in degrees and pwm signal in miliseconds.
33 int i = random(410) + 102; // bit range of pwm 0.5ms - 2.5ms is 102 - 512
34 int pos;
35 ledcWrite(servo, i);
36 pos = map(i, 102, 512, 0, 180); // scaling the bit range to the degree range of 0 - 180 degrees.
37 float t = 1/f;
38 float pwm = i*20.0/4095.0;
39 float dutyCycle = pwm*100.0/t;
40 Serial.print("Current angle = ");
41 Serial.println(pos);
42 Serial.print("Current PWM signal = ");
43 Serial.print(pwm);
44 Serial.println("ms");
45 Serial.print("Dutycycle = ");
46 Serial.print(dutyCycle, 0);
47 Serial.println("%");
48 delay (4000);
49
50
51 if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com
52 {
53
54 String postStr = apiKey;
55 postStr +="&field1=";
56 postStr += String(pos);
57 postStr +="&field2=";
58 postStr += String(pwm);
59 postStr +="&field3=";
60 postStr += String(dutyCycle);
61 postStr += "\r\n\r\n";
62
63 client.print("POST /update HTTP/1.1\n");
64 client.print("Host: api.thingspeak.com\n");
65 client.print("Connection: close\n");
66 client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
67 client.print("Content-Type: application/x-www-form-urlencoded\n");
68 client.print("Content-Length: ");
69 client.print(postStr.length());
70 client.print("\n\n");
71 client.print(postStr);
72
73 Serial.print("Servo position ");
74 client.print("\n\n");
75 Serial.println(pos);
76
77 Serial.println("Send to Thingspeak.");
78 }
79
80 client.stop();
81 Serial.println("Waiting...");
82 delay(4000);
83}