Node & Firmata PTZ Camera

This article describes the implementation of a WiFi-connected PTZ camera system built around a Raspberry Pi Zero 2W. The Raspberry Pi hosts a web interface using Node.js and communicates with an Arduino Nano over USB serial using the Firmata protocol. A remote client browser captures input from its connected game controller and sends these control inputs over Wi-Fi to the camera system. Node.js receives and processes the inputs, then translates them into commands that are sent to the Arduino Nano. The Arduino, in turn, controls the stepper motors responsible for the camera’s pan, tilt and zoom/ focus movements.

Introduction

The author’s particular area of interest lies in assembling WiFi-connected devices, typically FPV systems incorporating a camera together with some form of device feedback and control. Such devices are generally operated remotely through a browser running on a distantly connected client machine. The device itself typically consists of a small Linux-based single-board computer, responsible for WiFi communication with the remote client, coupled to a microcontroller that performs the real-time hardware control tasks.

In previous projects, I have relied on the Apache web server, running on the SBC, to serve the web interface, with C code, PHP and JavaScript scripting providing the application logic. I have also used I²C communication to interface with a slave microcontroller, together with dedicated firmware to perform the real-time control functions. While this architecture is workable, it has proven less than ideal in practice. It introduces unnecessary complexity, divides the application logic between disparate software environments, and requires the development and maintenance of dedicated microcontroller firmware.

Although PHP running under Apache is sufficiently performant for the application, the memory footprint of the web server is a significant concern, particularly on a Linux SBC with only 0.5 GiB of RAM, of which 256 MB must be reserved for GPU-based image processing. There is also a more practical difficulty with the use of the optimized Arduino I²C Slave Peripheral routines developed for earlier projects. Although these routines perform well, their complexity makes them difficult for other users to understand or adapt. Consequently, despite their technical merits, they have come to be regarded as having relatively little practical value beyond the projects for which they were originally developed.

Accordingly, in developing this PTZ camera system, which serves as a pilot for a more sophisticated remotely operated telescope project, I decided to investigate Node.js as an alternative platform for both serving the web interface and implementing the application logic. Node.js offers a particularly attractive combination of execution speed and modest memory requirements. At the same time, I investigated the Firmata serial protocol, together with Node.js’ firmata.js library, as a replacement for I²C communication.

This approach eliminates the need to develop dedicated firmware for the microcontroller, since the logic governing real-time operation can instead be implemented in JavaScript on the SBC. The microcontroller effectively becomes a runtime-configured peripheral, with its behavior established through the Firmata USB serial connection between the Linux host and the 8-bit slave processor.

Firmata?

Firmata is, fundamentally, a communication protocol that provides an interface between a host system and a microcontroller running a suitable implementation of Firmata firmware. Rather than developing application-specific firmware for the slave microcontroller, the developer installs the appropriate Firmata firmware and then configures and controls the microcontroller at runtime. Hardware configuration and manipulation are performed by calling generic functions on the host system through a Firmata client library.

There is, however, no single, universally applicable implementation of Firmata. Multiple versions of the protocol exist, along with several Firmata firmware implementations, with support for a range of microcontrollers. There are also a variety of client libraries, each intended for use with a particular host programming language. Identifying a combination that worked reliably proved to be something of a challenge. The following is the configuration with which I ultimately had success:

  • Firmata Protocol 2.5
  • ConfigurableFirmata Server Arduino Library version 2.10.1
  • Arduino Nano 5V 16MHz ATmega328p
  • firmata.js Node.js JavaScript Client Library version 2.3.0
  • Node.js JavaScript runtime Engine version 12.22.12

Firmata Server Setup

The initial setup is straightforward. Download ConfigurableFirmata Server Arduino Library version 2.10.1, then follow these installation instructions to install and compile the library for an Arduino Nano fitted with an ATmega328P. Although visually and electrically similar, a Nano fitted with an ATmega328PB is not compatible with ConfigurableFirmata.

As its name suggests, ConfigurableFirmata is designed to be configured according to the hardware functions required by the application. In this project, its optional accelStepper module is used to control the stepper motors. Consequently, the corresponding header include in the master sketch, ConfigurableFirmata.ino, must be uncommented and enabled. This file is located in the examples/ConfigurableFirmata sub-directory of the library.

Early testing on an Arduino Pro Mini.

Firmata Client Javascript

The complete listing of the pathfinder project’s JavaScript code is linked below. Before examining it in detail, however, there are two aspects that warrant discussion: first, how the Firmata server is configured for stepper motor control, and second, how the project’s implementation makes unconventional use of its accelStepper module.

The slave-control.js file contains a class built around the firmata.js client library, providing the interface through which the Firmata server is configured and controlled. The file begins by importing the Firmata module:

// slave-control.js
const Board = require("firmata");

Further into the class, a configuration method establishes the type, pin assignment, and operating mode for each stepper motor connected to the slave microcontroller. For brevity, only the configuration for the first motor is shown below:


  configureSlave() {
    this.board.accelStepperConfig({
      deviceNum: Device.PAN,
      type: this.board.STEPPER.TYPE.FOUR_WIRE,
      motorPin1: 2,    // IN2 for 28byj-48-5v unipolar stepper motor drive board.
      motorPin2: 3,    // IN4                        ''
      motorPin3: 4,    // IN1                        ''
      motorPin4: 5,    // IN3                        ''
      stepSize: this.board.STEPPER.STEP_SIZE.WHOLE,
    });
    console.log("x device 0 configured");
    .
    .
    .
  }

