1

I have a question regarding the Python3 time sleep() function. My set up is consisted of the Arduino UNO running Firmata firmware and a PC/laptop running python code using pyfirmata library.

What I am trying to do is to analog write to a PWM pin from a list of values (100 values in this case). I also want them to output in every 0.001 second or 1 ms. Therefore, technically, 100 values in 0.001s/each would take ~0.1 sec to complete.

Then the problem happened when I used timer to see how long it would take. It only achieved ~0.1 sec total when Google Chrome was opened on certain websites (I know it seems weird, but it's true 100%). Even when I minimized Google Chrome, the total time would slow down to 1.6s consistently until I opened Chrome again.

Then I tried to take off my time.sleep(0.001) in my loop then it worked fine regardless the appearance of Chrome or not.

I really want to understand why and a solution for this case. Maybe an alternative of time.sleep? Here is my code in python. You can load the firmata sketch from Arduino IDE.

Also note at higher value of time.sleep(), everything works fine with or without Chrome opened.

import pyfirmata
import time
from timeit import default_timer as timer

board = pyfirmata.Arduino("COM4", baudrate = 115200)
pwmPin = board.get_pin('d:5:p') #digital pin 5 pwm mode

my_points = [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]

def LoadWaveform():
   rate = 1/1000
   #print (my_points)
   while True:
      start = timer()
      for i in range(len(my_points)):
         pwmPin.write(my_points[i]/300)
         #time.sleep(rate)

      end = timer()
      print ("Total time run: ", end - start)
      time.sleep(1)

LoadWaveform()
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
Iker Hua
  • 403
  • 4
  • 14

0 Answers0