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

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 10,491
» Latest member: lodeonlinezcom
» Forum threads: 4,329
» Forum posts: 21,322

Full Statistics

Online Users
There are currently 965 online users.
» 0 Member(s) | 949 Guest(s)
AhrefsBot, Amazonbot, Applebot, Baidu, Bytespider, Crawl, Google, bot

Latest Threads
[Arduino source code for ...
Forum: KC868-A2
Last Post: admin
Yesterday, 12:04 PM
» Replies: 8
» Views: 1,850
B4 water tank controller
Forum: B4
Last Post: Armsp0
Yesterday, 04:39 AM
» Replies: 0
» Views: 22
Automatic Modbus Sensor p...
Forum: "KCS" v3 firmware
Last Post: admin
11-09-2026, 11:43 PM
» Replies: 1
» Views: 21
Can the digital inputs ac...
Forum: KC868-A16S
Last Post: admin
11-08-2026, 09:27 PM
» Replies: 1
» Views: 29
No AP appears
Forum: KC868-A6
Last Post: admin
11-08-2026, 12:38 AM
» Replies: 8
» Views: 2,962
kc868-a6 analog input
Forum: KC868-A6
Last Post: admin
11-06-2026, 09:56 AM
» Replies: 3
» Views: 422
F24 ESPHome yaml for home...
Forum: F24
Last Post: admin
11-06-2026, 07:25 AM
» Replies: 0
» Views: 46
[arduino code examples fo...
Forum: F24
Last Post: admin
11-06-2026, 05:35 AM
» Replies: 0
» Views: 43
[arduino code examples fo...
Forum: F24
Last Post: admin
11-06-2026, 05:33 AM
» Replies: 0
» Views: 38
KC868-A4 – Relay 1 clicks...
Forum: KC868-A series and Uair Smart Controller
Last Post: admin
11-03-2026, 11:58 PM
» Replies: 3
» Views: 127

Big Grin B4 water tank controller
Posted by: Armsp0 - Yesterday, 04:39 AM - Forum: B4 - No Replies

We recently completed the installation of a water transfer system between two potable water storage tanks at a remote holiday home and based the control system on a Kincony B4 controller.

One tank is drawn from for a pumped house supply, the second storage tank collects water but had only a manual transfer system to move water to the main house tank for use if the main tank levels were low. This meant access at height to the tank tops to remove bolted down concrete tank lids then reinstatement of the heavy lids on completion of transfer. This work was too physically demanding for the owner and also presented significant safety hazards

The owner wished to have a submersible pump permanently installed in the second storage tank to pump water over to the house tank. The brief was that a web enabled transfer system would operate automatically to transfer at tuneable levels along with a manual override function. Protection logic was to be implemented to prevent transfer operations if water was below critical levels in the storage tank, above high level in the main tank and provide notifications of system faults and low levels in either tank.

A Kincony B4 controller was chosen and custom firmware developed to suit the specification. Integration with Home Assistant allowed sophisticated graphical representation of the water system with a user HMI and of course, remote access. Home Assistant could have been used to provide the entire control functionality but in line with the proven industrial DCS (Distributed Control System) philosophy an autonomous system was preferred. The important role of system monitoring and critical notifications is also provided by Home Assistant.

After installation and commissioning and handover to the owner, operation was monitored for a time for issues and the system has been working without problems to date. 

Thanks for a great product Kincony, we have a few installations of these systems completed now and we plan many more. We presently offer controllers for Potable water, Wastewater and Swimming Pools. One system operates over a LoRa communications bridge which solved a difficult installation problem where cabling was impractical and WiFi beyond range.

Print this item

  Automatic Modbus Sensor polling fails with ESP_ERR_INVALID_STATE
Posted by: PrivatePerson - 11-09-2026, 06:14 PM - Forum: "KCS" v3 firmware - Replies (1)

KC868-A16 V3 – Automatic Modbus Sensor polling fails with ESP_ERR_INVALID_STATE (KCS v3.27.2)

Hello KinCony team,
I need help troubleshooting an issue with automatic Modbus RTU sensor polling on my KC868-A16 V3 controller.

1. Hardware and firmware
• Controller: KinCony KC868-A16 V3
• Firmware: KCS v3.27.2
• Build date: September 10, 2026
• Sensor: Water Quality pH + EC Sensor
• Communication: RS485 Modbus RTU
• Sensor supply voltage: 12–24V DC
• Modbus slave address: 1
• Baud rate: 9600
Serial settings: 9600, 8 data bits, no parity, 1 stop bit (8N1).

2. Sensor configuration in KCS
I configured two standard Modbus sensors:
Sensor 1 – pH
• Type: Modbus
• Slave Address: 1
• Function Code: 03 Holding Register
• Register Address: 0
• Data Type: uint16
• Byte Order: ABCD
• Multiplier: 0.01
• Unit: pH
Sensor 2 – EC
• Type: Modbus
• Slave Address: 1
• Function Code: 03 Holding Register
• Register Address: 1
• Data Type: uint16
• Byte Order: ABCD
• Multiplier: 1
Both registers belong to the same physical sensor.

3. Manual Modbus Master works correctly
Using the built-in Modbus Master page, I can successfully read both registers with one request.
Settings:
• Interface: RS485 RTU
• Slave ID: 1
• Function: FC03
• Start address: 0
• Quantity: 2
• Baud rate: 9600
• Data bits: 8
• Parity: None
• Stop bits: 1
• Display: UInt16
• Byte order: ABCD
Successful response:
• Register 0: 703 (pH = 7.03)
• Register 1: 59 (EC raw value)
Transaction completed successfully. Response latency: 236 ms.
This confirms that the sensor, wiring, Modbus address and serial communication work correctly when using Modbus Master.

4. Automatic sensor polling fails
In the KCS Logs, I repeatedly receive:
standard_modbus_sensor read error, id=0 err=ESP_ERR_INVALID_STATE
standard_modbus_sensor read error, id=1 err=ESP_ERR_INVALID_STATE
After repeated failures, the logs also show:
sensor id=0 read err too much, need reinit
sensor id=1 read err too much, need reinit
The Monitor page displays — instead of sensor values.
The same error occurs after restarting the controller.

5. Additional tests performed
I have already tried:
1. Power cycling the controller.
2. Checking the RS485 wiring and tightening the GND connection.
3. Using separate power supplies for the controller and sensor.
4. Verifying the sensor settings and Modbus register addresses.
5. Testing manual Modbus communication repeatedly — it works.
6. Disabling Sensor 2 (EC) and testing only Sensor 1 (pH). The same ESP_ERR_INVALID_STATE error still occurs.
7. Keeping General RS485 disabled.
Enabling General RS485 previously caused the controller to become unresponsive / lose Wi-Fi, so I am currently keeping it disabled.

6. Questions for KinCony developers
1. Is there a known issue with standard_modbus_sensor initialization or automatic polling in KCS v3.27.2 on KC868-A16 V3?
2. Does the automatic sensor driver use the same UART/RS485 interface as the built-in Modbus Master?
3. Can General RS485 conflict with the automatic Modbus sensor driver?
4. Is there a recommended configuration for reading two registers from one third-party Modbus RTU device?
5. Is there a newer firmware or beta firmware that fixes this issue?

Could you please provide a recommended configuration, troubleshooting steps, or a firmware version that resolves this problem?
I can provide additional screenshots, logs and configuration details if needed.
Thank you for your help!

Print this item

  Can the digital inputs accept a 24V DC signal from a gate controller?
Posted by: gmfr17 - 11-08-2026, 01:23 PM - Forum: KC868-A16S - Replies (1)

Hello,

I'm planning to use a KC868-A16S with ESPHome and Home Assistant, and I would like to confirm that I can connect the 24V DC status output of my motorized gate controller to one of the digital inputs.

Signal source (gate controller DEA NET24N, terminals 12-13 "WARNING"):

  • Output: 24V DC, max 15 W (designed to drive a gate-status lamp)
  • Depending on a parameter, it is either steady while the gate is open, or flashing while the gate is moving
  • It is a power-type output meant for a lamp, not a low-current logic signal
  • I only need to read this one signal (1 input used)

My questions:
  1. Can the optocoupled inputs (IN1 to IN16) accept 24V DC directly? Is this within the rated limits of the optocoupler and input circuit?
  2. What is the maximum input voltage you recommend or guarantee on these inputs?
  3. The inputs share a common by group of 8. Should I connect the gate controller's 0V to this common? Is this common isolated from the board's 12V supply ground, or are they tied together?
  4. Is the response time of the inputs and the PCF8574 path suitable for detecting a signal flashing at about 1 to 2 Hz?
  5. Since the source is a lamp output that may show voltage spikes or ripple (it is not a regulated logic signal), would you recommend any protection on the input (series resistor, TVS diode)?
If direct connection is not recommended, I was thinking of using an external relay with a 24V DC coil (Finder 40.52) driven by the gate signal, with its dry contact switching the 12V from the board's supply to the input. Would you consider this the safer approach?

Thank you very much for your help.
Best regards,
GM from France (I used some help from an AI as English is not my native language)

Print this item

  F24 ESPHome yaml for home assistant by XL9555 chip
Posted by: admin - 11-06-2026, 07:25 AM - Forum: F24 - No Replies

Code:
esphome:
  name: f24
  friendly_name: f24
  platformio_options:
    board_build.extra_flags:
      # WIFI_CONTROL_SELF_MODE = 0
      # WIFI_CONTROL_SELF_MODE = 1
      - "-DWIFI_CONTROL_SELF_MODE=1"
esp32:
  board: esp32-s3-devkitc-1
  framework:
    type: esp-idf
   

external_components:
  - source:
      type: git
      url: https://github.com/hzkincony/esphome-tuya-wifi-mcu
      ref: v1.4.0

# Enable logging

  # hardware_uart: USB_SERIAL_JTAG
# Enable Home Assistant API
api:
  encryption:
    key: "WeVOuL5oNhjXcfzXtTirlOwvtWvCD5yqIxd3oV4es1k="

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

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

pca9554:
  - id: 'xl9555_hub_out_1'  # for output channel 9-24
    i2c_id: bus_a
    address: 0x25
    pin_count: 16

  - id: 'xl9555_hub_in_1'  # for digital input channel 1-16
    i2c_id: bus_a
    address: 0x24
    pin_count: 16

  - id: 'xl9555_hub_out_in_2'  # for output channel 1-8  + (input 17-24)
    i2c_id: bus_a
    address: 0x26
    pin_count: 16

uart:
  - id: uart_1    #RS485
    baud_rate: 9600
    debug:
      direction: BOTH
      dummy_receiver: true
      after:
        timeout: 10ms
    tx_pin: 16
    rx_pin: 17

  - id: tuya_mcu_uart
    tx_pin: GPIO39
    rx_pin: GPIO38
    baud_rate: 9600

tuya_wifi_mcu:
  # tuya mcu product id
  product_id: cchos3g1j2ucfbyd
  uart_id: tuya_mcu_uart
  wifi_reset_pin: 28
  wifi_led_pin: 16

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

  - platform: gpio
    name: "f24-output01"
    id: "f24_output01"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 12
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output1-tuya
    dp_id: 1
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output01"

  - platform: gpio
    name: "f24-output02"
    id: "f24_output02"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 13
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output2-tuya
    dp_id: 2
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output02"

  - platform: gpio
    name: "f24-output03"
    id: "f24_output03"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 14
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output3-tuya
    dp_id: 3
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output03"

  - platform: gpio
    name: "f24-output04"
    id: "f24_output04"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 15
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output4-tuya
    dp_id: 4
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output04"

  - platform: gpio
    name: "f24-output05"
    id: "f24_output05"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 8
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output5-tuya
    dp_id: 5
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output05"

  - platform: gpio
    name: "f24-output06"
    id: "f24_output06"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 9
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output6-tuya
    dp_id: 6
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output06"

  - platform: gpio
    name: "f24-output07"
    id: "f24_output07"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 10
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output7-tuya
    dp_id: 101
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output07"

  - platform: gpio
    name: "f24-output08"
    id: "f24_output08"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 11
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output8-tuya
    dp_id: 102
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output08"

  - platform: gpio
    name: "f24-output09"
    id: "f24_output09"
    pin:
      pca9554: xl9555_hub_out_1
      number: 0
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output9-tuya
    dp_id: 103
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output09"

  - platform: gpio
    name: "f24-output10"
    id: "f24_output10"
    pin:
      pca9554: xl9555_hub_out_1
      number: 1
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output10-tuya
    dp_id: 104
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output10"

  - platform: gpio
    name: "f24-output11"
    id: "f24_output11"
    pin:
      pca9554: xl9555_hub_out_1
      number: 2
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output11-tuya
    dp_id: 105
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output11"

  - platform: gpio
    name: "f24-output12"
    id: "f24_output12"
    pin:
      pca9554: xl9555_hub_out_1
      number: 3
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output12-tuya
    dp_id: 106
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output12"

  - platform: gpio
    name: "f24-output13"
    id: "f24_output13"
    pin:
      pca9554: xl9555_hub_out_1
      number: 4
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output13-tuya
    dp_id: 107
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output13"

  - platform: gpio
    name: "f24-output14"
    id: "f24_output14"
    pin:
      pca9554: xl9555_hub_out_1
      number: 5
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output14-tuya
    dp_id: 108
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output14"

  - platform: gpio
    name: "f24-output15"
    id: "f24_output15"
    pin:
      pca9554: xl9555_hub_out_1
      number: 6
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output15-tuya
    dp_id: 109
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output15"

  - platform: gpio
    name: "f24-output16"
    id: "f24_output16"
    pin:
      pca9554: xl9555_hub_out_1
      number: 7
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output16-tuya
    dp_id: 110
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output16"

  - platform: gpio
    name: "f24-output17"
    id: "f24_output17"
    pin:
      pca9554: xl9555_hub_out_1
      number: 8
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output17-tuya
    dp_id: 126
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output17"

  - platform: gpio
    name: "f24-output18"
    id: "f24_output18"
    pin:
      pca9554: xl9555_hub_out_1
      number: 9
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output18-tuya
    dp_id: 129
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output18"

  - platform: gpio
    name: "f24-output19"
    id: "f24_output19"
    pin:
      pca9554: xl9555_hub_out_1
      number: 10
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output19-tuya
    dp_id: 130
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output19"

  - platform: gpio
    name: "f24-output20"
    id: "f24_output20"
    pin:
      pca9554: xl9555_hub_out_1
      number: 11
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output20-tuya
    dp_id: 131
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output20"

  - platform: gpio
    name: "f24-output21"
    id: "f24_output21"
    pin:
      pca9554: xl9555_hub_out_1
      number: 12
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output21-tuya
    dp_id: 132
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output21"

  - platform: gpio
    name: "f24-output22"
    id: "f24_output22"
    pin:
      pca9554: xl9555_hub_out_1
      number: 13
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output22-tuya
    dp_id: 133
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output22"

  - platform: gpio
    name: "f24-output23"
    id: "f24_output23"
    pin:
      pca9554: xl9555_hub_out_1
      number: 14
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output23-tuya
    dp_id: 134
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output23"

  - platform: gpio
    name: "f24-output24"
    id: "f24_output24"
    pin:
      pca9554: xl9555_hub_out_1
      number: 15
      mode: OUTPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-output24-tuya
    dp_id: 135
    # hide from homeassistant ui
    internal: true
    # bind other switch, sync state
    bind_switch_id: "f24_output24"


binary_sensor:
  - platform: gpio
    name: "f24-input01"
    id: "f24_input01"
    pin:
      pca9554: xl9555_hub_in_1
      number: 0
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input1-tuya
    dp_id: 111
    bind_binary_sensor_id: f24_input01
    internal: true

  - platform: gpio
    name: "f24-input02"
    id: "f24_input02"
    pin:
      pca9554: xl9555_hub_in_1
      number: 1
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input2-tuya
    dp_id: 112
    bind_binary_sensor_id: f24_input02
    internal: true

  - platform: gpio
    name: "f24-input03"
    id: "f24_input03"
    pin:
      pca9554: xl9555_hub_in_1
      number: 2
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input3-tuya
    dp_id: 113
    bind_binary_sensor_id: f24_input03
    internal: true

  - platform: gpio
    name: "f24-input04"
    id: "f24_input04"
    pin:
      pca9554: xl9555_hub_in_1
      number: 3
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input4-tuya
    dp_id: 114
    bind_binary_sensor_id: f24_input04
    internal: true

  - platform: gpio
    name: "f24-input05"
    id: "f24_input05"
    pin:
      pca9554: xl9555_hub_in_1
      number: 4
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input5-tuya
    dp_id: 115
    bind_binary_sensor_id: f24_input05
    internal: true

  - platform: gpio
    name: "f24-input06"
    id: "f24_input06"
    pin:
      pca9554: xl9555_hub_in_1
      number: 5
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input6-tuya
    dp_id: 116
    bind_binary_sensor_id: f24_input06
    internal: true

  - platform: gpio
    name: "f24-input07"
    id: "f24_input07"
    pin:
      pca9554: xl9555_hub_in_1
      number: 6
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input7-tuya
    dp_id: 117
    bind_binary_sensor_id: f24_input07
    internal: true

  - platform: gpio
    name: "f24-input08"
    id: "f24_input08"
    pin:
      pca9554: xl9555_hub_in_1
      number: 7
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input8-tuya
    dp_id: 118
    bind_binary_sensor_id: f24_input08
    internal: true

  - platform: gpio
    name: "f24-input09"
    id: "f24_input09"
    pin:
      pca9554: xl9555_hub_in_1
      number: 8
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input9-tuya
    dp_id: 119
    bind_binary_sensor_id: f24_input09
    internal: true

  - platform: gpio
    name: "f24-input10"
    id: "f24_input10"
    pin:
      pca9554: xl9555_hub_in_1
      number: 9
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input10-tuya
    dp_id: 120
    bind_binary_sensor_id: f24_input10
    internal: true

  - platform: gpio
    name: "f24-input11"
    id: "f24_input11"
    pin:
      pca9554: xl9555_hub_in_1
      number: 10
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input11-tuya
    dp_id: 121
    bind_binary_sensor_id: f24_input11
    internal: true

  - platform: gpio
    name: "f24-input12"
    id: "f24_input12"
    pin:
      pca9554: xl9555_hub_in_1
      number: 11
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input12-tuya
    dp_id: 122
    bind_binary_sensor_id: f24_input12
    internal: true

  - platform: gpio
    name: "f24-input13"
    id: "f24_input13"
    pin:
      pca9554: xl9555_hub_in_1
      number: 12
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input13-tuya
    dp_id: 123
    bind_binary_sensor_id: f24_input13
    internal: true

  - platform: gpio
    name: "f24-input14"
    id: "f24_input14"
    pin:
      pca9554: xl9555_hub_in_1
      number: 13
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input14-tuya
    dp_id: 124
    bind_binary_sensor_id: f24_input14
    internal: true

  - platform: gpio
    name: "f24-input15"
    id: "f24_input15"
    pin:
      pca9554: xl9555_hub_in_1
      number: 14
      mode: INPUT
      inverted: true
  - platform: tuya_wifi_mcu
    name: f24-input15-tuya
    dp_id: 125
    bind_binary_sensor_id: f24_input15
    internal: true

  - platform: gpio
    name: "f24-input16"
    id: "f24_input16"
    pin:
      pca9554: xl9555_hub_in_1
      number: 15
      mode: INPUT
      inverted: true


  - platform: gpio
    name: "f24-input17"
    id: "f24_input17"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 0
      mode: INPUT
      inverted: true


  - platform: gpio
    name: "f24-input18"
    id: "f24_input18"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 1
      mode: INPUT
      inverted: true


  - platform: gpio
    name: "f24-input19"
    id: "f24_input19"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 2
      mode: INPUT
      inverted: true


  - platform: gpio
    name: "f24-input20"
    id: "f24_input20"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 3
      mode: INPUT
      inverted: true


  - platform: gpio
    name: "f24-input21"
    id: "f24_input21"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 4
      mode: INPUT
      inverted: true


  - platform: gpio
    name: "f24-input22"
    id: "f24_input22"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 5
      mode: INPUT
      inverted: true


  - platform: gpio
    name: "f24-input23"
    id: "f24_input23"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 6
      mode: INPUT
      inverted: true


  - platform: gpio
    name: "f24-input24"
    id: "f24_input24"
    pin:
      pca9554: xl9555_hub_out_in_2
      number: 7
      mode: INPUT
      inverted: true


##pull-up resistance on PCB
  - platform: gpio
    name: "f24-W1-io48"
    pin:
      number: 48
      inverted: true

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

  - platform: gpio
    name: "f24-W1-io21"
    pin:
      number: 21
      inverted: true

  - platform: gpio
    name: "f24-W1-io15"
    pin:
      number: 15
      inverted: true
## without resistance on PCB
  - platform: gpio
    name: "f24-W1-io13"
    pin:
      number: 13
      inverted: false

  - platform: gpio
    name: "f24-W1-io14"
    pin:
      number: 14
      inverted:  false

  - platform: gpio
    name: "f24-433M"
    pin:
      number: 40
      inverted:  false

sensor:
  - platform: adc
    pin: 5
    name: "f24 A1 Voltage"
    update_interval: 5s
    attenuation: 11db
    filters:
      - lambda:
          if (x >= 3.11) {
            return x * 1.60256;
          } else if (x <= 0.15) {
            return 0;
          } else {
            return x * 1.51;
          }
  - platform: adc
    pin: 7
    name: "f24 A2 Voltage"
    update_interval: 5s
    attenuation: 11db
    filters:
      # - multiply: 1.51515
      - lambda:
          if (x >= 3.11) {
            return x * 1.60256;
          } else if (x <= 0.15) {
            return 0;
          } else {
            return x * 1.51;
          }
  - platform: adc
    pin: 6
    name: "f24 A3 Current"
    update_interval: 5s
    unit_of_measurement: mA
    attenuation: 11db
    filters:
      - multiply: 6.66666666
  - platform: adc
    pin: 4
    name: "f24 A4 Current"
    update_interval: 5s
    unit_of_measurement: mA
    attenuation: 11db
    filters:
      - multiply: 6.66666666

web_server:
  port: 80

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

display:
  - platform: ssd1306_i2c
    i2c_id: bus_a
    model: "SSD1306 128x64"
    address: 0x3C
    lambda: |-
      it.printf(0, 0, id(roboto), "KinCony F24");
download yaml file:

.txt   F24-HA-with-Tyua-XL9555.txt (Size: 18.5 KB / Downloads: 35)
   

Print this item

  [arduino code examples for F24]-02 Read digital input ports state by XL9555 chip
Posted by: admin - 11-06-2026, 05:35 AM - Forum: F24 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* Description:
* This Arduino program reads the state of two 16-channel XL9555SS I/O expanders
* and prints the state of all input pins (1-24) to the Serial Monitor. The state of
* each pin is represented as a bit in a 24-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
* - XL9555SS I2C Address: 0x24 for inputs 1-16, 0x26 for inputs 17-24
*/

#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

constexpr uint8_t INPUT_ADDR_1 = 0x24;
constexpr uint8_t INPUT_ADDR_2 = 0x26;
PCA9555 inputIO1;
PCA9555 inputIO2;

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

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

    // Configure both expanders for the input-only test.
    inputIO1.attach(Wire, INPUT_ADDR_1);
    inputIO1.polarity(PCA95x5::Polarity::ORIGINAL_ALL);
    inputIO1.direction(PCA95x5::Direction::IN_ALL);

    // Read only ports 0-7 on 0x26. Leave the relay ports undriven.
    inputIO2.attach(Wire, INPUT_ADDR_2);
    inputIO2.polarity(PCA95x5::Polarity::ORIGINAL_ALL);
    inputIO2.direction(PCA95x5::Direction::IN_ALL);

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

void loop() {
    // DI1-16 occupy bits 0-15; DI17-24 occupy bits 16-23.
    const uint32_t first = inputIO1.read();
    const uint32_t second = inputIO2.read() & 0x00FFU;
    const uint32_t state = first | (second << 16);

    // Print the state of all 24 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: 1 KB / Downloads: 30)
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.2 KB / Downloads: 33)

Print this item

  [arduino code examples for F24]-01 Turn ON/OFF relay by XL9555 chip
Posted by: admin - 11-06-2026, 05:33 AM - Forum: F24 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* This program controls a 24-channel relay board via two 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

PCA9555 relayIO1; // Relays 9-24
PCA9555 relayIO2; // Relays 1-8

// XL9555SS port indices in physical relay order (1-8).
constexpr uint8_t RELAY_PORTS_1_TO_8[] = {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);
  // Ports 0-7 remain inputs, and ports 8-15 drive relays 1-8.
  relayIO2.direction(0x00FF);
}

void loop() {
  // Sequentially turn on each relay (1-24)
 
  // Control relays 1-8 in physical channel order.
  for (uint8_t port : RELAY_PORTS_1_TO_8) {
    relayIO2.write(static_cast<PCA95x5::Port::Port>(port), PCA95x5::Level::L);
    delay(DELAY_TIME);          // Wait for DELAY_TIME milliseconds
  }

  // Then control the relays on the first XL9555SS (relays 9-24)
  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-24)
 
  // Control relays 1-8 in physical channel order.
  for (uint8_t port : RELAY_PORTS_1_TO_8) {
    relayIO2.write(static_cast<PCA95x5::Port::Port>(port), PCA95x5::Level::H);
    delay(DELAY_TIME);          // Wait for DELAY_TIME milliseconds
  }

  // Then control the relays on the first XL9555SS (relays 9-24)
  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.19 KB / Downloads: 31)
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.02 KB / Downloads: 31)

