Adsense HTML/JavaScript

Friday, July 22, 2022

Display on I2C SSD1327 grayscale OLED with Arduino Nano RP2040 Connect/CircuitPython

Exercise to display on I2C SSD1327 grayscale OLED with Arduino Nano RP2040 Connect/CircuitPython 7.3.2.


CircuitPython Libraries is needed, visit https://circuitpython.org/libraries to download.

The default I2C pins assigned for Arduino Nano RP2040 Connect/CircuitPython are:
SDA - A4
SCL - A5

The I2C address of my no-brand SSD1327 OLED is 0x3C.



cpyNrp2040_i2c_test.py, I2C test code to I2C pins and address.
import board

i2c = board.I2C()

print("SDA :", board.SDA)
print("SCL :", board.SCL)

while not i2c.try_lock():
    pass

print([hex(x) for x in i2c.scan()])
i2c.unlock()


cpyNrp2040_ssd1327_ani.py
"""
Arduino Nano RP2040 Connect/CircuitPython
128x128 I2C ssd1327 OLED support grayscale
- with something animation.

CircuitPython lib need,
have to be copied to CircutPytho device's /lib:
- adafruit_ssd1327.mpy
- adafruit_display_text folder
- adafruit_display_shapes folder
"""

import time
import board
import displayio
import adafruit_ssd1327
import terminalio
from adafruit_display_text import label
from adafruit_display_shapes.roundrect import RoundRect
from adafruit_display_shapes.rect import Rect

import sys, os

displayio.release_displays()

# print system info
print(board.board_id)
print(sys.implementation[0] + ' ' +
      str(sys.implementation[1][0]) +'.'+
      str(sys.implementation[1][1]) +'.'+
      str(sys.implementation[1][2]))
print("=====================================")
info = sys.implementation[0] + ' ' + \
       os.uname()[3] + '\n' + \
       'run on ' + os.uname()[4]
print(info)
print("=====================================")
print(adafruit_ssd1327.__name__,
      adafruit_ssd1327.__version__)

# Use for I2C
i2c = board.I2C()
#display_bus = displayio.I2CDisplay(i2c, device_address=0x3D)
display_bus = displayio.I2CDisplay(i2c, device_address=0x3C)

display_width = display_height = 128

time.sleep(1)
display = adafruit_ssd1327.SSD1327(display_bus,
                                   width=display_width,
                                   height=display_height)

print()
print(display)
print(display.width,"x", display.height)
print()

g = displayio.Group()
color_count = 128
pattern = displayio.Bitmap(display_width,
                           display_height,
                           color_count)
palette = displayio.Palette(color_count)
t = displayio.TileGrid(pattern, pixel_shader=palette)

pattern.fill(color_count-1)

#init palette
for i in range(color_count):
    component = i * 255 // (color_count - 1)
    #print(component)
    palette[i] = component << 16 | component << 8 | component
    
    """
    print(i, ' - ' ,
          component,":",
          hex(component << 16),
          hex(component << 8),
          hex(component))
    """

g.append(t)

display.show(g)

time.sleep(1)

for i in range(color_count):
    for z in range(i+1):
        pattern[z, 0] = i
        pattern[z, i] = i
        pattern[0, z] = i
        pattern[i, z] = i
    #for y in range(i+1):
    #    pattern[0, y] = i
    #    pattern[i, y] = i

    #time.sleep(0.2)

time.sleep(1)

#================================================
#reverse palette
for i in range(color_count):
    component = i * 255 // (color_count - 1)
    palette[color_count-1-i] = (
        component << 16 | component << 8 | component)
    
time.sleep(3)

#re-reverse palette
for i in range(color_count):
    component = i * 255 // (color_count - 1)
    palette[i] = (
        component << 16 | component << 8 | component)
    
time.sleep(1)
#================================================
#prepare to animate somethin
group_ani = displayio.Group(scale=1)
group_ani.x = 0
group_ani.y = 0
label_ani = label.Label(terminalio.FONT,
                        text="  hello  ",
                        color=0xFFFFFF)
label_ani.anchor_point = (0.0, 0.0)
label_ani.anchored_position = (0, 0)
label_ani_width = label_ani.bounding_box[2]
label_ani_height = label_ani.bounding_box[3]
shape_ani = RoundRect(x=0, y=0,
                       width=label_ani_width,
                       height=label_ani_height,
                       r=6,
                       fill=0x000000,
                       outline=0xFFFFFF, stroke=1)

group_ani.append(shape_ani)
group_ani.append(label_ani)
g.append(group_ani)
#================================================
#prepare to somethin on fixed position
group_fix = displayio.Group(scale=2)
group_fix.x = 70
group_fix.y = 20
label_fix = label.Label(terminalio.FONT,
                        text=":)",
                        color=0xFFFFFF)
label_fix.anchor_point = (0.0, 0.0)
label_fix.anchored_position = (0, 0)
label_fix_width = label_fix.bounding_box[2]
label_fix_height = label_fix.bounding_box[3]
shape_fix = Rect(x=0, y=0,
                 width=label_fix_width,
                 height=label_fix_height,
                 fill=0x000000,
                 outline=0xFFFFFF, stroke=1)

group_fix.append(shape_fix)
group_fix.append(label_fix)
g.append(group_fix)
#=== loop of animation ===
aniXMove = +1
aniYMove = +1
aniXLim = display_width - 1 - label_ani_width
aniYLim = display_height - 1 - label_ani_height

NxAniMs = time.monotonic() + 3

while True:
    time.sleep(0.05)
    
    if time.monotonic() > NxAniMs:
        NxAniMs = time.monotonic() + 1
        
    #Move Temperate group
    x = group_ani.x + aniXMove
    group_ani.x = x
    if aniXMove > 0:
        if x >= aniXLim:
            aniXMove = -1
    else:
        if x <= 0:
            aniXMove = +1
            
    y = group_ani.y + aniYMove
    group_ani.y = y
    if aniYMove > 0:
        if y > aniYLim:
            aniYMove = -1
    else:
        if y <= 0:
            aniYMove = +1

#================================================
            
print("~ bye ~")



cpyNrp2040_ssd1327_ani2.py
"""
Arduino Nano RP2040 Connect/CircuitPython
128x128 I2C ssd1327 OLED support grayscale
- Change background bitmap by changing palette

CircuitPython lib need,
have to be copied to CircutPytho device's /lib:
- adafruit_ssd1327.mpy
- adafruit_display_text folder
- adafruit_display_shapes folder
"""

import time
import board
import displayio
import adafruit_ssd1327
import terminalio
from adafruit_display_text import label
from adafruit_display_shapes.circle import Circle

import sys, os

displayio.release_displays()

# print system info
print(board.board_id)
print(sys.implementation[0] + ' ' +
      str(sys.implementation[1][0]) +'.'+
      str(sys.implementation[1][1]) +'.'+
      str(sys.implementation[1][2]))
print("=====================================")
info = sys.implementation[0] + ' ' + \
       os.uname()[3] + '\n' + \
       'run on ' + os.uname()[4]
print(info)
print("=====================================")
print(adafruit_ssd1327.__name__,
      adafruit_ssd1327.__version__)

# Use for I2C
i2c = board.I2C()
#display_bus = displayio.I2CDisplay(i2c, device_address=0x3D)
display_bus = displayio.I2CDisplay(i2c, device_address=0x3C)

display_width = display_height = 128

time.sleep(1)
display = adafruit_ssd1327.SSD1327(display_bus,
                                   width=display_width,
                                   height=display_height)

print()
print(display)
print(display.width,"x", display.height)
print()

g = displayio.Group()

# I define the OLED in 16 grayscale,
# hardcode defined in a list (instead of by calculating),
# such that you can manual set according to your need.
grayscale = [0x00, 0x10, 0x20, 0x30,
             0x40, 0x50, 0x60, 0x70,
             0x80, 0x90, 0xA0, 0xB0,
             0xC0, 0xD0, 0xE0, 0xF0]
grayscale_count = len(grayscale)
#print([hex(g) for g in grayscale])
#print(grayscale_count)

#back ground have on color only
bg_color_count = 1
bg_bitmap = displayio.Bitmap(display_width,
                           display_height,
                           bg_color_count)
bg_palette = displayio.Palette(bg_color_count)
t = displayio.TileGrid(bg_bitmap,
                       pixel_shader=bg_palette)

bg_bitmap.fill(0)

print()
print("default bg_palette without init")
print([hex(p) for p in bg_palette])
print()

#================================================
#prepare to display grayscale
group_gray = displayio.Group(scale=1)
group_gray.x = 0
group_gray.y = 0
label_gray = label.Label(terminalio.FONT,
                        text="    ",
                        color=0xB0B0B0)
label_gray.anchor_point = (0.0, 0.0)
label_gray.anchored_position = (10, 10)
label_gray_width = label_gray.bounding_box[2]
label_gray_height = label_gray.bounding_box[3]

shape_gray = Circle(x0=0,
                    y0=0,
                    r=80,
                    fill=0xFFFFFF,
                    outline=0x000000,
                    stroke=3)

group_gray.append(shape_gray)
group_gray.append(label_gray)

#====================================

g.append(t)
g.append(group_gray)

display.show(g)

