Thursday, 11 June 2026

2026- Car 4 New controller using PICO



Preparing the computer:

To enable the port for the user to be able to connect through it to the PICO.

sudo usermod -a -G dialout peterm

Next to Download the files for MQTT communication as Per:

https://randomnerdtutorials.com/raspberry-pi-pico-w-mqtt-micropython

Download and configure the files for Network configuration

https://randomnerdtutorials.com/raspberry-pi-pico-w-wi-fi-micropython/

Use the bit about Connecting your Pico board to your Wi-Fi network in writing the software.

Reading inputs:

https://randomnerdtutorials.com/raspberry-pi-pico-outputs-inputs-micropython/

pins 1,2,4,5,9 for inputs pin 1 is GPIO 0, etc.‘button = Pin(21, Pin.IN, Pin.PULL_UP)’ has pull up resistor.

I2C LCD display

https://randomnerdtutorials.com/raspberry-pi-pico-i2c-lcd-display-micropython/

pins 6 SDA GPIO 4

pin 7 SCL GPIO 5

Pin 8 gnd

Ran the I2C test program from randomnerd tutorials start and got this:

I2C SCANNER

i2c devices found: 1

I2C hexadecimal address: 0x27

MicroPython v1.28.0 on 2026-04-06; Raspberry Pi Pico 2 W with RP2350

Type "help()" for more information.

Hint: Change the file name to main.py and reboot the PICO

The Hello World program worked too, though only on two lines.

I will put that into my 1C version and test it again.

Have tested moving text program too.
---------------------
Building the System
---------------------

There are four parts.

1. Driving the display -- Done

2. Input of keypresses via GPIO

3. Wifi link to car

4. MQTT communications.

In this order I think.
So next step is to wire up the switches. All must have pullups so key goes to ground.
Built switches into controller, and it all worked. That’s part B done

Part C: From Randomnerd tutorials set up WiFi.

It connected but assigned a random IP address rather than the one set in the program.

Have set specified IP address. It works.

Now to figure out how to send MQTT data – Part D

Have added appropriate lines from MQTT sample I think.

Error as it cannot find ‘client’

It now seems that when it sends it wants 3 parts to send and I only have two.

When I broke the data into two parts it still didn’t work.

I am looking at what other references suggest for MQTT:

https://www.hivemq.com/blog/iot-reading-sensor-data-raspberry-pi-pico-w-micropython-mqtt-node-red/

2026-6-3

According to Subscriber I am subscribing to topic “rc-car”

In Publisher I have set topic to ‘Move’ or ‘turn’ and I get the error:

"Connection successful!

IP address: 192.168.4.4

Error connecting to MQTT: [Errno 104] ECONNRESET

Traceback (most recent call last):

File "<stdin>", line 132, in <module>

File "<stdin>", line 112, in connect_mqtt

File "umqtt/simple.py", line 73, in connect

File "ssl.py", line 1, in wrap_socket

File "ssl.py", line 1, in wrap_socket

OSError: [Errno 104] ECONNRESET"

I don’t know whether this is an error sending, with the Broker, or with the Subscriber.

Try correcting the Topic by creating in the publisher a variable called p_topic
Same error.

The thing that calls line 112 is:

client = MQTTClient(client_id=MQTT_CLIENT_ID,
server=MQTT_SERVER,
port=MQTT_PORT,
# user=MQTT_USER,
# password=MQTT_PASSWORD,
keepalive=MQTT_KEEPALIVE,
ssl=MQTT_SSL,
ssl_params=MQTT_SSL_PARAMS
)

Which breaks down to:

client = MQTTClient(client_id= rc-car-11,
server=192.168.4.1,
port=1883,
# user=MQTT_USER, [commented out]
# password=MQTT_PASSWORD, [commented out]
keepalive=7200,
ssl= True,
ssl_params='server_hostname': 'raspberrypi'
)

As per suggestion, used the supplied simple.py file and still had the same error. I notice that the config
file contains a few items and they are duplicated throughout the program, so I tried changing the
program to just call them there, and that didn’t work: Invalid sysntax on one statement, so now I am
looking into the use of config files in micropython:

https://forums.raspberrypi.com/viewtopic.php?t=340983

https://stackoverflow.com/questions/5055042/whats-the-best-practice-using-a-settings

config-file-in-python – This refers to YAML and JSON and complicated data storage.

https://www.youtube.com/watch?v=g599FlcKgxA

2026-6-6 Lets learn about Micropython
https://www.mclibre.org/descargar/docs/revistas/hackspace-books/hackspace-get-started

-with-micropython-on-pico-01-202101.pdf Pretty good, if simple, for hardware connectivity and

data file stuff. Downloaded.

https://docs.micropython.org/en/latest/rp2/quickref.html

https://www.raspberrypi.com/documentation/microcontrollers/micropython.html

Look at Wiki and Forums later. From Wiki to ‘discussions’

Https://docs.micropython.org/en/latest/library/rp2.html - Not useful for current problem

AND ABOUT CONFIG FILES:

https://stackoverflow.com/questions/5055042/whats-the-best-practice-using-a-

settingsconfig-file-in-python too complex – discusses YAML and other complicated means.

https://docs.python.org/3/library/configparser.html configparser part of a program.

Took wifi stuff out of config file and put in program. It now connects, but doesn’t like

name ‘Topic’ – not defined.

Used p_topic – it worked for forward.

Check out all other motions.

Used for all. All work well, bit slow to respond. Need better off switch.

Fixed intermittent display, rotated socket on pin to Vsys on board for a better connection.

Have added state flag for turns so that turn button alternates on and off.

---------------------------------------------------------

#
#  RC Controller using Raspberry Pi Pico and MQTT   --- VERSION C

# this is a conversion from the Arduino software for the Wemos Microcontroller to Micropython for the R-Pi PICO

# PArt A -This is a test of the Display using I2C
# Part B - added input to GPIO pins, displayed
# Part C - Adding Wifi connection as per https://randomnerdtutorials.com/raspberry-pi-pico-w-wi-fi-micropython/

# 2026-5-10  working from  randomnerdtutorials.com/raspberry-pi-pico-i2c-lcd-display-micropython
#  For I2C display, use pin 6 for SDA, pin 7 for SCL, and pin 8 for GND now need 5v.

# ------------------------------

vers = "vn:1.C"

#Setting up I2C for LCD and MQTT
from machine import SoftI2C, Pin
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd
from umqtt.simple import MQTTClient
import config
import network
from time import sleep


# set GPIO pins
button0 = Pin(0, Pin.IN, Pin.PULL_UP)   # forward
button1 = Pin(1, Pin.IN, Pin.PULL_UP)   # back
button2 = Pin(2, Pin.IN, Pin.PULL_UP)   # left
button3 = Pin(3, Pin.IN, Pin.PULL_UP)   # right
button4 = Pin(6, Pin.IN, Pin.PULL_UP)   # stop

# part D set up MQTT parameters
# in config.py
p_topic = "rc-car"

# Part C Wifi from  https://randomnerdtutorials.com/raspberry-pi-pico-w-wi-fi-micropython/
wifi_ssid = "rc-car"
wifi_password = 'Ashmeads'

# Static IP configuration
static_ip = '192.168.4.4'  # Replace with your desired static IP
subnet_mask = '255.255.255.0'
gateway_ip = '192.168.4.254'
dns_server = '8.8.8.8'

turn_state = False

# Init Wi-Fi Interface
def initialize_wifi(wifi_ssid, wifi_password):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)

# Connect to your network
    wlan.connect(wifi_ssid, wifi_password)

# Wait for Wi-Fi connection
    connection_timeout = 10
    while connection_timeout > 0:
        if wlan.status() >= 3:
            break
        connection_timeout -= 1
        print('Waiting for Wi-Fi connection...')
        sleep(1)

# Set static IP address
    wlan.ifconfig((static_ip, subnet_mask, gateway_ip, dns_server))

# Check if connection is successful
    if wlan.status() != 3:
        raise RuntimeError('Failed to establish a network connection')
    else:
        print('Connection successful!')
        network_info = wlan.ifconfig()
        print('IP address:', network_info[0])
    return True


#   start test A here

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-i2c-lcd-display-micropython/


# Define the LCD I2C address and dimensions
I2C_ADDR = 0x27
I2C_NUM_ROWS = 4
I2C_NUM_COLS = 20

# Initialize I2C and LCD objects
i2c = SoftI2C(sda=Pin(4), scl=Pin(5), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)

def connect_mqtt():
    try:
        client = MQTTClient(client_id=config.mqtt_client_id,
                            server= config.mqtt_server,
                            port= config.mqtt_port,
#                            user=MQTT_USER,
#                            password=MQTT_PASSWORD,
                            keepalive=  config.mqtt_keepalive,
#                            ssl=MQTT_SSL,
#                            ssl_params=MQTT_SSL_PARAMS
                            )
        client.connect()
        return client
    except Exception as e:
        print('Error connecting to MQTT:', e)
        raise  # Re-raise the exception to see the full traceback

def send_MQTT(p_topic, message):
        client.publish(p_topic, message)
        lcd.move_to(4, 4)
        lcd.putstr(message)
        sleep(0.2)

try:
    lcd.move_to(12, 0)
    lcd.putstr(vers)
    sleep(0.2)
    if not initialize_wifi(wifi_ssid, wifi_password):
        print('Error connecting to the network... exiting program')
    else:
        # Connect to MQTT broker, start MQTT client
        client = connect_mqtt()
    
    while True:
        # check each GPIO input
        lcd.clear()
        if ( button0.value() == False):
            message = "move/forward"

            send_MQTT(p_topic, message)

        elif ( button1.value() == False):
            message = "move/backwards"

            send_MQTT(p_topic, message)

        elif ( button2.value() == False):
            if (turn_state == False):
                message = "turn/motorleft/on"
                turn_state = True
                print( message, turn_state)
                send_MQTT(p_topic, message)
            else:
                message = "turn/motorleft/off"
                turn_state = False
                print ( message, turn_state)
                send_MQTT(p_topic, message)

        elif ( button3.value() == False):
            if (turn_state == False):
                message = "turn/motorright/on"
                turn_state = True
                print( message, turn_state)
                send_MQTT(p_topic, message)
            else:
                message = "turn/motorright/off"
                turn_state = False
                print ( message, turn_state)
                send_MQTT(p_topic, message)

        elif ( button4.value() == False):
            message = "stop"
            send_MQTT(p_topic, message)

        else:
            lcd.move_to(5, 2)
            lcd.putstr("done loop")
#            sleep(1)



except KeyboardInterrupt:
    # Turn off the display when the code is interrupted by the user
    print("Keyboard interrupt")
    lcd.backlight_off()
    lcd.display_off()

No comments: