Last active
April 19, 2020 15:57
-
-
Save peterfoxflick/7299e4e8752776879634f57dfe9c63e6 to your computer and use it in GitHub Desktop.
ATTINY Social Distancing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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