Wednesday, 17 April 2013

Raspberry Pi / Digispark distance measurement 1.

I used the following sketch to be able to receive the distance measurement from an HC-SR04 ultrasound sensor connected to the Digispark on the Pi using the digispark example '' script.

#include <DigiUSB.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.

#define trigPin 0
#define echoPin 2
char data[] = "The quick brown fog jumped over the lazy dogx";
long distance = 42;
long duration;

void setup() {
  pinMode(1,OUTPUT); //give us some idea it's workng by flashing led
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

void measure() {
  int lastRead;
  while (true) { // loop forever
    // Try measure, and send response.
    digitalWrite(trigPin, LOW);  // Trig needs to go high on 10us pulse
    delayMicroseconds(2); // wait....
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10); // Trig pin pulse time.
    digitalWrite(trigPin, LOW);  // Now, we time to echo.
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    ltoa(distance, data, 10);
    strcat(data, " cm");
    delay(500); //sleep for 0.5 seconds before sending again.

void loop() {
  // print output
  DigiUSB.println("Waiting for input...");
  digitalWrite(1, LOW); 
  // Measure....

No comments:

Post a Comment

Note: only a member of this blog may post a comment.