Getting Started With Arduino IoT Control With Tuya IoT Platform

Struggling to connect your cheap Arduino UNO to a reliable IoT network, meet Tuya, an enterprise-grade IoT development suite.

Introduction:

I have always enjoyed using Arduino UNO since it was my first programmable board but it lacks IoT network capabilities even if you have a network module like HC-05 Bluetooth module or ESP8266 you still struggle to find a perfect IoT management software suite. According to Juniper Research, there are over 46 billion IoT devices in 2021. But we must not turn blind when it comes to security, we all want a secure plug-and-play IoT device and here comes Tuya IoT development suite into play. IoT

Things used in this project

Hardware:

Software:

What is Tuya?

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. Tuya IoT

With Tuya, you implement IoT networks to your devices and leverage their ecosystem to make a commercial product with mobile apps, AI integrations, and real-time authentications. But one has to start somewhere, let’s see a small introductory example on how to use the Tuya IoT platform – Tuya Developer – Tuya Smart – Global IoT Development Platform

But, how do I join Tuya as a developer?

Tuya is open to all, join as a beta tester and developer with their recent Arduino Library and Tuya Development kits release. Sign up and join the Tuya Developer Arduino Beta Test to get your development gifts and make your own Arduino projects with Tuya Support. Don’t forget to share your feedback with the whole community.

Setting up Arduino UNO Tuya IOT Control with ESP8266:

Step 1: Create a device on Tuya To start developing with Tuya, you need to sign up for an account on Tuya.com. After creating an account, log in and follow the steps shown below. Click on create button to create a new IoT device. step1

Once you click create you get several options to select the type of your device, in fact, there are hundreds of IoT device types to select from, Tuya has more than 410.000 different SKUs in over 1, 100 categories, covering over 220 countries and regions. For this demonstration, we are going to select switch (you can use Light Source as well, both works the same for the Arduino example).

