Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 10,608
» Latest member: tg88contact
» Forum threads: 4,352
» Forum posts: 21,389

Full Statistics

Online Users
There are currently 87 online users.
» 0 Member(s) | 79 Guest(s)
Amazonbot, Crawl, Google, PetalBot, bot

Latest Threads
Shipping costs new CT Cla...
Forum: N30
Last Post: Vega
46 minutes ago
» Replies: 2
» Views: 63
KC868-A16 V3 – HTTPS GET ...
Forum: "KCS" v3 firmware
Last Post: admin
10 hours ago
» Replies: 3
» Views: 97
ds3231 added to esphome, ...
Forum: KC868-A16v3
Last Post: admin
Yesterday, 02:59 AM
» Replies: 2
» Views: 122
how to use DS3231/SD8931 ...
Forum: Getting Started with ESPHome and Home Assistant
Last Post: admin
Yesterday, 02:58 AM
» Replies: 0
» Views: 58
Whether KinCony have Alie...
Forum: KC868-AI
Last Post: admin
Yesterday, 02:25 AM
» Replies: 1
» Views: 44
how to use ethernet and w...
Forum: Getting Started with ESPHome and Home Assistant
Last Post: admin
Yesterday, 12:24 AM
» Replies: 0
» Views: 59
Ethernet jack link LED se...
Forum: B16M
Last Post: admin
11-23-2026, 11:40 PM
» Replies: 1
» Views: 32
KinCony N30 – CT clamp se...
Forum: N30
Last Post: admin
11-22-2026, 11:53 PM
» Replies: 1
» Views: 57
KC868-A8v3 (KCS v3.27.4) ...
Forum: KinCony integrate with Loxone home automation
Last Post: admin
11-22-2026, 11:44 PM
» Replies: 1
» Views: 72
Single-family home automa...
Forum: DIY Project
Last Post: lulu01
11-22-2026, 10:42 PM
» Replies: 5
» Views: 1,279

  [arduino code examples for MT4v2]-09 how to communication with Tuya WiFi module
Posted by: admin - 10-20-2026, 03:32 AM - Forum: MT4v2 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* This Arduino program implements communication between ESP32 and the Tuya module
* via UART (serial communication). It listens for specific packets from the Tuya module
* and responds according to the predefined commands.
*
* Functionality:
* 1. When the ESP32 receives a heartbeat packet (55 AA 00 00 00 00 FF),
*    it sends a heartbeat response (55 AA 03 00 00 01 00 03).
* 2. When the ESP32 receives a product information request (55 AA 00 01 00 00 00),
*    it sends a product information response (55 AA 03 01 ...).
* 3. When the ESP32 receives a work mode request (55 AA 00 02 00 00 01),
*    it sends a work mode response (55 AA 03 02 00 03 10 1C 14 47).
* 4. When the ESP32 receives a network status request (55 AA 00 03 00 01 00 03),
*    it sends a network status response (55 AA 03 03 00 00 05).
* 5. Subsequent heartbeat packets (55 AA 00 00 00 00 FF) are responded to with
*    (55 AA 03 00 00 01 01 04).
*/

#include <HardwareSerial.h>

// Create a HardwareSerial object for UART communication on ESP32
HardwareSerial tuyaSerial(1);

// Define the GPIO pins for TXD and RXD used for serial communication
#define TXD_PIN 6
#define RXD_PIN 7

// Set the baud rate for Tuya module communication to 9600
#define BAUD_RATE 9600

// Define the response packets for different commands from the Tuya module

// Heartbeat response: 55 AA 03 00 00 01 00 03
uint8_t heartBeatResponse[] = {0x55, 0xAA, 0x03, 0x00, 0x00, 0x01, 0x00, 0x03};

// Product info response with a detailed payload (e.g., firmware version, product name, etc.)
uint8_t productInfoResponse[] = {
  0x55, 0xAA, 0x03, 0x01, 0x00, 0x2A, 0x7B, 0x22, 0x70, 0x22, 0x3A, 0x22,
  0x63, 0x68, 0x6D, 0x7A, 0x6C, 0x67, 0x6A, 0x70, 0x61, 0x64, 0x70, 0x71,
  0x78, 0x64, 0x6B, 0x6F, 0x22, 0x2C, 0x22, 0x76, 0x22, 0x3A, 0x22, 0x31,
  0x2E, 0x30, 0x2E, 0x30, 0x22, 0x2C, 0x22, 0x6D, 0x22, 0x3A, 0x30, 0x7D, 0xAA
};

// Work mode response: 55 AA 03 02 00 03 10 1C 14 47
uint8_t workModeResponse[] = {0x55, 0xAA, 0x03, 0x02, 0x00, 0x03, 0x10, 0x1C, 0x14, 0x47};

// Network status response: 55 AA 03 03 00 00 05
uint8_t netStatusResponse[] = {0x55, 0xAA, 0x03, 0x03, 0x00, 0x00, 0x05};

// Subsequent heartbeat response: 55 AA 03 00 00 01 01 04
uint8_t secondHeartBeatResponse[] = {0x55, 0xAA, 0x03, 0x00, 0x00, 0x01, 0x01, 0x04};

void setup() {
  // Initialize the serial communication for debugging at 115200 baud rate
  Serial.begin(115200);

  // Initialize the serial communication with Tuya module at 9600 baud rate
  tuyaSerial.begin(BAUD_RATE, SERIAL_8N1, RXD_PIN, TXD_PIN);

  // Debug message to indicate that the serial communication has been initialized
  Serial.println("ESP32-Tuya serial communication initialized.");
}

void loop() {
  // Check if data is available from the Tuya module
  if (tuyaSerial.available()) {
    uint8_t incomingPacket[7];  // Array to store the received packet
    size_t bytesRead = tuyaSerial.readBytes(incomingPacket, 7); // Read 7 bytes from Tuya

    // Check if the packet has a valid header (0x55, 0xAA)
    if (bytesRead >= 2 && incomingPacket[0] == 0x55 && incomingPacket[1] == 0xAA) {
      // If less than 7 bytes were received, wait for more data
      if (bytesRead < 7) {
        Serial.println("Incomplete packet received. Waiting for remaining bytes...");
        delay(50); // Delay to allow more data to be received
        while (tuyaSerial.available()) {
          incomingPacket[bytesRead++] = tuyaSerial.read(); // Continue reading remaining bytes
          if (bytesRead >= 7) break;
        }
      }

      // If still less than 7 bytes, discard the incomplete packet
      if (bytesRead < 7) {
        Serial.println("Error: Incomplete packet discarded.");
        return;
      }

      // Debug: Print the received packet for logging
      Serial.print("Received packet: ");
      for (size_t i = 0; i < 7; i++) {
        Serial.print(incomingPacket[i], HEX);
        Serial.print(" ");
      }
      Serial.println();

      // Call the function to process the received packet
      processTuyaPacket(incomingPacket, 7);

    } else {
      // If the header is invalid, discard the packet and flush the buffer
      Serial.print("Error: Invalid packet header. Data received: ");
      for (size_t i = 0; i < bytesRead; i++) {
        Serial.print(incomingPacket[i], HEX);
        Serial.print(" ");
      }
      Serial.println();
      tuyaSerial.flush(); // Clear the serial buffer
    }
  }

  // Delay to avoid CPU overuse
  delay(100);
}