for gs in grayscale:
    
    bg_palette[0] = (gs << 16
                     | gs << 8
                     | gs)
    
    # you can try to remove any elements
    # to check the effect.
    #bg_palette[0] = (0
    #                 | gs << 8
    #                 | 0)
    
    #print([hex(p) for p in bg_palette])
    label_gray.text = str(hex(bg_palette[0]))
    time.sleep(0.5)

time.sleep(1)

#================================================
            
print("~ bye ~")



Saturday, July 16, 2022

My color TFT collection: ILI9488, ST7796

My SPI color TFT collection:
3.5" 480x320 SPI TFT ILI9488 with Touch
SKU:MSP3520
- product page


4" 480x320 SPI TFT ST7796 with Touch
SKU:MSP4021
- product page


















Friday, July 15, 2022

my dev. board: micro:bit, and Edge Breakout for micro:bit

Here are new member of my dev. board collection: BBC micro:bit, and WaveShare Edge Breakout for micro:bit.








Sunday, July 10, 2022

ESP32-C3/MicroPython BLE UART Communication


In my form posts:
MicroPython bluetooth (BLE) exampls, run on ESP32-C3 show steps to run MicroPython BLE examples, with example of dummy BLE UART example.
MicroPython/ESP32-C3 Exercise: send/receive command via BLE UART modified to send command via UART to control onboard RGB LED remotely.

In this post, it's modified to implement bi-direction BLE UART communication, user enter text, and display on I2C SSD1306 OLED.

For the OLED, read the post ESP32-C3/MicroPython + SSD1306 I2C OLED.

- Once Central connected to Peripheral (both onboard RGB LED ON), user enter text in REPL.
- Central send the text to Peripheral via BLE UART.
- In Peripheral received the text, display on SSD1306 and echo back to Central via BLE UART.
- Central received the text, display on SSD1306.

mpyESP-C3-32S-Kit_ble_simple_peripheral_UART_ssd1306.py

"""
MicroPython/AI-Thinker NodeMCU ESP-C3-32S-Kit
BLE UART Exercise, act as peripheral,
with 128x64 I2C SSD1306 OLED.

Connection between:
ESP32-C3   I2C SSD1306 OLED
============================
GND        GND
3V3        VCC
18         SCL
19         SDA


modified from ble_simple_peripheral.py
"""

# This example demonstrates a UART periperhal.

import bluetooth
import random
import struct
import time
from ble_advertising import advertising_payload

from micropython import const

from machine import Pin, I2C, PWM
import ssd1306

# NodeMCU ESP-C3-32S-Kit onboard LEDs assignment
pwmR = PWM(Pin(3))
pwmG = PWM(Pin(4))
pwmB = PWM(Pin(5))

# set PWM frequency from 1Hz to 40MHz
pwmR.freq(1000)
pwmG.freq(1000)
pwmB.freq(1000)

_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)

_FLAG_READ = const(0x0002)
_FLAG_WRITE_NO_RESPONSE = const(0x0004)
_FLAG_WRITE = const(0x0008)
_FLAG_NOTIFY = const(0x0010)

_UART_UUID = bluetooth.UUID(
    "6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
_UART_TX = (bluetooth.UUID(
    "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"),
    _FLAG_READ | _FLAG_NOTIFY,
)
_UART_RX = (bluetooth.UUID(
    "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"),
    _FLAG_WRITE | _FLAG_WRITE_NO_RESPONSE,
)
_UART_SERVICE = (
    _UART_UUID,
    (_UART_TX, _UART_RX),
)


class BLESimplePeripheral:
    def __init__(self, ble, name="mpy-uart"):
        self._ble = ble
        self._ble.active(True)
        self._ble.irq(self._irq)
        ((self._handle_tx, self._handle_rx),) \
                           = self._ble.gatts_register_services(
                               (_UART_SERVICE,))
        self._connections = set()
        self._write_callback = None
        self._payload = advertising_payload(
            name=name, services=[_UART_UUID])
        self._advertise()

    def _irq(self, event, data):
        # Track connections so we can send notifications.
        if event == _IRQ_CENTRAL_CONNECT:
            conn_handle, _, _ = data
            print("New connection", conn_handle)
            self._connections.add(conn_handle)
            
            #turn ON GREEN LED
            pwmG.duty(10)
            
            oled_ssd1306.fill(0)    #clear screen
            oled_ssd1306.text("Connected", 0, 0 , 1)
            oled_ssd1306.show()
        elif event == _IRQ_CENTRAL_DISCONNECT:
            conn_handle, _, _ = data
            print("Disconnected", conn_handle)
            self._connections.remove(conn_handle)
            # Start advertising again to allow a new connection.
            self._advertise()
            
            #turn OFF GREEN LED
            pwmG.duty(0)
            
            oled_ssd1306.fill(0)    #clear screen
            oled_ssd1306.text("Disconnected", 0, 0 , 1)
            oled_ssd1306.show()
        elif event == _IRQ_GATTS_WRITE:
            conn_handle, value_handle = data
            value = self._ble.gatts_read(value_handle)
            if (value_handle == self._handle_rx
                and self._write_callback):
                self._write_callback(value)

    def send(self, data):
        for conn_handle in self._connections:
            self._ble.gatts_notify(
                conn_handle, self._handle_tx, data)

    def is_connected(self):
        return len(self._connections) > 0

    def _advertise(self, interval_us=500000):
        print("Starting advertising")
        self._ble.gap_advertise(
            interval_us, adv_data=self._payload)

    def on_write(self, callback):
        self._write_callback = callback


def demo():
    ble = bluetooth.BLE()
    p = BLESimplePeripheral(ble)

    def on_rx(v):
        print("RX", v)
        
        oled_ssd1306.scroll(0,-10)
        oled_ssd1306.fill_rect(0, 50,
                               oled_ssd1306.width-1, 10,
                               0)
        oled_ssd1306.text(v, 0, 50 , 1)
        oled_ssd1306.show()
        
        # echo back in upper case
        p.send(v.upper())
        
    p.on_write(on_rx)

    i = 0
    while True:
        pass
#        if p.is_connected():
#            # Short burst of queued notifications.
#            for _ in range(3):
#                data = str(i) + "_"
#                print("TX", data)
#                p.send(data)
#                i += 1
#        time.sleep_ms(100)

if __name__ == "__main__":
    #All OFF all onboard LED
    pwmR.duty(0)
    pwmG.duty(0)
    pwmB.duty(0)
    
    oled_i2c = I2C(0)
    print("Default I2C:", oled_i2c, "\n")
    
    try:
        oled_ssd1306 = ssd1306.SSD1306_I2C(128, 64, oled_i2c)
        print("Default SSD1306 I2C address:",
              oled_ssd1306.addr, "/",
              hex(oled_ssd1306.addr))
        oled_ssd1306.text('ESP32C3 BLE UART', 0, 0, 1)
        oled_ssd1306.text('Peripheral', 0, 10, 1)
        oled_ssd1306.show()
    except OSError as exc:
        print("OSError!", exc)
        if exc.errno == errno.ENODEV:
            print("No such device")


    demo()


mpyESP32-C3-DevKitM-1_ble_simple_central_UART_128x32.py
"""
MicroPython/Espressif ESP32-C3-DevKitM-1
BLE UART Exercise, act as central,
with 128x32 I2C SSD1306 OLED.

Connection between:
ESP32-C3   I2C SSD1306 OLED
============================
GND        GND
3V3        VCC
18         SCL
19         SDA
"""

# This example finds and connects to a peripheral running the
# UART service (e.g. ble_simple_peripheral.py).

import bluetooth
#import random
#import struct
import time

from ble_advertising import decode_services, decode_name

from micropython import const
from neopixel import NeoPixel
import _thread

from machine import Pin, I2C
import ssd1306

# On Espreffif ESP32-C3-DevKitM-1:
# The onboard RGB LED (WS2812) is connected to GPIO8

np = NeoPixel(Pin(8), 1)

rqs_to_send =False
to_send = ""

_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)
_IRQ_GATTS_READ_REQUEST = const(4)
_IRQ_SCAN_RESULT = const(5)
_IRQ_SCAN_DONE = const(6)
_IRQ_PERIPHERAL_CONNECT = const(7)
_IRQ_PERIPHERAL_DISCONNECT = const(8)
_IRQ_GATTC_SERVICE_RESULT = const(9)
_IRQ_GATTC_SERVICE_DONE = const(10)
_IRQ_GATTC_CHARACTERISTIC_RESULT = const(11)
_IRQ_GATTC_CHARACTERISTIC_DONE = const(12)
_IRQ_GATTC_DESCRIPTOR_RESULT = const(13)
_IRQ_GATTC_DESCRIPTOR_DONE = const(14)
_IRQ_GATTC_READ_RESULT = const(15)
_IRQ_GATTC_READ_DONE = const(16)
_IRQ_GATTC_WRITE_DONE = const(17)
_IRQ_GATTC_NOTIFY = const(18)
_IRQ_GATTC_INDICATE = const(19)

_ADV_IND = const(0x00)
_ADV_DIRECT_IND = const(0x01)
_ADV_SCAN_IND = const(0x02)
_ADV_NONCONN_IND = const(0x03)

