Tuesday, April 16, 2013

Digispark - Ultrasonic Range finder

I had an HC-SR04 Ultrasonic range detector laying around and wanted to do something fun with it and my new digi spark. I set it up so that as objects became closer to the HC-SR04 the RGB would go from Green to red. (Blue when out of range)

One note here with the PWM, don't power it from a computer's USB port. you need to not have anything on pin 4, so I just powered it directly with 5volts to the 5v pin.

/* HC-S04 on a DigiSpark with and RGB Shield
Author: Chris Crumpacker
Date: January 2013
Copyright (c) 2013 Chris Crumpacker.  All right reserved.

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details. 

Sketch Notes: The HC-S04 Ultrasonic detector is attached to Pins 3 and 5. The RGB shield is set to use pins 0, 1, and 4 for PWM. As something comes closer to the detector the RGB goes from green to red.

Using the NewPing library from Teckel http://arduino.cc/forum/index.php?topic=106043.0 I did have to remove the timer functions to get it working against the digispark. I have version 1.5 and Teckel mentioned support for the atTiny was going to be added in V1.6

Other than the pin numbering for PWM pins nothing here is DigiSpark specific
and would work on any arduino once the pics are updated */

#include <NewPing.h>

#define TRIGGER_PIN 3
#define ECHO_PIN 5
#define RED_PIN 0
#define GREEN_PIN 1
#define BLUE_PIN 4
#define MAX_DISTANCE 60

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  pinMode(RED_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);
void loop() {
  uint8_t distance = sonar.ping_cm();

  if (distance) {
    uint8_t greenValue = map(distance, 1, MAX_DISTANCE, 0, 255);  //Map the distance range to a range of 0 to 255 to the pwm value for the Green LED
    uint8_t redValue = 255 - greenValue;
    analogWrite(GREEN_PIN, greenValue);
    analogWrite(RED_PIN, redValue);
    digitalWrite(BLUE_PIN, LOW);
  } else {
    //Out of range, turn the LED blue
    digitalWrite(GREEN_PIN, LOW);
    digitalWrite(RED_PIN, LOW);   
    digitalWrite(BLUE_PIN, HIGH);

1 comment: