# 2 posts tagged with "hardware"

View All Tags

## Create falling sand simulation

Hey everyone, I've got a super cool project to share with you - a falling sand simulation.

So, I was just chilling, watching some YouTube videos, when I stumbled upon this awesome falling sand coding challenge. I thought, why not bring this magic to our SwiftIO Playground Kit? (The Swift core team is actively developing embedded Swift, and I'd like to introduce you the potential of embedded Swift programming through hands-on projects.)

Here's the plan: I use a button to spray sand and a potentiometer to control where it goes. Turn the knob, press the button, and boom! A beautiful sand scene on my tiny screen. So, I set up the kit next to my computer and dive right in.

## TL;DR​

Here's a breakdown of the development process in 7 steps:

2. Move it
4. Create sand with the sprayer
5. Create natural sandpiles

Let's go through them step by step.

## 1. Add one sand particle​

Picture this: the screen is like a giant canvas, divided into a grid where each square represents a single particle of sand. As the sand moves, it jumps from one square to another. To keep track of these squares, I’ve organized them into a 2D array of rows and columns. A specific square is referred to as `grid[rowIndex][columnIndex]`.

Each square in the array is labeled as either having sand (1) or being empty (0). At the start, it's all 0 because, well, there is no sand yet. So, I randomly picked a square and switched its status to 1. Then, I drew a red square on that spot to mark the initial sand particle.

## 2. Move it​

To move a sand particle downward, I just need to draw it on the square below and clear its current position. But, what if the square below isn't empty? It gets blocked and stays put.

The trick is to check the states of all squares. If a square isn't empty, I looked below to determine if the sand can move or not.

Ah, the first problem emerged! While iterating and updating grid states, an error popped up. Drawing from experience, I suspected it might be an array out-of-index issue. And indeed, that's the case.

When iterating through the cells in the last row to determine movement, each one needs to reference the one below it. But alas, there are no cells below the last row! Additionally, no need to check that row, as it's already at the bottom🤨. The solution? Simply skip the last row during iteration.

Let's take a break from the sand and shift our attention to the sprayer. Positioned at the top of the screen, it's set to smoothly slide left or right in response to my potentiometer twist.

To make this happen, I created a square matching the size of all other squares. This way, the first row of the grid is solely dedicated to the sprayer's movements. The potentiometer readings are mapped to the cell index, determining the sprayer's position.

Oh, wait… sometimes the sprayer drifted back and forth 🫨.

This issue often arises when dealing with a potentiometer, as its readings can fluctuate and be mapped to different values. To avoid this, I opted to take an average reading.

## 4. Create sand with the sprayer​

Now, let's bring the sprayer and sand together. The initial random sand particle was no longer necessary. I was ready to generate sand!

To kick things off, I needed a trigger condition for sand generation. So, I introduced a button, and when pressed, sand generation began. The new sand particles would appear below the sprayer, specifically in the second row.

However, if sand particles were created endlessly while the button is held down, it could overcrowd my tiny screen. To prevent this, I added a small gap before each new sand particle.

As the number of sand particles increased, I noticed an illogical aspect of my sand falling mechanism. If the square below the current sand was not empty, the current sand remained still, while the sand particle below it might fall when it was its turn.

To address this, I reversed the iteration of rows in my algorithm. Thus, the sand particle below would be moved downward to clear the square in advance if possible, allowing the current particle to fall successfully.

## 5. Create natural sandpiles​

Currently, the sand particles would stop if the squares below them were filled. As a result, they piled up vertically, which appeared unnatural. In reality, sand continues to spread to the sides of the pile instead of stacking vertically.

If the square below is not empty, it's time to examine the states of the squares to the right and left of it. To prevent the sand from moving exclusively to the left or right, I introduced some randomness to determine the direction each time.

And voila! The falling sand simulation is complete.

Now, it was time to elevate the visual effects.

The sprayer only added one sand particle at a time, which wasn’t particularly striking. To enhance the visual impact, I increased the number of sand particles added each time within a certain range. The squares within that range were chosen randomly.

A monochrome scene can be rather dull... I’d like to inject some colors! It's quite straightforward. Instead of just using binary values of 1 and 0, update the grid state with color values. Ta-da!

## Code​

Well, folks, there you have it. Below is my code.

You can find it on GitHub. Feel free to download and give it a try. Happy coding!

``import SwiftIOimport MadBoardimport ST7789// Initialize the SPI pin and the digital pins for the LCD.let bl = DigitalOut(Id.D2)let rst = DigitalOut(Id.D12)let dc = DigitalOut(Id.D13)let cs = DigitalOut(Id.D5)let spi = SPI(Id.SPI0, speed: 30_000_000)// Initialize the LCD using the pins above. Rotate the screen to keep the original at the upper left.let screen = ST7789(spi: spi, cs: cs, dc: dc, rst: rst, bl: bl, rotation: .angle90)let cursor = AnalogIn(Id.A0)let button = DigitalIn(Id.D1)var pressCount = 0var sand = Sand(screen: screen, cursor: cursor)while true {    // Add more sand particles if the button is been pressed.    if pressCount > 10 {                sand.drawNewSand()        pressCount = 0    }    if button.read() {        pressCount += 1    } else {        pressCount = 0    }        sleep(ms: 5)    // Update the position of sand and cursor over time.    sand.update(cursor: cursor)}``

## How did I debug I2C communication failure?

I personally find the SPI protocol to be more favorable than I2C, as the I2C protocol has several additional features that make the protocol more complex to implement and more prone to communication errors. Recently, a member, Jimmy, in our discord community encountered an I2C communication failure. So I researched the issue in more depth to understand and solve the problem. I would like to share my findings.

## What's the problem​

A 1602 LCD screen that was connected to the I2C interface was displaying an incrementing value over time. However, unexpectedly, after an indeterminate period, the screen froze and stopped displaying the updated value.

## How to find out the cause​

### Step 1​

To understand the cause of the problem with the 1602 LCD screen, I decided to observe the I2C signals. To do this, I added a digital trigger pin and configured it to go low when an error occurs. This would allow me to visualize the I2C signals and detect any issues with the communication. Here is my test code:

``import SwiftIOimport MadBoardimport LCD1602@mainpublic struct I2CIssue {    public static func main() {        var seconds = 0        let i2c = I2C(Id.I2C0)        let lcd = LCD1602(i2c)        lcd.write(x: 0, y: 0, "Hello SwiftIO!")        let trigger = DigitalOut(Id.D0)        trigger.high()        var ret = true        while true {            seconds += 1            sleep(ms: 20)            // Display the new value on the LCD.            ret = lcd.write(x: 0, y: 1, "\(seconds)s")            // If an error happens, change the state on trigger pin.            if ret == false {                trigger.low()                seconds = 0                break            }        }        while true {            sleep(ms: 200)        }    }}``

As shown below, the I2C signal appears to be working normally at first, then an error happens, the I2C reports an I/O error, and the trigger pin is set to low, which is indicated by a yellow dotted line. The last I2C data before the error was sent without any issue, which indicates that something is causing the I2C communication failure.

### Step 2​

The problem with the I2C communication and the LCD screen was difficult to reproduce consistently. Despite multiple attempts, I was unable to consistently replicate the issue, making it hard to pinpoint the exact cause of the failure😔.

Fortunately, I did discover that when other connectors were plugged into the same USB hub as the SwiftIO board, the LCD would stop working. This provided a clue towards identifying the cause of the problem🧐.

Further investigation revealed that the I2C communication would fail when power-consuming devices were connected to the USB hub. This led me to suspect that the issue may be related to a power problem.

### Step 3​

After trying to sample the actual analog voltages on the bus, I FINALLY noticed a small glitch in the signal which causes the I2C communication error.

I discovered that when another device was plugged into the hub, the voltage on the SDA line dropped to around 2.9V, causing the glitch which interfered with the signal. The master device thought that communication was still ongoing on the bus and waited for a stop signal, thereby keeping the I2C in busy mode.

Let's first take a look at I2C. I2C is a two-wire protocol that is used to connect multiple devices to a single bus. It is suitable for short-distance communication.

The I2C bus consists of two lines: the serial data line (SDA) and the serial clock line (SCL). The master device generates the clock signal on the SCL line, and the devices on the bus use this clock to synchronize their communication. Data is transmitted on the SDA line.

Each I2C device has a unique address. The master device can initiate communication with a specific slave device by sending its address, and the slave device will respond if it matches the address. Then, the master device can send or request data from the slave device, which is transmitted on the SDA line.

I2C is designed for short-distance communication, typically on a single PCB (printed circuit board). Longer bus lines can have more noise and crosstalk that can affect the signal integrity and cause errors.

### Push-pull and open-drain​

The I2C uses open-drain configuration. There are two kinds: push-pull and open-drain:

• A push-pull output can both source and sink current. This is how it got its name since it pushes the signal high and pulls it low.

In a push-pull circuit, two active devices are used to drive a load. One device is used to "push" current into the load, while the other device is used to "pull" current out of the load. The two devices switch back and forth, following the internal signal, to create the output.

It can drive a signal over a longer distance and have less susceptibility to noise compared to open-drain outputs.

• In contrast, an open-drain output can only sink current.

An active device is used to pull the output voltage to a low state, but does not actively drive it to a high state. It acts like a switch that connects the signal line to the ground, pulling the voltage level of the signal line low. This is called "drain" because it is "draining" current away from the signal line. And if it is turned off, the signal line is in an "open" state, not connected to either power or ground. This means that there is no current flowing through the line and it would float.

To drive the signal high, an external pull-up resistor can be used to connect it to the high voltage level (Vcc), which will pull the output high when no other device is actively driving the signal. This means that the current flowing through the pull-up resistor is sourced by the voltage source, not by the open-drain output.

The use of open-drain outputs is useful in situations where multiple devices need to share a single communication line, such as the I2C bus.

### I2C Pull-up resistor​

I2C bus uses open-drain output, hence it needs external pull-up resistors.

The value of the pull-up resistors can affect the charging and discharging time of the bus capacitance, which in turn can affect the rise time of the signals on the bus. The capacitance refers to the total capacitance present on the SDA and SCL lines, including the parasitic capacitance of the devices and any additional capacitors that may be present. It makes the voltage level on the two lines cannot change instantaneously. When a device changes the line state, it causes a charging or discharging process of the bus capacitance, which takes a certain amount of time known as the rise time and fall time.

Why the falling time of a signal is usually shorter than the rising time? When a device pulls the SDA or SCL line low, the bus capacitance is effectively discharged through the device's open-drain output. Since the output is actively pulling the line low, the transistor acts as a switch with very low internal resistance and the discharge time is relatively short.

When a device releases the SDA or SCL line, the bus capacitance is charged through the pull-up resistor. Since the device is no longer actively pulling the line low, the charge time is determined by the value of the pull-up resistor and the total capacitance of the bus. A higher value pull-up resistor or larger bus capacitance results in a longer charge time, and therefore a longer rising time.

• A "strong" pull-up is one with relatively low resistance. It allows for a faster charging of the bus capacitance when the lines are released, which results in a faster bus speed and better performance in high-speed I2C applications. However, it also increases the power consumption on the bus.

• A "weak" pull-up is one with relatively high resistance, which increases the charging time of the bus capacitance when the lines are released. This can result in slower communication speeds and a higher probability of errors on the bus. It may be suitable for low-speed or low-power I2C applications.

By default, the I2C interfaces on the SwiftIO board have 4.7kΩ pull-up resistors. So you don't have to add external pull-up resistors when connecting other I2C devices.

## Solution​

Returning to the issue at hand, it was established that the I2C signal can be easily affected by external noises and disturbances. After further investigation, I discovered that the MCU has an I2C glitch filter feature that can be enabled to prevent these types of errors.

The I2C glitch filter is a useful feature that helps to prevent errors in communication caused by short, unwanted pulses or glitches on the SDA and SCL lines of the I2C bus. It is typically set to ignore pulses that are shorter than a certain duration, for example, in a 1MHz I2C bus, a cycle lasts for 1000ns, with 500ns for the high level and 500ns for the low level. By adding a 400ns glitch filter, any noise or disturbance shorter than 400ns will be filtered out, thus improving the reliability of the I2C communication by reducing the chances of errors caused by unwanted pulses.

After activating the I2C glitch filter and running the test again, the communication is much more stable, indicating that the filter successfully eliminated the unwanted pulses that were causing errors in the communication👏.

## Go further: Schmitt trigger​

I found in the MCU's datasheet that it has an I2C glitch filter built-in, which is specifically designed to filter out unwanted pulses or glitches on the SDA and SCL lines of the I2C interface. Furthermore, it also provides a Schmitt trigger for the General Purpose Input/Output (GPIO) pins to filter out external noise and improve signal integrity.

In a digital input circuit, the input signal is typically an analog signal, such as a voltage, which needs to be converted into a digital signal that can be understood by the digital logic of the system. Schmitt triggers are commonly used in digital input circuits to provide noise immunity and improve signal quality. It compares the input signal to two different threshold voltages, typically an upper threshold and a lower threshold. When the input voltage exceeds the upper threshold, the output goes high. When the input voltage falls below the lower threshold, the output goes low.

Since the Schmitt trigger has hysteresis, the threshold voltages between high and low states, there is a range of input voltage where the state doesn't change even though the input voltage is changing. This property allows the Schmitt trigger to ignore small voltage fluctuations that would otherwise cause false triggers.

For example, after a mechanical switch is pressed, the voltage may fluctuate for a certain period near the center threshold before settling in its final state. These fluctuations near the center threshold can be interpreted as multiple pulses. For example, once the voltage passes the center threshold, it is considered high, and if it falls a bit below that threshold, it becomes low again. This can cause errors in the digital signal, and the Schmitt trigger helps to filter out these unwanted pulses and ensure a clean transition in the signal.

• If the button is pressed (or released depending on your circuit), after the input voltage rises above the upper threshold, the Schmitt trigger's output changes to a high level, indicating that the button has been released.
• When the button is released (or pressed depending on your circuit), after the input voltage falls below the lower threshold, the Schmitt trigger's output changes to a low level, indicating that the button has been pressed.

Therefore, it ensures that the input is interpreted as a single, clean transition.

While Schmitt triggers are often effective at suppressing noise on digital input signals, there may still be some noise present even after adding a Schmitt trigger to the circuit. This may be due to the sufficient hysteresis of the Schmitt trigger to filter out all the noise present on the input signal. Or the amplitude of the noise on the input signal may be larger than the hysteresis of the Schmitt trigger, making it impossible for the circuit to filter it out. Therefore, a combination of different types of filters or even other software debounce techniques may be needed to achieve the desired level of noise suppression.

The MCU has the Schmitt trigger on all GPIOs. It's configured by default, I cannot change its setting but only turn on/off it. So there may be still some noises when using these pins. So when I am working with a button, I tend to add a simple RC filter, made up of a resistor and a capacitor, for button debounce.