Simulating Diffusion-Limited Aggregation with a Raspberry PI RP2040 MCU
A bolt of lightning flashes across the sky and scientists marvel at diffusion-limited aggregation, a process in which random moving particles join to form static clusters. Three Cornell University students, Angela, Nathaniel and William, use an RP2040 and an inertial measurement unit to build a cyclic DLA simulator to tap into technology’s ability to shed insight on natural processes like the formation of lightning.
The formation of snowflakes, the growth of crystals, and the path taken by lightning are all examples of natural phenomena can be modeled by diffusion limited aggregation (DLA), the process by which particles undergo a random walk and cluster together. Inspired by technology’s ability to help us better understand natural processes, we built an interactive, diffusion-limited aggregation simulator as our final project for Cornell University’s Digital System Design using Microcontrollers class. We augmented with motion controls that enabled users to manipulate the behavior of our simulated particles.
What Is DLA? Diffusion-limited aggregation models systems in which particle transport occurs primarily through diffusion, and particles tend to cluster around a pre-existing aggregate. DLA can model systems such as dielectric discharge, mineral aggregation, and even snowflake formation, an example of which is shown on a frosty window in Figure 1.
DLA models diffusion by simulating Brownian motion of particles. In a given time step, particles move by an amount sampled from a random normal distribution. The equation for the probability distribution of a normal distribution is shown below, where depends on the time step and simulation parameters. The 0 in the exponent expresses the notion that a particle is equally likely to go in one direction as it is the other.
At each time step, DLA dictates conditions for when a particle aggregates. In the standard DLA formulation, a particle aggregates if it collides with an adjacent aggregated particle. Each particle moves randomly under Brownian motion until they aggregate, at which time the particles will remain aggregated and do not change position for the remainder of the simulation. An example can be seen in Figure 2.

A representation of a free particle aggregating upon collision with a pre-existing aggregate.
In practice, Brownian motion dictates that particles slowly drift from their initial locations at a velocity proportional to the square root of time elapsed. The movement of a single particle appears chaotic and random, but over time, from the randomness of many particles, predictable patterns and fractal-like structures can emerge when particles cluster onto an aggregate, as shown in Figure 3.

Image of VGA display executing our DLA project. The bright green particles are part of the aggregate, while the dim green particles move freely.
Contrary to the standard DLA simulation, where particles aggregate permanently, “cyclic DLA” [1] adds a “decay” component. After aggregating, a particle will decay according to some decay factor and “break free” from its aggregate, resuming its Brownian motion until it aggregates again. A cyclic element introduces interesting emergent properties in simulations, depending on the rate of decay. In particular, small, self-sustaining clusters of aggregate can form that tend to remain separate from other clusters.
We added a dimming effect to our simulation to convey our cyclic decay effect. Particles dim the longer they are part of the aggregate, until they eventually detach from the aggregate and resume Brownian motion. Freely moving, detached particles are displayed as dimmest of all, as shown in Figure 4.

