Showing posts with label Electronics. Show all posts
Showing posts with label Electronics. Show all posts

Friday, March 28, 2025

Print your own USB connector

For an index to all my stories click this text.

Sometimes I find something on the web that is so usefull that I want to share it with you.

Powering your circuits.

When testing and building a small circuit with just one or two sensors you can use the power that your microcontroller supplies over it's 5V pin. Both the ESP32 and the Raspberry Pi Pico have a 5V and 3V3 power out pin.

But when I need more power I use an USB breadboard connector to power the project.


An example is this circuit where two TM1637 7 segment displays are connected to a Raspberry Pi Pico. The Raspberry pi pico is powered through it's USB port and on the left-top side you can see a breadboard USB connector attached to a USB power plug.

Nothing wrong with this but I always seem to run out of breadboard USB connectors.

3D printer to the rescue

Then I found this on the web:
https://www.instructables.com/Minimalist-USB-Connector-No-Special-Hardware-Requi/


This is a 3D printed USB connector. The photo shows the assembled version.
But does it work ????


Works like a charm !!!
As you can see the USB connector is plugged into a powerbank and the multimeter shows that a nice 5V is supplied.

The STL files

The connector consists of 2 parts.

You can find the STL files in the original story which you can find here:
https://www.instructables.com/Minimalist-USB-Connector-No-Special-Hardware-Requi/


The first part is the bottom in which you need to insert the wires. The second part is the top which you should glue and press on to the bottom part when the wires are placed. The top part has ridges that help keep the wires in place.


This is how the files look in my slicer. I use Cura.


Set the quality at 0.2mm and supports on. As these are small parts you could set adhesion also on.

Assembling

I used solid copper wire with a diameter of 0.5mm. That worked very well.

I took a slightly different approach to assembling as what the original developer described.

First I stripped the wires.


Then I pulled the stripped part through the holes.

Then I glued the lid on.
The last step was to cut off the excess wire.

The blue wire at the top is GND.
The red wire at the bottom is VCC (5V).
Please test before you actually put it to use to make sure the wires are not twisted. If you mix the wires up you might/will blow up your circuit so test, test, test !!!


The wires are thick enough to fit direct into a breadboard.

You can make the wires any length you want. Short to connect to a powerbank and fit on your desk. Or make them long to connect to a wall outlet with an USB power plug.

I have printed several of these. They are ready to use in my drawer. A really great design.

Til next time
Have fun

Luc Volders

Friday, February 28, 2025

Raspberry Pi Pico audio player

For an index to all my stories click this text.

After all the proceeding stories the time has come to build a complete stand-alone audio player with the Raspberry Pi Pico. The audio quality is not Hifi but it is really good !! Good enough as a player in your mancave, bedroom or even as a portable player. I have made a permanent setup and using it to play music and podcasts. My setup has a few neat extra features which will be described later on. 

The programming is done in MicroPython with Thonny as the IDE.

You can use a Pico or a Pico-W for this project. The pin connections and the program are the same.

To build this I am going to list the parts that are needed first:

- A Raspberry Pi Pico or Pico W
- 3 push buttons
- 4 10K resistors.
- 2 1K resistors
- 4 2K2 resistors
- 2 47nF capacitors.
- 1 SD card module or SD card adapter
- 1 SSD1306 Oled display
- 1 large on several small breadboards
- Dupont wires for the breadboard

Extra

- An active speaker (like a computer speaker) or
- a pair of earplug headphones.
- a 3.5mm contra connector for the headphone or speakers
- an optional small amplifier so you do not need an active speaker
- a pair of small speakers when using the amplifier
- alligator clips for connecting to the headphone or speakers
- Power Bank or USB power supply

To get this working we need a lot of drivers for MicroPython. We need drivers for playing the sounds, we need drivers for the SD card, we need drivers for the SSD1306 oled screen.

I bundled all these drivers on my Github depositry. You can find them here:
https://github.com/Lucvolders/MicroPython/tree/main/Libraries

Next to that you need to know that this audio player only plays 8k WAV files.  

