Is There Art in (Fake) Artificial Intelligence?

A tech amateur dives into building an Internet enabled gadget from scratch.

“Obsessed with building a shitty robot for political satire, I used trial and error to jam code into cheap micro-controllers and eastern European IoT clouds.”

The Presidential Weather Forecast Machine is an Internet of thing inspired by a 2018 news story
The Presidential Weather Forecast Machine is an Internet of thing inspired by a 2018 news story
The Presidential Weather Forecast Machine is an Internet of thing inspired by a 2018 news story

[This post contains affiliate links, but not in a skeezy way. It’s all the stuff I used, recommend and now hope to pay for!]

This Presidential Weather Forecast Machine is an Internet-enabled, wall-mounted device that provides tomorrow’s weather forecast, letting the user know if it will be sunny, rainy or windy. the Machine is styled after artifacts of local government, like public school pencil sharpeners or signage at the Department of Motor Vehicles. It’s utilitarian and unassuming, like an elevator safety certificate, but It has a button.

When the button is pushed, the Machine checks tomorrow’s weather for the city indicated on its front and notifies the use of the weather — with a surprise. [Spoiler Video embedded below]

The Presidential Weather Forecast Machine is an Internet of thing inspired by a 2018 news story — and resulting ‘Twitterstorm’ — about presidents and the weather.

It’s a comment on anachronism in the three-way relationship between ourselves, information and the presidency. It is constructed with a thrift store wooden photo frame, a drawing of the White House and three photos from the National Archives, printed on paper, mounted on cardboard, with legos, medical-grade tongue depressors, brass paper fasteners, a clear acrylic sheet from Home Depot, staples, glue, scrap wood and a series of microcontrollers, two online Internet of Things (IoT) cloud services, ‘jumper cable’ wires, a two-port USB adapter, an extension cable, a breadboard, an LED, some tin foil and motors. Details and links below.

Is that AI?

Because of the quirks of how it works, the Machine can seem alive as it buzzes, twitches and blinks — all imperfectly. While it’s tempting to pretend it’s an Artificial Intelligence (AI), it’s not. The Presidential Weather Forecast Machine is based on very basic logic bouncing between circuits and clouds.

How it Works: Rube Goldberg in the Cloud

Behind the scenes, the Machine is actually two machines: different microcontrollers running on two different cloud services. The button tells an NodeMCU ESP8266 microcontroller to connect to WiFi (securely) and make an HTTPS request to a webhook running on an an online / cloud service called Integromat. This then activates an Integromat ‘Scenario’ in the cloud that makes its own HTTP request to OpenWeatherMap and filters the response to determine if the weather tomorrow is windy, sunny or rainy. The first ‘yes’ to these questions sends an HTTP request to Blynk.io, another online / cloud service for IoT. A WeMos D1 microcontroller connects to Blynk when it powers on and spends its life awaiting Blynk’s instructions. The ‘yes’ from Integromat makes a HTTP request to change the value of one of Blynk’s three virtual pins, belonging to corresponding servo motors, to move about 90 degrees. Integromat then counts 7 seconds and returns the servo to its original position, about 0 degrees. The Machine is then ready for its next forecast, repeating all this.

The back of the Machine.
The back of the Machine.
The back of the Machine.

More about the clouds: Integromat and Blynk

Integromat is an independent company based in Prague, Czech Republic with a subsidiary in USA. It helps connect different online apps and, in this case, things. It can be used for serious integration of important things like AWS, Microsoft Teams, Salesforce, Stripe, Twilio and Zoho. I use it to tell the weather and tell my little $2 servo motors how to move, from the cloud.

Blynk.io is Blynk started in Kiev, Ukraine as a Kickstarter, but is now headquartered in New York City. Their offerings are growing for serious IoT, M2M and mobile developers. They can connect anything from Arduinos o very serious-sounding things like ARM mbed and Intel Edison. [Full list of Blynk-supported hardware here]. They also have a super almost no-code — and free — way to send HTTP calls, based on weather data, back to my $10 microcontroller.

The Machine can almost seem ‘intelligent’ or alive because of how its commodity, very-basic (i.e. super cheap) SG90 servos work.