Once initialization of the server board is complete, including the configuration described above, the class provides a number of functions for controlling the individual stepper motors. Unfortunately, the underlying accelStepper module is designed around a rather different control model from that required by this application. It expects the host to specify a target position relative to the motor’s current position, together with a maximum speed at which that position should be reached. The module then determines the direction of travel, accelerates the motor towards the target, and subsequently decelerates it as the target is approached. This behavior is useful for positional control, but is not what we require for a responsive PTZ system.

Our PTZ application instead requires an interface through which the step rate and direction of each motor can be changed rapidly and repeatedly. To achieve this using accelStepper, we effectively co-opt its positional interface. We repeatedly supply it with a deliberately distant and otherwise irrelevant target position, using that target solely to establish the desired direction of travel, together with the speed at which the motor should run. The actual position of each motor is tracked independently by our own software, which maintains a separate time-varying measure of its position. In effect, accelStepper provides the low-level stepping mechanism, while the application retains responsibility for determining where the motor actually is.

setStepperValue(deviceNum, value) {

    // Request the current position first (this is asynchronous)
    this.board.accelStepperReportPosition(deviceNum, (currentPosition) => {
      // Store the reported position
      this.posnValue[deviceNum] = currentPosition;
      .
      .
      . 
        // Calculate new target position and speed
        const newPosition = 
                 currentPosition + Math.round(value * this.positionIncrement);
        const newSpeed = Math.round((value - DEAD_BAND) * this.maxStepsPerSec);
        .
        .
        .
          // Set the speed (this command returns immediately)
          this.board.accelStepperSpeed(deviceNum, newSpeed);
          // Set arbitrary, large target to indicate direction
          this.board.accelStepperTo(deviceNum, newPosition); 
        .
        .
        .
    });
  }

We therefore have direct control over the speed and direction of all three stepper motors, with each motor governed by the deflection of the corresponding joystick axis on the client’s game controller. This is a simplification of the actual implementation, but it should make the otherwise non-intuitive portion of the JavaScript code easier to understand.

The Node.js runtime executes an index.js application script, which instantiates the class described above and serves the index.html interface to the client browser. Once the page has loaded, JavaScript running in the browser communicates with the corresponding back-end JavaScript functions running on the Node.js server. Data is exchanged in both directions, with the client transmitting joystick inputs to control the PTZ system, and the server returning information describing the current state of the device.

Hardware & Wiring

As this was primarily a path-finding exercise, the hardware implementation was deliberately modest. I simply gutted a $5 WiFi camera with its original, rather inadequate pan and tilt mechanism, retaining the small stepper motors, and replaced its original PCB with an inexpensive OV5647-based 5MP camera module. The Arduino Nano and stepper motor control circuitry are housed within the original enclosure, while the camera module and Nano are connected to a Raspberry Pi Zero 2W mounted externally.

The camera lens used was an inexpensive 25 mm, 5MP telephoto lens with an M12 × 0.5 mounting thread. More capable lenses are readily available, although their prices tend to increase commensurately with their optical performance.

Only the pan and tilt functions were implemented in the interim prototype, although each axis was fully tested and is supported by the source code. The zoom/ focus function, though implemented in software, was not connected to the prototype hardware.

OS Setup

Because the inexpensive camera module used by this project relies on the legacy Multi-Media Abstraction Layer (MMAL) camera stack, I have chosen the relatively dated and minimal Buster release of the Raspbian OS. This provides the necessary support for legacy Raspberry Pi cameras while also keeping the operating system’s memory footprint to a minimum.

The firmata.js client library for Node.js, which supports the Firmata protocol version 2.5 used by this project, requires Node.js 12.22.x. We will therefore install the early 12.22.12 release of Node.js.

We will also install a version of Motion, the motion detection and video surveillance application, that remains compatible with both the legacy camera stack and the older operating system. Motion will provide the video stream for the application, while MotionEye, its web-based front-end, will provide a more convenient means of configuring and managing Motion. The two work remarkably well together on the Raspberry Pi Zero 2W, despite the platform’s limited memory.

The Raspberry Pi Zero 2W can be prepared for first use by following this extensive installation and configuration guide.

The github repository from which the project files are made available is at https://github.com/Green-Bug-Eyed-Monster/PTZ-Camera/.

Setting up MotionEye

Once MotionEye is running, its web interface is available on your local WLAN at http://camera.local:8765/. The default username is admin, while the default password is blank.

The first step is to select Add a Camera. In my case, the camera is of the MMAL type, although the appropriate selection will depend on the camera hardware being used. Under the Video Device tab, set a frame rate and resolution appropriate to the intended application.

If, like me, you make hasty purchasing decisions and have fitted a telephoto lens without a daylight IR filter, you may find that the resulting image has a distinctly pink cast. This can be corrected by adding the following line to Video Device > Extra Motion Options:

mmalcam_control_params -awb off -awbg 0.9,1.1 -sa 90 -co 0 -br 35

These parameters disable automatic white balance and apply a manual correction to the red and blue gain, while also adjusting saturation, contrast, and brightness to produce a more natural image.

To provide the Node.js-served PTZ application with a video feed, first enable Video Streaming in MotionEye. The available frame-rate and video-quality settings can then be adjusted to suit the application, with the resulting stream available at http://camera.local:8081/.

MotionEye also provides direct access to a JPEG snapshot of the current camera output. This can be viewed in a browser at http://camera.local:8765/picture/1/current/.

If you wish to experiment with video capture triggered by motion detection, there is a slightly non-obvious prerequisite: the Movies tab must first be enabled. Once enabled, Motion Detection can be activated, allowing its various detection and recording parameters to be configured and tested.

PTZ Camera UI

