Monday, 16 November 2026

ESP-NOW to WiFi/MQTT Gateway using Xiao EPS S3s

 I use Home Assistant to control and monitor devices around my home, I designed a wireless door/window sensor in an earlier blog entry that used very little power and used the ESP-NOW protocol to send data packets.  To receive the data I use an ESP07 with an external antenna which feeds the data into the USB port of a Raspberry Pi running HA.

I decided to make a dedicated ESP-NOW To WiFi gateway using two ESP devices linked via a serial connection, this means I can now locate the ESP-NOW receiver closer to the centre of the house rather than being right next to the Raspberry Pi.

This is a first for me, this project has been sponsored by PCBWay, they have provided the PCBs populated with all the SMD components apart from the Xiao ESP32 S3s free of charge.

The quality of the PCBA is good and I would have no problem using them again. For PCBs, PCBA, 3D printing and CNC machining visit WWW.PCBWAY.com

WWW.PCBWay.com
Assembled PCB

### This hardware design is solely done by me without AI assistance but the software is written by Gemini AI based on my instructions ###

All files are available on my Github page www.github.com/gadjet

Basic Features

  • Two distinct ESP32 S3s linked by the Serial ports
  • Each ESP individually programmable by reversing the USB plug
  • The selected ESP is indicated by an LED under the ESP
  • Optional OLED display for Gateway status
  • Status RGB LED indicating connection status
  • Optional Touch input (D3 on Wifi ESP) to wake up OLED from sleep (I used Copper tape on the inside of the 2mm thick PLA enclosure)
  • Web page hosted by WiFi ESP with status and settings (use IP address from OLED or check router)
AI Generated Instructions for the project below: -

Dual XIAO ESP32-S3 ESP-NOW to MQTT Gateway

An industrial-grade, dual-microcontroller bridge between low-power ESP-NOW sensor nodes and an MQTT broker (e.g. Home Assistant, Mosquitto, CloudAMQP). Built around two Seeed Studio XIAO ESP32-S3 modules on a custom PCB.


1. System Architecture

[ Remote ESP-NOW Sensor Nodes ] (Battery powered, deep-sleep, ultra-fast burst)
             │  ESP-NOW (2.4 GHz RF - Channel 1 default)
             ▼
┌────────────────────────────┐
│   Xiao ESP32-S3 (U1)       │  - Dedicated ESP-NOW RX/TX
│   ESP-NOW Receiver Node    │  - Continuous listening (zero packet loss)
└─────────────┬──────────────┘  - Hardware FIFO frame packaging
              │
              │ Inter-ESP Hardware UART (D6 & D7 @ 115200 baud)
              ▼
┌────────────────────────────┐
│   Xiao ESP32-S3 (U10)      │  - WiFi Station (Auto-reconnect)
│   WiFi & MQTT Gateway      │  - MQTT Client (Publish & Subscribe)
└──────┬──────────────┬──────┘  - Web Dashboard & REST API
       │              │         - Common-Anode RGB Status LED (LED1)
       │              └────────► Optional I2C OLED Display (SSD1306 on H1)
       ▼
[ Local MQTT Broker / Home Assistant ]

Why Dual ESP32-S3 Modules?

Standard single-chip ESP-NOW + WiFi gateways suffer from packet drops, channel conflicts, and latency jitter because WiFi station mode and ESP-NOW share the same radio hardware. Using two dedicated Xiao ESP32-S3 modules connected via hardware UART provides:

  • Zero Packet Drops: U1 is dedicated to ESP-NOW listening 100% of the time.
  • Independent WiFi Channel Management: U10 connects to any router channel without disrupting U1.
  • Hardware UART FIFO: Direct hardware serial communication over pins D6 and D7 eliminates SoftwareSerial bit-banging CPU overhead.

2. Reversible USB-C Connector (Flippable Programming)