There are three in the Machine and each makes a different buzz and moves at slightly different speeds. Because the Machine relies on two WiFi connections and shared clouds for its brains, its reaction times are unpredictable and jerky. Dogs hate it.

You might be wondering how and why the Machine is so needlessly complicated.

The rest of this post is about that.

If you want to skip ahead to see the full Spoiler Video of how it works and get the ESP8266 Arduino sketch code, scroll on down now!

For maker schadenfreude fiends, read on, you’re in for a treat.

My Background in Building IoT Devices is zero. I majored in English and have a career in communications and public relations, so programming and electronics are not something I know about. That said, this was my second-ever Arduino project so I was very confident, having made the first one do what I wanted! That was a single relay activated by If This Then That (IFTTT) via Blynk by an Arduino Uno using an Arduino Ethernet shield. Not exactly a flux capacitor, in retrospect, but as Einstein says, “it’s all relative.”

Image for post
Image for post
Einstein from Back to the Future, a dog that is now surely long dead

Me thinking this was even going to be an Arduino project would become the first of my many mistakes. This was in actuality going to be a nine-month deep dive into ESP8266 microcontrollers.

I was about to make all of this work by learning through excruciating trial and error! I would google until my fingers bled, Frankenstein’s-monster copy and paste code examples and go to the forums when all else failed.

It Begins: Blynk.io is IoT That’s Easy and Amazing…for most people.

Before I knew what it would look like exactly, I knew the Machine needed to move arms based on weather data. I suspected that weather data could be pulled in from somewhere and broken down into triggers: if it’s windy tomorrow, move one arm, if it’s rainy move another, etc. I’d figure out the weather later, but assumed IFTTT would help again. (If it rains, send an HTTP request?)

For now, the first step was to make the servos move using Blynk.io. I’d used Blynk previously for running a relay, which just needed a pin turned to HIGH. For that project, I set the Blynk Button to send a 1 when the relay was on, 0 when it wasn’t. Moving the servos wasn’t very different. The servo would move to 60 degrees when it was ‘on’ and 0 degrees when it was ‘off’. I could change the numbers easily in the Blynk mobile app. The degrees the servos needed to turn to were easy to change in the Blynk mobile app to put the servos exactly where you need them.

Image for post
Image for post
Setting the Button on Blynk.io mobile app to control a servo with the WeMos D1

This was valuable for prototyping the servos moving, but to get them reacting to weather, the commands to Blynk cloud would be sent not by my iPhone but by another cloud. More on that later. For now, th e the important learning from forum posts I found helpful like this one [ How to Control Servo With Button switch 1 or 2 servo — Need Help With My Project — Blynk Community ] was that Blynk doesn’t care that these are servos, it’s just sending numbers to a device connected to its cloud.

I created the prototype to move the servos with Blynk using an Arduino Uno with an Ethernet shield and tested it with the mobile app. [video below] The next step was to go wireless. I pictured the Machine as something portable and Ethernet would ruin that. Nothing bulks up this tiny hardware like a thick Ethernet cable wagging it around.

WiFi Swap: How ‘Arduino’ Became ‘ESP8266 with Arduino IDE’

I hadn’t tried WiFi with Arduino. I thought I could get a WiFi shield just as I’d done with Ethernet. I already had an Uno ready to go and typed “Arduino WiFi Shield” into smile.amazon. I ended up with one of these: a WeMos D1. You’ll notice that, at $9.99 USD, it was even more tempting to believe that this would do the job of the very legit-looking Arduino MKR WiFi 1010, which is more than three times the price of the WeMos. Because this thing’s called a ‘shield’ I also assumed that this would strap onto the back of an Arduino Uno just like its Ethernet shield, and not require me to learn anything else. All wrong.

A note on spending money for hardware and cloud services

You can always save a few dollars by getting roughly the same hardware on Aliexpress, but delivery is much slower, in my experience. Weeks versus days. Sometimes you just need things Amazon Prime-fast to keep the project going. This is also why I gave Integromat $9 when I accidentally sent too many HTTP requests in one burst and ran out of bandwidth for the month. Of course, that payment repeats and isn’t super easy to cancel.

Image for post
Image for post
WeMos D1 ESP9266 microcontroller https://commons.wikimedia.org/wiki/File:Wemos_d1.jpg

Here’s how I started with ESP8266 and IoT while knowing nothing

When I got the WeMos D1 and realized it was a standalone microcontroller, rather than a shield, I still didn’t know what that meant. I didn’t know how different this was from the Arduino Uno. It looks deceptively similar!

I quickly learned what every article says about working with ESP8266 on the Arduino IDE: Once I had the latest-ish IDE from Arduino.cc I needed to add the board manager for all things ESP8266. You don’t need me to tell you how to do that because Sparkfun has already written a great tutorial with its own appropriate shoutouts for how to setup an ESP8266 on the Arduino IDE. It’s got pictures! Also they actually know what they’re talking about.

Setting Up the Arduino IDE to talk to ESP8266 Board

After all the forums and all the bracket closing and semi-colon forgetting, when the ESP8266 code finally compiles, setting up the Arduino IDE to talk to the WeMos D1 — or any ESP8266 board — can be another tricky hurdle. I recommend getting it to work with the Blink example before getting fancy and you might save yourself some pain. Here are a few examples of ESP8266 Arduino IDE errors I had the pleasure of enjoying!

The wrong USB cable means the IDE won’t see the board and you’ll get this error:

the selected serial port serial.serialutil.SerialException: [Errno 2] could not open port /dev/cu.wchusbserial410: [Errno 2] No such file or directory: ‘/dev/cu.wchusbserial410’does not exist or your board is not connected
Image for post
Image for post

Many argue the following Arduino IDE error isn’t even an error:

‘Leaving… Hard resetting via RTS pin…”
Image for post
Image for post

However, it does mean that you probably won’t see anything on the Serial Monitor but nonsense.

This happened to me when I specified the Flash Size setting on the default setting (2MB) instead of this one: none. There are probably countless other reasons this error may occur.

Image for post
Image for post

Setting up ESP8266 Boards is Trial and Error

Finally, here’s the kicker. Even when I successfully uploaded code to my WeMos D1, it didn’t always work properly because the board settings are finicky. Another example is that different baud rates specified in the Arduino sketch, Serial Monitor and board settings can cause jumbled nonsense in the Serial Monitor. Be sure that you set those Arduino IDE board settings very specifically to the model and version of the microcontroller you’re using to avoid troubleshooting hell.

Image for post
Image for post
The Serial Monitor read out from connecting to Blynk.io

How Pins Work on ESP8266 and Arduino Microcontrollers is Different: Something Else I Didn’t Know!

When you finally upload a sketch smoothly and see the Serial Monitor come to life by reading something from the Internet, it’s just exhilarating enough to keep you going toward the next Rube Goldberg IoT obstacle!

For me, it was that the board didn’t stay online once connecting. The WeMos D1 WiFi connecting to Blynk.cc would drop the connection repeatedly and so, as this link shows, I went to the amazing Blynk community for help. They’d done it many times before, even when my questions were very basic (though I always exhaust googling before posting a new question.)

What i learned is the biggest differences between Arduinos and ESP8266 micro-controllers, from the perspective of a newbie like me, anyway — is that the pin numbers on ESP8266s, both the WeMos D1 and the NodeMCU 1.0 I used for this project, were not the same as written on the board.

You heard me! On the Arduino, the pin hole with the number 5 on it is pin 5. On ESP8266 — you need to ask which model to find out!
Both boards required me to refer to the pinout diagrams over and over. (below) Another fun fact, NodeMCU.com — the URL laser-etched into the board itself, does not contain a pinout illustration of the NodeMCU anywhere I could find.

NodeMCU 1.0 ESP8266 Microcontroller pinout pin diagram
NodeMCU 1.0 ESP8266 Microcontroller pinout pin diagram
NodeMCU 1.0 Pinout diagram
WeMos D1 ESP8266 Microcontroller pinout pin diagram
WeMos D1 ESP8266 Microcontroller pinout pin diagram
WeMos D1 ESP8266 pinout diagram

