Skip to content

Code

Features

Relying upon the final control board design used in the project, I developed code in micropython for the project.

As seen in the electronics design, the software has the following components:

  • Response to three buttons
    • A button to increase the number of players
    • A button to increase the number of cards
    • A button to initiate dealing
  • An I2C connection and driver for the 2x16 LCD display
  • Instructions for the two stepper motors
    • One motor to move to each player’s position
    • One motor to distribute cards

Motor control

This functionality relies upon a library with a class for the stepper motors

# Based on <https://github.com/jeffmer/micropython-upybbot/blob/master/nemastepper.py>
#

from machine import Pin
import time

# Class for a stepper motor
class Stepper:
    # Initate the motor, setting current position to zero
    # Delay is used between steps. 
    def __init__(self, dir_pin, step_pin, enable_pin):
        self.step_pin = Pin(step_pin, Pin.OUT)
        self.dir_pin = Pin(dir_pin, Pin.OUT)
        self.enable_pin = Pin(enable_pin, Pin.OUT)
        self.enable_pin.high()
        self.dir = 0
        self.position = 0
        self.MIN_DELAY = 0.003
        self.STEPS_PER_REV = 200

    # Move the motor a specified number of steps
    # Positive or negative determines the direction
    def move(self, steps, delay=0.003):
        if delay < self.MIN_DELAY:
            delay = self.MIN_DELAY
        if steps == 0:
            return
        elif steps > 0:
            self.dir = 1
            self.dir_pin.high()
        elif steps < 0:
            self.dir = -1
            self.dir_pin.low()
        self.set_on()

        # Used the delay between steps
        # Shorter delay means faster movement
        # The motor doesn't move well with delay
        # less than 0.001
        for _ in range(abs(steps)):
            self.step_pin.high()
            time.sleep(delay)
            self.step_pin.low()
            time.sleep(delay)
            self.position += self.dir

        self.position = self.position % self.STEPS_PER_REV
        self.set_off()

    # This moves the motor to a specified position based on the number of steps per revolution
    def goto_position(self, pos, delay=0.003, full_rotation=False):
        # Full rotation might be needed later. Placeholder variable
        pos = pos % self.STEPS_PER_REV
        if delay < self.MIN_DELAY:
            delay = self.MIN_DELAY
        if pos == self.position:
            return
        dist = pos - self.position
        self.move(dist)

    # Turns the motor on
    def set_on(self):
        self.enable_pin.low()

    # Turns the motor off
    def set_off(self):
        self.enable_pin.high()

    # Return current position of motor
    def get_position(self):
        return self.position

    # Return the maximum position number
    def get_max_position(self):
        return self.STEPS_PER_REV

The stepper motor control library.

While this library was based on work on github https://github.com/jeffmer/micropython-upybbot/blob/master/nemastepper.py, I followed the logic there, and created the library in the code.

Button control

For the button, I needed a class to respond to the button. This needs to include a ‘debounce’ time, which means that it would only respond once if the button detects multiple changes in state in a short period of time.

For this I utilized code for a MicroPython Button.

# From https://github.com/ubidefeo/MicroPython-Button

from machine import Pin
from time import ticks_ms

class Button(object):
  rest_state = False
  RELEASED = 'released'
  PRESSED = 'pressed'
  DEBOUNCE_TIME = 50

  def __init__(self, pin, rest_state = False, callback = None, internal_pullup = False, internal_pulldown = False, debounce_time = DEBOUNCE_TIME):
    self.pin_number = pin
    self.rest_state = rest_state
    self.previous_state = rest_state
    self.current_state = rest_state
    self.previous_debounced_state = rest_state
    self.current_debounced_state = rest_state
    self.last_check_tick = ticks_ms()
    self.debounce_time = debounce_time or Button.DEBOUNCE_TIME
    if internal_pulldown:
      self.internal_pull = Pin.PULL_DOWN
      self.rest_state = False
    elif internal_pullup:
      self.internal_pull = Pin.PULL_UP
      self.rest_state = True
    else:
      self.internal_pull = None
    self.pin = Pin(pin, mode = Pin.IN, pull = self.internal_pull)
    self.callback = callback
    self.active = False

  def debounce(self):
    ms_now = ticks_ms()
    self.current_state = self.pin.value()
    state_changed = self.current_state != self.previous_state
    if state_changed:
      self.last_check_tick = ms_now
    state_stable = (ms_now - self.last_check_tick) > self.debounce_time
    if state_stable and not state_changed:
      self.last_check_tick = ms_now
      self.current_debounced_state = self.current_state
    self.previous_state = self.current_state

  def check_debounce_state(self):
    if self.current_debounced_state != self.previous_debounced_state:
      if self.current_debounced_state != self.rest_state:
        self.active = True
        if self.callback != None:
          self.callback(self.pin_number, Button.PRESSED)
      else:
        self.active = False
        if self.callback != None:
          self.callback(self.pin_number, Button.RELEASED)
    self.previous_debounced_state = self.current_debounced_state

  def update(self):
    self.debounce()
    self.check_debounce_state()