Print this item

  [arduino code examples for CO16]-13 ST7789 TFT LCD Flash MJPEG Player
Posted by: admin - 11-03-2026, 03:04 AM - Forum: CO16 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
* CO16 Flash MJPEG Player: 320x240, 10 fps target, 120 frames, silent loop.
* No SD card and no filesystem upload required. Remove SD card before use.
* Video is embedded in KinConyVideo.h and uploaded with this sketch.
* Libraries: Adafruit GFX Library, Adafruit BusIO, JPEGDEC by Larry Bank.
* Board: ESP32S3 Dev Module, Flash 16MB, OPI PSRAM, Arduino-ESP32 3.x.
* Choose an application partition >= 3MB (e.g. Huge APP).
* Serial 115200: p=pause/resume, r=restart. Relays commanded OFF at startup.
*/
#include <Arduino.h>
#include <Wire.h>
#include <JPEGDEC.h>
#include <cstring>
#include "KinConyVideo.h"

#include <Adafruit_GFX.h>
#include <driver/gpio.h>
#include <driver/spi_master.h>
#include <esp_heap_caps.h>


// CO16 ST7789 (GMT020-02-7P) pin mapping from kcs_co16.h.
constexpr gpio_num_t kTftSclk = GPIO_NUM_11;
constexpr gpio_num_t kTftMosi = GPIO_NUM_10;
constexpr gpio_num_t kTftMiso = GPIO_NUM_12;
constexpr gpio_num_t kTftCs = GPIO_NUM_4;
constexpr gpio_num_t kTftDc = GPIO_NUM_0;
constexpr gpio_num_t kTftReset = GPIO_NUM_5;
constexpr gpio_num_t kTftBacklight = GPIO_NUM_40;

