Source

ArduinoProjects / Experimental / MicroHorse / MicroHorse.ino

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Sweep
// by BARRAGAN <http://barraganstudio.com> 
// This example code is in the public domain.

#include <NewPing.h>
#include <Servo.h> 
#include <MathTypes.h>
#include <MathUtil.h>
#include <Animation.h>

#define DEBUG_RESET 0
#define DEBUG_PRINT 0
#define ALLOW_PING 1

const float obstacleDistanceInches = 28.0f;

float steeringValue = 0.0f;
const float calibrationAngle = -20.0f;
const float pingAngleMax = 90.0f;
float pingCurrAngle = -pingAngleMax;
int pingCurrIndex = 0;
const float pingEstimatedServoRotationSpeed = 250.0f; //deg per second
float pingAngleMoveTime = pingAngleMax/pingEstimatedServoRotationSpeed;

const int pingNumDistArrayEntries = 32;
const int robotFatness = 3;
float pingDistArray[pingNumDistArrayEntries];
float pingDistArrayAngles[pingNumDistArrayEntries];  //Should be fine since memory seems to not be an issue yet

const float updateAnimSPF = 1.0f/60.0f;
  
Animation* upperLegServoAnimFR;
Animation* upperLegServoAnimFL;
Animation* upperLegServoAnimBR;
Animation* upperLegServoAnimBL;
Animation* lowerLegServoAnimFR;
Animation* lowerLegServoAnimFL;
Animation* lowerLegServoAnimBR;
Animation* lowerLegServoAnimBL;
Animation* pingAnim;

const float movementMin = 0.0f;
const float movementMax = 1.0f;

//const float movementDistCheckMax = 40.0f;

float overallMovementR = 1.0f;
float overallMovementL = 1.0f;

float animSpeedMin = 2.0f;
float animSpeedMax = 4.0f;
float animSpeed = 2.0f;

const float backLegOffset = 0.8f;

const float rightSideOffset = 3.5f*0.45f;

//Ping
Servo servoPingSensor;
int ultrasonicMaxDistanceCM = 400;
int ultraSoundSignal = 3; // Ultrasound signal pin
NewPing* sonar;

float pingAnimVal;
const Animation::AnimMode pingAnimMode = Animation::AnimMode_PingPong;
const int pingAnimNumValues = 2;
Animation::KeyFrame pingAnimValues[pingAnimNumValues] = {{0.0f,-70},{0.75f,70}};

const Animation::AnimMode upperLegMode = Animation::AnimMode_Wrap;
const Animation::AnimMode lowerLegMode = Animation::AnimMode_Wrap;

//Top

//Front
const int numUpperLegAnimValuesF = 4;
Animation::KeyFrame upperLegAnimValuesF[numUpperLegAnimValuesF] = {{0.0f,20},{1.0f,-60},{2.1f,-20},{3.5f,20}};

//Back
const int numUpperLegAnimValuesB = 4;
Animation::KeyFrame upperLegAnimValuesB[numUpperLegAnimValuesB] = {{0.0f,30},{1.0f,-50},{2.1f,10},{3.5f,30}};


//Bottom

//Front
const int numLowerLegAnimValuesF = 5;
Animation::KeyFrame lowerLegAnimValuesF[numLowerLegAnimValuesF] = {{0.0f,-5},{0.9f,90},{1.25f,-20},{2.0f,0},{3.5f,-5}};


//Back
const int numLowerLegAnimValuesB = 5;
Animation::KeyFrame lowerLegAnimValuesB[numLowerLegAnimValuesB] = {{0.0f,15},{0.6f,90},{1.7f,-20},{2.0f,0},{3.5f,15}};


Servo servoUpperFR;
Servo servoUpperFL;
Servo servoUpperBR;
Servo servoUpperBL;

Servo servoLowerFR;
Servo servoLowerFL;
Servo servoLowerBR;
Servo servoLowerBL;

