Home | History | Annotate | Line # | Download | only in i2c
pca9685.c revision 1.2
      1 /* $NetBSD: pca9685.c,v 1.2 2019/07/24 05:47:39 thorpej Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 2018, 2019 Jason R. Thorpe
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     26  * POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 #include <sys/cdefs.h>
     30 __KERNEL_RCSID(0, "$NetBSD: pca9685.c,v 1.2 2019/07/24 05:47:39 thorpej Exp $");
     31 
     32 #include <sys/param.h>
     33 #include <sys/systm.h>
     34 #include <sys/device.h>
     35 #include <sys/kernel.h>
     36 #include <sys/mutex.h>
     37 
     38 #include <dev/i2c/i2cvar.h>
     39 #include <dev/i2c/pca9685reg.h>
     40 
     41 #include <dev/pwm/pwmvar.h>
     42 
     43 #include <dev/fdt/fdtvar.h>
     44 
     45 /*
     46  * Special channel number used to indicate that we want to set the
     47  * pulse mode for all channels on this controller.
     48  */
     49 #define	PCA9685_ALL_CHANNELS	PCA9685_NCHANNELS
     50 
     51 struct pcapwm_channel {
     52 	struct pwm_controller	ch_controller;
     53 	struct pwm_config	ch_conf;
     54 	u_int			ch_number;
     55 };
     56 
     57 struct pcapwm_softc {
     58 	device_t	sc_dev;
     59 	i2c_tag_t	sc_i2c;
     60 	i2c_addr_t	sc_addr;
     61 	int		sc_i2c_flags;
     62 
     63 	/*
     64 	 * Locking order is:
     65 	 *	pcapwm mutex -> i2c bus
     66 	 */
     67 	kmutex_t	sc_lock;
     68 
     69 	/*
     70 	 * The PCA9685 only has a single pre-scaler, so the configured
     71 	 * PWM frequency / period is shared by all channels.
     72 	 */
     73 	u_int		sc_period;	/* nanoseconds */
     74 	u_int		sc_clk_freq;
     75 	bool		sc_ext_clk;
     76 	bool		sc_invert;	/* "invert" property specified */
     77 	bool		sc_open_drain;	/* "open-drain" property specified */
     78 
     79 	/*
     80 	 * +1 because we treat channel "16" as the all-channels
     81 	 * pseudo-channel.
     82 	 */
     83 	struct pcapwm_channel sc_channels[PCA9685_NCHANNELS+1];
     84 };
     85 
     86 static int	pcapwm_pwm_enable(struct pwm_controller *, bool);
     87 static int	pcapwm_pwm_get_config(struct pwm_controller *,
     88 		    struct pwm_config *);
     89 static int	pcapwm_pwm_set_config(struct pwm_controller *,
     90 		    const struct pwm_config *);
     91 
     92 static const struct device_compatible_entry compat_data[] = {
     93 	{ "nxp,pca9685-pwm",	0 },
     94 	{ NULL }
     95 };
     96 
     97 static int
     98 pcapwm_read1(struct pcapwm_softc * const sc, uint8_t reg, uint8_t *valp)
     99 {
    100 
    101 	return iic_exec(sc->sc_i2c, I2C_OP_READ_WITH_STOP,
    102 			sc->sc_addr, &reg, sizeof(reg),
    103 			valp, sizeof(*valp), cold ? I2C_F_POLL : 0);
    104 }
    105 
    106 static int
    107 pcapwm_write1(struct pcapwm_softc * const sc, uint8_t reg, uint8_t val)
    108 {
    109 
    110 	return iic_exec(sc->sc_i2c, I2C_OP_WRITE_WITH_STOP,
    111 			sc->sc_addr, &reg, sizeof(reg),
    112 			&val, sizeof(val), cold ? I2C_F_POLL : 0);
    113 }
    114 
    115 static int
    116 pcapwm_read_LEDn(struct pcapwm_softc * const sc, uint8_t reg, uint8_t *buf,
    117 		 size_t buflen)
    118 {
    119 
    120 	/* We rely on register auto-increment being enabled. */
    121 	return iic_exec(sc->sc_i2c, I2C_OP_READ_WITH_STOP,
    122 			sc->sc_addr, &reg, sizeof(reg),
    123 			buf, buflen, cold ? I2C_F_POLL : 0);
    124 }
    125 
    126 static int
    127 pcapwm_write_LEDn(struct pcapwm_softc * const sc, uint8_t reg, uint8_t *buf,
    128 		  size_t buflen)
    129 {
    130 
    131 	/* We rely on register auto-increment being enabled. */
    132 	return iic_exec(sc->sc_i2c, I2C_OP_WRITE_WITH_STOP,
    133 			sc->sc_addr, &reg, sizeof(reg),
    134 			buf, buflen, cold ? I2C_F_POLL : 0);
    135 }
    136 
    137 static int
    138 pcapwm_program_channel(struct pcapwm_softc * const sc,
    139 		       struct pcapwm_channel * const chan,
    140 		       uint16_t on_tick, uint16_t off_tick)
    141 {
    142 	const uint8_t reg = chan->ch_number == PCA9685_ALL_CHANNELS ?
    143 	    PCA9685_ALL_LED_ON_L : PCA9685_LEDx_ON_L(chan->ch_number);
    144 	uint8_t regs[4];
    145 
    146 	regs[0] = (uint8_t)(on_tick & 0xff);
    147 	regs[1] = (uint8_t)((on_tick >> 8) & 0xff);
    148 	regs[2] = (uint8_t)(off_tick & 0xff);
    149 	regs[3] = (uint8_t)((off_tick >> 8) & 0xff);
    150 
    151 	return pcapwm_write_LEDn(sc, reg, regs, sizeof(regs));
    152 }
    153 
    154 static int
    155 pcapwm_inspect_channel(struct pcapwm_softc * const sc,
    156 		       struct pcapwm_channel * const chan,
    157 		       uint16_t *on_tickp, uint16_t *off_tickp)
    158 {
    159 	const uint8_t reg = chan->ch_number == PCA9685_ALL_CHANNELS ?
    160 	    PCA9685_ALL_LED_ON_L : PCA9685_LEDx_ON_L(chan->ch_number);
    161 	uint8_t regs[4];
    162 	int error;
    163 
    164 	error = pcapwm_read_LEDn(sc, reg, regs, sizeof(regs));
    165 	if (error) {
    166 		return error;
    167 	}
    168 
    169 	*on_tickp = regs[0] | (((uint16_t)regs[1]) << 8);
    170 	*off_tickp = regs[2] | (((uint16_t)regs[3]) << 8);
    171 
    172 	return 0;
    173 }
    174 
    175 static struct pcapwm_channel *
    176 pcapwm_lookup_channel(struct pcapwm_softc * const sc, u_int index)
    177 {
    178 
    179 	if (index > PCA9685_ALL_CHANNELS)
    180 		return NULL;
    181 
    182 	return &sc->sc_channels[index];
    183 }
    184 
    185 static void
    186 pcapwm_init_channel(struct pcapwm_softc * const sc, u_int index)
    187 {
    188 	struct pcapwm_channel * const chan = pcapwm_lookup_channel(sc, index);
    189 
    190 	KASSERT(chan != NULL);
    191 
    192 	chan->ch_number = index;
    193 
    194 	chan->ch_controller.pwm_enable = pcapwm_pwm_enable;
    195 	chan->ch_controller.pwm_get_config = pcapwm_pwm_get_config;
    196 	chan->ch_controller.pwm_set_config = pcapwm_pwm_set_config;
    197 
    198 	chan->ch_controller.pwm_dev = sc->sc_dev;
    199 	chan->ch_controller.pwm_priv = chan;
    200 }
    201 
    202 static pwm_tag_t
    203 pcapwm_get_tag(device_t dev, const void *data, size_t len)
    204 {
    205 	struct pcapwm_softc * const sc = device_private(dev);
    206 	const u_int *pwm = data;
    207 
    208 	/* #pwm-cells == 2 in the PCA9685 DT bindings. */
    209 	if (len != 12)
    210 		return NULL;
    211 
    212 	/* Channel 16 is the special call-channels channel. */
    213 	const u_int index = be32toh(pwm[1]);
    214 	struct pcapwm_channel * const chan = pcapwm_lookup_channel(sc, index);
    215 	if (chan == NULL)
    216 		return NULL;
    217 
    218 	const u_int period = be32toh(pwm[2]);
    219 
    220 	mutex_enter(&sc->sc_lock);
    221 
    222 	/*
    223 	 * XXX Should we reflect the value of the "invert" property in
    224 	 * pwm_config::polarity?  I'm thinking not, but...
    225 	 */
    226 	chan->ch_conf.period = period;
    227 	chan->ch_conf.polarity = PWM_ACTIVE_HIGH;
    228 
    229 	mutex_exit(&sc->sc_lock);
    230 
    231 	return &chan->ch_controller;
    232 }
    233 
    234 static struct fdtbus_pwm_controller_func pcapwm_pwm_funcs = {
    235 	.get_tag = pcapwm_get_tag,
    236 };
    237 
    238 static int
    239 pcapwm_pwm_enable(pwm_tag_t pwm, bool enable)
    240 {
    241 	struct pcapwm_softc * const sc = device_private(pwm->pwm_dev);
    242 	struct pcapwm_channel * const chan = pwm->pwm_priv;
    243 	int error;
    244 
    245 	if (enable) {
    246 		/* Set whatever is programmed for the channel. */
    247 		error = pwm_set_config(pwm, &chan->ch_conf);
    248 		if (error) {
    249 			device_printf(sc->sc_dev,
    250 			    "enable: unable to set config for channel %u\n",
    251 			    chan->ch_number);
    252 		}
    253 		return error;
    254 	}
    255 
    256 	mutex_enter(&sc->sc_lock);
    257 
    258 	error = pcapwm_program_channel(sc, chan, 0, PCA9685_PWM_TICKS);
    259 	if (error) {
    260 		device_printf(sc->sc_dev,
    261 		    "disable: unable to program channel %u\n",
    262 		    chan->ch_number);
    263 	}
    264 
    265 	mutex_exit(&sc->sc_lock);
    266 
    267 	return error;
    268 }
    269 
    270 static int
    271 pcapwm_pwm_get_config(pwm_tag_t pwm, struct pwm_config *conf)
    272 {
    273 	struct pcapwm_softc * const sc = device_private(pwm->pwm_dev);
    274 	struct pcapwm_channel * const chan = pwm->pwm_priv;
    275 	uint16_t on_tick, off_tick;
    276 	u_int duty_cycle;
    277 	int error;
    278 
    279 	mutex_enter(&sc->sc_lock);
    280 
    281 	error = pcapwm_inspect_channel(sc, chan, &on_tick, &off_tick);
    282 	if (error) {
    283 		device_printf(sc->sc_dev,
    284 		    "get_config: unable to inspect channel %u\n",
    285 		        chan->ch_number);
    286 		goto out;
    287 	}
    288 
    289 	if (on_tick & PCA9685_PWM_TICKS) {
    290 		duty_cycle = chan->ch_conf.period;
    291 	} else if (off_tick & PCA9685_PWM_TICKS) {
    292 		duty_cycle = 0;
    293 	} else {
    294 		/*
    295 		 * Compute the number of ticks, accounting for a non-zero
    296 		 * on-tick (which the hardware can do, even if the software
    297 		 * can't).
    298 		 */
    299 		int signed_off_tick = off_tick;
    300 		signed_off_tick -= on_tick;
    301 		if (signed_off_tick < 0)
    302 			signed_off_tick += PCA9685_PWM_TICKS;
    303 		const uint64_t nticks = signed_off_tick;
    304 		duty_cycle = (u_int)((nticks * chan->ch_conf.period) /
    305 		    PCA9685_PWM_TICKS);
    306 	}
    307 
    308 	*conf = chan->ch_conf;
    309 	conf->duty_cycle = duty_cycle;
    310 
    311  out:
    312 	mutex_exit(&sc->sc_lock);
    313 
    314 	return error;
    315 }
    316 
    317 static int
    318 pcapwm_pwm_set_config(pwm_tag_t pwm, const struct pwm_config *conf)
    319 {
    320 	struct pcapwm_softc * const sc = device_private(pwm->pwm_dev);
    321 	struct pcapwm_channel * const chan = pwm->pwm_priv;
    322 	int error = 0;
    323 
    324 	mutex_enter(&sc->sc_lock);
    325 
    326 	/* Only active-high is supported. */
    327 	if (conf->polarity != PWM_ACTIVE_HIGH) {
    328 		device_printf(sc->sc_dev,
    329 		    "set_config: invalid polarity: %d\n", conf->polarity);
    330 		error = EINVAL;
    331 		goto out;
    332 	}
    333 
    334 	if (sc->sc_period != conf->period) {
    335 		/*
    336 		 * Formula for the prescale is:
    337 		 *
    338 		 *           (     clk_freq      )
    339 		 *      round( ----------------- ) - 1
    340 		 *           (  4096 * pwm_freq  )
    341 		 *
    342 		 * pwm_freq == 1000000000 / period.
    343 		 *
    344 		 * To do the rounding step, we scale the oscillator_freq
    345 		 * by 100, check for the rounding condition, and then
    346 		 * de-scale before the subtraction step.
    347 		 */
    348 		const u_int pwm_freq = 1000000000 / conf->period;
    349 		u_int prescale = (sc->sc_clk_freq * 100) /
    350 		    (PCA9685_PWM_TICKS * pwm_freq);
    351 		if ((prescale % 100) >= 50)
    352 			prescale += 100;
    353 		prescale = (prescale / 100) - 1;
    354 		if (prescale < PCA9685_PRESCALE_MIN ||
    355 		    prescale > PCA9685_PRESCALE_MAX) {
    356 			device_printf(sc->sc_dev,
    357 			    "set_config: invalid period: %uns\n", conf->period);
    358 			error = EINVAL;
    359 			goto out;
    360 		}
    361 
    362 		uint8_t mode1;
    363 		error = pcapwm_read1(sc, PCA9685_MODE1, &mode1);
    364 		if (error) {
    365 			device_printf(sc->sc_dev,
    366 			    "set_config: unable to read MODE1\n");
    367 			goto out;
    368 		}
    369 
    370 		/* Disable the internal oscillator. */
    371 		mode1 |= MODE1_SLEEP;
    372 		error = pcapwm_write1(sc, PCA9685_MODE1, mode1);
    373 		if (error) {
    374 			device_printf(sc->sc_dev,
    375 			    "set_config: unable to write MODE1\n");
    376 			goto out;
    377 		}
    378 
    379 		/* Update the prescale register. */
    380 		error = pcapwm_write1(sc, PCA9685_PRE_SCALE,
    381 		    (uint8_t)(prescale & 0xff));
    382 		if (error) {
    383 			device_printf(sc->sc_dev,
    384 			    "set_config: unable to write PRE_SCALE\n");
    385 			goto out;
    386 		}
    387 
    388 		/*
    389 		 * If we're using an external clock source, keep the
    390 		 * internal oscillator turned off.
    391 		 *
    392 		 * XXX The datasheet is a little ambiguous about how this
    393 		 * XXX is supposed to work -- on the same page it says to
    394 		 * XXX perform this procedure, and also that PWM control of
    395 		 * XXX the channels is not possible when the oscillator is
    396 		 * XXX disabled.  I haven't tested this with an external
    397 		 * XXX oscillator yet, so I don't know for sure.
    398 		 */
    399 		if (sc->sc_ext_clk) {
    400 			mode1 |= MODE1_EXTCLK;
    401 		} else {
    402 			mode1 &= ~MODE1_SLEEP;
    403 		}
    404 
    405 		/*
    406 		 * We rely on auto-increment for the PWM register updates.
    407 		 */
    408 		mode1 |= MODE1_AI;
    409 
    410 		error = pcapwm_write1(sc, PCA9685_MODE1, mode1);
    411 		if (error) {
    412 			device_printf(sc->sc_dev,
    413 			    "set_config: unable to write MODE1\n");
    414 			goto out;
    415 		}
    416 
    417 		if (sc->sc_ext_clk == false) {
    418 			/* Wait for 500us for the clock to settle. */
    419 			delay(500);
    420 		}
    421 
    422 		sc->sc_period = conf->period;
    423 	}
    424 
    425 	uint16_t on_tick, off_tick;
    426 
    427 	/*
    428 	 * The PWM framework doesn't support the phase-shift / start-delay
    429 	 * feature of this chip, so all duty cycles start at 0 ticks.
    430 	 */
    431 
    432 	/*
    433 	 * For full-on and full-off, use the magic FULL-{ON,OFF} values
    434 	 * described in the data sheet.
    435 	 */
    436 	if (conf->duty_cycle == 0) {
    437 		on_tick = 0;
    438 		off_tick = PCA9685_PWM_TICKS;
    439 	} else if (conf->duty_cycle == sc->sc_period) {
    440 		on_tick = PCA9685_PWM_TICKS;
    441 		off_tick = 0;
    442 	} else {
    443 		uint64_t ticks =
    444 		    PCA9685_PWM_TICKS * (uint64_t)conf->duty_cycle;
    445 		/* Scale up so we can check if we need to round. */
    446 		ticks = (ticks * 100) / sc->sc_period;
    447 		/* Round up. */
    448 		if (ticks % 100)
    449 			ticks += 100;
    450 		ticks /= 100;
    451 		if (ticks >= PCA9685_PWM_TICKS) {
    452 			ticks = PCA9685_PWM_TICKS - 1;
    453 		}
    454 
    455 		on_tick = 0;
    456 		off_tick = (u_int)ticks;
    457 	}
    458 
    459 	error = pcapwm_program_channel(sc, chan, on_tick, off_tick);
    460 	if (error) {
    461 		device_printf(sc->sc_dev,
    462 		    "set_config: unable to program channel %u\n",
    463 		    chan->ch_number);
    464 		goto out;
    465 	}
    466 
    467 	chan->ch_conf = *conf;
    468 
    469  out:
    470 	mutex_exit(&sc->sc_lock);
    471 
    472 	return error;
    473 }
    474 
    475 static int
    476 pcapwm_match(device_t parent, cfdata_t cf, void *aux)
    477 {
    478 	struct i2c_attach_args * const ia = aux;
    479 	int match_result;
    480 
    481 	if (iic_use_direct_match(ia, cf, compat_data, &match_result)) {
    482 		return match_result;
    483 	}
    484 
    485 	/* This device is direct-config only. */
    486 
    487 	return 0;
    488 }
    489 
    490 static void
    491 pcapwm_attach(device_t parent, device_t self, void *aux)
    492 {
    493 	struct pcapwm_softc * const sc = device_private(self);
    494 	struct i2c_attach_args * const ia = aux;
    495 	struct clk *clk;
    496 	const int phandle = (int)ia->ia_cookie;
    497 	u_int index;
    498 	int error;
    499 
    500 	sc->sc_dev = self;
    501 	sc->sc_i2c = ia->ia_tag;
    502 	sc->sc_addr = ia->ia_addr;
    503 
    504 	aprint_naive("\n");
    505 	aprint_normal(": PCA9685 PWM controller\n");
    506 
    507 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_NONE);
    508 
    509 	for (index = 0; index <= PCA9685_ALL_CHANNELS; index++) {
    510 		pcapwm_init_channel(sc, index);
    511 	}
    512 
    513 	clk = fdtbus_clock_get_index(phandle, 0);
    514 	if (clk != NULL) {
    515 		sc->sc_ext_clk = true;
    516 		sc->sc_clk_freq = clk_get_rate(clk);
    517 	} else {
    518 		sc->sc_clk_freq = PCA9685_INTERNAL_FREQ;
    519 	}
    520 
    521 	if (of_hasprop(phandle, "invert")) {
    522 		sc->sc_invert = true;
    523 	}
    524 
    525 	if (of_hasprop(phandle, "open-drain")) {
    526 		sc->sc_open_drain = true;
    527 	}
    528 
    529 	/*
    530 	 * XXX No DT bindings for the OUTNEx configurations in
    531 	 * MODE2.
    532 	 */
    533 
    534 	/*
    535 	 * Set up the outputs.  We want the channel to update when
    536 	 * we send the I2C "STOP" condition.
    537 	 */
    538 	uint8_t mode2;
    539 	error = pcapwm_read1(sc, PCA9685_MODE2, &mode2);
    540 	if (error == 0) {
    541 		mode2 &= ~(MODE2_OUTDRV | MODE2_OCH | MODE2_INVRT);
    542 		if (sc->sc_invert) {
    543 			mode2 |= MODE2_INVRT;
    544 		}
    545 		if (sc->sc_open_drain == false) {
    546 			mode2 |= MODE2_OUTDRV;
    547 		}
    548 		error = pcapwm_write1(sc, PCA9685_MODE2, mode2);
    549 	}
    550 	if (error) {
    551 		aprint_error_dev(sc->sc_dev, "failed to configure MODE2\n");
    552 		return;
    553 	}
    554 
    555 	fdtbus_register_pwm_controller(self, phandle,
    556 	    &pcapwm_pwm_funcs);
    557 }
    558 
    559 CFATTACH_DECL_NEW(pcapwm, sizeof(struct pcapwm_softc),
    560     pcapwm_match, pcapwm_attach, NULL, NULL);
    561