constexpr int16_t kDisplayWidth = 320;
constexpr int16_t kDisplayHeight = 240;
constexpr int16_t kTransferChunkHeight = 10;
constexpr uint32_t kDisplaySpiFrequency = 20 * 1000 * 1000;
constexpr uint8_t kCo16Madctl = 0x68;  // MX | MV | BGR.

constexpr uint16_t kBlack = 0x0000;
constexpr uint16_t kBlue = 0x001F;
constexpr uint16_t kRed = 0xF800;
constexpr uint16_t kGreen = 0x07E0;
constexpr uint16_t kCyan = 0x07FF;
constexpr uint16_t kMagenta = 0xF81F;
constexpr uint16_t kYellow = 0xFFE0;
constexpr uint16_t kWhite = 0xFFFF;

class Co16St7789 : public Adafruit_GFX {
public:
  Co16St7789() : Adafruit_GFX(kDisplayWidth, kDisplayHeight) {}

  bool begin() {
    gpio_reset_pin(kTftCs);
    gpio_set_direction(kTftCs, GPIO_MODE_OUTPUT);
    gpio_set_level(kTftCs, 1);

    gpio_reset_pin(kTftDc);
    gpio_set_direction(kTftDc, GPIO_MODE_OUTPUT);
    gpio_set_level(kTftDc, 1);

    gpio_reset_pin(kTftBacklight);
    gpio_set_direction(kTftBacklight, GPIO_MODE_OUTPUT);
    gpio_set_level(kTftBacklight, 0);

    // SPI3 is initialized once by setup(); only the display uses it.
    esp_err_t err;

    spi_device_interface_config_t deviceConfig = {};
    deviceConfig.clock_speed_hz = kDisplaySpiFrequency;
    deviceConfig.mode = 0;
    deviceConfig.spics_io_num = -1;
    deviceConfig.queue_size = 1;

    err = spi_bus_add_device(SPI3_HOST, &deviceConfig, &spiDevice_);
    if (err != ESP_OK) {
      Serial.printf("ST7789 SPI device setup failed: %s\n",
                    esp_err_to_name(err));
      return false;
    }

    drawBuffer_ = static_cast<uint8_t*>(heap_caps_malloc(
        kDisplayWidth * kTransferChunkHeight * sizeof(uint16_t),
        MALLOC_CAP_DMA));
    if (drawBuffer_ == nullptr) {
      Serial.println("ST7789 DMA buffer allocation failed");
      return false;
    }

    // GPIO5 is shared with the optional LoRa module. Match the working KCS
    // firmware and issue one reset pulse before initializing the controller.
    gpio_reset_pin(kTftReset);
    gpio_set_direction(kTftReset, GPIO_MODE_OUTPUT);
    gpio_set_level(kTftReset, 1);
    delay(1);
    gpio_set_level(kTftReset, 0);
    delay(1);
    gpio_set_level(kTftReset, 1);
    delay(10);

    if (!initializeController()) {
      return false;
    }

    fillScreen(kBlack);
    delay(120);
    if (!writeCommand(0x29)) {  // Display on.
      return false;
    }
    delay(120);

    gpio_set_level(kTftBacklight, 1);
    initialized_ = true;
    return true;
  }

  void drawPixel(int16_t x, int16_t y, uint16_t color) override {
    fillRect(x, y, 1, 1, color);
  }

  void writePixel(int16_t x, int16_t y, uint16_t color) override {
    fillRect(x, y, 1, 1, color);
  }

  void fillRect(int16_t x, int16_t y, int16_t width, int16_t height,
                uint16_t color) override {
    if (x < 0) {
      width += x;
      x = 0;
    }
    if (y < 0) {
      height += y;
      y = 0;
    }
    if (x + width > kDisplayWidth) {
      width = kDisplayWidth - x;
    }
    if (y + height > kDisplayHeight) {
      height = kDisplayHeight - y;
    }
    if (drawBuffer_ == nullptr || width <= 0 || height <= 0) {
      return;
    }

    const uint8_t high = color >> 8;
    const uint8_t low = color;
    for (int16_t row = y; row < y + height;
         row += kTransferChunkHeight) {
      const int16_t chunkHeight =
          min<int16_t>(kTransferChunkHeight, y + height - row);
      const size_t pixelCount = width * chunkHeight;
      for (size_t index = 0; index < pixelCount; ++index) {
        drawBuffer_[index * 2] = high;
        drawBuffer_[index * 2 + 1] = low;
      }

      if (!setWindow(x, row, x + width, row + chunkHeight) ||
          !writePixels(drawBuffer_, pixelCount * sizeof(uint16_t))) {
        Serial.println("ST7789 pixel transfer failed");
        return;
      }
    }
  }

  void writeFillRect(int16_t x, int16_t y, int16_t width, int16_t height,
                     uint16_t color) override {
    fillRect(x, y, width, height, color);
  }

