I need help to find the issue in my code that creates a sine wave along time with a servo motor

I have created this code for a DOCYKE 350 kg hybrid servo motor. The motor is supposed to create a single sine wave, but for some reason the servo creates a sine wave within another. I have a tilt angle sensor that allows me to track the motion of the motor which is how I know that there is a sine wave inside od a sine wave. I am not sure if its creating a separate sine wave but it seems to be moving like one and the sine wave I am trying to make isnt consistent.

#include <Servo.h>
Servo servo_1;

int Ampl = 32.536;
int frequency = 1;
int pos1 = 90;

void setup()
{
  servo_1.attach(9, 800, 2200);
  Serial.begin(9600);
}

void loop()
{
  float value = millis()*2;
  
  pos1 = 90.0+((Ampl)*sin(2*3.14*frequency*value-0));
  pos1 = constrain(pos1, 0, 180);
  servo_1.write(pos1);
  Serial.println(pos1);

}

The line that has millis() in it is multiplied by 2 because it gives me the most consistent line, if that is my issue please let me know.


This is the kind of line I am getting

an int won't have the decimal part, so you are using only 32 (use float or double for the type)

your formula is (if I simplify) 90 + 32 x sin (2𝝅 t ) so your angle will vary between 58 and 122

I'm not sure what you represented on the curve in your second post

Okay I will change the int to float thank you! I failed to mention that I am using a 10:1 gearbox so yes the values of the servo motor are 58-122 but the gearbox cuts that by 10.

still your curve goes into negative territory ?

where is the sine wave inside the sine wave?

The reason it goes into negative territory is due to the position of the tilt angle sensor, when the servo is at position 90 the tilt angle is 0 degrees. its not necessarily another sin wave it just looks like one, I'm more concerned about how inconsistent the wave is.

remember you are sampling a sine wave based on time and you take some time to move the servo and execute the code so you are not 100% guaranteed to always hit the top of the sine wave

here is an exaggerated view

if you really want to follow the sine wave, then don't depend on time and just walk the sine wave by incrementing time by a fixed fraction of a radian every step

That is a fair point but this would be true but I am taking 200 readings per second.

Does your servo keep the pace ?

Print becomes blocking when the output buffer is full - at 9600 bauds (960 characters per second) this might throttle your loop

1 Like

Is there a way to change that?

Im using a DOCYKE 350 Kg motor from amazon, it was the only decent priced servo I could find

can your servo react to a new position order in 5ms ?

you could change the Serial baud rate to 500000 to empty the buffer faster or not print at all

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.