An example of cyclic DLA by our simulation. Note that the oldest particles, toward the center of the aggregate, are the dimmest.
In addition to simulating Brownian motion, detecting collisions, and dimming particles based on their age, our simulator interfaces with “interactive motion controls.” By wearing a custom designed glove, users can tilt their hands to bias particles’ motion (making all the particles tend towards a certain direction), and can shake their hands up and down to increase the particles’ average velocity across a single time step.
HARDWARE
Our simulation ran on both Cortex M0+ cores in the Raspberry Pi RP2040 microcontroller. We utilized a built-in UART channel to interface with command line prompts and used an I2C channel to gather positional data from our inertial measurement unit. We also utilized most of the system’s 264KB of SRAM to store data about particle state and pixel color. We leveraged the RP2040’s Programmable IO ports to implement our VGA driver [2]. These ports connect to stripped-down processors capable of executing programs made of a restricted set of instructions. We offloaded the VGA driver entirely to these PIO ports, freeing up the processor to focus on simulation and user input. We also used the RP2040’s DMA channels to transfer pixel data to the PIO ports without processor intervention.
To complete our VGA driver, we needed to convert our digital PIO port signals (high/low) into an analog signal to be sent along VGA cables. To this end we constructed an R-2R digital-to-analog converter (DAC) to drive the color signal going into our VGA port. Due to memory constraints, our simulator was limited to using 4 bits to convey color information. We chose to use all 4 bits to drive a single channel, green. Our R-2R DAC ensured that each of these 4 bits contributed an appropriate amount of voltage to the VGA input. As shown in the schematic diagram in Figure 5, each resistor in our DAC had approximately double the resistance of the previous line. This meant that the most significant bit contributed approximately double the voltage of the second-most significant bit, and so on.
Our final piece of hardware external to the microcontroller was an inertial measurement unit (IMU), a device that uses gyroscopes, accelerometers, and sometimes magnetometers to measure and report a body’s angular rate and specific force, and sometimes orientation. We attached an MPU-6050 IMU to the back side of a glove, as a means of controlling various parameters of the simulation. Tilting one’s hand influenced the direction in which particles traveled, on average, whereas rapidly shaking one’s hand up and down increased the average speed at which particles moved.
SOFTWARE
Our simulator was created by composing various open-source libraries with our own simulator code. In particular, we integrated Adam Dunkel’s protothread library [3] and a modified version of Professor Hunter Adams’ and Bruce Land’s VGA library with our DLA simulator. The code for our project is available for download from Circuit Cellar’s Code and Files webpage.
Protothreads are a lightweight, stackless thread implementation that allow for the concurrent execution of threads. Protothreads are non-preemptive; all context switches happen explicitly after the currently scheduled thread yields itself. In this way, code that uses protothreads remains explicitly event driven and retains a linear-looking control sequence. Each thread requires a mere 2 bytes of memory overhead, which lets us use threads liberally throughout our simulator, despite running into memory limitations as our simulation grew in complexity.
Adams’ & Land’s VGA library controls the timing of VGA’s HSYNC and VSYNC lines via PIO ports. On a 320 x 240 monitor, the HSYNC line is held high for 320 cycles (plus a few cycles to conform to the VGA spec), then is set low for a few cycles, before repeating. Similarly, the VSYNC signal is held high for approximately 240 repetitions of an HSYNC line, before repeating as well. The driver also uses direct memory access to read from a backing pixel array to drive color signals. The use of DMA allowed us to avoid bogging down the processor with data transfer work, freeing it to perform the intensive collision detection and random sampling work.
Our simulator consisted of 8,000 particles bound in a 320×240, two-dimensional grid space. Our particles’ state consisted of position, color, and age. We stored this state in a fixed point representation, to optimize the compute time on our processor. We utilized a single thread on each of two cores to separate user input from simulation computations, and to allow for the easy execution of both threads completely in parallel. We elaborate below on how we used our VGA’s pixel buffer to detect the existence of neighboring aggregated pixels,
Fixed-Point Representations: Fixed-point representations allowed our simulator to perform fractional resolution arithmetic with (fast) integer arithmetic hardware. These fast computations allowed us to maintain a smooth 30 frames per second without getting slowed down by expensive floating point arithmetic operations.
Fixed-point values work by designating some bits as integer bits and other bits as fractional bits. To consider the value that our fixed-point number represents, consider that a bit n places to the left of our decimal contributes a value of 2n-1 to our number, while a bit m to the right contributes 2-m In our case, we divided the 32 bits usually found in integers into 15 integer bits, 16 fractional bits and a sign bit. As an example, this means that a fixed-point number containing all 0s, except for the 15th (0-indexed) bit, represents a value of 2-1 = 0.5.
Fixed-point values can reuse the same operators (and hardware) as integer arithmetic for addition and subtraction. Multiplication and division require some additional overhead in the form of type casts and bit shifts. Conversions between representations of fixed-point, integers, and floats require some casting and bit shifts as well. To see where bit shifts come into play, consider that in our fixed-point representation a 1 is represented by a single high bit in the 16th digit. To convert this to an integer, we can simply right shift by 16 our fixed-point representation. This would leave us with a 1 in the 0th bit, and 0 elsewhere.
We model diffusion, the first half of DLA, using Brownian motion. Brownian motion, in the ideal, can be simulated by sampling from a normal distribution once per time step, and updating the position of a particle based on that sample. Unfortunately, generating normal distributions efficiently is not always easy. To avoid computing a computationally expensive normal distribution sampling at every time step, we instead used the C standard library rand() function, which samples a uniform distribution at each time step, and updates particles’ positions based on that value. While this may seem to imply that our particle motion is not Brownian, over many time steps, the motion of a given particle will approximate a normal distribution. This is a result of the Central Limit Theorem, which states that the mean of any large enough sample approaches a normal distribution, regardless of the underlying sample’s distribution.
Because our particles are updated 30 times a second, and the sampling distribution tends to become normal over time, we can get a good approximation of Brownian motion with this uniform distribution. Figure 7 shows the empirical probability distribution of displacement of a particle over 15 time steps (equivalent to half a second), using this “sum of uniform samples” method.

Probability distribution using the “sum of uniform samples” method. The blue represents the measured sample. The orange line represents the expected normal distribution.
We took acceleration measurements from our IMU to implement motion tracking. Our IMU transferred measurements over I2C to a buffer containing raw acceleration data at a rate of exactly 30Hz. This acceleration data was then low-passed in software to filter out noise, and converted to fixed point to enable fast arithmetic.
In particular, we were interested in rotation around the x-axis (in the direction one is facing) and in the y-axis (to the left or right). To calculate the orientation of our IMU, and by extension our glove, we needed to divide acceleration readings in the x/y axis by acceleration in the z-axis. An inverse tangent can provide the angle of rotation around an axis, provided the rotation isn’t too extreme (Figure 8).