  // Copy a fully rendered RGB565 frame into the DMA staging buffer.
  bool present(const uint16_t* pixels) {
    if (!initialized_ || pixels == nullptr) return false;
    for (int y = 0; y < kDisplayHeight; y += kTransferChunkHeight) {
      const int rows = min<int>(kTransferChunkHeight, kDisplayHeight - y);
      const int count = kDisplayWidth * rows;
      for (int i = 0; i < count; ++i) {
        uint16_t c = pixels[y * kDisplayWidth + i];
        drawBuffer_[2 * i] = c >> 8;
        drawBuffer_[2 * i + 1] = c & 0xFF;
      }
      if (!setWindow(0, y, kDisplayWidth, y + rows) ||
          !writePixels(drawBuffer_, count * 2)) return false;
    }
    return true;
  }

  bool initialized() const { return initialized_; }

private:
  bool transmit(const void* data, size_t length, int dcLevel) {
    if (data == nullptr || length == 0) {
      return true;
    }

    gpio_set_level(kTftDc, dcLevel);
    spi_transaction_t transaction = {};
    transaction.length = length * 8;
    transaction.tx_buffer = data;
    const esp_err_t err = spi_device_polling_transmit(spiDevice_, &transaction);
    if (err != ESP_OK) {
      Serial.printf("ST7789 SPI transfer failed: %s\n", esp_err_to_name(err));
      return false;
    }
    return true;
  }

  bool writeCommand(uint8_t command) {
    gpio_set_level(kTftCs, 0);
    const bool success = transmit(&command, sizeof(command), 0);
    gpio_set_level(kTftCs, 1);
    return success;
  }

  bool writeCommandData(uint8_t command, const uint8_t* data, size_t length) {
    gpio_set_level(kTftCs, 0);
    const bool success = transmit(&command, sizeof(command), 0) &&
                         transmit(data, length, 1);
    gpio_set_level(kTftCs, 1);
    return success;
  }

  bool setWindow(int16_t x1, int16_t y1, int16_t x2, int16_t y2) {
    const uint8_t columns[] = {
        static_cast<uint8_t>(x1 >> 8), static_cast<uint8_t>(x1),
        static_cast<uint8_t>((x2 - 1) >> 8), static_cast<uint8_t>(x2 - 1),
    };
    const uint8_t rows[] = {
        static_cast<uint8_t>(y1 >> 8), static_cast<uint8_t>(y1),
        static_cast<uint8_t>((y2 - 1) >> 8), static_cast<uint8_t>(y2 - 1),
    };
    return writeCommandData(0x2A, columns, sizeof(columns)) &&
           writeCommandData(0x2B, rows, sizeof(rows));
  }

  bool writePixels(const uint8_t* data, size_t length) {
    constexpr uint8_t kRamWrite = 0x2C;
    gpio_set_level(kTftCs, 0);
    const bool success = transmit(&kRamWrite, sizeof(kRamWrite), 0) &&
                         transmit(data, length, 1);
    gpio_set_level(kTftCs, 1);
    return success;
  }

  bool initializeController() {
    const uint8_t madctl[] = {kCo16Madctl};
    const uint8_t displayFunction[] = {0x0A, 0x82};
    const uint8_t pixelFormat[] = {0x55};
    const uint8_t porchControl[] = {0x0C, 0x0C, 0x00, 0x33, 0x33};
    const uint8_t gateControl[] = {0x35};
    const uint8_t vcom[] = {0x28};
    const uint8_t lcmControl[] = {0x0C};
    const uint8_t vdvVrhEnable[] = {0x01, 0xFF};
    const uint8_t vrh[] = {0x10};
    const uint8_t vdv[] = {0x20};
    const uint8_t frameRate[] = {0x0F};
    const uint8_t powerControl[] = {0xA4, 0xA1};
    const uint8_t positiveGamma[] = {
        0xD0, 0x00, 0x02, 0x07, 0x0A, 0x28, 0x32,
        0x44, 0x42, 0x06, 0x0E, 0x12, 0x14, 0x17,
    };
    const uint8_t negativeGamma[] = {
        0xD0, 0x00, 0x02, 0x07, 0x0A, 0x28, 0x31,
        0x54, 0x47, 0x0E, 0x1C, 0x17, 0x1B, 0x1E,
    };

    if (!writeCommand(0x11)) {  // Sleep out.
      return false;
    }
    delay(120);

    return writeCommand(0x13) &&
           writeCommandData(0x36, madctl, sizeof(madctl)) &&
           writeCommandData(0xB6, displayFunction, sizeof(displayFunction)) &&
           writeCommandData(0x3A, pixelFormat, sizeof(pixelFormat)) &&
           (delay(10), true) &&
           writeCommandData(0xB2, porchControl, sizeof(porchControl)) &&
           writeCommandData(0xB7, gateControl, sizeof(gateControl)) &&
           writeCommandData(0xBB, vcom, sizeof(vcom)) &&
           writeCommandData(0xC0, lcmControl, sizeof(lcmControl)) &&
           writeCommandData(0xC2, vdvVrhEnable, sizeof(vdvVrhEnable)) &&
           writeCommandData(0xC3, vrh, sizeof(vrh)) &&
           writeCommandData(0xC4, vdv, sizeof(vdv)) &&
           writeCommandData(0xC6, frameRate, sizeof(frameRate)) &&
           writeCommandData(0xD0, powerControl, sizeof(powerControl)) &&
           writeCommandData(0xE0, positiveGamma, sizeof(positiveGamma)) &&
           writeCommandData(0xE1, negativeGamma, sizeof(negativeGamma)) &&
           writeCommand(0x21);  // Display inversion on.
  }

  spi_device_handle_t spiDevice_ = nullptr;
  uint8_t* drawBuffer_ = nullptr;
  bool initialized_ = false;
};

constexpr uint32_t VIDEO_FPS = 10;
constexpr uint32_t FRAME_INTERVAL_MS = 1000 / VIDEO_FPS;
static_assert(VIDEO_FPS > 0 && VIDEO_FPS <= 30, "Choose FPS between 1 and 30");
Co16St7789 display;
JPEGDEC jpeg;
uint16_t* frameBuffer = nullptr;
bool paused = false;
uint32_t frameCount = 0, reportStart = 0, reportFrames = 0;

void haltPlayer(const char* title, const char* hint) {
  Serial.printf("%s: %s\n", title, hint);
  if (display.initialized()) {
    display.fillScreen(kBlack);
    display.setTextWrap(true);
    display.setTextSize(2);
    display.setTextColor(kRed);
    display.setCursor(8, 30);
    display.print(title);
    display.setTextSize(1);
    display.setTextColor(kWhite);
    display.setCursor(8, 85);
    display.print(hint);
  }
  while (true) delay(1000);
}

void* allocateVideoMemory(size_t size) {
  void* p = heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  if (!p) p = heap_caps_malloc(size, MALLOC_CAP_8BIT);
  return p;
}

int decodedPixels(JPEGDRAW* block) {
  if (!frameBuffer || !block || block->iBpp != 16 || block->x < 0 || block->y < 0)
    return 0;
  if (block->x >= 320 || block->y >= 240) return 0;
  int width = min<int>(block->iWidthUsed, 320 - block->x);
  int height = min<int>(block->iHeight, 240 - block->y);
  if (width <= 0 || height <= 0) return 0;
  for (int row = 0; row < height; ++row) {
    memcpy(frameBuffer + (block->y + row) * 320 + block->x,
           block->pPixels + row * block->iWidth, width * sizeof(uint16_t));
  }
  return 1;
}

void setup() {
  Serial.begin(115200);
  Wire.begin(8, 18);
  Wire.setClock(100000);
  Wire.setTimeOut(20);
  Wire.beginTransmission(0x22);
  Wire.write(uint8_t(0xFF));
  Wire.write(uint8_t(0xFF));
  if (Wire.endTransmission() != 0) Serial.println("Warning: relay OFF command not acknowledged.");

  // Keep unused SPI peripherals deselected. Remove the SD card for this demo.
  const int csPins[] = {4, 9, 13, 14, 42};
  for (int pin : csPins) { digitalWrite(pin, HIGH); pinMode(pin, OUTPUT); }
  pinMode(40, OUTPUT);
  digitalWrite(40, LOW);
  spi_bus_config_t bus = {};
  bus.sclk_io_num = 11;
  bus.mosi_io_num = 10;
  bus.miso_io_num = 12;
  bus.quadwp_io_num = -1;
  bus.quadhd_io_num = -1;
  bus.max_transfer_sz = 320 * kTransferChunkHeight * 2;
  esp_err_t err = spi_bus_initialize(SPI3_HOST, &bus, SPI_DMA_CH_AUTO);
  if (err != ESP_OK) haltPlayer("SPI init failed", esp_err_to_name(err));

  if (!display.begin()) haltPlayer("LCD init failed", "Check serial output and CO16 board selection.");
  display.setTextWrap(false);
  display.setTextSize(2);
  display.setTextColor(kCyan);
  display.setCursor(30, 90);
  display.print("KinCony MJPEG");
  display.setTextSize(1);
  display.setCursor(30, 122);
  display.print("Loading slogan video ...");

  frameBuffer = static_cast<uint16_t*>(allocateVideoMemory(320 * 240 * 2));
  if (!frameBuffer)
    haltPlayer("Not enough RAM", "Enable OPI PSRAM for ESP32-S3 N16R8 and upload again.");
  Serial.printf("Embedded video: %u bytes, %lu frames\n",
                unsigned(sizeof(kVideoData)), static_cast<unsigned long>(kVideoFrameCount));
  reportStart = millis();
  Serial.println("Player ready. 10 fps target; p=pause/resume, r=restart.");
}

void loop() {
  while (Serial.available()) {
    char c = Serial.read();
    if (c == 'p') paused = !paused;
    if (c == 'r') {
      frameCount = 0;
      paused = false;
    }
  }
  if (paused) {
    reportStart = millis(); reportFrames = 0;
    delay(10); return;
  }
  uint32_t started = millis();
  if (frameCount >= kVideoFrameCount) frameCount = 0;
  uint32_t offset = kFrameOffsets[frameCount];
  uint32_t end = kFrameOffsets[frameCount + 1];
  if (end <= offset || end > sizeof(kVideoData))
    haltPlayer("Bad frame index", "Re-upload the complete firmware package.");
  if (!jpeg.openFLASH(kVideoData + offset, int(end - offset), decodedPixels))
    haltPlayer("JPEG open failed", "Check JPEGDEC library and embedded video data.");
  if (jpeg.getWidth() != 320 || jpeg.getHeight() != 240) {
    jpeg.close();
    haltPlayer("Wrong frame size", "Convert the video to exactly 320x240 pixels.");
  }
  jpeg.setPixelType(RGB565_LITTLE_ENDIAN);
  memset(frameBuffer, 0, 320 * 240 * 2);
  int decoded = jpeg.decode(0, 0, 0);
  int jpegError = jpeg.getLastError();
  jpeg.close();
  if (!decoded) {
    Serial.printf("JPEG decode error: %d\n", jpegError);
    haltPlayer("JPEG decode failed", "Check video integrity and JPEGDEC library.");
  }
  // Present the decoded full frame to the display.
  if (!display.present(frameBuffer)) haltPlayer("LCD write failed", "Check power and SPI connection.");
  ++frameCount;
  ++reportFrames;
  uint32_t elapsed = millis() - started;
  if (elapsed < FRAME_INTERVAL_MS) delay(FRAME_INTERVAL_MS - elapsed);
  else delay(1); // Yield; do not skip frames or run catch-up bursts.
  uint32_t now = millis();
  if (now - reportStart >= 5000) {
    Serial.printf("Playback %.1f fps, read/decode/display %lu ms, frame %lu\n",
                  reportFrames * 1000.0f / (now - reportStart),
                  static_cast<unsigned long>(elapsed), static_cast<unsigned long>(frameCount));
    reportStart = now; reportFrames = 0;
  }
}
arduino ino file download: 