_UART_SERVICE_UUID = bluetooth.UUID(
    "6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
_UART_RX_CHAR_UUID = bluetooth.UUID(
    "6E400002-B5A3-F393-E0A9-E50E24DCCA9E")
_UART_TX_CHAR_UUID = bluetooth.UUID(
    "6E400003-B5A3-F393-E0A9-E50E24DCCA9E")


class BLESimpleCentral:
    def __init__(self, ble):
        self._ble = ble
        self._ble.active(True)
        self._ble.irq(self._irq)

        self._reset()

    def _reset(self):
        # Cached name and address from a successful scan.
        self._name = None
        self._addr_type = None
        self._addr = None

        # Callbacks for completion of various operations.
        # These reset back to None after being invoked.
        self._scan_callback = None
        self._conn_callback = None
        self._read_callback = None

        # Persistent callback for when
        # new data is notified from the device.
        self._notify_callback = None

        # Connected device.
        self._conn_handle = None
        self._start_handle = None
        self._end_handle = None
        self._tx_handle = None
        self._rx_handle = None

    def _irq(self, event, data):
        if event == _IRQ_SCAN_RESULT:
            addr_type, addr, adv_type, rssi, adv_data = data
            if (adv_type in (_ADV_IND, _ADV_DIRECT_IND)
                and
                _UART_SERVICE_UUID in decode_services(adv_data)):
                # Found a potential device,
                # remember it and stop scanning.
                self._addr_type = addr_type
                self._addr = bytes(
                    addr
                )  # Note: addr buffer is owned by
                   #       caller so need to copy it.
                self._name = decode_name(adv_data) or "?"
                self._ble.gap_scan(None)

        elif event == _IRQ_SCAN_DONE:
            if self._scan_callback:
                if self._addr:
                    # Found a device during the scan
                    # (and the scan was explicitly stopped).
                    self._scan_callback(
                        self._addr_type, self._addr, self._name)
                    self._scan_callback = None
                else:
                    # Scan timed out.
                    self._scan_callback(None, None, None)

        elif event == _IRQ_PERIPHERAL_CONNECT:
            # Connect successful.
            conn_handle, addr_type, addr = data
            if addr_type == self._addr_type and addr == self._addr:
                self._conn_handle = conn_handle
                self._ble.gattc_discover_services(self._conn_handle)

        elif event == _IRQ_PERIPHERAL_DISCONNECT:
            # Disconnect (either initiated by us or the remote end).
            conn_handle, _, _ = data
            if conn_handle == self._conn_handle:
                # If it was initiated by us, it'll already be reset.
                self._reset()

        elif event == _IRQ_GATTC_SERVICE_RESULT:
            # Connected device returned a service.
            conn_handle, start_handle, end_handle, uuid = data
            print("service", data)
            if (conn_handle == self._conn_handle
                and
                uuid == _UART_SERVICE_UUID):
                self._start_handle, self._end_handle \
                                    = start_handle, end_handle

        elif event == _IRQ_GATTC_SERVICE_DONE:
            # Service query complete.
            if self._start_handle and self._end_handle:
                self._ble.gattc_discover_characteristics(
                    self._conn_handle,
                    self._start_handle,
                    self._end_handle)
            else:
                print("Failed to find uart service.")

        elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
            # Connected device returned a characteristic.
            conn_handle, def_handle, value_handle, properties, uuid = data
            if (conn_handle == self._conn_handle
                and
                uuid == _UART_RX_CHAR_UUID):
                self._rx_handle = value_handle
            if (conn_handle == self._conn_handle
                and
                uuid == _UART_TX_CHAR_UUID):
                self._tx_handle = value_handle

        elif event == _IRQ_GATTC_CHARACTERISTIC_DONE:
            # Characteristic query complete.
            if (self._tx_handle is not None
                and
                self._rx_handle is not None):
                # We've finished connecting and
                # discovering device, fire the connect callback.
                if self._conn_callback:
                    self._conn_callback()
            else:
                print("Failed to find uart rx characteristic.")

        elif event == _IRQ_GATTC_WRITE_DONE:
            conn_handle, value_handle, status = data
            print("TX complete")

        elif event == _IRQ_GATTC_NOTIFY:
            conn_handle, value_handle, notify_data = data
            if (conn_handle == self._conn_handle
                and
                value_handle == self._tx_handle):
                if self._notify_callback:
                    self._notify_callback(notify_data)

    # Returns true if we've successfully connected
    # and discovered characteristics.
    def is_connected(self):
        return (
            self._conn_handle is not None
            and self._tx_handle is not None
            and self._rx_handle is not None
        )

    # Find a device advertising the environmental
    # sensor service.
    def scan(self, callback=None):
        self._addr_type = None
        self._addr = None
        self._scan_callback = callback
        self._ble.gap_scan(2000, 30000, 30000)

    # Connect to the specified device (otherwise
    # use cached address from a scan).
    def connect(self, addr_type=None, addr=None, callback=None):
        self._addr_type = addr_type or self._addr_type
        self._addr = addr or self._addr
        self._conn_callback = callback
        if self._addr_type is None or self._addr is None:
            return False
        self._ble.gap_connect(self._addr_type, self._addr)
        return True

    # Disconnect from current device.
    def disconnect(self):
        if not self._conn_handle:
            return
        self._ble.gap_disconnect(self._conn_handle)
        self._reset()

    # Send data over the UART
    def write(self, v, response=False):
        if not self.is_connected():
            return
        self._ble.gattc_write(self._conn_handle,
                              self._rx_handle,
                              v,
                              1 if response else 0)

    # Set handler for when data is received over the UART.
    def on_notify(self, callback):
        self._notify_callback = callback

def demo():
    global rqs_to_send
    global to_send
    
    ble = bluetooth.BLE()
    central = BLESimpleCentral(ble)

    not_found = False
    
    #Turn ON onboard RGB BLUE
    np[0] = (0, 0, 10)
    np.write()
    
    def on_scan(addr_type, addr, name):
        if addr_type is not None:
            print("Found peripheral:",
                  addr_type, addr, name)
            central.connect()
        else:
            nonlocal not_found
            not_found = True
            print("No peripheral found.")
            
            #Turn ON onboard RGB BLUE
            np[0] = (10, 0, 0)
            np.write()

    central.scan(callback=on_scan)

    # Wait for connection...
    while not central.is_connected():
        time.sleep_ms(100)
        if not_found:
            return

    #Turn ON onboard RGB GREEN
    np[0] = (0, 10, 0)
    np.write()
    
    oled_ssd1306.fill(0)    #clear screen
    oled_ssd1306.text("Connected", 0, 0 , 1)
    oled_ssd1306.show()
            
    print("Connected")
    print("Enter anything to send")
    
    rqs_to_send = False  # clear previous request

    def on_rx(v):
        # convert memoryview to str
        v_str = str(v,'utf8')
        print("RX", v, " : ", v_str)
        
        oled_ssd1306.scroll(0,-10)
        oled_ssd1306.fill_rect(0, 20,
                               oled_ssd1306.width-1, 10,
                               0)
        oled_ssd1306.text(v_str, 0, 20 , 1)
        oled_ssd1306.show()

    central.on_notify(on_rx)

    with_response = False

#    i = 0
    while central.is_connected():
    
        if rqs_to_send:
            central.write(to_send, with_response)
            rqs_to_send = False
            
#        try:
#            v = str(i) + "_"
#            print("TX", v)
#            central.write(v, with_response)
#        except:
#            print("TX failed")
#        i += 1
#       time.sleep_ms(400 if with_response else 30)

    #Turn OFF onboard RGB
    np[0] = (0, 0, 0)
    np.write()
    
    oled_ssd1306.fill(0)    #clear screen
    oled_ssd1306.text("Disconnected", 0, 0 , 1)
    oled_ssd1306.show()
    
    print("Disconnected")


if __name__ == "__main__":
    
    #All OFF all onboard RGB
    np[0] = (0, 0, 0)
    np.write()
    
    oled_i2c = I2C(0)
    print("Default I2C:", oled_i2c, "\n")
    
    try:
        oled_ssd1306 = ssd1306.SSD1306_I2C(128, 32, oled_i2c)
        print("Default SSD1306 I2C address:",
              oled_ssd1306.addr, "/",
              hex(oled_ssd1306.addr))
        oled_ssd1306.text('ESP32C3 BLE UART', 0, 0, 1)
        oled_ssd1306.text('Central', 0, 10, 1)
        oled_ssd1306.show()
    except OSError as exc:
        print("OSError!", exc)
        if exc.errno == errno.ENODEV:
            print("No such device")
    
    def input_thread():
        global rqs_to_send
        global to_send
        while True:
            time.sleep(0.1)
            to_send = input()
            rqs_to_send = True
    
    # In my trial:
    # Without call _thread.stack_size(32768) will easy
    # to force reboot by:
    # ***ERROR*** A stack overflow in task mp_thread has been detected.
    _thread.stack_size(32768)
    _thread.start_new_thread(input_thread, ())
    
    demo()


Wednesday, July 6, 2022

ESP32-C3/MicroPython multithreading exercise, get user input un-blocked using _thread.

This exercise get user input by call input(). But input() is a blocking function, means it blocks further execution of a program until user enter something. In this exercise code, read user input by calling input() and control RGB in two separated thread using _thread.

Please notice that _thread currently is highly experimental and its API is not yet fully settled.


mpyC3_thread.py
"""
ESP32-C3/MicroPython exercise:
read user input non-blocked using _thread

MicroPython libraries _thread (multithreading support)
https://docs.micropython.org/en/latest/library/_thread.html

This module is highly experimental and its API is not yet fully
settled and not yet described in documentation.

So, basically - the excise is by guessing, and run as is.

Tested on Espressif ESP32-C3-DevKitM-1/micropython v1.19.1
"""
import os
import sys
import time
import _thread
import neopixel
from machine import Pin

# On Espreffif ESP32-C3-DevKitM-1:
# The onboard RGB LED (WS2812) is connected to GPIO8
np = neopixel.NeoPixel(Pin(8), 1)

rqs_to_show =False
to_show = ""

print()

print("====================================")
print(sys.implementation[0], os.uname()[3],
      "\nrun on", os.uname()[4])
print("====================================")

# thread to read user input,
# input() will block the program,
# so have to run in another thread.
def input_thread():
    global rqs_to_show
    global to_show
    while True:
        user_input = input()
        to_show = user_input
        rqs_to_show = True
        print("in input_thread() => ", user_input)
        
# thread to change RGB repeatly.
def rgb_thread():
    while True:
        np[0] = (10, 0, 0)
        np.write()
        time.sleep(0.5)
        np[0] = (0, 10, 0)
        np.write()
        time.sleep(0.5)
        np[0] = (0, 0, 10)
        np.write()
        time.sleep(0.5)

_thread.start_new_thread(input_thread, ())
_thread.start_new_thread(rgb_thread, ())

while True:
    if rqs_to_show:
        rqs_to_show = False
        print("in main thread: rqs_to_show -> ", to_show)

Next:
~ applied on real exercise: ESP32-C3/MicroPython BLE UART Communication

Sunday, July 3, 2022

MicroPython/ESP32-C3 Exercise: send/receive command via BLE UART

My former post show steps to MicroPython bluetooth (BLE) exampls, run on ESP32-C3. It's modified to send and receive command to control onboard LED remotely.

ble_simple_peripheral_LED.py (modified from ble_simple_peripheral.py) run on AI-Thinker NodeMCU ESP-C3-32S-Kit, act to be BLE Peripheral.

ble_simple_central_button.py (modified from ble_simple_central.py) run on Espressif ESP32-C3-DevKitM-1, act to be BLE Central.

Both flashed with MicroPython v1.19.1 frameware. ble_advertising.py have to be saved on both central/peripheral MicroPython device.

Once connected, user pressed central's onboard button to send command to peripheral via BLE UART, to toggle peripheral onboard LED.

In peripheral side, turn ON/OFF onboard LED according to received command, and send back the command to central, to control central's onboard LED. 

Once central receive command, turn ON/OFF onboard LED accordingly.

related:
MicroPython/NodeMCU ESP-C3-32S-Kit to control onboard LEDs
MicroPython/ESP32-C3-DevKitM-1 exercise: onboard BOOT button, and RGB LED (Neopixel)


ble_simple_peripheral_LED.py

"""
MicroPython(v1.19.1) exercise
run on AI-Thinker NodeMCU ESP-C3-32S-Kit
act as BLE UART periperhal.

Receive command from central, turn on/off onboard LED,
and send back the command to central.

Modified from MicroPython ble_simple_peripheral.py example
https://github.com/micropython/micropython/
blob/master/examples/bluetooth/ble_simple_central.py

"""

# This example demonstrates a UART periperhal.

import bluetooth
import random
import struct
import time
from ble_advertising import advertising_payload
from machine import Pin

from micropython import const

CMD_LEDON = b'LEDON\r\n'
CMD_LEDOFF = b'LEDOFF\r\n'

# NodeMCU ESP-C3-32S-Kit onboard LEDs assignment
pinR = Pin(3, Pin.OUT)
pinG = Pin(4, Pin.OUT)
pinB = Pin(5, Pin.OUT)

_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)

