The driver consists of the following functions, which you can use to drive the underlying hardware when writing your own application in Python:
You can create a new object for each HAT with
pwm = PWM(0x40)
In this case, pwm (lowercase) is the object created, and
PWM(0x40) is the creation call. By default, all HATs are address 0x40, but by changing the address jumpers, you can create objects that use other addresses such as 0x60, 0x42, etc.
This function can be used to adjust the PWM frequency, which determines how many full 'pulses' per second are generated by the IC. Stated differently, the frequency determines how 'long' each pulse is in duration from start to finish, taking into account both the high and low segments of the pulse.
Frequency is important in PWM, since setting the frequency too high with a very small duty cycle can cause problems, since the 'rise time' of the signal (the time it takes to go from 0V to VCC) may be longer than the time the signal is active, and the PWM output will appear smoothed out and may not even reach VCC, potentially causing a number of problems.
- freq: A number representing the frequency in Hz, between 40 and 1000
The following code will set the PWM frequency to the maximum value of 1000Hz:
This function sets the start (on) and end (off) of the high segment of the PWM pulse on a specific channel. You specify the 'tick' value between 0..4095 when the signal will turn on, and when it will turn of. Channel indicates which of the 16 PWM outputs should be updated with the new values.
- channel: The channel that should be updated with the new values (0..15)
- on: The tick (between 0..4095) when the signal should transition from low to high
- off:the tick (between 0..4095) when the signal should transition from high to low
The following example will cause channel 15 to start low, go high around 25% into the pulse (tick 1024 out of 4096), transition back to low 75% into the pulse (tick 3072), and remain low for the last 25% of the pulse:
If you need to calculate pulse-width in microseconds, you can do that by first figuring out how long each cycle is. That would be 1/freq where freq is the PWM frequency you set above. For 1000 Hz, that would be 1 millisecond. Then divide by 4096 to get the time per tick, eg 1 millisecond / 4096 = ~0.25 microseconds. If you want a pulse that is 10 microseconds long, divide the time by time-per-tick (10us / 0.25 us = 40) then turn on at tick 0 and turn off at tick 40.