Hello, I'm new to this forum. I need help.
I have a 12v 10rpm DC geared motor, 2 inductive proximity sensors, push button and l298n drivers.
I want the Arduino code to work as follows using millis, 2D array.
when the button is pressed the code should start.
when the motor direction is forward and sensor 2 is triggered motor should stop and when the direction is revere and sensor 1 is triggered then the motor should stop.
I've a working code:
the problem is when the sensor2 is triggered then it stops but in reverse direction, it is not running. please help me with this.
double dc_mot[][5] = { {1, 0, 5, 255, 1}, {1, 6, 10, 255, -1},{1, 10, 15, 255, 1}, {1, 15, 20, 255, -1} };
int animLen = sizeof(dc_mot)/sizeof(dc_mot[0]);
unsigned long previousMillis = 0;
const long interval = 100;
const int buttonPin = 12;
int buttonState;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
int showStarted = LOW;
unsigned long showStartTime = 0;
int in1 = 4;
int in2 = 3;
int enA = 5;
int sensor1 = 9;
int sensor2 = 8;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enA, OUTPUT);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
pinMode(sensor1, INPUT_PULLUP);
pinMode(sensor2, INPUT_PULLUP);
motors(255, -1);
delay(10);
Serial.begin(9600);
Serial.println("begin");
}
void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if ((buttonState == LOW) && (showStarted == LOW)) {
showStarted = HIGH;
showStartTime = millis();
}
}
}
if (showStarted){
unsigned long currentMillis = millis() - showStartTime;
unsigned long temp = currentMillis/100;
double currentMillisInt = temp/10.0f;
for (int i = 0; i < animLen; i++){
if (dc_mot[i][1] == currentMillisInt)
motors(dc_mot[i][3], dc_mot[i][4]);
else if (dc_mot[i][2] == currentMillisInt)
motors(dc_mot[i][3], 0);
}
if (currentMillis - previousMillis >= interval){
previousMillis = currentMillis;
for (int i = 0; i < animLen; i++){
if (dc_mot[i][1] == currentMillisInt)
motors(dc_mot[i][3], dc_mot[i][4]);
else if (dc_mot[i][2] == currentMillisInt)
motors(dc_mot[i][3], 0);
}
}
}
lastButtonState = reading;
Serial.print("sens 1 = ");Serial.print(digitalRead(sensor1)); Serial.print(", sens 2 = ");Serial.println(digitalRead(sensor2));
if (digitalRead(sensor1) == LOW && dc_mot[animLen-1][4] == 1) {
motors(255, 0);
}
if (digitalRead(sensor2) == LOW && dc_mot[animLen-1][4] == -1) {
motors(255, 0);
}
}
void motors(int speed, int dir){
if (dir == 1){
analogWrite(enA, speed);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
}else if (dir == -1){
analogWrite(enA, speed);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
} else if (dir == 0) {
analogWrite(enA, speed);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
}
}
please help me with this. thank you.