© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
A. SuberoProgramming Microcontrollers with Pythonhttps://doi.org/10.1007/978-1-4842-7058-5_10

10. Python MCU Interfacing

Armstrong Subero1  
(1)
Basse Terre, Moruga, Trinidad and Tobago
 

Congratulations! If you made it so far, then you will have covered the basics you need to work with microcontrollers and Python. We have come a long way, but we are not done yet. In this chapter, we will look at using a microcontroller running CircuitPython to interface with some common sensors. The topic of interfacing sensors can cover an entire volume. However, as you go on to building your own projects, there are some sensors you may want to use; in this chapter, we cover sensors you are likely to want to use in your projects.

RGB LED

If you think LEDs are great, then I have a sensor that will knock your socks off. Sometimes, you cannot decide on the color of LED to put in your projects. In such a scenario, we would need to use an LED that contains three LEDs in one package. This is the red, green, and blue or RGB LED. The RGB LED is pictured in Figure 10-1.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig1_HTML.jpg
Figure 10-1

RGB LED Credit: Adafruit, Adafruit.com

As we learned in our chapter on displays, using the colors red, green, and blue, we will be able to produce any color of light. RGB LEDs have one red, one green, and one blue LED in the same package. Using RGB LEDs, we will be able to produce almost any color of LED we can think of. This makes them great for things like indicators. Instead of having multiple LEDs to relay information, we can have one LED and just vary its color.

The RGB LED has four pins, and the LED may be a common anode or a common cathode. If we look at the RGB LED, we will observe that one pin is longer than the other pins. This long pin can either be connected to the anode or to the cathode of our power supply.

RGB LED with MCU Schematic

We connect the circuit as is shown in Figure 10-2. Our RGB LED is connected to pins D10, D11, and D12. This schematic assumes a common cathode RGB LED is used. If you are using a common anode LED, the longest pin would be connected to VCC instead of the ground.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig2_HTML.jpg
Figure 10-2

RGB LED with MCU Schematic

Note how we use three resistors, since each LED in the package must still be treated like one individual device.

RGB LED Circuit Connection Tips

These are the recommended steps to connect the circuit:
  1. 1.

    Connect the long common pin of your RGB LED to either VCC or the ground depending on which version you have.

     
  2. 2.

    Connect the remaining three short pins to pins D10, D11, and D12, respectively, using 1k resistors.

     
When you are finished connecting your circuit, it should look like Figure 10-3.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig3_HTML.jpg
Figure 10-3

RGB LED with MCU on Breadboard

Libraries We’ll Need

These are the libraries we will need to add to our lib folder:
  • adafruit_rgbled

  • simpleio

RGB LED with CircuitPython Program

We can then open our code.py file in the Mu editor so that it resembles Listing 10-1.
# import board library
import board
# import time library
import time
# import library for RGB led
(1) import adafruit_rgbled
# setup pin constants
(2) RED_LED = board.D10
GREEN_LED = board.D11
BLUE_LED = board.D12
# create a RGB LED object
# invert pwm = false if common cathode
#              true common anode
(3) rgbLed = adafruit_rgbled.RGBLED(RED_LED, GREEN_LED, BLUE_LED, invert_pwm=False)
(4) while True:
    # turn on red
    rgbLed.color = (128, 0, 0)
    time.sleep(1)
    # turn on green
    rgbLed.color = (0, 128, 0)
    time.sleep(1)
    # turn on blue
    rgbLed.color = (0, 0, 128)
    time.sleep(1)
    # mix 1
    rgbLed.color = (100, 0, 204)
    time.sleep(1)
    # mix 2
    rgbLed.color = (90, 20, 0)
    time.sleep(1)
Listing 10-1

MCU with RGB LED Program

We import the modules to set up our board for use. At (1) we import the adafruit_rgbled library which will allow us to control the LED. After we have done this, at (2) then we set up constants for our pin that represents each LED. After this is done, we create an RGB LED object at (3). In our main loop at (4), this object is used where we turn on each individual LED one at a time, red, then green, and then blue for one second each. Then we practice mixing color values.

HC-SR04

Sometimes, you need to measure distance for whatever reason. If you are building a microcontroller-based mobile robot, for instance, you will need to be able to control the direction the robot drives. Using a sensor, to measure the distance the robot is from the object we are using, we can create a semi-intelligent robot. There are two ways we can measure distance, which are using light and sound. Using light is difficult since it is subject to interference from ambient light in the environment. There are resilient light sensors like LIDAR-based sensors; however, these are expensive to integrate into projects. A nice low-cost solution is to use sound. The most used sound sensor is the HC-SR04 sensor which uses ultrasound to measure distance. This sensor is seen in Figure 10-4.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig4_HTML.jpg
Figure 10-4

