AlphaBot: Autonomous Lane Guidance with ArduCam

Aus HSHL Mechatronik
Zur Navigation springen Zur Suche springen
Abb. 1: Kamerasensor Arducam Mini 2MP
Autor: Bertrand Mungu Cho
Art: Project Work
Starttermin: 05.10.26
Abgabetermin: 20.01.27
Betreuer: Prof. Dr.-Ing. Schneider
Sprache: 🇩🇪  🇬🇧

Introduction

The AlphaBot is a small, programmable mobile robot used for educational projects in robotics, embedded systems and autonomous navigation. It moves using two independently driven wheels and changes direction by varying their relative speeds. This differential-drive arrangement provides a practical platform for investigating how sensor measurements can be used to control a robot's movement.

This project develops camera-based autonomous lane guidance for the AlphaBot using an ArduCAM Mini 2MP Plus camera. The objective is to enable the robot to observe a marked lane, estimate its position and heading relative to that lane, and adjust its motion to follow the intended path. The project brings together mechanical design, image acquisition, image processing and feedback control.

The work includes designing and 3D printing a camera mount, commissioning the camera with an Arduino, and transferring captured images to a PC running MATLAB. Image processing is used to identify the lane and estimate the lateral and heading errors. These estimates provide the input to the lane guidance controller, while gyroscope measurements are intended to provide feedback on the robot's turning rate. The resulting left and right motor commands are sent to the Arduino, which controls the motors through the motor driver.

Development proceeds from individual component tests to integration and evaluation of the complete system. MATLAB/Simulink supports algorithm and controller development, while practical experiments assess image-transfer reliability, processing time and lane-following performance. This article documents the design decisions, implementation steps and experimental results.

Tasks

  1. Familiarization with the topics Arduino, Arducam Mini 2MP
  2. CAD design and 3D printing of the camera mount
  3. Commissioning of the camera
  4. Image processing for lane detection
  5. Autonomous lane following (control)
  6. Model-based development with MATLAB®/Simulink
  7. Testing and scientific documentation
  8. Proof of functionality as a wiki article with animated GIF

Getting Started

  1. Transponder for the Student Lab from Mr. Ebmeyer
  2. Security Infomation for the Student Lab (from Mr. Ebmeyer)
  3. Wiki Access (from Mr. Schröder)
  4. Plan your task with working packages and dependencies as a gantt chart.
  5. Get started with programming the ArduCam with Arduino.
  6. Document your steps in this article: Arducam Mini 2MP
  7. Design mount for ArduCam. Reuse or optimise the existing design.
  8. Print the mount an attach it to the AlphaBot.
  9. Document the new mount in SVN and your Wiki Article.
  10. Research how to programm the ArduCam via MATLAB/Simlink.

System Design

The proposed system uses the ArduCAM to capture lane images and a gyroscope to measure the AlphaBot’s yaw rate. The Arduino Uno R4 WiFi transfers these data to a PC through a wireless router. MATLAB processes the images to estimate the robot’s position and heading relative to the lane. The guidance and yaw-rate controllers calculate left and right motor commands, which are sent back to the Arduino for execution. This process repeats continuously to maintain lane following.

Mechanical Design and Camera Mount

Camera mount with pivot lug

ArduCAM camera's 8-pin connector

Back view of the camera mount. 8-pin connector with cable strain relief for connecting the ArduCAM camera to the Arduino.

The CAD designs for the camera mount and connector support are available in the SVN repository:

CAD designs – camera mount and connector support


Preconditions

  • ArduCAM Mini 2MP Plus B0067
  • Arduino UNO R4 WiFi
  • Connection/Cable Plan? Image?
  • Library Link?? Version?
  • Source code? Link??
  • USE SPI Connector
  • Move with versioning to c-files.

Camera Commissioning

This section describes how to reproduce image acquisition using an ArduCAM Mini 2MP Plus B0067 and an Arduino UNO R4 WiFi. The Arduino captures JPEG images and transmits them to MATLAB over Wi-Fi using UDP.

Required Hardware and Software

The following hardware is required:

  • Arduino UNO R4 WiFi.
  • ArduCAM Mini 2MP Plus B0067 with OV2640 image sensor.
  • Jumper wires suitable for the camera and Arduino headers.
  • USB data cable for programming and powering the Arduino.
  • PC running MATLAB.
  • Wi-Fi router or phone hotspot that allows communication between connected devices.

The following software is required:

Software Version or requirement
Arduino IDE INSERT_TESTED_IDE_VERSION
Arduino UNO R4 Boards package INSERT_TESTED_BOARD_PACKAGE_VERSION
Modified ArduCAM library Version 1.0.0 declared in library.json, project copy committed in SVN revision 2250
MATLAB INSERT_TESTED_MATLAB_RELEASE
Instrument Control Toolbox INSERT_TESTED_TOOLBOX_VERSION