float lastTimeMillis = 0.0f;
void setup() 
{ 
#if DEBUG_PRINT
  Serial.begin(9600);
#endif

  for(int i=0; i<pingNumDistArrayEntries; ++i)
  {
    pingDistArray[i] = 0.0f;
    
    const float t = (float)i/(float)(pingNumDistArrayEntries-1);
    pingDistArrayAngles[i] = Lerp(pingAngleMax,-pingAngleMax,t);
   
#if DEBUG_PRINT
    Serial.print(i);
    Serial.print(": ");
    Serial.println(pingDistArrayAngles[i]);
#endif
  }

  sonar = new NewPing(ultraSoundSignal,ultraSoundSignal,ultrasonicMaxDistanceCM);
  
  //Create animations
  pingAnim = new Animation(pingAnimValues,pingAnimNumValues,pingAnimMode);
  
  //Left legs
  upperLegServoAnimFL = new Animation(upperLegAnimValuesF,numUpperLegAnimValuesF,upperLegMode);
  lowerLegServoAnimFL = new Animation(lowerLegAnimValuesF,numLowerLegAnimValuesF,lowerLegMode);
  upperLegServoAnimBL = new Animation(upperLegAnimValuesB,numUpperLegAnimValuesB,upperLegMode);
  lowerLegServoAnimBL = new Animation(lowerLegAnimValuesB,numLowerLegAnimValuesB,lowerLegMode);
  
  //Right legs
  upperLegServoAnimFR = new Animation(upperLegAnimValuesF,numUpperLegAnimValuesF,upperLegMode);
  lowerLegServoAnimFR = new Animation(lowerLegAnimValuesF,numLowerLegAnimValuesF,lowerLegMode);
  upperLegServoAnimBR = new Animation(upperLegAnimValuesB,numUpperLegAnimValuesB,upperLegMode);
  lowerLegServoAnimBR = new Animation(lowerLegAnimValuesB,numLowerLegAnimValuesB,lowerLegMode);

  //Right legs
  upperLegServoAnimFR->currT += rightSideOffset;
  lowerLegServoAnimFR->currT += rightSideOffset;
  upperLegServoAnimBR->currT += rightSideOffset;
  lowerLegServoAnimBR->currT += rightSideOffset;
  
  //Left legs
  upperLegServoAnimBL->currT += backLegOffset;
  lowerLegServoAnimBL->currT += backLegOffset;

  //Right legs
  upperLegServoAnimBR->currT += backLegOffset;
  lowerLegServoAnimBR->currT += backLegOffset;
  
  servoUpperFR.attach(4);
  servoUpperFL.attach(5);
  servoUpperBR.attach(6);
  servoUpperBL.attach(7);
  
  servoLowerFR.attach(8);
  servoLowerFL.attach(9);
  servoLowerBR.attach(10);
  servoLowerBL.attach(11);
  
  servoPingSensor.attach(12);
  
  //pinMode(ultraSoundSignal,OUTPUT);

  //Init time
  lastTimeMillis = millis();
} 

float animUpdateTimer = 0.0f;

void UpdatePing(float timeDelta)
{
  bool reachedEnd = false;
  
  //If we should be at the next angle, change to the next index and do a ping
  pingAngleMoveTime -= timeDelta;
  if(pingAngleMoveTime <= 0.0f)
  {
    //Do a ping at the current angle
    const float distance = sonar->ping_in();
    
    pingDistArray[pingCurrIndex] = distance;
    
/*#if DEBUG_PRINT
    Serial.print("Angle: ");
    Serial.print(pingCurrAngle);
    Serial.print("Distance (inches): ");
    Serial.println(distance);
#endif*/
    
    const float lastAngle = pingCurrAngle;
    
    //Switch to next angle
    if(pingCurrIndex == pingNumDistArrayEntries-1)
    {
      reachedEnd = true;
      
      //Get next angle
      pingCurrAngle = -pingAngleMax;
    }
    else
    {
      //Increment index
      ++pingCurrIndex;
    }
    
    //Get next angle
    pingCurrAngle = pingDistArrayAngles[pingCurrIndex];

    //Set timer based on the amount of turning to do
    pingAngleMoveTime = abs(pingCurrAngle-lastAngle)/pingEstimatedServoRotationSpeed;
    
    //Write to servo
    servoPingSensor.write(pingCurrAngle+calibrationAngle+90.0f);
    
    //Finished a scan so update movement!
    if(reachedEnd)
    {
      pingCurrIndex = 0;
      
      int bestNonObstacleCount = -1;
      int countIndexStart = 0;
      int currNonObstacleCount = 0;
      int selectedIndex = 0;
      float bestAccumulatedDist = 0.0f;
      float currAccumulatedDist = 0.0f;
      
      for(int i=0; i<pingNumDistArrayEntries; ++i)
      {
        const float currDist = pingDistArray[i];
        
        //If we find an obstacle or we reach the end of the array...
        if(currDist < obstacleDistanceInches
          || i == (pingNumDistArrayEntries-1))
        { 
#if DEBUG_PRINT
    Serial.print('X');
#endif
          //If this is the widest open area we've found
          //so far...
          if(currNonObstacleCount >= robotFatness
            && currNonObstacleCount >= bestNonObstacleCount
            && currAccumulatedDist > bestAccumulatedDist)
          {
            //Save the best!
             bestNonObstacleCount = currNonObstacleCount;
             bestAccumulatedDist = currAccumulatedDist;
             
             //Save the angle in the center of this hopefully huge open area
             selectedIndex = (countIndexStart + i)/2;
          }
          
          //Set up for net run
          countIndexStart = i+1;        
          currNonObstacleCount = 0;
          currAccumulatedDist = 0.0f;
        }
        //No obstacles.  Yay!
        else
        {
#if DEBUG_PRINT
    Serial.print('.');
#endif
          currAccumulatedDist += currDist;
          ++currNonObstacleCount;
        }
      }

    if(bestNonObstacleCount == -1)
    {
      selectedIndex = (pingNumDistArrayEntries-1)/2;
    }
    
#if DEBUG_PRINT
    Serial.println(' ');
    for(int i=0; i<pingNumDistArrayEntries; ++i)
    {
      if(i == selectedIndex)
      {
        Serial.print('^');
      }
      else
      {
        Serial.print(' ');
      }
    }  
    Serial.println(' ');
#endif
      steeringValue = (float)selectedIndex/(float)(pingNumDistArrayEntries-1);
  
      overallMovementL = steeringValue;
      overallMovementR = 1.0f-overallMovementL;
      
      const float moveDiff = 1.0f-abs(overallMovementL-overallMovementR);
      const float maxMove = MaxF(overallMovementL,overallMovementR);
      
      //animSpeed = Lerp(animSpeedMin,animSpeedMax,moveDiff);
      
      overallMovementL /= maxMove;
      overallMovementR /= maxMove;
    
      overallMovementL = Lerp(movementMin,movementMax,overallMovementL);
      overallMovementR = Lerp(movementMin,movementMax,overallMovementR);
  
/*#if DEBUG_PRINT
      Serial.print("Left: ");
      Serial.print(overallMovementL);
      Serial.print(", Right: ");
      Serial.print(overallMovementR);
      Serial.print(", Anim Speed: ");
      Serial.println(animSpeed);
#endif*/
    }
  }
}