_FLAG_READ = const(0x0002)
_FLAG_WRITE_NO_RESPONSE = const(0x0004)
_FLAG_WRITE = const(0x0008)
_FLAG_NOTIFY = const(0x0010)

_UART_UUID = bluetooth.UUID(
    "6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
_UART_TX = (
    bluetooth.UUID(
        "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"),
    _FLAG_READ | _FLAG_NOTIFY,
)
_UART_RX = (
    bluetooth.UUID(
        "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"),
    _FLAG_WRITE | _FLAG_WRITE_NO_RESPONSE,
)
_UART_SERVICE = (
    _UART_UUID,
    (_UART_TX, _UART_RX),
)


class BLESimplePeripheral:
    def __init__(self, ble, name="mpy-uart"):
        self._ble = ble
        self._ble.active(True)
        self._ble.irq(self._irq)
        ((self._handle_tx,
          self._handle_rx),) \
          = self._ble.gatts_register_services(
              (_UART_SERVICE,))
        self._connections = set()
        self._write_callback = None
        self._payload = \
                      advertising_payload(
                          name=name, services=[_UART_UUID])
        self._advertise()

    def _irq(self, event, data):
        # Track connections so we can send notifications.
        if event == _IRQ_CENTRAL_CONNECT:
            conn_handle, _, _ = data
            print("New connection", conn_handle)
            self._connections.add(conn_handle)
        elif event == _IRQ_CENTRAL_DISCONNECT:
            conn_handle, _, _ = data
            print("Disconnected", conn_handle)
            self._connections.remove(conn_handle)
            # Start advertising again to allow a new connection.
            self._advertise()
        elif event == _IRQ_GATTS_WRITE:
            conn_handle, value_handle = data
            value = self._ble.gatts_read(value_handle)
            if (value_handle == self._handle_rx and
                self._write_callback):
                self._write_callback(value)

    def send(self, data):
        for conn_handle in self._connections:
            self._ble.gatts_notify(conn_handle,
                                   self._handle_tx,
                                   data)

    def is_connected(self):
        return len(self._connections) > 0

    def _advertise(self, interval_us=500000):
        print("Starting advertising")
        self._ble.gap_advertise(interval_us,
                                adv_data=self._payload)

    def on_write(self, callback):
        self._write_callback = callback

def Turn_LED(val):
    pinR.value(val)
    pinG.value(val)
    pinB.value(val)

def demo():
    ble = bluetooth.BLE()
    p = BLESimplePeripheral(ble)

    def on_rx(v):
        # command received from central,
        # turn ON/OFF LED accoringly,
        # and send back the command to centrol.
        print("RX", v)
        
        if v == CMD_LEDON:
            Turn_LED(1)
            print("command received: ", CMD_LEDON)
            p.send("from peripheral:")
            p.send(CMD_LEDON)
        elif v == CMD_LEDOFF:
            Turn_LED(0)
            print("command received: ", CMD_LEDOFF)
            p.send("from peripheral:")
            p.send(CMD_LEDOFF)

    p.on_write(on_rx)

    i = 0
    while True:
        """
        if p.is_connected():
            # Short burst of queued notifications.
            for _ in range(3):
                data = str(i) + "_"
                print("TX", data)
                p.send(data)
                i += 1
        """
        time.sleep_ms(100)


if __name__ == "__main__":
    demo()

ble_simple_central_button.py
"""
MicroPython(v1.19.1) exercise
run on Espressif ESP32-C3-DevKitM-1 
act as BLE UART central.

Detect onboard BOOT button,
send command to peripheral to toggle peripheral onboard LED.
and receive command from peripheral, turn on/off onboard.

* No debouncing for BOOT button detection here.

Modified from MicroPython ble_simple_central.py example
https://github.com/micropython/micropython/
blob/master/examples/bluetooth/ble_simple_peripheral.py

"""

# This example finds and connects to a peripheral running the
# UART service (e.g. ble_simple_peripheral.py).

import bluetooth
import random
import struct
import time
import micropython
import machine
import neopixel

from ble_advertising import decode_services, decode_name

from micropython import const

CMD_LEDON = b'LEDON\r\n'
CMD_LEDOFF = b'LEDOFF\r\n'

button_BOOT = machine.Pin(9,
                          machine.Pin.IN,
                          machine.Pin.PULL_UP)
np = neopixel.NeoPixel(machine.Pin(8), 1)

# To turn OFF peripheral LED in first power-up
current_led_val = True
root_button_pressed = True

# Turn OFF onboard RGB
np[0] = (0, 0, 0)
np.write()

def boot_pressed_handler(pin):
    global root_button_pressed
    root_button_pressed = True
    
button_BOOT.irq(trigger=machine.Pin.IRQ_FALLING,
                handler=boot_pressed_handler)

_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)
_IRQ_GATTS_READ_REQUEST = const(4)
_IRQ_SCAN_RESULT = const(5)
_IRQ_SCAN_DONE = const(6)
_IRQ_PERIPHERAL_CONNECT = const(7)
_IRQ_PERIPHERAL_DISCONNECT = const(8)
_IRQ_GATTC_SERVICE_RESULT = const(9)
_IRQ_GATTC_SERVICE_DONE = const(10)
_IRQ_GATTC_CHARACTERISTIC_RESULT = const(11)
_IRQ_GATTC_CHARACTERISTIC_DONE = const(12)
_IRQ_GATTC_DESCRIPTOR_RESULT = const(13)
_IRQ_GATTC_DESCRIPTOR_DONE = const(14)
_IRQ_GATTC_READ_RESULT = const(15)
_IRQ_GATTC_READ_DONE = const(16)
_IRQ_GATTC_WRITE_DONE = const(17)
_IRQ_GATTC_NOTIFY = const(18)
_IRQ_GATTC_INDICATE = const(19)

