Skip to content

Instantly share code, notes, and snippets.

@peterfoxflick
Last active April 19, 2020 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterfoxflick/7299e4e8752776879634f57dfe9c63e6 to your computer and use it in GitHub Desktop.
Save peterfoxflick/7299e4e8752776879634f57dfe9c63e6 to your computer and use it in GitHub Desktop.
ATTINY Social Distancing
/*
* Original Ultrasonic code by Rui Santos, https://randomnerdtutorials.com
* Modified by Peter Fox Flick for attiny, peterfoxflick.com
* VIDEO: https://youtu.be/dF5E5jsWSZA
Ultrasonic sensor Pins:
VCC: +5VDC
Trig : Trigger (INPUT) - Pin 0
Echo: Echo (OUTPUT) - Pin 1
GND: GND
LED Schematic
Pin 2 -- LED -- 330 Resistor -- GND
*/
int trigPin = 0; // Trigger MOSI 0
int echoPin = 1; // Echo MISO 1
int ledPin = 2;
long duration;
long dist[3];
int pos = 0;
void setup() {
//Define inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// Convert the time into a distance
dist[pos] = (duration/2) / 29.1;
pos = pos > 2 ? 0 : pos + 1;
//use a rolling average to help prevent spikes
long sum = 0;
for(int i = 0; i < 3; i++){
sum += dist[i];
}
long avg = sum / 3;
if(avg < 200){
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
delay(500);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment