# Trinket Ultrasonic Rangefinder

## Overview and Wiring

Ultrasonic sensors are excellent at proximity detection. Whether on a robot or protecting an area. The Adafruit shop carries an [excellent selection of sensors by Maxbotix](http://www.adafruit.com/category/35_57 "Link: http://www.adafruit.com/category/35\_57").  
  
The LCD display with an I2C backpack works well in Trinket projects as an informational display. It only requires two of the five Trinket pins.  
  
Sensor monitoring is very common for Internet of Things (IoT) projects. This project can be placed in a very small enclosure and used anywhere sensing is needed. The code and concepts may be used in a number of your own projects. Info: 

![](https://cdn-learn.adafruit.com/assets/assets/000/011/353/medium800/trinket_Trinket_Maxbotix_Fritzing.jpg?1380500951)

# Trinket Ultrasonic Rangefinder

## The LCD Display

Adafruit carries many [character LCD display varieties](http://www.adafruit.com/category/63_96) with multiple sizes and backlight colors.   
  
The [Adafruit I2C / SPI character LCD backpack](http://www.adafruit.com/products/292 "Link: http://www.adafruit.com/products/292") allows you to control these displays by sending data over the two wire I2C interface. Standard LCDs require a large number of digital pins, straining the capability of even an Arduino Uno. Use of the I2C backpack reduces the pins needed considerably.  
  
This project features a 16x2 display, displaying distance without using a great deal of memory (important on a small microcontroller like Trinket).   
  
The I2C backpack may be assembled and placed on the back of the display. See [the guide to backpack assembly](http://learn.adafruit.com/i2c-spi-lcd-backpack/assembly) to prepare your display and the backpack.  
  
The color displays have a couple of extra connectors - pins 16, 17, and 18 control the three color backlights. If you connect pin 16 to GND, the I2C will control the red light. You can choose to put a jumper from one of the backlight pins to backpack pin 16 to choose a different color or connect the pins high to keep them on all the time. Making the pin choice before soldering on the backpack allows you the most flexibility in choosing your backlight color.  
.  
Or you can just go with a ['classic' blue & white 16x2 LCD](http://www.adafruit.com/product/181)

![](https://cdn-learn.adafruit.com/assets/assets/000/011/351/medium800/trinket_i2cspilcdbackpack.jpg?1380497997)

![](https://cdn-learn.adafruit.com/assets/assets/000/011/352/medium800/trinket_IMG_2201.jpg?1380499392)

# Trinket Ultrasonic Rangefinder

## Adding the Sensor

Once you have the display connected to the Trinket, you can expand the project in many ways. One of the most popular is to add sensor(s) of some sort. [The Adafruit store has a wonderful selection to chose from](http://www.adafruit.com/category/35 "Link: http://www.adafruit.com/category/35").   
  
The easiest place to add a sensor is to Trinket GPIO #1. GPIO pins #0 and #2 are used for the display.

On the original ATtiny85-based Trinket, #3 and #4 are shared with the USB port. Using #3 and #4 is perfectly fine, but you may have to disconnect the connections on those pins when uploading software. The Trinket M0 doesn't have this restriction, by the way.

Also, limiting a project to pins #0 to #2 gives you a similar pinout to the Adafruit [Gemma&nbsp;M0](https://www.adafruit.com/product/3501) wearable controller.   
  
This project demonstrates using the Maxbotix family of ultrasonic proximity sensors. These sensors are extremely flexible to interface via serial, analog, and pulse width outputs. Linking in the SoftwareSerial library with the TinyLiquidCrystal exceeds the memory available on the Trinket. The pulse output may be sensed on one digital pin and works on Trinket GPIO #1 (the one shared with the red LED). This is the connection used here. (We could also use the analog output, it could be connected to the Trinket GPIO #3 or #4 but like we said, the original Trinket has these on the USB interface too - so using these could require the connection be removed during USB programming.)  
  
A small stick of header, 7 pins long, was soldered to the sensor to facilitate attachment to the breadboard.

![](https://cdn-learn.adafruit.com/assets/assets/000/011/354/medium800/trinket_Maxbotix.jpg?1380501574)

See the wiring on the Fritzing diagram (first page) and the picture (second page). It is fairly easy to connect Maxbotic sensors. You use only 3 of the 7 pins on the sensor for sensing via the pulse width output:

- **Maxbotix +5** to **Trinket 5V or 3V** (the sensor takes a 2.5V to 5.5V supply with a 2mA typical current draw)
- **Maxbotix GND** to **Trinket GND**
- **Sensor PW (Pulse Width)** to **Trinket GPIO #1**

# Trinket Ultrasonic Rangefinder

## Arduino Code

Info: 

The 5V Trinket was tested at 8 MHz. The Maxbotix LV Series can operate from 2.5 to 5.5 volts, most likely supporting Trinket 3V and Gemma. The LCD display is a 5 volt device so it may require separate power if you keep it as part of your project.

To test the display, wire the **DAT pin** to Trinket **GPIO #0** , the **CLK** pin to **Trinket GPIO #2** , **5V** to the **Trinket 5V or USB** line and **GND** to **GND**.  
  
Ensure your Arduino IDE has support added for Adafruit Trinket. &nbsp;For Arduino.cc IDE version 1.6.7 and above, all you need to do is add the Adafruit AVR Boards package in the **Tools -\> Board Managers** section which provides Trinket support.  
  
The display test program is a variation of the Hello World program. You need to install two libraries for the I2C and LCD functions: the Wire library&nbsp;and `Adafruit_LiquidCrystal` library respectively.&nbsp;Unlike when Getting Started with Adafruit Trinket was published, no modifications to the IDE are needed, only support added for the boards. &nbsp;Much easier.

If this is your first time using Trinket, work through the guides first:

- [Adafruit Trinket M0 Guide](../../../../adafruit-trinket-m0-circuitpython-arduino/guided-tour)
- [Adafruit Trinket Guide](../../../../introducing-trinket/guided-tour?view=all)

Info: 

## Software Libraries Used

To maximize the functionality of software on Trinket, new libraries need to be installed. See the [All About Arduino Libraries](http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use "Link: http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use") tutorial for details on how to download and install thee liquidcrystal library.

- The Arduino internal Wire library for I2C communications
- The [Adafruit\_LiquidCrystal](https://github.com/adafruit/Adafruit_LiquidCrystal "Adafruit Liquid Crystal library") library

No library is needed for the ultrasonic sensor.

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Trinket_Ultrasonic_Rangefinder/Trinket_Ultrasonic_Rangefinder.ino

## What if I have no display?
Using the contrast potentiometer on the backpack (a small silver bump), turn the dial with a small screwdriver. Change the contrast until you can read the text.

## Saving Space
The above code compiles to 4,336 bytes of 5,310 available. This leaves over 900&nbsp;bytes of code on an original Trinket if you wish to add additional functionality. On a Trinket M0 you have a _ton_ of space to spare. If you use decimal (floating point) numbers, you will most likely exceed the space available. The Arduino IDE built-in functions which calculate&nbsp;floating point math are somewhat large.

# Trinket Ultrasonic Rangefinder

## CircuitPython Code

![](https://cdn-learn.adafruit.com/assets/assets/000/050/506/medium800/trinket_gemma-cp.jpg?1516832895)

 **Trinket M0&nbsp;** boards can&nbsp;run&nbsp; **CircuitPython** &nbsp;— a different approach to programming compared to Arduino sketches. In fact,&nbsp; **CircuitPython comes&nbsp;factory pre-loaded on Trinket M0**. If you’ve overwritten it with an Arduino sketch, or just want to learn the basics of setting up and using CircuitPython, this is explained in the&nbsp;[**Adafruit** &nbsp;](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwiK-__azsnXAhWFsVQKHeLhDgcQFgg8MAA&url=https%3A%2F%2Flearn.adafruit.com%2Fadafruit-trinket-m0-circuitpython-arduino%2Foverview&usg=AOvVaw1KR3kAPHYx-DXtGZjUQX60)**[Trinket M0 guide](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwiK-__azsnXAhWFsVQKHeLhDgcQFgg8MAA&url=https%3A%2F%2Flearn.adafruit.com%2Fadafruit-trinket-m0-circuitpython-arduino%2Foverview&usg=AOvVaw1KR3kAPHYx-DXtGZjUQX60).**

Info: 

Below is CircuitPython code that works&nbsp;similarly (though not exactly the same) as the Arduino sketch shown on a prior page. To use this, plug the Trinket M0 into USB…it should show up on your computer as a small&nbsp; **flash drive** …then edit the file “ **code.py** ” with your text editor of choice. Select and copy the code below and paste it into that file,&nbsp; **entirely replacing its contents** &nbsp;(don’t mix it in with lingering bits of old code). When you save the file, the code should&nbsp; **start running almost immediately** &nbsp;(if not, see notes at the bottom of this page).

**If Trinket M0 doesn’t show up as a&nbsp;drive, follow the Trinket M0 guide link above to prepare the board for CircuitPython.**

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Trinket_Ultrasonic_Rangefinder/code.py

## Installing Libraries:
The adafruit\_character\_lcd and adafruit\_bus\_device libraries must be installed for the above code to run correctly. The latest version of the [Adafruit CircuitPython Library Bundle](https://github.com/adafruit/Adafruit_CircuitPython_Bundle/releases/latest/) contains both libraries. You want to download the latest stable&nbsp; **mpy** bundle which will have a filename like this:

**adafruit-circuitpython-bundle-x.x.x-mpy-date.zip**

The Trinket M0 has limited space, but so in this case we will be selective about which files are copied over to the CIRCUITPY drive. A detailed explanation for [installing libraries is available](../../../../welcome-to-circuitpython/circuitpython-libraries).

Create these two directories and copy the following files from the unzip'd CircuitPython Library Bundle to the CIRCUITPY drive to a new folder called 'lib'.&nbsp;

- **adafruit\_character\_lcd**
  - ./adafruit\_character\_lcd/character\_lcd.mpy
  - ./adafruit\_character\_lcd/\_\_init\_\_.py
  - ./adafruit\_character\_lcd/character\_lcd\_rgb.mpy
  - ./adafruit\_character\_lcd/mcp23008.mpy

- **adafruit\_bus\_device**
  - ./adafruit\_bus\_device/\_\_init\_\_.py
  - ./adafruit\_bus\_device/i2c\_device.mpy

# Trinket Ultrasonic Rangefinder

## Debugging and Going Further

# Going Further

You can use any of the Maxbotix line of ultrasonic sensors to get differing distance characteristics (be sure to change the code to reflect minimum and maximum distance values).  
  
If you're using a Trinket classic with ATtiny85, do conversion from centimeters to inches or other calculations, you should use integer math (best to use an int16\_t integer size or larger for big numbers). This avoids linking in the big floating point library for only a few calculations, possibly exceeding the memory available.  
  
For projects using other sensor types, see the tutorials [Trinket / Gemma Mini Theramin](http://learn.adafruit.com/trinket-gemma-mini-theramin-music-maker) and [Trinket Temperature & Humidity LCD Display](http://learn.adafruit.com/trinket-temperature-humidity-lcd-display "Link: http://learn.adafruit.com/trinket-temperature-humidity-lcd-display").

 **For errors in the Arduino IDE software with classic Trinket:**

- Ensure you have set up the Arduino IDE as listed in the [Introducing Trinket](http://learn.adafruit.com/introducing-trinket) tutorial. &nbsp;It is suggested you use the Arduino.cc Arduino IDE version 1.6.7 or greater.
- Ensure you have installed the Adafruit\_LiquidCrystal&nbsp;library listed on the first page of this tutorial.The Arduino standard&nbsp;standard LiquidCrystal library does not have the I2C support offered by the Adafruit\_LiquidCrystal library.
- Ensure you push the Trinket on board reset button before uploading your sketch, the red LED will blink when ready for upload, there is a 10 second window to do this.
- If you place a large amount of code or other libraries in a sketch, it is very easy to exceed the available code space on the Trinket. If your program absolutely will not fit, consider switching to an Arduino Uno, [Adafruit Boarduino](http://learn.adafruit.com/boarduino-kits), or [Adafruit Flora](http://learn.adafruit.com/getting-started-with-flora "Link: http://learn.adafruit.com/getting-started-with-flora") with standard libraries or try to not use a memory hungry library or declare a great number of variables or strings.
- If you get errors similar to the one below, you may have included decimal numbers and the floating point library was added by the Arduino IDE, or otherwise exceeded the amount of program space available.

`arduino-1.0.1/hardware/tools/avr/bin/../lib/gcc/avr/4.3.2/../../../../avr/lib/avr25/crttn85.o:(.init9+0x2):relocation truncated to fit: R_AVR_13_PCREL against symbol `exit' defined in .fini9 section in /arduino-1.0.1/hardware/tools/avr/bin/../lib/gcc/avr/4.3.2/avr25\libgcc.a(_exit.o)`  
  
**For project issues:**

- If you get no display, go to the Hello World I2C sketch and ensure that works.
- If you have no display on Hello World, on the I2C backpack, use the contrast knob to change the LCD display contrast to a readable level. If you decided on an external potentiometer to change contrast and not pin 16 on the backpack, use that.
- If you get no reading of distance, check your wiring from Trinket pin GPIO #1 to the PW pin on the Maxbotix sensor and that the sensor has its 5V and Ground pins connected.
- Ensure you selected Trinket 5V 8 MHz as the Board type in the Arduino IDE Tools menu.


## Featured Products

### Adafruit Trinket M0 - for use with CircuitPython & Arduino IDE

[Adafruit Trinket M0 - for use with CircuitPython & Arduino IDE](https://www.adafruit.com/product/3500)
The&nbsp;Adafruit Trinket M0 may be small, but do not be fooled by its size! It's a tiny microcontroller board, built around the Atmel ATSAMD21, a little chip with _a lot_ of power. We wanted to design a microcontroller board that was small enough to fit into any project, and low...

In Stock
[Buy Now](https://www.adafruit.com/product/3500)
[Related Guides to the Product](https://learn.adafruit.com/products/3500/guides)
### Adafruit GEMMA M0 - Miniature wearable electronic platform

[Adafruit GEMMA M0 - Miniature wearable electronic platform](https://www.adafruit.com/product/3501)
The **Adafruit Gemma M0** is a super small microcontroller board, with just enough built-in to create many simple projects. It may look small and cute: round, about the size of a quarter, with friendly alligator-clip sew pads. But do not be fooled! The Gemma M0 is incredibly...

In Stock
[Buy Now](https://www.adafruit.com/product/3501)
[Related Guides to the Product](https://learn.adafruit.com/products/3501/guides)
### Adafruit Trinket - Mini Microcontroller - 5V Logic

[Adafruit Trinket - Mini Microcontroller - 5V Logic](https://www.adafruit.com/product/1501)
 **Deprecation Warning: The Trinket bit-bang USB technique it uses doesn't work as well as it did in 2014, many modern computers won't work well. So while we still carry the Trinket so that people can maintain some older projects, we no longer recommend it.** <a...></a...>

In Stock
[Buy Now](https://www.adafruit.com/product/1501)
[Related Guides to the Product](https://learn.adafruit.com/products/1501/guides)
### Standard LCD 16x2 + extras

[Standard LCD 16x2 + extras](https://www.adafruit.com/product/181)
Standard HD44780 LCDs are useful for creating standalone projects.

- 16 characters wide, 2 rows
- White text on blue background
- Connection port is 0.1" pitch, single row for easy breadboarding and wiring
- Pins are documented on the back of the LCD to assist...

In Stock
[Buy Now](https://www.adafruit.com/product/181)
[Related Guides to the Product](https://learn.adafruit.com/products/181/guides)
### RGB backlight negative LCD 16x2 + extras

[RGB backlight negative LCD 16x2 + extras](https://www.adafruit.com/product/399)
This is a fancy upgrade to standard 16x2 LCDs, instead of just having blue and white, or red and black, this LCD has full color RGB characters on a dark/black background! That means you can change the character display colors to anything you want - red, green, blue, pink, white, purple yellow,...

In Stock
[Buy Now](https://www.adafruit.com/product/399)
[Related Guides to the Product](https://learn.adafruit.com/products/399/guides)
### RGB backlight positive LCD 16x2 + extras

[RGB backlight positive LCD 16x2 + extras](https://www.adafruit.com/product/398)
This is a fancy upgrade to standard 16x2 LCDs, instead of just having blue and white, or red and black, this LCD has black characters on a full color RGB-backlight background! That means you can change the background color to anything you want - red, green, blue, pink, white, purple yellow,...

In Stock
[Buy Now](https://www.adafruit.com/product/398)
[Related Guides to the Product](https://learn.adafruit.com/products/398/guides)
### i2c / SPI character LCD backpack - STEMMA QT / Qwiic

[i2c / SPI character LCD backpack - STEMMA QT / Qwiic](https://www.adafruit.com/product/292)
Character LCDs are a fun and easy way to have your microcontroller project talk back to you. They are also common, and easy to get, available in tons of colors and sizes. [We've written tutorials on using character LCDs with an Arduino](http://learn.adafruit.com/character-lcds)...

In Stock
[Buy Now](https://www.adafruit.com/product/292)
[Related Guides to the Product](https://learn.adafruit.com/products/292/guides)
### Maxbotix Ultrasonic Rangefinder - LV-EZ1

[Maxbotix Ultrasonic Rangefinder - LV-EZ1](https://www.adafruit.com/product/172)
LV-EZ1 Maxbotix Ultrasonic Rangefinder provides very short to long-range detection and ranging, in an incredibly small package. It can detect objects from 0-inches to 254-inches (6.45-meters) and provides sonar range information from 6-inches out to 254-inches with 1-inch resolution. (Objects...

In Stock
[Buy Now](https://www.adafruit.com/product/172)
[Related Guides to the Product](https://learn.adafruit.com/products/172/guides)

## Related Guides

- [I2C/SPI LCD Backpack](https://learn.adafruit.com/i2c-spi-lcd-backpack.md)
- [Adafruit Trinket M0](https://learn.adafruit.com/adafruit-trinket-m0-circuitpython-arduino.md)
- [Interactive Gift Box](https://learn.adafruit.com/interactive-custom-gift-box.md)
- [3D Printed LED Fire Horns](https://learn.adafruit.com/3d-printed-led-fire-horns.md)
- [Screaming Cauldron](https://learn.adafruit.com/screaming-cauldron.md)
- [Zelda: Breath of the Wild – 3D Printed Guardian Sword with NeoPixel LEDs](https://learn.adafruit.com/breath-of-the-wild-guardian-sword-led-3d-printed.md)
- [NeoPixel Punk Collar](https://learn.adafruit.com/neopixel-punk-collar.md)
- [Adafruit LED Sequins](https://learn.adafruit.com/adafruit-led-sequins.md)
- [NeoPixel GoPro Lens Light](https://learn.adafruit.com/neopixel-gopro-lens-light.md)
- [Secret Knock Activated Drawer Lock](https://learn.adafruit.com/secret-knock-activated-drawer-lock.md)
- [Porting an Arduino library to CircuitPython: VL6180X Distance Sensor](https://learn.adafruit.com/porting-an-arduino-library-to-circuitpython-vl6180x-distance-sensor.md)
- [CircuitPython Basics: Digital Inputs & Outputs](https://learn.adafruit.com/circuitpython-digital-inputs-and-outputs.md)
- [NeoPixel LED Mickey Ears](https://learn.adafruit.com/neopixel-led-mickey-ears.md)
- [How to Choose a Microcontroller](https://learn.adafruit.com/how-to-choose-a-microcontroller.md)
- [Build your own SPARC workstation with QEMU and Solaris](https://learn.adafruit.com/build-your-own-sparc-with-qemu-and-solaris.md)
- [3D Printed NeoPixel Ring Hair Dress](https://learn.adafruit.com/neopixel-ring-hair-dress.md)
- [Pro Trinket as a USB HID Mouse](https://learn.adafruit.com/pro-trinket-usb-hid-mouse.md)