The custom PCB features an ingenious USB-C circuit:

  • USB Data Lines (D+/D-): Only one ESP32-S3 is connected to the USB data lines at a time.
  • Flippable Cable: Turning the USB-C plug over switches the USB connection between U10 (WiFi/MQTT) and U1 (ESP-NOW).
  • Orientation Indicator LEDs: An onboard LMV393 comparator monitors the USB-C CC1/CC2 lines:
    • LED3 (WiFi/MQTT): Illuminates when the cable is oriented to program U10.
    • LED2 (ESP-NOW): Illuminates when the cable is turned over to program U1.

3. Hardware Pin Mapping

A. U10 (WiFi, MQTT Gateway, Web Server & Display Controller)

U10 PinESP32-S3 GPIOConnected ComponentSchematic NetPurpose
D0GPIO1LED1 Pin 1 via R3 (680Ω)redRGB LED: Red (Active LOW)
D1GPIO2LED1 Pin 3 via R5 (680Ω)greenRGB LED: Green (Active LOW)
D2GPIO3LED1 Pin 4 via R4 (680Ω)blueRGB LED: Blue (Active LOW)
D3GPIO4Test Pad D3# (Copper Tape Pad)D3#Capacitive Touch (TOUCH4): Wakes OLED display for 30s
D4GPIO5Connector H1 Pin 4 + R1 (4.7kΩ pull-up)SDAI2C Data (Optional OLED)
D5GPIO6Connector H1 Pin 3 + R2 (4.7kΩ pull-up)SCLI2C Clock (Optional OLED)
D6GPIO43U1 Pin 7 (D6)RXHardware UART1 RX from U1
D7GPIO44U1 Pin 8 (D7)TXHardware UART1 TX to U1
3V3+3.3VVCC RailVCC+3.3V Power
GNDGNDGround RailGNDCommon Ground
5V+5VUSB1 VBUS Rail+5VSystem 5V Input

B. U1 (Dedicated ESP-NOW Receiver & Forwarder)

U1 PinESP32-S3 GPIOConnected ComponentSchematic NetPurpose
D0GPIO1Test Pad D0D0Breakout / Diagnostic Pin
D1GPIO2Test Pad D1D1Breakout / Diagnostic Pin
D2GPIO3Test Pad D2D2Breakout / Diagnostic Pin
D3GPIO4Test Pad D3D3Breakout / Diagnostic Pin
D4GPIO5Test Pad D4D4Breakout / Diagnostic Pin
D5GPIO6Test Pad D5D5Breakout / Diagnostic Pin
D6GPIO43U10 Pin 7 (D6)TXHardware UART1 TX to U10
D7GPIO44U10 Pin 8 (D7)RXHardware UART1 RX from U10
5V+5VUSB1 VBUS Rail+5VSystem 5V Input
GNDGNDGround RailGNDCommon Ground

C. RGB Status LED (LED1 - Common Anode, Active LOW)

The RGB LED anodes are connected to VCC (+3.3V). Driving a pin LOW illuminates the color; driving it HIGH turns it off.

State / ConditionLED ColorPin States
Connecting to WiFiSolid RedRed(D0): LOW, Green(D1): HIGH, Blue(D2): HIGH
WiFi Connected, Connecting to MQTTSolid YellowRed(D0): LOW, Green(D1): LOW, Blue(D2): HIGH
WiFi & MQTT Connected (Normal)Solid GreenRed(D0): HIGH, Green(D1): LOW, Blue(D2): HIGH
ESP-NOW Packet Received & ForwardedBrief Blue PulseBlue(D2): LOW for ~70ms on packet arrival
Outbound Message Sent via ESP-NOWBrief Cyan PulseGreen(D1) + Blue(D2): LOW for ~80ms on transmit

4. Optional I2C Display (Connector H1)

