#include <NewPing.h>
#define SONAR_NUM 4
#define MAX_DISTANCE 100
#define PING_INTERVAL 33
unsigned long pingTimer[SONAR_NUM];
unsigned int cm[SONAR_NUM];
uint8_t currentSensor = 0;
NewPing sonar[SONAR_NUM] = {
NewPing(4,8,MAX_DISTANCE),
NewPing(5,9,MAX_DISTANCE),
NewPing(6,10,MAX_DISTANCE),
NewPing(7,11,MAX_DISTANCE)
};
int step_pin=2;
int dir_pin=3;
int run;
int startPin;
int customDelay,customDelayMapped;
void setup() {
Serial.begin(115200);
pingTimer[0] = millis() +75;
for(uint8_t i = 1; i<SONAR_NUM; i++)
pingTimer[i]=pingTimer[i-1]+PING_INTERVAL;
pinMode(dir_pin, OUTPUT);
pinMode(step_pin, OUTPUT);
digitalWrite(dir_pin, LOW);
run = 0;
startPin = 13;
pinMode(startPin,INPUT_PULLUP);
}
void loop() {
customDelayMapped = speedUp();
if(digitalRead(startPin)==LOW)
{
{
digitalWrite(step_pin, HIGH);
delayMicroseconds(customDelayMapped);
digitalWrite(step_pin, LOW);
delayMicroseconds(customDelayMapped);
}
for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
if (millis() >= pingTimer[i]) { // Is it this sensor's time to ping?
pingTimer[i] += PING_INTERVAL * SONAR_NUM; // Set next time this sensor will be pinged.
sonar[currentSensor].timer_stop(); // Make sure previous timer is canceled before starting a new ping (insurance).
currentSensor = i; // Sensor being accessed.
cm[currentSensor] = 0; // Make distance zero in case there's no ping echo for this sensor.
sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
}
}
if (cm[0]==15)
{digitalWrite(step_pin,LOW);
delayMicroseconds(customDelayMapped);}
}
}
void echoCheck() { // If ping received, set the sensor distance to array.
if (sonar[currentSensor].check_timer()) {
cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
pingResult(currentSensor);
}
}
void pingResult(uint8_t sensor) { // Sensor got a ping, do something with the result.
// The following code would be replaced with your code that does something with the ping result.
Serial.print(sensor);
Serial.print(" ");
Serial.print(cm[sensor]);
Serial.println("cm");
}
int speedUp() {
int customDelay = analogRead(A0);
int newCustom = map(customDelay, 1023, 0, 0,1600);
return newCustom;
}
I want to do a conveyor belt with 4 distance sensor to stop a thing in middle of belt
I have a stepper motor(with EasyDriver), on off button and a potentiometer for speed controll...
Can someone help me please?