I wrote several stories on each step that was needed to come to this project. I will list here the links to each step.

Converting audio files to an 8K WAV file with Audacity:
http://lucstechblog.blogspot.com/2024/10/audacity-pico-audio-part-1.html

Building the Raspberry Pi Pico audio hardware with just a few resistors and capacitors:
http://lucstechblog.blogspot.com/2024/10/audio-on-pico-part-2-hardware.html

Raspberry Pi pico audio playing software:
http://lucstechblog.blogspot.com/2024/10/pico-audio-part-3.html

SD card for the Raspberry Pi Pico (hardware):
http://lucstechblog.blogspot.com/2025/01/pico-sdcard-part-1-hardware.html

SD card for the Raspberry Pi Pico (software):
http://lucstechblog.blogspot.com/2025/01/pico-sd-card-part-2-software.html

I did not write a story on the SSD1306 oled screen. But that is in my book: Raspberry Pi pico Simplified ;) There is a link to that book on the bottom of this page. The driver is however in my Github depositry.

These stories describe the hardware in details with breadboard setup. The stories also cover the origin of the MicroPython drivers and how to collect them and install them. Like said before I bundled all the drivers in my Github repositry here:
https://github.com/Lucvolders/MicroPython/tree/main/Libraries

I urge you to read these stories so you know what is going on.

The breadboard setup.

Here is the breadboard setup. There are some expansions possible like adding the digital thermometer which was discussed in this story:
http://lucstechblog.blogspot.com/2024/11/pico-audio-part-4-talking-thermometer.html



Please note that you are looking at the backside of the SD card. That is the side where the connector is soldered. If you are using an SD card module make sure to attach to the right pins.

As there might be some confusion from looking at the above picture I will show you all the connections here.

The Buttons

Button 01 is attached with a pull-up resistor to pin GP18
Button 02 is attached with a pull-up resistor to pin GP19
Button 03 is attached with a pull-up resistor to pin GP20

Audio

Audio left is attached to GP02
Audio right is attached to GP03

SSD1306

The oled screen is powered by VCC (3.3 Volt) and GND
SDA is attached to GP09
SCL is attached to GP08

SD-Card

The SD card is powered by VCC (3.3 Volt) and GND.

MISO is attached with a pull-up resistor to GP12
CS is attached to GP13
SCK is attached to GP14
MOSI is attached to GP15

You can find all the details about these connections in the previous stories in this series. Please pay special attention to the audio connections to the low-pass filter and the SD card connections.

As the pins where the hardware is attached have to be defined in MicroPython you can also find the pin numbers in the MicroPython program.

The audioplayer program

As you are used to on this weblog, I present the full code here which you can copy and paste into your favorite MicroPython editor.

'''
Audioplayer Plays 8k WAV files
With Oled screen for choosing audiofiles

Audio files on SD card
Button GP18 next number
Button GP19 previous number
Button GP20 play the song
'''

# Import garbage collect
import gc

import os as os
import time
import machine
from machine import SPI, Pin, Timer
import sdcard
from wavePlayer import wavePlayer

import ssd1306

sda=machine.Pin(8)
scl=machine.Pin(9)

i2c=machine.I2C(0,sda=sda, scl=scl,freq=400000)
print(i2c.scan())

oled = ssd1306.SSD1306_I2C(128, 64, i2c)

player = wavePlayer()

spi = SPI(1,sck=Pin(14), mosi=Pin(15), miso=Pin(12))
cs = Pin(13)
sd = sdcard.SDCard(spi, cs)

os.mount(sd, '/storage')

but01=machine.Pin(18, machine.Pin.IN)
but02=machine.Pin(19, machine.Pin.IN)
but03=machine.Pin(20, machine.Pin.IN)

playnow = -1

array=(os.listdir('/storage/Music'))
numbers = len(array)
print (numbers)

oled.fill(0)
oled.show()
oled.text("Raspberry Audio",0,0)
oled.text("player",40,10)
for i in range(0, 127):
    oled.pixel(0 + i, 20, 1)
oled.show()

try: 
   while True:

      
      if (but01.value()==0): 
          print("button 1 pressed")
          playnow = playnow + 1
          if (playnow == numbers):
              playnow = 0
          song = "/storage/Music/"+array[playnow]
          print(type(song))
          help= array[playnow]
          print("Now playing " + help[0:-4])
          
          oled.fill(0)
          oled.text("Raspberry Audio",0,0)
          oled.text("player",40,10)
          for i in range(0, 127):
              oled.pixel(0 + i, 20, 1)
          oled.text("This song is :",0,25)
          oled.text("                   ",0,35)
          oled.text(help[0:-4],0,35)
          oled.show()
          print(playnow)
          time.sleep(.5)
          # test how much memory is free
          gc.collect()
          print(gc.mem_free())  
    
      if (but02.value()==0):
          #player.stop()
          print("button 2 pressed")
          
          if (playnow == -1 or playnow ==0):
              playnow = 0
          else:
              playnow = playnow -1
          song = "/storage/Music/"+array[playnow]
          print(type(song))
          
          help= array[playnow]
          print("Now playing " + help[0:-4])
          oled.fill(0)
          oled.text("Raspberry Audio",0,0)
          oled.text("player",40,10)
          for i in range(0, 127):
              oled.pixel(0 + i, 20, 1)
          oled.text("This song is : ",0,25)
          oled.text("                   ",0,35)
          oled.text(help[0:-4],0,35)
          oled.show()
          print(playnow)
          time.sleep(.5)
          
      if (but03.value() ==0):
          help= array[playnow]
          print("Now playing " + help[0:-4])
          oled.fill(0)
          oled.text("Raspberry Audio",0,0)
          oled.text("player",40,10)
          for i in range(0, 127):
             oled.pixel(0 + i, 20, 1)
          oled.text("Now playing:",0,25)
          oled.text("                   ",0,35)
          oled.text(help[0:-4],0,35)
          oled.show()
          player.play(song)
   
except KeyboardInterrupt:
   player.stop()


All of this code has been explained in the previous chapters except a neat trick.

array=(os.listdir('/storage/Music'))
numbers = len(array)
print (numbers)

The audio files are stored in a subdirectory on the SD card with the name Music. This piece of code puts the directory entries (the music names) into an array and then prints that array on Thonny's console. The number of music tracks is put into the variable number. This variable tells us how many music tracks there are on the SD card.

          print("button 1 pressed")
          playnow = playnow + 1
          if (playnow == numbers):
              playnow = 0
          song = "/storage/Music/"+array[playnow]
          print(type(song))
          help= array[playnow]
          print("Now playing " + help[0:-4])


Pressing the first button increases the playnow variable. That variable points to the array that holds the directory items. The array entry is copied into the help variable and that is printed on the oled screen. This variable entry is the name of the music track that is going to be played if you press the third button.

If the increased number is higher as the number of array entries the number is set back to 0 which is the first array entry.

The same is done for the second button that decreases the variable so walks backwards through the array till it reaches 0.

The last button takes the array entry and plays it.

Operating the player.

First thing to do is saving this program into your Pico and naming it main.py When the Pico reboots MicroPython looks for a program with the name main.py and automatically starts that program. This way you can run this player stand-alone with a USB power supply or, for mobile use, with a power bank.

Once started the oled display shows the text:

Raspberry Audio
   Player


This tells that the program is ready. Press the first button and the names of the music on your SD card in the subdirectory Music will be shown one by one.
By pressing the second button you can scroll backwards through the names.
Pressing the third button will play the song which name is on the oled screen.


Any flaws ??

Well yes actually there is a flaw. Once you start playing a song you can not stop it. You'll have to sit it out before you can choose another one. A work around solution would be adding another button and connect pin 30 to GND when the button is pressed. Pin 30 is RUN and acts as a reset pin. This would actually reset the pico so it physically reboots. You can find how to build a reset button here: http://lucstechblog.blogspot.com/2021/02/raspberry-pico-rest-button.html

Expansions.

I can think of a few.