Node.js, running on the Pi Zero 2W, serves the index.html application at http://camera.local:3000/. The interface includes a reference to Motion’s MJPEG stream at http://camera.local:8081/, which is sufficient when the application is being used within the local WLAN. If the interface is to be operated from a remote location, however, this reference must be changed to whatever globally accessible URL you have configured for the camera’s video stream.

As this was intended only as a pathfinder project, little effort was invested in producing an aesthetically refined user interface. Once a game controller is connected and operational however, the interface provides the essential information required to operate and monitor the system. This includes the camera image, the various locally and remotely reported joystick axes, the absolute positions maintained for the stepper motor axes, and other relevant device-state information.

The right-hand joystick’s X and Y axes control pan and tilt speed respectively, with the motor speed varying proportionally according to joystick deflection. The left-hand joystick’s Y axis is assigned to the zoom/ focus function, although this was not connected to the prototype hardware.

I encountered an unexpected difficulty when connecting a recent Microsoft Xbox game controller to Linux Mint. The controller’s joystick and button mappings were presented in a rather unhelpful arrangement, requiring the installation of the rather intimidating xpadneo kernel module to restore the expected axis and button assignments.

Conclusions

The project was an experiment, seeking to determine the merits of replacing the usual Apache webserver, C code, JavaScript and PHP scripting, with the Node.js JavaScript engine and JavaScript. This part of the investigation was a success, and I will be using Node.js for all such WiFi-connected FPV gadgets in future. Node.js v12.22.12 saved a lot of memory space, and is known to be superior in performance in every respect.

The second part of the investigation was less conclusive. Rather than using the conventional I²C link, stepper motor control was implemented using ConfigurableFirmata and its integrated accelStepper module, communicating with the real-time microcontroller over USB serial. This proved entirely adequate for manual camera positioning, with motor speed varying proportionally with joystick deflection. It did not, however, provide sufficiently smooth, fine-grained positional control for applications such as OpenCV-based motion tracking.

I remain convinced that the Firmata protocol itself is a viable means of communicating with a real-time microcontroller. The limitation was more likely a consequence of the particular way in which I employed ConfigurableFirmata’s accelStepper module. Its interface is fundamentally intended for a different style of motor control from that required by this application, and the rather unconventional solution described earlier was necessarily a compromise.

For future projects, I expect to return to I²C communication, coupled with dedicated real-time slave peripheral firmware. The previous I²C communication routines may well be revised as a more accessible library implementation, with greater emphasis on comprehensibility, portability, and ease of adoption. There also appears to be scope for a non-blocking firmware solution that allows 4-control-signal stepper motors to ‘run at speed x’.

I hope that this project has proved useful to those considering similar technologies for their own work, whether as a practical guide or simply as a source of ideas for further experimentation. At the very least, I hope it has provided a small and worthwhile distraction from the rather troubled state of the world in which we currently find ourselves.

If you are able and so inclined, please consider helping to buy dinner for one of my many beloved street kitties:
paypal.me/RoxbyLaneDumpsterCat 🐾

Arduino I2C Slave Peripheral

With a recognition of the existing gap, I present this contribution aimed at enhancing the publicly accessible guidelines for laying out and coding Arduino I2C slave devices. This proposal introduces an organizational framework for coding I2C slave peripherals on Arduino, illustrated through a Platformio-based example.

Structure

Using an Atmel328PB microcontroller, we simulate a series of 16-bit peripheral registers, each with an 8-bit address. These registers are programmed akin to standard silicon I2C devices, allowing individual configuration for read-only, write-only, or read-write operations as perceived by the I2C master.

/*****************************************************************************
 *
 *                              Global Variables
 *
 *****************************************************************************/
// An array to store register values
int i2c_registers[I2C_NUM_REGS] = {0};

// I2C session persistent register address
uint8_t registerAddr = 0xFF;

In the development of an I2C slave application, peripheral functionality must be implemented through data source and data sink operations, skillfully integrated with the aforementioned emulated device registers.

In scenarios demanding highly efficient application code execution, integration occurs within the I2C interrupt service context. These application operations are executed dynamically during active I2C communication. However, integrating time-consuming application operations here can potentially delay I2C timing to a degree that compromises standards compliance, resulting in communication failures.

To mitigate this risk, in cases where application code runs slower, linkage between data source/sink operations and emulated peripheral registers occurs outside the I2C service interrupt context, typically within or under the task loop scope. Despite this approach, simultaneous access to emulated registers can occur, due to I2C ISR service routine triggering, leading to data integrity issues.

To ensure robustness, a pair of interrupt-suspending memory access macros is provided. These macros guarantee atomicity during peripheral register data manipulation within the task loop, thereby preventing potential corruption

I2C Call-back Functions

During program setup, the I2C bus under configuration, is assigned a device address, and call-back routines for the service of wired I2C bus transactions. When an I2C-inbound write occurs, data is consumed and/ or is stored in a register, with code inside the receiveEvent() callback. When an I2C-inbound read occurs, data is application generated, or is retrieved from a register, inside the requestEvent() ISR.

  Wire.begin(I2C_ADDRESS);      // Initialize I2C communication as a slave
  Wire.onReceive(receiveEvent); // Register the receive event handler
  Wire.onRequest(requestEvent); // Register the request event handler

The unpopulated receiveEvent() call-back

An unpopulated receiveEvent() ISR services wired I2C register storage instructions. Not yet linked to any application functionality, it merely provides write access to peripheral register memory.

/*****************************************************************************
 *
 *                               receiveEvent()
 *
 *****************************************************************************/
