Make an IoT Switch to Control Any Device on WiFi

If you have a bunch of hardwired devices in your home, then you'll want to create a smart switch to control them. Here's how to get started!

Disclosure: Some of the links in this post are affiliate links. This means that, at zero cost to you, Learn Robotics will earn an affiliate commission if you click through the link and finalize a purchase. Learn Robotics is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a way for websites to earn advertising revenues by advertising and linking to

This Article is Sponsored by our Robotics Specialist Certification for Beginners.

πŸš€ Unleash Opportunities: Embrace the world of robotics with our beginner-friendly certification…

🧠 No Experience Needed: Perfect for beginners; we’ll guide you every step of the way…

πŸ§‘β€πŸ« Expert Instruction: Learn from industry engineers and professionals…

πŸ€– Secure Your Future: Robotics skills are in high demand with jobs over $100,000…

πŸ‘‰ Get Certified in Robotics

Table of Contents

Devices and homes are getting smarter these days. However, if you’re not the lucky owner of a brand-new house, you might be looking for ways to add home automation to your home without a big expense.

In this article, I’m going to share how you can make an IoT Switch that controls any device or appliance on WiFi. As a result, you’ll be able to control just about any device that’s hardwired into any light switch.

Additionally, I’ll show you how to add voice control to the Smart IoT Switch so that you can integrate this device with existing voice assistants and home automation systems.

Materials You’ll Need

Before you begin this project, you’ll need to buy and 3D print a few parts.

Here’s the list of materials you’ll need to create a Smart IoT Switch:

[amazon box=”B076F52NQD,B07MLR1498,B00FG7BN62,B07TYRGWSQ” template=”list”]

If you don’t have a 3D printer, you can order the Smart Switch parts on our website, and we’ll print and ship them to you. You can also check out the list of 3D printers we recommend.

I recommend buying a 3D printer and learning how to manufacture parts if you plan on doing a lot of projects like this.

Download the 3D Printer Files

Download and print the Smart Switch Files from Thingiverse. I chose the Wemos D1 Mini Light switch with a Servo; however, there are many designs you can choose from.

Just make sure that the design fits a standard light switch, the Wemos D1 Mini, and a Micro 9g Servo.

After you have the files, print them out. I used Gizmo Dorks White PLA and printed at Draft Quality (Layer Height = 0.20mm) and about 20% Infill. The parts took me about 2 hours to print.

If you’re in the US, we can print these parts for you. Just submit your order, here.

Part 1. Assemble the Smart Switch

Now that you have the materials, it’s time to start the assembly process.

Step 1. Wiring Diagram

Before assembling the components, it’s a good idea to solder male header pins to the Wemos. I use a breadboard to hold the headers in place while I’m soldering.

Then, create a small wire harness to connect the servo motor to the Wemos. It’s a good idea to position the wires through the 3D printed case before soldering both ends of the harness.

Here’s a Wiring Diagram:

Control any light switch with a servo and Arduino Smart Switch

Be sure the servo has a secure connection with the Wemos D1 Mini. Then move on Step 3 to finish the assembly.

Step 2. Attach Servo and Wemos D1 Mini

Once you have the 3D printed parts, mount the 9g Servo motor to the top of the mounting plate. Then, attach the servo horn. I used hot glue and the set screw included with the servo kit.

Next, press-fit the Wemos D1 Mini inside the controller compartment. The ESP8266 chip is facing up and the USB port is facing toward the right side.

Neatly tuck the wires aside. You can use a small zip tie to keep them together. Then, install the top plate cover. I used a bit of hot glue to keep the cover fully secure.

Smart Switch using Arduino and IoT

Now you should have a fully assembled IoT Switch that’s ready for programming!

Part 2. Programming the IoT Switch

There are four steps to writing the code for our smart IoT switch.

You can go through these steps or use our Starter Code as a FAST starting point.

Download Now!

Step 4. Calibrate Servo Positions

The first part includes calibrating the servo positions. This is important because we need to know which positions will turn the light switch on and off.

We also need to find a “home” position that will keep the servo horn in a neutral (center) position. That way if we want to move the switch manually, the horn won’t be blocking the switch.

You can use the test calibration code to figure out these positions.