Visualization of angle calculation using accelerometer data. In this case, θ about the z-axis can be computed via acceleration data in the x and y axes.
In addition to orientation, we wanted to know when users were shaking their hands up and down. To this end, we kept track of a history of our z-acceleration readings across frame of ~2/3 seconds. This time frame was large enough to reduce the noise in our variance calculation while being small enough to still feel responsive to changes.
Readings from the IMU and simulation parameters were processed and modified in real time. In particular, we implemented particle skew by shifting the mean of the normal distribution describing the movement of particles based on the orientation of the glove. So, tilting one’s hand to the left would make particles, on average, move to the left, and tilting one’s hand to the right would make the particles move to the right. We implemented variable particle speed by setting the maximum speed of the particles based on the variance of measured z acceleration, which effectively modifies the variance of the normal distribution from which we sample the distance to move in a single time step. Thus, the faster the user’s hand was shaken, the greater the variance of the z acceleration, and the wider the range from which our uniform distribution was taken. The set-up of the glove and IMU are shown in Figure 9.
We simulated aggregation, the second half of DLA, by implementing collision detection with the help of our fixed-points, an alpha-max beta-min square root approximation algorithm, and our pixel backing array (Figure 10). During the update step of each particle during each time step, a collision-detection algorithm was run to determine if the particle should aggregate or continue its Brownian motion. If a particle would have collided with any aggregate on its way to its new location, the particle was added to the aggregate at that location.
Our fixed-point representation allowed us to represent a particle’s location in decimal increments, as opposed to being completely aligned to our pixel-grid. With proper rounding logic this allowed us to keep track of a particle’s location with a precision of pixel-units. This allowed for the motion of our particles to appear smooth, when compared with motion that would be enabled by only using integers to store particle location data.
To detect collisions, we approximate the distance between a particle’s current location and its new desired location using our alpha-max beta-min algorithm, shown in the equation above. We then use this distance to determine an increment, which can be thought of as a vector of unit length in the direction of the particle’s updated location. With the help of this “increment vector,” each pixel between the particle’s current location and new location is checked to see if it is touching the existing aggregate or not. If a pixel is determined to be touching our aggregate, the particle is moved to that pixel (falling short of the intended update location) and it is mutated to be part of the collective aggregate (by changing its color to bright green). If the path between a particle’s current location and new location is free of aggregate, the particle is moved to the intended update location and remains “active” (as opposed to aggregated).
Consider Figure 10, where the dark green particle is projected to move 3 pixels to the right (call this dx) and 4 pixels up (dy), as determined by sampling from our uniform distribution. The lighter green particle is an aggregated particle. To check for a particle collision, we normalize dx and dy by dividing each by the distance of the arrow. Then, in a for-loop, we check at each normalized dx and dy point along the arrow for a collision, rounding at each point from fixed-point to integer, to access our backing pixel-array.
One can consider that if we only kept a store of particles, collision detection for a single particle would have been an O(n) operation, requiring us to compare every other pixel’s location with the current pixel we are examining. To reduce the complexity of our collision detection, we rely on the fact that our backing pixel array also holds information about the state of our aggregate. In particular, the pixels where the aggregate is located are bright green, compared to black/dark green where our aggregate is not. Since a particle location exactly correlates with the pixel at that location, collision detection can be reduced to a constant time operation by examining the color of neighboring pixels within the backing pixel array.
BUG HUNT
Throughout the design process, we encountered quite a few interesting bugs. We thought that discussing them could be helpful for others doing projects with microcontroller design.
Rotten Randomness: Before settling on approximating a normal distribution over time by sampling from a uniform distribution, we attempted to sample from a normal distribution for every particle, once a frame. One approach involved averaging over multiple calls to rand() to approximate a normal distribution within a single frame. However, performing tens of function calls per particle severely limited the speed of our simulation. Another approach involved concatenating bits read from the RP 2040’s ring oscillator clock (ROSC), which would allow us to generate a normal by combining this ROSC with the RP2040’s DMA channels, at little or no cost to the CPU.
Although the second approach is particularly attractive due to the minimal CPU overhead, testing revealed that the simple approach that we used—generating a normal distribution “over time”—simulated well, and was both pleasant to interact with via motion controls, and behaved in line with other DLA simulations. For this reason, we were happy to keep using rand() and move on to other parts of our system.
Polling Problems: Initially, polling our IMU at a rate of 1,000Hz via a repeating alarm timer led to our simulation crashing shortly after start-up. The root cause of these issues was unclear, because they persisted even when moving our repeating alarm timer to a different core. This went against our initial suspicion that our interrupts were interfering with in-flight writes/reads to our backing pixel array, which may have eventually led to the reading of garbage data which soft-locked our program.
To resolve this, we moved our IMU polling trigger to occur within our simulation protothread. This meant that no calculations or pixel updates could be interrupted and guaranteed the sequentiality of our polling-to-simulate step.
Moving our IMU polling trigger to our simulation protothread meant that our IMU was only polled 30 times a second, instead of 1,000. However, we found that this frequency still provided accurate-enough readings for our motion controls to feel responsive.
Aggravating Angle Assessment: During testing, we noticed that when we rotated our IMU to almost 90° along the x-axis, the rotational measurements of our y-axis became inaccurate. The same occurred if we swapped the axes of rotation. We learned that using acceleration along axes is limited, in that at extreme angles we lose a degree of information. For example, say we wanted to obtain data from rotating around the y-axis, which, under expected operating circumstances, would look like the left side of Figure 11. We would calculate rotation around the y-axis by comparing z and x-axis accelerations.

