XIAO RP2040 Mouse Ver 3.0

Over the last few months, We have been steadily improving the design of our XIAO RP2040-based mouse device. With this, ver 3.0 all the hardware bugs were finally eliminated, and we also placed the device into its first-ever enclosure.

Let us take a look at the design

The PCB and Schematic


The PCB is a very strange shape, with lots of cut-outs. This is to accommodate the big push buttons that will be mounted in the enclosure, as well as to fit nicely into the mounting area of the enclosure… This design took quite some time with a pair of callipers and CAD, but all went well, and the shape is perfectly accurate.


The schematic is also straight forward, with the only real changes begin to the rotary encoder. In ver 2.0, We connected the encoder to the MCP23008, but for some reason CircuitPython does not seem to like an encoder connected to an IO extender… That forced us to do some software hack to use the encoder… I have thus decided to change things around in ver 3.0 and move the encoder back to the native GPIO on the XIAO RP2040

It is also interesting to note that the circuit was initially designed for the XIAO ESP32S3, but due to issues with stock, as well as crazy prices on local parts, we made a quick turn-around and went back to the RP2040. The ESP32S3 was going to allow us to implement a wireless device, through using ESPNow protocol… That may still be done in future, but for now, I think we have done enough work on the mouse device for the time being…

Manufacturing the PCB and Assembly

I choose PCBWay for my PCB manufacturing. Why? What makes them different from the rest?

PCBWay‘s business goal is to be the most professional PCB manufacturer for prototyping and low-volume production work in the world. With more than a decade in the business, they are committed to meeting the needs of their customers from different industries in terms of quality, delivery, cost-effectiveness and any other demanding requests. As one of the most experienced PCB manufacturers and SMT Assemblers in China, they pride themselves to be our (the Makers) best business partners, as well as good friends in every aspect of our PCB manufacturing needs. They strive to make our R&D work easy and hassle-free.

How do they do that?

PCBWay is NOT a broker. That means that they do all manufacturing and assembly themselves, cutting out all the middlemen, and saving us money.

PCBWay’s online quoting system gives a very detailed and accurate picture of all costs upfront, including components and assembly costs. This saves a lot of time and hassle.

PCBWay gives you one-on-one customer support, that answers you in 5 minutes ( from the Website chat ), or by email within a few hours ( from your personal account manager). Issues are really resolved very quickly, not that there are many anyway, but, as we are all human, it is nice to know that when a gremlin rears its head, you have someone to talk to who will do his/her best to resolve your issue as soon as possible.

Find out more here


Assembly was quite easy, I chose to use a stencil, because the IO Expander chip has a very tiny footprint, as well as a leadless package… The stencil definitely helps prevent excessive solder paste, as well as saves a lot of time on reworking later…


In the picture above, we can clearly see why I had to design the PCB with such an irregular shape.

Firmware and Coding

We are still using CircuitPython for the firmware on this device. It is not perfect, but it works, well sort of anyway. What does that mean? Well… As far as the mouse functions are concerned, clicking, scrolling, moving the pointer – all of that is works perfectly, and thus allows me to use the device for basic operations every day. Drag and Drop, as well as selecting and or highlighting text DOES NOT work. This seem to be an issue with the HID code in Circuitpython, meaning it doesn’t seem to be implemented. It is also way beyond my abilities to implement it myself…

Below is the code.py file, with the boot.py below that


import time
import board
import busio
from rainbowio import colorwheel
import neopixel
import rotaryio
import microcontroller
from digitalio import Direction
from adafruit_mcp230xx.mcp23008 import MCP23008
import digitalio
i2c = busio.I2C(board.SCL, board.SDA)
mcp = MCP23008(i2c)


from analogio import AnalogIn
import usb_hid
from adafruit_hid.mouse import Mouse
joyX = board.A0
joyY = board.A1
JoyBtn = board.D2

LeftBtn = 0
CenterBtn = 1
RightBtn = 2
UpBtn = 3
DownBtn = 4
EncoderBtn = 5


mouse = Mouse(usb_hid.devices)
xAxis = AnalogIn(joyX)
yAxis = AnalogIn(joyY)

# NEOPIXEL
pixel_pin = board.NEOPIXEL
num_pixels = 1
pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.1, auto_write=False)

leftbutton = mcp.get_pin(LeftBtn)
leftbutton.direction = digitalio.Direction.INPUT
leftbutton.pull = digitalio.Pull.UP

centerbutton = mcp.get_pin(CenterBtn)
centerbutton.direction = digitalio.Direction.INPUT
centerbutton.pull = digitalio.Pull.UP

maint_btn = digitalio.DigitalInOut(JoyBtn)
maint_btn.switch_to_input(pull=digitalio.Pull.UP)

rightbutton = mcp.get_pin(RightBtn)
rightbutton.direction = digitalio.Direction.INPUT
rightbutton.pull = digitalio.Pull.UP

enc_btn = mcp.get_pin(EncoderBtn)
enc_btn.direction = digitalio.Direction.INPUT
enc_btn.pull = digitalio.Pull.UP

scroll_up = mcp.get_pin(UpBtn)
scroll_up.direction = digitalio.Direction.INPUT
scroll_up.pull = digitalio.Pull.UP

scroll_down = mcp.get_pin(DownBtn)
scroll_down.direction = digitalio.Direction.INPUT
scroll_down.pull = digitalio.Pull.UP



mousewheel = rotaryio.IncrementalEncoder(board.D6, board.D7, 4)
last_position = mousewheel.position
print(mousewheel.position)

move_speed = 3
enc_down = 0