- First possible expansion is, like discussed above, adding a reset button.
- The player plays a song and then waits till you choose another song and press a button. An expansion would be the possibility to start playing at a certain song and then the next ones in line would play automatic.
- An expansion would be adding a Dallas DS18B20 digital thermometer. You would also need to attach another button that gives you the option to toggle between the audio player and the talking thermometer. You can find the talking thermometer in this story : http://lucstechblog.blogspot.com/2024/11/pico-audio-part-4-talking-thermometer.html
- You could add yet another button that would activate a talking clock. You can find the talking clock in this story: http://lucstechblog.blogspot.com/2024/11/pico-audio-part-5-talking-clock.html
- How about adding the talking clock and have the audio player play your favorite song at waking time.
- Remove the buttons (except a reset button) and use a rotary encoder to walk through the menu items/songs etc and choose the item you need.
- Add extra buttons that you can use as preset buttons for playing certain songs. You would add the possibility to program these buttons when you change the SD card for one with different music.

These are just a few ideas I came up with in a few minutes. I believe you can come up with a few of your own......

Please send me a mail if you have build this or something that was based on this project. I am always curious about what my readers come up with.

Till next time,
have fun

Luc Volders


Saturday, February 22, 2025

Pico audio part 6: Talking dice

For an index to all my stories click this text

This is an ongoing series about audio on the Raspberry Pi Pico. This time I am going to build a talking dice. Just like the previous is made in MicroPython.

Actually this is the sixth story on how to play audio on the Raspberry Pi Pico with MicroPython. In this story shows how to build a talking dice. The audio on the Pico does not sound like the crappy audio on the ESP32 with Talkie. That sounded like voice synthesizes on the Commodore 64 and Atari computers if you still remember that. No this is real clear audio. And for the talking dice we are going to use your own recorded voice.

I urge you to read the proceeding stories in which audio recording, the necessary hardware and software were discussed.

Audacity. This is the first story in this series. With Audacity we can record our own voice using a microphone or a build-in microphone in your webcam. You can also convert mp3 files to the required 8K wav files for this project. Read that story here: http://lucstechblog.blogspot.com/2024/10/audacity-pico-audio-part-1.html

Picoaudio 2 the hardware. This story shows what hardware you need. Don't worry its just a few resistors and some capacitors. The total cost will be around 1 Euro/USD without the Raspberry Pi Pico. And as you know the Pico itself will set you back around 5 Euro/USD for the non-wifi version and about 8 Euro/USD for the wifi version.
http://lucstechblog.blogspot.com/2024/10/audio-on-pico-part-2-hardware.html
 
Picoaudio 3 the software. This story describes which MicroPython drivers you will need. In total 5 drivers. The story gives you the links to the download site. Thye story also shows a small program that will play your first sounds.
http://lucstechblog.blogspot.com/2024/10/pico-audio-part-3.html

There are 2 more stories in this series about building a talking thermometer and a talking clock. You can find those here:
http://lucstechblog.blogspot.com/2024/11/pico-audio-part-4-talking-thermometer.html
http://lucstechblog.blogspot.com/2024/11/pico-audio-part-5-talking-clock.html

To store the audio clips Pico's memory is rather limited. So the audio is stored on an SD card. Therefore you will need to attach an SD card to the Pico.
 
It is really easy to attach an SD card to the Raspberry Pi Pico. This story shows how to do that: http://lucstechblog.blogspot.com/2025/01/pico-sdcard-part-1-hardware.html

Next to physically attaching the SD card you will also need to install the drivers in MicroPython. This story shows how to do that:
http://lucstechblog.blogspot.com/2025/01/pico-sd-card-part-2-software.html

So what you will need to build the talking dice are the following components:

- A Raspberry Pi Pico or Pico W
- 1 push button
- 2 10K resistors.
- 2 1K resistors
- 4 2K2 resistors
- 2 47nF capacitors.
- 1 SD card module or SD card adapter
- 1 large or several small breadboards
- Dupont wires foir the breaboard

Extra