.zip   13-CO16_Flash_MJPEG_Player.zip (Size: 8.21 MB / Downloads: 51)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download:

.zip   13-CO16_Flash_MJPEG_Player.ino.merged.zip (Size: 1.05 MB / Downloads: 42)

Print this item

  [arduino code examples for CO16]-12 ST7789 TFT LCD image display
Posted by: admin - 11-03-2026, 01:34 AM - Forum: CO16 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
* CO16 Image Display - show the supplied photograph on the onboard LCD.
* Target: ESP32-S3 CO16, ST7789 320x240 landscape.
* Uses the display initialization from the validated CO16 Cyber Show sketch.
* Install Adafruit GFX Library and its Adafruit BusIO dependency.
* Select ESP32S3 Dev Module; retain your working CO16 board settings.
* Keep image_data.h in the same folder as this sketch.
* Image is stored in flash as RGB565; no SD card, JPEG decoder or Wi-Fi.
* Full image is resized to 320x240 with no margins; aspect ratio changes.
* PCF8575 relay outputs at 0x22 are commanded OFF at startup.
*/
#include <Arduino.h>
#include <Wire.h>
#include "image_data.h"

#include <Adafruit_GFX.h>
#include <driver/gpio.h>
#include <driver/spi_master.h>
#include <esp_heap_caps.h>


// CO16 ST7789 (GMT020-02-7P) pin mapping from kcs_co16.h.
constexpr gpio_num_t kTftSclk = GPIO_NUM_11;
constexpr gpio_num_t kTftMosi = GPIO_NUM_10;
constexpr gpio_num_t kTftMiso = GPIO_NUM_12;
constexpr gpio_num_t kTftCs = GPIO_NUM_4;
constexpr gpio_num_t kTftDc = GPIO_NUM_0;
constexpr gpio_num_t kTftReset = GPIO_NUM_5;
constexpr gpio_num_t kTftBacklight = GPIO_NUM_40;

constexpr int16_t kDisplayWidth = 320;
constexpr int16_t kDisplayHeight = 240;
constexpr int16_t kTransferChunkHeight = 10;
constexpr uint32_t kDisplaySpiFrequency = 20 * 1000 * 1000;
constexpr uint8_t kCo16Madctl = 0x68;  // MX | MV | BGR.

constexpr uint16_t kBlack = 0x0000;
constexpr uint16_t kBlue = 0x001F;
constexpr uint16_t kRed = 0xF800;
constexpr uint16_t kGreen = 0x07E0;
constexpr uint16_t kCyan = 0x07FF;
constexpr uint16_t kMagenta = 0xF81F;
constexpr uint16_t kYellow = 0xFFE0;
constexpr uint16_t kWhite = 0xFFFF;

class Co16St7789 : public Adafruit_GFX {
public:
  Co16St7789() : Adafruit_GFX(kDisplayWidth, kDisplayHeight) {}

  bool begin() {
    gpio_reset_pin(kTftCs);
    gpio_set_direction(kTftCs, GPIO_MODE_OUTPUT);
    gpio_set_level(kTftCs, 1);

    gpio_reset_pin(kTftDc);
    gpio_set_direction(kTftDc, GPIO_MODE_OUTPUT);
    gpio_set_level(kTftDc, 1);

    gpio_reset_pin(kTftBacklight);
    gpio_set_direction(kTftBacklight, GPIO_MODE_OUTPUT);
    gpio_set_level(kTftBacklight, 0);

    spi_bus_config_t busConfig = {};
    busConfig.sclk_io_num = kTftSclk;
    busConfig.mosi_io_num = kTftMosi;
    busConfig.miso_io_num = kTftMiso;
    busConfig.quadwp_io_num = -1;
    busConfig.quadhd_io_num = -1;
    busConfig.max_transfer_sz =
        kDisplayWidth * kTransferChunkHeight * sizeof(uint16_t);

    esp_err_t err =
        spi_bus_initialize(SPI3_HOST, &busConfig, SPI_DMA_CH_AUTO);
    if (err != ESP_OK) {
      Serial.printf("SPI3 initialization failed: %s\n", esp_err_to_name(err));
      return false;
    }

    spi_device_interface_config_t deviceConfig = {};
    deviceConfig.clock_speed_hz = kDisplaySpiFrequency;
    deviceConfig.mode = 0;
    deviceConfig.spics_io_num = -1;
    deviceConfig.queue_size = 1;

    err = spi_bus_add_device(SPI3_HOST, &deviceConfig, &spiDevice_);
    if (err != ESP_OK) {
      Serial.printf("ST7789 SPI device setup failed: %s\n",
                    esp_err_to_name(err));
      return false;
    }

    drawBuffer_ = static_cast<uint8_t*>(heap_caps_malloc(
        kDisplayWidth * kTransferChunkHeight * sizeof(uint16_t),
        MALLOC_CAP_DMA));
    if (drawBuffer_ == nullptr) {
      Serial.println("ST7789 DMA buffer allocation failed");
      return false;
    }

    // GPIO5 is shared with the optional LoRa module. Match the working KCS
    // firmware and issue one reset pulse before initializing the controller.
    gpio_reset_pin(kTftReset);
    gpio_set_direction(kTftReset, GPIO_MODE_OUTPUT);
    gpio_set_level(kTftReset, 1);
    delay(1);
    gpio_set_level(kTftReset, 0);
    delay(1);
    gpio_set_level(kTftReset, 1);
    delay(10);

    if (!initializeController()) {
      return false;
    }

    fillScreen(kBlack);
    delay(120);
    if (!writeCommand(0x29)) {  // Display on.
      return false;
    }
    delay(120);

    gpio_set_level(kTftBacklight, 1);
    initialized_ = true;
    return true;
  }

  void drawPixel(int16_t x, int16_t y, uint16_t color) override {
    fillRect(x, y, 1, 1, color);
  }

  void writePixel(int16_t x, int16_t y, uint16_t color) override {
    fillRect(x, y, 1, 1, color);
  }

  void fillRect(int16_t x, int16_t y, int16_t width, int16_t height,
                uint16_t color) override {
    if (x < 0) {
      width += x;
      x = 0;
    }
    if (y < 0) {
      height += y;
      y = 0;
    }
    if (x + width > kDisplayWidth) {
      width = kDisplayWidth - x;
    }
    if (y + height > kDisplayHeight) {
      height = kDisplayHeight - y;
    }
    if (drawBuffer_ == nullptr || width <= 0 || height <= 0) {
      return;
    }

    const uint8_t high = color >> 8;
    const uint8_t low = color;
    for (int16_t row = y; row < y + height;
         row += kTransferChunkHeight) {
      const int16_t chunkHeight =
          min<int16_t>(kTransferChunkHeight, y + height - row);
      const size_t pixelCount = width * chunkHeight;
      for (size_t index = 0; index < pixelCount; ++index) {
        drawBuffer_[index * 2] = high;
        drawBuffer_[index * 2 + 1] = low;
      }

      if (!setWindow(x, row, x + width, row + chunkHeight) ||
          !writePixels(drawBuffer_, pixelCount * sizeof(uint16_t))) {
        Serial.println("ST7789 pixel transfer failed");
        return;
      }
    }
  }

  void writeFillRect(int16_t x, int16_t y, int16_t width, int16_t height,
                     uint16_t color) override {
    fillRect(x, y, width, height, color);
  }

  // Copy a fully rendered RGB565 frame into the DMA staging buffer.
  bool present(const uint16_t* pixels) {
    if (!initialized_ || pixels == nullptr) return false;
    for (int y = 0; y < kDisplayHeight; y += kTransferChunkHeight) {
      const int rows = min<int>(kTransferChunkHeight, kDisplayHeight - y);
      const int count = kDisplayWidth * rows;
      for (int i = 0; i < count; ++i) {
        uint16_t c = pixels[y * kDisplayWidth + i];
        drawBuffer_[2 * i] = c >> 8;
        drawBuffer_[2 * i + 1] = c & 0xFF;
      }
      if (!setWindow(0, y, kDisplayWidth, y + rows) ||
          !writePixels(drawBuffer_, count * 2)) return false;
    }
    return true;
  }

  bool initialized() const { return initialized_; }

private:
  bool transmit(const void* data, size_t length, int dcLevel) {
    if (data == nullptr || length == 0) {
      return true;
    }

    gpio_set_level(kTftDc, dcLevel);
    spi_transaction_t transaction = {};
    transaction.length = length * 8;
    transaction.tx_buffer = data;
    const esp_err_t err = spi_device_polling_transmit(spiDevice_, &transaction);
    if (err != ESP_OK) {
      Serial.printf("ST7789 SPI transfer failed: %s\n", esp_err_to_name(err));
      return false;
    }
    return true;
  }

  bool writeCommand(uint8_t command) {
    gpio_set_level(kTftCs, 0);
    const bool success = transmit(&command, sizeof(command), 0);
    gpio_set_level(kTftCs, 1);
    return success;
  }

  bool writeCommandData(uint8_t command, const uint8_t* data, size_t length) {
    gpio_set_level(kTftCs, 0);
    const bool success = transmit(&command, sizeof(command), 0) &&
                         transmit(data, length, 1);
    gpio_set_level(kTftCs, 1);
    return success;
  }

  bool setWindow(int16_t x1, int16_t y1, int16_t x2, int16_t y2) {
    const uint8_t columns[] = {
        static_cast<uint8_t>(x1 >> 8), static_cast<uint8_t>(x1),
        static_cast<uint8_t>((x2 - 1) >> 8), static_cast<uint8_t>(x2 - 1),
    };
    const uint8_t rows[] = {
        static_cast<uint8_t>(y1 >> 8), static_cast<uint8_t>(y1),
        static_cast<uint8_t>((y2 - 1) >> 8), static_cast<uint8_t>(y2 - 1),
    };
    return writeCommandData(0x2A, columns, sizeof(columns)) &&
           writeCommandData(0x2B, rows, sizeof(rows));
  }

