Introduction: Control a Sonoff Smart Plug Using NETPIE

Hello Maker m(- -)m

For a hobby project, before you do make sure you know about electric power and electronic because this project we control high voltage (220V in my country) for turn on and turn off electric device. So today i will present how to control a Smart Plug using NETPIE, It's easy to make a IoT solution to your smart home. Let's do it !!!

  • Sonoff is a smart plug that allows you to control via appliances on app. Sonoff use ESP8266 to connect wifi so we can upload code to this board.
  • NETPIE is a clound platform for IoT solution development. It's let's you to connect IoT device easily.

Things used in this project !

  1. Sonoff WiFi Smart Switch x 1
  2. FT232RL USB to Serial x 1
  3. USB Cable x 1
  4. Wire Female to Female x 1

Library & Service

  1. ESP8266 microgear library
  2. NETPIE.io account
  3. Arduino IDE

Step 1: Connect Sonoff to Your Computer

  1. Connect FTDI to sonoff board.
  2. If you connect ftdi to your computer, you will see the com port (for windows).
  3. connect wire power to sonoff and output to connect to electric device (lamp holder).
  4. if you finish step 3 do not turn on power to sonoff, we will upload example code first.

Step 2: Edit and Upload Example Code

1. Download the example code here.

2. edit WiFi password and netpie authentication

const char* ssid     = "your wifi name";	<---- your wifi ssid
const char* password = "yout wifi password"; <---- your wifi password
#define APPID "NETPIE APP ID" <---- netpie app id (you must register and create netpie account first) #define KEY "NETPIE KEY" <---- netpie key #define SECRET "NETPIE SECRET" <---- netpie secret #define ALIAS "Device Name" <---- your device name

3. edit when receive message

/* If a new message arrives, do this */
void onMsghandler(char *topic, uint8_t* msg, unsigned int msglen) { char strMsg[msglen]; for (int i = 0; i < msglen; i++) { strMsg[i] = (char)msg[i]; }String msgStr = String(strMsg).substring(0, msglen); String strTopic = (char *)topic; Serial.print("Incoming Topic --> "); Serial.println(strTopic); Serial.print("Incoming message --> "); Serial.println(msgStr); Serial.println(""); Serial.println(""); if (msgStr == "ON") { digitalWrite(SONOFF_RELAY, HIGH); digitalWrite(SONOFF_LED, LOW); relayState = true; } if (msgStr == "OFF") { digitalWrite(SONOFF_RELAY, LOW); digitalWrite(SONOFF_LED, HIGH); relayState = false; } }

4. edit publish data to netpie.io

microgear.publish("/gearname/Sonoff001/status", "Connectecd");
microgear.publish("/gearname/Sonoff001/relayState", String(relayState));

Step 3: Create Netpie Freeboard

Step 4: Upload to Sonoff and Happy Coding M(^-^)m

Arduino Contest 2019

Participated in the
Arduino Contest 2019