adapter_motor.ino 9.59 KB
Newer Older
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
1
2
3
4
5
6
7
8
9
10
11
//***********************************************************************//
/*
Aquanaute - PWM interpreter
Code to read a pwm exit of the navio2 to transform it to a byte speed command, to control a continuous drive motor with an absolute encoder.
Made by: Ricardo RICO URIBE - Internt at U2IS during the summer of 2020
Helpers:
- Thibault TORALBA
- Thomas SIMON
*/
//***** CONSTANTS *****//
const byte INTERRUPT_NOISE_THRESHOLD = 10; //microseconds in which the detection of interrupt will ignore a change
12

Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
13
14
15
16
17
const word MOTOR_CENTER = 1000;  //motor position center, this was arbitrarily chosen
const word MOTOR_RIGHT = 1300;   //300 steps, arbitrarily chosen to indicate full right, this is aprox 90°
const word MOTOR_LEFT = 700;     //300 steps, arbitrarily chosen to indicate full left, this is aprox 90°
const byte MOTOR_THRESHOLD = 10; //value to range the motor position to eliminate oscilation
const word MOTOR_RANGE = MOTOR_RIGHT - MOTOR_LEFT;
18

Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
19
20
21
22
23
const word RADIO_CENTER = 1492;  //radio "high time" when radio control is centered, experimentaly obtained, directly linked with the trim value of ardupilot params
const word RADIO_RIGHT = 1872;   //radio "high time" when radio control is full right, experimentaly obtained, directly linked with the max pwm value of ardupilot params
const word RADIO_LEFT = 1120;    //radio "high time" when radio control is full left, experimentaly obtained, directly linked with the min pwm value of ardupilot params
const byte RADIO_THRESHOLD = 10; //value to range the time calculated to eliminate oscilation
const word RADIO_RANGE = RADIO_RIGHT - RADIO_LEFT;
24

Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
25
26
27
28
29
30
const byte COMM_ALL_STOP = 0;
const byte COMM_STOP = 64;
const byte COMM_FULL_FWD = 127;
const byte COMM_MED_FWD = 100;
const byte COMM_FULL_BCK = 1;
const byte COMM_MED_BCK = 28;
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

const byte RADIO_SCALE_CENTER = 50;
const byte RADIO_SCALE_LEFT = 0;
const byte RADIO_SCALE_RIGHT = 100;

const byte MAX_ERROR_BEFORE_SPEED_IS_SET_TO_MAX = 30;
const byte ERROR_CENTER_THRESHOLD = 1;
const byte ERROR_MIN = -50;
const byte ERROR_MAX = 50;
//scale (-50,50) to (1-127) f(x) = (b-a)(x - min)/max - min  + a
const float SPEED_COMMAND_SCALE_COEFFICIENT = (COMM_FULL_FWD-COMM_FULL_BCK)/(ERROR_MAX - ERROR_MIN)

const byte TOTAL_OF_MESSAGES = 4;
const byte BYTE_CARRY_LEFT = 8;

const byte HEX_CHAR_C =0x43; //Char "C", by design this is the message that the encoder expects to respond with its position
const word FIFTY_HZ = 331; // = (16*10^6) / (50*1024) - 1 (must be <65536) // 311 = 50Hz
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
48
49
//***** Variables *****//
byte speed_command = COMM_ALL_STOP; //Message to send to the Motor Controller
50

Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
51
const int _kp = 1; //Controller Proportional Coefficient
52

Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
53
54
55
56
57
58
const byte interrupt_pin = 20;                    //Pin to detect interruptions (connected to the yaw channel in the Navio)
static volatile uint32_t delta_us;                //time "high"
static volatile uint32_t prev_change_date_us = 0; //record previous time
static volatile uint32_t pos = 0;                 //motor position
static volatile byte count = 0;                   //counter for position response bytes (0-3)
static volatile uint32_t recv = 0;                //Bytes recieved
59

Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
60
61
62
63
64
bool first = true;                    //first byte recieved
bool started = false;                 //setup to center the motor
bool go_print = false;                //debug routine
static volatile int scale_pos = 50;   //scale of position, initialized as centered
static volatile int scale_radio = 50; //scale of radio controller position, initialized as centered
65
//***********************************************************************//
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
66
67
68
69
70
71
void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);    //usb pc
  Serial1.begin(9600);   //sabertooth driver (speed selected physically on the driver)
  Serial2.begin(115200); //multiplexer (speed recommended by the manufactor)