  bool writePixels(const uint8_t* data, size_t length) {
    constexpr uint8_t kRamWrite = 0x2C;
    gpio_set_level(kTftCs, 0);
    const bool success = transmit(&kRamWrite, sizeof(kRamWrite), 0) &&
                         transmit(data, length, 1);
    gpio_set_level(kTftCs, 1);
    return success;
  }

  bool initializeController() {
    const uint8_t madctl[] = {kCo16Madctl};
    const uint8_t displayFunction[] = {0x0A, 0x82};
    const uint8_t pixelFormat[] = {0x55};
    const uint8_t porchControl[] = {0x0C, 0x0C, 0x00, 0x33, 0x33};
    const uint8_t gateControl[] = {0x35};
    const uint8_t vcom[] = {0x28};
    const uint8_t lcmControl[] = {0x0C};
    const uint8_t vdvVrhEnable[] = {0x01, 0xFF};
    const uint8_t vrh[] = {0x10};
    const uint8_t vdv[] = {0x20};
    const uint8_t frameRate[] = {0x0F};
    const uint8_t powerControl[] = {0xA4, 0xA1};
    const uint8_t positiveGamma[] = {
        0xD0, 0x00, 0x02, 0x07, 0x0A, 0x28, 0x32,
        0x44, 0x42, 0x06, 0x0E, 0x12, 0x14, 0x17,
    };
    const uint8_t negativeGamma[] = {
        0xD0, 0x00, 0x02, 0x07, 0x0A, 0x28, 0x31,
        0x54, 0x47, 0x0E, 0x1C, 0x17, 0x1B, 0x1E,
    };

    if (!writeCommand(0x11)) {  // Sleep out.
      return false;
    }
    delay(120);

    return writeCommand(0x13) &&
           writeCommandData(0x36, madctl, sizeof(madctl)) &&
           writeCommandData(0xB6, displayFunction, sizeof(displayFunction)) &&
           writeCommandData(0x3A, pixelFormat, sizeof(pixelFormat)) &&
           (delay(10), true) &&
           writeCommandData(0xB2, porchControl, sizeof(porchControl)) &&
           writeCommandData(0xB7, gateControl, sizeof(gateControl)) &&
           writeCommandData(0xBB, vcom, sizeof(vcom)) &&
           writeCommandData(0xC0, lcmControl, sizeof(lcmControl)) &&
           writeCommandData(0xC2, vdvVrhEnable, sizeof(vdvVrhEnable)) &&
           writeCommandData(0xC3, vrh, sizeof(vrh)) &&
           writeCommandData(0xC4, vdv, sizeof(vdv)) &&
           writeCommandData(0xC6, frameRate, sizeof(frameRate)) &&
           writeCommandData(0xD0, powerControl, sizeof(powerControl)) &&
           writeCommandData(0xE0, positiveGamma, sizeof(positiveGamma)) &&
           writeCommandData(0xE1, negativeGamma, sizeof(negativeGamma)) &&
           writeCommand(0x21);  // Display inversion on.
  }

  spi_device_handle_t spiDevice_ = nullptr;
  uint8_t* drawBuffer_ = nullptr;
  bool initialized_ = false;
};

Co16St7789 display;

void setup() {
  Serial.begin(115200);
  Wire.begin(8, 18);
  Wire.setClock(100000);
  Wire.setTimeOut(20);
  // Active-low PCF8575 relay outputs: HIGH on all channels means OFF.
  Wire.beginTransmission(0x22);
  Wire.write(uint8_t(0xFF));
  Wire.write(uint8_t(0xFF));
  if (Wire.endTransmission() != 0) {
    Serial.println("Warning: relay OFF command not acknowledged at 0x22.");
  }

  // Deselect all other SPI peripherals before initializing the LCD bus.
  const int inactiveCs[] = {9, 13, 14, 42};
  for (int pin : inactiveCs) {
    digitalWrite(pin, HIGH);
    pinMode(pin, OUTPUT);
  }
  if (!display.begin()) {
    Serial.println("ST7789 initialization failed.");
    while (true) delay(1000);
  }
  // ESP32 flash is memory mapped. present() reads the constant image into
  // a small DMA-capable staging buffer, then sends it to the ST7789.
  if (!display.present(kImageRgb565)) {
    Serial.println("Image transfer failed.");
    while (true) delay(1000);
  }
  Serial.println("Image displayed: 320x240 RGB565, full-screen image.");
}

void loop() {
  // The LCD retains its image; no continuous redraw is necessary.
  delay(1000);
}
arduino ino file download: 

.zip   12-CO16_Image_Display.zip (Size: 729.92 KB / Downloads: 52)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download:

.zip   12-CO16_Image_Display.ino.merged.zip (Size: 273.66 KB / Downloads: 50)
   
   

Print this item

  [arduino code examples for CO16]-11 ST7789 TFT LCD Cyber Show With Relay
Posted by: admin - 11-03-2026, 12:15 AM - Forum: CO16 - No Replies

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
* CO16 CYBER SHOW - standalone Shorts demo, 32-second automatic loop.
* Target: ESP32-S3, CO16 with PCF8575 relay outputs at 0x22.
* Display: 320x240 ST7789; native SPI3 initialization from CO16-pcb-test.ino.
* Install Adafruit GFX Library and its Adafruit BusIO dependency.
* Board: ESP32S3 Dev Module; retain the settings used for the factory sketch.
* No PCF8575, Ethernet, SD, RTC or ADC libraries required.
*
* IMPORTANT: disconnect all loads from relay terminals before filming.
* These are mechanical relays: use this as a short filming demo, not a
* continuous endurance test. The graphics are synthetic, not sensor data.
* Relay tiles show acknowledged output commands, NOT contact feedback.
*
* Serial Monitor, 115200 baud (no line ending needed):
*   0 = automatic show from beginning; 1..5 = hold a scene
*   p = pause/resume (pause switches relays OFF); r = restart auto show
*   x = disable relay motion; e = enable relay motion
* Frame rendering uses 153600 bytes of RAM plus a 6400-byte DMA buffer.
* No EEPROM writes, networking, SD operations or other peripheral tests.
*/
#include <Arduino.h>
#include <Wire.h>
#include <math.h>
#include <string.h>

#include <Adafruit_GFX.h>
#include <driver/gpio.h>
#include <driver/spi_master.h>
#include <esp_heap_caps.h>


// CO16 ST7789 (GMT020-02-7P) pin mapping from kcs_co16.h.
constexpr gpio_num_t kTftSclk = GPIO_NUM_11;
constexpr gpio_num_t kTftMosi = GPIO_NUM_10;
constexpr gpio_num_t kTftMiso = GPIO_NUM_12;
constexpr gpio_num_t kTftCs = GPIO_NUM_4;
constexpr gpio_num_t kTftDc = GPIO_NUM_0;
constexpr gpio_num_t kTftReset = GPIO_NUM_5;
constexpr gpio_num_t kTftBacklight = GPIO_NUM_40;

constexpr int16_t kDisplayWidth = 320;
constexpr int16_t kDisplayHeight = 240;
constexpr int16_t kTransferChunkHeight = 10;
constexpr uint32_t kDisplaySpiFrequency = 20 * 1000 * 1000;
constexpr uint8_t kCo16Madctl = 0x68;  // MX | MV | BGR.

constexpr uint16_t kBlack = 0x0000;
constexpr uint16_t kBlue = 0x001F;
constexpr uint16_t kRed = 0xF800;
constexpr uint16_t kGreen = 0x07E0;
constexpr uint16_t kCyan = 0x07FF;
constexpr uint16_t kMagenta = 0xF81F;
constexpr uint16_t kYellow = 0xFFE0;
constexpr uint16_t kWhite = 0xFFFF;

class Co16St7789 : public Adafruit_GFX {
public:
  Co16St7789() : Adafruit_GFX(kDisplayWidth, kDisplayHeight) {}

  bool begin() {
    gpio_reset_pin(kTftCs);
    gpio_set_direction(kTftCs, GPIO_MODE_OUTPUT);
    gpio_set_level(kTftCs, 1);

    gpio_reset_pin(kTftDc);
    gpio_set_direction(kTftDc, GPIO_MODE_OUTPUT);
    gpio_set_level(kTftDc, 1);

    gpio_reset_pin(kTftBacklight);
    gpio_set_direction(kTftBacklight, GPIO_MODE_OUTPUT);
    gpio_set_level(kTftBacklight, 0);

    spi_bus_config_t busConfig = {};
    busConfig.sclk_io_num = kTftSclk;
    busConfig.mosi_io_num = kTftMosi;
    busConfig.miso_io_num = kTftMiso;
    busConfig.quadwp_io_num = -1;
    busConfig.quadhd_io_num = -1;
    busConfig.max_transfer_sz =
        kDisplayWidth * kTransferChunkHeight * sizeof(uint16_t);

    esp_err_t err =
        spi_bus_initialize(SPI3_HOST, &busConfig, SPI_DMA_CH_AUTO);
    if (err != ESP_OK) {
      Serial.printf("SPI3 initialization failed: %s\n", esp_err_to_name(err));
      return false;
    }

    spi_device_interface_config_t deviceConfig = {};
    deviceConfig.clock_speed_hz = kDisplaySpiFrequency;
    deviceConfig.mode = 0;
    deviceConfig.spics_io_num = -1;
    deviceConfig.queue_size = 1;

    err = spi_bus_add_device(SPI3_HOST, &deviceConfig, &spiDevice_);
    if (err != ESP_OK) {
      Serial.printf("ST7789 SPI device setup failed: %s\n",
                    esp_err_to_name(err));
      return false;
    }

    drawBuffer_ = static_cast<uint8_t*>(heap_caps_malloc(
        kDisplayWidth * kTransferChunkHeight * sizeof(uint16_t),
        MALLOC_CAP_DMA));
    if (drawBuffer_ == nullptr) {
      Serial.println("ST7789 DMA buffer allocation failed");
      return false;
    }

    // GPIO5 is shared with the optional LoRa module. Match the working KCS
    // firmware and issue one reset pulse before initializing the controller.
    gpio_reset_pin(kTftReset);
    gpio_set_direction(kTftReset, GPIO_MODE_OUTPUT);
    gpio_set_level(kTftReset, 1);
    delay(1);
    gpio_set_level(kTftReset, 0);
    delay(1);
    gpio_set_level(kTftReset, 1);
    delay(10);

    if (!initializeController()) {
      return false;
    }

    fillScreen(kBlack);
    delay(120);
    if (!writeCommand(0x29)) {  // Display on.
      return false;
    }
    delay(120);

    gpio_set_level(kTftBacklight, 1);
    initialized_ = true;
    return true;
  }

  void drawPixel(int16_t x, int16_t y, uint16_t color) override {
    fillRect(x, y, 1, 1, color);
  }

