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 430 online users.
» 0 Member(s) | 411 Guest(s)
AhrefsBot, Amazonbot, Applebot, Baidu, Bing, Bytespider, Crawl, Google, PetalBot, bot

Latest Threads
Shipping costs new CT Cla...
Forum: N30
Last Post: Vega
45 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: 58
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 A8v3]-02 Read digital input ports state by XL9555
Posted by: admin - 11-20-2026, 02:58 AM - Forum: KC868-A8v3 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* Description:
* This Arduino program reads ports 8-15 of an XL9555 I/O expander
* and prints their states to the Serial Monitor. The state of
* each pin is represented as a bit in a 16-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
* - XL9555 I2C Address: 0x22
*/

#include "Arduino.h"
#include <Wire.h>
#include <PCA95x5.h>

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

// Set I2C address
PCA9555 xl9555_IN1; // XL9555 driver object
#define I2C_ADDRESS 0x22

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

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

    // Configure all ports as inputs; only ports 8-15 are read below.
    xl9555_IN1.attach(Wire, I2C_ADDRESS);
    xl9555_IN1.polarity(PCA95x5::Polarity::ORIGINAL_ALL);
    xl9555_IN1.direction(PCA95x5::Direction::IN_ALL);

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

void loop() {
    // Keep ports 8-15 in bits 8-15, as in the original program.
    // Bits 0-7 remain zero; do not shift the input states down.
    uint16_t state = xl9555_IN1.read() & 0xFF00;

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

    delay(500); // Delay 500ms
}

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

.zip   2-digital-input-9555.ino.merged.zip (Size: 194.13 KB / Downloads: 32)

Print this item

  [arduino code examples for A8v3]-01 Turn ON/OFF relay by XL9555 chip
Posted by: admin - 11-20-2026, 02:54 AM - Forum: KC868-A8v3 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* This program controls a 8-channel relay board via a XL9555 I/O expander.
* It sequentially turns on each relay and then turns them off in a loop.
*
* Pin Definitions:
* - SDA: GPIO 8
* - SCL: GPIO 18
*
* Delay Time:
* - 200 milliseconds between switching relays
*/

#include <Wire.h>        // Include the Wire library for I2C communication
#include <PCA95x5.h>     // XL9555 I/O expander driver

#define SDA 8           // Define the SDA pin
#define SCL 18          // Define the SCL pin
#define DELAY_TIME 200   // Define the delay time in milliseconds

// Set I2C address of the XL9555 module
#define I2C_ADDRESS 0x22 // I2C address of the XL9555 module

PCA9555 xl9555_R1; // Driver object for the XL9555

void setup() {
  // Initialize I2C communication
  Wire.begin(SDA, SCL); // SDA on GPIO 8, SCL on GPIO 18 (according to your board's configuration)
 
  // Initialize serial communication for debugging (optional)
  Serial.begin(115200);
  Serial.println("XL9555 Relay Control: Starting...");

  // Attach the XL9555 to the existing I2C bus.
  xl9555_R1.attach(Wire, I2C_ADDRESS);
  xl9555_R1.polarity(PCA95x5::Polarity::ORIGINAL_ALL);

  // Preload HIGH so active-low relays start OFF.
  xl9555_R1.write(PCA95x5::Level::H_ALL);

  // Ports 0-7 are relay outputs; ports 8-15 remain inputs.
  // Direction bits: 0 = output, 1 = input.
  xl9555_R1.direction(0xFF00);
}

void loop() {
  // Sequentially turn on each relay
  for (int i = 0; i < 8; i++) {
    xl9555_R1.write((PCA95x5::Port::Port)i, PCA95x5::Level::L);   // Turn on the relay at pin i (LOW means ON for the relay)
    delay(DELAY_TIME);          // Wait for DELAY_TIME milliseconds
  }

  // Sequentially turn off each relay
  for (int i = 0; i < 8; i++) {
    xl9555_R1.write((PCA95x5::Port::Port)i, PCA95x5::Level::H);  // Turn off the relay at pin i (HIGH means OFF for the relay)
    delay(DELAY_TIME);          // Wait for DELAY_TIME milliseconds
  }
}
arduino ino file download:

.zip   1-output-9555.zip (Size: 1.01 KB / Downloads: 32)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download:

.zip   1-output-9555.ino.merged.zip (Size: 193.91 KB / Downloads: 31)

Print this item

  ds3231 added to esphome, can help with configuration?
Posted by: riri0 - 11-19-2026, 01:07 PM - Forum: KC868-A16v3 - Replies (2)

ds3231 added to esphome 2026.11. I would like to use it.
https://esphome.io/components/ds3231/

Is there interrupt pin and 32khz pin?
Any recommended settings?

Print this item

Bug HAv2 + ESPHome - Avoiding Frame Collision
Posted by: phrfpeixoto - 11-18-2026, 11:17 PM - Forum: KC868-HA /HA v2 - Replies (4)

Hello there,

I have a home setup with 3 E16S boards running ESPHome. Each one is connected to a series of HAv2 breakout boards through the RS485 bus.

I'm using momentary switches very similar to the ones you sell, but they are from a different supplier.
Each wall switch has digital inputs (K1 to K6, dry contact) and digital outputs (D1 to D6 - LEDs).
LEDs go WHITE if I short Dx to GND. Otherwise, they stay AMBER

In the YAML (attached), I configure every Kx press to:
- Flip an output of the E16S
- Flip an output of an HAv2 (Dx) so that the LED is White/Ambar based on the relay state

The issue I'm having is inconsistent behavior between presses and LEDs. Sometimes presses are ignored.
With ChatGPT's help and logs, we've figured out that the issue happens due to collisions on the RS485 bus:
Repeated key presses collide with ESPHome's "reply" to flip the LED. This happens especially when:
- A kid spams a switch
- Someone presses two switches "at the same time"

Is there a way to avoid this collision? Can you implement bus access arbitration in HAv2?



Attached Files Thumbnail(s)
   
Image(s)
   

.txt   E16S YAML.txt (Size: 17.7 KB / Downloads: 39)
Print this item

  Does KCS v3 on CO16 operate as a BACnet client, or only as a BACnet server?
Posted by: jackmsf@gmail.com - 11-18-2026, 03:20 PM - Forum: CO16 - Replies (1)

I have questions below:

  1. Does KCS v3 on CO16 operate as a BACnet client, or only as a BACnet server?
  2. Can CO16 send Who-Is requests and receive I-Am responses?
  3. Can it read remote BACnet objects using ReadProperty  ReadPropertyMultiple, and write objects using WriteProperty, WritePropertyMultiple?
  4. Does it support BACnet/IP client operation and BACnet MS/TP master operation?

thanks

Jack

Print this item

  KCS debounce option for KC868-A16 v1.6
Posted by: tech1977 - 11-18-2026, 12:31 PM - Forum: KC868-A16 - Replies (3)

Hello,

I have a KC868-A16 running KCS v2.2.20,
integrated with Home Assistant via MQTT.

Input 16 reads an auxiliary contact of a latching relay (Finder 20.22)
to get the real ON/OFF state of a light. While the contact is closed
(input ON), I occasionally get a false OFF lasting 1-2 seconds, then
the input goes back to ON by itself. These glitches are published
immediately via MQTT.

I saw in this thread that you added an input debounce option
("input delay time") to the KCS v3 firmware for the KC868-A16v3:
https://www.kincony.com/forum/showthread.php?tid=9119

My questions:
1. Is there (or will there be) a KCS firmware with the same debounce
  option for the KC868-A16 with ESP32 (not v3)?
2. What is the maximum debounce time that can be set? In my case
  I would need about 2-3 seconds.
3. Is the debounce setting global or can it be set per input?
4. If I upgrade from KCS v2 to v3, do the MQTT topics and the JSON
  payload format (e.g. {"input16":{"value":true}}) stay the same?

Thank you!

Print this item

  [arduino code examples for F32]-02 Read digital input ports state by 9555 chip
