Hi there, I am in need of some extra brain power to solve this issue I am facing with my project.
So the gist is, I'm using some 12v DC brushless motors that I purchased from AliExpress to convert my desk into a sit/stand desk as a project. These motors have been working fine so far, but I have been trying to use the motor's built-in hall effect sensor to count the pulses when the motor turns, and then use this determine the height that the desk is at.
The problem I am having is that the counts I am getting from the motors are very unreliable and prone to skip about quite a bit when changing direction, and I cannot work out why.
I have measured the square wave that the motor is outputting, and this seems to be fine.
Ill post the code below that I am running on an Arduino Mega to capture these pulses and keep track of them. I've
also posted a capture of the square wave on the oscilloscope.
Any suggestions would be great as I've been trying to solve this for a while now with no luck.
Thanks in advance,
Hayden.
const int DownButton = 10;
const int UpButton = 11;
const int MotorUp1 = 6;
const int MotorDown1 = 7;
const int DistanceButton = 9;
const unsigned int PulsePin1 = 2;
volatile unsigned long pulseCount;
volatile bool countChanged;
int DIRECTION = 1;
double MM_PER_PULSE = 0.016;
void isr () {
countChanged = true;
pulseCount = pulseCount + DIRECTION;
}
void setup()
{
Serial.begin(9600);
pinMode(DownButton, INPUT_PULLUP);
pinMode(UpButton, INPUT_PULLUP);
pinMode(MotorUp1, OUTPUT);
pinMode(MotorDown1, OUTPUT);
pinMode(PulsePin1, INPUT);
pinMode(DistanceButton, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PulsePin1), isr, RISING);
Serial.println("Start");
}
void loop() {
static int lastUp = LOW;
static int lastDown = LOW;
static int lastDistance = HIGH;
int Up = digitalRead(UpButton);
int Down = digitalRead(DownButton);
if (Up != lastUp || Down != lastDown)
{
lastUp = Up;
lastDown = Down;
if (Up == HIGH && Down == HIGH ) // neither button pressed
{
digitalWrite(MotorDown1, HIGH);
digitalWrite(MotorUp1, LOW);
}
else if (Up == LOW && Down == HIGH) // UpButton pressed
{
DIRECTION = 1;
digitalWrite(MotorDown1, HIGH);
digitalWrite(MotorUp1, HIGH);
}
else if (Up == HIGH && Down == LOW) // DownButton pressed
{
DIRECTION = -1;
digitalWrite(MotorDown1, LOW);
digitalWrite(MotorUp1, HIGH);
}
else // Both buttons pressed
{
// undefined, no effect
}
}
int Distance = digitalRead(DistanceButton);
if (Distance != lastDistance) {
lastDistance = Distance;
if (Distance == LOW) {
double distance = pulseCount * MM_PER_PULSE;
Serial.println(distance);
}
}
}