  void writePixel(int16_t x, int16_t y, uint16_t color) override {
    fillRect(x, y, 1, 1, color);
  }

  void fillRect(int16_t x, int16_t y, int16_t width, int16_t height,
                uint16_t color) override {
    if (x < 0) {
      width += x;
      x = 0;
    }
    if (y < 0) {
      height += y;
      y = 0;
    }
    if (x + width > kDisplayWidth) {
      width = kDisplayWidth - x;
    }
    if (y + height > kDisplayHeight) {
      height = kDisplayHeight - y;
    }
    if (drawBuffer_ == nullptr || width <= 0 || height <= 0) {
      return;
    }

    const uint8_t high = color >> 8;
    const uint8_t low = color;
    for (int16_t row = y; row < y + height;
         row += kTransferChunkHeight) {
      const int16_t chunkHeight =
          min<int16_t>(kTransferChunkHeight, y + height - row);
      const size_t pixelCount = width * chunkHeight;
      for (size_t index = 0; index < pixelCount; ++index) {
        drawBuffer_[index * 2] = high;
        drawBuffer_[index * 2 + 1] = low;
      }

      if (!setWindow(x, row, x + width, row + chunkHeight) ||
          !writePixels(drawBuffer_, pixelCount * sizeof(uint16_t))) {
        Serial.println("ST7789 pixel transfer failed");
        return;
      }
    }
  }

  void writeFillRect(int16_t x, int16_t y, int16_t width, int16_t height,
                     uint16_t color) override {
    fillRect(x, y, width, height, color);
  }

  // Copy a fully rendered RGB565 frame into the DMA staging buffer.
  bool present(const uint16_t* pixels) {
    if (!initialized_ || pixels == nullptr) return false;
    for (int y = 0; y < kDisplayHeight; y += kTransferChunkHeight) {
      const int rows = min<int>(kTransferChunkHeight, kDisplayHeight - y);
      const int count = kDisplayWidth * rows;
      for (int i = 0; i < count; ++i) {
        uint16_t c = pixels[y * kDisplayWidth + i];
        drawBuffer_[2 * i] = c >> 8;
        drawBuffer_[2 * i + 1] = c & 0xFF;
      }
      if (!setWindow(0, y, kDisplayWidth, y + rows) ||
          !writePixels(drawBuffer_, count * 2)) return false;
    }
    return true;
  }

  bool initialized() const { return initialized_; }

private:
  bool transmit(const void* data, size_t length, int dcLevel) {
    if (data == nullptr || length == 0) {
      return true;
    }

    gpio_set_level(kTftDc, dcLevel);
    spi_transaction_t transaction = {};
    transaction.length = length * 8;
    transaction.tx_buffer = data;
    const esp_err_t err = spi_device_polling_transmit(spiDevice_, &transaction);
    if (err != ESP_OK) {
      Serial.printf("ST7789 SPI transfer failed: %s\n", esp_err_to_name(err));
      return false;
    }
    return true;
  }

  bool writeCommand(uint8_t command) {
    gpio_set_level(kTftCs, 0);
    const bool success = transmit(&command, sizeof(command), 0);
    gpio_set_level(kTftCs, 1);
    return success;
  }

  bool writeCommandData(uint8_t command, const uint8_t* data, size_t length) {
    gpio_set_level(kTftCs, 0);
    const bool success = transmit(&command, sizeof(command), 0) &&
                         transmit(data, length, 1);
    gpio_set_level(kTftCs, 1);
    return success;
  }

  bool setWindow(int16_t x1, int16_t y1, int16_t x2, int16_t y2) {
    const uint8_t columns[] = {
        static_cast<uint8_t>(x1 >> 8), static_cast<uint8_t>(x1),
        static_cast<uint8_t>((x2 - 1) >> 8), static_cast<uint8_t>(x2 - 1),
    };
    const uint8_t rows[] = {
        static_cast<uint8_t>(y1 >> 8), static_cast<uint8_t>(y1),
        static_cast<uint8_t>((y2 - 1) >> 8), static_cast<uint8_t>(y2 - 1),
    };
    return writeCommandData(0x2A, columns, sizeof(columns)) &&
           writeCommandData(0x2B, rows, sizeof(rows));
  }

  bool writePixels(const uint8_t* data, size_t length) {
    constexpr uint8_t kRamWrite = 0x2C;
    gpio_set_level(kTftCs, 0);
    const bool success = transmit(&kRamWrite, sizeof(kRamWrite), 0) &&
                         transmit(data, length, 1);
    gpio_set_level(kTftCs, 1);
    return success;
  }

  bool initializeController() {
    const uint8_t madctl[] = {kCo16Madctl};
    const uint8_t displayFunction[] = {0x0A, 0x82};
    const uint8_t pixelFormat[] = {0x55};
    const uint8_t porchControl[] = {0x0C, 0x0C, 0x00, 0x33, 0x33};
    const uint8_t gateControl[] = {0x35};
    const uint8_t vcom[] = {0x28};
    const uint8_t lcmControl[] = {0x0C};
    const uint8_t vdvVrhEnable[] = {0x01, 0xFF};
    const uint8_t vrh[] = {0x10};
    const uint8_t vdv[] = {0x20};
    const uint8_t frameRate[] = {0x0F};
    const uint8_t powerControl[] = {0xA4, 0xA1};
    const uint8_t positiveGamma[] = {
        0xD0, 0x00, 0x02, 0x07, 0x0A, 0x28, 0x32,
        0x44, 0x42, 0x06, 0x0E, 0x12, 0x14, 0x17,
    };
    const uint8_t negativeGamma[] = {
        0xD0, 0x00, 0x02, 0x07, 0x0A, 0x28, 0x31,
        0x54, 0x47, 0x0E, 0x1C, 0x17, 0x1B, 0x1E,
    };

    if (!writeCommand(0x11)) {  // Sleep out.
      return false;
    }
    delay(120);

    return writeCommand(0x13) &&
           writeCommandData(0x36, madctl, sizeof(madctl)) &&
           writeCommandData(0xB6, displayFunction, sizeof(displayFunction)) &&
           writeCommandData(0x3A, pixelFormat, sizeof(pixelFormat)) &&
           (delay(10), true) &&
           writeCommandData(0xB2, porchControl, sizeof(porchControl)) &&
           writeCommandData(0xB7, gateControl, sizeof(gateControl)) &&
           writeCommandData(0xBB, vcom, sizeof(vcom)) &&
           writeCommandData(0xC0, lcmControl, sizeof(lcmControl)) &&
           writeCommandData(0xC2, vdvVrhEnable, sizeof(vdvVrhEnable)) &&
           writeCommandData(0xC3, vrh, sizeof(vrh)) &&
           writeCommandData(0xC4, vdv, sizeof(vdv)) &&
           writeCommandData(0xC6, frameRate, sizeof(frameRate)) &&
           writeCommandData(0xD0, powerControl, sizeof(powerControl)) &&
           writeCommandData(0xE0, positiveGamma, sizeof(positiveGamma)) &&
           writeCommandData(0xE1, negativeGamma, sizeof(negativeGamma)) &&
           writeCommand(0x21);  // Display inversion on.
  }

  spi_device_handle_t spiDevice_ = nullptr;
  uint8_t* drawBuffer_ = nullptr;
  bool initialized_ = false;
};

Co16St7789 display;
GFXcanvas16 canvas(320, 240);
constexpr uint32_t FRAME_MS = 80;   // Target ~12.5 FPS; actual rate depends on SPI.
constexpr uint32_t RELAY_STEP_MS = 250;
constexpr uint32_t SHOW_MS = 32000;
constexpr uint8_t RELAY_ADDRESS = 0x22;
constexpr float TAU = 6.28318530718f;
constexpr uint16_t BG = 0x0001, GRID = 0x0843, CYAN = 0x07FF;
constexpr uint16_t PINK = 0xF81F, WHITE = 0xFFFF, DIM = 0x5B6D;
constexpr uint16_t GREEN = 0x07E0, GOLD = 0xFDE0;
const char* const SCENE_NAMES[] = {
  "SYSTEM BOOT", "RELAY RADAR", "ENERGY CORE", "BEAT MATRIX", "ONE BRAIN"
};
uint32_t showTime = 0, lastTick = 0, lastFrame = 0, lastRelay = 0;
uint16_t relayMask = 0;
bool relayEnabled = true, paused = false, relayFault = false;
int manualScene = -1;

// A single two-byte write changes all 16 PCF8575 outputs together.
// P0 is channel 1. HIGH = OFF, LOW = ON, as in the supplied test.
bool writeRelays(uint16_t mask) {
  uint16_t raw = uint16_t(~mask);
  Wire.beginTransmission(RELAY_ADDRESS);
  Wire.write(uint8_t(raw));
  Wire.write(uint8_t(raw >> 8));
  bool ok = Wire.endTransmission() == 0;
  if (ok) relayMask = mask;
  return ok;
}

uint16_t channelBit(int i) { return uint16_t(1u << (i & 15)); }

int sceneAt(uint32_t t) {
  if (t < 4000) return 0;
  if (t < 12000) return 1;
  if (t < 20000) return 2;
  if (t < 28000) return 3;
  return 4;
}
uint32_t sceneStart(int s) {
  const uint32_t starts[] = {0, 4000, 12000, 20000, 28000};
  return starts[s];
}

uint16_t patternFor(int s, uint32_t t) {
  uint32_t step = t / RELAY_STEP_MS;
  switch (s) {
    case 0: return channelBit(step % 16);
    case 1: return channelBit(step % 16);
    case 2: {
      int p = step % 14;
      if (p > 7) p = 14 - p;
      return channelBit(p) | channelBit(15 - p);
    }
    case 3: {
      const uint16_t beats[] = {0x1111, 0, 0x2222, 0, 0x4444, 0, 0x8888, 0};
      return beats[step % 8];
    }
    default: return t < 3000 ? channelBit(15 - (step % 16)) : 0;
  }
}

void label(int x, int y, const char* text, int size, uint16_t color) {
  canvas.setTextSize(size);
  canvas.setTextColor(color);
  canvas.setCursor(x, y);
  canvas.print(text);
}
void center(int y, const char* text, int size, uint16_t color) {
  label((320 - int(strlen(text)) * 6 * size) / 2, y, text, size, color);
}

void background(uint32_t t) {
  canvas.fillScreen(BG);
  for (int x = 0; x < 320; x += 20) canvas.drawFastVLine(x, 30, 158, GRID);
  for (int y = 30; y < 188; y += 20) canvas.drawFastHLine(0, y, 320, GRID);
  // Deterministic drifting stars, without allocations or random-state changes.
  for (int i = 0; i < 36; ++i) {
    int x = (i * 73 + t / (15 + i % 7)) % 320;
    int y = 34 + (i * 47) % 149;
    canvas.drawPixel(x, y, i % 3 ? DIM : CYAN);
  }
}

