Site icon DIY Usthad

Tuya IoT with ESP8266 & Arduino

TUYA WITH ESP8266

In this project, we are going to make an IoT-connected device using the tuya IoT platform and ESP8266 module.

What is Tuya IoT

Tuya is a leading global IoT Cloud Platform that connects the intelligent needs of brands, OEMs, developers, and retail chains. The platform provides developers with a one-stop IoT PaaS-level solution that contains hardware development tools, global cloud services, and smart business platform development, Tuya offering comprehensive ecosystem empowerment from technology to marketing channels to build the world’s leading IoT Cloud Platform.

Read more

Hardware required

ComponentsAmazonAliExpressBanggood
Arduino
ESP8266
Jumper Wire
Bread Board
Affiliate links

Softwares required

SoftwaresDownload
Arduino IDE
Tuya firmware burner
Tuya Smart app (Android)
Tuya Smart app (IOS)

Accounts needed

WebsiteSignup Link
Tuya Smart PMShttps://pms.tuya.com/en/reg
Tuya IoThttps://auth.tuya.com/register

Let’s build it!

Step 1: Create a product and get the PID

https://diyusthad.com/wp-content/uploads/2021/10/Create-Product-Final.mp4

Step 2: Getting and Activating token in smart PMS

https://diyusthad.com/wp-content/uploads/2021/10/PMS-token-activation.mp4

Step 3: Burning authorizations for ESP8266

  1. Download and install the Tuya firmware burner from here.
  2. Then login with using your PMS account detail and then click Online Login. You can choose Automatic Login and Remember The Password if needed.
  3. Then from the menu File -> Setup under Basic Settings you must set up Burning Baud to 921600 and click Ok.
  4. Now click Enter Token and select Token from the Popup window.
  5. Paste your Token ID to the provided field, select Firmware Download check box and from the Select work station dropdown list select Burning Authorization.
  6. Click OK.
  7. Now connect the ESP8266 board to your computer and choose the right com port.
  8. Now click RUN. The burning process will take few seconds, wait for it to finish and a “Success” message will be displayed.
https://diyusthad.com/wp-content/uploads/2021/10/Burning-Auth.mp4

Circuit

Follow the below circuit diagram to connect your ESP8266 with Arduino.

Note: Here I’m using NodeMUC but any other ESP8266 development boards will work

ESP8266ArduinoMomentary Push Button
TXRX
RXTX
GNDGNDterminal 1
Digital Pin 7terminal 2
VIN5v

Arduino Programing

For making things easier for beginners in this tutorial we are going to use an example code provided by the TUYA_WIFI_MCU_SDK library for Arduino.

Sign up and join the Tuya Developer Arduino Beta Test

Installing the TUYA_WIFI_MCU_SDK library

  1. Open your Arduino IDE.
  2. From menus go to Sketch -> Include library -> Manage Libraries.
  3. When the dialog box apears search for TUYA_WIFI_MCU_SDK & click install.
https://diyusthad.com/wp-content/uploads/2021/10/Installing-tuya-iot-lib.mp4

We need to change the PID given in the example code to the PID of our device which we created from the tuya IoT platform. Find the below line in the code and change the PID & also we need to change the MCU version.

Note: Check your MCU version in the tuya firmware burning app.

unsigned char pid[] = {"ma67l9sgmdyg3d2k"};
unsigned char mcu_ver[] = {"1.0.0"};

Note: While uploading the code remove the RX connection from Arduino.

After making the changes upload the code to your Arduino, don’t forget to choose the right board and port. If you are using Arduino Nano also choose the right bootloader version otherwise the uploading process will fail.

Code

/*
 * @FileName: start.ino
 * @Author: Tuya
 * @Email: 
 * @LastEditors: Tuya
 * @Date: 2021-04-10 11:24:27
 * @LastEditTime: 2021-04-28 19:48:31
 * @Copyright: HANGZHOU TUYA INFORMATION TECHNOLOGY CO.,LTD
 * @Company: http://www.tuya.com
 * @Description: This demo is based on the Arduino UNO, and the LEDs on the UNO board are controlled by the Tuya Smart App. 
 *               Enter network connection mode when Pin7 to GND.
 * @Github:https://github.com/tuya/tuya-wifi-mcu-sdk-arduino-library
 */

#include <TuyaWifi.h>
#include <SoftwareSerial.h>

TuyaWifi my_device;


/* Current LED status */
unsigned char led_state = 0;
/* Connect network button pin */
int key_pin = 7;

/* Data point define */
#define DPID_SWITCH 20