Once I changed the pins the servos were assigned to, the WeMos D1 finally stayed connected to WiFi. I could control each of the 3 servos attached to the WeMos D1 using the Blynk iPhone app. It was bliss. This video I made for Facebook, including its soundtrack, says it all.

If you need a primer on using Blynk.io to control Arduino, ESP8266, ESP32, any Raspberry Pi and other …things with a phone or with HTTP requests (as I’m doing), check out their easy-peasy Blynk Getting Started page.

IoT Clouds: If the Weather is X, Then please Move Servo Y? Please??

At this point, understanding how I would translate weather into HTTP requests was unknown to me. I’d assumed that IFTTT would do the trick but got confused in whatever the IFTTT Maker Platform thing has become. You’d think this use case is the exact thing the IFTTT name implies, but those freebie, maker-hippie, ‘monetize-later’ days are long gone. It’s later. I’d also looked at Zapier, but that looked like it was also for business and other useful things: not the help with my shitty robots I’m looking for.

Then, I found Integromat: My Internet of Thing wouldn’t work without it! No they’re not paying me, but they can feel free to! Yes, this connects serious apps but it also seems to have been purpose built for my needs. This is the no code, IoT utopia I’d been promised! It can do basic ‘reading’ of data and turn it into triggers such as HTTP requests. Furthermore, Integromat has open, detailed, weather data you can automatically read and filter, turning different weather into different triggers and then — for my purposes — HTTP calls to Blynk.io.

The best thing is that Integromat’s visual interface, compared to all the other we-integrate-everything internet of things cloud services, is that it worked very well with how my brain visualized the different steps I needed to run the WeMos D1 servo motors. Filters identify the weather in Integromat: e.g. will wind be faster than 25mph? Fun fact: The National Weather Service defines ‘Windy’ as winds from 20 to 30 miles per hour. The Presidential Weather Forecast Machine predicts a windy day tomorrow when speeds are going to be more than 25mph to split the difference, but I can easily adjust it if I want the forecasts to have some variety near the coast, for example — since who care about ‘windy’ anyway.

Image for post
Image for post
Setting the Integromat filter for windy weather

If the filter is triggered then bam, a call to Blynk is made that contains everything Blynk needs: the virtual pin 7 will make the servo move to 90 degrees. The URL is the IP address for Blynk cloud plus the secret Blynk Code.

The HTTP call to Blynk from Integromat looks like this:

http://45.55.96.146/xxxxMYSECRETBLYNKCODExxxx/update/V7?value=90

Now we’re moving all the servos via the cloud however we want in reaction to the weather and back to starting position. It’s also easy to include delays on Integromat. The screenshot of the Integromat scenario below is the Machine’s entire logic, triggered when it gets a Webhooks call from the Machine’s button, which is the other half of this project.

Image for post
Image for post
Integromat Scenario for the Presidential Weather Forecast Machine

How is this ‘How to’ post not over yet?

The Machine Gets a Button

At this point, the main premise of the Presidential Weather Forecast Machine was done. The servos moved based on weather using Integromat and Blynk.io with the WeMos D1. This made me bold and ambitious. It was also around the time my first-ever interactive installation, The Wall Shutdown, appeared in an art show at The Crucible in Oakland and I wanted this project to be able to be interactive as well. The Wall Shutdown project had a switch people loved flipping. [VIDEO]

By contrast, the Presidential Weather Forecast Machine was running on an Integromat timer. It would just check the weather every 15 minutes or so and twitch accordingly.

This would suck in an art gallery. I realized it needed a button.

Again, I had no idea how difficult this would be.

Adding a physical button to activate the NodeMCU HTTPS call to Integromat took me around nine more months to figure out.

Adding a physical button to a microcontroller project sounds so simple and mundane that I would have never imagined I’d find myself feeling so alone in looking for a way to make it happen. A HTTPS request at the press of a physical button sounds like the essence of all Internet of Things promises but nobody seems to have bothered to update the How-Tos since 2016.

So here’s the short version (too late, I know!)

The sketch to drive three servos from Blynk was already complicated, by my newbie standards. Plan A is always to try mashing up two examples. You would think the ESP8266 Blynk code plus ESP8266 WiFi and button examples could be mashed up simply enough. I did and I was very wrong again.

