In this section:

Sine wave generator →

Make the R3PTAR slither →

### Sine wave generator

In this section, the C# code for a simple sine wave generator is described. The main purpose is to serve as an oscillating reference to the Ev3 Medium Motor on board the R3PTAR, so that the snake neck can oscillate accordingly. The following equation describes a sine wave that varies with time:

, where

- is the mean value of the wave,
- is the wave amplitude,
- is the frequency expressed in Hz and,
- is time expressed in seconds.

On our robots, or on board every digital device for what matters, time cannot vary continuously and so we have to *discretize* the time by posing , where is the independent discrete time, and is the sampling time expressed in seconds; so we get:

, which sometimes is written as

.

The following thread body contains the code that generates the sine wave given its mean value, frequency and sample time;

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 |
/// <summary> /// Generates a sinusoidal wave /// </summary> void WaveThread() { UInt64 k = 0; // Discrete time counter double t = 0; // Time double angularPulsation = 2 * Math.PI * frequency; // Angular pulsation while (!stopWaveThread.WaitOne(waveThreadSampleTime)) { // Current time t = ((double) k * waveThreadSampleTime) / 1000; // Wave signal computation wave = meanValue + amplitude * Math.Sin (angularPulsation * t); // Update next discrete time istant if (k < UInt64.MaxValue) { k++; } else { k = 0; } } } |

The code is pretty straightforward; just take note of the if statement that reverts the variable to zero when it grows bigger than the largest representable integer value.

### Make the R3PTAR slither

So, making the R3PTAR slither becomes much simpler now: just use a PID controller to regulate the angular position of the Ev3 Medium Motor of the robot, and send it the output of the sine wave generator plus a mean value as a reference. See the following picture for clarity:

The mean value is the key to steer the robot in the desired direction: if the mean value is positive the robot will steer to the right, else to the left… always slithering as a real snake.

To change the behavior of the snake according to your preference, you can do the following:

- increase or decrease the amplitude of the sine wave if you want a wider or a tighter undulation;
- increase or decrease the frequency of the sine wave to get a more nervous or a smoother movement.