I was able to use this library as-is.

The micropython button library

LCD interface

My project includes an Arduino 2x16 LCD display, with an I2C backpack. This needs library functions to control the display in Micropython.

I am utilizing functions as-is for Micropython LCD.

This includes an API for the LCD, as well as an I2C interface.

API for the LCD:

"""Provides an API for talking to HD44780 compatible character LCDs."""

import time


class LcdApi:
    """Implements the API for talking with HD44780 compatible character LCDs.
    This class only knows what commands to send to the LCD, and not how to get
    them to the LCD.

    It is expected that a derived class will implement the hal_xxx functions.
    """

    # The following constant names were lifted from the avrlib lcd.h
    # header file, however, I changed the definitions from bit numbers
    # to bit masks.
    #
    # HD44780 LCD controller command set

    LCD_CLR = 0x01  # DB0: clear display
    LCD_HOME = 0x02  # DB1: return to home position

    LCD_ENTRY_MODE = 0x04  # DB2: set entry mode
    LCD_ENTRY_INC = 0x02  # --DB1: increment
    LCD_ENTRY_SHIFT = 0x01  # --DB0: shift

    LCD_ON_CTRL = 0x08  # DB3: turn lcd/cursor on
    LCD_ON_DISPLAY = 0x04  # --DB2: turn display on
    LCD_ON_CURSOR = 0x02  # --DB1: turn cursor on
    LCD_ON_BLINK = 0x01  # --DB0: blinking cursor

    LCD_MOVE = 0x10  # DB4: move cursor/display
    LCD_MOVE_DISP = 0x08  # --DB3: move display (0-> move cursor)
    LCD_MOVE_RIGHT = 0x04  # --DB2: move right (0-> left)

    LCD_FUNCTION = 0x20  # DB5: function set
    LCD_FUNCTION_8BIT = 0x10  # --DB4: set 8BIT mode (0->4BIT mode)
    LCD_FUNCTION_2LINES = 0x08  # --DB3: two lines (0->one line)
    LCD_FUNCTION_10DOTS = 0x04  # --DB2: 5x10 font (0->5x7 font)
    LCD_FUNCTION_RESET = 0x30  # See "Initializing by Instruction" section

    LCD_CGRAM = 0x40  # DB6: set CG RAM address
    LCD_DDRAM = 0x80  # DB7: set DD RAM address

    LCD_RS_CMD = 0
    LCD_RS_DATA = 1

    LCD_RW_WRITE = 0
    LCD_RW_READ = 1

    def __init__(self, num_lines, num_columns):
        self.num_lines = num_lines
        if self.num_lines > 4:
            self.num_lines = 4
        self.num_columns = num_columns
        if self.num_columns > 40:
            self.num_columns = 40
        self.cursor_x = 0
        self.cursor_y = 0
        self.implied_newline = False
        self.backlight = True
        self.display_off()
        self.backlight_on()
        self.clear()
        self.hal_write_command(self.LCD_ENTRY_MODE | self.LCD_ENTRY_INC)
        self.hide_cursor()
        self.display_on()

    def clear(self):
        """Clears the LCD display and moves the cursor to the top left
        corner.
        """
        self.hal_write_command(self.LCD_CLR)
        self.hal_write_command(self.LCD_HOME)
        self.cursor_x = 0
        self.cursor_y = 0

    def show_cursor(self):
        """Causes the cursor to be made visible."""
        self.hal_write_command(
            self.LCD_ON_CTRL | self.LCD_ON_DISPLAY | self.LCD_ON_CURSOR
        )

    def hide_cursor(self):
        """Causes the cursor to be hidden."""
        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY)

    def blink_cursor_on(self):
        """Turns on the cursor, and makes it blink."""
        self.hal_write_command(
            self.LCD_ON_CTRL
            | self.LCD_ON_DISPLAY
            | self.LCD_ON_CURSOR
            | self.LCD_ON_BLINK
        )

    def blink_cursor_off(self):
        """Turns on the cursor, and makes it no blink (i.e. be solid)."""
        self.hal_write_command(
            self.LCD_ON_CTRL | self.LCD_ON_DISPLAY | self.LCD_ON_CURSOR
        )

    def display_on(self):
        """Turns on (i.e. unblanks) the LCD."""
        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY)

    def display_off(self):
        """Turns off (i.e. blanks) the LCD."""
        self.hal_write_command(self.LCD_ON_CTRL)

    def backlight_on(self):
        """Turns the backlight on.

        This isn't really an LCD command, but some modules have backlight
        controls, so this allows the hal to pass through the command.
        """
        self.backlight = True
        self.hal_backlight_on()

    def backlight_off(self):
        """Turns the backlight off.

        This isn't really an LCD command, but some modules have backlight
        controls, so this allows the hal to pass through the command.
        """
        self.backlight = False
        self.hal_backlight_off()

    def move_to(self, cursor_x, cursor_y):
        """Moves the cursor position to the indicated position. The cursor
        position is zero based (i.e. cursor_x == 0 indicates first column).
        """
        self.cursor_x = cursor_x
        self.cursor_y = cursor_y
        addr = cursor_x & 0x3F
        if cursor_y & 1:
            addr += 0x40  # Lines 1 & 3 add 0x40
        if cursor_y & 2:  # Lines 2 & 3 add number of columns
            addr += self.num_columns
        self.hal_write_command(self.LCD_DDRAM | addr)

    def putchar(self, char):
        """Writes the indicated character to the LCD at the current cursor
        position, and advances the cursor by one position.
        """
        if char == "\n":
            if self.implied_newline:
                # self.implied_newline means we advanced due to a wraparound,
                # so if we get a newline right after that we ignore it.
                pass
            else:
                self.cursor_x = self.num_columns
        else:
            self.hal_write_data(ord(char))
            self.cursor_x += 1
        if self.cursor_x >= self.num_columns:
            self.cursor_x = 0
            self.cursor_y += 1
            self.implied_newline = char != "\n"
        if self.cursor_y >= self.num_lines:
            self.cursor_y = 0
        self.move_to(self.cursor_x, self.cursor_y)

    def putstr(self, string):
        """Write the indicated string to the LCD at the current cursor
        position and advances the cursor position appropriately.
        """
        for char in string:
            self.putchar(char)

    def custom_char(self, location, charmap):
        """Write a character to one of the 8 CGRAM locations, available
        as chr(0) through chr(7).
        """
        location &= 0x7
        self.hal_write_command(self.LCD_CGRAM | (location << 3))
        self.hal_sleep_us(40)
        for i in range(8):
            self.hal_write_data(charmap[i])
            self.hal_sleep_us(40)
        self.move_to(self.cursor_x, self.cursor_y)

    def hal_backlight_on(self):
        """Allows the hal layer to turn the backlight on.

        If desired, a derived HAL class will implement this function.
        """
        pass

    def hal_backlight_off(self):
        """Allows the hal layer to turn the backlight off.

        If desired, a derived HAL class will implement this function.
        """
        pass

    def hal_write_command(self, cmd):
        """Write a command to the LCD.

        It is expected that a derived HAL class will implement this
        function.
        """
        raise NotImplementedError

    def hal_write_data(self, data):
        """Write data to the LCD.

        It is expected that a derived HAL class will implement this
        function.
        """
        raise NotImplementedError

    def hal_sleep_us(self, usecs):
        """Sleep for some time (given in microseconds)."""
        time.sleep_us(usecs)