The Arduino IDE version can be checked under Help → About. The installed board-package version is shown in Boards Manager. MATLAB and toolbox versions can be displayed by entering ver in the MATLAB Command Window.

Downloading the Project Files

The tested project files are available in the following SVN locations:

The links point to the current files in the repository. To retrieve the recorded test versions using TortoiseSVN:

  1. Open TortoiseSVN → Repo-browser.
  2. Enter the URL of the required folder.
  3. Select the required revision using the revision selector.
  4. Right-click the folder or file and select Export.
  5. Choose a local destination.

Export the complete ArduCAM library folder so that its sensor-register headers and other required files are included.

Camera Wiring

Disconnect USB and any other power source before connecting the camera. Identify pin 1 of the Arduino's six-pin SPI header using the official UNO R4 WiFi pinout.

Wiring diagram for the ArduCAM B0067 and Arduino UNO R4 WiFi, showing the six-pin SPI header and the separate CS, SDA, and SCL connections..

https://svn.hshl.de/project/HSHL_Projekte/show/trunk/AlphaBot/Documentation/Images/Alphabot_ArduCam_Wiring.svg

Connect the camera as follows:

ArduCAM B0067 to Arduino UNO R4 WiFi pin assignment
ArduCAM pin Arduino connection Function
VCC SPI header pin 2, +5 V Camera power supply
GND SPI header pin 6, GND Common ground
MOSI SPI header pin 4, COPI SPI data from Arduino to camera
MISO SPI header pin 1, CIPO SPI data from camera to Arduino
SCK SPI header pin 3, SCK SPI clock
CS D7 Camera chip select
SDA A4 / SDA I2C data for sensor configuration
SCL A5 / SCL I2C clock

SPI header pin 5 is RESET and is left unconnected. Use the SPI header identified in the pinout, rather than the separate ESP32 programming header.

After checking the wiring, connect the Arduino to the PC using the USB data cable.

Arduino IDE Setup

  1. Open Arduino IDE.
  2. Open Tools → Board → Boards Manager.
  3. Search for Arduino UNO R4 Boards and install the package provided by Arduino.
  4. Select Tools → Board → Arduino UNO R4 Boards → Arduino UNO R4 WiFi.
  5. Select the connected board under Tools → Port. The COM number depends on the computer.
  6. Open File → Preferences and note the Sketchbook location.

The UNO R4 board package supplies the WiFiS3 library used by the wireless sketch. The sketch also uses the board package's SPI and Wire libraries.

Installing the Modified ArduCAM Library

  1. Close Arduino IDE.
  2. Open the sketchbook folder identified in Preferences.
  3. Open its libraries folder, creating it if necessary.
  4. If an ArduCAM library is already installed there, back it up outside the libraries folder.
  5. Copy the complete modified ArduCAM folder from SVN revision 2250 into libraries.
  6. Check that ArduCAM.h, ArduCAM.cpp, memorysaver.h and the sensor-register headers are directly inside that folder.
  7. Reopen Arduino IDE.

The expected location is:

<Sketchbook location>/libraries/ArduCAM/ArduCAM.h
<Sketchbook location>/libraries/ArduCAM/ArduCAM.cpp
<Sketchbook location>/libraries/ArduCAM/memorysaver.h

Avoid an additional nested folder such as libraries/ArduCAM/ArduCAM/.

Library Adaptations and Camera Configuration

The installed project library includes the changes described below. These changes document how the library was adapted for the UNO R4 WiFi.

Camera Selection

Open memorysaver.h and check that this definition is enabled:

#define OV2640_MINI_2MP_PLUS

The other camera-platform selections in the same section must be commented out. The sensor-selection section for ArduCAM Shield models is left unchanged.

UNO R4 Architecture Support

The original library produced compilation errors because regtype and regsize were undefined for the UNO R4 architecture.

The following block was added to ArduCAM.h before the existing AVR definitions:

#if defined(ARDUINO_ARCH_RENESAS_UNO)
#define regtype volatile uint32_t
#define regsize uint32_t

#define cbi(reg, bitmask) digitalWrite(bitmask, LOW)
#define sbi(reg, bitmask) digitalWrite(bitmask, HIGH)
#endif

In the constructor in ArduCAM.cpp, the condition selecting the pin-number branch was extended to include the UNO R4 architecture:

#if (defined(ESP8266) || defined(ESP32) || defined(TEENSYDUINO) || defined(NRF52840_XXAA) || defined(ARDUINO_ARCH_RENESAS_UNO))
    B_CS = CS;
#else
    P_CS = portOutputRegister(digitalPinToPort(CS));
    B_CS = digitalPinToBitMask(CS);
#endif

For the UNO R4, B_CS stores the Arduino pin number. The modified macros use digitalWrite() to select and deselect the camera.

