week eight

input devices


ultrasonic sensor

For this week, I decided to start on my final project, a spa that would mist and play music when a person's head was detected inside of the box. This was a perfect opportunity to use the ultasonic sensor (which also happens to count as an input device). The ones available from the fab lab inventory are the SunFounder Ultrasonic Module HC-SR04 Distance Sensors.

ultrasonic

ultrasonic sensor

The board that I ended up making for my final project spanned a lot of weeks, so I'll be documenting the details of that on my final project page and focus mostly on the ultrasonic sensor here, so the following is assuming you have a board that already works (can connect the sensor to the microcontroller).

The ultrasonic sensor has 4 pins - VCC, GND, TRIG, and ECHO. The VCC and GND connect to 5V and GND, the ECHO pin can connect to any pin, and the TRIG pin should connect to a pin that can support PWM. Here's a handy diagram:

ultrasonicpins

ultrasonic pin connections (to an Arduino board)

From this diagram, you can just pick any pins on your microcontroller to connect the ultrasonic sensor to, as long as they aren't already connected to something else and they can support whatever pin type you're trying to connect. For the ultrasonic sensor, it's good to note that the "~11" in the picture above means that that pin can support PWM, so I needed to pick a pin on the ATtiny44 that could do the same.

ultrasonic2

ultrasonic hooked up to my board

I wrote the code for reading distance in inches in Arduino. You'll see that in order to print the distance reading in inches, there's a conversion that needs to happen in code.

w8code

ultrasonic sensor code

A couple things were different from what I was used to doing with Arduino (using an Arduino board). Because I made my own board, I needed to import the SoftwareSerial library in order to set up serial connection. The line of code setting this up is SoftwareSerial my_serial(0, 1); where 0 is rx and 1 is tx. This is an example of SoftwareSerial by Arduino that I found helpful throughout this process.

Something that I initially had trouble with was correctly figuring out what my rx and tx pins were. Reading the ATtiny44 pins, I thought (rx,tx) should've been (1,0). Anthony informed me that this actually switches on the other end (the FTDI), so (0,1) is what I needed to use.

Another problem that I encountered was having trouble uploading, though all of my "tools" settings seemed correct (referencing weeks four and six). Anthony again helped me with this - we changed the clock to 8 MHz internal. The serial monitor was still printing strings of "?" though the 9600 baud rate was correct, so he clicked on "burn bootloader," which somehow ended up fixing this! Not sure how or what that means, but it's a good fix that I used many times subsequently.

Overall, the sensor reads pretty accurately! Here are some videos of its operation.

videos: reading ultrasonic sensor