// Function to process the received packet and send the appropriate response
void processTuyaPacket(uint8_t* packet, size_t size) {
  // Ensure the packet size is 7 and the header is valid
  if (size == 7 && packet[0] == 0x55 && packet[1] == 0xAA) {
    // Determine the command in the packet (packet[2])
    switch(packet[2]) {
      case 0x00:
        if (packet[3] == 0x00 && packet[4] == 0x00 && packet[5] == 0x00 && packet[6] == 0xFF) {
          Serial.println("Heartbeat received.");
          sendPacket(heartBeatResponse, sizeof(heartBeatResponse));
        } else if (packet[3] == 0x01 && packet[4] == 0x00 && packet[5] == 0x00 && packet[6] == 0x00) {
          Serial.println("Product info request received.");
          sendPacket(productInfoResponse, sizeof(productInfoResponse));
        } else if (packet[3] == 0x02 && packet[4] == 0x00 && packet[5] == 0x00 && packet[6] == 0x01) {
          Serial.println("Work mode request received.");
          sendPacket(workModeResponse, sizeof(workModeResponse));
        } else if (packet[3] == 0x03 && packet[4] == 0x00 && packet[5] == 0x01 && packet[6] == 0x00) {
          Serial.println("Network status request received.");
          sendPacket(netStatusResponse, sizeof(netStatusResponse));
        }
        break;

      default:
        Serial.println("Error: Unhandled command received.");
        break;
    }
  }
}

// Function to send the response packet to the Tuya module
void sendPacket(uint8_t* packet, size_t size) {
  // Send the packet via UART to Tuya module
  tuyaSerial.write(packet, size);

  // Debug: Print the sent packet for logging
  Serial.print("Sent packet: ");
  for (size_t i = 0; i < size; i++) {
    Serial.print(packet[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}
arduino ino file download:

.zip   9-tuya-wifi-config.zip (Size: 2 KB / Downloads: 93)

Print this item

  [arduino code examples for MT4v2]-08 Ethernet W5500 chip work with TCP Server mode
Posted by: admin - 10-20-2026, 03:31 AM - Forum: MT4v2 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* This Arduino program sets up an ESP32-S3 with a W5500 Ethernet module
* as a TCP server. It listens on port 4196 and echoes back any string
* received from a client.
*
* Hardware connections:
* - CLK: GPIO42
* - MOSI: GPIO43
* - MISO: GPIO44
* - CS: GPIO41
* - RST: GPIO1
* - INT: GPIO2
*
* Static IP address: 192.168.3.55
* Subnet Mask: 255.255.255.0
* Gateway: 192.168.3.1
* DNS: 192.168.3.1
*/

#include <SPI.h>
#include <Ethernet.h>

// Define the W5500 Ethernet module pins
#define W5500_CS_PIN  42
#define W5500_RST_PIN 44
#define W5500_INT_PIN 43
#define W5500_CLK_PIN 1
#define W5500_MOSI_PIN 2
#define W5500_MISO_PIN 41

// MAC address for your Ethernet shield (must be unique on your network)
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// Static IP address configuration
IPAddress ip(192, 168, 3, 55);       // Static IP address
IPAddress subnet(255, 255, 255, 0);   // Subnet mask
IPAddress gateway(192, 168, 3, 1);    // Default gateway
IPAddress dns(192, 168, 3, 1);        // DNS server address

// Create an EthernetServer object to handle TCP connections
EthernetServer server(4196);

void setup() {
  // Initialize serial communication
  Serial.begin(115200);
  while (!Serial) {
    ; // Wait for serial port to connect
  }

  // Initialize the W5500 module
  pinMode(W5500_RST_PIN, OUTPUT);
  pinMode(W5500_INT_PIN, INPUT);
  digitalWrite(W5500_RST_PIN, LOW);  // Reset the W5500 module
  delay(100);                       // Wait for reset to complete
  digitalWrite(W5500_RST_PIN, HIGH); // Release reset

  // Initialize SPI with the correct pin definitions
  SPI.begin(W5500_CLK_PIN, W5500_MISO_PIN, W5500_MOSI_PIN);

  // Set up the Ethernet library with W5500-specific pins
  Ethernet.init(W5500_CS_PIN);

  // Start the Ethernet connection with static IP configuration
  Ethernet.begin(mac, ip, dns, gateway, subnet);

  // Print the IP address to the serial monitor
  Serial.print("IP Address: ");
  Serial.println(Ethernet.localIP());

  // Start listening for incoming TCP connections
  server.begin();
}

void loop() {
  // Check for incoming client connections
  EthernetClient client = server.available();
  if (client) {
    Serial.println("New client connected");

    // Read data from the client and echo it back
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        server.write(c);
      }
    }

    // Close the connection when done
    client.stop();
    Serial.println("Client disconnected");
  }
}
arduino ino file download:

.zip   8-Ethernet-W5500.zip (Size: 1.23 KB / Downloads: 87)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download: 

.zip   8-Ethernet-W5500.ino.merged.zip (Size: 191.06 KB / Downloads: 85)

Print this item

  [arduino code examples for MT4v2]-07 RF433MHz wireless recevier decode
Posted by: admin - 10-20-2026, 03:30 AM - Forum: MT4v2 - No Replies

Code:
#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(digitalPinToInterrupt(14));
  Serial.print("begin test");
}

void loop() {
  if (mySwitch.available()) {
   
    Serial.print("Received ");
    Serial.print( mySwitch.getReceivedValue() );
    Serial.print(" / ");
    Serial.print( mySwitch.getReceivedBitlength() );
    Serial.print("bit ");
    Serial.print("Protocol: ");
    Serial.println( mySwitch.getReceivedProtocol() );

    mySwitch.resetAvailable();
  }
}
arduino ino file download:

.zip   7-RF-433M-receiver.zip (Size: 417 bytes / Downloads: 80)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download: 