- An active speaker (like a computer speaker) or
- a pair of earplug headphones.
- a 3.5mm contra connector for the headphone or speakers
- an optional small amplifier so you do not need an active speaker
- a pair of small speakers when using the amplifier
- alligator clips for connecting to the headphone or speakers
- Power Bank or USB power supply

The breadboard setup

As the breadboard setup was extensive discussed in the previous stories I will not go into details here. Just follow those stories.



Back to Audacity

In the first story in this series I showed how to record audio and convert it to an 8K wav file with Audacity. If you did not read that story please do it now.

Our program will speak out the words: one, two, three, four, five and six. Those we already recorded in the story about Audacity :

lucstechblog.blogspot.com/2024/10/audacity-pico-audio-part-1.html


We do want to record some extra sentences. The first one is: "Here we go". And the second one is: "You threw an eight"

So please record these sentences and save them on your SD card in the directory where the number.wav files are stored. Name these files "Here.wav"and "Threw.wav". Chose any name you might like better but keep in mind to alter the names in the program also.

If you do not know how to load and transfer files to an SD card please read this story:
http://lucstechblog.blogspot.com/2025/01/pico-sd-card-part-2-software.html
and this story:
http://lucstechblog.blogspot.com/2023/07/a-few-small-thonny-tips.html



I also added a sound effect of rolling dice which I found on Pixabay. You can find it here: https://pixabay.com/sound-effects/search/dice_roll/
It is called Dice_roll and lasts 1 second. Great for our project.
Make sure you convert it to an 8K wav file before transferring it to the Pico's
SD card. Name this file "Roll.wav"


The talking dice program

Here is the full program in MicroPython. Don't forget to put the required libraries in the lib folder.

'''
Talking dice by Luc Volders
http://lucstechblog.blogspot.com/
'''

import os as os
import machine
from wavePlayer import wavePlayer
from machine import SPI, Pin, Timer
import sdcard
import random

random.seed(None)

but01=machine.Pin(18, machine.Pin.IN)

player = wavePlayer()

spi = SPI(1,sck=Pin(14), mosi=Pin(15), miso=Pin(12))
cs = Pin(13)
sd = sdcard.SDCard(spi, cs)

os.mount(sd, '/sd')

while True:
    if (but01.value()==0):
        player.play("/sd/Sounds/Here.wav")
        player.play("/sd/Sounds/Roll.wav")
        player.play("/sd/Sounds/Threw.wav")
        number = random.randint(1,6)
        strnum = str(number)
        soundstr = "/sd/Sounds/"
        soundstr = soundstr + strnum
        soundstr = soundstr + ".wav"
        player.play(soundstr)

If you have read the previous stories in this series the program speaks for itself. The number.wav files and the "Here.wav", "Roll.wav" and "Threw.wav" files are all in the Sounds directory on the SD card.

The only part that needs some explanation is this part in the While True loop:

        number = random.randint(1,6)
        strnum = str(number)
        soundstr = "/sd/Sounds/"
        soundstr = soundstr + strnum
        soundstr = soundstr + ".wav"
        player.play(soundstr)

The player.play() command accepts a string to point to the file we want to play.
First step is to create a random number from 1 to 6.
We make a string from that number with the str() command.
The first part of the string is the location of the files which is here: "/sd/Sounds/"
We add to this the string with the number and then we add ".wav"
And then the string is put into the player.play() command.

That is all there is to it.

Sidenote

If you are building a dedicated project for this there is enough memory in the Pico to put all the files in just like we did in the first part of this series:
http://lucstechblog.blogspot.com/2024/11/pico-audio-part-4-talking-thermometer.html picoaudio4 talking thermometer
That way you can leave the SD card and the accompanying resistor out.

Till next time.
Have fun

Luc Volders


Saturday, December 7, 2024

Order your Christmas presents now !!

 For an index to all my stories click this text

Now is the time !!

Just a shameless plug.

IF you have any friends, loved ones or relatives that are stepping into the wonderful world of Microcontrollers, electronics or the Internet Of Things please consider buying one of my books. And now is the time so it will arrive in time before Christmas