/* Stores all DPs and their types. PS: array[][0]:dpid, array[][1]:dp type. 
 *                                     dp type(TuyaDefs.h) : DP_TYPE_RAW, DP_TYPE_BOOL, DP_TYPE_VALUE, DP_TYPE_STRING, DP_TYPE_ENUM, DP_TYPE_BITMAP
*/
unsigned char dp_array[][2] =
{
  {DPID_SWITCH, DP_TYPE_BOOL},
};

unsigned char pid[] = {"ma67l9sgmdyg3d2k"};
unsigned char mcu_ver[] = {"1.0.0"};

/* last time */
unsigned long last_time = 0;

void setup() 
{
  // Serial.begin(9600);
  Serial.begin(9600);

  //Initialize led port, turn off led.
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  //Initialize networking keys.
  pinMode(key_pin, INPUT_PULLUP);

  //Enter the PID and MCU software version
  my_device.init(pid, mcu_ver);
  //incoming all DPs and their types array, DP numbers
  my_device.set_dp_cmd_total(dp_array, 1);
  //register DP download processing callback function
  my_device.dp_process_func_register(dp_process);
  //register upload all DP callback function
  my_device.dp_update_all_func_register(dp_update_all);

  last_time = millis();
}

void loop() 
{
  my_device.uart_service();

  //Enter the connection network mode when Pin7 is pressed.
  if (digitalRead(key_pin) == LOW) {
    delay(80);
    if (digitalRead(key_pin) == LOW) {
      my_device.mcu_set_wifi_mode(SMART_CONFIG);
    }
  }
  /* LED blinks when network is being connected */
  if ((my_device.mcu_get_wifi_work_state() != WIFI_LOW_POWER) && (my_device.mcu_get_wifi_work_state() != WIFI_CONN_CLOUD) && (my_device.mcu_get_wifi_work_state() != WIFI_SATE_UNKNOW)) {
    if (millis()- last_time >= 500) {
      last_time = millis();

      if (led_state == LOW) {
        led_state = HIGH;
      } else {
        led_state = LOW;
      }
      digitalWrite(LED_BUILTIN, led_state);
    }
  }

  delay(10);
}

/**
 * @description: DP download callback function.
 * @param {unsigned char} dpid
 * @param {const unsigned char} value
 * @param {unsigned short} length
 * @return {unsigned char}
 */
unsigned char dp_process(unsigned char dpid,const unsigned char value[], unsigned short length)
{
  switch(dpid) {
    case DPID_SWITCH:
      led_state = my_device.mcu_get_dp_download_data(dpid, value, length); /* Get the value of the down DP command */
      if (led_state) {
        //Turn on
        digitalWrite(LED_BUILTIN, HIGH);
      } else {
        //Turn off
        digitalWrite(LED_BUILTIN, LOW);
      }
      //Status changes should be reported.
      my_device.mcu_dp_update(dpid, value, length);
    break;

    default:break;
  }
  return SUCCESS;
}

/**
 * @description: Upload all DP status of the current device.
 * @param {*}
 * @return {*}
 */
void dp_update_all(void)
{
  my_device.mcu_dp_update(DPID_SWITCH, led_state, 1);
}

Adding device into tuya smart app

After uploading the code connect back the RX connection of Arduino and turn on the power. Now press and hold the push button for 3-4 seconds. After releasing the inbuilt LED on the Arduino will start to blink.

  1. Now open the Tuya Smart App in your phone, For testing you can use the app as guest user (click on Try now).
  2. Now click on “Add Device“.
  3. There will be bunch of devices listed as categories, for us we are choosing “Light Source(WiFi)” from “Lighting” tab.
  4. Now choose your WiFi network and enter the password and click next.
  5. Select “Confirm the light is blinking rapidly” and click next.
  6. Now the app will scan and add the device to your app dashboard, it may take a while.

Testing

Open the device from the dashboard and try clicking the ON/OFF button, the inbuilt LED of your Arduino with toggle accordingly in sync with the smart app button state.

https://diyusthad.com/wp-content/uploads/2021/10/tuya-testing.mp4

That’s it guys we have successfully made an IoT device with ESP8266 and Tuya IoT. Instead of the inbuilt LED on the Arduino now you can change the code to control any pin of the Arduino and use relays to control any appliances in your home like fan, TV, oven, lights, RGB lights, etc…


Troubleshooting


Video

Conclusion

If you want to build a commercial automation product or provide a great and easy tool for your customer to integrate any technology into the internet of things with ESP8266 or If you want an app with a simple interface and a great experience for the users. The answer to all these is Tuya IoT Smart technology.

Exit mobile version