.zip   7-RF-433M-receiver.ino.merged.zip (Size: 181.95 KB / Downloads: 92)

Print this item

  [arduino code examples for MT4v2]-06 How to use SD Card
Posted by: admin - 10-20-2026, 03:28 AM - Forum: MT4v2 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* SD Card File Operations
*
* This program demonstrates basic file operations on an SD card using the ESP32.
* It includes functionality to:
* - Initialize and test the SD card
* - Read from, write to, append to, and delete files on the SD card
* - Measure file read and write performance
*
* Hardware Connections:
* - SCK: GPIO 11
* - MISO: GPIO 12
* - MOSI: GPIO 10
* - CS: GPIO 9
*/

#include "FS.h"
#include "SD.h"
#include "SPI.h"

// Pin definitions for SD card
#define SCK  11
#define MISO 12
#define MOSI 10
#define CS   9

/**
* @brief Reads the contents of a file from the SD card and prints it to the serial monitor.
*
* @param fs File system to use (in this case, SD).
* @param path Path of the file to read.
*/
void readFile(fs::FS &fs, const char * path) {
  Serial.printf("Reading file: %s\n", path);

  File file = fs.open(path);
  if (!file) {
    Serial.println("Failed to open file for reading");
    return;
  }

  Serial.print("Read from file: ");
  while (file.available()) {
    Serial.print((char)file.read());
  }
  file.close();
}

/**
* @brief Writes a message to a file on the SD card.
*
* @param fs File system to use (in this case, SD).
* @param path Path of the file to write.
* @param message Message to write to the file.
*/
void writeFile(fs::FS &fs, const char * path, const char * message) {
  Serial.printf("Writing file: %s\n", path);

  File file = fs.open(path, FILE_WRITE);
  if (!file) {
    Serial.println("Failed to open file for writing");
    return;
  }
  if (file.print(message)) {
    Serial.println("File written");
  } else {
    Serial.println("Write failed");
  }
  file.close();
}

/**
* @brief Appends a message to a file on the SD card.
*
* @param fs File system to use (in this case, SD).
* @param path Path of the file to append.
* @param message Message to append to the file.
*/
void appendFile(fs::FS &fs, const char * path, const char * message) {
  Serial.printf("Appending to file: %s\n", path);

  File file = fs.open(path, FILE_APPEND);
  if (!file) {
    Serial.println("Failed to open file for appending");
    return;
  }
  if (file.print(message)) {
    Serial.println("Message appended");
  } else {
    Serial.println("Append failed");
  }
  file.close();
}

/**
* @brief Deletes a file from the SD card.
*
* @param fs File system to use (in this case, SD).
* @param path Path of the file to delete.
*/
void deleteFile(fs::FS &fs, const char * path) {
  Serial.printf("Deleting file: %s\n", path);
  if (fs.remove(path)) {
    Serial.println("File deleted");
  } else {
    Serial.println("Delete failed");
  }
}

/**
* @brief Tests file read and write performance.
*
* @param fs File system to use (in this case, SD).
* @param path Path of the file to test.
*/
void testFileIO(fs::FS &fs, const char * path) {
  File file = fs.open(path);
  static uint8_t buf[512];
  size_t len = 0;
  uint32_t start = millis();
  uint32_t end = start;

  if (file) {
    len = file.size();
    size_t flen = len;
    start = millis();
    while (len) {
      size_t toRead = len;
      if (toRead > 512) {
        toRead = 512;
      }
      file.read(buf, toRead);
      len -= toRead;
    }
    end = millis() - start;
    Serial.printf("%u bytes read for %u ms\n", flen, end);
    file.close();
  } else {
    Serial.println("Failed to open file for reading");
  }

  file = fs.open(path, FILE_WRITE);
  if (!file) {
    Serial.println("Failed to open file for writing");
    return;
  }

  size_t i;
  start = millis();
  for (i = 0; i < 2048; i++) {
    file.write(buf, 512);
  }
  end = millis() - start;
  Serial.printf("%u bytes written for %u ms\n", 2048 * 512, end);
  file.close();
}

void setup() {
  // Initialize serial communication
  Serial.begin(115200);
 
  // Initialize SPI and SD card
  SPIClass spi = SPIClass(HSPI);
  spi.begin(SCK, MISO, MOSI, CS);

  if (!SD.begin(CS, spi, 80000000)) {
    Serial.println("Card Mount Failed");
    return;
  }

  uint8_t cardType = SD.cardType();

  if (cardType == CARD_NONE) {
    Serial.println("No SD card attached");
    return;
  }

  Serial.print("SD Card Type: ");
  if (cardType == CARD_MMC) {
    Serial.println("MMC");
  } else if (cardType == CARD_SD) {
    Serial.println("SDSC");
  } else if (cardType == CARD_SDHC) {
    Serial.println("SDHC");
  } else {
    Serial.println("UNKNOWN");
  }

  uint64_t cardSize = SD.cardSize() / (1024 * 1024);
  Serial.printf("SD Card Size: %lluMB\n", cardSize);
  delay(2000);

  // Perform file operations
  deleteFile(SD, "/hello.txt");
  writeFile(SD, "/hello.txt", "Hello ");
  appendFile(SD, "/hello.txt", "World!\n");
  readFile(SD, "/hello.txt");
  testFileIO(SD, "/test.txt");
  Serial.printf("Total space: %lluMB\n", SD.totalBytes() / (1024 * 1024));
  Serial.printf("Used space: %lluMB\n", SD.usedBytes() / (1024 * 1024));
}

void loop() {
  // No operation in loop
}
arduino ino file download:

.zip   6-SD.zip (Size: 1.53 KB / Downloads: 94)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download: 

.zip   6-SD.ino.merged.zip (Size: 219.15 KB / Downloads: 84)

Print this item

  [arduino code examples for MT4v2]-05 Read free GPIO state
Posted by: admin - 10-20-2026, 03:27 AM - Forum: MT4v2 - No Replies

Code:
/*
* ESP32 GPIO State Reader
* Reads the state of GPIO47, GPIO48, GPIO7, GPIO40, GPIO0, and GPIO5
* and prints the results to the serial monitor.
*
* Made by KinCony IoT: https://www.kincony.com
*/


#define GPIO_40  40
#define GPIO_48  48
#define GPIO_0   0
#define GPIO_47  47
#define GPIO_17  17



void setup() {
    Serial.begin(115200); // Initialize serial communication at 115200 baud rate
   
    // Set GPIOs as input

    pinMode(GPIO_40, INPUT);
    pinMode(GPIO_48, INPUT);
    pinMode(GPIO_0, INPUT);
    pinMode(GPIO_47, INPUT);
    pinMode(GPIO_17, INPUT);           
}