I2C interface for the LCD:

import utime
import gc

from lcd_api import LcdApi
from machine import I2C

# PCF8574 pin definitions
MASK_RS = 0x01  # P0
MASK_RW = 0x02  # P1
MASK_E = 0x04  # P2

SHIFT_BACKLIGHT = 3  # P3
SHIFT_DATA = 4  # P4-P7


class I2cLcd(LcdApi):
    # Implements a HD44780 character LCD connected via PCF8574 on I2C

    def __init__(self, i2c, i2c_addr, num_lines, num_columns):
        self.i2c = i2c
        self.i2c_addr = i2c_addr
        self.i2c.writeto(self.i2c_addr, bytes([0]))
        utime.sleep_ms(20)  # Allow LCD time to powerup
        # Send reset 3 times
        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET)
        utime.sleep_ms(5)  # Need to delay at least 4.1 msec
        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET)
        utime.sleep_ms(1)
        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET)
        utime.sleep_ms(1)
        # Put LCD into 4-bit mode
        self.hal_write_init_nibble(self.LCD_FUNCTION)
        utime.sleep_ms(1)
        LcdApi.__init__(self, num_lines, num_columns)
        cmd = self.LCD_FUNCTION
        if num_lines > 1:
            cmd |= self.LCD_FUNCTION_2LINES
        self.hal_write_command(cmd)
        gc.collect()

    def hal_write_init_nibble(self, nibble):
        # Writes an initialization nibble to the LCD.
        # This particular function is only used during initialization.
        byte = ((nibble >> 4) & 0x0F) << SHIFT_DATA
        self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
        self.i2c.writeto(self.i2c_addr, bytes([byte]))
        gc.collect()

    def hal_backlight_on(self):
        # Allows the hal layer to turn the backlight on
        self.i2c.writeto(self.i2c_addr, bytes([1 << SHIFT_BACKLIGHT]))
        gc.collect()

    def hal_backlight_off(self):
        # Allows the hal layer to turn the backlight off
        self.i2c.writeto(self.i2c_addr, bytes([0]))
        gc.collect()

    def hal_write_command(self, cmd):
        # Write a command to the LCD. Data is latched on the falling edge of E.
        byte = (self.backlight << SHIFT_BACKLIGHT) | (((cmd >> 4) & 0x0F) << SHIFT_DATA)
        self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
        self.i2c.writeto(self.i2c_addr, bytes([byte]))
        byte = (self.backlight << SHIFT_BACKLIGHT) | ((cmd & 0x0F) << SHIFT_DATA)
        self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
        self.i2c.writeto(self.i2c_addr, bytes([byte]))
        if cmd <= 3:
            # The home and clear commands require a worst case delay of 4.1 msec
            utime.sleep_ms(5)
        gc.collect()

    def hal_write_data(self, data):
        # Write data to the LCD. Data is latched on the falling edge of E.
        byte = (
            MASK_RS
            | (self.backlight << SHIFT_BACKLIGHT)
            | (((data >> 4) & 0x0F) << SHIFT_DATA)
        )
        self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
        self.i2c.writeto(self.i2c_addr, bytes([byte]))
        byte = (
            MASK_RS
            | (self.backlight << SHIFT_BACKLIGHT)
            | ((data & 0x0F) << SHIFT_DATA)
        )
        self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
        self.i2c.writeto(self.i2c_addr, bytes([byte]))
        gc.collect()

The API and I2C python library code.

Control board

Putting this together, the primary code is as below. This program is titled ‘main.py’. When this program (under this specific name), and each of the libraries above, are saved to the RP-2040, are saved to the RP2040 the program will run automatically.

The following code will respond to each of the three buttons, give status information on the LCD, and also control the motors after being told by the start button.

# Software to control card dealer final project.
# Key control elements needed:
#   - Motor control to rotate card dealer
#   - Motor control to dispense cards
#   - Button based counter for # players
#   - Button based counter for # cards
#   - Button to start dealing
#   - I2C output for LCD/LED status screen
# This is being put together in steps
#
# First step is to get motor control working
# v0.1 Controlling motors
#   Started from code from ,https://how2electronics.com/control-stepper-motor-with-a4988-raspberry-pi-pico/>
#   Added a 2nd motor
#   Somehow I am getting 800 steps per revolution,
#   though both motors rotate forwards and backward
# 
# v0.2 Move motor control to module
#   Put stepper functions in module
#   Basic player and card movement logic
#   Essentially no remnants of starting motor code

from nemastepper import Stepper
from button import Button
from i2c_lcd import I2cLcd
from machine import SoftI2C
import time

sdaPIN = 6
sclPIN = 7

# Setup the LDC
def setup_lcd():
    global lcd
    i2c = SoftI2C(sda=sdaPIN, scl=sclPIN, freq=10000)
    devices = i2c.scan()
    lcd = I2cLcd(i2c, devices[0], 2, 16)
    print(devices[0])

