Thimble Learning Platform
Back to full view

WiFi Light Switch

Introduction

This kit uses a small servo and an ESP to give you wireless remote control of your lights from anywhere in your house. There are also many other uses for this kit and we have included a few, so don't worry if you don't have a compatible switch. Be sure to check out the linked videos and the Further Reading section for more details on the design.

Objectives

  • Learn about internet packets
  • Understand PCB construction
  • Use case statements
  • Learn about complex electronic components: Voltage regulators, resistor packs, MOSFETs
  • Control a servo
  • Electrical Assembly

    Gather Materials 

    Gather the materials below and get ready to build the PCB for the Thimble WiFi Light Switch!

    Introduction
    This short video introduces the Thimble WiFi Light Switch.

    Parts

    All Parts x Qty
    WiFi Light Switch PCB x 1
    0.1μF Ceramic Capacitor x 1
    Diode x 1
    40 Pin Male Breakaway Header x 1
    2x4 Female Socket Header x 1
    1x6 Female Socket Header x 1
    10kΩ Resistor Pack x 1
    Small Tactile Button x 1
    Large Tactile Button x 1
    3.3v Regulator x 1
    ESP8266 Module x 1
    MOSFETs x 2
    10kΩ Resistors x 2
    10μF Electrolytic Capacitors x 2

    Your kit will also include two spare capacitors that aren't attached to brown paper.

    Tools you'll need

    Soldering Iron
    Solder
    Flush Cutters
    Screw Driver
    Pliers (optional)
    Solder Sucker (optional)
    Multimeter (optional)
    Electrical Assembly
    This video walks through the complete electrical assembly of the WiFi Light Switch Kit.

    Resistors 

    It may help to bend the leads of these components into a U shape before putting them in the PCB.
    Place the two 10k resistors through the bottom left of the PCB and bend the leads back to hold them in place. Resistors have no polarity; you can put them in either direction.

    Install the 10k Resistors
    Install the 10k Resistors
    Solder
    Clip the leads
    Clipped leads

    Diode 

    Place the diode through the holes marked D1; found above the reset button.
    Make sure the black line on the diode matches the line on the PCB.
    Unlike resistors, diodes limit the flow of electricity in one direction, if you put the diode in the wrong way the circuit will not get power!

    Install the diode in the correct orientation
    Solder the leads
    Clip the leads
    Clipped leads

    Reset Button 

    Place the Adruino reset button in the hole labeled SW1.
    The pins of the button are shaped to grab onto the PCB when it is fully inserted.
    Push the button through until the button sits flat.

    Install button
    Solder the leads
    No need to clip the leads once soldered

    Resistor Pack 

    A resistor pack is a group of resistors, in this case they all share the same connection to ground. This is usually done to save space. It is important to note: unlike the single resistors we put in earlier, resistor packs have a direction and will not work if soldered in backwards.
    Put the resistor pack with pin one (marked with a dot) in the square hole. The markings should be facing towards the thimble logo just above.

    Install resistor pack like this with the dot above the square hole
    Make sure the text faces the Thimble logo
    Solder the leads
    No need to clip the leads once soldered

    10μF Capacitors 

    There are two types of capacitors in this kit: Electrolytic (the can shaped black ones), and Ceramic (the little yellow ones). The 10μF Capacitors marked on the PCB are electrolytic and therefor polarized. This means that the direction does matter when installing them.
    Place the negative lead (the shorter one) of the 10μF capacitor through the round hole marked with silkscreen on the PCB. The section of white silkscreen should match the negative line on the side of the capacitor.
    Do the same thing for the other capacitor at the top of the PCB.

    First 10μF Capacitor
    Second 10μF Capacitor
    Solder the leads carefully
    Clip the leads
    Clipped leads

    0.1μF Capacitor 

    Next install the single yellow 0.1μF ceramic capacitor at the top of the board.
    Ceramic capacitors are not polarized and will work in either direction.

    Ceramic Capacitor
    Solder the leads carefully
    Clip the leads
    Clipped leads

    MOSFETs 

    The ESP8266 (WiFi module) was designed for 3.3v, and not the 5v data lines coming from the Arduino. To protect it, this circuit uses two 2N7000 N-channel MOSFETs; one for Transmit, TX and one for Receive, RX.
    MOSFETs are like a door that uses one voltage to control another. On one side of the door is 3.3v, on other side is the ESP. The 5v signal from the Arduino is what opens and closes the door.
    When the Arduino data line is off (0v) the door is closed and the ESP does not get 3.3v data. When the Arduino output goes high (5v) it opens the door for the 3.3v to go to the ESP. This same principle is also used to allow low power devices to safely control high voltages too.
    For a more in depth explanation on how MOSFETs work, check out this video by Afrotechmods.

    Install the two Mosfets in the holes marked Q1 and Q2, making sure the line up the flat side of the MOSFET to the flat line of the silkscreen.

    Line up the flat side with the flat part of the silkscreen
    Install the second MOSFET the same way
    Solder the leads
    Clip the leads
    Clipped leads

    Voltage Regulator 

    The 3.3v regulator has three pins, Input, Output, and Ground. Its job is to take 5v input from the Arduino and safely lower it to 3.3v for powering the ESP.
    You might be wondering why we can't just use the 3.3v output that the Arduino already has? The reason is while most Arduinos can supply 3.3v, they can only do so for low power devices. In this case the ESP uses more current than the Arduino's 3.3v regulator can provide.

    To install the 3.3v regulator carefully bend the leads with some pliers, or the edge of your PCB, to a 90 degree angle. Insert your voltage regulator so the large metal side faces down.
    Make sure the metal tab doesn't cover the row of holes along the bottom of your PCB.

    Bend the pins at a right angle like so
    Install with the flat metal side facing down
    Make sure the solder joints are nice and strong
    Clip the leads just above the solder joint
    Clipped leads

    Arduino Headers 

    Cut (or snap) the following segments from the 40 pin strip of male headers:
    One segment of 8 pins
    One segment of 6 pins
    Two segments of 3 pins

    The grooves between each pin will help you cut or snap the headers off cleanly.
    There will be some leftover if you accidentally cut the wrong number.

    One segment of 8 pins
    One segment of 6 pins
    Two segments of 3 pins

    If you look closely at the row of holes along the bottom of the PCB and you will notice they don't line up perfectly. This feature was added to help hold the header pins when soldering by applying slight pressure to both sides.

    Insert the 8 and 6 pin segments on the bottom row of holes and solder them in:

    Install the 8 pin header into the PCB
    Install the 6 pin header into the PCB
    Solder the headers, making sure they are straight

    Install the two 3 pin segments into the rows marked Servo 1 & 2 and solder them in:

    Install the first 3 pin segment into the Servo 1 holes
    Install the second 3 pin segment into the Servo 2 holes
    Solder the headers in place

    When you're done, your PCB should look like this.When you're done, your PCB should look like this.

    Big Button 

    Align the big button with it's mounting holes labeled SW2, just like the Arduino Reset button you installed earlier. This button features two guide pegs that fit into the PCB to align it correctly.

    Install the big button
    Solder the leads
    Soldered

    ESP Socket 

    Install the 2x4 female socket into the top left corner of the PCB labeled ESP.

    Install the ESP Socket
    Make sure all the pins are soldered to the PCB
    Soldered

    ESP Breakout 

    Optionally, you can install the ESP breakout header in the top right of the board.
    This offers connections to the ESPs two GPIO outputs as well as data and reset lines. This can be very helpful for flashing new firmware onto the ESP but is not required to use this kit.
    Your ESP comes pre-programmed with firmware version 1.5, which is required for this kit.

    Install the ESP breakout header into the top right of the board
    Solder the pins
    Soldered

    Test your PCB 

    You're done with soldering the PCB.
    Make sure you haven't forgotten any parts, and that you only have the two spare capacitors left over. Check over all your solder joints to make sure they are clean and strong.

    To test the quality of your work plug in the ESP and a servo like so:

    Wire color Function
    Brown Ground
    Red Power (5v)
    Orange Data
    Line up the pins of the ESP
    ESP installed
    Plug in the servo

    Attach the Arduino to the Light Switch PCB by lining up the analog and power headers to the pins on the bottom of your PCB:

    Attach your Arduino
    Attach your Arduino

    Give your Arduino some power from a computer and you should see the ESP power LED light up as well as hear and see the servo move to it's default position.
    If not, go back through the assembly steps and check that you haven't forgotten anything, and that all your components are installed correctly. If you're still stuck, have a look at the Troubleshooting section for some solutions to common mistakes.

    Mechanical Assembly

    Gather Materials 

    Gather the materials below and get ready to assemble the Thimble WiFi Light Switch!

    Parts

    All Parts x Qty
    Small Spacers x 10
    Large Spacers x 4
    Extension x 1
    Actuator Plate x 1
    Force Mountain x 1
    Servo Assembly x 1
    #6-32 Screw 1¼" x 2
    M2 Screw 8mm & nut x 2
    M2 Screw 16mm & nut x 1
    M3 Screw 8mm x 1
    M3 Washer x 1
    M3 Nut x 4
    M3 Nylon Screw x 1

    Tools you'll need

    Screw Driver
    Tape
    Pliers (optional)

    Servo 

    Servo Assembly
    This video walks through attaching the Servo and arm to the PCB and actuator plate.

    With the Thimble logo facing up, insert the servo head (the white gear part) through the small rectangular hole in the bottom of the PCB.
    Use the two 8mm M2 screws and matching M2 nuts to fix the servo into the PCB.
    Plug your servo into the Servo 1 header on the PCB. The PCB features connections for two servos, this allows you to control another switch or device from your kit.

    Install the servo with the Gear facing down
    Using the two 8mm M2 screw (the thin ones)
    Add the nuts to the back side of the PCB
    Tighten the screws
    Plug your servo into the Servo 1 header

    Controlling the Servo 

    If you are new to servos watch this video by Great Scott for a good explanation on how a they work.
    For now we are going to quickly use an Arduino to set our servo to a known position so we can continue the assembly.

    Reattach your Arduino for this next partReattach your Arduino for this next part

    Copy the following code into a new Arduino sketch, or download the Servo Test file.

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #include <Servo.h>
    
    Servo ThimbleServo;	// Give our Servo a name
    
    void setup() {
      ThimbleServo.attach(A0);	// Tell Arduino what pin the Servo is connected to
    }
    
    void loop() {
      ThimbleServo.write(0);	// Tell servo to go to min
      delay(3000);		// wait 3 seconds
      ThimbleServo.write(180);	// Tell servo to go to max
      delay(3000);		// wait 3 seconds
    }
    

    Servo ThimbleServo; is how we tell the program what our servo is called. Try changing the name to your own and compile the program. Make sure you change it in the three other locations.

    There are different kinds of servos some of which can rotate different amounts. The servo included in this kit has a range of 180 degrees. This means that it can only rotate half way around a full circle.
    The following line of code tells our servo what angle of that circle to rotate to: ThimbleServo.write(180); This will have the servo rotate to 180 degrees from zero, which is its maximum.

    • Try changing some of the values and seeing how the servo position changes

    Servo Horn 

    Align the actuator plate so that the screw bump is in the top right.
    Using the threaded screw (the longer one) from the servo bag, line up the last hole in the short servo horn through the horizontal slot.
    Make sure the screw goes up through the bottom of the plate so that the servo horn is on top.

    Line up the actuator plate so the screw bump is in the top right
    Add a threaded screw (the longer ones) from the servo bag
    Line up the last hole on the servo horn with the screw
    Attach the servo horn to the actuator plate]
    Make sure the servo horn is on top

    Select Your Switch Type 

    This kit includes parts to install onto the two most common US light switch types. The next few steps will be different depending on the kind of light switch you have. Videos have also been made for both assembly processes; it will help to watch the video corresponding to your switch type before proceeding.

    Click here if you have a toggle switch like this one below:

    Click here if you have a paddle switch like this one below:

    If you don't have access to either style of switch, don't worry, the WiFi Light Switch can be adapted to control other things. One example here uses the WiFi Light Switch to remotely control a power strip.
    The kit was assembled using the Paddle Style instructions, minus the extension arm, and uses only the cardboard from the box and some hot glue

    Mount the PCB on the top of the box with some cardboard spacers for height
    Attach your power strip to the box
    Use a generous amount of hot glue to keep the spacers on the screw

    Toggle Switch Mounting Screws 

    Toggle Switch Assembly
    This video explains how to assemble the kit for a Toggle Style light switch.

    Collect the two 1¼" metal screws and insert them through the two large holes in the PCB.
    When finished, set the PCB on its side leaning back onto the servo. It may help to put a piece of tape over the top of each screw to keep it from falling out during the next few steps.

    Install the bottom 1¼" screw into the PCB
    Install the top 1¼" screw into the PCB
    make sure they are threaded all the way through the PCB

    Toggle Switch Spacers 

    Stack three small spacers onto the bottom screw (the one closer to the Servo).
    Next add a large spacer and the 5mm washer followed by small spacer.
    Flip the actuator plate over so the servo horn is now between it and the PCB.
    Line up the small spacer with the large rounded slot in the actuator plate.
    Lastly add two large spacers to finish the first screw.

    Add three small spacers
    Add one large spacer and the washer, smooth side down
    Add another small spacer
    Line up the actuator plate with the servo horn facing up
    Install the actuator plate onto the screw with the spacer in the rounded slot
    Add two more large spacers
    Use tape to keep the spacers on temporarily

    The second screw is much easier than the first:
    Add six small spacers to the screw.
    Finally add a large spacer and you're all done! Before moving on to the next step you may want to add a piece of tape on the end of each screw to help hold the spacers on.

    Add six small spacers to the top screw
    add one large spacer
    Add some tape to hold the spacers on temporarily

    Paddle Switch Servo Horn 

    Paddle Switch Assembly
    This video explains how to assemble the kit for a Paddle Style light switch.

    Use the included M3 8mm long nylon screw and two nuts to create the striker.
    Screw one nut all the way down the screw so that it is tight to the head.
    Then, thread that screw combo up through the actuator plate. The thread should be sticking up on the same side as the servo horn.
    Thread the second nut down so its tightly attached to the actuator plate.

    Add one nut to the nylon screw
    Tighten the nut all the way down
    Thread the nut/screw combo through the actuator plate
    Use the second nut to attach the striker to the actuator plate
    Tighten the screw
    Make sure the head of the screw is on the opposite side of the servo horn

    Paddle Switch Force Mountain 

    Finish the actuator plate by adding the force mountain. (Cool name right? We made it up.)
    Slot a nut into the force mountain. Using an M3 8mm screw from the bottom and M3 nut to attach it through the two square holes in the top left of the actuator plate.
    Carefully tighten the screw so it isn't loose, but don't go to tight!

    Install the nut into the force mountain
    Slot the force mountain into the actuator plate and add an M3 8mm screw
    Tighten the screw, but not too much!

    Paddle Switch Mounting Screws 

    Install one 1¼" metal screw through the lower large hole in the PCB, closest to the servo.
    With the extension piece, use a M3 8mm screw and nut to attach it to the PCB on one end.
    Lay the PCB on its side leaning back onto the servo. It may help to put a piece of tape over the top of the screw to keep it from falling out during the next few steps.
    Thread the 16mm long M2 screw through the hole on the in the upper left side of the PCB and tighten the nut onto to other side.

    Install the 1¼" screw into the PCB
    Use an M3 8mm screw and nut to attach the extension to the top of the PCB
    Tighten the screw
    Thread the 16mm M2 screw through the small hole on the upper left of the PCB
    Add the nut onto the bottom of he PCB
    Tighten it all the way, but be careful not to damage the PCB

    Paddle Switch Spacers 

    Stack three small spacers onto the bottom screw (the one closer to the Servo).
    Next add a large spacer and the washer followed by small spacer.
    Line up the actuator plate with the servo horn facing up.
    Line up the small spacer with the large rounded slot and the guide peg to its slot in the actuator plate.
    Lastly, add one large spacer to finish the first screw.

    Add three small spacers
    Add one large spacer and the washer
    Add another small spacer
    Line up the actuator plate with the servo horn facing up
    Line up the guide peg into its slot and the small spacer into the rounded slot
    Add one more large spacer
    Use tape to keep the spacers in place for now

    The top screw is much easier: Thread the other 1¼" screw through the other end of the acrylic extension.
    Add five small spacers.
    Add a large spacer and you are all set! You should have left over one large spacer and one small spacer; keep this for later.

    Add the 1¼" screw
    Add five small spacers
    Add one large spacer
    Use tape to keep the spacers in place for now
    Code

    Install the WiFiESP Library 

    Set up the Arduino IDE
    This video explains how to Install the WiFi ESP Library and program your Uno board.

    Download the WiFi ESP Library.zip

    From the Arduino IDE
    Sketch > Include Library > Add .ZIP Library...
    Navigate to the WiFiEsp-Library.zip and add it.

    Add the following libraries to the top of your program:

    Download file Copy to clipboard
    1
    2
    3
    4
    #include "SoftwareSerial.h"
    #include <Servo.h>
    #include <WiFiEsp.h>
    #include "WiFiEspUdp.h"
    

    This is telling the Arduino IDE what other code your program will need access to when running.
    You can use wither <LibraryName.h> or "LibraryName.h" to declare a library in your code.

    Set Up WiFi 

    The WiFiESP library needs some information to connect your ESP to your WiFi.
    Add these three lines right below your library declarations:

    Download file Copy to clipboard
    1
    2
    3
    char ssid[] = "YourWiFiName";       // The network SSID (name) you are connecting to
    char pass[] = "YourWiFiPassword";   // The password of the network you are connecting to
    int status = WL_IDLE_STATUS;        // The WiFi radio's status
    

    Put in your WiFi name and Password with the name of your WiFi network as it appears to your phone or laptop.

    • For example if your home WiFi is called NETGEAR 2.4g and the password is ILoveThimble your code should look like this:
    Download file Copy to clipboard
    1
    2
    char ssid[] = "NETGEAR 2.4g";  // The network SSID (name) you are connecting to
    char pass[] = "ILoveThimble";  // The password of the network you're connecting to
    

    The status is used by the library to determine whether the ESP is connected to a network.
    You will not need to change it.

    Serial Communication 

    To allow the Arduino to talk to the ESP we need to tell it what pins are connected. In the case of the Thimble Light Switch kit, the ESP connects to the A2 and A3 pins.
    When looking at the Light Switch Kit schematic you'll notice that pin A2 of the Arduino connects to the RX pin of the ESP, and A3 to the TX pin of the ESP.

    • Serial communication works by connecting the TX of one device to the RX of another
    • In this case we are telling the program what the Arduino's new pins are for TX and RX with this command:
    Download file Copy to clipboard
    1
    SoftwareSerial Serial1(A3, A2); // Arduino's: RX, TX
    

    So the Ardunio A3 pin is the RX pin of the Arduino and gets connected to the TX pin of the ESP.

    Setting up the Serial Monitor 

    There is one last thing we need to do before we can get the code for connecting the ESP to the WiFi.
    Working from inside the setup loop (remember the setup loop only runs once at the start of the program) we need to start the serial communication with the ESP and to the Arduino Serial Monitor on your computer so you can see what is going on.
    Add the following lines to your Arduino code in the Setup loop:

    Download file Copy to clipboard
    1
    2
    3
    4
      Serial.begin(115200); //serial monitor output for debugging
      Serial1.begin(9600);  // Serial for the ESP to talk to the Arduino
      WiFi.init(&Serial1);  // Tell the ESPWiFi library what serial to talk to the ESP
      Serial.println("===== Thimble Remote Control Light Switch =====");
    

    The Serial.begin is what will be used for the Serial Monitor on your computer. The number you see in the parenthesis is the baud rate which is how fast the serial monitor talks to devices. Serial1.begin is for the software serial we set on the page before; this is for the ESP.

    Upload the code to your Arduino. Open the serial monitor and set the baud rate to 115200.
    You should now see the message from above printed out. If you aren't sure how to do this, watch the video at the beginning of this section.

    • It is important that the baud rate for the ESP (Serial1) is slower than the Serial monitor speed otherwise we will not be able to see the data.
      • Try changing the baud rate in the bottom right of the serial monitor to something different than 115200. Notice what happens to the text when you set it faster or slower.

    Connecting to the WiFi 

    The following code uses the WiFiESP library to communicate with your ESP.
    Copy it into your setup loop; because your ESP only needs to setup the connection to your WiFi once each time the kit is powered on.

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
      if (WiFi.status() == WL_NO_SHIELD) {    // Check for the presence of the ESP
        Serial.println("WiFi shield not present");
        while (true);                         // Don't continue, because the ESP isn't connected.
      }
    
      while ( status != WL_CONNECTED) {       // Attempt to connect to WiFi network
        Serial.print("Attempting to connect to SSID:");
        Serial.println(ssid);
        status = WiFi.begin(ssid, pass);      // Connect to WPA/WPA2 network
      }
      Serial.println("Successfully connected to WiFi:");
      printWiFiStatus();
    

    The last line printWiFiStatus(); calls a function which shows you information about your WiFi connection.

    Adding Functions 

    Paste this function from the WiFiESP library, at the very bottom of your program, after the closing brace of your loop. You will not need to change it in this tutorial.

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    // =========== Functions ===========
    
    void printWiFiStatus() { // Shows information about the WiFi connection:
      // print the SSID of the network you're attached to:
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());
    
      // print your WiFi shield's IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);
    
      // print the received signal strength:
      long rssi = WiFi.RSSI();
      Serial.print("signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
    }
    

    Once you upload your code and open the serial monitor you should see something like this (with a different SSID and IP Address):

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    6
    7
    ===== Thimble Remote Control Light Switch =====
    Attempting to connect to SSID: ThimbleHQ
    [WiFiEsp] Connected to ThimbleHQ
    Successfully connected to WiFi:
    SSID: ThimbleHQ
    IP Address: 10.0.10.154
    signal strength (RSSI):-51 dBm
    

    The SSID, IP Address and Signal strength are all being printed out by the printWiFiStatus function.

    Controlling The Servo 

    We will need a way to control our servo; for now lets use the large button on the PCB. Have a look at the schematic to see what pin it's connected to.

    If you are having trouble finding the button pin on the schematic, Head to the Troubleshooting Section

    Once you figure out the pin, add the following lines to the start of your code before the setup loop. Make sure to to fill in the buttonPin with the correct one for the Arduino.

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    Servo ThimbleServo;         // Give our Servo a name
    int buttonPin = ;           // Pin the Arduino is reading the button signal
    boolean buttonState = HIGH;	// Button pressed state
    
    int center = 85;            // Servo positions 0-180 degrees
    int up = 40;
    int down = 150;
    
    int switchCase = 0;         // Used for the buttonCase function
    int nextCase = 0;
    

    Reading the Button 

    To tell the Arduino how to read the state of the button, we need to set the pin function by adding this line in the setup loop of our program.

    Download file Copy to clipboard
    1
      pinMode(buttonPin, INPUT_PULLUP); // set button pin as an input pin with a pull-up resistor (makes sure that it is high unless connected to ground)
    

    This tells the Arduino that the buttonPin is high until the button is pushed, connecting it to ground, and making it go low.

    Now that we have all the setup for the button in place we need to tell the program when to actually take input from the button, and what to do with it.
    For that we add this assignment and an if statement to the main loop of our program:

    Download file Copy to clipboard
    1
    2
    3
    4
      buttonState = digitalRead(buttonPin);	// Read button state
      if (buttonState == LOW) {
        buttonCase();                       // Enter the buttonCase function
      }
    

    This line: buttonState = digitalRead(buttonPin); sets the boolean called buttonState to whatever the button is.
    So when the button it's pressed the boolean will be HIGH because the button pin is pulled up to 5v.

    There is one final function we need to add, and it is the most important one. This is the function that gets called whenever you press the button. This function contains the actual code the moves the servo to turn the lights on and off.

    Add this to the functions section of your code:

    Download file Copy to clipboard
    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
    void buttonCase()               // This is what controls the movement of the servo
    {
      switch (switchCase)
      {
        case 0:         //  === W A I T ===
          if (nextCase >= 2)        // If the lights were just turned off
            nextCase = 1;           // The next state will be turning them On
          else
            nextCase += 1;          // Otherwise add one to nextState to go to the next state
    
          if (buttonState == LOW)
            switchCase = nextCase;  // When button is go to the next state
          break;                    // End case 0 (Wait)
    
        case 1: // ========== L I G H T S  O N ===========
          Serial.println("Turning the lights On.");      
          ThimbleServo.attach(A0);	// Set up the servo on Arduino Pin A0 (for servo 1 header on PCB)
    
          ThimbleServo.write(40);   // Tell servo to go to UP
          delay(500);               // Wait 1/2 second for the servo to reach the position
          ThimbleServo.write(85);   // tell servo to go to CENTER
          delay(500);
    
          ThimbleServo.detach();    // turn off the servo to save power.
          switchCase = 0;           // Go back to WAIT case
          break;                    // End Case 1 (lights on)
    
        case 2: // ========== L I G H T S  O F F ==========
          Serial.println("Turning the Lights Off.");    
          ThimbleServo.attach(A0);
    
          ThimbleServo.write(150);  // Tell servo to go to DOWN
          delay(500);
          ThimbleServo.write(85);   // Tell servo to go to CENTER
          delay(500);
    
          ThimbleServo.detach();
          switchCase = 0;
          break;                    // End case 2 (Lights off)
    
      } // End switch statement
    } // End buttonCase function  
    

    This function contains a switch statement. A switch statement can only run from one case at a time.
    This switch statement has three cases: 0, 1, 2. Each case does something different.

    For example Case 1 does the following in this order:

    • Prints out that it's turning the lights on
    • Attaches the servo to pin A0 (this enables the servo)
    • Moves the servo up
    • Waits for the servo to finish moving
    • Moves back to the middle position
    • Waits for the servo to finish moving
    • Detaches the servo (this turns the servo off to save power)
    • Sets the next switch case to 0 (the wait case)
    • break; exits the current case

    You may find that the values here for the servo's up and down position don't quite work for you light switch. You will have to experiment with different values until you find the ones that work for your switch.

    Upload the code and watch your serial monitor. When you press the button you should see the servo move up and down! If not, don't worry, go back over the last few steps and double check that you have everything in your code. If you're still stuck, head to the Troubleshooting section for some tips on common mistakes.

    UDP Packets 

    To allow a computer or mobile phone to control your light switch kit you'll need to add support for your Arduino to receive UDP packets.
    Put simply a UDP packet is package of information that contains three main things:

    • Destination IP Address (In this case the IP of the ESP you saw in the serial monitor earlier)
    • Port number
    • Some data (This is the most important part!)

    For our code to start accepting UDP packets we need to add a few things. The following four lines will go up top before the setup loop:

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    WiFiEspUDP Udp;                         // Start the UDP library
    
    char packetBuffer[255];                 // Buffer to hold incoming packet
    char ReplyBuffer[] = "Message Received"; // A string to send back
    unsigned int localPort = 10109;         // Local UDP port to listen on
    

    The first line enables the UDP functions from the ESP WiFi library you installed at the beginning of this module. The packetBuffer is the place we will store the message you receive in a packet.

    When you get a UDP packet the ESP will send a response to whatever device sent the packet. You can change the Message Received to whatever you like, but keep in mind, too many characters can fill up the buffer of the other device.

    Lastly the localPort is exactly what is sounds like. If a UDP packet is sent to the IP of your ESP but a different port it will be ignored, so make sure this is the same port on both the sending device and your ESP. We've chosen port 10109 because it is unlikely to be in use by any other device in your home. You can see a list of port numbers and their uses on Wikipedia here.

    We will also need to add this to the setup loop:

    Download file Copy to clipboard
    1
    2
    3
    4
      Udp.begin(localPort);  // Start listening for incoming UDP packets
    
      Serial.print("Listening on port ");
      Serial.println(localPort);
    

    This starts the ESP listening on the local port we set above and prints out the port number for reference.

    Actions Based on UDP packets 

    Now that we have your ESP set up to receive and respond to UDP packets it's time to do something with them!

    This might look like a lot of code, but it is very simple once we break it down.
    For now, add it to your program loop just after the button reading if statement:

    Download file Copy to clipboard
    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
    int packetSize = Udp.parsePacket();       // If there's data available, read a packet
      if (packetSize) {
        Serial.print("Received packet of size ");
        Serial.println(packetSize);
        Serial.print("From ");
        IPAddress remoteIp = Udp.remoteIP();  // Tell the program what IP we just received a message from
        Serial.print(remoteIp);
        Serial.print(", port ");
        Serial.println(Udp.remotePort());
    
        int len = Udp.read(packetBuffer, 255); // Read the packet into packetBufffer
        if (len > 0) {
          packetBuffer[len] = 0;
        }
        Serial.print("Message: ");
        Serial.println(packetBuffer);          // Prints out the data we just received in the packet
    
        if (strcmp(packetBuffer, "On") == 0) { // Checks to see if received packet matches the text string: on
          nextCase = 1;
          switchCase = 1;
          buttonCase();                        // Enter the buttonCase  function
        }
        else if (strcmp(packetBuffer, "Off") == 0) { // Checks to see if received packet matches the text string: off
          nextCase = 2;
          switchCase = 2;
          buttonCase();                        // Enter the buttonCase  function
        }
    
        Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); // send a reply, to the IP address and port the last packet came from
        Udp.write(ReplyBuffer);                // Send the char 'ReplyBuffer' we set at the beginning of the program
        Udp.endPacket();
      }
    

    The first block of Serial.print statements is showing the information about the UDP packet you've received. This can be useful for debugging.

    The next block reads the message from the packet into your buffer, then prints it to the serial monitor as well.

    The next block of if and else if statements are what acts on the message you receive in the UDP packet. Right now if the UDP packet contains the word "On" the code will set the switchCase to 1 (which is the Lights ON case) and calls the buttonCase .
    When this happens the code acts the same as it did when you pressed the button, going right to the servo moving case statement.

    After that, the last three lines are what sends the ReplyBuffer message back to the device which sent you the UDP packet.

    Set Up Your phone 

    Sending UDP packets is very easy, there are many free app that can do this. We recommend UDP Sender for Android, and TCP-UDP Client for iOS devices.

    For Android:

    Once installed enter the Destination IP as the IP of your ESP from the serial monitor.
    Enter the Port from this step.
    Set the Text as either On or Off and tap Send to control your lights!

    Enter the IP of your ESP from the Serial Monior
    Set the port number
    Set the message text and tap Send

    For iOS

    Once installed, select UDP Connection.
    Enter the IP of your ESP from the serial monitor.
    Add the Port number from this step.
    Set the Message as either On or Off and tap Send to control your lights!

    Tap UDP Connection
    Enter the IP of your ESP from the Serial Monitor
    Set the port number
    Set the message text and tap Send

    Select Your Switch type 

    The next two steps will guide you through attaching the WiFi Light Switch kit to both kinds of US light switches. Follow the step that matches your switch style.

    Click here if you have a toggle switch like this one below:

    Click here if you have a paddle switch like this one below:

    Attachment To Toggle Switch 

    Attach to a Toggle Switch Assembly
    This video explains how to attach your kit to a Toggle Style light switch.

    Double check that your servo is calibrated to the middle position from the Controlling The Servo step.

    Carefully remove both the flat head screws of your light switch plate, but do not take the plate off! It may help to use some painters tape to hold it to the wall for the next few steps.
    Place the screws in a bag from your kit so they don't get lost.

    Carefully remove the screws holding your switch plate to the wall
    Carefully remove the screws holding your switch plate to the wall
    Don't lose these screws! Stash them in your Thimble kit box for safe keeping

    Screw the top screw into the hole where your switch plate screw was just removed. For now a couple of turns is enough, you will tighten it later.
    Line up the light switch toggle with the large rectangular hole in the middle of your actuator plate.
    Screw the bottom long screw into the other hole in your switch plate.
    Attach the servo horn to your servo so it is as roughly straight across, you may need to adjust this later.
    You should now be able to tighten both screws until the PCB no longer wobbles.

    Line up the top screw
    A few turns to the top screw of your kit should hold it to the wall for now
    Line up the toggle switch with the rectangular hole on the actuator plate
    Turn the bottom screw of your kit to attach it to the wall
    Tighten the top screw until it is firm but not too tight
    Attach the servo horn to the servo and tighten the bottom screw
    Attach the servo arm facing to the right

    Test Your Toggle Switch 

    Your kit should now be mounted to the wall; you should be able to move the actuator plate slowly by hand with very little resistance except for that from the servo.
    If that's not the case, you may have attached the bottom mounting screw too tightly, or have forgotten the washer. If you're still stuck, have a look at the Troubleshooting section for some solutions to common mistakes.

    Line up your Arduino
    Give it power and test it out

    Attachment To Paddle Switch 

    Attach to a Paddle Switch
    This video explains how to attach your kit to a Paddle Style light switch.

    Carefully remove both the flat head screws of your light switch plate, but do not take the plate off! It may help to use some painters tape to hold it to the wall for the next few steps.
    Place the screws in a bag from your kit so they don't get lost.

    Carefully remove the screws holding your switch plate to the wall
    Carefully remove the screws holding your switch plate to the wall
    Don't lose these screws! Stash them in your Thimble kit box for safe keeping

    Double check that your servo is calibrated to the middle position from the Controlling The Servo step.
    If it is, go ahead and click the servo horn into the servo so it is facing to the right.
    Screw the top screw into the hole where your light switch screw was just removed. For now a couple of turns is enough, you will tighten it later.
    Screw the bottom long screw into the other hole in your light switch.
    You should now be able to tighten both screws until the PCB no longer wobbles.

    Attach the servo arm facing to the right
    Line up the top screw to your light switch plate
    A few turns to the top screw of your kit should hold it to the wall for now
    Line up the bottom screw
    Turn the bottom screw of your kit to attach it to the wall
    Tighten both screws until they are firm but not too tight

    Test Your Paddle Switch 

    You're done with the assembly! Your kit should now be mounted to the wall; you should be able to move the actuator plate slowly by hand with very little resistance except for that from the servo. If that's not the case, you may have attached the mounting screws too tightly, or have forgotten the washer. If you're still stuck, have a look at the Troubleshooting section for some solutions to common mistakes.

    Line up your Arduino
    Give it power
    You can use a phone charger to power your kit if it's close to an outlet
    Troubleshooting

    Electrical Troubleshooting 

    If your ESP lights up but the servo does not move:

    • Check that the brown wire of the servo is lined up to plug into the pin labeled GND and that the orange wire is on the left.
    • Looking at the back of the PCB make sure there is no bridged connection between any of the pins, especially on your servo headers.

    If the servo moves but the ESP does not light up

    • Make sure the ESP is plugged in the correct way and hanging over the top of the PCB away from the cut out hole in the middle.
    • On the back of the PCB look at the solder connections of the socket and mare sure they are secure
    • Check the polarity of the 10uF capacitor (Tall cylinder one) just to the right of the ESP socket. the negative marking should be facing away from the ESP socket (towards the little yellow ceramic capacitor next to it).
    • Look at the connections of the pins on the voltage regulator, make sure it is facing up with the tab side touching the PCB.

    If neither the ESP or Servo move/light up:

    • Check the soldering of the male headers on the bottom of your PCB, make sure they are all secure and none of them are connected to each other.
    • Make sure when you plug your Arduino into the Light Switch PCB that you line up the gap between the two headers on the Arduino with the space between the two pin rows on the PCB.
    • It is possible to insert an Arduino incorrectly by shifting it to the left or right by as little as one pin. This can cause damage to your Arduino and the Light Switch PCB so be careful to line it up!

    Mechanical Troubleshooting 

    Troubleshooting
    This video details a few things you can try if your Light Switch Kit isn't correctly turning your lights on and off.

    If the actuator plate is very hard to move:

    • Check that you have installed the M3 washer from the Paddle Switch Spacers or Toggle Switch Spacers step (depending on which light switch you have).
    • Make sure the two #6-32 1¼" screws that go into the wall aren't too tight. They should be firm but you don't need to over tighten them.

    If the servo gets stuck while moving:

    • Make note of how tight the screw is for the servo arm as seen in the following step (depending on which light switch you have) Servo Horn step.
    • Depending on the age of light switch in your house, you may need to add or remove a spacer from each screw of your assembly to achieve the correct height.

    If the serial monitor prints but the servo doesn't move:

    • Make sure the servo is connected to the Servo 1 header and that the data pin for it is correct in your code

    Code Troubleshooting 

    If nothing happens when you press the button:

    • Make sure that your code is using pin A4 for the button reading
    • Check that you have the following code in your run loop.
    Download file Copy to clipboard
    1
    2
    3
    4
    	  buttonState = digitalRead(buttonPin);	// Read button state
    	  if (buttonState == LOW) {
    	    buttonCase();			// Enter the buttonCase function
            }
    

    If you do not get a response from the ESP;

    • Make sure the IP and Port you are sending the packet to are exactly what the ESP is listening for.
    • Make sure your phone or device is connected to the same WiFi network as your ESP.

    If you get a response from the ESP but nothing happens:

    • Make sure you have the correct servo position values in your buttonCase function.

    If you are really stuck and can't get your code to work

    Further Reading

    Note 

    This section goes into detail about the design of your kit and provides some more information on how to flash new firmware onto your ESP. This isn't part of the assembly instructions of your kit, but may interesting to read for those of you who want to know more about this kit.

    Schematic and PCB Design 

    The kit is designed to be noninvasively mounted over top of an existing household light switch and can be installed with only a screw driver. An Arduino will plug into the PCB along the bottom using only the Analog and power header row. This allows for a very small PCB that also functions as the backbone of the mechanical components of the switch.

    Thimble WiFi Light Switch SchematicThimble WiFi Light Switch Schematic

    Serial Data

    The circuit is fairly simple and uses only five of the Arduino's Analog data pins. Two servos can be are driven from pins A1 and A2 respectively, and the RX/TX lines for the ESP are on pins A2/A3.

    • An Adruino's serial pins are accessible via digital pins 0 and 1, but using the SoftwareSerial library any pin on an Arduino can be used as an emulated serial pin. This is what allows the Arduino to communicate with the ESP using Serial data, but on pins A2 and A3.

    Voltage Regulator

    The LD1117 is a 3.3v regulator which can supply current up to 800mA. The three capacitors around it are what is recommended by the datasheet and serve to smooth the power input and output to a steady 3.3v. This is referred to as VCC in the schematic whereas the source voltage from the Arduino is labeled as +5v.

    • The reason that the Arduino's 3.3v supply can't be used is because when transmitting the ESP will need up to 170mA of current; most Arduinos have 3.3v regulators that can only supply a maximum of 100mA.
    • The larger package version (TO-200) of the LD1117 was used, even though it is somewhat overrated for this application, to avoid confusion between it and the two MOSFETS used for level shifting. Since nearly all TO-92 packages look identical, we figured that having all three parts look identical would only lead to mistakes when assembling the PCB.

    Level Shifting

    The ESP is a 3.3v device and therefore requires 3.3v serial data; the Arduino Uno can only send serial data at 5v. Connecting the two directly would eventually damage the ESP, so two 2N7000 MOSFETS were used. They were chosen because of their fast switching rate and ability to provide 400mA of current. They are the same model as the surface mount (SOT-23) level shifting MOSFETS found on the WiFi Robot kit.

    • The 10kΩ pull up resistors (R3, R5) on the Arduino side pull up the line to 5v and limit the current when the Arduino takes the pin low.
    • The resistor array (all 10KΩ) was used to pull up the ESP side of the circuit to 3.3v and limit the current when the ESP took the line low

    Resistor Pack

    The 10kΩ resistor pack was used manly to show people one example of how combined components can simplify a circuit. In this case one connection to VCC is made and then the three pull up resistors only need one external connection to the circuit.

    ESP Pinout

    The Light Switch kit contains holes for soldering in a 6 pin female header to breakout the ESP. This is especially useful for flashing the ESP with new firmware. It also has GPIO 0 and 2 available for use if desired.

    Pinout of the ESP8266Pinout of the ESP8266

    Reset

    The reset button functions as a reset switch for the Arduino and ESP. the 1n138 diode was chosen as a general purpose diode which can protect the ESP reset line from current spikes when pushing the button.

    Large Push Button

    The 12mm push button is used as a fallback toggle button for the light switch state. It can be pushed at any time to toggle the lights if for some reason the ESP stops working. It can also be repurposed to trigger more complex states if the user desires.

    Servos

    The PCB features connections for two servos, this is in the case where someone wishes to use their kit to control a double switch plate. Standard 9g servos were used and mount into the PCB because they are fairly inexpensive but are still powerful enough to toggle switches.

    Flash New ESP firmware 

    You don't have to do this to use your ESP, it comes flashed with the correct firmware to use with your Light Switch Kit.
    This file includes the necessary programs, binaries, and instructions in order to flash new firmware to the ESP 8266.

    Wire Connections

    The ESP is "not" 5v tolerant, but many people have been treating it as though it is and have been fine. This is my warning that using a 5v programmer can damage it so be careful!

    • Before connecting your FTDI chip to your computer, wire it to the ESP like so:
      • FDTI -> ESP
      • 3.3v -> VCC
      • 3.3v -> CH_PD
      • GND -> GND
      • GND -> GPIO0 (through a resistor to limit current)
      • TX -> RX
      • RX -> TX
      • When the ESP is powered on while GPIO0 is tied to ground it will start in flash mode and allow you to program it.

    Program Settings

    • Open ESPFlashDownloadTool_v3.3.4.exe from the /FLASH_DOWNLOAD_TOOLS_V3.3.4_Win/ folder
    • Select the COM port of your FTDI chip; in this example COM5
    • Set the baud rate to 115200 (this is only the baud rate of the programming, and can be different than your ESP's configured rate if you've previously set it lower)
    • Make sure the SpiAutoSet this will allow the programmer to read your ESP for the correct flash, clock, and device id and set the programming settings accordingly.
    • Leave all the Download Path Config boxes unchecked and empty.
    • Click start in the bottom right and you should see the DETECTED INFO box populate with your ESP's information as well as the MAC address in the bottom window.
      • This information is also seen in the terminal window that opens with the program.

    Selecting The binary

    • For an ESP matching the settings shown in the settings image, we have already created a combined Binary .bin to be used.
    • Click the ... to the right of the first box at the top of the program and select the CombinedFiles.bin file from the same folder this readme is in.
    • Enter the offset of 0x00000 (that is 0x with five zeros after it)
    • Click the checkbox on the left and you should see both boxes on that line turn green. If so that means you are all set.
      • If not, then you may have not properly selected the .bin file or it has been moved to a different location since you selected it.
    • With you ESP and FTDI chip still powered on and connected from the steps above, click the START button and you should see the progress shown in the terminal window.
    • Once the progress reaches 100% your ESP is now programmed.
    • The last thing to do is test and set the baud rate of your ESP to work with an Arduino. To verify you can use the ESP_AT_Test.ino to test the AT commands with your ESP.
      • Run the sketch and with your serial monitor set to 115200 baud send this AT command:
        AT+UART_DEF=9600,8,1,0,0

    Selecting Custom Binaries or Updating to a Newer Version

    • Included in the \bin folder is a set of binaries for various specifications of ESP8266s. This can be downloaded from the Espressif site by searching ESP8266 Firmware SDK online.
    • To program the ESP with a different or newer set of firmware than what is pre-built here make sure you use the following files and offsets:
    File Offset
    \bin\boot_v.16.bin 0x00000
    \bin\at\512+512\user1.1024.new.2.bin 0x01000
    \bin\esp_init_data_default.bin 0x3fc000
    \bin\blank.bin 0x7e000
    \bin\blank.bin 0x3fe000

    (the 512+512 or 1024+1024 folders correspond to your ESP's Flash sizes)

    • With these files selected as in the settings.png image, clicking the START button will program your ESP.
      • You can also use the CombineBin button to generate a single bin file using the files and offsets above. That is how we made the CombinedFiles.bin from earlier.

    Troubleshooting

    • Make sure your TX/RX lines are correct, some FTDI programmers label them as the device sees is and therefore should be connected TX->TX and RX->RX
    • If the programmer is not recognizing your ESP make sure that GPIO0 is connected to ground BEFORE you power it on.
      • Most times (if it's wired correctly) unplugging the whole setup from your computer's USB port and plugging it back in is enough to reset the ESP back into Flashing mode.
    • The default baud rate for an ESP is 115200, which can cause issues for Arduino ESP libraries:
      • Run this AT command to set your ESP's baud rate to 9600: AT+UART_DEF=9600,8,1,0,0