Context: I'm testing a portion of code to implement in a bigger project. In the test I have a function to generate the value of a sine wave and output it to my motor driver at a certain resolution (in my code I'm outputting a 1hz sine wave with a resolution of 1000 points per second (1kHz)). I am calling that function as a multiprocessing processes because in my project that's where it will be. The function generates the value and then sleeps for whatever time it has left over before generating the next value, in general this works but every once in a while the loop take 100x + longer than it was and attempts to sleep for a negative time crashing the code. All the code is implemented on a raspberry pi 3B+
My Question: Why does it all of a sudden take so much longer? (I've also tried at lower resolutions ,500hz,and 333hz)
from DFRobot_RaspberryPi_Motor.raspberry.DFRobot_RaspberryPi_DC_Motor import DFRobot_DC_Motor_IIC as Board
from time import sleep, time
import math
import multiprocessing
freq_motor = 1
res_period = .001
def OutputSine():
global freq_motor, res_period
a = 2 * math.pi*freq_motor
t0 = time()
while True:
t1 = time()
duty = 50 + 50 * math.sin(a * (t1 - t0))
board.motor_movement([board.M1], board.CW, duty)
b = (time() - t1)
print(b)
sleep(res_period - b)
if __name__ == '__main__':
board = Board(1, 0x10)
while board.begin() != board.STA_OK: # Board begin and check board status
print("board begin faild")
print("board begin success")
board.set_encoder_disable(board.ALL) # Set selected DC motor encoder disable
board.set_moter_pwm_frequency(10000) # Set DC motor pwm frequency to 1000HZ
p1 = multiprocessing.Process(target=OutputSine, args=())
p1.start()
p1.join()