HC-SR04 Ultrasonic SensorCredit: Adafruit, adafruit.com

The sensor has four pins which are the VCC, GND, a trigger pin, and an echo pin. The device has two ultrasonic transducers. One of the transducers transmits an ultrasonic pulse, and the other device listens for the transmitted pulses. The sensor can measure a distance from 2 cm to 400 cm.

How the sensor works is that the trigger pin (Trig) is used to transmit a pulse from one of the transducers. The echo pin then becomes high when the reflected signal is received. According to the length of the time the device takes to detect a signal on the receive (echo) pin, we can determine the distance of the object we are measuring.

HC-SR04 with MCU Schematic

The circuit connection is given in Figure 10-5. Since the HC-SR04 is a 5-volt device, we need to use a logic level converter to interface it with our CircuitPython MCU. The trigger pin is connected to the MCU via the logic level converter to pin D5, and the echo pin is connected to the MCU via the logic level converter to pin D6.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig5_HTML.jpg
Figure 10-5

Temperature Sensor with MCU Schematic

HC-SR04 Circuit Connection Tips

These are the recommended steps to connect the circuit:
  1. 1.

    Connect the VCC pin of your HC-SR04 sensor to the positive rail.

     
  2. 2.

    Connect the ground pin of the sensor to the ground.

     
  3. 3.

    Connect the Trig pin of the HC-SR04 to HV4 and the echo pin to HV3.

     
  4. 4.

    Connect the LV4 pin of the logic level converter to pin D5 and the LV3 pin to pin D6 of the microcontroller.

     
  5. 5.

    Connect the GND pin of the logic level converter to the negative rail of the breadboard.

     
When you are finished connecting your circuit, it should look like Figure 10-6.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig6_HTML.jpg
Figure 10-6

HC-SR04 with MCU on Breadboard

Libraries We’ll Need

These are the libraries we will need to add to our lib folder:
  • adafruit_hcsr04.mpy

HC-SR04 with CircuitPython Program

Edit your code.py in the Mu editor so that it resembles Listing 10-2. This example is modified from the example provided by Adafruit Industries for reading the sensor.
# import time library
import time
# import board library
import board
# import HCSR04 sensor
(1) import adafruit_hcsr04
# create instance of our HCSR04 object
(2) sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D5, echo_pin=board.D6)
# super loop
(3) while True:
    # try to get the distance
    try:
        print((sonar.distance,))
    # else tell us it failed
    except RuntimeError:
        print("Fail!")
    # wait 0.1s
    time.sleep(0.1)
Listing 10-2

MCU with Temperature Sensor Program

In the program, we do our usual imports, and at (1) we import the library allowing us to use the HC-SR04 sensor. At (2) we create an instance of the HCSR04 object we can manipulate, on pins D5 and D6. At (3) in the main super loop, we have a try catch statement that we use to try to read the sensor, and if it fails, we tell the user that an error has occurred. We see the output of the serial console in Figure 10-7.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig7_HTML.jpg
Figure 10-7

HC-SR04 Sensor Output

As we move our hand closer to the sensor, the distance reading gets smaller, and as we put our hand away, we observe that the distance reading gets larger.

Piezo Speaker

If you have ever used a microwave or an ATM, you are sure to have heard the electronic beeping that is created from these devices. Sometimes, when we need to alert users of something, we can not only use the light from LEDs, but we can also use sound. The classic way for creating sound is to use a piezoelectric speaker, also called a piezo buzzer or piezo speaker. One such speaker is shown in Figure 10-8.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig8_HTML.jpg
Figure 10-8

Piezo Speaker Credit: Adafruit, adafruit.com

The piezo speaker consists of a tiny metal plate we call a piezo element. The piezo element vibrates when we apply a square wave to it and creates an audible sound. We can use this effect to create a program that allows us to send waves of different frequencies to the device to create different sounds.

Piezo with MCU Schematic

We connect the circuit as is shown in Figure 10-9. The piezo speaker has two pins. We connect the positive pin on the piezo to pin D5 and the other pin to the ground. The positive pin of the piezo usually has a small “+” sign written on the buzzer.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig9_HTML.jpg
Figure 10-9

Temperature Sensor with MCU Schematic

Piezo Circuit Connection Tips

These are the recommended steps to connect the circuit:
  1. 1.

    Connect the ground pin of the piezo speaker to the ground.

     
  2. 2.

    Connect the positive pin of the piezo to pin D5.

     
When you are finished connecting your circuit, it should look like Figure 10-10.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig10_HTML.jpg
Figure 10-10

Piezo with MCU on Breadboard

Libraries We’ll Need

These are the libraries we will need to add to our lib folder:
  • simpleio

Piezo with CircuitPython Program