void loop() {
    // Read GPIO states
    int state_40 = digitalRead(GPIO_40);
    int state_48 = digitalRead(GPIO_48);
    int state_0  = digitalRead(GPIO_0);
    int state_47 = digitalRead(GPIO_47);
    int state_17 = digitalRead(GPIO_17);


    // Print GPIO states to the serial monitor
    Serial.printf("GPIO40: %d, GPIO48: %d, GPIO0: %d, GPIO47: %d, GPIO17: %d\n",
                  state_40, state_48, state_0, state_47, state_17);
   
    delay(1000); // Read GPIO states every second
}
arduino ino file download:

.zip   5-free-gpio-state.zip (Size: 685 bytes / Downloads: 85)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download: 

.zip   5-free-gpio-state.ino.merged.zip (Size: 180.12 KB / Downloads: 83)

Print this item

  [arduino code examples for MT4v2]-04 RS485 communication test
Posted by: admin - 10-20-2026, 03:26 AM - Forum: MT4v2 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* RS485 Communication Test
*
* This program is a simple test for RS485 communication using ESP32-S3.
* It will send a message over RS485 and then read incoming messages.
* The TXD pin is defined as GPIO 18 and RXD pin is defined as GPIO 8.
*/

#include <HardwareSerial.h>

// Define RS485 pins
#define RS485_RXD 38
#define RS485_TXD 39

// Create a hardware serial object
HardwareSerial rs485Serial(1);

void setup() {
  // Start serial communication for debugging
  Serial.begin(115200);
  while (!Serial);

  // Initialize RS485 Serial communication
  rs485Serial.begin(9600, SERIAL_8N1, RS485_RXD, RS485_TXD);
 
  Serial.println("RS485 Test Start");
}

void loop() {
  // Send a test message
  rs485Serial.println("Hello from KinCony");

  // Wait for a short period
  delay(1000);

  // Check if data is available to read
  if (rs485Serial.available()) {
    String receivedMessage = "";
    while (rs485Serial.available()) {
      char c = rs485Serial.read();
      receivedMessage += c;
    }
    // Print the received message
    Serial.print("Received: ");
    Serial.println(receivedMessage);
  }

  // Wait before sending the next message
  delay(2000);
}
arduino ino file download:

.zip   4-RS485-Test.zip (Size: 758 bytes / Downloads: 82)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download: 

.zip   4-RS485-Test.ino.merged.zip (Size: 185.84 KB / Downloads: 87)

Print this item

  [arduino code examples for MT4v2]-03 Read ADS1115 analog input ports value
Posted by: admin - 10-20-2026, 03:24 AM - Forum: MT4v2 - No Replies

Code:
/*
* This program reads voltage values from the ADS1115 analog-to-digital converter
* on all four channels (A0, A1, A2, A3) and prints the results through the serial port.
* The ADS1115 communicates via the I2C protocol. This version of the code includes
* the capability to specify custom SDA and SCL pins for I2C communication.
*
* Copyright: Made by KinCony IoT: https://www.kincony.com
*
*/

#include <Wire.h>                // Library for I2C communication
#include <DFRobot_ADS1115.h>     // Library for ADS1115 ADC module

// Define the I2C SDA and SCL pins for communication with ADS1115
#define SDA_PIN 8 
#define SCL_PIN 18 

// Initialize ADS1115 instance using the Wire library
DFRobot_ADS1115 ads(&Wire);

void setup(void)
{
    // Begin serial communication at a baud rate of 115200
    Serial.begin(115200);

    // Initialize the I2C bus using the defined SDA and SCL pins
    Wire.begin(SDA_PIN, SCL_PIN);

    // Set the I2C address for the ADS1115 (default: 0x49)
    ads.setAddr_ADS1115(ADS1115_IIC_ADDRESS0);   // Address is 0x49

    // Set the gain for the ADS1115 (2/3x gain allows for a maximum input voltage of 6.144V)
    ads.setGain(eGAIN_TWOTHIRDS);

    // Set the ADS1115 to operate in single-shot mode (each reading is a single conversion)
    ads.setMode(eMODE_SINGLE);

    // Set the sample rate to 128 samples per second (SPS)
    ads.setRate(eRATE_128);

    // Set the operational status mode to single-conversion start
    ads.setOSMode(eOSMODE_SINGLE);

    // Initialize the ADS1115 module
    ads.init();
}

void loop(void)
{
    // Check if the ADS1115 is properly connected and functioning
    if (ads.checkADS1115())
    {
        // Variables to store the voltage readings for each channel
        int16_t adc0, adc1, adc2, adc3;

        // Read the voltage from channel A0 and print the value
        adc0 = ads.readVoltage(0);
        Serial.print("A0:");
        Serial.print(adc0);
        Serial.print("mV,  ");    // Print the value in millivolts

        // Read the voltage from channel A1 and print the value
        adc1 = ads.readVoltage(1);
        Serial.print("A1:");
        Serial.print(adc1);
        Serial.print("mV,  ");    // Print the value in millivolts

        // Read the voltage from channel A2 and print the value
        adc2 = ads.readVoltage(2);
        Serial.print("A2:");
        Serial.print(adc2);
        Serial.print("mV,  ");    // Print the value in millivolts

        // Read the voltage from channel A3 and print the value
        adc3 = ads.readVoltage(3);
        Serial.print("A3:");
        Serial.print(adc3);
        Serial.println("mV");     // Print the value in millivolts and end the line
    }
    else
    {
        // If ADS1115 is not connected, print a message indicating disconnection
        Serial.println("ADS1115 Disconnected!");
    }

    // Wait for 1 second before the next loop iteration
    delay(1000);
}
arduino ino file download:

.zip   3-ads1115_adc.zip (Size: 1.2 KB / Downloads: 84)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download: 

.zip   3-ads1115_adc.ino.merged.zip (Size: 194.32 KB / Downloads: 87)

Print this item

  [arduino code examples for MT4v2]-02 Read digital input ports state
Posted by: admin - 10-20-2026, 03:22 AM - Forum: MT4v2 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* Description:
* This Arduino program reads the state of a 16-channel PCF8574 I/O expander
* and prints the state of all input pins to the Serial Monitor. The state of
* each pin is represented as a bit in a 8-bit value, where each bit corresponds
* to an input pin. The program prints the input state in binary format.
*
* Pin Definitions:
* - SDA: GPIO 8
* - SCL: GPIO 18
* - PCF8575 I2C Address: 0x22
*/

