am a complete beginner at coding with Arduino, although I have used them for a few years by copying other peoples code. I only understand a tiny fraction of the layout of a sketch and would really appreciate some help to solve, what I believe, is a simple problem.
I have a sketch to control the speed and direction of a stepper motor:-
/*
Stepper Motor Test
stepper-test01.ino
Uses MA860H or similar Stepper Driver Unit
Has speed control & reverse switch
DroneBot Workshop 2019
https://dronebotworkshop.com
*/
// Defin pins
int reverseSwitch = 2; // Push button for reverse
int driverPUL = 7; // PUL- pin
int driverDIR = 6; // DIR- pin
int spd = A0; // Potentiometer
// Variables
int pd = 500; // Pulse Delay period
boolean setdir = LOW; // Set Direction
// Interrupt Handler
void revmotor (){
setdir = !setdir;
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
pinMode (driverPUL, OUTPUT);
pinMode (driverDIR, OUTPUT);
attachInterrupt(digitalPinToInterrupt(reverseSwitch), revmotor, FALLING);
}
void loop() {
pd = map((analogRead(spd)),0,1023,1000,150);
digitalWrite(driverDIR,setdir);
digitalWrite(driverPUL,HIGH);
digitalWrite(LED_BUILTIN, HIGH);
delayMicroseconds(pd);
digitalWrite(driverPUL,LOW);
delayMicroseconds(pd);
}
This works perfectly with my stepper driver and stepper motor with good speed control. However, the author did warn that debounce might be a problem and this has proved to be the case. I understand the principal of debounce and I have studied a number of debounce sketches and can also understand the method of reduction using a few milliseconds delay. I believe that the following code is as simple as it can get but I have no idea how to incorporate this in the above sketch.
bool debounce() {
static uint16_t state = 0;
state = (state<<1) | digitalRead(btn) | 0xfe00;
return (state == 0xff00);
}
(The author appears to have split the code into two parts (I think)
#define btn 2 //assuming we use D2 on Arduino
void setup() {
pinMode(btn, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
if (debounce()) {
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}
}
Can anyone look at these sketches and advise me if a) they are compatible and b) how do incorporate the debounce code into the working sketch?
Thanks in advance from a complete coding numptee (Scottish expression!)