Chip-Select Name in the Sketch

The sketch uses CAMERA_CS to avoid a naming conflict with the UNO R4 board package:

const int CAMERA_CS = 7;

The physical camera CS connection is therefore D7.

Configuring and Uploading the Arduino Sketch

  1. Place AlphaBot_ArduCam_UDP_Wifi.ino inside a folder named AlphaBot_ArduCam_UDP_Wifi.
  2. Open the sketch in Arduino IDE. Accept the IDE's offer to create the matching folder if prompted.
  3. Find the Wi-Fi configuration and replace the placeholders with the local network name and password:
char ssid[] = "YOUR_HOTSPOT_NAME";
char password[] = "YOUR_HOTSPOT_PASSWORD";
  1. Connect the laptop to that same network. For a phone hotspot, use 2.4 GHz or compatibility mode if needed.
  2. Check that the sketch uses LOCAL_PORT = 5001, PAYLOAD_SIZE = 512, and CAMERA_CS = 7.
  3. Confirm that Arduino UNO R4 WiFi and the correct COM port are selected.
  4. Click Verify and wait for compilation to finish.
  5. Click Upload and wait for successful completion.

Keep actual Wi-Fi credentials in the local sketch and use placeholders in shared source files.

Checking Camera and Wi-Fi Startup

  1. Open Tools → Serial Monitor.
  2. Set the baud rate to 115200.
  3. Press the Arduino's RESET button if the startup messages have already passed.
  4. Check for messages similar to the following:
SPI interface OK.
Connecting to hotspot...
Arduino IP: 192.168.43.49
Ready for MATLAB capture requests.

The address shown above is an example from the test setup. Copy the actual address printed by the Arduino. It may change after reconnecting to the network.

The Arduino is ready to receive a capture request when the final message appears.


Image Acquisition and Communication

MATLAB requests an image over UDP. The Arduino captures a JPEG at 320 × 240 pixels, reads the camera buffer through SPI, and sends the data in numbered packets. MATLAB reassembles the frame, checks completeness, extracts the JPEG and displays it.

MATLAB Setup

  1. Open MATLAB.
  2. In the Command Window, enter which udpport.
  3. If MATLAB cannot find the function, open Home → Add-Ons → Get Add-Ons.
  4. Search for Instrument Control Toolbox and select the MathWorks product. Install it if available under the MATLAB licence.
  5. Run which udpport again to check that the function is available.
  6. Download and open capture_arducam_udp_repeated.m.
  7. Set MATLAB's Current Folder to a writable project folder. The script saves its JPEG files in this folder.

Configuring the UDP Receiver

Edit the connection settings near the beginning of the MATLAB script:

arduinoIP = "192.168.43.49";
arduinoPort = 5001;
matlabPort = 55000;

payloadSize = 512;
maxImageBytes = 200000;
receptionTimeout = 30;

Replace arduinoIP with the current address printed in Arduino Serial Monitor.

Setting Purpose
arduinoIP Address of the Arduino on the Wi-Fi network
arduinoPort = 5001 Must match the Arduino's listening port
matlabPort = 55000 Local UDP port used by MATLAB
payloadSize = 512 Must match the Arduino's image-payload size
maxImageBytes = 200000 Maximum accepted frame size for this test
receptionTimeout = 30 Maximum wait for a complete frame, in seconds

The Arduino replies to the address and port from which MATLAB sends its request.

For timing measurements, check that timerStart = tic; occurs immediately before MATLAB sends the capture request.

Running a Single Image Capture

  1. Keep the Arduino powered and wait for Ready for MATLAB capture requests. in Serial Monitor.
  2. Confirm that the laptop is still connected to the same Wi-Fi network.
  3. In the MATLAB script, set numberOfImages = 1;.
  4. Point the camera towards a well-lit object.
  5. Click Run in MATLAB.
  6. Check that Arduino Serial Monitor reports Capturing image..., the FIFO byte count and the number of packets sent.
  7. Check that MATLAB displays the photograph and reports a complete frame.
  8. Open the saved JPEG and inspect it for visible corruption.

Serial Monitor can remain open during this test because MATLAB communicates through Wi-Fi.

Expected MATLAB output has the following form:

Capture requested over UDP...
Expecting ... bytes in ... packets.
Complete frame received: ... packets.
JPEG size: ... bytes.
Request-to-complete-reception time: ... seconds.
Saved to: ...

The script saves images in MATLAB's Current Folder with filenames beginning with ArduCAM_UDP_.

Running Repeated Image Capture

  1. Set numberOfImages = 10; in the MATLAB script.
  2. Save the script and click Run.
  3. MATLAB requests each image after the previous image has been received, saved and displayed.
  4. Observe the preview window as it updates.
  5. At completion, record the successful image count and the average, minimum and maximum reception times.

