Wyatt  1.0.1
EncoderAdapter.cpp
1 #include "hardwareinterface/EncoderAdapter.h"
2 #include <iostream>
3 
4 EncoderAdapter::EncoderAdapter(int channelA, int channelB, int ticksPerRev, Hardware hardware):
5  m_channelA(channelA),
6  m_channelB(channelB),
7  m_count(0),
8  m_lastTransition(-2),
9  m_ticksPerRevolution(ticksPerRev),
10  hardware(hardware)
11 {
12  m_revolutionsPerTick = 10.0 / (double)ticksPerRev;
13  pinMode(channelA, INPUT);
14  pinMode(channelB, INPUT);
15  m_channelAState = digitalRead(m_channelA);
16  m_channelBState = digitalRead(m_channelB);
17 }
18 
20 {
21 
22 }
23 
25 {
26  int numTicks = 0;
27  while (m_signal >= 0)
28  {
29  if (m_signal == 1) // Reset count
30  {
31  m_count = 0;
32  m_signal = 0;
33  }
34  int newChannelAState = digitalRead(m_channelA);
35  int newChannelBState = digitalRead(m_channelB);
36  int newTransition = (newChannelAState != m_channelAState) ? 1 : (newChannelBState != m_channelBState) ? -1 : 0;
37  // Calculate encoder speed in RPM, store in m_speed
38  numTicks += abs(newTransition);
39  if (numTicks >= 10)
40  {
41  numTicks = 0;
42  std::chrono::high_resolution_clock::time_point newTime = std::chrono::high_resolution_clock::now();
43  std::chrono::microseconds diffTime = std::chrono::duration_cast<std::chrono::microseconds>(newTime - m_lastTickTime);
44  m_lastTickTime = newTime;
45  m_speed = (m_revolutionsPerTick / (double)diffTime.count()) * 60000000.0;
46  m_speed = m_speed * GEAR_RATIO;
47  }
48  m_channelAState = newChannelAState;
49  m_channelBState = newChannelBState;
50  // If last transition is uninitialized, initialize direction to whichever transition just occurred. It will
51  // be forward if the A channel is read first, and backward if B is read first. Otherwise, direction
52  // will be reversed if it reads two transitions from the same channel in sequence.
53  m_direction = (m_lastTransition == -2) ? newTransition : (newTransition == m_lastTransition) ? -m_direction : m_direction;
54  // Set last transition only if a new transition has occurred.
55  m_lastTransition = (newTransition == 0) ? m_lastTransition : newTransition;
56  // Add the direction (-1, 1) to the encoder count. If no transition has occurred, do nothing.
57  m_count = (newTransition != 0) ? (long)m_count + m_direction : (long)m_count;
58  }
59  return NULL;
60 }
61 
63 {
64  return m_count;
65 }
66 
68 {
69  this->signal(1);
70 }
71 
72 std::list<IMessage*>* EncoderAdapter::read()
73 {
74  std::list<IMessage*>* messages = new std::list<IMessage*>();
75  IMessage* msg = new EncoderMessage(this->hardware, m_speed);
76  messages->push_back(msg);
77 
78  return messages;
79 }
80 
82 {
83  return m_speed;
84 }
EncoderAdapter(int channelA, int channelB, int ticksPerRev, Hardware hardware)
std::list< IMessage * > * read() override
double getSpeedRPM()
~EncoderAdapter() override
void * run() override