Then I did once again what I always do when stuck, throw myself on the mercy of The Community with this post: Need Help: Won’t Compile w Button, Servos, Webhooks on WeMos D1 — Need Help With My Project — Blynk Community. The Blynk community has some wildly expert and altruistic folks like Pete there who have helped me time after time, even as a novice newbie with no coding background.

I wondered: “Is it even possible to do this many things with one microcontroller?

This time, the advice in this thread didn’t help. I’m still not sure if what I needed could have ever worked, since it requires one humble WeMos D1 ESP8266 microcontroller to send a request to one URL: Integromat’s Web hooks and then receive commands via Blynk.io — which doesn’t seem to love playing with others. It just logs on and waits to be triggered.

Two IoT Heads Are Better Than One

Took me months to realize the answer was a second microcontroller. Just like Carly Rae Jepsen’s “Call Me Maybe”, this would create a call and response relationship between the microcontrollers. The button would tell Integromat to start its scenario using the webhook and the WeMos D1 could just stand by and wait for Blynk.io to tell it what to do. Plus, doing it this way would have to be easier, right? No.

Image for post
Image for post
NodeMCU 1.0 https://commons.wikimedia.org/wiki/File:NodeMCU_DevKit_1.0.jpg

Why the NodeMCU ESP8266?

The NodeMCU has WiFi built in, is itty-bitty small and can be had for around three dollars. To sweeten the deal, I had one lying around already that I’d been intimidated by, compared to the friendly Arduino Uno. That’s why, the WeMos D1 is the perfect Arduino to ESP8266 gateway board, luring in Arduino newbies with its Uno-like good looks and approachability. I was now ready to try the NodeMCU!

Again, this was freakishly hard considering I was just trying to make my own Amazon Tab button. Nothing at all unique. Articles like this one — in credible publications like Make Use Of — made me think this wouldn’t be hard. Lies!

The following article and ones like it are wrong and outdated: How to Make Your Own Wi-Fi Connected Button With ESP8266 This article tells you to just go get the IFTTT library and you’re good to go! There is no more IFTTT Arduino library. It was deprecated years ago. Again, I’d have to do this the hard way.

[I was going to make this paragraph profanity-filled, but keeping this post family friendly]

Getting the NodeMCU onto WiFi wasn’t hard, once figuring out the same board-connection and pinout challenges I talk about above. But then…

HTTP vs. HTTPS, 301 Errors, SSL and SHA1 Fingerprints

When trying to connect to Integromat webhooks I kept getting an error 301 in the Serial Monitor. Again, the community answer to what is an Arduino 301 error didn’t help. This is when I discovered postman-echo.com which is helpful for troubleshooting HTTP calls and other API things. When I used it to make the call to HTTPS instead of HTTP, I got the response I wanted: triggering Integromat. I understood that the HTTP approach I used with Blynk and IFTTT (my only Arduino to cloud experience) wasn’t going to work for Integromat. HTTPS / SSL on the NodeMCU was hard to figure out. Some articles said I would need to reflash the board with new firmware using Esptool or the NodeMCU firmware builder for this work, but that was wrong. Others had deceptively hopeful names like Doing SSL Requests on ESP8266 Correctly and still left me lost.

The most useful article about making HTTPS GET and PUT requests with an NodeMCU ESP8266 is this one from Circuits4you.com:
ESP8266 NodeMCU HTTPS Secured GET Request | Circuits4you.com

It didn’t work right out of the box, (nothing seems to), but It helped me realize that I didn’t need to flash firmware or get a fancier board than the NodeMCU. This was at least possible. And it’s the only article I’ve seen talking about the SHA1 fingerprint to do SSL on Arduino compatible boards and it even shows you how to obtain the SHA1 fingerprint.

Once I got the SHA1 fingerprint for Integromat and added some of the other elements in the Circuits4you example, I could do the HTTPS calls. This took a lot of trial and error so please check out my code closely. For example, you’ll need to use Port 443 and add a library for base64 which the above example doesn’t have.

And another fun fact about SHA1 fingerprints: they change and need updating.