#include "Arduino.h"
#include "PCF8574.h"

// Define I2C pins
#define I2C_SDA 8  // Define SDA pin
#define I2C_SCL 18  // Define SCL pin

// Set I2C address
PCF8574 pcf8574_IN1(0x22); // The I2C address of the PCF8575

void setup() {
    Serial.begin(115200);

    // Initialize I2C communication
    Wire.begin(I2C_SDA, I2C_SCL); // Initialize I2C with defined SDA and SCL pins

    pcf8574_IN1.pinMode(P0, INPUT);
    pcf8574_IN1.pinMode(P1, INPUT);
    pcf8574_IN1.pinMode(P2, INPUT);
    pcf8574_IN1.pinMode(P3, INPUT);
    pcf8574_IN1.pinMode(P4, INPUT);
    pcf8574_IN1.pinMode(P5, INPUT);
    pcf8574_IN1.pinMode(P6, INPUT);
    pcf8574_IN1.pinMode(P7, INPUT);

    pcf8574_IN1.begin(); // Initialize the PCF8575

    Serial.println("KinCony 8 channel input state 0:ON  1:OFF");
}

void loop() {
    uint16_t state = 0;

    // Read the state of each pin (assuming 16 pins)
    for (int pin = 0; pin < 8; pin++) {
        if (pcf8574_IN1.digitalRead(pin)) {
            state |= (1 << pin); // Set the bit for the active pin
        }
    }

    Serial.print("Input state: ");
    Serial.println(state, BIN); // Print the state of inputs in binary

    delay(500); // Delay 500ms
}
arduino ino file download:

.zip   2-digital-input.zip (Size: 890 bytes / Downloads: 86)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download: 

.zip   2-digital-input.ino.merged.zip (Size: 195.59 KB / Downloads: 96)

Print this item

  [arduino code examples for MT4v2]-01 Control 4 channel DC motor
Posted by: admin - 10-20-2026, 03:18 AM - Forum: MT4v2 - No Replies

Code:
/*
* KinCony MT4V2 DC Motor Test
* Power ON -> M1-M4 run at 100%
*
* Made by KinCony IoT
* https://www.kincony.com
*/

#include <Arduino.h>

#define RXD 15
#define TXD 16

HardwareSerial MotorSerial(1);

uint16_t crc16(const uint8_t *data, uint8_t len)
{
  uint16_t crc = 0xFFFF;

  while (len--)
  {
    crc ^= *data++;

    for (uint8_t i = 0; i < 8; i++)
      crc = (crc & 1) ? (crc >> 1) ^ 0xA001 : crc >> 1;
  }

  return crc;
}

void sendFrame(uint8_t *data)
{
  uint16_t crc = crc16(data, 6);

  MotorSerial.write(data, 6);
  MotorSerial.write(crc & 0xFF);
  MotorSerial.write(crc >> 8);
  MotorSerial.flush();

  delay(50);

  // Clear ARM response
  while (MotorSerial.available())
    MotorSerial.read();
}

void enableMotor()
{
  uint8_t cmd[] = {
    1, 0x05,
    0x01, 0xF7,     // Coil 503
    0xFF, 0x00      // ON
  };

  sendFrame(cmd);
}

void setMotor(uint8_t motor, int16_t speed)
{
  uint16_t reg = 2000 + motor - 1;

  uint8_t cmd[] = {
    1, 0x06,
    uint8_t(reg >> 8),
    uint8_t(reg),
    uint8_t(speed >> 8),
    uint8_t(speed)
  };

  sendFrame(cmd);
}

void startMotors()
{
  enableMotor();

  setMotor(1, 100);  //100 is speed
  setMotor(2, 100);  //100 is speed
  setMotor(3, 100);  //100 is speed
  setMotor(4, 100);  //100 is speed
}

void setup()
{
  MotorSerial.begin(115200, SERIAL_8N1, RXD, TXD);

  // Wait for ARM CPU startup
  delay(3000);

  startMotors();
}

void loop()
{
  // Refresh commands every 2 seconds
  delay(2000);

  startMotors();
}
arduino ino file download:

.zip   1-motor.zip (Size: 797 bytes / Downloads: 84)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download:

.zip   1-motor.ino.merged.zip (Size: 185.77 KB / Downloads: 82)

Print this item

  MT4v2 ESPHome yaml for home assistant without tuya
Posted by: admin - 10-20-2026, 03:15 AM - Forum: MT4v2 - No Replies

Code:
esphome:
  name: mt4v2
  friendly_name: mt4v2


# ============================================================
# ESP32-S3
# ============================================================

esp32:
  board: esp32-s3-devkitc-1
  framework:
    type: arduino


# ============================================================
# Logger
# ============================================================

logger:
  hardware_uart: USB_SERIAL_JTAG


# ============================================================
# Home Assistant API
# ============================================================

api:


# ============================================================
# Ethernet - W5500
# ============================================================

ethernet:
  type: W5500
  clk_pin: GPIO1
  mosi_pin: GPIO2
  miso_pin: GPIO41
  cs_pin: GPIO42
  interrupt_pin: GPIO43
  reset_pin: GPIO44


# ============================================================
# I2C
# ============================================================

i2c:
  - id: bus_a
    sda: 8
    scl: 18
    scan: true
    frequency: 400kHz


# ============================================================
# PCF8574 - Digital Inputs
# ============================================================

pcf8574:
  - id: pcf8574_hub_in_1
    i2c_id: bus_a
    address: 0x24


# ============================================================
# UART
# ============================================================

uart:

  # RS485 UART
  - id: uart_1
    baud_rate: 9600
    tx_pin: 39
    rx_pin: 38
    debug:
      direction: BOTH
      dummy_receiver: true
      after:
        timeout: 10ms

  # ARM CPU Motor Control UART
  # ESP32-S3 TX GPIO16 -> ARM RX
  # ESP32-S3 RX GPIO15 <- ARM TX
  # MODBUS RTU 115200 / 8N1
  - id: uart_motor
    baud_rate: 115200
    tx_pin: 16
    rx_pin: 15
    data_bits: 8
    parity: NONE
    stop_bits: 1


# ============================================================
# Global Motor Speed Variables
#
# Positive = Forward
# Negative = Reverse
# 0        = Stop
# ============================================================

globals:

  - id: motor1_speed
    type: int
    restore_value: no
    initial_value: '100'

  - id: motor2_speed
    type: int
    restore_value: no
    initial_value: '100'

  - id: motor3_speed
    type: int
    restore_value: no
    initial_value: '100'

  - id: motor4_speed
    type: int
    restore_value: no
    initial_value: '100'