And by ordering these books you also support this weblog which allows me to buy new sensors etc. to build new projects and write about them.

These books are aimed at beginners to this hobby and are clearly written with many examples and projects that get you started right away.


This book was written several years ago and is still a bestseller.
It explains working with a breadboard, the C++ (Arduino) language and explains the workings of many sensors. Next to that the book shows how to work with cloud based services. It also shows how to build a simple webserver that allows to get sensor (like your home temperature etc) data from anywhere in the world.
Click here to buy this book.


The Raspberry Pi Pico was the first microcontroller from the Raspberry Pi Org. that is well known for its small Linux computers. The Pico took the IOT world by storm because of it's low price, worldwide availability, many IO pins, great speed and the availability of the MicroPython language that makes programming this chip really easy. This book shows how to install MicroPython, and covers the basic syntax of this easy to learn language. Next to that the book shows how to work with all kinds of sensors, motor, buttons etc. etc. All projects are well documented and breadboard based so no soldering !! The projects in this book will also work on the Pico2.
Click here to buy this book.


The Raspberry Pi Pico W is the successor of the Pico and adds Wifi to its capabilities. The book shows how to install the MicroPython language and the basic syntax. Then it focus on working with many sensors, motors, buttons etc. The book shows how to use wifi to get access to internet services. And a lot of attention is paid to building webservers in MicroPythoin that allow you to read sensors (like your home temperature) and set lights on or off from anywhere in the world. The projects in this book will also work on the Pico 2W
Click here to buy this book.


Javascript is without a doubt the most used computer language in the world. Anytime you click a button on a webpage or see some interactive action on a webpage Javascript is involved.
This book does not learn how to program in Javascript but gives you hundreds of tips while programming in this language. It covers topics like sorting of data, date manipulation like calculating the number of days between days, rounding figures, hding and showing hidden elements on a webpage, acting on key presses etc. etc. etc. There are hundreds of tips covering almost any aspect of building interactive webpages and working with the data on these pages.
This book might also be a valuable asset when building webservers with microcontrollers like the ESP32 and Raspberry Pi Pico series.
Click here to buy this book

Have a good Christmas
and have fun

Luc Volders

Friday, September 13, 2024

Testing an obstacle avoidance sensor

For an index to all my stories click this text

I was playing around with an obstacle avoiding sensor and want to share my experiences with you.

What is it.

An obstacle avoidance sensor is mostly used in robotics.

The sensor has an infrared led. This led sends out lightin the infrared spectrum which we can not see. the light normally shines streight on.

Next to the infrared led there is a photodiode. That photodiode detects infrared licht.

When the sensor approaches an obstacle the infrared light is reflected back and detected by the photodiode.

Like said, this is mostly used in robotics. The sensor is mounted on a robot and when the robot comes close to a wall or any other obstacle the photodiode sends a signal to the robots controller to alter direction.

The sensor

This is how the sensor looks in real life. Let's have a look at the different parts of it.

On the left you can see the photodiode at the top and the IR led beneath it. They are next to eachother so the there is a maximum chance of detecting any reflection.

In the middle there is a screw with witch you can adjust sensitivity. That means by turning the screw you can adjust the maximum distance at what the reflection is detected.

Next to the header pins there are two leds. The top led is the power led and that is always on whenever the sensor has power. The led at the bottom is off and goes on when an obstacle is detected.

A test setup

To test the sensor I build a simple setup on a breadboard. I connected the sensor to a Raspberry Pi Pico. Here is what the breadboard looks.


The led (I used a blue one) is connected with a current limiting resistor to GND and to GPIO15.

Pico's GND (pin38) is connected to the sensor's GND. and Pico's 5V (pin 40) is connected to VCC. The sensors output (OUT) is connected to GPIO16.

Test program in MicroPython

To test the sensor I wrote a simple program in MicroPython.

import time
from machine import Pin

obstac = Pin(16, Pin.IN)
led = Pin(15, Pin.OUT)