Connector H1 is pinned out for standard 4-pin I2C OLED modules (e.g. SSD1306 128x64 or 128x32):

  • Pin 1: GND
  • Pin 2: VCC (+3.3V)
  • Pin 3: SCL (U10 Pin D5)
  • Pin 4: SDA (U10 Pin D4)

[!NOTE] The I2C display is optional and auto-detected. At boot, U10 scans the I2C bus for addresses 0x3C and 0x3D. If no display is detected, the gateway continues executing normally without delay.

OLED Power-Save & Capacitive Touch Wake-Up (Pin D3)

To prevent OLED burn-in and save power:

  • Auto-Off after 30 Seconds: When enabled, the OLED turns on at power-up and automatically enters hardware sleep (SSD1306_DISPLAYOFF) 30 seconds after startup or last wake.
  • Web & API Toggle: The 30-second timeout can be enabled or disabled at any time via the 30s Screen Timeout slide switch on the Web Dashboard or the /api/oled_timeout API endpoint (persisted in Flash NVS).
  • Touch-to-Wake on D3 (GPIO4 / TOUCH4): Connecting test pad D3# on U10 to a piece of copper tape on the inside of the 2mm 3D-printed PLA cover enables capacitive touch wake-up. Touching the cover over the copper pad wakes the display for 30 seconds (or resets the 30-second timer if already awake).
  • Auto-Calibration: At startup, U10 automatically calibrates the untouched baseline capacitance of the copper pad through the enclosure and tracks slow ambient temperature/humidity drift.

5. Project Folder Structure

ESP32 S3 Gateway/
├── Gateway_WiFi_MQTT/
│   └── Gateway_WiFi_MQTT.ino       <-- Flash to U10 (WiFi + MQTT + Web Server + LED + OLED)
├── Gateway_ESPNOW_Receiver/
│   └── Gateway_ESPNOW_Receiver.ino <-- Flash to U1 (ESP-NOW Receiver & Forwarder)
├── ESPNOW_Sender_Example/
│   └── ESPNOW_Sender_Example.ino   <-- Test sketch for remote sensor nodes
├── Schematic/
│   ├── SCH_Schematic1_2026-10-30.pdf
│   └── schematic_highres.png
├── PCB/
│   ├── Top.png
│   └── Bottom.png
└── README.md                       <-- Documentation

6. Setup & Flashing Instructions

Required Libraries

Install the following via the Arduino IDE Library Manager (Sketch -> Include Library -> Manage Libraries...):

  • PubSubClient by Nick O'Leary
  • Adafruit SSD1306 by Adafruit (Required only if using OLED)
  • Adafruit GFX Library by Adafruit (Required only if using OLED)

Board Settings in Arduino IDE

For both modules, select:

  • Board: XIAO_ESP32S3 (under ESP32 Arduino)
  • USB CDC On Boot: Enabled
  • Flash Size: 8MB (or default)
  • Upload Speed: 921600

Step 1: Flash U1 (ESP-NOW Receiver)

  1. Plug the USB-C cable into the gateway board.
  2. Verify that LED2 ("ESP-NOW") is illuminated. (If LED3 is illuminated instead, flip the USB-C plug over).
  3. Open Gateway_ESPNOW_Receiver/Gateway_ESPNOW_Receiver.ino in Arduino IDE.
  4. Select the COM port corresponding to the board.
  5. Click Upload.
  6. Open Serial Monitor at 115200 baud to confirm U1 startup and note its MAC address.

Step 2: Flash U10 (WiFi & MQTT Gateway)

  1. Flip the USB-C cable connector over.
  2. Verify that LED3 ("WiFi/MQTT") is now illuminated.
  3. Open Gateway_WiFi_MQTT/Gateway_WiFi_MQTT.ino in Arduino IDE.
  4. Select the new COM port in the IDE.
  5. Click Upload.
  6. Open Serial Monitor at 115200 baud.
  7. Observe the RGB LED:
    • Solid Red: Connecting to WiFi.
    • Solid Yellow: WiFi connected, connecting to MQTT.
    • Solid Green: Fully connected and operating.

