We have to tell the program the part's address. By default, it is 0x20, so set
a variable to that for later use.
addr = 0x20
Next, we want to enable the PWM chip and tell it to automatically increment
addresses after a write (that lets us do single-operation multi-byte writes).
bus.write_byte_data(addr, 0, 0x20)
bus.write_byte_data(addr, 0xfe, 0x1e)
Write Values to the PWM Registers
That's all the setup that needs to be done. From here on out, we can write
data to the PWM chip and expect to have it respond. Here's an example.
bus.write_word_data(addr, 0x06, 0)
bus.write_word_data(addr, 0x08, 1250)
The first write is to the "start time" register for channel 0. By default, the
PWM frequency of the chip is 200Hz, or one pulse every 5ms. The start
time register determines when the pulse goes high in the 5ms cycle. All
channels are synchronized to that cycle. Generally, this should be written to
0. The second write is to the "stop time" register, and it controls when the
pulse should go low. The range for this value is from 0 to 4095, and each
count represents one slice of that 5ms period (5ms/4095), or about 1.2us.
Thus, the value of 1250 written above represents about 1.5ms of high time
per 5ms period.
Servo motors get their control signal from that pulse width. Generally
speaking, a pulse width of 1.5ms yields a "neutral" position, halfway
between the extremes of the motor's range. 1.0ms yields approximately 90
degrees off center, and 2.0ms yields -90 degrees off center. In practice,
those values may be slightly more or less than 90 degrees, and the motor
may be capable of slightly more or less than 90 degrees of motion in either
direction.
To address other channels, simply increase the address of the two registers
above by 4. Thus, start time for channel 1 is 0x0A, for channel 2 is 0x0E,
channel 3 is 0x12, etc. and stop time address for channel 1 is 0x0C, for
channel 2 is 0x10, channel 3 is 0x14, etc. See the table below.
Channel #
Start Address
Ch 0
0x06
Ch 1
0x0A
Ch 2
0x0E
Ch 3
0x12
Ch 4
0x16
Ch 5
0x1A
Ch 6
0x1E
Ch 7
0x22
Ch 8
0x26
Ch 9
0x2A
Stop Address
0x08
0x0C
0x10
0x14
0x18
0x1C
0x20
0x24
0x28
0x2C
Page 6 of 10
Need help?
Do you have a question about the Pi Servo Hat and is the answer not in the manual?
Questions and answers