// Event handler for receiving data from the master, to write to a register
void receiveEvent(int numBytes) 
{ 
  // Read the requested register address
  registerAddr = Wire.read(); 
  
  if (numBytes == 3) 
  {
    // Read the data to write
    uint16_t value = Wire.read() ;        // value LSB
    value |= Wire.read() << 8;            // value MSB

    switch (registerAddr)
    {
      // Comment-out any read-only registers to prevent master write
      case I2C_REG_0:
      case I2C_REG_1: 
      case I2C_REG_2:
      case I2C_REG_3:
      case I2C_REG_4:
      case I2C_REG_5:
      case I2C_REG_6:
      case I2C_REG_7:
      {
        i2c_registers[registerAddr] = value;
        break;
      }
      default: return;
    }

    I2C_WRITE_DEBUG(registerAddr, value)
  }
}

The unpopulated requestEvent() call-back

An unpopulated requestEvent() ISR services wired I2C register retrieval instructions. Not yet linked to any application functionality, it merely provides read access to peripheral register memory.

/*****************************************************************************
 *
 *                               requestEvent()
 *
 *****************************************************************************/
// Event handler for responding to requests for register contents, from the master
void requestEvent() 
{
  uint16_t value = 0;

  switch (registerAddr)
  {
    // Comment out any write-only registers to prevent master read
    case I2C_REG_0:
    case I2C_REG_1:
    case I2C_REG_2:
    case I2C_REG_3:
    case I2C_REG_4:
    case I2C_REG_5:
    case I2C_REG_6:
    case I2C_REG_7:
    {
      value = i2c_registers[registerAddr];
      break;
    }
    default:
      return;
  }

  // Send the data read from
  Wire.write(value & 0xFF); // send LSB
  Wire.write(value >> 8);   // send MSB

  I2C_READ_DEBUG(registerAddr, value);

  return;
}

Read-ability and write-ability

So, we may see from the above, in the unpopulated ISR pair, an I2C master has the ability to write a value to one of a number of memory-only registers, and then read it back from there verbatim. We’ll see later, when we come to adding applications, such simultaneous read-ability and write-ability may not be desirable.

To make a peripheral register read-only, we remove the receiveEvent() ISRs ability to service peripheral register write requests. We do this by commenting-out service routine switch cases that involve the register.