use_lcd = True

if use_lcd:
    setup_lcd()

card_motor = Stepper(28,29,0)
player_motor = Stepper(26,27,0)

# Define the positions for each player.
# Assume they are arranged equidistant 
def player_positions(players, max_position=200):
    separation = (max_position // players)
    print(max_position,players,separation)
    positions = list(range(0,max_position, separation))[0:players]
    return(positions)

first_card = True
start = False
cards = 0
players = 0

idle_message= "Albert's Dealer\nFabAcademy 2025\n"

if use_lcd:
    lcd.putstr(idle_message)

# Action for the start button
def start_button_action(pin, event):
    global start
    if event == Button.PRESSED:
        if players > 0 and cards > 0:
            start = True
            print(f'Ready to START!')
        else:
            print(f'Invalid Start\n')

# Action for the card button
# Increase the number of cards, and update
# the output display

def card_button_action(pin, event):
    global cards
    if event == Button.PRESSED:
        cards += 1
        print(f'Cards: {cards}\nPlayers: {players}\n')
        if use_lcd:
            lcd.clear()
            lcd.move_to(0,0)
            lcd.putstr(f'Cards: {cards}\n')
            lcd.move_to(0,1)
            lcd.putstr(f'Players: {players}\n')

# Action after hitting the player
# button. Increase the number of player
# and update the display

def player_button_action(pin, event):
    global players
    if event == Button.PRESSED:
        players += 1
        print(f'Cards: {cards}\nPlayers: {players}\n')
        if use_lcd:
            lcd.clear()
            lcd.move_to(0,0)
            lcd.putstr(f'Cards: {cards}\n')
            lcd.move_to(0,1)
            lcd.putstr(f'Players: {players}\n')

# Set up buttons
start_button = Button(1, callback = start_button_action, internal_pullup = True)
players_button = Button(2, callback = player_button_action, internal_pullup = True)
cards_button = Button(4, callback = card_button_action, internal_pullup = True)

# Primary code
while(True):
    start_button.update()
    players_button.update()
    cards_button.update()
    if(players>6):
        print("Max number of players is 6")
        if use_lcd:
            lcd.clear()
            lcd.putstr("Max players is 6")
        print("Choose number of players again\n")
        players = 0
    if(cards>52 or cards*players>52):
        print("Too many cards")
        if use_lcd:
            lcd.clear()
            lcd.putstr("Max hand 13, max cards 52")
        print("Choose number of cards again\n")
        cards = 0
    if(start):
        print("DEALING\n")
        if use_lcd:
            lcd.clear()
            lcd.putstr("DEALING")
        positions = player_positions(players,100)
        left = players*cards
        # First card needs a little extra
        # roll to come out
        card_motor.move(-100,0.001)
        for c in range(cards):
            for p, pos in enumerate(positions):
                left -= 1
                if use_lcd:
                    lcd.clear()
                    lcd.move_to(0,0)
                    lcd.putstr(f"Dealing {left} left")
                    lcd.move_to(0,1)
                    lcd.putstr(f"P# {p+1}, C# {c+1}")
                print(f'Card: {c+1}\nPlayer:{p+1}\n')
                player_motor.goto_position(pos,0.02)
                if first_card:
                    card_motor.move(-200,0.001)
                    first_card = False
                else:
                    card_motor.move(-200,0.001)
        print("CARDS DEALT")
        if use_lcd:
            lcd.clear()
            lcd.putstr(idle_message)
            lcd.move_to(0,1)
        player_motor.goto_position(positions[0],0.02)
        players = 0
        cards = 0
        start = False

This is the main control code used for the project.

main.py

QC power

Details on constructing an programming the QC hack power board are on our group site. I have include the schematics for my redesign, the code files are available here.