72
  Serial1.write(speed_command);
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
73
74
75
  while (!Serial)
  {
    //wait for pc connection or RP4 power_up
76
77
  }
  cli(); //stop interrupts
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
78
79
80
81
82

  //setup for timed interrupts
  TCCR4A = 0; // set entire TCCR4A register to 0
  TCCR4B = 0; // same for TCCR4B
  TCNT4 = 0;  //initialize counter value to 0
83
  // set compare match register for 20hz increments
84
  OCR4A = FIFTY_HZ;// = (16*10^6) / (50*1024) - 1 (must be <65536) // 311 = 50Hz // turn on CTC mode
85
86
  TCCR4B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
87
  TCCR4B |= (1 << CS12) | (1 << CS10);
88
89
90
  // enable timer compare interrupt
  TIMSK4 |= (1 << OCIE4A);

Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
91
92
93
94
95
  //Setup for external Interrupt
  sei();                                                              //allow interrupts
  pinMode(interrupt_pin, INPUT_PULLUP);                               //activate internal resistor for interrupt pin
  attachInterrupt(digitalPinToInterrupt(interrupt_pin), pwm, CHANGE); //set pin to read external interrupts
} //end setup
96
//***********************************************************************//
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
97
98
99
100
//*****Time Interrupt - Request the Motor Position*****//
/*Request the motor position, with a frecuency of 50Hz*/
ISR(TIMER4_COMPA_vect)
{
101
  Serial2.write(HEX_CHAR_C); 
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
102
103
  count = 0;           //reset of message counter
  first = true;        //reset of first message
104
105
}
//***********************************************************************//
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
106
107
108
109
110
111
112
113
//*****Physical Interruption - Read of Navio PWM*****//
/*Read a change from low to high or from high to low in the pwm signal sended by the navio,
and obtain the "high" time to interpret it as duty cycle and to translate it to and scale between 0 and 100,
where 0 is full left, 50 is center, and 100 is full right*/
void pwm()
{
  uint32_t curr_date = micros();
  bool state_us;
114
  /* Record the previous pin state since it has just changed. */
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
115
116
117
118
119
120
121
122
123
  state_us = !digitalRead(interrupt_pin);
  /* Ensure that we have detected a falling edge, i.e. the previous level of the pin was HIGH. */
  if (state_us)
  {
    delta_us = curr_date - prev_change_date_us;
    if (delta_us < INTERRUPT_NOISE_THRESHOLD || delta_us < RADIO_LEFT - RADIO_THRESHOLD || delta_us > RADIO_RIGHT + RADIO_THRESHOLD)
      return;
    if (delta_us <= RADIO_CENTER + RADIO_THRESHOLD && delta_us >= RADIO_CENTER - RADIO_THRESHOLD)
    {
124
      scale_radio = RADIO_SCALE_CENTER;
125
    }
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
126
127
    else if (delta_us <= RADIO_LEFT + RADIO_THRESHOLD)
    {
128
      scale_radio = RADIO_SCALE_LEFT;
129
    }
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
130
131
    else if (delta_us >= RADIO_RIGHT - RADIO_THRESHOLD)
    {
132
      scale_radio = RADIO_SCALE_RIGHT;
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
133
134
135
    }
    else
    {
136
      scale_radio = (delta_us - RADIO_LEFT) * 100 / (RADIO_RANGE); //scale the recieved radio to a value between 0-100
137
    }
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
138
139
140
141
142
    go_print = true;
  }
  else
  {
    prev_change_date_us = curr_date;
143
144
  }
}
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
145
146
147
148
149
150
151
152
153
154
155
//*****Serial Interrupt - Read Motor Position*****//
/*If the encoder answers with its position, save the 4 bytes of information, translate them to decimal
and do a convertion to be in a scale between 0 and 100, where 0 is full left, 50 is center and 100 is full right.
After that, do a proportial control and send an speed command to the motor, the command is coded in 7 bits,
where 1 is full backward, 64 is stop and 127 is full forward*/
void serialEvent2()
{
  while (Serial2.available())
  {
    if (first) //Save the first byte of the message
    {
156
157
158
      recv = Serial2.read();
      first = false;
    }
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
159
160
    else //chain all the bytes to have the number that indicates a position
    {
161
      recv = (recv << BYTE_CARRY_LEFT) + Serial2.read();
162
163
164
    }
    count++;
  }
165
  if (count == TOTAL_OF_MESSAGES) //when all 4 bytes of the message have been recieved, do the control
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
166
  {
167
168
    pos = recv;
    count = 0;
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
169
    speed_command = COMM_ALL_STOP;
170
    first = true;
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

    if (!started) //When the arduino recieves power it will center the motor.
    {
      if (pos > MOTOR_CENTER + MOTOR_THRESHOLD || pos < MOTOR_CENTER - MOTOR_THRESHOLD)
      {
        if (pos < MOTOR_LEFT)
          speed_command = COMM_FULL_FWD;
        else if (pos > MOTOR_RIGHT)
          speed_command = COMM_FULL_BCK;
        else if (pos < MOTOR_CENTER - MOTOR_THRESHOLD)
          speed_command = COMM_MED_FWD;
        else if (pos > MOTOR_CENTER + MOTOR_THRESHOLD)
          speed_command = COMM_MED_BCK;
      }
      else
      {
        Serial.print("centered");
        speed_command = COMM_STOP;
189
190
191
192
        started = true;
      }
      Serial1.write(speed_command);
    }
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
193
194
195
196
    else //Normal use
    {
      scale_pos = (pos - MOTOR_LEFT) * 100 / (MOTOR_RANGE); //scale the motor position to a range between 0,100

197
      int error_pos = scale_radio - scale_pos;
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
198
199
200

      int v = _kp * error_pos; //Control

201
      if (v >= -ERROR_CENTER_THRESHOLD && v <= ERROR_CENTER_THRESHOLD) //if the error is at 0 with a threshold, send stop to the motor
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
202
203
      {
        speed_command = COMM_STOP;
204
      }
205
      else if (v >= MAX_ERROR_BEFORE_SPEED_IS_SET_TO_MAX) //if the error (-50,50) is more than "30" (value arbitrarily chosen) send the maximum speed, this is done to minimize the time of the mouvement
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
206
207
      {
        speed_command = COMM_FULL_FWD;
208
      }
209
      else if (v <= -MAX_ERROR_BEFORE_SPEED_IS_SET_TO_MAX) //if the error (-50,50) is less than "-30" (value arbitrarily chosen) send the maximum speed, this is done to minimize the time of the mouvement
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
210
211
      {
        speed_command = COMM_FULL_BCK;
212
      }
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
213
214
      else //Calculate the speed with this formula that transforms the error (-50,50) into the speed command (1,127)
      {
215
        speed_command = SPEED_COMMAND_SCALE_COEFFICIENT * (v - ERROR_MIN) + COMM_FULL_BCK;    
216
217
      }
    }
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
218
    go_print = true;
219
220
221
222
    Serial1.write(speed_command);
  }
}
//***********************************************************************//
Ricardo Rico Uribe's avatar
Ricardo Rico Uribe committed
223
224
225
226
227
228
229
230
231
232
void loop()
{
  //routine for debug. "never print inside an interruption"
  if (go_print)
  {
    //Serial.print("delta time: ");
    //Serial.println(delta_us);
    //Serial.print("speed command: ");
    //Serial.println(speed_command);
  }
233
}