I found this out while getting the Machine ready to photograph for this Medium post, long after I thought I was done messing with the code. The Machine stopped working while I’d been busy writing this never-ending novella. I had to troubleshoot back to authentication to realize the fingerprint had changed when I repeated the process above.

I now realize that the Machine has so many dependencies, it will always be a never-ending story.

Arduino Sketch Buttons with IF/ELSE — and without

With the fingerprint working, the NodeMCU was making HTTPS calls to Integromat and getting responses, but I still didn’t have a button. This was the final hurdle because all the Arduino Button examples I found rely on IF / ELSE structure — I struggled to find examples that could include this within all the WiFi / SSL connectivity IF / ELSEs and reading the server’s responses in between.

No example had both. Furthermore, this wasn’t Blynk.io anymore. General ESP8266 forums proved less helpful. I got zero response to desperate pleas like this: NodeMCU ButtonBush-> WiFi HTTP Request not working — Everything ESP8266

Adding the physical button, finally

It took some lateral thinking — which will always be your friend here too — and googling — to solve this. Finally, I found this post Arduino ESP32 : HTTP(S) POST Request to IBM Watson IoT on Button Press. It’s a more baroque code than I’d originally imagined needing but it’s also the only online example I found of WiFi with a physical button and an API call, plus it’s written by a genuine programming person. Abhishek Ghosh, who’s also an orthopedic surgeon! You see his creds are also still in the sketch code below. This code’s also awesome at tying a status LED to what the button is doing. I tinkered with the delays of the LED to give the Presidential Weather Machine its signature blue glow.

Now, when the button is pressed, this would happen (Serial Monitor view of the NodeMCU in action)

…It’s alive!

There’s no video of the mechanism before I assembled the Machine, because I damn-near lost it from joy.

There was an odd moment, once the parts all worked as planned, that I needed to think about how I would make the ball of wires, motors and silicon into an object. I also needed this to be realistic. Having spent about a year making my weird snarky dream a reality, finishing it was also top of my mind. I needed it done. The paper I used would have to forgo getting stained with tea to make it look old, for example. However, I got the frame I’d pictured from the closest Goodwill and bought an acrylic sheet of the same size at the Home Depot to match the size. Using scrap wood, Legos, cardboard and gallons of hot — and other temperatures of — glue, I built something that could hang, be rugged enough to be poked at and hide its comical secret for maximum effect. Just like the project itself, I can keep adding details to the trial and error of getting the motors and photos to fit within in the frame, but will save that for other posts.

Presidential Weather Forecast Machine [Spoiler Video]

Presidential Weather Forecast Machine [Spoiler Video]

What did we learn?

That the road to self expression through the internet of things is paved with broken promises and triumphs. Most documentation lies. Most articles are out of date. Most forums are bad and sometimes the most obvious conclusion is wrong. All that said, there are many smart technical people who do this for real who say nobody can succeed by just copying and pasting code snippets until something just works. My painful but ultimately successful journey proves them wrong. There are also many people who will go out of their way to help a newbie figure out a technology they’re expert on and passionate about. This is who makes developer communities great and dumb IoT dreams possible!

Follow your own ridiculous technology dreams and keep going until it does whatever the Internet of thing you want!

Did this huge post leave something out or just want to hear more about something? Say so in the comments! Below’s all the code, as promised.

Just Show Me That Sweet Code

Code on NodeMCU to push button and send HTTPS request

// From https://thecustomizewindows.com/2019/03/arduino-esp32-https-post-request-to-ibm-watson-iot-on-button-press/
// connects once upon pressing ESP32 boot pushbutton (GPIO 0) button and sends a message, closes connection
// written by Dr. Abhishek Ghosh, https://thecustomizewindows.com
// released under GNU GPL 3.0
const byte BUTTON=5; // boot button pin (built-in on ESP32)
const byte LED=4; // onboard LED (built-in on ESP32)
const char* fingerprint = "83 A7 2E 6C 37 83 38 14 CB A8 BB B9 03 76 DA BE F8 8A C1 79";
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <base64.h>
#define USE_SERIAL Serial