Edit your code.py in the Mu editor so that it resembles Listing 10-3. This example is modified from the example provided by Adafruit Industries for creating sound.
# import board
import board
# import simple io library
import simpleio
# Define pin connected to piezo buzzer.
(1) PIEZO_PIN = board.D5
# Define a list of tones/music notes to play.
(2) TONE_FREQ = [ 262,  # C4
              294,  # D4
              330,  # E4
              349,  # F4
              392,  # G4
              440,  # A4
              494 ] # B4
# super loop
(3) while True:
    # Play tones going from start to end of list.
    for i in range(len(TONE_FREQ)):
        simpleio.tone(PIEZO_PIN, TONE_FREQ[i], duration=0.5)
    # Then play tones going from end to start of list.
    for i in range(len(TONE_FREQ)-1, -1, -1):
        simpleio.tone(PIEZO_PIN, TONE_FREQ[i], duration=0.5)
Listing 10-3

MCU with Piezo Program

In the program, we do our usual imports; then at (1) we set up the piezo to pin D5. At (2) we define a list of notes to play. Using the list of notes in the program, in the super loop at (3), we iterate over them. Once the program works correctly, you will hear the notes coming from your speaker.

DHT11

In the section where we looked at analog interfacing, we looked at using a temperature sensor. However, there is a popular 2-in-1 sensor that can measure temperature and humidity, which is the DHT11 sensor. The DHT11 is pictured in Figure 10-11.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig11_HTML.jpg
Figure 10-11

DHT11 Temperature and Humidity Sensor Credit: Adafruit, adafruit.com

This device has four pins. One pin is VCC, and the other pin is the ground pin. There is also an output pin that we use to read the data from the sensor.

DHT11 with MCU Schematic

We connect the circuit as is shown in Figure 10-12. We connect the output of the DHT11 to our input pin D10. To operate properly, we need a pull-up resistor connected to the output pin of the DHT11.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig12_HTML.jpg
Figure 10-12

DHT11 Sensor with MCU Schematic

DHT11 Sensor Circuit Connection Tips

These are the recommended steps to connect the circuit:
  1. 1.

    Connect the VCC pin of your DHT11 to the positive rail.

     
  2. 2.

    Connect the ground pin of the sensor to the ground.

     
  3. 3.

    Connect the 1k resistor from the output pin to the VCC pin.

     
  4. 4.

    Run a jumper wire from the output pin of the DHT11 sensor to pin D10 on the MCU running CircuitPython.

     
When you are finished connecting your circuit, it should look like Figure 10-13.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig13_HTML.jpg
Figure 10-13

Temperature Sensor with MCU on Breadboard

Libraries We’ll Need

These are the libraries we will need to add to our lib folder:
  • adafruit_dht

DHT11 Sensor with CircuitPython Program

Edit your code.py in the Mu editor so that it resembles Listing 10-4. This example is modified from the example provided by Adafruit Industries for reading the sensor.
# import board
import board
# import time
import time
# import busio
import busio
# import library for working with sensor
(1) import adafruit_dht
# connect the DHT11 to pin10
(2) dht = adafruit_dht.DHT11(board.D10)
(3) while True:
    try:
        # read the temperature and humidity
        temperature = dht.temperature
        humidity = dht.humidity
        # print the read temepratue and humidity
        print("Temp: {:.1f} *C Humidity: {}%".format(temperature, humidity))
    except RuntimeError as e:
        # if dosent work print error
        print("Reading from DHT failure: ", e.args)
    # print every second
    time.sleep(1)
Listing 10-4

MCU with DHT11 Sensor Program

In the program, we do our usual imports; then at (1) we import the library for working with the DHT11 sensor. At (2) we create an instance of the DHT11 sensor on pin 10. In our main loop at (3), we read the temperature and humidity of the sensor and print it to the console. The output is shown in Figure 10-14.
../images/511128_1_En_10_Chapter/511128_1_En_10_Fig14_HTML.jpg
Figure 10-14

DHT11 Sensor Output

The sensor will output data at a steady rate, and thanks to our try catch, if the program fails, it will keep running and output data to the console.

Note that even though this example uses the DHT11 sensor, the DHT22 can also be used without any problems as the “adafruit_dht” library supports both devices. To use this sensor when creating an instance of the sensor, you would simply change DHT11 to DHT22.

Conclusion

In this chapter, we looked at interfacing some common sensors using MicroPython-based microcontrollers. We looked at using RGB LEDs, ultrasonic sensors, sound, and temperature and humidity sensors. The knowledge gained in this chapter will allow you to build some remarkably interesting embedded systems.

Congratulations! You have worked through the entire book. If you made it this far, then you would have built a solid foundation for using CircuitPython with microcontrollers. Don’t stop there! There is still a lot you can do to increase your knowledge. Examine the Adafruit libraries bundle and run the code samples from there. Keep tinkering!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.235.120.24