void loop() 
{ 
  //Get current time in seconds
  const float currTimeMillis = millis();
  const float timeDelta = (currTimeMillis-lastTimeMillis)/1000.0f;
  lastTimeMillis = currTimeMillis;
  
#if ALLOW_PING
  UpdatePing(timeDelta);
#endif
  
  animUpdateTimer -= timeDelta;
  if(animUpdateTimer < 0.0f)
  {
    animUpdateTimer += updateAnimSPF;
    
    UpdateAnims(updateAnimSPF);
  }
} 

inline void UpdateAnims(float timeDelta)
{
  upperLegServoAnimFR->animSpeed = animSpeed;
  lowerLegServoAnimFR->animSpeed = animSpeed;
  upperLegServoAnimBR->animSpeed = animSpeed;
  lowerLegServoAnimBR->animSpeed = animSpeed;
  upperLegServoAnimFL->animSpeed = animSpeed;
  lowerLegServoAnimFL->animSpeed = animSpeed;
  upperLegServoAnimBL->animSpeed = animSpeed;
  lowerLegServoAnimBL->animSpeed = animSpeed; 
  
  //Update animations
  //Right legs
  upperLegServoAnimFR->Update(timeDelta); 
  lowerLegServoAnimFR->Update(timeDelta);
  upperLegServoAnimBR->Update(timeDelta); 
  lowerLegServoAnimBR->Update(timeDelta);
  
  //Left legs
  upperLegServoAnimFL->Update(timeDelta);
  lowerLegServoAnimFL->Update(timeDelta);
  upperLegServoAnimBL->Update(timeDelta);
  lowerLegServoAnimBL->Update(timeDelta);  
  
  float topFrontRightAnimVal =  upperLegServoAnimFR->CalcAnimVal();
  float topFrontLeftAnimVal = -upperLegServoAnimFL->CalcAnimVal();
  float topBackRightAnimVal =  upperLegServoAnimBR->CalcAnimVal();
  float topBackLeftAnimVal = -upperLegServoAnimBL->CalcAnimVal();
  
  float bottomFrontRightAnimVal =  lowerLegServoAnimFR->CalcAnimVal();
  float bottomFrontLeftAnimVal = -lowerLegServoAnimFL->CalcAnimVal();
  float bottomBackRightAnimVal =  lowerLegServoAnimBR->CalcAnimVal();
  float bottomBackLeftAnimVal = -lowerLegServoAnimBL->CalcAnimVal();
  
   //Right legs
  topFrontRightAnimVal *= overallMovementR;
  bottomFrontRightAnimVal *= overallMovementR;
  topBackRightAnimVal *= overallMovementR;
  bottomBackRightAnimVal *= overallMovementR;
  
  //Left legs
  topFrontLeftAnimVal *= overallMovementL;
  bottomFrontLeftAnimVal *= overallMovementL;
  topBackLeftAnimVal *= overallMovementL;
  bottomBackLeftAnimVal *= overallMovementL;
  
  //TODO: bake these into the animations at startup
  
  //Right legs
  topFrontRightAnimVal += 90.0f;
  bottomFrontRightAnimVal += 90.0f;
  topBackRightAnimVal += 90.0f;
  bottomBackRightAnimVal += 90.0f;
  
  //Left legs
  topFrontLeftAnimVal += 90.0f;
  bottomFrontLeftAnimVal += 90.0f;
  topBackLeftAnimVal += 90.0f;
  bottomBackLeftAnimVal += 90.0f;  
  
 #if !DEBUG_RESET
   //Set servo values from animations
  servoUpperFR.write(topFrontRightAnimVal);
  servoLowerFR.write(bottomFrontRightAnimVal);
  servoUpperBR.write(topBackRightAnimVal);
  servoLowerBR.write(bottomBackRightAnimVal);
  
  servoUpperFL.write(topFrontLeftAnimVal);
  servoLowerFL.write(bottomFrontLeftAnimVal);
  servoUpperBL.write(topBackLeftAnimVal);
  servoLowerBL.write(bottomBackLeftAnimVal);
 #endif
}