Input Devices

I was impressed by how interesting this week was. Reflecting on week 04, when we created our PCB, I had doubts about whether the XIAORP 2040 microcontroller had functions beyond turning an LED on or off, and it turns out it does. The objective of this week was to add an input or output device to the PCB we created. After considering which device to attach to my XIAO, I finally decided to utilize the 3 LEDs I had previously implemented on my board and added an ultrasonic sensor. The LEDs will light up periodically depending on the distance of the object detected by the sensor.

Xiao RP2040

The pins used on the XIAO RP2040 microcontroller were D4 and D5, where the Echo was assigned to input D5 and the TRIG to output D4.

Previously, the designated pins for the LEDs were D0, D7, and D6, and I decided to keep those pins because the LEDs are connected there.

HC-SR04 Ultrasonic Distance Sensor

The HC-SR04 ultrasonic distance sensor measures the distance to an object using ultrasonic waves. It works by emitting an ultrasonic pulse from its TRIG pin and measuring the time it takes to bounce back and return to the ECHO pin. To use it with Arduino, connect VCC to 5V, GND to ground, TRIG to a digital pin (in this case, pin D4), and ECHO to another digital pin (in this case, D5). This sensor is very common in Arduino projects, especially in robotics, security systems, and automation, due to its ease of use and accuracy in distance measurement.

Connections

The connections are simple, it connects to the corresponding pins of the XIAORP2040

  • Orange cable is the Echo which go to D5 digital pin from the XIAORP2040
  • Yellow cable is Trigger and go to D4 digital pin
  • Red is ground
  • Brown is 5v voltage

Programming

I decided to use Arduino for the code because I am more familiar with it. In summary, the code measures a distance in cm. In this case, there will be three specific distances: 20 cm, 50 cm, and 90 cm. Depending on each distance, it will perform the following actions:

  • If the distance is less than 20cm ALL the lights will turn on
  • If the distance is between 21cm and 50cm TWO lights will be turn on
  • If the distance is between 51cm and 90cm ONE light will be turn on
  • If the distance is more than 90cm NONE lights will be turn on

Here we have the code with its respective comments explaining how the code works:

Final result

Once the program has been compiled, we will upload it to the XIAO RP2040 and test its functionality.

Less than 20cm

As you can see, all the lights turn on if the sensor detects an object less than 20cm

21cm to 50cm

Here you can see that there is a distance of 42cm and two lights are on

51cm to 90cm

Only one light is on from a distance of 58cm

More than 90cm

No light turns on with a distance greater than 90cm