RED = (255, 0, 0)
YELLOW = (255, 150, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (180, 0, 255)
BLACK = (0, 0, 0)


if move_speed == 0:
    in_min, in_max, out_min, out_max = (0, 65000, -20, 20)
    filter_joystick_deadzone = (
        lambda x: int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
        if abs(x - 32768) > 500
        else 0
    )
if move_speed == 1:
    pixels.fill(GREEN)
    pixels.show()
    in_min, in_max, out_min, out_max = (0, 65000, -15, 15)
    filter_joystick_deadzone = (
        lambda x: int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
        if abs(x - 32768) > 500
        else 0
    )
if move_speed == 2:
    pixels.fill(BLUE)
    pixels.show()
    in_min, in_max, out_min, out_max = (0, 65000, -10, 10)


filter_joystick_deadzone = (
        lambda x: int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
        if abs(x - 32768) > 500
        else 0
    )
if move_speed == 3:
    pixels.fill(PURPLE)
    pixels.show()
    in_min, in_max, out_min, out_max = (0, 65000, -8, 8)
    filter_joystick_deadzone = (
        lambda x: int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
        if abs(x - 32768) > 500
        else 0
    )
if move_speed == 4:
    pixels.fill(CYAN)
    pixels.show()
    in_min, in_max, out_min, out_max = (0, 65000, -5, 5)
    filter_joystick_deadzone = (
        lambda x: int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
        if abs(x - 32768) > 500
        else 0
    )


pixels.fill(BLACK)
pixels.show()
while True:
    # Set mouse accelleration ( speed)
    #print(mousewheel.position)
    if move_speed == 0:
        pixels.fill(BLACK)
        pixels.show()
        in_min, in_max, out_min, out_max = (0, 65000, -20, 20)
        filter_joystick_deadzone = (
            lambda x: int(
                (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
            )
            if abs(x - 32768) > 500
            else 0
        )
    if move_speed == 1:
        pixels.fill(GREEN)
        pixels.show()
        in_min, in_max, out_min, out_max = (0, 65000, -15, 15)
        filter_joystick_deadzone = (
            lambda x: int(
                (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
            )
            if abs(x - 32768) > 500
            else 0
        )
    if move_speed == 2:
        pixels.fill(BLUE)
        pixels.show()
        in_min, in_max, out_min, out_max = (0, 65000, -10, 10)
        filter_joystick_deadzone = (
            lambda x: int(
                (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
            )
            if abs(x - 32768) > 500
            else 0
        )
    if move_speed == 3:
        pixels.fill(PURPLE)
        pixels.show()
        in_min, in_max, out_min, out_max = (0, 65000, -8, 8)
        filter_joystick_deadzone = (
            lambda x: int(
                (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
            )
            if abs(x - 32768) > 500
            else 0
        )
    if move_speed == 4:
        pixels.fill(CYAN)
        pixels.show()
        in_min, in_max, out_min, out_max = (0, 65000, -5, 5)
        filter_joystick_deadzone = (
            lambda x: int(
                (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
            )
            if abs(x - 32768) > 500
            else 0
        )

    current_position = mousewheel.position
    position_change = current_position - last_position

    x_offset = filter_joystick_deadzone(xAxis.value) * -1  # Invert axis
    y_offset = filter_joystick_deadzone(yAxis.value)
    mouse.move(x_offset, y_offset, 0)

    if enc_btn.value and enc_down == 1:
        move_speed = move_speed + 1
        if move_speed > 4:
            move_speed = 0

        # print (move_speed)
        enc_down = 0

    if not enc_btn.value:
        enc_down = 1

    if leftbutton.value:
        mouse.release(Mouse.LEFT_BUTTON)
        # pixels.fill(BLACK)
        # pixels.show()
    else:
        mouse.press(Mouse.LEFT_BUTTON)
        pixels.fill(GREEN)
        pixels.show()

    if centerbutton.value:
        mouse.release(Mouse.MIDDLE_BUTTON)
    else:
        mouse.press(Mouse.MIDDLE_BUTTON)
        pixels.fill(YELLOW)
        pixels.show()

    # Center button on joystick
    if maint_btn.value:
        mouse.release(Mouse.LEFT_BUTTON)
    else:
        mouse.press(Mouse.LEFT_BUTTON)
        pixels.fill(GREEN)
        pixels.show()

    if rightbutton.value:
        mouse.release(Mouse.RIGHT_BUTTON)
        # pixels.fill(BLACK)
        # pixels.show()
    else:
        mouse.press(Mouse.RIGHT_BUTTON)
        pixels.fill(PURPLE)
        pixels.show()

    if not scroll_up.value:
        mouse.move(wheel=1)
        time.sleep(0.25)
        pixels.fill(BLUE)
        pixels.show()

    if not scroll_down.value:
        mouse.move(wheel=-1)
        time.sleep(0.25)
        pixels.fill(CYAN)
        pixels.show()

    if not scroll_up.value and not scroll_down.value:
        for x in range(4):
            pixels.fill(RED)
            pixels.show()
            time.sleep(0.5)
            pixels.fill(BLACK)
            pixels.show()
            time.sleep(0.5)
        microcontroller.reset()



    if position_change > 0:
        mouse.move(wheel=position_change)
        #print(current_position)
        #pixels.fill(BLUE)
        #pixels.show()
    elif position_change < 0:
        mouse.move(wheel=position_change)
        #print(current_position)
        #pixels.fill(CYAN)
        #pixels.show()
    last_position = current_position
    pixels.fill(BLACK)
    pixels.show()

boot.py

import storage
import board, digitalio
import time
from rainbowio import colorwheel
import neopixel
import busio
from digitalio import Direction
from adafruit_mcp230xx.mcp23008 import MCP23008
import digitalio
i2c = busio.I2C(board.SCL, board.SDA)
mcp = MCP23008(i2c)



#button = digitalio.DigitalInOut(board.D8)
#button.pull = digitalio.Pull.UP

button = mcp.get_pin(6)
button.direction = digitalio.Direction.INPUT
button.pull = digitalio.Pull.UP

Rstbutton = mcp.get_pin(7)
Rstbutton.direction = digitalio.Direction.INPUT
Rstbutton.pull = digitalio.Pull.UP

# NEOPIXEL
pixel_pin = board.NEOPIXEL
num_pixels = 1
pixels = neopixel.NeoPixel(pixel_pin,num_pixels,brightness=0.2,auto_write=False)

RED = (255, 0, 0)
YELLOW = (255,150, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (180, 0, 255)
BLACK = (0, 0, 0)

# Disable devices only if button is not pressed.
#usb_hid.enable((), boot_device=2)
if button.value:
   pixels.fill(GREEN)
   pixels.show()
   storage.disable_usb_drive()
   usb_cdc.disable()
else:
    pixels.fill(RED)
    pixels.show()
    usb_cdc.enable(console=True, data=False)
    storage.enable_usb_drive()


time.sleep(5)
# Write your code here :-)

Xiao RP2040 Joystick Mouse – revision 2.00

Revision 1.0 of the Project


Over the last few months, I have been using the initial revision of this project on almost a daily basis. It has come a long way since the initial concept was implemented on the breadboard.

Initial Concept on a Breadboard

While completely functional, and relatively easy to use, quite a few things started adding up – making me believe that it could be better…

That prompted me to start thinking about a hardware revision, adding some missing features, like a middle button, and “maybe” a display to the device, making it easier to visualise settings, etc…

Current Revision 2.0 ” Proof of concept ” prototype

My main limitations came from the Seeed Studio Xiao RP2040 Module. While super tiny and compact, the module only has access to 11 GPIO pins on the RP2040 chip. Most of these were already in use, connected to buttons etc.

I would thus have to find an I2C IO expander that will be supported by CircuitPython and have a suitably small footprint. That way, I could free up many of the valuable GPIO pins on the Xiao RP2040 for other purposes.

What did I use?

My initial goto chip was the MCP23017, with 16 GPIO pins. But after some more thinking, I settled on the MCP23008, which has only 8 GPIO lines. I2C bus breakout headers to allow for expansion, as well as access to all the unused GPIO pins on the XIAO RP2040, were also added.

The Rotary encoder was once again included, as it could later be used for selecting Menu options etc.

What is the current status of the project?

The revision 2.00 hardware works as expected, with a few issues.
CircuitPython has an issue with rotary encoders connected to IO expanders. I don’t understand why that would be the case, but wrote my basic routine to handle the encoder, which at this time, is only used for scrolling. ( I have still got to decide if a display would be needed)

As far as settings are concerned, I have only implemented a sort of “mouse speed” feature that determines how fast or slow ( for better accuracy ) the pointer moves. This is currently controlled by the encoder button, on a cycling loop, with different colours on the NeoPixel as visual feedback on the current speed selected.

USB connectivity at computer startup and/or resuming from a suspend operation is still a major problem. This means that you have to physically reset the device after every resume from suspend, or after starting your computer.
From what I can see in the CircuitPython documentation, it is possible to detect USB connectivity. That part works. From there, It seems that once USB connectivity is lost, CircuitPython goes into some sort of unknown state, and no further code is executed, thus making a software reset not executing…

I have an idea that it has got something to do with the HID Mouse mode or something ???? For now, I am happy to just hit a reset button to continue…

Another big issue is a suitable enclosure. Revision 2.00 PCB was not designed to be placed into an enclosure, mainly because I have so far been quite unsuccessful in finding a suitable one. My 3D design skills are also quite lacking, so designing something from scratch won’t do either. I have decided to sort out all the hardware and firmware issues first, find an enclosure and then modify the PCB layout to fit that.

Manufacturing the PCB

I choose PCBWay for my PCB manufacturing. Why? What makes them different from the rest?

PCBWay‘s business goal is to be the most professional PCB manufacturer for prototyping and low-volume production work in the world. With more than a decade in the business, they are committed to meeting the needs of their customers from different industries in terms of quality, delivery, cost-effectiveness and any other demanding requests. As one of the most experienced PCB manufacturers and SMT Assemblers in China, they pride themselves to be our (the Makers) best business partners, as well as good friends in every aspect of our PCB manufacturing needs. They strive to make our R&D work easy and hassle-free.

How do they do that?

PCBWay is NOT a broker. That means that they do all manufacturing and assembly themselves, cutting out all the middlemen, and saving us money.

PCBWay’s online quoting system gives a very detailed and accurate picture of all costs upfront, including components and assembly costs. This saves a lot of time and hassle.

PCBWay gives you one-on-one customer support, that answers you in 5 minutes ( from the Website chat ), or by email within a few hours ( from your personal account manager). Issues are really resolved very quickly, not that there are many anyway, but, as we are all human, it is nice to know that when a gremlin rears its head, you have someone to talk to who will do his/her best to resolve your issue as soon as possible.

Find out more here

Assembly and Testing

Assembly is easy but does require a stencil due to the small size of some of the SMD components.

CircuitPython Coding – A work in progress

This is the current code, and it is a work in progress. It works, and could definitely be optimised quite a lot. I am not very familiar with Python but I believe I can help myself around it.

import time
import board
import busio
from rainbowio import colorwheel
import neopixel
import digitalio
import rotaryio
import microcontroller
from digitalio import Direction
from adafruit_mcp230xx.mcp23008 import MCP23008
import digitalio
i2c = busio.I2C(board.SCL, board.SDA)
mcp = MCP23008(i2c)

from analogio import AnalogIn
import usb_hid
from adafruit_hid.mouse import Mouse

mouse = Mouse(usb_hid.devices)
xAxis = AnalogIn(board.A2)
yAxis = AnalogIn(board.A1)

# NEOPIXEL
pixel_pin = board.NEOPIXEL
num_pixels = 1
pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.1, auto_write=False)

leftbutton = mcp.get_pin(3)
leftbutton.direction = digitalio.Direction.INPUT
leftbutton.pull = digitalio.Pull.UP

centerbutton = mcp.get_pin(4)
centerbutton.direction = digitalio.Direction.INPUT
centerbutton.pull = digitalio.Pull.UP

maint_btn = digitalio.DigitalInOut(board.D0)
maint_btn.switch_to_input(pull=digitalio.Pull.UP)

rightbutton = mcp.get_pin(5)
rightbutton.direction = digitalio.Direction.INPUT
rightbutton.pull = digitalio.Pull.UP

enc_btn = mcp.get_pin(2)
enc_btn.direction = digitalio.Direction.INPUT
enc_btn.pull = digitalio.Pull.UP

scroll_up = mcp.get_pin(6)
scroll_up.direction = digitalio.Direction.INPUT
scroll_up.pull = digitalio.Pull.UP

scroll_down = mcp.get_pin(7)
scroll_down.direction = digitalio.Direction.INPUT
scroll_down.pull = digitalio.Pull.UP

enc_a = mcp.get_pin(0)
enc_a.direction = digitalio.Direction.INPUT
enc_a.pull = digitalio.Pull.UP

enc_b = mcp.get_pin(1)
enc_b.direction = digitalio.Direction.INPUT
enc_b.pull = digitalio.Pull.UP

enc_a_pressed = False
enc_b_pressed = False

#mousewheel = rotaryio.IncrementalEncoder(enc_a, mcp.get_pin(1))
#last_position = mousewheel.position

move_speed = 3
enc_down = 0

RED = (255, 0, 0)
YELLOW = (255, 150, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (180, 0, 255)
BLACK = (0, 0, 0)


if move_speed == 0:
    in_min, in_max, out_min, out_max = (0, 65000, -20, 20)
    filter_joystick_deadzone = (
        lambda x: int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
        if abs(x - 32768) > 500
        else 0
    )
if move_speed == 1:
    pixels.fill(GREEN)
    pixels.show()
    in_min, in_max, out_min, out_max = (0, 65000, -15, 15)
    filter_joystick_deadzone = (
        lambda x: int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
        if abs(x - 32768) > 500
        else 0
    )
if move_speed == 2:
    pixels.fill(BLUE)
    pixels.show()
    in_min, in_max, out_min, out_max = (0, 65000, -10, 10)


filter_joystick_deadzone = (
        lambda x: int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
        if abs(x - 32768) > 500
        else 0
    )
if move_speed == 3:
    pixels.fill(PURPLE)
    pixels.show()
    in_min, in_max, out_min, out_max = (0, 65000, -8, 8)
    filter_joystick_deadzone = (
        lambda x: int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
        if abs(x - 32768) > 500
        else 0
    )
if move_speed == 4:
    pixels.fill(CYAN)
    pixels.show()
    in_min, in_max, out_min, out_max = (0, 65000, -5, 5)
    filter_joystick_deadzone = (
        lambda x: int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
        if abs(x - 32768) > 500
        else 0
    )


pixels.fill(BLACK)
pixels.show()
while True:
    # Set mouse accelleration ( speed)
    if move_speed == 0:
        pixels.fill(BLACK)
        pixels.show()
        in_min, in_max, out_min, out_max = (0, 65000, -20, 20)
        filter_joystick_deadzone = (
            lambda x: int(
                (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
            )
            if abs(x - 32768) > 500
            else 0
        )
    if move_speed == 1:
        pixels.fill(GREEN)
        pixels.show()
        in_min, in_max, out_min, out_max = (0, 65000, -15, 15)
        filter_joystick_deadzone = (
            lambda x: int(
                (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
            )
            if abs(x - 32768) > 500
            else 0
        )
    if move_speed == 2:
        pixels.fill(BLUE)
        pixels.show()
        in_min, in_max, out_min, out_max = (0, 65000, -10, 10)
        filter_joystick_deadzone = (
            lambda x: int(
                (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
            )
            if abs(x - 32768) > 500
            else 0
        )
    if move_speed == 3:
        pixels.fill(PURPLE)
        pixels.show()
        in_min, in_max, out_min, out_max = (0, 65000, -8, 8)
        filter_joystick_deadzone = (
            lambda x: int(
                (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
            )
            if abs(x - 32768) > 500
            else 0
        )
    if move_speed == 4:
        pixels.fill(CYAN)
        pixels.show()
        in_min, in_max, out_min, out_max = (0, 65000, -5, 5)
        filter_joystick_deadzone = (
            lambda x: int(
                (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
            )
            if abs(x - 32768) > 500
            else 0
        )

    #current_position = mousewheel.position
    #position_change = current_position - last_position

    x_offset = filter_joystick_deadzone(xAxis.value) * -1  # Invert axis
    y_offset = filter_joystick_deadzone(yAxis.value) * -1
    mouse.move(x_offset, y_offset, 0)

    if enc_btn.value and enc_down == 1:
        move_speed = move_speed + 1
        if move_speed > 4:
            move_speed = 0

        # print (move_speed)
        enc_down = 0

    if not enc_btn.value:
        enc_down = 1

    if leftbutton.value:
        mouse.release(Mouse.LEFT_BUTTON)
        # pixels.fill(BLACK)
        # pixels.show()
    else:
        mouse.press(Mouse.LEFT_BUTTON)
        pixels.fill(GREEN)
        pixels.show()

    if centerbutton.value:
        mouse.release(Mouse.MIDDLE_BUTTON)
    else:
        mouse.press(Mouse.MIDDLE_BUTTON)
        pixels.fill(YELLOW)
        pixels.show()

    # Center button on joystick
    if maint_btn.value:
        mouse.release(Mouse.LEFT_BUTTON)
    else:
        mouse.press(Mouse.LEFT_BUTTON)
        pixels.fill(GREEN)
        pixels.show()

    if rightbutton.value:
        mouse.release(Mouse.RIGHT_BUTTON)
        # pixels.fill(BLACK)
        # pixels.show()
    else:
        mouse.press(Mouse.RIGHT_BUTTON)
        pixels.fill(PURPLE)
        pixels.show()

    if not scroll_up.value:
        mouse.move(wheel=1)
        time.sleep(0.25)
        pixels.fill(BLUE)
        pixels.show()

    if not scroll_down.value:
        mouse.move(wheel=-1)
        time.sleep(0.25)
        pixels.fill(CYAN)
        pixels.show()

    if not scroll_up.value and not scroll_down.value:
        for x in range(4):
            pixels.fill(RED)
            pixels.show()
            time.sleep(0.5)
            pixels.fill(BLACK)
            pixels.show()
            time.sleep(0.5)
        microcontroller.reset()

    if enc_a.value:
        enc_a_pressed = False
    else:
        if enc_b_pressed:
            enc_a_pressed = False
        else:
            enc_a_pressed = True

    if enc_b.value:
        enc_b_pressed = False
    else:
        if enc_a_pressed:
            enc_b_pressed = False
        else:
            enc_b_pressed = True

    if enc_a_pressed:
        mouse.move(wheel=1)
        time.sleep(0.25)
        enc_a_pressed = False
    if enc_b_pressed:
        mouse.move(wheel=-1)
        time.sleep(0.25)
        enc_b_pressed = False

    #if position_change > 0:
    #    mouse.move(wheel=position_change)
    #    # print(current_position)
    #    pixels.fill(BLUE)
    #    pixels.show()
    #elif position_change < 0:
    #    mouse.move(wheel=position_change)
    #    # print(current_position)
    #    pixels.fill(CYAN)
    #    pixels.show()
    #last_position = current_position
    pixels.fill(BLACK)
    pixels.show()

Conclusion

Okay, so this is where it is at at the moment. The code is not perfect, and the hardware is not perfect, but it works. I am using this device every day, and also making changes as needed. At the moment, there are some issues, but they do not prevent the actual use of the device.

If you are interested or would like to make modifications, feel free to do so.

MCP23008 Breakout

I designed this breakout to assist me during prototyping my next version of the “RP2040 Emergency Mouse“. In that project, I used the SEEED Studio Xiao RP2040, along with a few other components to create a simple but effective computer mouse-type device.

While the “mouse” works quite well, I have quite early on discovered that it could be better. More on that in a follow-up article, but let us just say that I needed more GPIO pins than that were available on the XIAO RP2040 and that the layout can be improved a bit – especially If I want to get it into an enclosure.

I am still quite neutral about CircuitPython and Micropython on microcontrollers, and Python in general, but since the above-mentioned project runs completely on CircuitPython, it made a lot of good sense to get more into it.

What is on the PCB?


I wanted something as small as possible, and that meant that I chose a QFN package for the MCP23008 IO expander chip. At only 4mm x 4mm, and not being bothered to try and find a DIP version, a breakout board became a much-needed necessity.

Address Selection Jumpers, Two I2C bus headers, and of course the all-important GPIO pins make up all of the user accessible interfacing. Note that the chip reset line is permanently tied to Vcc to make things a bit less cluttered, and easier to use while prototyping.

A decoupling capacitor, as well as pullup resistors on the I2c lines, were also included. Another note here, I did not provide my usual selection jumper to disable these on this particular board.

The Schematic


Manufacturing the PCB

I choose PCBWay for my PCB manufacturing. Why? What makes them different from the rest?

PCBWay‘s business goal is to be the most professional PCB manufacturer for prototyping and low-volume production work in the world. With more than a decade in the business, they are committed to meeting the needs of their customers from different industries in terms of quality, delivery, cost-effectiveness and any other demanding requests. As one of the most experienced PCB manufacturers and SMT Assemblers in China, they pride themselves to be our (the Makers) best business partners, as well as good friends in every aspect of our PCB manufacturing needs. They strive to make our R&D work easy and hassle-free.

How do they do that?

PCBWay is NOT a broker. That means that they do all manufacturing and assembly themselves, cutting out all the middlemen, and saving us money.

PCBWay’s online quoting system gives a very detailed and accurate picture of all costs upfront, including components and assembly costs. This saves a lot of time and hassle.

PCBWay gives you one-on-one customer support, that answers you in 5 minutes ( from the Website chat ), or by email within a few hours ( from your personal account manager). Issues are really resolved very quickly, not that there are many anyway, but, as we are all human, it is nice to know that when a gremlin rears its head, you have someone to talk to that will do his/her best to resolve your issue as soon as possible.

Find out more here

Assembly and Testing

Due to the small size of the QFN package, I strongly recommend that you either have this assembled professionally, or at least consider buying a stencil for applying the solder paste to this board. Maybe those with excellent eyesight can do without that?


Assembly took only a few minutes, with the help of an extremely accurate stencil, followed by a few minutes on a hotplate, and manually soldering on the header pins.

Using the MCP23008 with CircuitPython

I2C devices are very easy to use with the Arduino IDE or similar, and as such, I will not be covering that here.

Circuitpython, however, is gaining popularity, and I am slowly starting to see what the hype is about myself…

So, to get started, you need a microcontroller running CircuitPython – See Adafruit for excellent tutorials. You will also need a few libraries from Adafruit
See this link

I will give a very simple example below, showing how to set a pin as an output, as well as an input with internal pullup resistors enabled. Note that the MCP23008 DOES NOT SUPPORT pull-down resistors internally. You need to add those by yourself externally.

# Initialising all the required libraries
import board
import busio
from digitalio import Direction
from adafruit_mcp230xx.mcp23008 import MCP23008
i2c = busio.I2C(board.SCL, board.SDA)
# Adding the MCP23008
mcp = MCP23008(i2c)
# This assumes that you are using the default address [ i.e. all address 
# pins are grounded]
#
#
#
# Defining two outputs on pins 0 and 1
pin0 = mcp.get_pin(0)
pin0.direction = Direction.OUTPUT
pin1 = mcp.get_pin(1)
pin1.direction = Direction.OUTPUT
#
#
# We can now control the pins by setting them to true or false, true being 
# high
pin0.value = True
pin1.value = True
#
# and switch them off again by using
pin0.value = False
pin1.value = False
#
#
# We can also use the pins as inputs.
# We will activate the internal pullup as well
#
# first , we need another library
import digitalio
pin2 = mcp.get_pin(2)
pin2.direction = digitalio.Direction.INPUT
pin2.pull = digitalio.Pull.UP
#
#
# Reading the pin value is now as easy as 
pin2.value
#
# This will return True if the pin is high ( its default state with pullups # activated, of False if pulled low, by for example a switch of button )

Conclusion

The breakout works as expected, and it is very easy to use with CircuitPython.
I can now continue with the actual integration and Software for the RP2040 Mouse Rev 2.0 project.

High Current P-Mos Driver

This is a modification of my existing P-MOS driver circuits, intended for use with higher current LED Lights, as well as any other applications requiring a higher current capable P-Channel Mosfet to switch a load.

What is on the PCB?

I have used the IRF4905 P-Channe Mosfet here as it can sink up to 74 Amps of current – A complete overkill in many situations. Datasheet. The Mosfet is configured in a high-side switching configuration, thus eliminating problems with ground connections.

To prevent unreliable switching, a transistor is used to switch the gate, which is normally pulled high to keep the device switched off.


I have also included various connection headers for connecting the load, Power supply, as-well-as active high control headers for controlling the driver from a microcontroller. This was especially important as the Gate voltage of the Mosfet is above the acceptable 3.3 volt for use with many of the modern microcontrollers in use today.

It is important o note that I did not yet bother to do very accurate gate current calculations. I do not need super fast switching, and on the bench, the 500mA switching capability of the S9013W transistor gave me satisfactory results.

What is my intended use for this driver?

This is a 12v Automotive Fog light. It is meant to be an aftermarket upgrade. It will also be a very nice focused working light in my workshop, as the lighting is not optimal.

My initial idea is using two of these, PWM controlled from an ESPHome-controlled device to provide me with focused, dimmable lighting for assembly and other operations where a bit of extra light will be needed.

The Fish-eye lens of the internal lamp provides a very focused beam, and from initial testing seems to be exactly what I want.

The problem came in that the LED module consumes quite a bit of current ( 5A for the center lamp, and 3A for the ring light). These currents are way above the capabilities of my existing LED COB driver circuit, thus this MOD.

The Schematic

Manufacturing the PCB

I choose PCBWay for my PCB manufacturing. Why? What makes them different from the rest?

PCBWay‘s business goal is to be the most professional PCB manufacturer for prototyping and low-volume production work in the world. With more than a decade in the business, they are committed to meeting the needs of their customers from different industries in terms of quality, delivery, cost-effectiveness and any other demanding requests. As one of the most experienced PCB manufacturers and SMT Assemblers in China, they pride themselves to be our (the Makers) best business partners, as well as good friends in every aspect of our PCB manufacturing needs. They strive to make our R&D work easy and hassle-free.

How do they do that?

PCBWay is NOT a broker. That means that they do all manufacturing and assembly themselves, cutting out all the middlemen, and saving us money.

PCBWay’s online quoting system gives a very detailed and accurate picture of all costs upfront, including components and assembly costs. This saves a lot of time and hassle.

PCBWay gives you one-on-one customer support, that answers you in 5 minutes ( from the Website chat ), or by email within a few hours ( from your personal account manager). Issues are really resolved very quickly, not that there are many anyway, but, as we are all human, it is nice to know that when a gremlin rears its head, you have someone to talk to that will do his/her best to resolve your issue as soon as possible.

Find out more here

Assembly and Testing

This PCB is definitely quite easy to assemble, as there are only 16 SMD components on the board. These are all easily hand-solderable. The Mosfets and their respective heatsinks are through-hole components and thus super easy as well.

It is very important to note that we should NOT connect the heatsinks together. This is due to the fact that the Heatsink is connected to the DRAIN pin on the MOSFET. Connecting them together will thus short the various channels together.

For my testing procedure, I have connected the driver to the LED Fog light, as well as a 12v supply. Using an ESP8266 running ESPHome, the LED fog light was controlled with PWM. The current draw was 5A and 3A respectively. All of the MOSFETs remained cool to the touch, and the PCB tracks did not heat up as well.

Next steps

The next steps for this project would be to design a PCB that integrates this driver with the ESPHome control device, as well as design and build a suitable enclosure for the two lights and the control unit. This should ideally be mountable on the ceiling above my workbench. It would also be nice to design some sort of gimbal for each light, that can be controlled with stepper motors or servo’s to allow me to position the lights where I need them.

“The Emergency Mouse” – A project born out of necessity

Imagine You are working on a project late on a Friday evening and suddenly your mouse stops working… You can not scroll, and the right-side button won’t respond to your clicks… At the same time, you have a project design that has got to get finished… and the shops are all closed already…

These were the circumstances that led to the birth of “The Emergency Mouse” – A project born out of necessity. How did I solve my problem?

Having access to a lot of electronic modules saved the day. As a maker, I always have various modules and gadgets lying around, and on this unfortunate evening, I remember that the RP2040 has USB HID support. Combine that with a simple Analog Joystick module, a rotary encoder and some push buttons, add about 30 minutes worth of browsing the internet, struggling along with a broken mouse – we have to give the old one credit, it had a very long and hard life, and I finally found some example code that did not just jiggle the mouse pointer or do something equally silly…

The only problem with all of that was that the code was for CircuitPython… I generally dislike using Python on a Microcontroller, as I believe it is better suited for the computer, but, I am warming up to the idea… slowly…

The initial fix – a mess of wires on a breadboard

I quickly grabbed a RaspBerry Pi Pico out of a box, plugged it into a breadboard, loaded Circuitpyth and fired up the example code I got on the internet… While promising, It did not exactly do what I wanted… so a few minutes later, after some coding, I had a moving pointer, controlled by the small thumb joystick module, and with the center button as a “right button”…

So far so good… I can work more easily, but still did not have scrolling… so lets hit the datasheets and documentation on the Adafruit Website (not sponsored) and add a rotary encoder… works well, add more buttons, etc etc…

Eventually it was all done, and about 1 hour has passed, but we were left with a huge ugly mess on a breadboard, and a lot of unused GPIO pins.. So this Pico must go… it can be used for something more useful later…

Then my eye fell on a SEEED Studio XIAO RP2040 module, almost begging to be used… This is smaller, more compact… lets try that …

Initial breadboard version, here shown with the SEEED Studio XIAO RP2040

What functions did this “mouse” have

After changing to the XIAO RP2040, things went very quick…

I added two buttons for scrolling up and down, simulating a mouse wheel,
but kept the encoder… which, while VERY awkward to use at this stage, definitely had potential in the long run…

I also added another button to take over the function of a right button, while the center button on the joystick became left…

Disaster averted, with only about 2 hours wasted, I returned to my project and managed to get it finished using the “improvised-mouse-on-the-breadboard” contraption…

That night, while lying in bed, trying to get to fall asleep, the possibilities of this “contraption-on-the-breadboard” would not let me go… I am fairly old-school, and during the late 80’s and early 90’s owned quite a few “roller-ball” mouse devices… these later became trackballs, and being excessively overpriced, was promptly removed from my environment – the old ones did not last very long, and the new ones were, as I said, overly expensive…

I did however never forget the ease of use that first “rollerball mouse” gave me all that years ago, using only my thumb to move it around etc etc…

This idea would have to be investigated, and turned into a PCB… with that, I finally drifted off to sleep…

The PCB design

The next morning came, and due to reasons unknown, as well as being lazy, I decided not to leave the house, and go buy a new mouse. lets try online… No, they are crazy – I am not paying that for a mouse!

All the time using the “contraption-on-the-breadboard”. So this thing started growing on me… lets design a PCB

The Initial PCB design

After a few hours spent on deciding on optimal layout, I came up with this…
It was still a bit unrefined, but definitely had potential… It lacked a dedicated center button, and those momentary push-buttons requires a lot of force to use… but as a prototype, why not…

Let’s get this manufactured.

For this build, since I used a SEEED Studio module, I decided to send it to SEEED for manufacturing… no need to get components from various places, as they should have all in stock…

Seeed Studio’s Fusion service seamlessly marries convenience with full-feature capabilities in one simple platform. Whether you are prototyping or looking for a mass production partner or based on open source product customization requirements and other design manufacturing services, Seeed Studio Fusion service is catered to your needs starting with a simple online platform. https://www.seeedstudio.com/fusion.html

The PCB arrives from the factory

During the entire time that it took for the PCB to be manufactured and assembled, I was still using this “homemade mouse” – I started calling it a mouse now… and it was still on the breadboard… I never did bother to buy a new mouse, yet..


The PCB Arrived today, and apart from a few small soldering issues, looked great… I still had to do a bit of assembly on my own, as there was an issue with the components I wanted being out of stock.. I have plenty in stock of my own, so opted to do manual assembly…


The completed PCB now only needed a joystick, and some firmware…


After adding a few button caps, and mounting everything to a piece of acrylic plate, I had a working prototype…

The Firmware

As mentioned above, the device runs on CircuitPyton. As Such, there are quite a lot of “examples” on the internet, showing you how to do many USB HID “mouse” like things, but generally being completely useless…

I have thus spent quite a lot of time up to now, writing and refining my own version of the firmware, that is actually useful and does actually work.

It has the following features:
X-Y axis control of the mouse pointer via a thumb joystick, with a left click function on the center joystick button, as well as a dedicated “left” button.

A dedicated “right” button
A “virtual center” button made up of simultaneously pressing left and right

Up and down scrolling either using the rotary encoder as a “mouse wheel” or via dedicated up and down pushbuttons.

A dedicated Reset button – this is necessary, as I can not seem to get the device to initialise correctly at computer bootup.

Various software functions, like changing the pointer acceleration by pressing the center button on the rotary encoder

and most importantly, hiding the Circuitpyton drive, only showing it when I actually need access to the code in this device…

Various statuses are indicated using the NeoPixel on the XIAO, making it easy to see in what state the device is operating.

As such, I shall NOT be releasing the firmware at this moment, as it is still far from being perfect. It works, but it can be way better…

Summary and next steps

Since its “birth” late on a Friday night, about 3 weeks ago, I have been using this device, in its various forms as my primary pointer device. It is growing on me more every day, and it is quite comfortable to use – If we ignore the fact that it is not in a suitable enclosure and that I am still making small changes to the firmware from time to time.

I am already planning the next revision, in which I shall replace the momentary push-buttons with proper microswitches, as well as try my hand at designing a proper enclosure.

If you are a 3D printing expert and want to collaborate with me on this, let’s talk…

An I2C Matrix Keypad

The completed I2C Matrix Keypad

In a previous post this month I introduced my 4×4 matrix keypad. That keypad was designed to be directly interfaced to a microcontroller’s GPIO pins or alternatively to an IO expander chip like the PCF8574. That design, while working very well had the problem of requiring 8 GPIO pins to function correctly.

GPIO pins on a microcontroller can be considered very precious resources, and it should then be logical to assume that we should find a way to use these GPIO pins in a more conservative way, to allow us to interface more peripherals.

I solved this problem by integrating the keypad with an IO Expander on the same PCB. That will allow us to get away with using only 2 GPIO pins, and also open up the option of adding more keypads to the I2C bus, in the event that we need that many keys for a particular project.

The Schematic

I2C 4×4 Matrix Keypad Schematic

Looking closely at the schematic, we can see that it is exactly the same basic keypad circuit that I used in the initial design. The only difference is that in this design, I have integrated a PCF8574 directly onto the PCB.

Some additional features include selectable I2C Pullup resistors ( usually my microcontroller development boards already include those) that can be activated with a jumper when needed. There are also a set of address selection jumpers, making it possible to stack keypads together into a bigger keyboard if you require something like that. Note that, in this version of the hardware, I did not include headers for stacking.

The keypad can be powered by a DC power source of 3.3v to 5v.

The PCB

I2C Keypad PCB
3D Render of the I2C Keypad

The PCB is a double-layer board of 68.8mm x 50.8mm. Male header pins provide access to the connections as well as address and pullup resistor jumpers. In my build, I have mounted these male headers on the back of the PCB. That makes it possible to mount the Keypad in an enclosure without having the jumpers “stick out” and get in the way.

The top layer of the I2C Keypad PCB
Bottom Layer

Manufacturing

I choose PCBWay for my PCB manufacturing.
This month, PCBWay is also celebrating its 9th anniversary, and that means that there are quite a lot of very special offers available.

Why?
What makes them different from the rest?

PCBWay‘s business goal is to be the most professional PCB manufacturer for prototyping and low-volume production work in the world. With more than a decade in the business, they are committed to meeting the needs of their customers from different industries in terms of quality, delivery, cost-effectiveness and any other demanding requests. As one of the most experienced PCB manufacturers and SMT Assemblers in China, they pride themselves to be our (the Makers) best business partners, as well as good friends in every aspect of our PCB manufacturing needs. They strive to make our R&D work easy and hassle-free.

How do they do that?

PCBWay is NOT a broker. That means that they do all manufacturing and assembly themselves, cutting out all the middlemen, and saving us money.

PCBWay’s online quoting system gives a very detailed and accurate picture of all costs upfront, including components and assembly costs. This saves a lot of time and hassle.

PCBWay gives you one-on-one customer support, that answers you in 5 minutes ( from the Website chat ), or by email within a few hours ( from your personal account manager). Issues are really resolved very quickly, not that there are many anyway, but, as we are all human, it is nice to know that when a gremlin rears its head, you have someone to talk to that will do his/her best to resolve your issue as soon as possible.

Find out more here

Assembly

The assembly of this PCB was quite easy and quick. A stencil is not required. All SMD components are 0805 or bigger. It would thus be quite easy to solder them all by hand with a fine-tipped soldering iron.

I have however used soldering paste and hot air to reflow the components, as it is the fastest, in my opinion, and definitely looks neater than hand soldering.

After placing SMD components onto solder paste – ready for reflow soldering
After Reflow soldering with Hot Air

The board is now ready to solder the switches and header pins in place. As already mentioned above, I chose to assemble the headers on the back of the PCB to prevent them from interfering with any enclosure that I may later use with the keypad.

Final Assembly
Note that I assembled the headers onto the back of the PCB.

Testing and Coding

Testing the keypad consisted of a few steps, the first of which was ensuring that there were no short circuits, as well as that all the momentary switches worked.
This was done with a multimeter in continuity as well as diode mode, with probes alternatively on each column and row in turn, while pressing the buttons.

The next stage was testing the I2C IO Expander. This was done with a simple I2C Scanning sketch on an Arduino Uno. It did not do a lot, but, I could see that the PCF8574 is responding to its address and that the pullup resistors work when enabled. This test was repeated with my own ESP8266 and ESP32 boards, this time with pullup resistors disabled, as these boards already have them onboard.

Coding came next, and it was another case of perspectives. It seems like all commercial keypads do not have diodes. This affects the way that they work with a given library. It seems that software developers and hardware developers have different understandings of what a row and a column is.

This meant that, due to the fact that I have diodes on each switch, and the way that the library work – which pins are pulled high and which are set as inputs -, I had to swap around my rows and columns in the software to get everything to work. On a keypad with the diodes replaced with 0-ohm links, that was not needed.

A short test sketch follows below:

Note that with was run on an ESP8266-12E, therefore the Wire.begin() function was changed to Wire.begin(4,5); in order to use GPIO 4 and GPIO 5 for I2C

Another point to note is that the keypad Layout will seem strange. Remember that this is due to the diodes in series on each switch. That forces us to swap around the Rows and the Columns in the software, resulting in a mirrored and rotated left representation of the keypad. It looks funny, but believe me, it actually still works perfectly.

#include <Wire.h>
#include "Keypad.h"
#include <Keypad_I2C.h>

const byte n_rows = 4;
const byte n_cols = 4;

char keys[n_rows][n_cols] = {
    {'1', '4', '7', '*'},
    {'2', '5', '8', '0'},
    {'3', '6', '9', '#'},
    {'A', 'B', 'C', 'D'}};

byte rowPins[n_rows] = {4, 5, 6, 7};
byte colPins[n_cols] = {0, 1, 2, 3};

Keypad_I2C myKeypad = Keypad_I2C(makeKeymap(keys), rowPins, colPins, n_rows, n_cols, 0x20);

String swOnState(KeyState kpadState)
{
    switch (kpadState)
    {
    case IDLE:
        return "IDLE";
        break;
    case PRESSED:
        return "PRESSED";
        break;
    case HOLD:
        return "HOLD";
        break;
    case RELEASED:
        return "RELEASED";
        break;
    } // end switch-case
    return "";
} // end switch on state function

void setup()
{
    // This will be called by App.setup()
    Serial.begin(115200);
    while (!Serial)
    { /*wait*/
    }
    Serial.println("Press any key...");
    Wire.begin(4,5);
    myKeypad.begin(makeKeymap(keys));
}

char myKeyp = NO_KEY;
KeyState myKSp = IDLE;
auto myHold = false;

void loop()
{

    char myKey = myKeypad.getKey();
    KeyState myKS = myKeypad.getState();

    if (myKSp != myKS && myKS != IDLE)
    {
        Serial.print("myKS: ");
        Serial.println(swOnState(myKS));
        myKSp = myKS;
        if (myKey != NULL)
            myKeyp = myKey;
        String r;
        r = myKeyp;
        Serial.println("myKey: " + String(r));
        if (myKS == HOLD)
            myHold = true;
        if (myKS == RELEASED)
        {
            if (myHold)
                r = r + "+";
            Serial.println(r.c_str());
            myHold = false;
        }
        Serial.println(swOnState(myKS));
        myKey == NULL;
        myKS = IDLE;
    }
}

Conclusion

This project once again delivered what I set out to achieve. It has some quirks, but nothing serious. Everything works as expected, both in the Arduino IDE/platform IO realm, as well as in ESPHome. It is worth noting that in ESPHome, we do not need to swap the rows and columns to use the Keypad component. Do remember to leave the has_diodes flag to false though…

A quick P-MOS MOSFET Driver Board

Introduction

A driver is needed to switch a P-Channel MOSFET because the gate of a P-Channel MOSFET needs to be driven to a voltage that is more negative than the source in order to turn it on. This can be difficult to do with low-voltage logic, such as 5V or 3.3V. A driver can provide the necessary voltage and current to turn on the P-Channel MOSFET, even when the logic voltage is low.

Here are some of the benefits of using a driver to switch a P-Channel MOSFET:

  • Increased switching speed: A driver can provide the necessary current to charge and discharge the gate capacitance of the P-Channel MOSFET quickly, which results in faster switching speeds.
  • Reduced power consumption: A driver can help to reduce power consumption by providing the necessary current in a short pulse, rather than a continuous stream of current.
  • Improved noise immunity: A driver can help to improve noise immunity by providing a clean and isolated signal to the gate of the P-Channel MOSFET.

If you are using a P-Channel MOSFET in your circuit, it is a good idea to use a driver to switch it. This will help to ensure that the MOSFET is switched quickly and efficiently and that it is protected from noise.

Here are some of the different types of drivers that can be used to switch P-Channel MOSFETs:

  • Logic level drivers: These drivers are designed to work with low-voltage logic, such as 5V or 3.3V. They typically have a high output voltage, which can be used to drive the gate of a P-Channel MOSFET.
  • High-side drivers: These drivers are designed to provide a high voltage to the gate of a P-Channel MOSFET. They are often used in circuits where the P-Channel MOSFET is used to switch a high-voltage rail.
  • Isolated drivers: These drivers provide an isolated signal to the gate of the P-Channel MOSFET. This is useful in circuits where it is important to prevent noise from entering the circuit.

Why did I decide to design this prototype?

The Story behind the prototype

This driver PCB is part of a solution for a project involving a set of 6v LED lights.
Each of the LED lights requires +/- 300mA @ 6v to operate efficiently.
I want to control these from a Microcontroller, either an ESP32 or even the XIAO RP2040 or similar. The current sink capability of an individual GPIO pin on these microcontrollers is limited, in the case of the RP2040 it is limited to 3mA per pin.

This prototype is an attempt to test out some basic driver ideas that might perform correctly for my particular needs, being

  • To stay within the limitations of the particular microcontroller GPIO current specifications
  • To be able to use any of the particular microcontrollers, without having to design a specific solution tailored to a specific device

The Schematic

I decided to keep things extremely simple to start with, using a very simple circuit consisting of only 4 components per channel. These are :
– an S9013 NPN BJT Transistor, capable of switching up to 500mA of current
– a SI2301 P-Channel Logic Level MOSFET, capable of switching up to 2.3A
– 10k pullup-resitor
– 1k resistor on the base of the BJT


The theory of operation is as follows:
The pullup resistor, R8, keeps the gate of the MOSFET (Q4) positive, thus ensuring that Q4 stays turned off when T4 is turned off. A HIGH signal at B4 will turn on T4, which will in turn pull the gate of Q4 to ground, turning Q4 on in the process.
That will in turn turn on the load ( connected at 4+ and 4- ).

It is important to note here that the value of R8, 10K at the moment, is not finalised, and may change to increase the performance of the circuit.

The PCB

The board was made to fit on a standard breadboard or be used as a standalone module, depending on the position of the male header pins.


Manufacturing


I choose PCBWay for my PCB manufacturing.
This month, PCBWay is also celebrating its 9th anniversary, and that means that there are quite a lot of very special offers available.


Why? What makes them different from the rest?
PCBWay‘s business goal is to be the most professional PCB manufacturer for prototyping and low-volume production work in the world. With more than a decade in the business, they are committed to meeting the needs of their customers from different industries in terms of quality, delivery, cost-effectiveness and any other demanding requests. As one of the most experienced PCB manufacturers and SMT Assemblers in China, they pride themselves to be our (the Makers) best business partners, as well as good friends in every aspect of our PCB manufacturing needs. They strive to make our R&D work easy and hassle-free.

How do they do that?

PCBWay is NOT a broker. That means that they do all manufacturing and assembly themselves, cutting out all the middlemen, and saving us money.

PCBWay’s online quoting system gives a very detailed and accurate picture of all costs upfront, including components and assembly costs. This saves a lot of time and hassle.

PCBWay gives you one-on-one customer support, that answers you in 5 minutes ( from the Website chat ), or by email within a few hours ( from your personal account manager). Issues are really resolved very quickly, not that there are many anyway, but, as we are all human, it is nice to know that when a gremlin rears its head, you have someone to talk to that will do his/her best to resolve your issue as soon as possible.

Find out more here

Assembly

The assembly of the PCB does not require any special tools, and can be done completely by hand if you choose. A very fine-tipped soldering iron should be perfect.

I chose to go the hot-air and solder-paste route, as it is faster, and looks neater in the end. The use of a stencil was not required.

The total assembly took about 5 minutes in total.

Testing

Testing the completed PCB module was performed with one of the LED light modules connected to each MOSFET Channel in turn, and then applying a voltage signal, or ground, to the control pin ( marked A to D on the picture above)

That was followed by connecting an Oscilloscope and Signal Generator to the control pins, as well as the outputs, and observing the waveforms during operation. A square wave output from the signal generator provided the switching signal.

Conclusion

The module works as expected, but the pullup resistor value needs to be fine-tuned to provide a better switching response on the MOSFET at high frequency.
I am however happy with the initial performance, and can now move on to improving the circuit to perform to my specifications.


A Reliable Matrix Keypad

What is a matrix keypad?

A matrix keypad is a type of keypad that uses a matrix of wires to connect the keys to the microcontroller. This allows for a smaller and more compact keypad than a traditional keypad, which uses a single row and column of wires for each key. Matrix keypads are also more reliable than conventional keypads, as they are less susceptible to damage from dirt and moisture.

How does a matrix keypad work?

A matrix keypad is made up of a number of rows and columns of keys. Each key is connected to two wires, one for the row and one for the column. When a key is pressed, it completes a circuit between the row and column wires. The microcontroller can then determine which key is pressed by checking which row and column wires are connected.

Why use a matrix keypad?

There are a number of reasons why you might want to use a matrix keypad in your project. Here are a few of the most common reasons:

  • Smaller size and footprint.
  • Reliability.
  • Cost savings.

What makes my design different from most others out there?

While the matrix keypad in its simplest form is constructed from only wires and switches, that simple approach can sometimes have some unwanted effects, especially when pressing multiple keys at the same time – a phenomenon called ghosting – where you get phantom keypresses. This is easily eliminated by adding a diode in series with each switch, usually on the row connection.

That single component fixes ghosting reliably but does not come without its own problems, the most important of these being that a keypad with diodes becomes “polarised” – current can only flow in a single direction through a switch. This can cause problems with some third-party libraries, as the designer of the keypad and the designer of the library very often has quite different ideas of what a row and a column mean in a keypad.

This is important, – here we go down the rabbit hole; in my understanding of the keypad scanning routine, a column runs from top to bottom, and a row from left to right. Keeping this in mind, the microcontroller will alternatively set each column HIGH, and configure each row as an input. When a key is pressed, current will flow from the specific column GPIO, through the switch, and into the Row GPIO, sending the input pin HIGH…

It is also possible to configure the columns as inputs, with internal pullups enabled, and have each Row pin as an output, configured to sink ( pull current to ground). This will cause the specific column to go low – thus identifying the pressed key…

These different ways of handling the problem of reading a key, and believe me, there are actually more variations, create a few unique problems. We may have to swap rows and columns as far as pin connections and firmware are concerned, as well as define a custom “keymap” to assign values to each key.

The Schematic

As we can see above, the schematic is very basic. 16 switches, 16 diodes and a single 8-way header pin. Pin 1 to 4 on the header is connected to Columns 1 to 4, and Pin 5 to 8 is connected to Rows 1 to 4.

The diodes prevent “ghosting currents from flowing into other keys in a row when multiple keys are pressed together. They also seem to help with other stray signals and interference.

The PCB

The PCB is a simple double-layer board. All components are mounted on the top layer.

To limit interference from stray signals, I have routed rows and columns on opposite sides of the PCB where possible.

Manufacturing

I choose PCBWay for my PCB manufacturing.
This month, PCBWay is also celebrating its 9th anniversary, and that means that there are quite a lot of very special offers available.


Why? What makes them different from the rest?
PCBWay‘s business goal is to be the most professional PCB manufacturer for prototyping and low-volume production work in the world. With more than a decade in the business, they are committed to meeting the needs of their customers from different industries in terms of quality, delivery, cost-effectiveness and any other demanding requests. As one of the most experienced PCB manufacturers and SMT Assemblers in China, they pride themselves to be our (the Makers) best business partners, as well as good friends in every aspect of our PCB manufacturing needs. They strive to make our R&D work easy and hassle-free.

How do they do that?

PCBWay is NOT a broker. That means that they do all manufacturing and assembly themselves, cutting out all the middlemen, and saving us money.

PCBWay’s online quoting system gives a very detailed and accurate picture of all costs upfront, including components and assembly costs. This saves a lot of time and hassle.

PCBWay gives you one-on-one customer support, that answers you in 5 minutes ( from the Website chat ), or by email within a few hours ( from your personal account manager). Issues are really resolved very quickly, not that there are many anyway, but, as we are all human, it is nice to know that when a gremlin rears its head, you have someone to talk to that will do his/her best to resolve your issue as soon as possible.

Find out more here

Assembly

This project does not require a lot of specialised equipment to assemble. The SMD diodes can easily be soldered by hand, the same with the switches and 8-way header. In my case, I chose to solder the header pins on the back of the PCB, that way, I can later use the keypad in a suitable enclosure without having wires in the way.

Testing and Coding

Testing a matric keypad can sometimes be a challenge. In my case, a multimeter with clip leads, set to diode mode, with the leads connected to each column and row in turn, while minding the polarity, and pressing each key in that row in turn, verified continuity.

With that done, it was time to put my trusted Cytron Maker Uno to work, as this Arduino Clone has the added benefit of having LEDs on each of the GPIO lines, thus making it very easy to see what is happening.

I made use of a Keypad library in the Arduino IDE, mainly to cut down on the amount of coding, but also because it is easier to use a working piece of code, and then adapt that to my keypad.

Detailed Code examples for ESPHome are available on Patreon

/* @file CustomKeypad.pde
|| @version 1.0
|| @author Alexander Brevig
|| @contact alexanderbrevig@gmail.com
||
|| @description
|| | Demonstrates changing the keypad size and key values.
|| #

Edited by MakerIoT2020, with minor changes to make it function correctly with my custom keypad.
I have also added a simple LED blinking routine to show that the Arduino is “alive” and that the Keypad code seems to be NON-blocking – which is quite important to me.

*/
#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the symbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
{‘1′,’4′,’7′,’*’},
{‘2′,’5′,’8′,’0’},
{‘3′,’6′,’9′,’#’},
{‘A’,’B’,’C’,’D’}
};
byte rowPins[ROWS] = {2,3,4,5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6,7,8,9}; //connect to the column pinouts of the keypad
/*
* Due to libraries being written by different people, and our definitions about
* what a row and a column are, is different, note that the rows in the code
* is actually the columns on my PCB. This becomes true, due to the fact that my
* PCB has Diodes on each switch, and that thus makes current flow in only one
* direction///
*
* it also has the “side effect” that keys are layout in a strange “mirrored” and
* rotated way in the firmware.
* it does however NOT affect the correct operation of the Keypad Module at all
*
*/

const int LEDPin = LED_BUILTIN;
int ledState = LOW;
unsigned long prevmillis = 0;
const long interval = 1000;

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

void setup(){
Serial.begin(115200);
pinMode(LEDPin,OUTPUT);
}

void loop(){
unsigned long currentMillis = millis();
if (currentMillis – prevmillis >= interval) {
prevmillis = currentMillis;
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(LEDPin,ledState);
}
char customKey = customKeypad.getKey();

if (customKey){
Serial.println(customKey);
}
}

This code works very well and allowed me to verify the correct operation of the keypad.

In conclusion

Making my own Keypad Module is a project that is long overdue. I have purchased a few online over the years, and as they were mostly of the membrane type, they did not last very long – it must be something to do with the ultra-cheap flexible PCB ribbon connector, since a quality membrane keypad can be quite expensive, and usually lasts quite a long time.

Having my own module available to experiment with will allow me to do some long-delayed improvements to many of my IoT modules. That code, mostly YAML for ESPHome, will be made available on Patreon.

8Ch NMOS Breakout Module

As a companion module to my recently published 8Ch PMOD breakout board,
I decided to do a similar PCB, but with NMOS devices instead. This opens up more possibilities for proper testing and prototyping, as PMOS and NMOS devices has different use applications, and most importantly, can sometimes even be combined for a particular purpose, like an H-Bridge motor driver, for example.

8Ch NMOS Breakout

What is on the PCB?

As NMOS devices function quite differently from their PMOS counterparts, it did not make sense to reuse the PMOS board, and just change the devices… although some people may be tempted to think you could…

The N Channel Mosfet basically “works in mirrored mode” from a P Channel one, and is used to do so-called ” LOW Side switching” which means that your load connects to the positive power rail, and then to the DRAIN pin of the MOSFET, with the source being connected to ground… ( It can sometimes also be used the other way around… but lets not go there now….

The current prototype PCB contains 8 BSS138 NMOS Mosfets, in my case, with is capable of about 800mA of current… All source pins are internally connected to ground. This forces you to use this module as a low side switch…

Two 10-way 2.54mm headers are provided, with a ground pin on Pin 1 and 10 of each of these.

The Drain pins of each NMOS device is available on the top header, labeled D1 through D8, and the Gate pins of each respective NMOS device is available on the bottom header, labelled G1 through G8.

Each gate has a pull-down resistor to ground, to keep it from flapping around, as well as a gate resistor. In my case, I selected to use a 10k pulldown, and a 1k gate resistor, as that is sufficient for my general needs…

Each NMOS device also has a LED signal indicator, to assist in visual confirmation of a specific channel’s state.

PCB Top Side

The Schematic

Schematic

Using the breakout

The module is very easy to use, and as briefly mentioned above, you are only required to connect one side of your load to the positive supply rail, and the other side to the drain pin of your choice.

Connect the ground pins of the module to your ground rail.

The Gate pin, with a corresponding number to the drain you have selected, can now be connected to your GPIO of choice on a microcontroller.

Drive the pin High to switch on the load, drive it log to switch off. Easy.

Please note: While the NMOS devices used on the board can handle quite a lot of current, (800mA in the case of the BSS138), it is not recommended to try and pull too much current through a single channel. The PCB traces can safely handle about a maximum of 300 to 400mA per channel.

PCB Bottom

Manufacturing

The PCB for this project has been manufactured at PCBWay.
Please consider supporting them if you would like your own copy of this PCB, or if you have any PCB of your own that you need to have manufactured.

PCBWay

Example code for using the breakout (Arduino)

// Example code for 8Ch NMOS breakout
int Gate1 9;
int Gate2 10;

void setup() {
  // drive the two gate pins low to ensure NMOS devices
  // are in a positively known state at startup
  digitalWrite(Gate1,LOW);
  digitalWrite(Gate2,LOW);
  // Set gpio to output mode
  pinMode(Gate1,OUTPUT);
  pinMode(Gate2,OUTPUT);

}

void loop() {
  // Toggle the two channels in an alternating pattern
  digitalWrite(Gate1,!digitalRead(Gate1));
  digitalWrite(Gate2,!digitalRead(Gate1));
  delay(1000);  

}

8-Ch P-Mos Breakout

While prototyping our projects, we Makers often need to interface devices with a higher current draw, like motors, or RGB lights, to our microcontrollers. These typically are unsuitable for connecting directly to an Arduino, ESP32 or Raspberry Pi’s GPIO pins. This is usually the time when we start grabbing transistors or MOSFETs.

While I normally keep a few leaded transistors and MOSFETs in the lab, These are not always convenient to use, as they may be in big packages or have the wrong specifications for the task that we are trying to perform.

SMD versions are more common in my lab, but they come with the problem of being small, and also completely unfriendly to the breadboard environment.


I have thus been playing with an idea to make a series of dedicated breakout boards for just this purpose. Having an easy way to test a specific MOSFET for a design, and having more than one of them handy, without all the wiring issues, and using the bare minimum of those DuPont wires!

I came up with the following prototype, which, while not completely optimised yet, already makes things easier. The breakout board provides 8 P-Channel Mosfets, with a single source connection, and individually broken-out Drain and Gate pins.

LED indicators on each channel provide a visual indication of the status of each P-Mos device, and the breakout can also be mounted directly into an enclosure if needed.

What is on the PCB?

Each channel comprises a P-Channel Mosfet, in this case, a SI2301, which has a suitably low gate voltage, a pullup resistor on the gate, to keep it from floating, a status-indicating LED and a current-limiting resistor for the LED.

No gate resistor was added, as this would change depending on the actual MOSFET, as well as the microcontroller that you use. The Gate pullup resistor can also be left unpopulated, in case you need to do something specific there.

Two rows of 10-way, 2.54 header pins are at the top and bottom of the PCB, to make using the breakout on a breadboard possible.

The Pinouts are as follows

H2 – Top V+ D1 D2 D3 D4 D5 D6 D7 D8 GND
with Dx corresponding to the Drain pin of each MOSFET. All the Source pins are internally connected together, as I assumed that I will use the same source voltage on each channel anyway.

H1 – Bottom V+ G1 G2 G3 G4 G5 G6 G7 G8 GND
with Gx corresponding to the gate pin of each MOSFET.

V+ and GND for each header is internally connected, to make it possible to supply V+ and Gnd on any of the two headers.

PCB Top Layer

The Schematic

Schematic

Using the Breakout

Using the breakout is straightforward. Connect a source voltage to either of the V+ pins and Ground to either of the GND pins. ( the ground is used internally for the status LEDs)

Connect your load, with the positive to a drain pin, let us say D1, and the load ground to your breadboard, or power supply ground. Connect the corresponding gate pin, in our case G1, to the microcontroller pin of your choice, through a suitable gate resistor, and pull it high at setup, to ensure that the MOSFET stays off. Pull low to activate as needed.

Please note that you should not try to switch excessively large currents through a single MOSFET Channel, as the PCB traces can realistically only handle approximately 300 to 400mA per channel.

Note 2: If you are driving an inductive load, it is considered good practice to add a flywheel diode on the load as well. This will protect the MOSFET from back EMF when the MOSFET is switched off.

PCB Back

Manufacturing

The PCB for this project has been manufactured at PCBWay.
Please consider supporting them if you would like your own copy of this PCB, or if you have any PCB of your own that you need to have manufactured.

PCBWay

Example code for using the breakout (Arduino)

// Declare Gate driving GPIO pins
int gate1 = 10; 
int gate2 = 11;


void setup() {
// Set the GPIO pins as outputs and drive them HIGH
// This keeps the channels switched "OFF"
  digitalWrite(gate1,HIGH);
  digitalWrite(gate2,HIGH);
  pinMode(gate1,OUTPUT);
  pinMode(gate2,OUTPUT);

// Writing to the GPIO's before setting their pin Mode,ensures that the
// GPIO's are in fact initiated in a know correct state.

  Serial.begin(115200);

}

void loop() {
// In the loop, we just toggle the GPIOs, thus
// alternatively switching the channels on or off
  digitalWrite(gate1,!digitalRead(gate1));
  digitalWrite(gate2,!digitalRead(gate1));
  delay(1000);
  }