Skip to content

Arduino Uno R4 Wifi Chassis Control Script

directorcia edited this page Aug 2, 2025 · 1 revision

Arduino Chassis Control Script Documentation - chassis-control.cpp

Overview

This Arduino script provides remote control functionality for a 4-wheel robotic chassis using an Arduino Uno R4 WiFi, Adafruit Motor Shield v2, and RGB LCD display. The system receives commands via MQTT through Adafruit IO, allowing wireless control of the robot's movement patterns.

Hardware Requirements

Primary Components

  • Arduino Uno R4 WiFi - Main microcontroller with built-in WiFi
  • Adafruit Motor Shield v2 - Controls up to 4 DC motors with PWM
  • DFRobot RGB LCD1602 - 16x2 character display with RGB backlight
  • 4x DC Motors - Connected to motor shield ports M1, M2, M3, M4

Hardware Connections

  • Motor Shield: Stacked on Arduino using I2C (default address 0x60)
  • LCD Display: Connected via I2C (address 0x6B for v1.1 hardware)
  • Motors: Connected to shield terminals M1-M4

Software Dependencies

Required Libraries

#include <Adafruit_MotorShield.h>    // Motor control
#include <Arduino.h>                 // Core Arduino functions
#include <SPI.h>                     // Serial Peripheral Interface
#include "DFRobot_RGBLCD1602.h"     // LCD display control
#include "iot_configs.h"             // WiFi and MQTT credentials
#include <WiFi.h>                    // WiFi connectivity
#include <Adafruit_MQTT.h>           // MQTT protocol
#include <Adafruit_MQTT_Client.h>    // MQTT client implementation

Configuration Requirements

The script requires iot_configs.h with the following definitions:

  • WIFI_SSID - WiFi network name
  • WIFI_PASSWORD - WiFi network password
  • AIO_SERVER - Adafruit IO server address
  • AIO_SERVERPORT - MQTT server port
  • AIO_USERNAME - Adafruit IO username
  • AIO_KEY - Adafruit IO key

System Architecture

Hardware Initialization

  1. Motor Shield Setup - Initializes 4 DC motors on ports M1-M4
  2. LCD Display - Configures 16x2 RGB display for status output
  3. WiFi Connection - Connects to specified wireless network
  4. MQTT Client - Establishes connection to Adafruit IO service

Communication Protocol

  • Platform: Adafruit IO MQTT service
  • Feed: {username}/feeds/onoffbutton
  • Message Format: Single character commands (0-9, *, #)
  • Connection: Persistent MQTT subscription with auto-reconnect

Execution Flow

Startup Sequence (setup())

  1. Serial Communication - Initialize at 115200 baud
  2. LCD Initialization - Clear display and show startup messages
  3. Motor Shield Detection - Verify hardware connection (halt if failed)
  4. WiFi Connection - Connect to network with status indicators
  5. MQTT Subscription - Subscribe to control feed
Display Output During Startup:
Row 1: "Motor found" → "Motor run"
Row 2: "WiFi connect"

Main Operation Loop (loop())

  1. MQTT Connection Management - Ensure persistent connection
  2. Speed Display - Show current motor speed on LCD
  3. Motor Speed Setting - Apply current speed to all motors
  4. Command Processing - Listen for and execute MQTT commands
  5. Status Updates - Update LCD with current action

Command Processing System

The system interprets single-character MQTT messages as movement commands:

Speed Control

  • * (Asterisk) - Decrease Speed by 3 units (minimum: 75)
  • # (Hash) - Increase Speed by 3 units (maximum: 255)

Directional Movement (Keypad Layout)

[1] [2] [3]     [Forward-Left] [Forward] [Forward-Right]
[4] [5] [6]  =  [Left]         [Start/Stop] [Right]
[7] [8] [9]     [Back-Left]    [Back]    [Back-Right]
[0]             [Turn-Left]

Detailed Command Mapping

Command Action Motor Pattern Description
0 Turn Left M1:FWD, M2:BWD, M3:FWD, M4:BWD Rotation in place
1 Forward-Left M1:FWD, M2:OFF, M3:OFF, M4:FWD Diagonal movement
2 Forward M1:FWD, M2:FWD, M3:FWD, M4:FWD Straight ahead
3 Forward-Right M1:OFF, M2:FWD, M3:FWD, M4:OFF Diagonal movement
4 Left M1:FWD, M2:BWD, M3:BWD, M4:FWD Sideways movement
5 Start/Stop Toggle between speed 0 and 100 Emergency stop/start
6 Right M1:BWD, M2:FWD, M3:FWD, M4:BWD Sideways movement
7 Back-Left M1:OFF, M2:BWD, M3:BWD, M4:OFF Diagonal reverse
8 Back M1:BWD, M2:BWD, M3:BWD, M4:BWD Straight reverse
9 Back-Right M1:BWD, M2:OFF, M3:OFF, M4:BWD Diagonal reverse

Motor Legend: FWD=Forward, BWD=Backward, OFF=Released

Safety Features

Speed Management

  • Minimum Speed: 75 units (prevents stall conditions)
  • Maximum Speed: 255 units (full PWM duty cycle)
  • Incremental Changes: ±3 units per command for smooth acceleration

Quick Stop Function

void quickStop() {
  if (speed > 150) {  // Only activate at high speeds
    // Release all motors
    myMotor1->run(RELEASE);
    myMotor2->run(RELEASE);
    myMotor3->run(RELEASE);
    myMotor4->run(RELEASE);
    delay(50);  // 50ms brake period
  }
}
  • Purpose: Reduces momentum during direction changes at high speeds
  • Activation: Automatic when speed > 150 and changing direction
  • Duration: 50ms pause to allow deceleration

Emergency Stop

  • Trigger: Command 5 when speed ≥ 75
  • Action: Immediately set speed to 0 and release all motors
  • Recovery: Same command restarts at speed 100

Display Interface

LCD Status Information

The 16x2 LCD provides real-time feedback:

Row 1: Current action or speed

  • Shows movement direction during commands
  • Displays "Speed: XXX" during idle periods

Row 2: Generally used for status messages

  • "WiFi connect" during startup
  • Cleared during operation

Status Messages

Display Text Meaning
"Motor found" Motor shield detected successfully
"Motor run" System ready for operation
"WiFi connect" Network connection established
"Speed: XXX" Current motor speed value
"Slower/Faster" Speed adjustment feedback
"Forward", "Back", etc. Current movement direction
"Start/Stop" Emergency stop/start actions

Error Handling

Connection Management

  1. Motor Shield Failure

    • Detection: AFMS.begin() returns false
    • Response: Halt execution with error message
    • Recovery: Requires hardware check and restart
  2. WiFi Disconnection

    • Detection: Connection status monitoring
    • Response: Automatic reconnection attempts
    • Indicator: Status dots during connection process
  3. MQTT Connection Issues

    • Detection: mqtt.connected() check in loop
    • Response: Automatic reconnection via MQTT_connect()
    • Retry Logic: 2-second delay between attempts
    • Error Codes: Detailed error reporting (protocol, auth, server issues)

MQTT Error Codes

Code Meaning Typical Cause
1 Wrong protocol Version mismatch
2 ID rejected Invalid client ID
3 Server unavail Network/server issues
4 Bad user/pass Authentication failure
5 Not authed Authorization issues
6 Failed to subscribe Feed access problems

Performance Characteristics

Timing Specifications

  • Loop Frequency: Continuous execution with 100ms MQTT timeout
  • MQTT Read Timeout: 100ms per subscription check
  • Quick Stop Duration: 50ms motor brake period
  • Reconnection Delay: 2000ms between MQTT retry attempts

Motor Control

  • PWM Frequency: 1.6kHz (default Motor Shield frequency)
  • Speed Range: 0-255 (8-bit PWM resolution)
  • Speed Increment: 3 units per command
  • Response Time: Near-instantaneous motor response

Memory Usage

  • Global Variables: Minimal (speed counter, object instances)
  • String Handling: Dynamic string comparison for commands
  • Buffer Management: MQTT library handles message buffering

Troubleshooting Guide

Common Issues

  1. Motors Not Responding

    • Check motor shield power supply
    • Verify motor connections to M1-M4 terminals
    • Confirm shield stacking on Arduino
  2. LCD Display Issues

    • Verify I2C address (0x6B for v1.1 hardware)
    • Check power and data connections
    • Confirm hardware version matches address
  3. WiFi Connection Failures

    • Verify SSID and password in iot_configs.h
    • Check network availability and signal strength
    • Ensure Arduino R4 WiFi module is functional
  4. MQTT Communication Problems

    • Verify Adafruit IO credentials
    • Check internet connectivity
    • Confirm feed name format: {username}/feeds/onoffbutton

Diagnostic Information

  • Serial Monitor: 115200 baud for debug output
  • LCD Display: Real-time status and error messages
  • Network Status: WiFi connection progress indicators

Configuration Notes

Hardware Variants

The code includes support for different LCD hardware versions:

LCD1602 Module v1.0: RGBAddr = 0x60
LCD1602 Module v1.1: RGBAddr = 0x6B
LCD1602 RGB Module v1.0: RGBAddr = 0x60
LCD1602 RGB Module v2.0: RGBAddr = 0x2D

Motor Shield Addressing

  • Default Address: 0x60 (no modification required)
  • Stacking Support: Alternative address 0x61 available
  • Multiple Shields: Uncomment alternative initialization for shield stacking

Operational Recommendations

Setup Sequence

  1. Configure iot_configs.h with network credentials
  2. Upload sketch to Arduino R4 WiFi
  3. Connect hardware components
  4. Power on and monitor serial output for initialization
  5. Test basic movements using Adafruit IO dashboard

Usage Best Practices

  • Start with low speeds for initial testing
  • Use emergency stop (command 5) for immediate halt
  • Monitor LCD display for system status
  • Ensure stable WiFi connection for reliable control

Maintenance

  • Regularly check motor connections and power supply
  • Monitor MQTT connection stability
  • Verify LCD display clarity and responsiveness
  • Test emergency stop functionality periodically

Extension Possibilities

Hardware Enhancements

  • Add sensors (ultrasonic, camera, IMU)
  • Implement servo control for additional DOF
  • Include LED indicators for status visualization
  • Add buzzer for audio feedback

Software Improvements

  • Implement speed ramping for smoother acceleration
  • Add autonomous navigation capabilities
  • Include battery voltage monitoring
  • Implement command queuing for complex maneuvers

Communication Upgrades

  • Add web server for direct HTTP control
  • Implement multiple MQTT feeds for different functions
  • Include telemetry data publishing
  • Add OTA (Over-The-Air) update capability