Posted by: admin - 11-18-2026, 04:27 AM - Forum: F32 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
*
* Pin Definitions:
* - SDA: GPIO 8
* - SCL: GPIO 18
* - XL9555SS I2C Address: 0x24 for inputs 1-16, 0x26 for inputs 17-24, 0x27 for inputs 25-32
*/

#include "Arduino.h"
#include <Wire.h>
#include <PCA95x5.h>

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

PCA9555 inputIO1; // Address 0x24, ports 0-15: DI1-16
PCA9555 inputIO2; // Address 0x26, ports 0-7: DI17-24
PCA9555 inputIO3; // Address 0x27, ports 0-7: DI25-32

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

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

    // Configure the expanders for this standalone input test.
    inputIO1.attach(Wire, 0x24);
    inputIO1.polarity(PCA95x5::Polarity::ORIGINAL_ALL);
    inputIO1.direction(PCA95x5::Direction::IN_ALL);

    inputIO2.attach(Wire, 0x26);
    inputIO2.polarity(PCA95x5::Polarity::ORIGINAL_ALL);
    inputIO2.direction(PCA95x5::Direction::IN_ALL);

    inputIO3.attach(Wire, 0x27);
    inputIO3.polarity(PCA95x5::Polarity::ORIGINAL_ALL);
    inputIO3.direction(PCA95x5::Direction::IN_ALL);

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

void loop() {
    // Preserve the original channel positions in the 32-bit value.
    const uint32_t inputs1To16 = inputIO1.read();
    const uint32_t inputs17To24 = inputIO2.read() & 0x00FFU;
    const uint32_t inputs25To32 = inputIO3.read() & 0x00FFU;
    const uint32_t state = inputs1To16
                         | (inputs17To24 << 16)
                         | (inputs25To32 << 24);

    // Print the state of all 32 inputs in binary format
    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-9555.zip (Size: 915 bytes / Downloads: 47)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download:

.zip   2-digital-input-9555.ino.merged.zip (Size: 194.12 KB / Downloads: 44)

Print this item

  [arduino code examples for F32]-01 Turn ON/OFF relay by 9555 chip
Posted by: admin - 11-18-2026, 04:25 AM - Forum: F32 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* This program controls a 32-channel relay board via three XL9555SS I/O expanders.
* It sequentially turns on each relay and then turns them off in a loop.
*
* Pin Definitions:
* - SDA: GPIO 8
* - SCL: GPIO 18
*
* Delay Time:
* - 200 milliseconds between switching relays
*/

#include <Wire.h>        // Include the Wire library for I2C communication
#include <PCA95x5.h>     // XL9555SS I/O expander driver

#define SDA 8            // Define the SDA pin
#define SCL 18           // Define the SCL pin
#define DELAY_TIME 200   // Define the delay time in milliseconds

// Set I2C addresses of the XL9555SS modules
#define I2C_ADDRESS_R1 0x25 // I2C address of the first XL9555SS module
#define I2C_ADDRESS_R2 0x26 // I2C address of the second XL9555SS module
#define I2C_ADDRESS_R3 0x27 // I2C address of the second XL9555SS module

PCA9555 relayIO1; // Address 0x25, ports 0-15: relays 17-32
PCA9555 relayIO2; // Address 0x26, ports 8-15: relays 9-16
PCA9555 relayIO3; // Address 0x27, ports 8-15: relays 1-8

// Port indices for physical output channels 9-16 on address 0x26.
constexpr uint8_t RELAY_PORTS_9_TO_16[] = {12, 13, 14, 15, 8, 9, 10, 11};

void setup() {
  // Initialize I2C communication
  Wire.begin(SDA, SCL); // SDA on GPIO 8, SCL on GPIO 18 (according to your board's configuration)
 
  // Initialize serial communication for debugging (optional)
  Serial.begin(115200);
  Serial.println("XL9555SS Relay Control: Starting...");

  // Preload HIGH before enabling the active-low relay outputs.
  relayIO1.attach(Wire, I2C_ADDRESS_R1);
  relayIO1.write(PCA95x5::Level::H_ALL);
  relayIO1.polarity(PCA95x5::Polarity::ORIGINAL_ALL);
  relayIO1.direction(PCA95x5::Direction::OUT_ALL);

  relayIO2.attach(Wire, I2C_ADDRESS_R2);
  relayIO2.write(PCA95x5::Level::H_ALL);
  relayIO2.polarity(PCA95x5::Polarity::ORIGINAL_ALL);
  relayIO2.direction(0x00FF); // Ports 0-7: inputs; ports 8-15: outputs.

  relayIO3.attach(Wire, I2C_ADDRESS_R3);
  relayIO3.write(PCA95x5::Level::H_ALL);
  relayIO3.polarity(PCA95x5::Polarity::ORIGINAL_ALL);
  relayIO3.direction(0x00FF); // Ports 0-7: inputs; ports 8-15: outputs.

}

void loop() {
  // Sequentially turn on each relay (1-32)

  // First control the relays on the second XL9555SS (relays 1-8, corresponding to pins 8-15)
  for (int i = 8; i < 16; i++) {
    relayIO3.write(static_cast<PCA95x5::Port::Port>(i), PCA95x5::Level::L);   // Turn on the relay at pin i (LOW means ON for the relay)
    delay(DELAY_TIME);          // Wait for DELAY_TIME milliseconds
  }

  // First control the relays on the second XL9555SS (relays 9-16, corresponding to pins 8-15)
  for (uint8_t port : RELAY_PORTS_9_TO_16) {
    relayIO2.write(static_cast<PCA95x5::Port::Port>(port), PCA95x5::Level::L);   // Turn on the relay at pin i (LOW means ON for the relay)
    delay(DELAY_TIME);          // Wait for DELAY_TIME milliseconds
  }

  // Then control the relays on the first XL9555SS (relays 17-32)
  for (int i = 0; i < 16; i++) {
    relayIO1.write(static_cast<PCA95x5::Port::Port>(i), PCA95x5::Level::L);   // Turn on the relay at pin i (LOW means ON for the relay)
    delay(DELAY_TIME);          // Wait for DELAY_TIME milliseconds
  }

  // Sequentially turn off each relay (1-32)
 
  // First control the relays on the second XL9555SS (relays 1-8, corresponding to pins 8-15)
  for (int i = 8; i < 16; i++) {
    relayIO3.write(static_cast<PCA95x5::Port::Port>(i), PCA95x5::Level::H);   // Turn on the relay at pin i (LOW means ON for the relay)
    delay(DELAY_TIME);          // Wait for DELAY_TIME milliseconds
  }

  // First control the relays on the second XL9555SS (relays 9-16, corresponding to pins 8-15)
  for (uint8_t port : RELAY_PORTS_9_TO_16) {
    relayIO2.write(static_cast<PCA95x5::Port::Port>(port), PCA95x5::Level::H);  // Turn off the relay at pin i (HIGH means OFF for the relay)
    delay(DELAY_TIME);          // Wait for DELAY_TIME milliseconds
  }

  // Then control the relays on the first XL9555SS (relays 17-32)
  for (int i = 0; i < 16; i++) {
    relayIO1.write(static_cast<PCA95x5::Port::Port>(i), PCA95x5::Level::H);  // Turn off the relay at pin i (HIGH means OFF for the relay)
    delay(DELAY_TIME);          // Wait for DELAY_TIME milliseconds
  }
}
arduino ino file download:

.zip   1-relay-9555.zip (Size: 1.28 KB / Downloads: 56)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download:

.zip   1-relay-9555.ino.merged.zip (Size: 194.06 KB / Downloads: 48)

Print this item

  N20 energy
Posted by: pheerink@gmail.com - 11-17-2026, 03:57 PM - Forum: N20 - Replies (3)

Hello KinCony support,

I am using a KinCony N20 AC Energy Meter (order number: 4643, firmware/ESPHome version: 3.27.2) with Home Assistant. I have two problems with it, and I would like to ask for a solution or a replacement unit.

1. Correct power measurement is not possible in my 3-phase installation
My house has a 3-phase supply (L1, L2, L3). The N20 has only two voltage inputs (L1/N1 and L2/N2). At the moment I have connected one phase and bridged it to the second voltage input. The channels on the same phase as the voltage input show plausible power (W). The channels on the other phases show wrong active power. For example, my induction hob on standby (only capacitive current from its mains filter) reads about 60–70 W, with a power factor of exactly 0.87. That is what you would expect from the 120° phase shift between the CT and the voltage reference.
Even if I connect the two voltage inputs to two different phases, the circuits on the third phase still cannot be measured correctly.
Question: is there a firmware option or hardware version of the N20 (or another KinCony product) that measures all three phases correctly with 20 channels?

2. Energy (kWh) is always 0
All 20 channel energy sensors (energyX_chY.energy) and both energy_total sensors stay at 0.0, even though power and current are measured and change normally. The energy table on the device is also empty. So the device does not count energy at all.
Question: is this a known firmware issue, and how can I fix it?

I have seen in other replies on your forum that you sent a new unit to customers with similar problems. I would like to ask for the same: a replacement unit that supports my 3-phase installation and measures energy (kWh) correctly. If you need logs, screenshots or my ESPHome configuration, I am happy to send them.

Thank you in advance.

Kind regards,
Pauk Heerink

Print this item

  [arduino code examples for CO16]-15 Web Service Demo
Posted by: admin - 11-17-2026, 04:33 AM - Forum: CO16 - No Replies

Code:
/* Made by KinCony IoT: https://www.kincony.com
* CO16 WEB STUDIO v1.0 | ESP32-S3 | Arduino-ESP32 3.x
* SPI2: W5500. SPI3: native ST7789 driver from the working CO16 demo.
* No Wi-Fi, cloud, CDN, filesystem upload, or simulated sensor readings.
*/
#include <Arduino.h>
#include <Wire.h>
#include <ETH.h>
#include <WebServer.h>
#include <math.h>
#include "Config.h"
#include "CO16_Display.h"
#include "WebUI.h"

WebServer server(80);
Co16St7789 display;
GFXcanvas16 canvas(320,240);
constexpr uint8_t ADC_ADDR[]={0x48,0x49,0x4B,0x4A};
uint16_t relayMask=0, inputMask=0;
bool relayOK=false, inputOK=false, eepromOK=false, rtcOK=false;
bool adcOK[16]={}, pending[4]={};
float values[16]={}, adcPin[16]={}, eased[16]={};
uint32_t sampleAt[16]={};
volatile bool networkReady=false;
bool ethernetStarted=false, webStarted=false, tftOK=false;
bool chase=false;
uint8_t chaseStep=0, mux=0, focusChannel=0;
uint32_t chaseAt=0, adcAt=0, lastIO=0, lastFrame=0, lastDiag=0, lastClient=0;
bool settling=false;
String rtcText="Unavailable";
const uint16_t BG=0x0023, GRID=0x1149, DIM=0x6BD0, CYAN=0x07FF, WHITE=0xEFFF, PINK=0xF81F;

bool writeReg(uint8_t addr,uint8_t reg,uint16_t value,bool msbFirst) {
  Wire.beginTransmission(addr); Wire.write(reg);
  Wire.write(msbFirst ? value>>8 : value&255);
  Wire.write(msbFirst ? value&255 : value>>8);
  return Wire.endTransmission()==0;
}
bool readBytes(uint8_t addr,uint8_t reg,uint8_t *data,uint8_t count) {
  Wire.beginTransmission(addr); Wire.write(reg);
  if(Wire.endTransmission(false)!=0) return false;
  if(Wire.requestFrom(addr,count)!=count) { while(Wire.available()) Wire.read(); return false; }
  for(uint8_t i=0;i<count;i++) data[i]=Wire.read();
  return true;
}
bool readADC(uint8_t addr,uint8_t reg,uint16_t &value) {
  uint8_t bytes[2]; if(!readBytes(addr,reg,bytes,2))return false;
  value=(uint16_t(bytes[0])<<8)|bytes[1]; return true;
}
bool ping(uint8_t addr) { Wire.beginTransmission(addr);return Wire.endTransmission()==0; }
bool setRelays(uint16_t mask) {
  uint16_t bits=RELAY_ACTIVE_LOW?uint16_t(~mask):mask;
  Wire.beginTransmission(0x22); Wire.write(uint8_t(bits)); Wire.write(uint8_t(bits>>8));
  relayOK=Wire.endTransmission()==0;
  if(relayOK)relayMask=mask;
  return relayOK; // Command acknowledged, not contact feedback.
}
void stopChase() { chase=false; }
void serviceInputs() {
  // Reconfigure after temporary power loss; XL9555 uses paired little-endian registers.
  bool configured=writeReg(0x24,6,0xFFFF,false) && writeReg(0x24,4,0,false);
  uint8_t b[2]; inputOK=configured && readBytes(0x24,0,b,2);
  if(inputOK) { uint16_t raw=uint16_t(b[0])|(uint16_t(b[1])<<8); inputMask=INPUT_ACTIVE_LOW?uint16_t(~raw):raw; }
}
uint16_t adcConfig(uint8_t channel) { return 0x8000 | (uint16_t(4+channel)<<12) | 0x0283; }
void serviceADC() {
  if(!settling) {
    for(uint8_t b=0;b<4;b++) {
      pending[b]=writeReg(ADC_ADDR[b],1,adcConfig(mux),true);
      if(!pending[b])adcOK[b*4+mux]=false;
    }
    adcAt=millis();settling=true;return;
  }
  if(millis()-adcAt<30)return;
  for(uint8_t b=0;b<4;b++) {
    uint8_t i=b*4+mux; uint16_t cfg,raw;
    bool ok=pending[b] && readADC(ADC_ADDR[b],1,cfg) && ((cfg&0x7FFF)==(adcConfig(mux)&0x7FFF)) && readADC(ADC_ADDR[b],0,raw);
    adcOK[i]=ok;
    if(ok) {
      adcPin[i]=int16_t(raw)*0.000125f;
      values[i]=ANALOG_MODE[i]?adcPin[i]:(adcPin[i]<=0.0025f?0:adcPin[i]*VOLTAGE_MULTIPLIER);
      sampleAt[i]=millis();
    }
  }
  mux=(mux+1)&3;settling=false;
}
bool validADC(uint8_t i) { return adcOK[i] && millis()-sampleAt[i]<2000; }
uint8_t bcd(uint8_t v) {return (v>>4)*10+(v&15);}
void diagnostics() {
  eepromOK=ping(0x50);
  uint8_t d[7],status;
  rtcOK=readBytes(0x68,0,d,7) && readBytes(0x68,15,&status,1);
  if(!rtcOK) {rtcText="Unavailable";return;}
  if(status&0x80) {rtcText="Clock not set (OSF)";return;}
  uint8_t hour=(d[2]&0x40)?(bcd(d[2]&0x1F)%12+((d[2]&0x20)?12:0)):bcd(d[2]&0x3F);
  char s[32];snprintf(s,sizeof(s),"%04u-%02u-%02u %02u:%02u:%02u",2000+bcd(d[6])+((d[5]&128)?100:0),bcd(d[5]&31),bcd(d[4]&63),hour,bcd(d[1]&127),bcd(d[0]&127));
  rtcText=s;
}
void onNetwork(arduino_event_id_t event) {
  if(event==ARDUINO_EVENT_ETH_START)ETH.setHostname("kincony-co16");
  if(event==ARDUINO_EVENT_ETH_GOT_IP)networkReady=true;
  if(event==ARDUINO_EVENT_ETH_LOST_IP || event==ARDUINO_EVENT_ETH_DISCONNECTED || event==ARDUINO_EVENT_ETH_STOP)networkReady=false;
}
void jsonReply(int code,const String &body) {server.sendHeader("Cache-Control","no-store");server.send(code,"application/json",body);}
bool commandAllowed() {
  if(server.header("X-CO16")!="demo") {jsonReply(403,"{\"error\":\"Missing demo header\"}");return false;}
  return true;
}
void stateAPI() {
  lastClient=millis();
  String s; s.reserve(2600);
  s="{\"ip\":\""+ETH.localIP().toString()+"\",\"uptime\":"+String(millis()/1000)+",\"heap\":"+String(ESP.getFreeHeap());
  s+=",\"relays\":"+String(relayMask)+",\"inputs\":"+String(inputMask)+",\"relayOK\":"+String(relayOK?"true":"false")+",\"inputOK\":"+String(inputOK?"true":"false");
  s+=",\"chase\":"+String(chase?"true":"false")+",\"rtcOK\":"+String(rtcOK?"true":"false")+",\"eepromOK\":"+String(eepromOK?"true":"false")+",\"rtc\":\""+rtcText+"\",\"adc\":[";
  for(uint8_t i=0;i<16;i++) {
    if(i)s+=',';
    s+="{\"v\":"+(validADC(i)?String(values[i],4):String("null"))+",\"raw\":"+(validADC(i)?String(adcPin[i],5):String("null"))+",\"mode\":"+String(ANALOG_MODE[i])+"}";
  }
  s+="]}";jsonReply(200,s);
}
void commandAPI() {
  if(!commandAllowed())return;
  String action=server.arg("action");bool ok=true;
  if(action=="relay") {
    String c=server.arg("ch"), v=server.arg("on");int ch=c.toInt();
    if(ch<1||ch>16||c!=String(ch)||(v!="0"&&v!="1")) {jsonReply(400,"{\"error\":\"Invalid channel/state\"}");return;}
    stopChase();uint16_t bit=uint16_t(1)<<(ch-1);
    ok=setRelays(v=="1"?relayMask|bit:relayMask&~bit);
  } else if(action=="off") {stopChase();ok=setRelays(0);}
  else if(action=="on") {stopChase();ok=setRelays(0xFFFF);}
  else if(action=="chase") {
    stopChase();ok=setRelays(0);if(ok){chase=true;chaseStep=0;chaseAt=millis()-500;lastClient=millis();}
  } else {jsonReply(400,"{\"error\":\"Unknown action\"}");return;}
  jsonReply(ok?200:503,ok?"{\"ok\":true}":"{\"error\":\"Relay I2C write failed; state unknown\"}");
}
void setupWeb() {
  const char* headers[]={"X-CO16"};server.collectHeaders(headers,1);
  server.on("/",HTTP_GET,[]{server.sendHeader("Cache-Control","no-cache");server.send_P(200,"text/html; charset=utf-8",WEB_HTML);});
  server.on("/api/state",HTTP_GET,stateAPI);
  server.on("/api/control",HTTP_POST,commandAPI);
  server.onNotFound([]{server.send(404,"text/plain","Not found");});
  server.begin();webStarted=true;
}
float ratio(uint8_t i) {return fminf(1,fmaxf(0,eased[i]/(ANALOG_MODE[i]?4.096f:10.0f)));}
void label(int x,int y,int size,uint16_t color,const String &s) {canvas.setCursor(x,y);canvas.setTextSize(size);canvas.setTextColor(color);canvas.print(s);}
void drawScreen(uint32_t now) {
  if(!tftOK)return;
  canvas.fillScreen(BG);
  label(10,8,2,WHITE,"KinCony");label(221,11,1,CYAN,"CO16 / LIVE");
  canvas.drawFastHLine(10,31,300,GRID);canvas.drawFastHLine(10+(now/12)%260,31,40,CYAN);
  label(10,42,1,DIM,networkReady?"OPEN IN YOUR BROWSER":"ETHERNET / CONNECT TO ROUTER");
  label(10,58,2,networkReady?CYAN:PINK,networkReady?ETH.localIP().toString():(!ethernetStarted?"ETH INIT ERROR":ETH.linkUp()?"Waiting DHCP...":"Plug in LAN cable"));
  uint8_t best=focusChannel;
  for(uint8_t i=0;i<16;i++) {
    eased[i]+=(values[i]-eased[i])*.25f;
    if(validADC(i)&&(!validADC(best)||ratio(i)>ratio(best)+.03f))best=i;
  }
  focusChannel=best;
  const int cx=63,cy=133;
  for(int j=0;j<=44;j++) {
    float a=(140+j*6.0f)*PI/180;
    uint16_t color=validADC(best)&&j<=ratio(best)*44?CYAN:GRID;
    canvas.drawLine(cx+cosf(a)*41,cy+sinf(a)*41,cx+cosf(a)*34,cy+sinf(a)*34,color);
  }
  label(35,111,1,DIM,"CH "+String(best+1));
  label(29,129,2,WHITE,validADC(best)?String(values[best],2):"--.--");
  label(43,151,1,CYAN,ANALOG_MODE[best]?"ADC V":"VOLTS");
  for(int i=0;i<16;i++) {
    int x=119+i*12,h=validADC(i)?int(ratio(i)*64):0;
    canvas.drawFastVLine(x,100,67,GRID);
    if(h)canvas.fillRect(x,167-h,7,h,i<8?CYAN:PINK);
    if(!validADC(i))label(x,143,1,PINK,"!");
  }
  label(118,88,1,DIM,"16 ANALOG INPUTS");
  label(118,174,1,DIM,"01                  16");
  label(10,194,1,DIM,"OUT");label(10,213,1,DIM,"IN");
  for(int i=0;i<16;i++) {
    canvas.fillRoundRect(40+i*17,191,12,12,2,relayOK?((relayMask>>i)&1?PINK:GRID):DIM);
    canvas.fillCircle(46+i*17,216,4,inputOK?((inputMask>>i)&1?CYAN:GRID):DIM);
  }
  label(10,232,1,DIM,"kincony.com");label(193,232,1,chase?PINK:CYAN,chase?"RELAY CHASE":"WEB STUDIO / v1");
  display.present(canvas.getBuffer());
}
void setup() {
  Serial.begin(115200);
  const uint8_t inactiveCS[]={4,9,13,14,42};
  for(uint8_t pin:inactiveCS){digitalWrite(pin,HIGH);pinMode(pin,OUTPUT);}
  Wire.begin(8,18);Wire.setClock(100000);Wire.setTimeOut(20);
  setRelays(0);serviceInputs(); // No power-on relay sequence.
  tftOK=canvas.getBuffer() && display.begin();canvas.setTextWrap(false);
  Network.onEvent(onNetwork);
  ethernetStarted=ETH.begin(ETH_PHY_W5500,1,42,43,44,SPI2_HOST,1,41,2);
  if(ethernetStarted && USE_STATIC_IP)ETH.config(STATIC_IP,GATEWAY,SUBNET);
  Serial.println("CO16 WEB STUDIO: connect Ethernet to a DHCP router; read IP on LCD.");
  diagnostics();drawScreen(millis());
}
void loop() {
  uint32_t now=millis();
  if(networkReady && !webStarted) {setupWeb();Serial.println("Open http://"+ETH.localIP().toString());}
  if(webStarted)server.handleClient();
  serviceADC();
  if(now-lastIO>=100){lastIO=now;serviceInputs();}
  if(now-lastDiag>=1000){lastDiag=now;diagnostics();}
  now=millis();
  if(chase && (!networkReady || now-lastClient>4000)) {stopChase();setRelays(0);}
  if(chase && now-chaseAt>=500) {
    chaseAt=now;
    if(chaseStep>=16){stopChase();setRelays(0);}
    else if(!setRelays(uint16_t(1)<<chaseStep++)){stopChase();setRelays(0);}
  }
  if(now-lastFrame>=TFT_FRAME_MS){lastFrame=now;drawScreen(now);}
  delay(1);
}
arduino ino file and BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download:

.zip   15-CO16_Web_Demo.zip (Size: 7.04 MB / Downloads: 42)
   
   
   

Print this item