7. Web Dashboard & Configuration

Accessing the Web Dashboard

Open your browser and navigate to the gateway's IP address:

http://<U10_IP_ADDRESS>/

Screenshot

Features:

  • Live Badges: Real-time connection status for WiFi (including IP, RSSI, and connected AP BSSID), MQTT Broker, Inter-ESP U1 Link (including last ESP-NOW RSSI), and OLED display.
  • 1-Hour WiFi RSSI Trend Graph: Embedded sparkline on the WiFi card plotting up to 60 1-minute RSSI samples (-90 to -30 dBm) with a -65 dBm roaming threshold reference line.
  • Automatic Mesh AP Roaming: If WiFi RSSI drops below -65 dBm, U10 periodically scans for a stronger BSSID on the same SSID (>= 10 dB improvement) and reconnects to it.
  • OLED Timeout Slide Switch: Toggle the 30-second OLED auto-sleep timeout directly from the OLED status card.
  • Rolling Message Table: Auto-updating table of received ESP-NOW sensor packets with timestamps, MAC addresses, RSSI, and decoded payloads.
  • Test Transmitter: Send test unicast or broadcast ESP-NOW messages directly from your browser.

REST API Endpoints

  • GET /api/status: Returns live JSON status, wifi_bssid, wifi_rssi_history, u1_last_rssi, oled_timeout_enabled, touch calibration values, and recent packets.
  • GET / POST /api/oled_timeout?enabled=true|false: Reads or updates the NVS-persisted OLED 30-second screen timeout setting.
  • POST /api/send: Dispatches a unicast or broadcast ESP-NOW payload via U1.

Supported ESP-NOW Payloads (U1 Receiver)

In addition to UTF-8 JSON/text payloads, Gateway_ESPNOW_Receiver.ino automatically decodes binary struct_message packets (int id, char state[7], int vBatt — 16 bytes) and forwards them as JSON ({"id":...,"state":"...","vBatt":...}).

Reconfiguring Settings

Navigate to:

http://<U10_IP_ADDRESS>/config

From here you can adjust WiFi SSID/Password, MQTT broker host, port, credentials, and base topic prefix. All settings are persistently stored in the ESP32-S3 Flash NVS.


8. MQTT Topics & Payloads

DirectionTopicPayload ExampleDescription
Gateway -> MQTT<prefix>/rx/<CLEAN_MAC>{"temp":22.4,"humidity":55.1}Incoming ESP-NOW packet from sensor node
Gateway -> MQTT<prefix>/statusonline / offlineGateway LWT availability topic
MQTT -> Gateway<prefix>/tx{"cmd":"restart"}Broadcast packet sent to all ESP-NOW nodes
MQTT -> Gateway<prefix>/send/<TARGET_MAC>{"valve":"open"}Unicast packet dispatched to specific node

Monday, 14 September 2026

New Accessories for the AirChrony S3

With the increasing abilities of AI it has become so much easier to take an idea to a finished, working item in a really short time.

I was thinking about the next teps for the AirChrony S3 and I had two ideas, an addon battery holder so that I didn't need to plug it into a USB powerbank and a remote monitor so that I could use it without my phone.


Addon Battery Carrier

I wanted to be able to have the option of using the USB powerbank or a dedicated supply that attached to the Chronograph, to this end I designed a sleeve that slid over the chronograph body and secured it using the the existing screw.  The battery slot was sized for an 620mAh LP602248 Li-Ion rechargeable pouch cell.


3D Render of the battery Sleeve

Actual assembled device

Sectional View from the Right Side