step Once the switch solution is selected you will be presented with the option to select development type, here, we choose ‘Custom Solution’ as shown below and then fill out product details, since we are using ESP8266 as Tuya IoT node so we will select WiFi (ESP32 has both WiFi and BLE). step After doing the above steps you now need to select which functions does your solution need, there are already standard functions available for most of the sensor data types like temperature, humidity, on-off, pulse rate, etc. if you cannot find any standard function you can create a custom function in easy steps too, check here https://developer.tuya.com/en/docs/iot/custom-functions?id=K937y38137c64 step Here, the important things or basic concepts to keep in mind from the above image (we have added 4 switch data points for controlling RGB LEDs, add as many peripherals you want to control) are:
Data Point: represents functions of smart devices and parameters.
DP ID: indicates the code of a data point. Subsequent function data transfer between the device and the cloud is through data point ID.
Name: indicates the name of a custom function.
Identifier: indicates code value of a data point, displaying function name in multi-language on the app. Support letters, digits, and underlines, starting with a letter.
Data type:
Boolean: indicates the binary variable value (true or false). For instance: switching function (On or Off).
Integer: represents data that can be linearly adjusted. For instance: temperature adjustment, ranging from 20 to 40 °C.
Enum: indicates custom finite set value. For instance: working level (low, middle, and high).
Fault: specified for fault report and statistics. Support Only report when multiple faults occur.
Char type: indicates data transfer in char type.
RAW type: indicates data transfer in a raw binary format. Generally, it is recommended to use raw data transfer when the other five types cannot cope with the complicated product functions.
Data transfer type:
Issue and report: indicates two-way data transfer between the device and the cloud.
Only report: indicates one-way data transfer. Data can only be reported from the device.
Only issue: indicates one-way data transfer. Data can only be issued by the cloud.
step
Select TYWE3S Wifi Module from Hardware Development. The module is based upon ESP8266 and it works simply using serial communication or UART with our Arduino. In the device panel, we have the option to make a mobile app using drag and drop style tools but we will use the default app for this demonstration. step
Step 2: Burning Tuya Auth Token to ESP8266
To be able to use the NodeMCU ESP8266 as a Tuya product for this project, you need to flash and authorize it with the required firmware. To authorize the ESP8266, you have to send the product ID (PID) and your Tuya IoT account name (e-mail) to [email protected] After a while, they will send you a Token ID. Then, follow the steps below: step
First, go to the Tuya PMS service page https://pms.tuya.com/en/login and sign up for an account if you don’t have one. Then, go to Production Manage ➡Work Order Management ➡ Activation Code Verification. To activate the production certificate for the product, enter the Token ID. When the Token ID is confirmed, the ESP8266 is ready to be flashed and authorized. Remember only once ID can authorize from a single account. To check your activated Tokens go to Activation Code List in the Production Manage -> Work Order Management list.
You can download the cloud auth token burning application from the PMS console Software Download section or Download installations package on the Google drive https://drive.google.com/file/d/1SF-rM5qDLaPJiuMHrkqFauVyRXSSHMkj/view?usp=sharing from Tuya ESP8266 guide (link in the reference section) and log in with your PMS account.
step
Set the baud rate and test baud as shown in the above image. Also, click on Enter Token button and enter the token you got from the Tuya [email protected] email reply. step
Now, connect the NodeMCU V3 LoLin ESP8266 to the computer via a USB cable and select its port number, such as COM5. If you did not use it with the Arduino IDE or other compilers before, you may need to install its driver. Finally, click on flash to burn auth tokens. You would see a green box with success if nothing breaks.
step
Step 3: Arduino Program and Mobile Control App
1. Download and install Arduino IDE if you don’t have it already
2. After installing the IDE, you need to install a library by Tuya. It is very easy to install a library in Arduino IDE. First, open the IDE and click on Tools >> Manage Libraries. This will open a pop-up window, in this window type in the search bar “Tuya” and hit enter.
3. Now click on File >> Example >> Tuya_WiFi_MCU_SDK >> Start. This will open a pre-built sketch which I have modified for our project, check the attached code.
4. Now select the correct port for your Arduino UNO board and flash it.
step
The connections for this project are very simple. All you will need is 4 male-to-male jumper wires, ESP8266, and Arduino UNO. Follow the connections given in the diagram below. But make sure you disconnect the boards before. Otherwise, it will be problematic while uploading the codes since RX, TX pins would be easy and it won’t allow flashing codes. After the connections are made, let’s proceed to the app which will control the Red and Blue Led on 12, 11 pins.
Using the App:
First head over to the Play Store or App Store and download the Tuya Smart app. After the app is installed you should be greeted with the following screen.
1. Click on Add Device button. This will take you to the next page where we will create a switch. Here click on Add Device button and select Switch (WiFi) as we have made in the Tuya IoT console.
step
Then proceed to select WiFi network, remember the device connecting to Tuya i.e ESP8266 and app should be on the same WiFi network. The app would control led on pin 13 but you can add a relay or other actuators to control it through the app. Happy hacking! See the live demo below.
Now you can see the real potential and simplicity of Tuya IoT, make sure to give it a try and experiment well. Keep checking here, I will share some more interesting projects with Tuya IoT.

References:
Tuya IoT Platform: iot.tuya.com/…
Tuya Developer Platform: Tuya Developer – Tuya Smart – Global IoT Development Platform
Tuya Arduino Developer Program: Join Tuya Arduino Beta Test
Firmware burning guide: GitHub – GITOLEO/Tuya-ESP8266-firmware-burning-authorizations-guide
/*
 * @FileName: Arduino Led Control
 * @Author: Sumit
 * @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 1
#define DPID_Switch_2 2
#define DPID_Switch_3 3
/* 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},
  {DPID_Switch_2, DP_TYPE_BOOL},
  {DPID_Switch_3, DP_TYPE_BOOL},
};

unsigned char pid[] = {"pesdkvtaiorvldsm"};
unsigned char mcu_ver[] = {"3.1.4"};

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

// Define RGB pins:
#define redPin 12 
#define bluePin 11

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

  //Initialize led port, turn off led.
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  pinMode(redPin, OUTPUT);
  digitalWrite(redPin, LOW);
  pinMode(bluePin, OUTPUT);
  digitalWrite(bluePin, 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, 3);
  //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;

    case DPID_Switch_2:
      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(redPin, HIGH);
      } else {
        //Turn off
        digitalWrite(redPin, LOW);
      }
      //Status changes should be reported.
      my_device.mcu_dp_update(dpid, value, length);
    break;

    case DPID_Switch_3:
      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(bluePin, HIGH);
      } else {
        //Turn off
        digitalWrite(bluePin, 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);
  my_device.mcu_dp_update(DPID_Switch_2, led_state, 1);
  my_device.mcu_dp_update(DPID_Switch_3, led_state, 1);
}

Leave a Reply

STEPTOSTEM