Skip to content

Instantly share code, notes, and snippets.

@bradmartin333
Created July 27, 2022 23:02
Show Gist options
  • Save bradmartin333/042b997fe2df4f37fe24a6fb8a284563 to your computer and use it in GitHub Desktop.
Save bradmartin333/042b997fe2df4f37fe24a6fb8a284563 to your computer and use it in GitHub Desktop.
#include <AccelStepper.h>
#define dirPin 2
#define stepPin 3
#define motorInterfaceType 1
AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);
#define trigPin 4
#define echoPin 5
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
#include <TM1637.h>
#define clk 6
#define dio 7
TM1637 tm(clk, dio);
const int numReadings = 100;
int readings[numReadings]; // the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average
void setup()
{
stepper.setMaxSpeed(1000);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
tm.init();
tm.set(2); //set brightness; 0-7
for (int thisReading = 0; thisReading < numReadings; thisReading++) {
readings[thisReading] = 0;
}
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// subtract the last reading:
total = total - readings[readIndex];
// read from the sensor:
readings[readIndex] = distance;
// add the reading to the total:
total = total + readings[readIndex];
// advance to the next position in the array:
readIndex = readIndex + 1;
// if we're at the end of the array...
if (readIndex >= numReadings) {
// ...wrap around to the beginning:
readIndex = 0;
}
// calculate the average:
average = total / numReadings;
int thisSpeed = -180 + (4 * average);
stepper.setSpeed(thisSpeed);
stepper.runSpeed();
displayNumber(thisSpeed * -1);
}
void displayNumber(int num) {
tm.display(3, num % 10);
tm.display(2, num / 10 % 10);
tm.display(1, num / 100 % 10);
tm.display(0, num / 1000 % 10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment