Hello,
I am a Mechanical Engineering student and my senior design team and I are integrating an Arduino into our project. Since we are mechanical we don't have a lot of experience with coding. We Are trying to use the Arduino and rotary encoder as a timer. We need the time to start once the shaft that is coupled to the encoder starts spinning and the timer needs to stop when the shaft stops. Anything helps. I have attached a link to the encoder and a sample project that has helped us.
Anything helps.
Thanks,
Braden.
In this post we learn how to connect optical rotary encoder with arduino, this tutorial help to use optical rotary encoder with arduino.
Estimated reading time: 3 minutes
Did you get the sample code to work for you?
Yes, the sample code works just fine. its when we try to tweak it were things don't wok.
Do you need help with that code?
The sample code is what we are trying to modify to get it to time the encoder.
And that modified code is not being shown.
What is the time period needed to determine a stopped shaft from a slowly moving one. That is, how long of a time between counts defines "stopped"
Correct. Its not far off from the base code so I didn't think it was helpful.
But if the base code works and the code with your change does not work, how can anyone know what you tried and failed at? You did come here for help, did you not?
The shaft is coupled to a break so it should stop suddenly and it doesn't need to be super accurate. Id say about tenth of a second maybe.
gfvalvo
February 16, 2022, 11:15pm
12
So, 12 posts into it and we have yet to see the code that you actually need help with. Things aren't exactly off to an auspicious start, are they?
Assuming your encoder is connected to the External Interrupt pins (2 and 3 on an UNO):
const byte EncoderAPin = 2;
const byte EncoderBPin = 3;
volatile boolean IsMoving = false;
volatile unsigned long TimeStartedMoving;
volatile unsigned long TimeLastMoved;
void EncoderISR()
{
TimeLastMoved = millis();
if (!IsMoving)
{
IsMoving = true;
TimeStartedMoving = TimeLastMoved;
}
}
void setup()
{
Serial.begin(115200);
attachInterrupt(digitalPinToInterrupt(EncoderAPin), EncoderISR, CHANGE);
attachInterrupt(digitalPinToInterrupt(EncoderBPin), EncoderISR, CHANGE);
}
void loop()
{
noInterrupts();
unsigned long startTime = TimeStartedMoving;
unsigned long moveTime = TimeLastMoved;
interrupts();
if (IsMoving && millis() - moveTime >= 100)
{
// It has been over 0.1 seconds since the shaft last moved.
unsigned long timeSpentMoving = moveTime - startTime;
Serial.print("Shaft moved for ");
Serial.print(timeSpentMoving);
Serial.println(" milliseconds.");
IsMoving = false;
}
}
system
Closed
August 16, 2022, 2:50pm
14
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.