Due to the fact that the IR Detectors require a 5V supply to operate reliably I needed to supply 5V to the Xaio ESP32 rather that include a cell inside the device so I used a DC/DC step-up converter to increase the 3.7V cell voltage to 5V, the buck converter was very small and had the same connection pads as a USB C PCB connector I had and they soldered together perfectly, I soldered on a 2mm PH JST socket to the DC/DC conveter input to connect the batery to then slid the whole assembley into a 3D printed sleeve that fits into the USB connector entry of the Chronograph.


USB C Plug/DC/DC Buck Converter Assembly


 The above assembly in the 3D printed Sleeve

Remote Viewer Screen

The second accessory was a remote viewing screen that would connect to the Chronograph instead of the mobile phone and allow the viewing of the shot data and other functions.

I had an ESP32-S3 based display module that I'd bought from Aliexpress, this had a 2.8" capacitive touch screen, speaker output, battery charging circuit and SD card slot.  I designed an enclosure to house the display, speaker and an 1100mAh Pouch cell.
Whenever a shot is registered the display will beep (optional).


3D Rendering of the case


Actual Screen Layout


All the code for the display was written using Gemini Antigravity AI in a couple of hours, it's stil a work in progress with more functions to be added but so far it all seems to be working.

When I'm happy with the final version I'lI will post all the files/code on my github www.github.com/gadjet




Wednesday, 9 September 2026

Latest Version of Chronograph - AirChrony-S3

Update on the Latest version of the DIY Chronograph, the PCBs have arrived, I've populated them, assembled the chronograph and done some basic testing, so far so good.

All design files can be found on Github at www.github.com/gadjet 

Detector PCB


Emitter PCB


Top View with Xiao ESP32 S3


3D printed case parts



Also, to help assemble the detector and emitter PCBs with the detectors/LEDs I made a helper jig, this makes sure that the distance between the lenses on the detectors/LEDs are spaced exactly 50mm apart to match the tube.
Jig usage




Sunday, 6 September 2026

New version of the Chronograph

Latest project update for 2026 here


Yes I continue to find new ways to do the same thing again ..... and again, this time I wanted to learn how to program the ITEAD Nextion display which I got when they were on Kickstarter some time ago.
I have a couple of these 2.4" screens but not really got around to doing much with them so I thought about having a small touch screen chronograph remote connected to my pellet sensor fitted to the end of the rifle.
About the screen
The screens, made by ITEAD, come in various sizes and use resistive touch screens (Capacitive also available) and come with a full editor to allow you to design you whole interface layout including screens, buttons etc. on the PC and then download it to the screen.   The interaction/control can then be done via the serial port by an Arduino or other MCU.

I have a Brocock Compatto air rifle that has a picatinny rail under the front end of the stock and I planned to mount the screen on that rail.

For this project I started on the hardware first rather than my usual approach of starting with the software first.
The Hardware
I designed the hardware in Tinkercad making a front, rear, picatinny mount and the tube to hold the IR LED sensor assembly it looks like this

In the rear half of the case the battery, Nano and power PCB are mounted the front houses the display and also forms the mounting bracket to  secure to the Picatinny rail adapter.

Tuesday, 1 September 2026

DIY Chronograph Revisited

This project is still a work in progress as I am waiting for PCBs and parts to be delivered, so details like the 3D-printed enclosure and software will probably evolve. I will create a GitHub repository once I am happy with how everything is working.