# ============================================================
# Motor MODBUS Scripts
# ============================================================

script:

  # ----------------------------------------------------------
  # Motor Master Enable
  # Coil 503 = ON
  # ----------------------------------------------------------

  - id: motor_enable
    then:
      - lambda: |-
          uint8_t data[6] = {
            0x01, 0x05,
            0x01, 0xF7,
            0xFF, 0x00
          };

          uint16_t crc = 0xFFFF;

          for (int p = 0; p < 6; p++) {
            crc ^= data[p];

            for (int i = 0; i < 8; i++) {
              crc = (crc & 1)
                    ? (crc >> 1) ^ 0xA001
                    : crc >> 1;
            }
          }

          id(uart_motor).write_array(data, 6);

          uint8_t crc_data[2] = {
            (uint8_t)(crc & 0xFF),
            (uint8_t)(crc >> 8)
          };

          id(uart_motor).write_array(crc_data, 2);


  # ----------------------------------------------------------
  # Motor 1 - Register 2000
  # ----------------------------------------------------------

  - id: motor1_write
    mode: restart
    then:
      - lambda: |-
          int16_t speed = id(motor1_speed);

          uint8_t data[6] = {
            0x01, 0x06,
            0x07, 0xD0,
            (uint8_t)(speed >> 8),
            (uint8_t)speed
          };

          uint16_t crc = 0xFFFF;

          for (int p = 0; p < 6; p++) {
            crc ^= data[p];

            for (int i = 0; i < 8; i++) {
              crc = (crc & 1)
                    ? (crc >> 1) ^ 0xA001
                    : crc >> 1;
            }
          }

          id(uart_motor).write_array(data, 6);

          uint8_t crc_data[2] = {
            (uint8_t)(crc & 0xFF),
            (uint8_t)(crc >> 8)
          };

          id(uart_motor).write_array(crc_data, 2);


  # ----------------------------------------------------------
  # Motor 2 - Register 2001
  # ----------------------------------------------------------

  - id: motor2_write
    mode: restart
    then:
      - lambda: |-
          int16_t speed = id(motor2_speed);

          uint8_t data[6] = {
            0x01, 0x06,
            0x07, 0xD1,
            (uint8_t)(speed >> 8),
            (uint8_t)speed
          };

          uint16_t crc = 0xFFFF;

          for (int p = 0; p < 6; p++) {
            crc ^= data[p];

            for (int i = 0; i < 8; i++) {
              crc = (crc & 1)
                    ? (crc >> 1) ^ 0xA001
                    : crc >> 1;
            }
          }

          id(uart_motor).write_array(data, 6);

          uint8_t crc_data[2] = {
            (uint8_t)(crc & 0xFF),
            (uint8_t)(crc >> 8)
          };

          id(uart_motor).write_array(crc_data, 2);


  # ----------------------------------------------------------
  # Motor 3 - Register 2002
  # ----------------------------------------------------------

  - id: motor3_write
    mode: restart
    then:
      - lambda: |-
          int16_t speed = id(motor3_speed);

          uint8_t data[6] = {
            0x01, 0x06,
            0x07, 0xD2,
            (uint8_t)(speed >> 8),
            (uint8_t)speed
          };

          uint16_t crc = 0xFFFF;

          for (int p = 0; p < 6; p++) {
            crc ^= data[p];

            for (int i = 0; i < 8; i++) {
              crc = (crc & 1)
                    ? (crc >> 1) ^ 0xA001
                    : crc >> 1;
            }
          }

          id(uart_motor).write_array(data, 6);

          uint8_t crc_data[2] = {
            (uint8_t)(crc & 0xFF),
            (uint8_t)(crc >> 8)
          };

          id(uart_motor).write_array(crc_data, 2);


  # ----------------------------------------------------------
  # Motor 4 - Register 2003
  # ----------------------------------------------------------

  - id: motor4_write
    mode: restart
    then:
      - lambda: |-
          int16_t speed = id(motor4_speed);

          uint8_t data[6] = {
            0x01, 0x06,
            0x07, 0xD3,
            (uint8_t)(speed >> 8),
            (uint8_t)speed
          };

          uint16_t crc = 0xFFFF;

          for (int p = 0; p < 6; p++) {
            crc ^= data[p];

            for (int i = 0; i < 8; i++) {
              crc = (crc & 1)
                    ? (crc >> 1) ^ 0xA001
                    : crc >> 1;
            }
          }

          id(uart_motor).write_array(data, 6);

          uint8_t crc_data[2] = {
            (uint8_t)(crc & 0xFF),
            (uint8_t)(crc >> 8)
          };

          id(uart_motor).write_array(crc_data, 2);


# ============================================================
# Motor Speed Sliders
#
# 0   = Stop
# 100 = Full Speed
#
# Slider changes motor speed immediately.
# Current direction is retained.
# ============================================================

number:

  - platform: template
    name: "Motor 1 Speed"
    id: motor1_speed_slider
    min_value: 0
    max_value: 100
    step: 1
    initial_value: 100
    optimistic: true
    mode: slider
    set_action:
      - lambda: |-
          if (id(motor1_speed) < 0)
            id(motor1_speed) = -(int)x;
          else
            id(motor1_speed) = (int)x;
      - script.execute: motor1_write


  - platform: template
    name: "Motor 2 Speed"
    id: motor2_speed_slider
    min_value: 0
    max_value: 100
    step: 1
    initial_value: 100
    optimistic: true
    mode: slider
    set_action:
      - lambda: |-
          if (id(motor2_speed) < 0)
            id(motor2_speed) = -(int)x;
          else
            id(motor2_speed) = (int)x;
      - script.execute: motor2_write


  - platform: template
    name: "Motor 3 Speed"
    id: motor3_speed_slider
    min_value: 0
    max_value: 100
    step: 1
    initial_value: 100
    optimistic: true
    mode: slider
    set_action:
      - lambda: |-
          if (id(motor3_speed) < 0)
            id(motor3_speed) = -(int)x;
          else
            id(motor3_speed) = (int)x;
      - script.execute: motor3_write


  - platform: template
    name: "Motor 4 Speed"
    id: motor4_speed_slider
    min_value: 0
    max_value: 100
    step: 1
    initial_value: 100
    optimistic: true
    mode: slider
    set_action:
      - lambda: |-
          if (id(motor4_speed) < 0)
            id(motor4_speed) = -(int)x;
          else
            id(motor4_speed) = (int)x;
      - script.execute: motor4_write


# ============================================================
# Motor Control Buttons
# ============================================================