void drawBoot(uint32_t t) {
  center(42, "KinCony", 4, CYAN);
  center(80, "CO16", 3, WHITE);
  center(112, "INITIALIZING THE SHOW", 1, DIM);
  canvas.drawRoundRect(36, 132, 248, 18, 4, CYAN);
  int progress = int((t % 4000) * 242 / 3999);
  canvas.fillRect(39, 135, progress, 12, PINK);
  char line[32];
  snprintf(line, sizeof(line), "16 CHANNELS / %02lu%%", (unsigned long)((t % 4000) * 100 / 3999));
  center(163, line, 1, WHITE);
}

void drawRadar(uint32_t t) {
  const int cx = 96, cy = 108;
  for (int r = 20; r <= 64; r += 22) canvas.drawCircle(cx, cy, r, 0x0329);
  canvas.drawFastHLine(29, cy, 135, 0x0329);
  canvas.drawFastVLine(cx, 41, 135, 0x0329);
  float angle = (t % 4000) * TAU / 4000.0f - TAU / 4;
  for (int j = 12; j >= 0; --j) {
    float a = angle - j * 0.035f;
    canvas.drawLine(cx, cy, cx + int(cosf(a) * 63), cy + int(sinf(a) * 63),
                    j == 0 ? CYAN : uint16_t((12 - j + 3) << 5));
  }
  for (int i = 0; i < 16; ++i) {
    float a = i * TAU / 16 - TAU / 4;
    int x = cx + int(cosf(a) * 54), y = cy + int(sinf(a) * 54);
    bool on = relayMask & channelBit(i);
    canvas.fillCircle(x, y, on ? 5 : 2, on ? GOLD : DIM);
    if (on) canvas.drawCircle(x, y, 8, CYAN);
  }
  label(181, 51, "SCAN", 3, CYAN);
  label(182, 83, "16 RELAY NODES", 1, WHITE);
  char buf[16];
  snprintf(buf, sizeof(buf), "CH %02lu", (unsigned long)((t / RELAY_STEP_MS) % 16 + 1));
  label(182, 110, buf, 2, GOLD);
  label(182, 144, "COMMAND TRACKER", 1, DIM);
  label(182, 160, "250ms / STEP", 1, DIM);
}

void drawCore(uint32_t t) {
  float phase = t * 0.002f;
  for (int i = 0; i < 4; ++i) {
    int r = 24 + i * 13;
    for (int k = 0; k < 46; ++k) {
      float a = phase * (i % 2 ? -1 : 1) + k * TAU / 60;
      float b = a + TAU / 65;
      canvas.drawLine(160 + int(cosf(a) * r), 109 + int(sinf(a) * r),
                      160 + int(cosf(b) * r), 109 + int(sinf(b) * r), i % 2 ? PINK : CYAN);
    }
  }
  canvas.fillCircle(160, 109, 18 + int(3 * sinf(phase * 3)), 0x0410);
  label(148, 102, "16", 2, WHITE);
  for (int i = 0; i < 8; ++i) {
    int h = 5 + int((sinf(phase * 2 + i * 0.6f) + 1) * 24);
    canvas.fillRect(14 + i * 6, 139 - h, 4, h, CYAN);
    canvas.fillRect(260 + i * 6, 139 - h, 4, h, PINK);
  }
  label(12, 155, "CH 1-8", 1, DIM);
  label(255, 155, "CH 9-16", 1, DIM);
  center(176, "DUAL-WAVE SYNCHRONIZATION", 1, WHITE);
}

void drawBeat(uint32_t t) {
  // Synthetic frequency bars. No microphone, FFT, or audio synchronization.
  float phase = t * 0.004f;
  for (int i = 0; i < 16; ++i) {
    float v = (sinf(phase + i * 0.67f) + sinf(phase * 0.63f - i * 0.41f) + 2) / 4;
    int levels = 2 + int(v * 14);
    for (int j = 0; j < levels; ++j)
      canvas.fillRect(9 + i * 19, 166 - j * 6, 13, 4, j > 11 ? PINK : (j > 6 ? CYAN : 0x0410));
  }
  center(43, "BEAT MATRIX", 2, WHITE);
  center(65, "120 BPM / SYNTHETIC VISUALIZER", 1, DIM);
  canvas.fillCircle(299, 45, 4, (t % 500 < 250) ? GOLD : DIM);
}

void drawFinale(uint32_t t) {
  for (int i = 0; i < 32; ++i) {
    float a = i * TAU / 32;
    int r = 20 + (int(t / 12) + i * 17) % 130;
    canvas.drawLine(160 + int(cosf(a) * r), 108 + int(sinf(a) * r * 0.50f),
                    160 + int(cosf(a) * (r + 7)), 108 + int(sinf(a) * (r + 7) * 0.50f), GRID);
  }
  center(56, "16 CHANNELS", 3, CYAN);
  center(94, "ONE BRAIN.", 3, WHITE);
  center(136, "KinCony CO16 / ESP32-S3", 1, PINK);
  center(165, "www.kincony.com", 1, DIM);
}

void render(int scene, uint32_t t) {
  background(t);
  switch (scene) {
    case 0: drawBoot(t); break;
    case 1: drawRadar(t); break;
    case 2: drawCore(t); break;
    case 3: drawBeat(t); break;
    default: drawFinale(t); break;
  }
  canvas.fillRect(0, 0, 320, 29, BG);
  label(8, 9, "CO16", 2, CYAN);
  label(80, 12, SCENE_NAMES[scene], 1, WHITE);
  label(271, 12, manualScene < 0 ? "AUTO" : "HOLD", 1, PINK);
  canvas.drawFastHLine(8, 28, 304, CYAN);
  // Two rows of numbered output tiles, all drawn from the last ACKed command.
  canvas.fillRect(0, 190, 320, 50, BG);
  for (int i = 0; i < 16; ++i) {
    int x = 8 + (i % 8) * 39, y = 191 + (i / 8) * 18;
    bool on = relayMask & channelBit(i);
    canvas.fillRoundRect(x, y, 32, 15, 3, on ? CYAN : GRID);
    char number[4];
    snprintf(number, sizeof(number), "%02d", i + 1);
    label(x + 10, y + 4, number, 1, on ? BG : DIM);
  }
  const char* status = relayFault ? "I2C ERROR / OUTPUT UNKNOWN" :
    paused ? "PAUSED / RELAYS OFF" : !relayEnabled ? "SCREEN ONLY / RELAYS OFF" : "RELAY COMMANDS / VISUAL DEMO";
  center(231, status, 1, relayFault ? GOLD : DIM);
  if (!display.present(canvas.getBuffer())) {
    writeRelays(0);
    Serial.println("Display transfer failed. Demo halted; OFF command attempted.");
    while (true) { writeRelays(0); delay(1000); }
  }
}

void handleSerial() {
  while (Serial.available()) {
    char c = Serial.read();
    if (c == 'p') paused = !paused;
    if (c == 'x') relayEnabled = false;
    if (c == 'e') relayEnabled = true;
    if (c == '0' || c == 'r') { manualScene = -1; showTime = 0; paused = false; }
    if (c >= '1' && c <= '5') { manualScene = c - '1'; showTime = 0; paused = false; }
    if (c == 'p' || c == 'x' || c == '0' || c == 'r' || (c >= '1' && c <= '5')) {
      if (!writeRelays(0)) relayFault = true;
      lastRelay = millis();
    }
  }
}

void setup() {
  Serial.begin(115200);
  Wire.begin(8, 18);
  Wire.setClock(100000);
  Wire.setTimeOut(20);
  relayFault = !writeRelays(0);
  // Deselect other devices sharing the TFT wires BEFORE enabling SPI3.
  // Do not initialize SD, LoRa, or software SPI on this bus in this demo.
  const int inactiveCs[] = {9, 13, 14, 42};
  for (int pin : inactiveCs) { digitalWrite(pin, HIGH); pinMode(pin, OUTPUT); }
  if (!canvas.getBuffer() || !display.begin()) {
    Serial.println("Display/buffer initialization failed. Demo halted.");
    while (true) { writeRelays(0); delay(1000); }
  }
  canvas.setTextWrap(false);
  Serial.println("CO16 CYBER SHOW: 0=auto 1..5=scene p=pause x=relays off e=relays on r=restart");
  lastTick = lastRelay = millis();
}

void loop() {
  handleSerial();
  uint32_t now = millis();
  uint32_t dt = now - lastTick;
  lastTick = now;
  if (!paused) showTime = (showTime + dt) % SHOW_MS;
  int scene = manualScene < 0 ? sceneAt(showTime) : manualScene;
  uint32_t localTime = manualScene < 0 ? showTime - sceneStart(scene) : showTime;
  // Limit real relay updates independently of display rendering.
  if (now - lastRelay >= RELAY_STEP_MS) {
    lastRelay = now;
    uint16_t wanted = (paused || !relayEnabled || relayFault) ? 0 : patternFor(scene, localTime);
    if (relayFault || wanted != relayMask) {
      if (!writeRelays(wanted)) {
        relayFault = true;  // Latched until reset. Retry OFF, never resume motion.
        Serial.println("Relay I2C error: motion disabled; retrying OFF.");
        writeRelays(0);
      }
    }
  }
  if (now - lastFrame >= FRAME_MS) {
    lastFrame = now;
    render(scene, localTime);
  }
  delay(1);
}
arduino ino file download: 
[attachment=10732]
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download:

.zip   11-CO16_Cyber_Show.ino.merged.zip (Size: 218.48 KB / Downloads: 50)
   
   
   
   
   

Print this item

  KC868-A4 – Relay 1 clicks repeatedly when WiFi Access Point (AP) is enabled
Posted by: Natravn - 11-02-2026, 03:49 PM - Forum: KC868-A series and Uair Smart Controller - Replies (3)

Hello KinCony team,
I have a problem with my KC868-A4 board.
Problem:
Relay 1 switches ON and OFF intermittently when WiFi Access Point (AP) mode is enabled.
I have performed several tests using a simple Arduino sketch with no relay control code at all.
Test results:

  1. Code:
    WIFI_MODE_NULL
    – WiFi disabled: No relay clicking.
  2. Code:
    WIFI_STA
    – Station mode, without connecting to any network: No relay clicking.
  3. Code:
    WIFI_AP
    – Access Point mode: Relay 1 starts clicking intermittently.
Additional information:
  • The DS18B20 temperature sensor on GPIO13 works correctly in all tests.
  • I have tried a different power supply. The problem remains.
  • No external loads or devices are connected to the relay outputs.
  • Relay 1 is the only relay that clicks.
  • The LED for relay 4 stays constantly illuminated.
My questions:
  1. Is this a known issue with the KC868-A4?
  2. Could WiFi AP mode interfere with GPIO2 or the relay driver circuit?
  3. Could this indicate a hardware fault on my board?
  4. Is there a recommended solution?
I would appreciate your help in identifying the problem.
Best regards
Natravn

Print this item