unsigned long buttonPushedMillis; // when button was released
unsigned long ledTurnedOnAt; // when led was turned on
unsigned long turnOnDelay = 20; // wait to turn on LED
unsigned long turnOffDelay = 4000; // turn off LED after this time
bool ledReady = false; // flag for when button is let go
bool ledState = false; // for LED is on or not.
const char* ssid = "WifiName";
const char* password = "MyWIFIPassWord";
#define DEVICE_TYPE "name you given"
#define DEVICE_ID "name you given"
#define TOKEN "your token"
#define EVENT "myEvent" // example
// <------- CHANGE PARAMETERS ABOVE THIS LINE ------------>String urlPath = "/IntegromatWebHookURL";
String urlHost = "hook.integromat.com";
int urlPort = 443;
String authHeader;

void setup() {
pinMode(BUTTON, INPUT_PULLUP);
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
Serial.begin(115200); Serial.println();
initWifi();
authHeader = "Authorization: Basic " + base64::encode("use-token-auth:" TOKEN) + "\r\n";
}

void loop() {
// get the time at the start of this loop()
unsigned long currentMillis = millis();
// check the button
if (digitalRead(BUTTON) == LOW) {
// update the time when button was pushed
buttonPushedMillis = currentMillis;
ledReady = true;
}

// make sure this code isn't checked until after button has been let go
if (ledReady) {
//this is typical millis code here:
if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay) {
// okay, enough time has passed since the button was let go.
digitalWrite(LED, HIGH);
doWiFiClientSecure();
// setup our next "state"
ledState = true;
// save when the LED turned on
ledTurnedOnAt = currentMillis;
// wait for next button press
ledReady = false;
}
}

// see if we are watching for the time to turn off LED
if (ledState) {
// okay, led on, check for now long
if ((unsigned long)(currentMillis - ledTurnedOnAt) >= turnOffDelay) {
ledState = false;
digitalWrite(LED, LOW);
}
}
}
void doWiFiClientSecure() {
WiFiClientSecure client;
Serial.print("connect: "); Serial.println(urlHost);
Serial.printf("Using fingerprint '%s'\n", fingerprint); // Added
client.setFingerprint(fingerprint); // ADded
while ( ! client.connect(urlHost.c_str(), urlPort)) {
Serial.print(".");
}
Serial.println("Connected");
String postData = String("{ \"d\": {\"aMessage\": \"") + millis()/1000 + "\"} }";
String msg = "POST " + urlPath + " HTTP/1.1\r\n"
"Host: " + urlHost + "\r\n"
"" + authHeader + ""
"Content-Type: application/json\r\n"
"Content-Length: " + postData.length() + "\r\n"
"\r\n" + postData;

client.print(msg);
Serial.print(msg);
Serial.print("\n*** Request sent, receiving response...");
while (!!!client.available()) {
delay(50);
Serial.print(".");
}

Serial.println();
Serial.println("Got response");
while(client.available()){
Serial.write(client.read());
}
Serial.println(); Serial.println("closing connection");
client.stop();
}
void initWifi() {
Serial.print("Connecting to: "); Serial.print(WiFi.SSID());
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
Serial.print(".");
}

Serial.println("");
Serial.print("WiFi connected, IP address: "); Serial.println(WiFi.localIP());
}

Sketch code for WeMos D1 ESP8266 microcontroller for 3 Servos operated via Blynk.io

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <Servo.h>
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[40] = "BlynkAUthCode";
char ssid[15] = "MyWiFiName";
char pass[20] = "WiFiPassword";
Servo servoRAIN7;
Servo servoWIND9;
Servo servoSUN8;
BLYNK_WRITE(V7)
{
servoRAIN7.write(param.asInt());
}
BLYNK_WRITE(V9)
{
servoWIND9.write(param.asInt());
}
BLYNK_WRITE(V8)
{
servoSUN8.write(param.asInt());
}
void setup()
{
// Debug console
Serial.begin(115200);
Blynk.begin(auth, ssid, pass);servoRAIN7.attach(13); // Set servo
servoWIND9.attach(14); // Set servo
servoSUN8.attach(2); // Set servo
servoRAIN7.write(0); // reset servos
servoWIND9.write(0);
servoSUN8.write(0);
}
void loop()
{
Blynk.run();
}

Written by

Communicator.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store