Each request uses an identifier to distinguish its packets from earlier frames. The receiver places packets in order, ignores duplicates and checks that every expected packet has arrived. If a frame is incomplete or cannot be decoded, the script stops with an error.

Test Results

All ten images in the recorded wireless test were received and decoded successfully.

Results of the ten-image Wi-Fi/UDP test
Measurement Result
Resolution 320 × 240 pixels
Images received and decoded 10 out of 10
Packets received 17 per image, 170 in total
Missing packets detected 0 during this test
JPEG sizes 8,075–8,122 bytes
Average request-to-complete-reception time 1.48 s
Minimum reception time 1.38 s
Maximum reception time 1.61 s

The timing includes camera capture, FIFO readout and UDP delivery. It excludes MATLAB file saving, image decoding, display and the 0.5 s pause between captures. These results describe the recorded bench test.

Source Code and Library

Image Processing and Lane Detection

Control System


The control loop uses camera images to estimate the AlphaBot's position and heading relative to the lane. MATLAB calculates a desired turning rate and compares it with the yaw rate measured by the gyroscope. The resulting steering command is converted into left and right motor commands, which are sent to the Arduino.

1. Lane Position and Heading Errors

ey=yref−ymeas

The lateral error ey describes the difference between the desired lateral position yref and the position estimated from the camera image ymeas. When the lane centre is the reference, yref=0. An error of zero means that the robot is at the desired lateral position.

eψ=wrap[−π,π)(ψref−ψmeas)

The heading error eψ describes the difference between the desired heading ψref and the measured heading ψmeas. Both headings must use the same reference frame. The wrapping operation expresses the difference between −π and π radians, preventing an unnecessarily large correction when an angle crosses the boundary.

2. Lane Guidance

rref=kyey+kψeψ

The lane guidance equation converts the lateral and heading errors into a desired yaw rate rref. Yaw rate describes how quickly the robot turns around its vertical axis. The gains ky and kψ determine how strongly the robot responds to each error.

The lateral term guides the robot towards the desired lane position, while the heading term helps align it with the lane direction. With both errors equal to zero, this equation requests zero yaw rate.

3. Yaw-Rate Error

er=rref−rmeas

The yaw-rate error er compares the desired turning rate with the actual turning rate rmeas measured by the gyroscope. The gyroscope reading is corrected for bias and filtered before being used as feedback.

4. Yaw-Rate PI Controller

usteer(t)=Kper(t)+Ki∫0ter(τ)dτ

The proportional-integral (PI) controller calculates the steering command usteer. The proportional term, controlled by Kp, responds to the current yaw-rate error. The integral term, controlled by Ki, accumulates the error over time and helps reduce persistent differences between the desired and measured turning rates.

The steering command is a motor-control correction, rather than a physical steering angle, because the AlphaBot turns by driving its two wheels at different speeds.

5. Motor Mixing and Limits

uL=limit⁡(uforward−usteer)

uR=limit⁡(uforward+usteer)

The motor mixer combines the forward command uforward with the steering correction to obtain the left motor command uL and right motor command uR.

When the steering correction is zero, both motors receive the same command. A non-zero correction increases one motor command and decreases the other, causing the robot to turn.

The limiting function keeps each command within the permitted motor-command range:

limit⁡(u)=min⁡(umax,max⁡(umin,u))

The command bounds depend on the chosen direction and PWM representation. The Arduino converts the received motor commands into direction signals and PWM outputs for the motor driver.

Closing the Feedback Loop

The motor commands change the AlphaBot's motion. The camera observes the resulting lane position and heading, while the gyroscope measures the resulting yaw rate. MATLAB uses these updated measurements to calculate the next correction.

All position, heading, yaw-rate and motor-direction signs must follow a consistent convention so that the controller reduces the errors. Lateral position may initially be expressed in image pixels; expressing it in metres requires a calibrated image-to-ground mapping. Heading is expressed in radians and yaw rate in radians per second.

Integration and Experimental Results

Conclusion and Future Work

Appendix

A Gantt Project Chart

Gantt chart 1
Gantt chart 1
Gantt chart 2
Gantt chart 2

The Gantt chart outlines the project activities, dependencies and milestones, from camera mount design and commissioning to lane detection, controller development and final testing. It is updated regularly to reflect progress and changes to the schedule.

B Requirements for student skills

The project requires prior knowledge in the following subject areas. If you do not meet these requirements, you must acquire the necessary knowledge independently during the course of the project using literature and online courses.

  1. CAD design with SolidWorks
  2. 3D printing
  3. Image processing
  4. Optional: Model-based development with MATLAB®/Simulink
  5. Document versioning with SVN
  6. Documentation using Word and the HSHL Wiki

C Requirements for the Scientific Work


→ back to the main article: Student Work