while True:
      print(obstac.value())
      led.value(not obstac.value())
      #led.value(0)
      time.sleep(.2)

In the loop the program constant tests the out pin of the sensor. When that pin's output changes from 1 to 0 (obstacle detected) the led on GPIO15 goes on.

Copy this program, paste it in Thonny and save it as main.py on your Pico. It will work on the Pico, Pico W and Pico2.
Saving it as main.py makes the program run immediately when the Pico is powered up so you can do some tests with a powerbank, phone charger or batteries.

If you want to learn about MicroPython on the Raspberry Pi Pico or Pico W please consider buying one of my books that are listed at the bottom of this page.

First test.

This should immediately work. Just hold your hand above the sensor and move it towards the sensor. At a certain moment the led will go on both on the sensor as well as the blue led.

Now you can adjust the screw in such a way that the leds will go on at your desired distance.

Distance

According to some specifications I found you can adjust the screw so the distance at which the led will go on can be set from 2 to 20 cm.

Just be aware that there are environmental issues that might influence the detection distance. Here are some things you might like to take into consideration.
- Temperature may affect the distance
- TL light might affect the distance
- Sun light might affect the distance
- Direct light shining on the photodiode might affect the distance

The only thing I want to say is that you should adjust the sensivity screw in your real-life setup.

Some tests

Here are the results of some tests I performed.


All leds are OFF because there is no obstacle in front of the sensor.


A shining transparant box was put in front of the sensor and at a distance of 8 cm the obstacle was detected.


A black piece of paper was put in front of the sensor and at 6cm it was still not detected.


The black paper was detected at 2.5 cm.
This means that the black paper absorbed (did not reflect) a lot of infrared light so it was not detected until it was at a short distance.


A white piece of printer paper was detected at 8 cm distance. The white color reflects the infrared light more so the paper was earlier detected.


A black shining object was detected at 4cm. This means that the black color absorbed some infrared light but the shing surface reflected also some infrared light.


A book (yes my book about the Pico) with a shining green cover reflected the infrared light at a larger distance so it was already detected at about 8.5cm

Water ???

Solid obstacles: OK
But how about fluids.

If you want to reproduce this test yourself just make sure the electronics don't get wet. Water and electronics don't mix and you might damage your sensor or pico beyond repair.


I filled a white bowl with a small layer of water and help the breadboard above it.
The led stayed off: no obstacle detected.


I used a bottle of water to gradually fill the bowl and yes !!!
At a certain moment the led went on. So water reflects the infrared light.


Concluding

First let me state that obstacles are detected very well.
In the demo program you can lower the delay and that will not affect the working of the sensor. So in real life you should use an interrupt for testing for an obstacle which is the fasted method.

The obstacle avoidance sensor detects obstacles but does not give any indication at what distance the obstacle is 'seen'. The difficulty lies in different materials reflecting the infrared light more or less.
If you need to measure distance then use an HC-SR04 ultrasonic sensor.

This means that you should adjsut the sensivity screw so that the obstacle is detected at a larger distance when you are working with a fast moving object like a remote controlled car. That is because you will need time to shut the motor down. But you also need to take the obstacles material in count as black obstacles are seen later.

I was specially impressed when I realised that the sensor also detected water as an obstacle.
I did not try but wonder if a black bowl would make a difference.

And remeber: you can always use this sensor inverted. Meaning that an alarm is given when an obstacle is removed like the lid of a box is taken off.

Till next time
Have fun

Luc Volders




Friday, August 9, 2024

Let microcontrollers talk to eachother

For an index to all my stories click this text

I had an idea for a project that needed a lot of IO pins. That sounds easy as there are several stories on this weblog that demonstrate how to get more output or input pins for your microcontroller.

But this was different. I needed a lot of input pins on a microcontroller and depending on the state of those, certain outputs should be set, and a display should show values. And my microcontroller had not e4nough pins to achieve all this.

So I wondered if it was possible to send the output of the IO pins from one microcontroller to the input IO pins of another microcontroller. And for certain reasons I did not want to use serial communication over UART.