button:

  # Motor 1
  - platform: template
    name: "Motor 1 Forward"
    on_press:
      - script.execute: motor_enable
      - delay: 50ms
      - lambda: |-
          id(motor1_speed) =
            abs((int)id(motor1_speed_slider).state);
      - script.execute: motor1_write

  - platform: template
    name: "Motor 1 Reverse"
    on_press:
      - script.execute: motor_enable
      - delay: 50ms
      - lambda: |-
          id(motor1_speed) =
            -abs((int)id(motor1_speed_slider).state);
      - script.execute: motor1_write

  - platform: template
    name: "Motor 1 Stop"
    on_press:
      - lambda: |-
          id(motor1_speed) = 0;
      - script.execute: motor1_write


  # Motor 2
  - platform: template
    name: "Motor 2 Forward"
    on_press:
      - script.execute: motor_enable
      - delay: 50ms
      - lambda: |-
          id(motor2_speed) =
            abs((int)id(motor2_speed_slider).state);
      - script.execute: motor2_write

  - platform: template
    name: "Motor 2 Reverse"
    on_press:
      - script.execute: motor_enable
      - delay: 50ms
      - lambda: |-
          id(motor2_speed) =
            -abs((int)id(motor2_speed_slider).state);
      - script.execute: motor2_write

  - platform: template
    name: "Motor 2 Stop"
    on_press:
      - lambda: |-
          id(motor2_speed) = 0;
      - script.execute: motor2_write


  # Motor 3
  - platform: template
    name: "Motor 3 Forward"
    on_press:
      - script.execute: motor_enable
      - delay: 50ms
      - lambda: |-
          id(motor3_speed) =
            abs((int)id(motor3_speed_slider).state);
      - script.execute: motor3_write

  - platform: template
    name: "Motor 3 Reverse"
    on_press:
      - script.execute: motor_enable
      - delay: 50ms
      - lambda: |-
          id(motor3_speed) =
            -abs((int)id(motor3_speed_slider).state);
      - script.execute: motor3_write

  - platform: template
    name: "Motor 3 Stop"
    on_press:
      - lambda: |-
          id(motor3_speed) = 0;
      - script.execute: motor3_write


  # Motor 4
  - platform: template
    name: "Motor 4 Forward"
    on_press:
      - script.execute: motor_enable
      - delay: 50ms
      - lambda: |-
          id(motor4_speed) =
            abs((int)id(motor4_speed_slider).state);
      - script.execute: motor4_write

  - platform: template
    name: "Motor 4 Reverse"
    on_press:
      - script.execute: motor_enable
      - delay: 50ms
      - lambda: |-
          id(motor4_speed) =
            -abs((int)id(motor4_speed_slider).state);
      - script.execute: motor4_write

  - platform: template
    name: "Motor 4 Stop"
    on_press:
      - lambda: |-
          id(motor4_speed) = 0;
      - script.execute: motor4_write


# ============================================================
# RS485 Test Switch
# ============================================================

switch:

  - platform: uart
    uart_id: uart_1
    name: "RS485 Button"
    data: [0x11, 0x22, 0x33, 0x44, 0x55]


# ============================================================
# Digital Inputs
# ============================================================

binary_sensor:

  - platform: gpio
    name: "mt4v2-input01"
    id: mt4v2_input01
    pin:
      pcf8574: pcf8574_hub_in_1
      number: 0
      mode: INPUT
      inverted: true

  - platform: gpio
    name: "mt4v2-input02"
    id: mt4v2_input02
    pin:
      pcf8574: pcf8574_hub_in_1
      number: 1
      mode: INPUT
      inverted: true

  - platform: gpio
    name: "mt4v2-input03"
    id: mt4v2_input03
    pin:
      pcf8574: pcf8574_hub_in_1
      number: 2
      mode: INPUT
      inverted: true

  - platform: gpio
    name: "mt4v2-input04"
    id: mt4v2_input04
    pin:
      pcf8574: pcf8574_hub_in_1
      number: 3
      mode: INPUT
      inverted: true

  - platform: gpio
    name: "mt4v2-input05"
    id: mt4v2_input05
    pin:
      pcf8574: pcf8574_hub_in_1
      number: 4
      mode: INPUT
      inverted: true

  - platform: gpio
    name: "mt4v2-input06"
    id: mt4v2_input06
    pin:
      pcf8574: pcf8574_hub_in_1
      number: 5
      mode: INPUT
      inverted: true

  - platform: gpio
    name: "mt4v2-input07"
    id: mt4v2_input07
    pin:
      pcf8574: pcf8574_hub_in_1
      number: 6
      mode: INPUT
      inverted: true

  - platform: gpio
    name: "mt4v2-input08"
    id: mt4v2_input08
    pin:
      pcf8574: pcf8574_hub_in_1
      number: 7
      mode: INPUT
      inverted: true


  # GPIO inputs with pull-up resistors on PCB

  - platform: gpio
    name: "mt4v2-W1-io47"
    pin:
      number: 47
      inverted: true

  - platform: gpio
    name: "mt4v2-W1-io48"
    pin:
      number: 48
      inverted: true

  - platform: gpio
    name: "mt4v2-W1-io17"
    pin:
      number: 17
      inverted: true

  - platform: gpio
    name: "mt4v2-W1-io40"
    pin:
      number: 40
      inverted: true


  # ==========================================================
  # DRV8262 Fault Status
  #
  # Register 2020 = DRV8262 #1
  # Register 2021 = DRV8262 #2
  #
  # OFF = Normal
  # ON  = Problem
  # ==========================================================

  - platform: template
    name: "DRV8262-1 Fault"
    id: drv8262_1_fault
    device_class: problem

  - platform: template
    name: "DRV8262-2 Fault"
    id: drv8262_2_fault
    device_class: problem


# ============================================================
# ADS1115
# ============================================================

ads1115:
  - address: 0x48


# ============================================================
# Sensors
# ============================================================