It has been over 10 years since my first blog entry on my DIY chronograph (https://gadjetsblog.blogspot.com/2013/02/air-rifle-chronograph.html), which used an Arduino Nano and a Bluetooth transmitter. That setup connected to an app on my phone and transmitted the elapsed time between trigger 1 and trigger 2. The app then used that time, along with the entered pellet weight, to calculate the muzzle velocity and kinetic energy of the rifle/pistol.

I have built a few projects since then. Although I enjoy designing hardware, writing software is not my strong suit. Like many others, I have started using AI—specifically Google Gemini—to help write code not only for the microcontroller hardware, but also for the web-based user interface.

I realised that I could modernise the DIY Chronograph using an ESP32, my favourite being the Seeed Studio XIAO ESP32-S3. Running at 240 MHz, it is substantially faster than the older Arduino Nano. Because it features built-in Wi-Fi and web server capabilities, the entire user interface can now be hosted directly on the chronograph itself. You simply open a web browser on your phone, tablet, or laptop to interact with the device.

Hardware

The core concept remains similar to the original design: two optical IR emitter/detector pairs are spaced 50 mm apart, creating two infrared beams. When a pellet passes through and breaks each beam, high-speed hardware interrupts measure the travel time across that 50 mm distance to accurately calculate the projectile's velocity.
Chronograph - Top Down Section View

Chronograph - Side Section View

 
Chronograph - X-RAY View
The outer casing is printed in two halves that slide over the electronics and aluminium barrel tube. They lock securely together using two 2 mm alignment dowels and an M3 screw.


One interesting challenge was "how to package the FPC antenna" this proved to be a bit tricky so in the end I went for a single wire antenna 31mm long.

This solution allowed me to feed the antenna back into a hole inside the casing and it works perfectly well in the 2 or 3m range needed to work with your phone.

Power is currently supplied via a USB-C cable from a 5V power bank, with the option to add an internal LiPo battery later. *(Note: The USB-C connector head must be slim enough to fit into the 11.5 mm × 6.5 mm housing recess).*

Unlike the original design, where raw timing data was sent over Bluetooth for the phone app to process, all calculations are now performed locally on the ESP32. 

To view the live dashboard, simply connect your phone or PC to the **"AirChrony-S3"** Wi-Fi access point and navigate to **`http://192.168.4.1`** (or `http://chronograph.local`) in your browser.

User interface

When opened, the dashboard immediately displays the **"Live Chrono"** tab showing the latest shot's speed, muzzle energy, rolling averages, and a velocity progression graph. 

Additional tabs include:

  • Pellet Profiles:** Save custom pellet profiles with brand names, calibers, and weights (in grains or grams) to automatically calculate muzzle energy (Joules or ft-lbs).
  • Saved Strings:** Store, recall, and export previous shooting sessions directly to CSV or JSON from the ESP32's onboard flash memory.
  • Settings & Diagnostics:** Customise speed units (FPS / m/s), toggle between dark and light themes, configure sensor spacing, test beam alignment, and enable spoken voice callouts (e.g. shot count and velocity spoken aloud through your phone or Bluetooth ear defenders).

The project is constantly evolving as new ideas arise, and you are welcome to use AI to tailor the firmware and interface to your own setup!



Tuesday, 21 October 2025

Testing LoRA transmitters and receivers

I've wanted to have a play with 868MHz LoRA transmitters for some time now but never got around to it until,  a while ago, I did an hardware design and PCB for someone wanting a prototype remote sensor as part of a security system to monitor inclination levels and transmit them over longer distances than WiFi can reasonably achieve.

I chose the Seedstudio Wio-E5 for the prototype connected to an ESP32 S3 and it was succesful as a testbed for further development. 

I know some of you reading this will be saying that you can just buy the HELTEC modules and similar modules but, as usual, I want to learn myself and also use up some of the modules I've bought in the past and never got around to using.

For my own design I wanted a simpler solution that I could use for outbuildings (shed) to monitor the status of the door and also the ambient temperature, the requirements were: -
  • Cheap to build
  • Last a very long time on a battery
  • Have a good range, relative to WiFi
  • Not using Meshtastic just sending a datapacket when triggered
  • Use a DS18B20 Temp sensor
  • Have an I2C connection for other sensors or a screen
For the power control I used the same trigger logic  circuitry I used on my WiFi window/Door sensor  which means that the LDO is enabled when the reed switch opens or closes and when the code is finished sending the datapacket it shuts off the power to itself using a GPIO.

I have made three different variants of the PCB to use different processors: -
  • An adapter PCB to connect an Xiao ESP32-C3 or S3 (or other Xiao module?)


  • A transmitter using an ATMEGA328p

  • An adapter to connect the Wio-E5 to a Waveshare 1.47" Display module based on an ESP32-C6






The other thing I'm testing out for these projects is AI, I've tried ChatGPT for writing Arduino code for ESP32s etc. without much success but I thought I'd try out the new Google Gemini Canvas AI and I was blown away with the code it generated, it's not 100% perfect but unlike ChatGPT it remembers it's mistakes and doesn't make them twice.  It's not a cheap option at £18.99 ($25) per month but you also get 2TB of storage.

Within a couple of hours (total prompt writing time)  I had working code for all three options, the AI sometimes needed help with the different pins used on the different ESPs for serial connections and there were a couple of inconsistencies between the transimitter and receiver code when I switched on encryption of the data packets but by pasting the debug serial code from the PC into the prompt window the AI was able to track down it's mistake and fix it.

One of the biggest time saving things about using the AI to generate the code is that once the screen setup is complete it lays out all the text for you, no more counting pixels to determine where everything goes and when the screen refreshes it creates the code to draw a rectangle over the existing code to clear out any left over bits of text if the newer text is shorter in length.

I also added a web page option to the receiver by just asking the AI to include a web page with the same information that's displayed on the screen.

I will post the code and the PCB details on my GitHub page in the next few days, I'm making some corrections to the ATMEGA 328p version before I publish it to GitHub.







Thursday, 3 July 2025

Updates for my Commarker B4 30W fibre Laser

 Second Mod - Add external buttons and an automated height controller

******* PLEASE NOTE *********

I did this with my B4 30W laser unit, I cannot guarantee that it will be the same for your laser and you may break something if you attempt this. I am not responsible for anything you do to your laser if you follow my instructions.

This Blog article will give an overview of the project and all the files will be made available in my Github account www.github.com/gadjet

The github files will follow on after this blog post so please be patient if they aren't there yet.

While I was moving the Stepper controller inside the main body of the Commarker B4 30W laser I decided that I could tap into the lift buttons on the front of the unit and using the now spare 5 way cable, that used to connect to the stepper controller, connect to some external buttons to move the head up and down.

This was a good idea for me because the orientation of the laser unit means that I have to face it from the side and I can't see the buttons easily.

3D Printed enclosure for the external buttons

When I changed the 5 way connector on the back of the laser (old stepper controller connection) and replaced it with a 4 way connector (from the original stepper controller enclosure) I was able to use the redundant 5 way connector in a spare, unused,  hole at the rear of the laser to plug in the external buttons.

How the current buttons work


The front buttons on my B4 30W are connected to a motor controller module that switches the polarity of the DC motor depending which button is pressed to drive the laser head up or down.


The Module has two relays to control the polarity of the motor, at rest (no buttons pressed) both motor connections are connected via the relays to ground, this shorts the motor so it would be difficult to move.
When the UP button is pressed one of the relays switches one of the motor connections to positive causing the motor to move the head up, if the other button is pressed the opposite motor connection is connected to positive and the motor moves the headDOWN.
When the button is released the motor connections are then grounded again bringing the motor to a quick stop.  This is know a an H-Bridge arrangement.
Motor direction control example circuit

The addition of the external buttons


To enable the external controller to activate the motor I tapped in parallel with the buttons so that they would still work if the external buttons were not plugged in.
The drawing below shows how the external buttons were connected in parallel to the existing buttons, I have kept the wire colours as I found them inside the Laser.  The external buttons connector has the pins shorted out so that the internal buttons will also work, if the external buttons are disconnected then they will stop working and a shorting plug would be required.  The interconnecting cable is the one that was provided witht the external stepper controller which I placed inside the laser and was no longer required.


The addition of the height controller

Main components


The last stage of my modification was to add an external controller that could move the Galvo head to a known height that could be entered on my PC.
To achieve this I needed a method of detecting the position of the laser head relative to the base of the laser, after looking into to some laser distance measuring devices that used IR lasers and detectors using TOF (Time Of Flight) measurements to detect range I realised that the accuracy and repeatability for the reasonably priced detectors was not good enough.
I settled on using a Linear scale, a device used on lathes and milling machines to accurately and reliably measure distance for linear movement.
Linear Scale
Linear Scale - sourced from Aliexpress


These devices come in different lengths and I chose 550mm.  The Linear scale is secured to the top and bottom of the Z height tower of the laser using some 3D printed brackets I designed and the moving sled is attached to the Galvo head and moves up and down with the head.  The signals from the linear scale are fed into two interrupt pins of an ATMega328P (as used in the Arduino UNOs) 

As the Linear scale is a relative measuement method rather than absolute we need a way to define a reference point at a known measurement, to do this I used an inductive sensor that can detect the presence of the metal in the laser head unit and feedback to the controller when the head reaches a known position.
Inductive sensor
Inductive Sensor - Sourced from Amazon

These sensors are also used to stop the motor movement at the extremes of the Z height range.  One thing to note is that these sensors come with a wide voltage supply range but typically start at 6V but I've found that mine work fine at 5V, make sure your choice of sensor does work at 5V.

Component overview

The rendering below shows the position of the components added to the Z height tower (without the tower in the picture)

The controller


OK so the next thing is to connect all the parts to the controller, the controller is a custom PCB based on an Atmel Mega328p 8 bit processor (Arduino UNO) but you could use an Ardunino UNO, Nano, ESP based processor or any other with suitable IO.
I chose the 328P because it is relatively cheap and available at JLCPCB where I get my PCBs made.
I also included a serial to USB interface so the controller could be connected to a computer and interact with the user via the custom application.
The code I run is, apart from a couple of tweaks, generated by the Google Gemini Canvas AI.


The PCB has the ISP programming connector because the chips have no bootloader code as supplied so this need flashing before you can load a sketch.  There are also connectors for some of the spare GPIOs and the I2C bus so a display could be connected or even a laser distance measuring device if you like but please note that the voltage is 5V and NOT 3.3V.
Although initially the hardware was created with the intention of driving a stepper motor controller I've currently configured the code to drive the DC motor controller in the Laser unit, therefore Down for the motor uses the "DIR" connection and the Up uses the "STEP" connection

In this second version I added all the screw terminal connections so that each sensor could be connected, you can connect directly to the screw terminals or, like I did, use aircraft type connectors 
  • 2 off 4 pin 12mm connectors for the Limit Switches and the Linear scale
  • 2 off 5 pin 16mm connectors for the external buttons and the motor wires to the laser unit.

PC Software

The PC software is a work in progress and is written in Visual Studio/Visual Basic and connects to the controller via USB allowing 2 way communication, the application displays the mm of movement as the laser head moves up and down and is also used to trigger a fixed distance movement up or down and to calibrate the position of the laser head to a known distance from the base.


The current functions of the PC application: -
  • Display the available comm ports and connect/disconnect
  • Display the position of the laser head in mm
  • Calibrate the distance from the top limit switch to the base
  • Measure the distance from the head to the base and set the height to that value
  • Trigger a fixed distance move in mm from the current position
  • Setup some pre-defined positions on the three configurable buttons
    • Focus position for each lens?
  • Display the text data recieved from the controller in the console window
All the 3D files, Sketch and PC software will be available on my Github within the next couple of weeks.

Please note that this project is a work in progress and may change in functionality as time moves on also I make no guarantees on the functionality and/or safety of this software, use at your own risk.










ESP-NOW to WiFi/MQTT Gateway using Xiao EPS S3s

 I use Home Assistant to control and monitor devices around my home, I designed a wireless door/window sensor in an earlier blog entry that ...

Popular Posts