ESP32 to Raspberry Pi Pico

I started with trying to connect an ESP32's IO pin to a Raspberry Pi Pico. As a proof of concept I connected 1 IO pin of the ESP32 as an output to 1 IO pin of the Raspberry Pi Pico that acted as the input. Both operate at 3.3V so this should work.

The programs for both the ESP32 and Raspberry Pi Pico are written in MicroPython.
To get this working you should make sure that your IDE (I am using Thonny) is able to open multiple instances.

This is the breadboardsetup.

The GND of the ESP32 is connected to the GND of the Raspberry Pi Pico. If you do not do this the two will not be able to communicate.
Pin 23 from the ESP32 is connected to Pin 16 of the Raspberry Pi Pico. These are the two pins that are used to make the Microcontrollers communicate with eachother.
The Raspberry Pi pico has a led connected to pin 15. This led is connected with a 200 Ohm current delimiting resistor.

That's all for this first test.


The ESP32 program

Here is the full program.

'''
ESP32
send output to other micro on pin 23)
'''

import time
from machine import Pin

outbut = Pin(23, Pin.OUT)

outbut.value(0)

while True:
      outbut(not outbut())
      print(outbut.value())
      time.sleep(1)


I guess the code speaks for itself. Pin23 is defined as the output pin, and it's value is toggled by outbut(not outbut())

The Raspberry Pi Pico program

'''
Raspberry Pi Pico
get input on pin 16)
'''

import time
from machine import Pin

inpbut = Pin(16, Pin.IN, Pin.PULL_UP )
led = Pin(15, Pin.OUT)

while True:
      print(inpbut.value())
      if (inpbut.value() == 0):
          led.off()
      if (inpbut.value() == 1):
          led.on()
          pass
      time.sleep(1)


As this is just a simple test I did not use an external pullup resistor but defined the input pin (Pin 16) as an input with PULL_UP

The input pin gets its data from the ESP32. If the ESP32 sends a 1 (high) then the Pico's led is set on. If the ESP32 sends a 0 (low) then the Pico's led is set off.

The result

And here is what you will see in Thonny's shell.


On the left is Thonny's instance running the Raspberry Pi Pico. On the right you can see the ESP32 sending out a 1 or 0 every second.

At the breadboard you will see that the led blinks evey second when the Raspberry Pi Pico receives a high (1) signal.

A more advanced experiment.

As a test I attached a pushbutton to the ESP32. The goal was to set the led attached to the Raspberry Pi Pico on when the button attached to the ESP32 is pushed.

The breadboard setup is almost identical to the previous version I only attached a pusbutton with a pull-up resistor to the ESP32.


The only thing different from the previous setup is the attached pusbutton which is connected to pin 34 of the ESP32 with a 10K pull-up resistor.


The new ESP32 micropython program

The programn for the Raspberry Pi Pico remains the same. The only difference is in the program for the ESP32.

'''
ESP32
send output to other micro on pin 23
depending on button state
'''

import time
from machine import Pin

button = Pin(34, Pin.IN)
outbut = Pin(23, Pin.OUT)
led = Pin(2, Pin.OUT)

outbut.value(0)

while True:
      if (button.value() == 0):
          outbut.on()
          print(outbut.value())
      if (button.value() == 1):
          outbut.off()
          print(outbut.value())
      time.sleep(.2)


The program send constantly a 0 (LOW) signal on pin 23 and wait tills the button is pressed. When the button is pressed the signal on pin 23 turns into a 1 and that makes the Pico's led go on.

In real life

This works as I thought it would. In real life you possibly want to send more signals from one microcontroller to another.

Please make sure that both microcontrollers work at the same voltage. An ESP32 and a Raspberry Pi Pico both work at 3.3V.  An Arduino however works at 5V, so connecting that to an ESP32 or Raspberry Pico would fry one of these.

A solution to send more info over few pins would be to use binary coding. I covered that in a previous story :
http://lucstechblog.blogspot.com/2019/07/more-buttons-on-fewer-pins.html

That's all for now.
Have fun


Luc Volders