sensor:

  # ADS1115 Channel 1
  - platform: ads1115
    multiplexer: A0_GND
    gain: 6.144
    resolution: 16_BITS
    name: "ADS1115 Channel A0-GND"
    update_interval: 5s

  # ADS1115 Channel 2
  - platform: ads1115
    multiplexer: A1_GND
    gain: 6.144
    name: "ADS1115 Channel A1-GND"
    update_interval: 5s

  # ADS1115 Channel 3
  - platform: ads1115
    multiplexer: A2_GND
    gain: 6.144
    name: "ADS1115 Channel A2-GND"
    update_interval: 5s

  # ADS1115 Channel 4
  - platform: ads1115
    multiplexer: A3_GND
    gain: 6.144
    name: "ADS1115 Channel A3-GND"
    update_interval: 5s


  # ==========================================================
  # Motor Current
  #
  # ARM MODBUS Registers:
  # 2010 = Motor 1 Current
  # 2011 = Motor 2 Current
  # 2012 = Motor 3 Current
  # 2013 = Motor 4 Current
  #
  # Values are displayed as raw register values.
  # ==========================================================

  - platform: template
    name: "Motor 1 Current"
    id: motor1_current
    accuracy_decimals: 0
    update_interval: never

  - platform: template
    name: "Motor 2 Current"
    id: motor2_current
    accuracy_decimals: 0
    update_interval: never

  - platform: template
    name: "Motor 3 Current"
    id: motor3_current
    accuracy_decimals: 0
    update_interval: never

  - platform: template
    name: "Motor 4 Current"
    id: motor4_current
    accuracy_decimals: 0
    update_interval: never


# ============================================================
# MODBUS Status Polling
#
# Every 2 seconds:
#
# Read 2010-2013 -> Motor Current
# Read 2020-2021 -> DRV8262 Fault
# ============================================================

interval:

  - interval: 2s
    then:

      # ======================================================
      # Read Motor Current
      #
      # FC03
      # Start Register = 2010
      # Quantity       = 4
      # ======================================================

      - lambda: |-

          // Clear old UART receive data
          while (id(uart_motor).available()) {
            uint8_t c;
            id(uart_motor).read_byte(&c);
          }

          // MODBUS request:
          // Slave 1
          // Function 03
          // Start address 2010 = 0x07DA
          // Read 4 registers

          uint8_t data[6] = {
            0x01, 0x03,
            0x07, 0xDA,
            0x00, 0x04
          };

          uint16_t crc = 0xFFFF;

          // Calculate MODBUS RTU CRC16
          for (int p = 0; p < 6; p++) {
            crc ^= data[p];

            for (int i = 0; i < 8; i++) {
              crc = (crc & 1)
                    ? (crc >> 1) ^ 0xA001
                    : crc >> 1;
            }
          }

          // Send MODBUS request
          id(uart_motor).write_array(data, 6);

          // Send CRC
          uint8_t crc_data[2] = {
            (uint8_t)(crc & 0xFF),
            (uint8_t)(crc >> 8)
          };

          id(uart_motor).write_array(crc_data, 2);


      # Wait for ARM CPU response
      - delay: 50ms


      # ======================================================
      # Process Motor Current Response
      # ======================================================

      - lambda: |-

          uint8_t rx[32];
          int len = 0;

          // Read UART response
          while (id(uart_motor).available() && len < 32) {
            id(uart_motor).read_byte(&rx[len]);
            len++;
          }

          // Expected response:
          //
          // 01 03 08
          // M1_H M1_L
          // M2_H M2_L
          // M3_H M3_L
          // M4_H M4_L
          // CRC_L CRC_H
          //
          // Total = 13 bytes

          if (len >= 13 &&
              rx[0] == 0x01 &&
              rx[1] == 0x03 &&
              rx[2] == 0x08) {

            uint16_t m1 =
              ((uint16_t)rx[3] << 8) | rx[4];

            uint16_t m2 =
              ((uint16_t)rx[5] << 8) | rx[6];

            uint16_t m3 =
              ((uint16_t)rx[7] << 8) | rx[8];

            uint16_t m4 =
              ((uint16_t)rx[9] << 8) | rx[10];

            // Publish values to ESPHome
            id(motor1_current).publish_state(m1);
            id(motor2_current).publish_state(m2);
            id(motor3_current).publish_state(m3);
            id(motor4_current).publish_state(m4);
          }


      # ======================================================
      # Read DRV8262 Fault Status
      #
      # FC03
      # Start Register = 2020
      # Quantity       = 2
      # ======================================================

      - lambda: |-

          // Clear UART receive buffer
          while (id(uart_motor).available()) {
            uint8_t c;
            id(uart_motor).read_byte(&c);
          }

          // MODBUS request:
          // Slave 1
          // Function 03
          // Start address 2020 = 0x07E4
          // Read 2 registers

          uint8_t data[6] = {
            0x01, 0x03,
            0x07, 0xE4,
            0x00, 0x02
          };

          uint16_t crc = 0xFFFF;

          // Calculate MODBUS RTU CRC16
          for (int p = 0; p < 6; p++) {
            crc ^= data[p];

            for (int i = 0; i < 8; i++) {
              crc = (crc & 1)
                    ? (crc >> 1) ^ 0xA001
                    : crc >> 1;
            }
          }

          // Send MODBUS request
          id(uart_motor).write_array(data, 6);

          // Send CRC
          uint8_t crc_data[2] = {
            (uint8_t)(crc & 0xFF),
            (uint8_t)(crc >> 8)
          };

          id(uart_motor).write_array(crc_data, 2);


      # Wait for ARM CPU response
      - delay: 50ms


      # ======================================================
      # Process DRV8262 Fault Response
      # ======================================================

      - lambda: |-

          uint8_t rx[16];
          int len = 0;

          // Read UART response
          while (id(uart_motor).available() && len < 16) {
            id(uart_motor).read_byte(&rx[len]);
            len++;
          }

          // Expected response:
          //
          // 01 03 04
          // Fault1_H Fault1_L
          // Fault2_H Fault2_L
          // CRC_L CRC_H
          //
          // Total = 9 bytes

          if (len >= 9 &&
              rx[0] == 0x01 &&
              rx[1] == 0x03 &&
              rx[2] == 0x04) {

            uint16_t fault1 =
              ((uint16_t)rx[3] << 8) | rx[4];

            uint16_t fault2 =
              ((uint16_t)rx[5] << 8) | rx[6];

            // 0 = Normal
            // Non-zero = Fault
            id(drv8262_1_fault).publish_state(
              fault1 != 0
            );

            id(drv8262_2_fault).publish_state(
              fault2 != 0
            );
          }


# ============================================================
# Web Server
# ============================================================

web_server:
  port: 80


# ============================================================
# OLED Font
# ============================================================

font:
  - file: "gfonts://Roboto"
    id: roboto
    size: 20


# ============================================================
# OLED Display
# ============================================================

display:

  - platform: ssd1306_i2c
    i2c_id: bus_a
    model: "SSD1306 128x64"
    address: 0x3C

    lambda: |-
      it.printf(
        0,
        0,
        id(roboto),
        "KinCony MT4v2"
      );
ESPHome yaml file download:

.txt   MT4v2-HA-Motor-Current-Without-Tuya.txt (Size: 22.74 KB / Downloads: 84)

Print this item