Example of IMU angle measurement limitation. On the left side of the figure, rotation around the y-axis can be calculated as a ratio between z and x acceleration. On the right side, acceleration around the z and x axes are near 0.
Consider the extreme situation on the right of Figure 11, where our y-axis is now pointing up (z-axis pointing towards us, x-axis pointing to the right). Rotation around the y-axis no longer changes the acceleration experienced in both the x-axis and z-axis; rather, both remain close to 0. This makes measurement of rotation around y very difficult and sensitive to noise.
For our project, users did not often reach rotations of 90°, since doing so was quite uncomfortable with our glove. So, losing orientation information was not an issue in practice, but instead was an interesting lesson in limitations of calculating orientation via acceleration.
Restrictive Rounding: When shifting the mean of our uniform distribution based on the tilt of our IMU, we performed fixed-point arithmetic for the sake of computational speed, and then converted values to integers. Our initial system took into account the sign of our tilt, and shifted the mean of our distribution accordingly.
Because of the way our fixed-to-integer conversion works, numbers were rounded differently, depending on their sign. Namely, fixed-point representations were converted to integers by right shifting >>. This meant that integer values were truncated, not rounded. This had an effect on the magnitude of a number, after truncation based on its sign. For example, 4.3 is truncated to 4 whereas -4.3 is truncated to -5. This meant that our mean was incorrectly being biased toward negative numbers. Although a seemingly minor problem, the bias was apparent in our simulation as particles tending toward the top left, even when our IMU was held flat.
To fix this, we negated some fixed-point numbers before truncating them and negating them again. In this way, our truncation was “symmetrical” on both positive and negative fixed-point numbers.
MOVING FORWARD
First, it would be interesting to improve our VGA driver to allow for higher resolution and color fidelity. It seems like we could fairly easily increase our resolution to 640 x 480, which just about stretches the limits of our 264KB of SRAM. Further fidelity increases, like expanding our color-palette, could perhaps be achieved by integrating off-chip memory.
Second, if we increased color fidelity, we could enhance our simulation by having older particles change color, instead of just becoming dimmer. We imagine this would give rise to even more interesting and aesthetically pleasing emergent properties.
Third, more memory would allow us to increase the number of particles we simulate, until we become computationally constrained and fail to simulate the motion of all particles within a single frame update. More particles would also allow us to increase the resolution of our simulation.
— ADVERTISMENT—
—Advertise Here—
Finally, additional optimizations could reduce computation time, allowing us to further eke out possible resolution increases.
At some point, however, all interesting projects must end. Still, we can imagine taking the lessons we learned here and using them to create bigger and better particle simulations in the future.
RESOURCES
Raspberry PI | www.raspberrypi.com
REFERENCES
[1] Cyclic Diffusion-Limited Aggregation: Real-time natural pattern generation:
https://ciphrd.com/2020/07/21/cyclic-diffusion-limited-aggregation/
[2] VGA Driver: https://vanhunteradams.com/Pico/VGA/VGA.html
[3] Adam Dunkels Protothread Library: https://dunkels.com/adam/pt/
PUBLISHED IN CIRCUIT CELLAR MAGAZINE • NOVEMBER 2024 #412 – Get a PDF of the issue
Sponsor this ArticleAngela Cui is currently studying Electrical and Computer Engineering at Cornell University. She is interested in computer architecture with a focus on domain-specific accelerators.
Nathaniel Navarro is interested in hardware software interfaces and compilers. He recently graduated from Cornell with a degree in Computer Science and is currently working in California. He plans to pursue graduate studies soon.
William Yoon is a Master of Engineering student in electrical and computer engineering at Cornell, with interests in embedded systems and backend development.







