Control a RC car using Node-Red GUI and HiveMQ broker on PicoW
Node-Red Flow
The cyan node is button node from Dashboard 2.0 which needs to be installed in node-red additionally as it is a 3rd party app. The pink node is mqtt out node.
HiveMQ
Take all the cluster details from HiveMQ to be put in mqtt out node
Node-Red Button node settings
Change the payload value for Left, Right, Front, Back and Stop Button to L, R, F, B & S value and select the type to be string
Node-Red mqtt out node settings
Click on the pencil button to set the broker settings
First you need to arrange the buttons on the dashboard so that it intuitively can tell which button to press. so we need to rearrange the layout so that the buttons look like below on http://localhost:1880/dashboard
In Dasboard 2.0 under pages hover mouse on the page . For me it is Garden , when i hover my mouse there appears a pencil shaped button . Click on it to go to layout editor
Testing connection and messaging between NodeRed and HiveMQ
Open HiveMQ and go to Web Client tab add the credentials and login. Under Topic Subscriptions add # to subscribe to all the topics
Now open the node-red dashboard from url http://localhost:1880/dashboard/
Click on one of the buttons say front button we should see F in Messages on the Right side
Now the Micropython Code for PicoW is as follows(Modified from Random Nerd Tutorials). Just for simulation LEDs are connected on GP8, GP15, GP16 & GP20 Pins.
Micropython Code
# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-w-mqtt-micropython/
from machine import Pin
from time import sleep
import network
from umqtt.simple import MQTTClient
import config
# Define LED
led = Pin('LED', Pin.OUT)
led1 = Pin(8, Pin.OUT)
led2 = Pin(15, Pin.OUT)
led3 = Pin(16, Pin.OUT)
led4 = Pin(20, Pin.OUT)
# Constants for MQTT Topics
MQTT_TOPIC_LED = 'car/dir'
# MQTT Parameters
MQTT_SERVER = config.mqtt_server
MQTT_PORT = 0
MQTT_USER = config.mqtt_username
MQTT_PASSWORD = config.mqtt_password
MQTT_CLIENT_ID = b'raspberrypi_picow'
MQTT_KEEPALIVE = 7200
MQTT_SSL = True # set to False if using local Mosquitto MQTT broker
MQTT_SSL_PARAMS = {'server_hostname': MQTT_SERVER}
# Init Wi-Fi Interface
def initialize_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
# Connect to the network
wlan.connect(ssid, 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)
# Check if connection is successful
if wlan.status() != 3:
return False
else:
print('Connection successful!')
network_info = wlan.ifconfig()
print('IP address:', network_info[0])
return True
# Connect to MQTT Broker
def connect_mqtt():
try:
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)
client.connect()
return client
except Exception as e:
print('Error connecting to MQTT:', e)
# Subcribe to MQTT topics
def subscribe(client, topic):
client.subscribe(topic)
print('Subscribe to topic:', topic)
# Callback function that runs when you receive a message on subscribed topic
def my_callback(topic, message):
# Perform desired actions based on the subscribed topic and response
print('Received message on topic:', topic)
print('Response:', message)
# Check the content of the received message
if message == b'F':
print('Turning Car FRONT')
led1.value(1) # Turn LED ON
led2.value(0)
led3.value(0)
led4.value(0)
elif message == b'L':
print('Turning Car Left')
led1.value(0) # Turn LED ON
led2.value(1)
led3.value(0)
led4.value(0)
elif message == b'R':
print('Turning Car Right')
led1.value(0) # Turn LED ON
led2.value(0)
led3.value(1)
led4.value(0)
elif message == b'B':
print('Turning Car Back')
led1.value(0) # Turn LED ON
led2.value(0)
led3.value(0)
led4.value(1)
elif message == b'S':
print('Stopping Car')
led1.value(0) # Turn LED ON
led2.value(0)
led3.value(0)
led4.value(0)
else:
print('Unknown command')
try:
# Initialize Wi-Fi
if not initialize_wifi(config.wifi_ssid, config.wifi_password):
print('Error connecting to the network... exiting program')
else:
# Connect to MQTT broker, start MQTT client
client = connect_mqtt()
client.set_callback(my_callback)
subscribe(client, MQTT_TOPIC_LED)
# Continuously checking for messages
while True:
sleep(1)
client.check_msg()
print('Loop running')
except Exception as e:
print('Error:', e)
Comments
Post a Comment