OK - now pretty much happy with the digispark / HC-SR04 interface. Using a 'newping' library from here https://code.google.com/p/arduino-new-ping/ to control the interface which makes the digispark code simpler. - The code writes to the USB every time we get an input on the USB. - I will then use the Pi to send a 'request' to the digispark. - The digispark does the measurement (median / average of 20 pings), and returns the distance in cm.
Note that I had to comment out the 'timer' functions in the newping library to get it to compile for the digispark. - Think the Arduino has some functionallity which isn't available in the digispark.
HC-SR04 trigger connected to digispark pin 0.
HC-SR04 echo connected to digispark pin 2.
(Mine is a rev A digispark which means that the onboard LED is connected on Pin1, and I use this to flash when data is transmitted.)
Code for the digispark sketch.
#include <DigiUSB.h>
#include <NewPing.h>
//
// AJR - 17/4/13. USing HC-SR04 to measure distance
// and output on the USB so it can be read on an RPi.
// Use with the receive python progs
// from the Digispark examples.
// DigisparkExamplePrograms-master.
//
// Utilising the NewPing library from https://code.google.com/p/arduino-new-ping/
// Note that this will only compile if several of the timer functions are removed
// from the library. I think there are some bits missing on the digispark which
// would otherwise be present in arduino. One thing it is missing is memory!
// I keep running out of memory in the code space, and if I try to do too much here,
// then also run out. - Would like to have returned version string etc, but not
// enough room.... Ho, hum.
//
#define trigPin 0
#define echoPin 2
#define maxDist 300
// Pretty self explanatory below, but maxDist is the distance beyond
// which a ping is considered invalid.
NewPing sonar(trigPin, echoPin, maxDist);
void setup() {
DigiUSB.begin();
pinMode(1,OUTPUT); //give us some idea it's workng by flashing led
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
}
void measure() {
int lastRead;
digitalWrite(1,HIGH);
DigiUSB.delay(100);
// - This is where we call the NewPing library. Don't think digispark has enough memory to do 50
// but it seems reliable with 20.
unsigned int uS = sonar.ping_median(20);
DigiUSB.println(uS / US_ROUNDTRIP_CM);
digitalWrite(1,LOW);
delay(50); //sleep for 0.5 seconds before sending again.
}
void get_input() {
int lastRead;
// when there are no characters to read, or the character isn't a newline
while (true) { // loop forever
if (DigiUSB.available()) {
// something to read
lastRead = DigiUSB.read();
if (lastRead == '\n') {
measure();
break; // when we get a newline, break out of loop
}
}
// refresh the usb port for 10 milliseconds
DigiUSB.delay(10);
}
}
void loop() {
// print output
// DigiUSB.println("Waiting for input...");
digitalWrite(1, LOW);
// Measure....
get_input();
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.