Download the Smart Switch Position code, below.

Here’s your download! Smart Switch Position code (.ino)

Mount the IoT Switch to an outlet using the two existing screws on your light switch plate.

After the switch is mounted, plug the USB cord into the Wemos and your computer and give it a few seconds to initialize.

Upload the code to your Wemos. Then, open a Serial Monitor and type in an angle from 0-180. Figure out the position that moves the switch up, down, and center. Write these values down. We’ll use them in the next section.

Note: Servos are always active, which means, they’ll continuously receive a signal from the Wemos. Don’t try to manually move the servo horn or you risk sending feedback to the controller and frying it out.

Step 5. Create a method to control servo position

Use the readings from Step 4 to create a servo control method. I created three global variables (up, down, and center) to store the positions from the previous step. The setPos() method should look something like this:

 * Control ON, OFF, NEUTRAL pos on servo for smart switch
void setPos(int pos){
  if(pos == 1){
    smartSwitch.write(up); //switch is ON and up
  else if(pos == 2){
    smartSwitch.write(down); //switch is OFF and down
    smartSwitch.write(center); //servo horn is NEUTRAL
  delay(50); //allow servo to move to pos

Once you have this method written, it’s time to receive and parse data from a Webhook service. For this tutorial, we’ll use, but you can also use IFTTT or service of your choice.

The Webhook service will store information from Siri or a Voice Assistant to control the state of the smart switch.

Note: If you use, know that your device will be “public” unless you buy a lock.

This means that technically anyone could set the status of your smartSwitch by setting the State variable to “on” or “off.”

For this tutorial, I’m not going to cover best practices for IoT security; however, if you’re concerned about this, you can use IFTTT and get a private webhook to use for this project.

Step 6. Receive Data from Webhook (

To set the smart switch, we will use the ArduinoJSON library and to parse the data. Then, based on the status of our State variable, we’ll set the position of the Servo.

I created a getState() method to figure out this value. The first part is to create a client to connect to and get the latest “dweet,” or JSON file for the smartSwitch thing.

Code Block 1

 * Pull data from dweet to set position
void getState(){
  WiFiClient client;

    if (!client.connect(host, 80)) {
      Serial.println(F("Connection failed"));

    client.println("GET /get/latest/dweet/for/smartSwitch HTTP/1.0");
    client.println("Connection: closed");
    if (client.println() == 0) {
      Serial.println("Failed to send request");
      // Skip HTTP headers
    char endOfHeaders[] = "\r\n\r\n";
    if (!client.find(endOfHeaders)) {
      Serial.println("Invalid response");

    //... continued in code block 2 ...

Once we have that JSON file, we can use the ArduinoJSON library to parse it. If you never worked with the ArduinoJSON library, it’s an easier way to access the key-value pairs using Arduino.

Use the ArduinoJSON v6 assistant tool to set up the parsing program:

Code Block 2

// ...continued from code block 1... 
// Allocate the JSON document 
// Use to compute the capacity. 
const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(4) + 120; 
DynamicJsonDocument doc(capacity); // Parse JSON object DeserializationError 
error = deserializeJson(doc, client); 
if (error) { 
     Serial.print(F("deserializeJson() failed: ")); 
     Serial.println(error.c_str()); return; 
// Extract values 
JsonObject with_0 = doc["with"][0]; 
const char* with_0_thing = with_0["thing"]; // "smartSwitch" 
const char* with_0_created = with_0["created"]; // "2020-04-10T17:45:07.198Z" 
String switchState = with_0["content"]["State"]; //State value = "on" or "off" 
//...continued in code block 3...

I changed the name of the State key to “switchState,” just so that it’s easier to read. Then, I converted the string to lowercase so that I could run it through a set of conditional statements.

Code Block 3

//...continued from code block 2...	

    Serial.print("Current State = ");

    if(switchState != currState){
      if (switchState == "on"){
        Serial.println("smartSwitch ON"); //go to top position
        currState = "on";
      if (switchState == "off"){ //go to bottom position
        Serial.println("smartSwitch OFF");
        currState = "off";
    //goto NEUTRAL pos
    Serial.println("Set servo to NEUTRAL");

The conditional statements check to see the state value from Dweet and then moves the servo to the correct position. After the servo moves to the position, it’s commanded back to the neutral home position.

This code only runs if the new position from the Dweet website is different than the current position we’re at. There’s no point in moving the servo to the same position if we’re already there.

Note: You DO NOT want to “stall” the servo in any position. This could catch your switch in an “in-between” state, which can cause a short and/or pop breakers.

Make the moves as fast as you can. You’ll have to run some tests. But I’ve found that keeping the moves quick eliminates the risk of the servo horn getting “stuck” on the switch and causing problems.

Once you have the data from the JSON file, you can call the getState() in loop() and check every 2 seconds for a new reading.

You’ll have to play around by testing your code and tuning it for your particular scenario. However, this should give you a good starting point for setting up a versatile smart switch using Arduino.

Step 7. Grab the Full IoT Example Code

While it’s always more beneficial to try to learn the coding process yourself, you can unlock a copy of the full sample code below!

Download Now!

This code has been tested on our Smart Switch device; however, it comes without support, without warranty, and you assume all liability by using it.

With that said, it is a good starting point if you’re new to IoT and need a little extra help in the right direction.

Setup Voice Control using Siri

After you set up the code to work with a webhook service, it’s time to use a voice assistant to set the state values at that service.

You can use Alexa, Google Assistant, or Siri to add voice activation to your project. for this project, I will show you how to set up Siri using the Shortcuts app.

  1. First, open up Shortcuts on your iPhone. Then add a URL block with the following URL: Replace “smartSwitch” with your thing name.
  2. Next, add a Scripting block to Ask “Do you want the Switch on or off?” The Input Type is Text.
  3. Then, use a Network Block to Get contents of Name.
    • The method should be POST.
    • The Request Body is a JSON with the Key as “State” and the Text as Provided Input.
  4. Finally, add a Documents block to Speak “Setting Switch” Provided Input.

Name the Shortcut as “Set my SmartSwitch” and add an icon color and glyph as you like. Then hit Done. Now, you’re ready to test the voice control.

Make sure the Wemos is OFF during this test. Open up a browser window and navigate to Replace “smartSwitch” with the name of your Dweet thing.

Then, use your iPhone to give Siri the voice command: “Hey Siri, set my Smart Switch.” Siri will ask if you want the Switch On or Off. Test out the device in both positions by saying On or Off.

Check the page to see the State change “On” and “Off” respectively. If that works as expected, you’re ready to test the whole system in Part 3.

Part 3. Test & Install and Use the IoT Switch

Load the final code onto your Wemos D1 mini, and power up the switch either using an AC adapter and a nearby wall outlet or using a shield and a battery pack. Then use Siri to command your switch.

If all goes well, the switch will turn on and off as desired. You may have to do some tweaking on the Servo positions and delays.

The cool thing about this design is that you don’t have to use the smart switch to control the device. Because the servo horn always moves to neutral, you can always move the switch manually, as desired.

[amazon box=”B07CXNQ3ZR,B07PGTPGQ9,B076F52NQD” template=”list”]

Improvements and Recommendations

Lastly, I recommend adjusting the polling cycle. It’s not optimal to check the web service every 2 seconds.
A major improvement is to only adjust states when the new state is different than the current state.

If you get this feature working, we’d love to see it! Post your methodology in the comments below.

Once you have your Smart Switch working, you’ll be able to control any appliance or fixture that’s wired to a wall switch. You could make a bunch of them and install them around the house.

And, as always, if you’d like Expert Mentoring and guidance to breaking into the Robotics Industry with our “Beginner to Robotics Pro” Mentoring program, you can apply here.

Rated 4.9/5 by 12k+ Professionals

Experienced Engineer (Mechanical, Electrical, Computer, Software)

If I offered to help you upgrade your engineering career to robotics, earning $130k-$400k in the next 90 days, would you take me up on that offer?

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Learn Robotics Online
β€” Get 2 months free!

Exclusive Limited Offer for Serious Beginners Ready to take their Hobby to Engineering Internships, $100k+ Careers, and Beyond!

Enroll now, and earn your first robotics certificate in the next 7 days.

πŸ‘‡ Click below to claim this deal.