
Nervous Optic by Ben Felten, CC BY-ND 2.0
In tutorial 3 – “ramps” we learned how to repeat instructions again and again using the for statement. In this tutorial we need the for loop again, bur instead of changing the motor speed by a constant value we want a more dynamic behavior. Therefore we use the sinus function – a classical pattern used for controlling vibrators.
Here is a straight forward approach:
for (float i = 0; i < 20000; i = i + 0.05) { analogWrite(motor, (sin(i)); //motor speed set to sin(i) } delay(20);
We are changing the variable i in small steps of 0.05. So the variable i will become 0, 0.05, 0.1, 0.15, 0,2 … and so on.
But this doesn’t work. Let’s have a look at the sinus function. Just use the google search and type in “sin(x)”. You will see the following curve:
There are two problems:
- There are values below 0 (on the vertical or y-axis). If the value is 0 or below 0 the motor is off.
- The maximal value is 1. But we need values between the minimal motor speed (around 40) and the maximal speed (always 255).
You can try to adjust the function and visualize it with google search. Maybe you will discover an interesting variant of the sinus curve.
We use the following function:
(sin(x)+1) 0.5 * (maximal motor speed – minimal motor speed)) + minimal motor speed
- Sin(x)+1: add 1 to get positive values only between 0 and 2 instead of -1 and 1.
- Multiply by 0.5: get values between 0 an 1 instead 0 and 2
- Multiply with maximal motor speed (255) – minimal motor speed (40): values are now between 0 and 215
- Add minimal speed: values are between 40 and 255. So the motor will always be on.
This is the script. Please have a look at tutorial 2 if you don’t know how to upload the script.
// www.bodyinteraction.com tutorial sinus int motor = 3; int minimal_motorspeed = 50; void setup() { pinMode(motor, OUTPUT); } void loop() { for (float i = 0; i < 20000; i = i + 0.05) { analogWrite(motor, ((sin(i) + 1) * 0.5 * 215) + 40); delay(5); } }
If you want to slow down the changes in the motor speed change delay(5) and take larger values.
Go back to tutorial 3: ramps
One thought on “Programming Tutorial part 4: Sinus”