_ADV_IND = const(0x00)
_ADV_DIRECT_IND = const(0x01)
_ADV_SCAN_IND = const(0x02)
_ADV_NONCONN_IND = const(0x03)

_UART_SERVICE_UUID = bluetooth.UUID(
    "6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
_UART_RX_CHAR_UUID = bluetooth.UUID(
    "6E400002-B5A3-F393-E0A9-E50E24DCCA9E")
_UART_TX_CHAR_UUID = bluetooth.UUID(
    "6E400003-B5A3-F393-E0A9-E50E24DCCA9E")


class BLESimpleCentral:
    def __init__(self, ble):
        self._ble = ble
        self._ble.active(True)
        self._ble.irq(self._irq)

        self._reset()

    def _reset(self):
        # Cached name and address from a successful scan.
        self._name = None
        self._addr_type = None
        self._addr = None

        # Callbacks for completion of various operations.
        # These reset back to None after being invoked.
        self._scan_callback = None
        self._conn_callback = None
        self._read_callback = None

        # Persistent callback for when new data is
        # notified from the device.
        self._notify_callback = None

        # Connected device.
        self._conn_handle = None
        self._start_handle = None
        self._end_handle = None
        self._tx_handle = None
        self._rx_handle = None

    def _irq(self, event, data):
        if event == _IRQ_SCAN_RESULT:
            addr_type, addr, adv_type, rssi, adv_data = data
            if (adv_type in (_ADV_IND, _ADV_DIRECT_IND) and
                _UART_SERVICE_UUID in decode_services(adv_data)):
                # Found a potential device, remember it
                # and stop scanning.
                self._addr_type = addr_type
                self._addr = bytes(
                    addr
                )  # Note: addr buffer is owned by caller so
                   # need to copy it.
                self._name = decode_name(adv_data) or "?"
                self._ble.gap_scan(None)

        elif event == _IRQ_SCAN_DONE:
            if self._scan_callback:
                if self._addr:
                    # Found a device during the scan
                    # (and the scan was explicitly stopped).
                    self._scan_callback(self._addr_type,
                                        self._addr,
                                        self._name)
                    self._scan_callback = None
                else:
                    # Scan timed out.
                    self._scan_callback(None, None, None)

        elif event == _IRQ_PERIPHERAL_CONNECT:
            # Connect successful.
            conn_handle, addr_type, addr = data
            if addr_type == self._addr_type and addr == self._addr:
                self._conn_handle = conn_handle
                self._ble.gattc_discover_services(self._conn_handle)

        elif event == _IRQ_PERIPHERAL_DISCONNECT:
            # Disconnect (either initiated by us or the remote end).
            conn_handle, _, _ = data
            if conn_handle == self._conn_handle:
                # If it was initiated by us, it'll already be reset.
                self._reset()

        elif event == _IRQ_GATTC_SERVICE_RESULT:
            # Connected device returned a service.
            conn_handle, start_handle, end_handle, uuid = data
            print("service", data)
            if conn_handle == self._conn_handle and uuid == _UART_SERVICE_UUID:
                self._start_handle, self._end_handle = start_handle, end_handle

        elif event == _IRQ_GATTC_SERVICE_DONE:
            # Service query complete.
            if self._start_handle and self._end_handle:
                self._ble.gattc_discover_characteristics(
                    self._conn_handle,
                    self._start_handle,
                    self._end_handle
                )
            else:
                print("Failed to find uart service.")

        elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
            # Connected device returned a characteristic.
            conn_handle, def_handle, value_handle, properties, uuid = data
            if (conn_handle == self._conn_handle and
                uuid == _UART_RX_CHAR_UUID):
                self._rx_handle = value_handle
            if (conn_handle == self._conn_handle and
                uuid == _UART_TX_CHAR_UUID):
                self._tx_handle = value_handle

        elif event == _IRQ_GATTC_CHARACTERISTIC_DONE:
            # Characteristic query complete.
            if self._tx_handle is not None and self._rx_handle is not None:
                # We've finished connecting and discovering device,
                # fire the connect callback.
                if self._conn_callback:
                    self._conn_callback()
            else:
                print("Failed to find uart rx characteristic.")

        elif event == _IRQ_GATTC_WRITE_DONE:
            conn_handle, value_handle, status = data
            print("TX complete")

        elif event == _IRQ_GATTC_NOTIFY:
            conn_handle, value_handle, notify_data = data
            if (conn_handle == self._conn_handle
                and value_handle == self._tx_handle):
                if self._notify_callback:
                    self._notify_callback(notify_data)

    # Returns true if we've successfully connected and
    # discovered characteristics.
    def is_connected(self):
        return (
            self._conn_handle is not None
            and self._tx_handle is not None
            and self._rx_handle is not None
        )

    # Find a device advertising the environmental sensor service.
    def scan(self, callback=None):
        self._addr_type = None
        self._addr = None
        self._scan_callback = callback
        self._ble.gap_scan(2000, 30000, 30000)

    # Connect to the specified device
    # (otherwise use cached address from a scan).
    def connect(self, addr_type=None, addr=None, callback=None):
        self._addr_type = addr_type or self._addr_type
        self._addr = addr or self._addr
        self._conn_callback = callback
        if self._addr_type is None or self._addr is None:
            return False
        self._ble.gap_connect(self._addr_type, self._addr)
        return True

    # Disconnect from current device.
    def disconnect(self):
        if not self._conn_handle:
            return
        self._ble.gap_disconnect(self._conn_handle)
        self._reset()

    # Send data over the UART
    def write(self, v, response=False):
        if not self.is_connected():
            return
        self._ble.gattc_write(self._conn_handle,
                              self._rx_handle, v,
                              1 if response else 0)

    # Set handler for when data is received over the UART.
    def on_notify(self, callback):
        self._notify_callback = callback
    
def demo():
    global root_button_pressed
    global current_led_val
    
    ble = bluetooth.BLE()
    central = BLESimpleCentral(ble)

    not_found = False
    
    def send_CMD(cmd):
        try:
            central.write(cmd, with_response)
        except:
            print("TX failed")

    def on_scan(addr_type, addr, name):
        if addr_type is not None:
            print("Found peripheral:", addr_type, addr, name)
            central.connect()
        else:
            nonlocal not_found
            not_found = True
            print("No peripheral found.")

    central.scan(callback=on_scan)

    # Wait for connection...
    while not central.is_connected():
        time.sleep_ms(100)
        if not_found:
            return

    print("Connected")
    
    def on_rx(v):
        # command received from peripheral,
        # update onboard RGB accordingly.
        print("RX", v)
        
        #convert memoryview to str
        cmd = str(v,'utf8')
        print(cmd)
        
        if v == CMD_LEDON:
            np[0] = (3, 3, 0)
            np.write()
        elif v == CMD_LEDOFF:
            np[0] = (0, 0, 0)
            np.write()
            

    central.on_notify(on_rx)

    with_response = False

    while central.is_connected():
        
        if root_button_pressed:
            # BOOT button pressed,
            # send command to peripheral to toggle LED
            root_button_pressed = False
            current_led_val = not current_led_val
            print("- root_button_pressed -", current_led_val)
            
            if current_led_val:
                send_CMD(CMD_LEDON)
                
            else:
                send_CMD(CMD_LEDOFF)

        time.sleep_ms(400 if with_response else 30)

    print("Disconnected")


if __name__ == "__main__":
    demo()

Saturday, July 2, 2022

MicroPython/ESP32-C3-DevKitM-1 exercise: onboard BOOT button, and RGB LED (Neopixel).


Run on Espressif ESP32-C3-DevKitM-1 with MicroPython v1.19.1 on 2022-06-18 installed, the following exercise detect onboard BOOT button, and control onboard RGB LED (Neopixel).


mpyESP32-C3-DevKitM-1_neopixel.py
Simple testing on onboard RGB LED (Neopixel).
import machine
import time
import neopixel

"""
MicroPython v1.19.1/ESP32-C3-DevKitM-1 exercise:
Simple testing on onboard RGB LED (Neopixel).
"""

# On Espreffif ESP32-C3-DevKitM-1:
# The onboard RGB LED (WS2812) is connected to GPIO8

np = neopixel.NeoPixel(machine.Pin(8), 1)

while True:
    np[0] = (0, 0, 0)
    np.write()
    time.sleep(1)
    np[0] = (255, 0, 0)
    np.write()
    time.sleep(1)
    np[0] = (0, 255, 0)
    np.write()
    time.sleep(1)
    np[0] = (0, 0, 255)
    np.write()
    time.sleep(1)
    np[0] = (255, 255, 255)
    np.write()
    time.sleep(1)
    

mpyESP32-C3-DevKitM-1_neopixel_2.py
Control onboard RGB LED (Neopixel), with level control.
import machine
import time
import neopixel

"""
MicroPython v1.19.1/ESP32-C3-DevKitM-1 exercise:
Control onboard RGB LED (Neopixel), with level control.
"""

# On Espreffif ESP32-C3-DevKitM-1:
# The onboard RGB LED (WS2812) is connected to GPIO8

np = neopixel.NeoPixel(machine.Pin(8), 1)

def setNeoPixel(level, enable):
    np[0] = (level * enable[0],
             level * enable[1],
             level * enable[2])
    np.write()
    
def testNeoPixel(enable):
    for l in range(0, 256):
        setNeoPixel(l, enable)
        time.sleep(0.02)

while True:
    np[0] = (0, 0, 0)
    np.write()
    time.sleep(1)

    testNeoPixel([True, False, False])
    testNeoPixel([False, True, False])
    testNeoPixel([False, False, True])
    
    testNeoPixel([True, True, False])
    testNeoPixel([False, True, True])
    testNeoPixel([True, False, True])
    
    testNeoPixel([True, True, True])


mpyESP32-C3-DevKitM-1_button.py
Simple test onboard BOOT button, and verify the logic.
import machine
import time

"""
MicroPython v1.19.1/ESP32-C3-DevKitM-1 exercise:
Simple test onboard BOOT button, and verify the logic.
"""

# On Espreffif ESP32-C3-DevKitM-1:
# The onboard BOOT Button is connected to GPIO9

button_BOOT = machine.Pin(9,
                          machine.Pin.IN,
                          machine.Pin.PULL_UP)

while True:
    time.sleep(0.5)
    print(button_BOOT.value())

mpyESP32-C3-DevKitM-1_button_neopixel.py
Read BOOT button and turn on/off onboard RGB accordingly.
import machine
import time
import neopixel

"""
MicroPython v1.19.1/ESP32-C3-DevKitM-1 exercise:
Read BOOT button and turn on/off onboard RGB accordingly.
"""

# On Espreffif ESP32-C3-DevKitM-1:
# The onboard RGB LED (WS2812) is connected to GPIO8
# The onboard BOOT Button is connected to GPIO9

button_BOOT = machine.Pin(9,
                          machine.Pin.IN,
                          machine.Pin.PULL_UP)
np = neopixel.NeoPixel(machine.Pin(8), 1)

while True:
    time.sleep(0.2)
    if (button_BOOT.value()):  # button released
        np[0] = (0, 0, 0)
    else:                      # button pressed
        np[0] = (0, 3, 0)
    np.write()

mpyESP32-C3-DevKitM-1_button_irq.py
Implement IRQ handler to detect BOOT button pressing, and toggle onboard RGB.
import machine
import time
import neopixel

"""
MicroPython v1.19.1/ESP32-C3-DevKitM-1 exercise:
Implement IRQ handler to detect BOOT button pressing,
and toggle onboard RGB.

* No debouncing for button detection here.
"""

# On Espreffif ESP32-C3-DevKitM-1:
# The onboard RGB LED (WS2812) is connected to GPIO8
# The onboard BOOT Button is connected to GPIO9

button_BOOT = machine.Pin(9,
                          machine.Pin.IN,
                          machine.Pin.PULL_UP)
np = neopixel.NeoPixel(machine.Pin(8), 1)

np[0] = (0, 0, 0)
last_np_state = False
def toggle_LED():
    global last_np_state
    last_np_state =  not last_np_state

    if last_np_state:
        np[0] = (0, 0, 5)
    else:
        np[0] = (0, 0, 0)
    np.write()
    
def boot_pressed_handler(pin):
    print("BOOT button pressed:\t", pin)
    toggle_LED()
    
button_BOOT.irq(trigger=machine.Pin.IRQ_FALLING,
                handler=boot_pressed_handler)

while True:
    pass


Sunday, June 26, 2022

MicroPython bluetooth (BLE) exampls, run on ESP32-C3.

This video just show how MicroPython bluetooth module examples run on ESP32-C3, Ai-Thinker NodeMCU ESP-C3-32S-Kit and Espressif ESP32-C3-DevKitM-1, both running MicroPython v1.19.1 on 2022-06-18. Finally, have bi-direction BLE communication between ESP32-C3 dev. boards.




MicroPython bluetooth module provides an interface to a Bluetooth controller on a board. Currently this supports Bluetooth Low Energy (BLE) in Central, Peripheral, Broadcaster, and Observer roles, as well as GATT Server and Client and L2CAP connection-oriented-channels. A device may operate in multiple roles concurrently. Pairing (and bonding) is supported on some ports.

Note: This module is still under development and its classes, functions, methods and constants are subject to change.

NEXT:
~ It's modified to send/receive command via BLE UART to control LED remotely.
ESP32-C3/MicroPython BLE UART Communication, with user input and display on SSD1306 I2C OLED.


Monday, June 20, 2022

MicroPython/NodeMCU ESP-C3-32S-Kit to control onboard LEDs

With MicroPython v1.19 firmware installed on Ai-Thinker NodeMCU ESP-C3-32S-Kit, this exercise control the onboard LEDs.


Refer to ESP-C3-32S-Kit Specification, there are Cool, Warm and a three-in-one RGB lamp on board.
- IO3  : RGB red lamp beads
- IO4  : RGB green lamp beads
- IO5  : RGB blue lamp beads
- IO18 : Warm color lamp beads
- IO19 : Cool color lamp beads
  (high level is valid)




Exercise code:

mpy_NodeMCU_ESP-C3-32S-Kit_RGB.py, control onboard LEDs as Digital Output.
"""
MicroPython/NodeMCU ESP-C3-32S-Kit exercise
to control RGB LED.
"""
import uos
import usys
from machine import Pin
import time

# NodeMCU ESP-C3-32S-Kit onboard LEDs assignment
pinR = Pin(3, Pin.OUT)
pinG = Pin(4, Pin.OUT)
pinB = Pin(5, Pin.OUT)
pinWarm = Pin(18, Pin.OUT)
pinCool = Pin(19, Pin.OUT)


print()

print("====================================")
print(usys.implementation[0], uos.uname()[3],
      "\nrun on", uos.uname()[4])
print("====================================")

while True:
    
    #All OFF
    pinR.value(0)
    pinG.value(0)
    pinB.value(0)
    pinWarm.value(0)
    pinCool.value(0)
    time.sleep(1)
    
    #turn ON WARM
    pinWarm.value(1)
    time.sleep(1)
    
    #turn ON COOL
    pinWarm.value(0)
    pinCool.value(1)
    time.sleep(1)
    
    #turn ON RED
    pinCool.value(0)
    pinR.value(1)
    time.sleep(1)
    
    #turn ON GREEN
    pinR.value(0)
    pinG.value(1)
    time.sleep(1)
    
    #turn ON BLUE
    pinG.value(0)
    pinB.value(1)
    time.sleep(1)
    
    #turn ON RED/GREEN/BLUE
    pinR.value(1)
    pinG.value(1)
    pinB.value(1)
    time.sleep(1)


mpy_NodeMCU_ESP-C3-32S-Kit_RGB_PWM.py, control onboard LEDs as PWM.
"""
MicroPython/NodeMCU ESP-C3-32S-Kit exercise
to control RGB LED (PWM).

# ref:
# https://docs.micropython.org/en/latest/esp32/quickref.html#pwm-pulse-width-modulation
"""
import uos
import usys
import time
from machine import Pin, PWM

print()

print("====================================")
print(usys.implementation[0], uos.uname()[3],
      "\nrun on", uos.uname()[4])
print("====================================")
time.sleep(1)

# NodeMCU ESP-C3-32S-Kit onboard LEDs assignment
pwmR = PWM(Pin(3))
pwmG = PWM(Pin(4))
pwmB = PWM(Pin(5))
pwmWarm = PWM(Pin(18))
pwmCool = PWM(Pin(19))

pwmR.freq(1000)    # set PWM frequency from 1Hz to 40MHz
pwmG.freq(1000)
pwmB.freq(1000)
pwmWarm.freq(1000)
pwmCool.freq(1000)

def PWMLedTest(pwmpin):
    for d in range(0, 1024):
        pwmpin.duty(d)
        time.sleep(0.005)
    for d in range(1023, -1, -1):
        pwmpin.duty(d)
        time.sleep(0.005)

while True:
    
    #All OFF
    pwmR.duty(0)
    pwmG.duty(0)
    pwmB.duty(0)
    pwmWarm.duty(0)
    pwmCool.duty(0)
    time.sleep(1)
    
    PWMLedTest(pwmR)
    time.sleep(0.5)
    PWMLedTest(pwmG)
    time.sleep(0.5)
    PWMLedTest(pwmB)
    time.sleep(0.5)
    PWMLedTest(pwmCool) 
    time.sleep(0.5)
    PWMLedTest(pwmWarm)

    time.sleep(1)

Updated@2022-08-15
It's found that Cool and Warm LEDs are mutual affected. It because Cool and Warm LEDs share a common current limit resistors. And also, R, G and B share common current limit resistors.

Check update post in my new blogspot coXXect > MicroPython/NodeMCU ESP-C3-32S-Kit control onboard LEDs



Sunday, June 19, 2022

Flash MicroPython v1.19 firmware on ESP32-C3 (ESP32-C3-DevKitM-1/NodeMCU ESP-C3-32S-Kit)

To flash MicroPython v1.19 firmware on ESP32-C3, tested on Espressif ESP32-C3-DevKitM-1 and AI-Thinker NodeMCU ESP-C3-32S-Kit, both have a single USB connector. All steps run on Raspberry Pi.



To IDENTIFY connected USB port. 

- BEFORE Connect ESP32-C3 dev. board to USB
clear dmesg buffer:
$ sudo dmesg -c

- AFTER ESP32-C3 dev. board connected to USB
display dmesg:
$ dmesg

Download firmware.

Visit https://micropython.org/download/  to download for esp32c3.

Select "ESP32-C3 Espressif"


Flash Firmware.

To erase the entire flash using:

esptool.py --chip esp32c3 --port /dev/ttyUSB0 erase_flash

Flash firmware starting at address 0x0:

esptool.py --chip esp32c3 --port /dev/ttyUSB0 --baud 460800 write_flash -z 0x0 <.bin>












Finally, test with Thonny.









more exercise:
MicroPython/NodeMCU ESP-C3-32S-Kit to control onboard LEDs
MicroPython bluetooth (BLE) exampls
detect onboard BOOT button, and control onboard RGB LED (Neopixel)
send/receive command via BLE UART
multithreading exercise, get user input un-blocked using _thread
ESP32-C3/MicroPython + SSD1306 I2C OLED
ESP32-C3/MicroPython BLE UART Communication


Sunday, May 15, 2022

BLE UART communication between ESP32-S3 (arduino-esp32) and HC-42 BLE Module

This post show how to implement BLE UART communication between NodeMCU ESP-S3-12K-Kit (in Arduino framework usiing arduino-esp32) and HC-42 BLE Module.

For HC-42 BLE Module, refer to last post "HC-42 BLE 5 Serial Port Communication Module".

For ESP-S3-12K-Kit (arduino-esp32 2.0.3) side, basically it is modified from "ESP32 BLE Arduino" > "BLE_client" example.

Note that in HC-42:
- Search UUID: FFF0
- Service UUID: FFE0
- Transparent data transmission UUID: FFE1

We have to follow it in arduino code in ESP-S3-12K-Kit.


ESP32S3_BLE_client_HC42.ino, modified from "ESP32 BLE Arduino" > "BLE_client" example, for HC-42.

/**
 * A BLE client example that is rich in capabilities.
 * There is a lot new capabilities implemented.
 * author unknown
 * updated by chegewara
 */

#include "BLEDevice.h"
//#include "BLEScan.h"

#define SEARCH_UUID "FFF0"
#define SERVICE_UUID "FFE0"
#define TRAN_UUID "FFE1"

// The remote service we wish to connect to.
static BLEUUID searchUUID(SEARCH_UUID);
static BLEUUID serviceUUID(SERVICE_UUID);
// The characteristic of the remote service we are interested in.
static BLEUUID    charUUID(TRAN_UUID);

static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* myDevice;

static void notifyCallback(
  BLERemoteCharacteristic* pBLERemoteCharacteristic,
  uint8_t* pData,
  size_t length,
  bool isNotify) {
    Serial.print("Notify callback for characteristic ");
    Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
    Serial.print(" of data length ");
    Serial.println(length);
    Serial.print("data: ");
    Serial.println((char*)pData);
}

class MyClientCallback : public BLEClientCallbacks {
  void onConnect(BLEClient* pclient) {
  }

  void onDisconnect(BLEClient* pclient) {
    connected = false;
    Serial.println("onDisconnect");
  }
};

bool connectToServer() {
    Serial.print("Forming a connection to ");
    Serial.println(myDevice->getAddress().toString().c_str());
    
    BLEClient*  pClient  = BLEDevice::createClient();
    Serial.println(" - Created client");

    pClient->setClientCallbacks(new MyClientCallback());

    // Connect to the remove BLE Server.
    pClient->connect(myDevice); // if you pass BLEAdvertisedDevice
				// instead of address, it will be
				// recognized type of peer device 
				// address (public or private)
    Serial.println(" - Connected to server");
    pClient->setMTU(517); //set client to request maximum MTU from
						  //server (default is 23 otherwise)
  
    // Obtain a reference to the service we are after in the remote 
	// BLE server.
    BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
    if (pRemoteService == nullptr) {
      Serial.print("Failed to find our service UUID: ");
      Serial.println(serviceUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our service");


    // Obtain a reference to the characteristic in the service of
	// the remote BLE server.
    pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
    if (pRemoteCharacteristic == nullptr) {
      Serial.print("Failed to find our characteristic UUID: ");
      Serial.println(charUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our characteristic");

    // Read the value of the characteristic.
    if(pRemoteCharacteristic->canRead()) {
      std::string value = pRemoteCharacteristic->readValue();
      Serial.print("The characteristic value was: ");
      Serial.println(value.c_str());
    }

    if(pRemoteCharacteristic->canNotify())
      pRemoteCharacteristic->registerForNotify(notifyCallback);

    connected = true;
    return true;
}
/**
 * Scan for BLE servers and find the first one that advertises 
 * the service we are looking for.
 */
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
 /**
   * Called for each advertising BLE server.
   */
  void onResult(BLEAdvertisedDevice advertisedDevice) {
    Serial.print("BLE Advertised Device found: ");
    Serial.println(advertisedDevice.toString().c_str());

    // We have found a device, let us now see if it contains the service
	// we are looking for.
    if (advertisedDevice.haveServiceUUID() && 
		advertisedDevice.isAdvertisingService(searchUUID)) {

      BLEDevice::getScan()->stop();
      myDevice = new BLEAdvertisedDevice(advertisedDevice);
      doConnect = true;
      doScan = true;

    } // Found our server
  } // onResult
}; // MyAdvertisedDeviceCallbacks


void setup() {
  Serial.begin(115200);
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");

  // Retrieve a Scanner and set the callback we want to use to 
  // be informed when we have detected a new device. 
  // Specify that we want active scanning and start the
  // scan to run for 5 seconds.
  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(5, false);
} // End of setup.


// This is the Arduino main loop function.
void loop() {

  // If the flag "doConnect" is true then we have scanned for 
  // and found the desired BLE Server with which we wish to connect.  
  // Now we connect to it.  Once we are connected we set the connected
  // flag to be true.
  if (doConnect == true) {
    if (connectToServer()) {
      Serial.println("We are now connected to the BLE Server.");
    } else {
      Serial.println("We have failed to connect to the server; there is nothin more we will do.");
    }
    doConnect = false;
  }

  // If we are connected to a peer BLE Server, 
  // update the characteristic each time we are reached
  // with the current time since boot.
  if (connected) {
    String newValue = "Time since boot: " + String(millis()/1000)  +"\n";
    Serial.println("Setting new characteristic value to \"" + newValue + "\"");
    
    // Set the characteristic's value to be the array of bytes
	// that is actually a string.
    pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());
  }else if(doScan){
    BLEDevice::getScan()->start(0); // this is just example to start scan 
				    // after disconnect, most likely there
				    // is better way to do it in arduino
  }
  
  delay(1000); // Delay a second between loops.
} // End of loop



ESP32S3_BLE_uart_client_HC42.ino, bi-directional BLE UART communication.
/**
 * A BLE UART client example run on ESP32-S3,
 * act as client, connect to HC-42, to establish
 * BLE UART communication.
 *
 * Modified from "ESP32 BLE Arduino" > "BLE_client"
 */

#include "BLEDevice.h"
//#include "BLEScan.h"

#define SEARCH_UUID "FFF0"
#define SERVICE_UUID "FFE0"
#define TRANS_UUID "FFE1"

// The remote service we wish to connect to.
static BLEUUID searchUUID(SEARCH_UUID);
static BLEUUID serviceUUID(SERVICE_UUID);
// The characteristic of the remote service we are interested in.
static BLEUUID    charUUID(TRANS_UUID);

static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* myDevice;

static void notifyCallback(
  BLERemoteCharacteristic* pBLERemoteCharacteristic,
  uint8_t* pData,
  size_t length,
  bool isNotify) {

    if (length > 0){
      Serial.printf("%i :\t", length);
      
      for (int i=0; i<length; i++)
          Serial.print((char) pData[i]);

      Serial.println();
    }
}

class MyClientCallback : public BLEClientCallbacks {
  void onConnect(BLEClient* pclient) {
  }

  void onDisconnect(BLEClient* pclient) {
    connected = false;
    Serial.println("onDisconnect");
  }
};

bool connectToServer() {
    Serial.print("Forming a connection to ");
    Serial.println(myDevice->getAddress().toString().c_str());
    
    BLEClient*  pClient  = BLEDevice::createClient();
    Serial.println(" - Created client");

    pClient->setClientCallbacks(new MyClientCallback());

    // Connect to the remove BLE Server.
    pClient->connect(myDevice); // if you pass BLEAdvertisedDevice 
				// instead of address, it will be 
				// recognized type of peer device 
				// address (public or private)
    Serial.println(" - Connected to server");
    pClient->setMTU(517); //set client to request maximum MTU from server 
                          //(default is 23 otherwise)
  
    // Obtain a reference to the service we are after in the 
	// remote BLE server.
    BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
    if (pRemoteService == nullptr) {
      Serial.print("Failed to find our service UUID: ");
      Serial.println(serviceUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our service");


    // Obtain a reference to the characteristic in the service 
	// of the remote BLE server.
    pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
    if (pRemoteCharacteristic == nullptr) {
      Serial.print("Failed to find our characteristic UUID: ");
      Serial.println(charUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our characteristic");

    // Read the value of the characteristic.
    if(pRemoteCharacteristic->canRead()) {
      std::string value = pRemoteCharacteristic->readValue();
      Serial.print("The characteristic value was: ");
      Serial.println(value.c_str());
    }

    if(pRemoteCharacteristic->canNotify())
      pRemoteCharacteristic->registerForNotify(notifyCallback);

    connected = true;
    return true;
}
/**
 * Scan for BLE servers and find the first one that advertises 
 * the service we are looking for.
 */
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
 /**
   * Called for each advertising BLE server.
   */
  void onResult(BLEAdvertisedDevice advertisedDevice) {
    Serial.print("BLE Advertised Device found: ");
    Serial.println(advertisedDevice.toString().c_str());

    // We have found a device, let us now see if it contains the service 
	// we are looking for.
    if (advertisedDevice.haveServiceUUID() 
        && advertisedDevice.isAdvertisingService(searchUUID)) {

      BLEDevice::getScan()->stop();
      myDevice = new BLEAdvertisedDevice(advertisedDevice);
      doConnect = true;
      doScan = true;

    } // Found our server
  } // onResult
}; // MyAdvertisedDeviceCallbacks


void setup() {
  Serial.begin(115200);
  delay(1000);    //it's seem that adding delay here make it more stable
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");

  // Retrieve a Scanner and set the callback we want to use to be 
  // informed when we have detected a new device.  
  // Specify that we want active scanning and start the scan to 
  // run for 5 seconds.
  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(5, false);
} // End of setup.


// This is the Arduino main loop function.
void loop() {

  // If the flag "doConnect" is true then we have scanned for 
  // and found the desired BLE Server with which we wish to connect.  
  // Now we connect to it.  Once we are connected we set the connected 
  //flag to be true.
  if (doConnect == true) {
    if (connectToServer()) {
      Serial.println("We are now connected to the BLE Server.");
    } else {
      Serial.println("We have failed to connect to the server; there is nothin more we will do.");
    }
    doConnect = false;
  }

  // If we are connected to a peer BLE Server, 
  // update the characteristic each time we are reached
  // with the current time since boot.
  if (connected) {

    if (Serial.available()) {
      String newValue = "";
      while(Serial.available()){
        char c = Serial.read();
        newValue += c;
      }
      newValue += "\n";
      Serial.println(newValue);
      pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());
    } 
  }else if(doScan){
    BLEDevice::getScan()->start(0); // this is just example to start scan 
				    // after disconnect, most likely there 
				    // is better way to do it in arduino
  }
  
  delay(1000); // Delay a second between loops.
} // End of loop



Saturday, May 14, 2022

HC-42 BLE 5 Serial Port Communication Module

The HC-42 Bluetooth serial communication module is a new generation of data transmission module based on Bluetooth Specification V5.0 BLE Bluetooth protocol. It can be set using AT Command.


ref:
User Manual for HC-42 Bluetooth Serial Port Module




Connection between HC-42 and FTDI232 (USB to serial UART adapter)

				connect to host computer
				(Raspberry Pi)
	                          |||| 
	+-------------+		+-------------+
        |HC-42        |		| FTDI232     |
	|             |		| (VCC=3.3V)  |
	|             |		|             |
	|             |		|             |
	|             |		|             |
	|             |		|             |
	| S           |		|             |
	| T           |		|             |
	| A R T G V K |		| D     V C G |
	| T X X N C E |		| T R T C T N |
	| E D D D C Y |		| R X X C S D |
	+-------------+		+-------------+
	    | | | |                 | | |   |
	    | | | +-----------------|-|-+   |
	    | | +-------------------|-|-----+
	    | +---------------------+ |                         
	    +-------------------------+                       
	                            


next:
BLE UART communication between ESP32-S3 (arduino-esp32) and HC-42 BLE Module

Thursday, May 12, 2022

arduino-esp32 2.0.3 add support for ESP32-S3, to develope in Arduino IDE.

With arduino-esp32 2.0.3, ESP32-S3 support added now. (~release notice)

To install arduino-esp32 to Arduino IDE:
(Install arduino-esp32 2 on Arduino IDE, to program ESP32-C3/S2/S3)

In MENU > File > Preference, make sure "https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json" is added in Additional Board Manager URLs field.


In MENU > Tools > Board > Boards Manager...
Now you can search and install for "esp32 by Espressif Systems"


Then you can select ESP32S3 Dev Module



Try run on NodeMCU ESP-S3-12K-Kit

ESP32S3_info.ino, get ESP info.
#include <Esp.h>

void setup() {
  delay(500);
  Serial.begin(115200);
  delay(500);
  Serial.println("\n\n================================");
  Serial.printf("Chip Model: %s\n", ESP.getChipModel());
  Serial.printf("Chip Revision: %d\n", ESP.getChipRevision());
  Serial.printf("with %d core\n", ESP.getChipCores());
  Serial.printf("Flash Chip Size : %d \n", ESP.getFlashChipSize());
  Serial.printf("Flash Chip Speed : %d \n", ESP.getFlashChipSpeed());

  esp_chip_info_t chip_info;
  esp_chip_info(&chip_info);
  Serial.printf("\nFeatures included:\n %s\n %s\n %s\n %s\n %s\n",
      (chip_info.features & CHIP_FEATURE_EMB_FLASH) ? "embedded flash" : "",
      (chip_info.features & CHIP_FEATURE_WIFI_BGN) ? "2.4GHz WiFi" : "",
      (chip_info.features & CHIP_FEATURE_BLE) ? "Bluetooth LE" : "",
      (chip_info.features & CHIP_FEATURE_BT) ? "Bluetooth Classic" : "",
      (chip_info.features & CHIP_FEATURE_IEEE802154) ? "IEEE 802.15.4" : "");
  
  Serial.println();


  Serial.println();
  Serial.println("\n- end of setup() -");

}

void loop() {
  // put your main code here, to run repeatedly:

}




ESP32S3_pins.ino, list pins with pre-defined function.
void setup() {
  // put your setup code here, to run once:
  delay(500);
  Serial.begin(115200);
  delay(500);
  Serial.println("\n\n================================");
  Serial.printf("Chip Model: %s %s %d\n",
                ESP.getChipModel(),
                "rev.",
                (int)ESP.getChipRevision());
  Serial.printf("with number of cores = %d\n", (int)ESP.getChipCores());
  Serial.println("================================");

#ifdef EXTERNAL_NUM_INTERRUPTS
  Serial.printf("EXTERNAL_NUM_INTERRUPTS = %d\n", EXTERNAL_NUM_INTERRUPTS);
#endif
#ifdef NUM_DIGITAL_PINS
  Serial.printf("NUM_DIGITAL_PINS = %d\n", NUM_DIGITAL_PINS);
#endif
#ifdef NUM_ANALOG_INPUTS
  Serial.printf("NUM_ANALOG_INPUTS = %d\n", NUM_ANALOG_INPUTS);
#endif
  Serial.println();
  Serial.printf("Default TX:   %d\n", TX);
  Serial.printf("Default RX:   %d\n", RX);
  Serial.println();
  Serial.printf("Default SDA:  %d\n", SDA);
  Serial.printf("Default SCL:  %d\n", SCL);
  Serial.println();
  Serial.printf("Default SS:   %d\n", SS);
  Serial.printf("Default MOSI: %d\n", MOSI);
  Serial.printf("Default MISO: %d\n", MISO);
  Serial.printf("Default SCK:  %d\n", SCK);

  Serial.println();
  Serial.printf("A0\tA1\tA2\tA3\tA4\tA5\tA6\tA7\tA8\tA9\n");
  Serial.printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", 
                 A0, A1, A2, A3, A4, A5, A6, A7, A8, A9);
  Serial.println();
  Serial.printf("A10\tA11\tA12\tA13\tA14\tA15\tA16\tA17\tA18\tA19\n");
  Serial.printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", 
                 A10, A11, A12, A13, A14, A15, A16, A17, A18, A19);
  Serial.println();

  Serial.printf("T1\tT2\tT3\tT4\tT5\tT6\tT7\tT8\tT9\tT10\n");
  Serial.printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", 
                 T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
  Serial.println();
  Serial.printf("T11\tT12\tT13\tT14\n");
  Serial.printf("%d\t%d\t%d\t%d\n", 
                 T11, T12, T13, T14);

  Serial.println("================================");
}

void loop() {
  // put your main code here, to run repeatedly:

}



ESP32S3_RGB.ino, control ESP-S3-12K-Kit on-board RGB LED.
#define LED_R 5
#define LED_G 6
#define LED_B 7

void setup() {
  delay(500);
  Serial.begin(115200);
  delay(500);
  pinMode(LED_R, OUTPUT);
  pinMode(LED_G, OUTPUT);
  pinMode(LED_B, OUTPUT);
  digitalWrite(LED_R, LOW);
  digitalWrite(LED_G, LOW);
  digitalWrite(LED_B, LOW);
  delay(1000);
  digitalWrite(LED_R, HIGH);
  digitalWrite(LED_G, HIGH);
  digitalWrite(LED_B, HIGH);
  delay(1000);
  digitalWrite(LED_R, LOW);
  digitalWrite(LED_G, LOW);
  digitalWrite(LED_B, LOW);
  delay(1000);

}

void loop() {
  digitalWrite(LED_R, HIGH);
  delay(2000);
  digitalWrite(LED_R, LOW);
  digitalWrite(LED_G, HIGH);
  delay(2000);
  digitalWrite(LED_G, LOW);
  digitalWrite(LED_B, HIGH);
  delay(2000);
  digitalWrite(LED_B, LOW);
  delay(2000); 
}




more exercise of ESP32-S3 (arduino-esp32):