OutoSoft

Odd Software for Odd Jobs

Bike Sonar, part 2

The Arduino is coded up and it seems to be working!

Here's the Arduino code - pretty simple.

(sorry, I don't know how to display code all fancy-like at the moment!)


#include "LedControl.h"
#include "NewPing.h"

/* ---------------> Sonar Stuff <--------------- */
#define triggerPin 12
#define echoPin 10
#define maxDistance 400
NewPing sonar(triggerPin,echoPin,maxDistance);

/* ---------------> LED Stuff <--------------- */
#define Din 7
#define CLK 8
#define CS 9
LedControl lc = LedControl(Din,CLK,CS,1);

/* ---------------> speaker Stuff <--------------- */
#define speakerPin 11

#define triggerDistance 100 // cm
int i = 0;

void setup()
{
Serial.begin(115200);

// LEDs
lc.shutdown(false,0);
lc.setIntensity(0,8);
lc.clearDisplay(0);
for (i=0;i<=3;i++)
{
lc.setChar(0,i,i,false);
delay(100);
lc.setChar(0,i,' ',false);
}
for (i=3;i>=0;i--)
{
lc.setChar(0,i,i,false);
delay(100);
lc.setChar(0,i,' ',false);
}

pinMode(speakerPin, OUTPUT);

}

void loop()
{
delay(50);
int uS = sonar.ping();
int distance = 0;
int toneDelay = 0;

distance = uS / US_ROUNDTRIP_CM;
printDistanceOnLED(distance);
toneDelay = distance * 4;


if (triggerDistance > distance)
{
playTone(toneDelay,500);
delay(toneDelay);
playTone(toneDelay,500);
delay(toneDelay);
}
}

void printDistanceOnLED(int distance)
{
int metres = 0;
int cms = 0;
int cms_tens = 0;
int cms_ones = 0;

metres = distance / 100;
distance = distance - metres * 100;
cms_tens = distance / 10;
cms_ones = distance % 10;

// only display digits if non-zero
if (0 != metres)
{lc.setDigit(0,1,(byte)metres,false);}
else
{lc.setDigit(0,1,' ',false);}

if ((0 != cms_tens) || (0 != metres))
{lc.setDigit(0,2,(byte)cms_tens,false);}
else
{lc.setDigit(0,2,' ',false);}

if ((0 != cms_ones) || ((0 != cms_tens) || (0 != metres)))
{lc.setDigit(0,3,(byte)cms_ones,false);}
else
{lc.setDigit(0,3,' ',false);}

lc.setDigit(0,0,' ',true);

Serial.print(metres); Serial.print("."); Serial.print(cms_tens); Serial.print(cms_ones); Serial.println("m");
}

// duration in mSecs, frequency in hertz
// http://michael.thegrebs.com/2009/03/23/playing-a-tone-through-an-arduino-connected-piezo/
void playTone(long duration, int freq) {
duration *= 1000;
int period = (1.0 / freq) * 1000000;
long elapsed_time = 0;
while (elapsed_time < duration) {
digitalWrite(speakerPin,HIGH);
delayMicroseconds(period / 2);
digitalWrite(speakerPin, LOW);
delayMicroseconds(period / 2);
elapsed_time += (period);
}
}