Skip to content

I2C to PWM Controller Python Example

This example demonstrates controlling PWM using the PCA9685 PWM controller via the I2C bus.

Important

The chosen module is for demonstration purposes only; we do not promote or provide purchasing information for specific hardware. The example provided below is specifically tailored for this controller and may not work with modules using different controllers.

Hardware Connection

Connect the I2C servo control module to the KNEO Pi as follows:

Module Pin KNEO Pi Pin Function
GND GND / pin-9 Ground
VCC 3.3V / pin-1 Power Supply
SCK I2C_0 SCL / pin-5 I2C Clock
SDA I2C_0 SDA / pin-3 I2C Data

Info

This example uses i2c-0 bus for communication

Running the Example

Clone the modified example from GitHub

git clone https://github.com/kneron/kneopi-examples.git
cd kneopi-examples
cd peripherals/Python/pca9685

Tip

The example code is sourced from PCA9685.py as a base.

Run the example with the following command:

./pca9685.py [option]
    option:
        up
        down
        reset
        info

        chon [channel]
        choff [channel]
        allch  [ value:0~4095 ]
        allchd [duty cycle]

        ch   [channel] [value:0~4095]
        chd  [channel] [duty cycle:0.0~100.0]
        rchd  [channel] [relative duty cycle:0.0~100.0]
How to Use chmod to Make a Script Executable?

Before running the Python script, ensure it has execute permission.

You can grant permission using the command:

chmod +x pca9685.py

Then, you can execute it directly by:

./pca9685.py

If you prefer running it with python3, you can still use:

python pca9685.py

  • Power Up the Module
    ./pca9685.py up
    
  • Display Information About the Module

    ./pca9685.py info
    

  • Turn On and Off Specific Channels

    ./pca9685.py chon 1    # Turns on channel 1
    ./pca9685.py choff 1   # Turns off channel 1
    

  • Set PWM for All Channels

    ./pca9685.py allch 2048      # Sets all channels to a PWM value of 2048 (out of 4095)
    ./pca9685.py allchd 50.0     # Sets all channels to a 50% duty cycle
    

  • Command Sequence Example

    ./pca9685.py 'T:100 C1:1024 C15:2035 C13:999 C7:777 D9:55.5'
    

    This command:

    • Waits for 100 microseconds
    • Sets PWM count of Channel 1 to 1024, Channel 15 to 2035, Channel 13 to 999, and Channel 7 to 777.
    • Sets duty cycle of Channel 9 to 55.5%

Additional Information