void receiveEvent(int numBytes) 
{

...

    switch (registerAddr)
    {
      // Comment out any read-only registers to prevent master write
      case I2C_REG_0:
      //case I2C_REG_1:  // Make register 1 read-only
      case I2C_REG_2:
      case I2C_REG_3:
      case I2C_REG_4:
      case I2C_REG_5:
      case I2C_REG_6:
      case I2C_REG_7:
      {
        i2c_registers[registerAddr] = value;
        break;
      }
      default: return;
    }

...

To make a peripheral register write-only, we remove the requestEvent() ISRs ability to service peripheral register read requests. Again, we do this by commenting-out service routine switch cases that involve the register.

void requestEvent() 
{

...

  switch (registerAddr)
  {
    // Comment out any write-only registers to prevent master read
    case I2C_REG_0:
    case I2C_REG_1:
    // case I2C_REG_2:  // Make register 2 write-only
    case I2C_REG_3:
    case I2C_REG_4:
    case I2C_REG_5:
    case I2C_REG_6:
    case I2C_REG_7:
    {
      value = i2c_registers[registerAddr];
      break;
    }
    default:
      return;
  }

...

Application linkage inside loop()

Now that we have our peripheral registers configured, variously as read and write, read-only, or write-only, we come to linking these to application code. This involves the data sink and data source routines, that you will develop for your peripheral.

Remember, all access to peripheral registers outside the I2C interrupt service context, must employ the atomic register access macros, I2C_ATOMIC_REG_RD() and I2C_ATOMIC_REG_WR(). Again, this is vital to prevent the data corruption that occurs, when I2C ISRs are invoked, during peripheral register access. The macros momentarily ‘lock-out’ the ISRs.

/************************************************************************
 *
 *                                loop()
 *
 ************************************************************************/
void loop() 
{
  {
    uint16_t value = 0;

    // Read adc, and atomically save val in read-only slave register 1
    value = myadc_read();
    // i2c_registers[I2C_REG_1] = value; <- not atomic, instead...
    I2C_ATOMIC_REG_WR(i2c_registers[I2C_REG_1], value);

    // Retrieve contents of slave register 0 atomically, and consume
    // value = i2c_registers[I2C_REG_0]; <- not atomic, instead...
    I2C_ATOMIC_REG_RD(value, i2c_registers[I2C_REG_0]);
    myservo_set_pos(value);
  }

  // Other application tasks.

}

In the above, we see that a logically read-only peripheral register, I2C_REG_1, is fed samples from an onboard ADC, using an application call to myadc_read(). A remotely wired, I2C master may read the stored register data, with calls such as wiringPi’s wiringPiI2CReadReg16().

As well, above, we have an either read and write, or write-only configured peripheral register, I2C_REG_0, feeding position data to an attached servo. It does this via an application call to myservo_set_pos(). A remotely wired, I2C master may write the servo position data, with calls such as wiringPi’s wiringPiI2CWriteReg16().

On-demand, vs polled register access

The above mentioned approach for linking application data sink and source functionality, to underlying peripheral register memory, from outside I2C ISR service context, can be wasteful. Significant cpu cycles are consumed, in the application either constantly polling peripheral registers for incoming data, or frequently updating peripheral registers for fresh outgoing data.

To increase application efficiency, an alternate user code linkage solution exists, for on-demand exchange of data with peripheral registers. This involves application data source and data sink function calls, from within I2C ISR service context.

As mentioned previously, application calls made inside either of the I2C ISR call-backs, must be very brief, so as not to disrupt wired I2C communication. Between the servo and ADC application calls dealt with previously, only the myservo_set_pos() call is suitable. The myadc_read() function involves lengthy over-sampling, and any attempt to link it ‘on-demand’, from within an ISR, will break associated I2C transactions.

Application linkage inside the I2C ISRs

Here we examine the alternative approach to linking an I2C slave peripheral’s servo position. Data is exchanged only when requested to be, by a wired I2C bus transaction. The I2C receiveEvent() ISR handles incoming data, and we merely write that ‘value’ data to the servo, using the necessarily fast myservo_set_pos() application call.

void receiveEvent(int numBytes) 
{

...

    switch (registerAddr)
    {
      // Comment out any read-only registers to prevent master write
      case I2C_REG_0:
      {
        myservo_set_pos(value);
        i2c_registers[registerAddr] = value;
        break;
      }
      //case I2C_REG_1:  // Read-only
      case I2C_REG_2:
      case I2C_REG_3:
      case I2C_REG_4:
      case I2C_REG_5:
      case I2C_REG_6:
      case I2C_REG_7:
      {
        i2c_registers[registerAddr] = value;
        break;
      }
      default: return;
    }

    I2C_WRITE_DEBUG(registerAddr, value)
  }
}

...

In this case, we have chosen to make the servo peripheral register both readable, and writeable. To accomplish this, we must also store the incoming data in the underlying peripheral register, as shown above.

In the case where we wanted to make the application’s servo peripheral register write only, we would not store the incoming position data in any underlying peripheral register, or, at the very least, make the underlying register write only. This is again accomplished, by commenting-out the appropriate switch statement case, inside the requestEvent() ISR.

void requestEvent() 
{

...

  switch (registerAddr)
  {
    // Comment out any write-only registers to prevent master read
    //case I2C_REG_0:  // Make servo register 0 write-only
    case I2C_REG_1:
    case I2C_REG_2:
    case I2C_REG_3:
    case I2C_REG_4:
    case I2C_REG_5:
    case I2C_REG_6:
    case I2C_REG_7:
    {
      value = i2c_registers[registerAddr];
      break;
    }
    default:
      return;
  }

...

For the final case, we examine how outgoing application data may be linked to peripheral register requests, on-demand, from within I2C ISR context. For this, we will read an attached switch, with an imaginary application call, myswitch_get_posn(). We know that the call will be fast enough not to break wired I2C communication, and that logically the operation must be read-only.

The I2C requestEvent() ISR handles outgoing data, and we merely service a request for the switch position, with data from the myswitch_get_posn() application call.

void requestEvent() 
{

...

  switch (registerAddr)
  {
    // Comment out any write-only registers to prevent master read
    case I2C_REG_2:
    {
      value = myswitch_get_posn();
      break;
    }
    case I2C_REG_0:
    case I2C_REG_1:
    case I2C_REG_3:
    case I2C_REG_4:
    case I2C_REG_5:
    case I2C_REG_6:
    case I2C_REG_7:
    {
      value = i2c_registers[registerAddr];
      break;
    }
    default:
      return;
  }

...

As seen above, the switch peripheral register is logically read only, so stored peripheral register memory is not involved. To disable any attempt to write a peripheral register, making it read only, we comment-out it’s associated entry in the receiveEvent() I2C ISR.

void requestEvent() 
{

...

  switch (registerAddr)
  {
    // Comment out any write-only registers to prevent master read
    case I2C_REG_0:
    case I2C_REG_1:
    // case I2C_REG_2:  // Make switch register 2 write-only
    case I2C_REG_3:
    case I2C_REG_4:
    case I2C_REG_5:
    case I2C_REG_6:
    case I2C_REG_7:
    {
      value = i2c_registers[registerAddr];
      break;
    }
    default:
      return;
  }

...

Improving polled access efficiency

/************************************************************************
 *
 *                                loop()
 *
 ************************************************************************/
void loop() 
{
  {
    uint16_t value = 0;

    if (myservo_changed())
    {
      // Retrieve contents of slave register 0 atomically, and consume
      I2C_ATOMIC_REG_RD(value, i2c_registers[I2C_REG_0]);
      myservo_set_changed(0);

      // From here on, receiveEvent() ISR can take new register data,
      // and the snapshot 'value' can be processed, even if exhaustively
      myservo_set_pos(value);
    }
  }

  // Other application tasks.

}
void receiveEvent(int numBytes) 
{

...

    switch (registerAddr)
    {
      // Comment out any read-only registers to prevent master write
      case I2C_REG_0:
      {
        i2c_registers[registerAddr] = value;
        myservo_set_changed(1);
        break;
      }
      case I2C_REG_1:
      case I2C_REG_2:
      case I2C_REG_3:
      case I2C_REG_4:
      case I2C_REG_5:
      case I2C_REG_6:
      case I2C_REG_7:
      {
        i2c_registers[registerAddr] = value;
        break;
      }
      default: return;
    }

    I2C_WRITE_DEBUG(registerAddr, value)
  }
}

...

Well, that’s how the I2C slave peripheral model works, how to constrain access to it’s underlying peripheral registers, and how to link-in application code. Application linkage methods were shown, both by polling inside loop(), and by on-demand calls inside ISR context.

Just remember to keep application calls short inside the ISRs, and to use atomic register access macros outside them.

Associated Files:

The attached Arduino I2C slave demonstration code for this example, runs on an AT328PB. It reads the position of an ADC-connected potentiometer, and stores this data in a 16-bit I2C register numbered 1. It also reads data in a 16-bit I2C register numbered 0, and sets the corresponding position of an attached servo.

Example C code for a wiringPi-installed, Raspberry Pi master is also provided, which remotely reads the potentiometer value, and writes a proportionate value back to the I2C slave peripheral’s servo control register.

Demonstration code, of the suggested organisational paradigm, for an Arduino I2C slave peripheral. I2C_slave_model.zip

WiFi FPV Robots

I detail the make of WiFi Robots, with first person video, sensory feedback, and actuator control, from ‘toy hacked’ remote control toys.

WiFi FPV Robot 1

WiFi FPV Robot 1, featured above, is built upon a 2.4GHz RC Rock crawler chassis. The fitted Raspberry Pi Zero W streams video to an HTTP browser session, from which the operator can gain status feedback, and control motors and lights with a game controller.

The project was unique, in that it successfully employed dc brushed motor Back-EMF measurements, for fine motor control. The inbuilt Arduino 328P Nano, is tasked with motor feedback sampling and PID control, motor PWM outputs, as well as lighting control, status assessment and reporting.

WiFi FPV Robot 2 (WIP)

The plan is to acquire a mecanum wheeled version of the un-branded RC Rock Crawler used in V1, and convert it using many of the same techniques and technologies employed previously.

The updated mecanum rc toy runs a AUD$55 investment, though?


11/04/2024 – Component accumulation ensues…


22/04/24 – Parts still amassing.


ARDUINO COMPONENT

Interested in Raspberry Pi and Arduino robotics? Why not check-out my Arduino I2C Slave Peripheral Paradigm? There’s a brief write-up on how to use it, as well as sample code to download.


23/04/24 – The front connector for a Raspberry Pi Zero 2W.


24/04/24 – That’s I2C and power to the Pi Zero 2W, and an unpopulated IDC header to wire any remaining Pi pin, if ever required.


26/04/24 – The autopsy commences. I will measure motor currents first, before gutting, then build the electronics bay up large enough to accommodate PSUs, H-Bridges, and feedback signal conditioning. – Loaded motors current was ~2A or more. I’ll be splitting that between dual 1.5A supplies. The remaining half ampere on each, is exhausted by CPU and microcontroller power on one converter, and by more extensive lighting on the other.


27/04/24 – Four motors, means 4 signal conditioner circuits. They rectify, filter, scale and clip, motor back EMF signals for ADC conversion. This is the signal we use to control engine power, using PIDs. Perf board turned out to be a good choice, and the whole board was done in 2 hours, or so. Used less space than budgeted.


28/04/24 – 65-degree field of view, 5Mp OV5647 camera, gets a 120-degree FOV lens upgrade, courtesy of a cheap OV2640 donor camera. On the second attempt, I sanded the square flange right off the donor’s lens mounting ring. With SuperGlue, I tacked it to the old lens mount, where it’s lens ring had been sanded away. A final skin of epoxy, secures the 2 lens fixtures together, as well to the camera image sensor. The result was flawless.- I couldn’t find a wide angle lens equipped camera, for my Pi Zero 2W’s in-housing v2 camera, so I made one…hacking defined.


28/04/24 – Twin 1.5A Buck Boost power converters installed in the battery compartment. Loads of room for the H-Bridge and signal conditioner above.


ARDUINO COMPONENT

I’ve just finished the Arduino I2C slave peripheral code, which I’ll be using soon, and you can see the full write-up, and download the demo source over here.

As a foundation upon which to build register-oriented, I2C applications. These, typically in the control and data acquisition genre. The solution I provide in ‘Arduino I2C Slave Peripheral Paradigm’, is a good choice to build your application code over. The user implements both data source and data sink application functions, and link these to the underlying, emulated register set. The methods are fully documented, and the code has been ‘hardened’, during intense peer review.


Side and Rear Lights

30/04/24 – Marking, then carving up the enclosure; 8 square holes, mounting and wiring of 8 LEDs.

More WS2812 lights coming, for a total around 300mA. Adding in the original toy’s underbody lighting, will draw another 30+mA, as they’re being overdriven.


Body on Chassis

30/04/24 – Saw-milled dowel from a hardwood plank, to make the body/ chassis interstitial rails. Drill press used to bore the 4mm holes.

Everything fits, some polishing to do.


STM32F103C8T6 Blue Pill

I’ve been using an AT328PB microcontroller for development up to this point. It has decided to refuse to fully connect and program now, so I’m done with that device. It was never really suited to running 8 PWMs, and was looking like too much bother, anyhow.

So, now I’m looking at STM32F103C8T6 Blue Pill board, making sure which pins are available to run things like PWMs, DACs, etc.

Blue Pills were once a pain to work with, though ST’s USB Bootloader, has made it pleasure (but a setup hurdle).

15 PWM outputs!!! Buckets of CPU to run the 4 PID loops. Hope everything else works out.


Slave development and wiring

2/05/24 – Got code for an I2C slave with servo and potentiometer working. Different Servo library. Got Neopixel drive working, with a different STM32 library.

Will try to bring the full set of peripheral hardware up on the Blue Pill later tonight. So far, it’s looking good for application fit.


3/05/24 – Can now get 8 PWM outputs with Arduino calls, but only at 1kHz, and only on 8 of the 10 ADC inputs. We need 5 ADC inputs, so have to setup alternate PWM hardware myself.

Now, can get 5 PWM outputs, from 7 in non ADC group, to work. 2 taken by I2C. Need to figure out how to drive 4 reversible motors, using only 1 PWM for each. That’s extra logic to design and build.

Neopixel module looks great, but makes my I2C unstable. !

Extra logic

To drive the 8 H-Bridge motor inputs, with just 4 PWM outputs, we need some extra logic. Octal gated switches, to be precise.

Oh, how we love to hand wire daughter boards.


Slave Motherboard gets a Daughter


5/05/24 – Have the Octa-Switch tested, debugged and fully documented. ChatGPT seems to think that it should be called a quad duo-switch. Whicheither!


7/05/2024 – Got the Slave Controller’s Motherboard likely finalised, and then documented.


7/05/24 – FastLED refuses to work on the Blue Pill. Might be able to fix AdaFruit’s NeoPixel code, and stop it crashing I2C, but my STM32F103C8T6 Blue Pill Board has gone to heaven. Replacement board will have double flash size, and get here in ~12-days. Kind of a spanner, but I can re-order loads of other tasks.


8/05/24 – Blue Pill remains intermittent. WS8212 Neopixel for light bar arrived. Tested, and fortunately compatible with other LEDs. Wired-up, so that’s just the H-Bridge/ signal conditioner PCB to finish wiring.

All basic internal wiring complete, enough to run CPUs, motors and lights. Won’t power-up, so some tracing to do. Back to the dodgy bootloader problem first. Several bootloader options, dunno which is best.


9/05/24 – Given up on USB bootloaders, in favour of an ST-Link v2 USB debugger. The USB debugger was a real boon, but failed to connect reliably for programming.

First light from all 16 NeoPixels, photo does no justice.


11/05/24 – Sick as a dog.


12/05/24 – Extant Blue Pill board has developed a short from 3.3v to GND. Toast. New Blue Pill+ might arrive on Friday. I’ll be very interested to see how the USB Bootloader for a high density F103CB device works. Debugger is better, but hid device is just so easy.


13/05/24 – Basic rover hardware tested and working. Will be slow-going until replacement Blue Pill+ arrives. More care not to reverse bias the LDO on the new one.


HMC5883L

Adding this HMC5883L magnetometer early in the build, as it will be used to help control mecanum yaw motion. I’ve previously written a Compass module in C, that gives accurate compass degrees, either planar, or from a known tilt angle. We’ll use the planar compass routine here.


6Ah 8.4V Battery

~50Wh, 2S2P, 4 x 18650 3000mAh 15A NMC LiPo, slanted to reduce height.


14/05/24 – 3-motors and 1 PID loop in the first WiFi Robot was tricky enough. Now there are 4-motors and 4 PID control loops to code. All whilst getting one’s head around the permutations of this:


Getting Arduino AVR Disassembly with Platformio

You can get a cpp-source-interleaved disassembly listing, when compiling for Arduino AVR with Platformio.

...

void loop() 
{
  // Read adc and save result in read-only slave register 1
  i2c_registers[I2C_REG_1] = myadc_read();
     cc2:	0e 94 46 06 	call	0xc8c	; 0xc8c <_Z10myadc_readv>
     cc6:	90 93 21 01 	sts	0x0121, r25	; 0x800121 <i2c_registers+0x3>
     cca:	80 93 20 01 	sts	0x0120, r24	; 0x800120 <i2c_registers+0x2>

...

15/05/24 – Have ‘roughed-out’ control for 4 PID motor drivers, each with stall recovery, FAA lighting control, and battery voltage monitor.

Code structure needs much work, before dressing-up for presentation. Very productive coding session, lots of flow.

On-track for Blue Pill+ delivery on Friday, 2-days hence. If not, then Monday.

Time to ride=-🚴


16/05/24 – Auspost says the Blue Pill+ will be delivered today. Better get cracking and properly structure the motor driver, light control and voltage sensing solution.

Later:

Blue Pill+ arrived quite early. USB HID Bootloader is just as rubbish, so straight back to the debugger for programming. Plus variant pinout turns out to be different for 1 power pin. It shorted the 5V, when I plugged it into the hardware. Also, onboard indicator LED also changed.


17/05/24 – All 4 PWM motor drivers working, with motor back EMF feedback and PID control for each. FAA LEDs also working. Restructure complete. Tiny bit of optimisation, then dress-up for presentation, and we can move-on to mecanum moves.

Taking a slow day, as pooped from last few days frantic coding.


18/04/24 – Basic PID tune in place, stall detection debugged and roughly attuned.

Things are starting to come together, with mecanum motion motor patterns:


19/05/24 – Come to actually use that I2C slave code library you spent weeks agonising over every detail of, and you find it doesn’t work, still?!?!

As it looks, this could take a bit. Problem is with the Arduino Wire library, running on STM32 hardware.

Later: Cracked it. Default 100kHz Wire functionality problematic. Getting both master and slave up at 400kHz bothersome, but mostly successful. Time for a reward.🚴‍♂️


20/05/24 – All but 1 bug eliminated from I2C slave code. Needed something to command it, so skipped-ahead and re-wrote the I2C master code from first WiFi FPV Robot, so it now issues new moves and instructions. Will use it to debug the slave code tomorrow, when both the robot’s batteries, as well my own, are recharged.

Actually quite close to the end result, of basic FPV interaction. Just some JavaScript and PHP for the server to be re-written. Not bothering with On-screen visual feedback of controller inputs this time, as the mecanum movements don’t translate. That will make things far easier.


21/05/24 – Busy debugging the i2c part of the slave. Responds to most of the commands depicted above, yet won’t run any motors.

Later: Have the full i2c link working. On the master Raspberry Pi, you issue a command like i2c_master –LIGHTS_ON, and the Arduino slave now responds appropriately.

I2C comm link will be complete, after the servo driver is integrated into the slave, and a means to set it’s value is inserted into the i2c_master program.

Later again: Disaster! A timer conflict, between Arduino PWM outputs, and their Servo library.


22/05/24 – Bogged-down trying to find a solution to drive a servo off timer 2. Can’t get any of the public servo libraries to work. Not above writing my own servo driver, but then find public timer libraries are also shit. Okay, not above writing my own timer code, too!


24/05/24 – Still bogged, trying to get STM32CubeMX projects to compile on Platformio. Working toward a Timer library for Arduino. Drama downloading ST software, won’t be resolved today.


25/05/24 – Have the timer working as an STM32CubeMX project under Platformio (Gasp!). Now, to figure-out how to run just the timer code, as an Arduino library.


26/05/24 – Finally! As an Arduino library, using the Arduino STM32 HardwareTimer library, may I present, An up to 8 Positive-Pulse PWM Servo Driver.

Okay, 8 Positive-Pulse PWM Servo Driver library for Arduino, now integrated with I2C control of remaining mecanum robot functionality. Works great. Login to the Raspberry Pi 2W and type ‘i2c_master –SET_SERVO 127’, and hear the tiny 9g servo zip to it’s centre. No discernible latency, whatsoever!

Later: Fixed a sequencing error in the lighting system, and added a low-pass filter to the stream of battery voltage measurements. The battery voltage readings were very noisy when all four mecanum motors ran, and adding a couple of 1uF ceramics across the ADC input didn’t help much.


28/05/24 – Have build drivers for, and debugged both the HMC5833L magnetometer, and the VL53L1 time of flight distance sensor. Both of these have been integrated into the i2c_master program, that runs on the Pi Zero 2W. The three nodes on the Pi Zero 2W’s mastered i2c network are, the STM32 acting as real-time dog’s-body, the TOF distance sensor, and the magnetometer compass.

Now, we need to expand and modify, the PHP file that calls the i2c_master program, with parameters based on the webserver PHP file’s HTTP GET request.

Later:


30/05/24 – Whilst prototyping new ideas for the WiFi FPV Robot’s main webpage, we’ve discovered an issue.

i2c runs fine for a time, but then there’s the inevitable crash. The Pi Zero 2W hosted i2c_master runs afresh every repeated invocation, so that’s not primarily suspicious.

The error appears to occur for voltage retrieval, with associated voltage reports of -0.1, and 0.0. Everything stops as far as i2c comms goes, and there’s a strange pattern on the i2c lines:

So, which is it? The i2c slave code gone screwy, or the Raspberry Pi Zero 2W’s i2c comms subsystem that needs a reset? Nothing in dmesg. Thinking caps on.

Later: Optimised one bit of code in i2c_master, that prints the battery voltage as program output. After that, and running the webserver only, and not invoking the windowing subsystem, all the i2c problems went away.

All systems are go for completion of the final web interface. Prolly should include some mecanum moves, that in hindsight would benefit completion of the joystick interface, and with which previously I hadn’t dealt.


1/06/24 – Finalised and tested the Mecanum movement set, and all associated control code. Working on expanding the web browser UI section that reports status, to nine units of real-time data, plus an additional reboot button. But not tonight.


1/06/24 – Got the entire instrument panel working, as well as lights control, gear changing, and control of the servo position. Tiny bit of tidying up here to do.


4/06/24 – In addition to a complete instrument set, all code for movement based on joystick inputs is complete.

i2c is back to plague me. Push it too fast, and it falls over. Plan is to optimise some sections of code, and see if that doesn’t get me the CPU needed for i2c stability. I’ve done zero optimisation on this project, wanting to see what the STM32F103CB could do. Honestly, I’m surprised it’s coping with almost exclusively floating point math.


5/06/24 – Not knowing where to start with the i2c fault, I’ve gone off isolating potential problem areas, and carefully observing the results. It turns out I have a flawless i2c link when battery voltage is 8.1V, and an almost instantaneously broken one at 7.1V. In probing around at some voltages, I found that the ground level on my PI’s mounting board, is in difference to the one on my Blue Pill +. I expect I’ll have something driveable, as soon as I fix that.

But that will likely be body-off-chassis surgery to rectify that, so tomorrow will have to do.

Later: …and that turned out to be a wild goose chase. Still no i2c resolution.


6/06/24 – Starting to think that the STM32 Arduino Wire library may be the cause. I’ve isolated every subsystem, and twiddled every conceivable contention source, yet i2c remains unstable. If I can’t manage a graceful fault recovery, then we may be looking at a native STM32CubeMX re-wite.

Very limiting, is the discovery that the STM32 Arduino Wire library is deficient. Ordinary Arduino Wire calls, that might have gotten me out of i2c peril, just aren’t implemented in the STM32 version. Can I paste-in some low-level operations, inside the Arduino code?


10/06/24 – Narrowed the i2c problem down to Adafruit’s NeoPixel library, with it’s STM32 code turning off interrupts for the entirety of the time it emits pixel commands (breaking i2c), and screwing with the SysTick timer. Curious that it works at all.

May have to code a suitable replacement. Could cheat, and throw an Arduino Pro Mini at the problem, then go nuts coding extra lighting effects? No, we’ll persevere with the STM32F103CB for now.


16/06/24 – Working on an Arduino compatible WS2812 NeoPixel driver, that doesn’t screw with either the SysTick timer, interrupts or exceptions. DMA fed PWM timers are out of the picture, as Arduino’s use of HAL calls makes this impractical. Yet, I have one trick left up my sleeve, and it involves (ab)using the STM32’s DWT counter. I’ll wanna take my time and get it right, as so many other Arduino users find themselves with similar NeoPixel driver issues.