# Using a PCA9685 I2C 16 PWM lines generator with Roadrunner board

<abstract>
The PCA9685 is an I2C-bus controlled 16-channel LED controller optimized for
Red/Green/Blue/Amber (RGBA) color backlighting applications. Each LED output has its
own 12-bit resolution (4096 steps) fixed frequency individual PWM controller that operates
at a programmable frequency from a typical of 24 Hz to 1526 Hz with a duty cycle that is
adjustable from 0 % to 100 % to allow the LED to be set to a specific brightness value.
All outputs are set to the same PWM frequency.
</abstract>

## Linux config

	-> Device Drivers                                                                                          │  
		-> Pulse-Width Modulation (PWM) Support (PWM [=y])
			<*>   NXP PCA9685 PWM driver 

## Device tree

0x70 is the default address of the [Mikroe click board](https://download.mikroe.com/documents/add-on-boards/click/pwm/pwm-click-manual-v100.pdf)

	i2c0: i2c@f8028000 {
		dmas = <0>, <0>;
		pinctrl-names = "default";
		pinctrl-0 = <&pinctrl_i2c0_default>;
		i2c-sda-hold-time-ns = <350>;
		status = "okay";
		
		pca9685-0@70 {
			compatible = "nxp,pca9685-pwm";
			reg = <0x70>;
		};

	};

## User space sysfs interface

If the chip is probed this directory will be created

	/sys/class/pwm/pwmchip0

For any PWM line you want to use you have to export it.

	echo 0 > /sys/class/pwm/pwmchip0/export
	echo 1 > /sys/class/pwm/pwmchip0/export
	echo 2 > /sys/class/pwm/pwmchip0/export
	echo 3 > /sys/class/pwm/pwmchip0/export

To use again that line ad generic GPIO you can unexport it:

	echo 0 > /sys/class/pwm/pwmchip0/unexport
	echo 1 > /sys/class/pwm/pwmchip0/unexport
	echo 2 > /sys/class/pwm/pwmchip0/unexport
	echo 3 > /sys/class/pwm/pwmchip0/unexport

For any exported channel a directory called pwmX wil be created with the following structure:

	/sys/class/pwm/pwmchip0/pwmX/
	      |-- duty_cycle (r/w) duty cycle (in nanoseconds)
	      |-- enable     (r/w) enable/disable PWM
	      |-- period     (r/w) period (in nanoseconds)
	      |-- polarity   (r/w) polarity of PWM
	      |-- power
	      `-- uevent
      
The follow example illustrate how enable a PWM signale with a period of 1mS with a 0.5mS of duty cycle:

	echo 1000000 > /sys/class/pwm/pwmchip0/pwm0/period
	echo 500000 > /sys/class/pwm/pwmchip0/pwm0/duty_cycle
	echo 1 > /sys/class/pwm/pwmchip0/pwm0/enable

### Pin used on Roadrunner

The I2C port used is i2c-0

	PIN_PD21  TWD0    Data
	PIN_PD22  TWCK0   Clock
	
### Links

* [Datasheet](https://www.mouser.it/datasheet/2/302/PCA9685-1127478.pdf)
* [Driver Linux](https://github.com/torvalds/linux/blob/master/drivers/pwm/pwm-pca9685.c)
* [Click board](https://download.mikroe.com/documents/add-on-boards/click/pwm/pwm-click-manual-v100.pdf)

@include='bio_tanzilli'