Hi guys.
I've been trying to read a Ultrasonic sensor HC-SR04 using the NewPing library to control a bipolar stepper motor, without using any library for the stepper cotrol, which i suceeded.
However, i'm still having a little issue while the motor is moving. I've set the readings to happen every 125ms, or 8 times per seconds, and during the readings, the stepper motor moves with little bumps, the same thing that happens by using de pulseIn command, which the program stops and waits for the Echo pulse to happen. I'm posting my code below, and ask if you guys see any mistakes that i may have done.
#include <NewPing.h>
const int pulsePin = LED_BUILTIN;// the number of the LED pin
bool flagEnable = LOW;
int pulseState = LOW;
// constants won't change:
const long intervalServ = 250;
unsigned long previousMillis = 0;
unsigned long interval = 125;
unsigned long pingTimer = 0;
double distance = 0;
void echoCheck();
#define TRIGGER_PIN 6
#define ECHO_PIN 5
#define MAX_DISTANCE 200
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
// set the digital pin as output:
pinMode(pulsePin, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, INPUT_PULLUP);
unsigned long pingTimer = millis();
Serial.begin(9600);
}
void loop() {
unsigned long currentMillis = micros();
unsigned long tEnable = millis();
if (millis() >= pingTimer) { // pingSpeed milliseconds since last ping, do another ping.
pingTimer += interval; // Set the next ping time.
sonar.ping_timer(echoCheck); // Send out the ping, calls "echoCheck" function every 24uS where you can check the ping status.
}
distance = sonar.ping_result / US_ROUNDTRIP_CM;
if (distance >= 5.0) {
flagEnable = HIGH;
digitalWrite(12, flagEnable);
}
else {
flagEnable = LOW;
digitalWrite(12, flagEnable);
}
if (currentMillis - previousMillis >= intervalServ) {
// save the last time you blinked the LED
previousMillis = currentMillis;
if (pulseState == LOW) {
pulseState = HIGH;
currentMillis = micros();
} else {
pulseState = LOW;
currentMillis = micros();
}
digitalWrite(pulsePin, pulseState);
}
}
void echoCheck() { // Timer2 interrupt calls this function every 24uS where you can check the ping status.
// Don't do anything here!
if (sonar.check_timer()) { // This is how you check to see if the ping was received.
// Here's where you can add code.
Serial.print("Ping: ");
Serial.print(sonar.ping_result / US_ROUNDTRIP_CM); // Ping returned, uS result in ping_result, convert to cm with US_ROUNDTRIP_CM.
Serial.println("cm");
}
}