Mods, How about a sub-forum just for people to upload their code?
24 hours since I got it and really enjoying my Sparki!
I wrote a routine to have the range finder scan 180 degrees and return the angle of the closest detected object. Demo program does the scan, points the range finder in the direction found and shows angle & distance on the LCD, waits 10 seconds and loops.
I can see the routine used in steering or as a way to start other actions when something comes within range, maybe as a kind of burglar alarm.
The other obvious adaptation would be to change the routine to find the direction with the most distant object.
No copyrights claimed, use or adapt as you like with or without attribution.
[code]/*
LookAtClosest by Zax
Demo of routine to determine angle of closest
object the Ultrasonic Range Finder can detect
Program scans for closest, points
the servo in that direction and prints
angle & distance on the LCD
*/
#include <Sparki.h>
void setup()
{
sparki.clearLCD();
}
void loop()
{
// Call routine to find angle of nearest object
int clsdir = closestDir();
// Turn servo to angle
sparki.servo(clsdir);
// Print angle on LCD
sparki.print(“Angle:”);
sparki.println(clsdir);
// Find distance
int cm = sparki.ping();
// Print distance
sparki.print(“Distance:”);
sparki.println(cm);
sparki.updateLCD();
// Wait 10 seconds
delay(10000);
}
int closestDir()
/* Routine to find the angle that has the
nearest object Sparki can "see"
As the servo rotates, the RGB LED will
light if the current distance is the closest
*/
{
// Initialize closest distance
// you could set this low to ignore
// objects farther away
int closest = 999;
// Initialize direction - this will be
// returned if nothing is closer than
// closest, set above
int dir = 0;
// step the servo throgh the angles
for(int angle = -90; angle < 91; angle = angle + 10)
{
//set servo angle
sparki.servo(angle);
//delay(50);
//read distance
int cm = sparki.ping();
// check if distance can be read
if (cm != -1)
{
//Is this the closest yet?
if (cm < closest)
{
//set this as closest abgle
dir = angle;
// update closest distance
closest = cm;
// light RGB as indicator new closest
//has been found
sparki.RGB(RGB_BLUE);
}
else
{
// Not the closest - turn off RGB
sparki.RGB(RGB_OFF);
}
}
}
return dir;
}[/code]
