pwm.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. /****************************************************************************
  2. * drivers/pwm/pwm.c
  3. *
  4. * Copyright (C) 2011-2013, 2016-2017 Gregory Nutt. All rights reserved.
  5. * Author: Gregory Nutt <gnutt@nuttx.org>
  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. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. * 2. Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in
  15. * the documentation and/or other materials provided with the
  16. * distribution.
  17. * 3. Neither the name NuttX nor the names of its contributors may be
  18. * used to endorse or promote products derived from this software
  19. * without specific prior written permission.
  20. *
  21. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  24. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  25. * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  26. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  27. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  28. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  29. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  30. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  31. * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  32. * POSSIBILITY OF SUCH DAMAGE.
  33. *
  34. ****************************************************************************/
  35. /****************************************************************************
  36. * Included Files
  37. ****************************************************************************/
  38. #include <nuttx/config.h>
  39. #include <sys/types.h>
  40. #include <stdint.h>
  41. #include <stdbool.h>
  42. #include <stdlib.h>
  43. #include <unistd.h>
  44. #include <string.h>
  45. #include <semaphore.h>
  46. #include <fcntl.h>
  47. #include <assert.h>
  48. #include <errno.h>
  49. #include <debug.h>
  50. #include <nuttx/arch.h>
  51. #include <nuttx/kmalloc.h>
  52. #include <nuttx/semaphore.h>
  53. #include <nuttx/fs/fs.h>
  54. #include <nuttx/drivers/pwm.h>
  55. #include <nuttx/irq.h>
  56. #ifdef CONFIG_PWM
  57. /****************************************************************************
  58. * Private Type Definitions
  59. ****************************************************************************/
  60. /* This structure describes the state of the upper half driver */
  61. struct pwm_upperhalf_s
  62. {
  63. uint8_t crefs; /* The number of times the device has been opened */
  64. volatile bool started; /* True: pulsed output is being generated */
  65. #ifdef CONFIG_PWM_PULSECOUNT
  66. volatile bool waiting; /* True: Caller is waiting for the pulse count to expire */
  67. #endif
  68. sem_t exclsem; /* Supports mutual exclusion */
  69. #ifdef CONFIG_PWM_PULSECOUNT
  70. sem_t waitsem; /* Used to wait for the pulse count to expire */
  71. #endif
  72. struct pwm_info_s info; /* Pulsed output characteristics */
  73. FAR struct pwm_lowerhalf_s *dev; /* lower-half state */
  74. };
  75. /****************************************************************************
  76. * Private Function Prototypes
  77. ****************************************************************************/
  78. static void pwm_dump(FAR const char *msg,
  79. FAR const struct pwm_info_s *info,
  80. bool started);
  81. static int pwm_open(FAR struct file *filep);
  82. static int pwm_close(FAR struct file *filep);
  83. static ssize_t pwm_read(FAR struct file *filep, FAR char *buffer,
  84. size_t buflen);
  85. static ssize_t pwm_write(FAR struct file *filep, FAR const char *buffer,
  86. size_t buflen);
  87. static int pwm_start(FAR struct pwm_upperhalf_s *upper,
  88. unsigned int oflags);
  89. static int pwm_ioctl(FAR struct file *filep, int cmd, unsigned long arg);
  90. /****************************************************************************
  91. * Private Data
  92. ****************************************************************************/
  93. static const struct file_operations g_pwmops =
  94. {
  95. pwm_open, /* open */
  96. pwm_close, /* close */
  97. pwm_read, /* read */
  98. pwm_write, /* write */
  99. 0, /* seek */
  100. pwm_ioctl /* ioctl */
  101. #ifndef CONFIG_DISABLE_POLL
  102. , 0 /* poll */
  103. #endif
  104. };
  105. /****************************************************************************
  106. * Private Functions
  107. ****************************************************************************/
  108. /****************************************************************************
  109. * Name: pwm_dump
  110. ****************************************************************************/
  111. static void pwm_dump(FAR const char *msg, FAR const struct pwm_info_s *info,
  112. bool started)
  113. {
  114. #ifdef CONFIG_PWM_MULTICHAN
  115. int i;
  116. #endif
  117. pwminfo("%s: frequency: %d", msg, info->frequency);
  118. #ifdef CONFIG_PWM_MULTICHAN
  119. for (i = 0; i < CONFIG_PWM_NCHANNELS; i++)
  120. {
  121. pwminfo(" channel: %d duty: %08x",
  122. info->channels[i].channel, info->channels[i].duty);
  123. }
  124. #else
  125. pwminfo(" duty: %08x", info->duty);
  126. #endif
  127. #ifdef CONFIG_PWM_PULSECOUNT
  128. pwminfo(" count: %d\n", info->count);
  129. #endif
  130. pwminfo(" started: %d\n", started);
  131. }
  132. /****************************************************************************
  133. * Name: pwm_open
  134. *
  135. * Description:
  136. * This function is called whenever the PWM device is opened.
  137. *
  138. ****************************************************************************/
  139. static int pwm_open(FAR struct file *filep)
  140. {
  141. FAR struct inode *inode = filep->f_inode;
  142. FAR struct pwm_upperhalf_s *upper = inode->i_private;
  143. uint8_t tmp;
  144. int ret;
  145. pwminfo("crefs: %d\n", upper->crefs);
  146. /* Get exclusive access to the device structures */
  147. ret = nxsem_wait(&upper->exclsem);
  148. if (ret < 0)
  149. {
  150. goto errout;
  151. }
  152. /* Increment the count of references to the device. If this the first
  153. * time that the driver has been opened for this device, then initialize
  154. * the device.
  155. */
  156. tmp = upper->crefs + 1;
  157. if (tmp == 0)
  158. {
  159. /* More than 255 opens; uint8_t overflows to zero */
  160. ret = -EMFILE;
  161. goto errout_with_sem;
  162. }
  163. /* Check if this is the first time that the driver has been opened. */
  164. if (tmp == 1)
  165. {
  166. FAR struct pwm_lowerhalf_s *lower = upper->dev;
  167. /* Yes.. perform one time hardware initialization. */
  168. DEBUGASSERT(lower->ops->setup != NULL);
  169. pwminfo("calling setup\n");
  170. ret = lower->ops->setup(lower);
  171. if (ret < 0)
  172. {
  173. goto errout_with_sem;
  174. }
  175. }
  176. /* Save the new open count on success */
  177. upper->crefs = tmp;
  178. ret = OK;
  179. errout_with_sem:
  180. nxsem_post(&upper->exclsem);
  181. errout:
  182. return ret;
  183. }
  184. /****************************************************************************
  185. * Name: pwm_close
  186. *
  187. * Description:
  188. * This function is called when the PWM device is closed.
  189. *
  190. ****************************************************************************/
  191. static int pwm_close(FAR struct file *filep)
  192. {
  193. FAR struct inode *inode = filep->f_inode;
  194. FAR struct pwm_upperhalf_s *upper = inode->i_private;
  195. int ret;
  196. pwminfo("crefs: %d\n", upper->crefs);
  197. /* Get exclusive access to the device structures */
  198. ret = nxsem_wait(&upper->exclsem);
  199. if (ret < 0)
  200. {
  201. goto errout;
  202. }
  203. /* Decrement the references to the driver. If the reference count will
  204. * decrement to 0, then uninitialize the driver.
  205. */
  206. if (upper->crefs > 1)
  207. {
  208. upper->crefs--;
  209. }
  210. else
  211. {
  212. FAR struct pwm_lowerhalf_s *lower = upper->dev;
  213. /* There are no more references to the port */
  214. upper->crefs = 0;
  215. /* Disable the PWM device */
  216. DEBUGASSERT(lower->ops->shutdown != NULL);
  217. pwminfo("calling shutdown: %d\n");
  218. lower->ops->shutdown(lower);
  219. }
  220. ret = OK;
  221. nxsem_post(&upper->exclsem);
  222. errout:
  223. return ret;
  224. }
  225. /****************************************************************************
  226. * Name: pwm_read
  227. *
  228. * Description:
  229. * A dummy read method. This is provided only to satisfy the VFS layer.
  230. *
  231. ****************************************************************************/
  232. static ssize_t pwm_read(FAR struct file *filep, FAR char *buffer,
  233. size_t buflen)
  234. {
  235. /* Return zero -- usually meaning end-of-file */
  236. return 0;
  237. }
  238. /****************************************************************************
  239. * Name: pwm_write
  240. *
  241. * Description:
  242. * A dummy write method. This is provided only to satisfy the VFS layer.
  243. *
  244. ****************************************************************************/
  245. static ssize_t pwm_write(FAR struct file *filep, FAR const char *buffer,
  246. size_t buflen)
  247. {
  248. return 0;
  249. }
  250. /****************************************************************************
  251. * Name: pwm_start
  252. *
  253. * Description:
  254. * Handle the PWMIOC_START ioctl command
  255. *
  256. ****************************************************************************/
  257. #ifdef CONFIG_PWM_PULSECOUNT
  258. static int pwm_start(FAR struct pwm_upperhalf_s *upper, unsigned int oflags)
  259. {
  260. FAR struct pwm_lowerhalf_s *lower;
  261. irqstate_t flags;
  262. int ret = OK;
  263. DEBUGASSERT(upper != NULL);
  264. lower = upper->dev;
  265. DEBUGASSERT(lower != NULL && lower->ops->start != NULL);
  266. /* Verify that the PWM is not already running */
  267. if (!upper->started)
  268. {
  269. /* Disable interrupts to avoid race conditions */
  270. flags = enter_critical_section();
  271. /* Indicate that if will be waiting for the pulse count to complete.
  272. * Note that we will only wait if a non-zero pulse count is specified
  273. * and if the PWM driver was opened in normal, blocking mode. Also
  274. * assume for now that the pulse train will be successfully started.
  275. *
  276. * We do these things before starting the PWM to avoid race conditions.
  277. */
  278. upper->waiting = (upper->info.count > 0) && ((oflags & O_NONBLOCK) == 0);
  279. upper->started = true;
  280. /* Invoke the bottom half method to start the pulse train */
  281. ret = lower->ops->start(lower, &upper->info, upper);
  282. /* A return value of zero means that the pulse train was started
  283. * successfully.
  284. */
  285. if (ret == OK)
  286. {
  287. /* Should we wait for the pulse output to complete? Loop in
  288. * in case the wakeup form nxsem_wait() is a false alarm.
  289. */
  290. while (upper->waiting)
  291. {
  292. /* Wait until we are awakened by pwm_expired(). When
  293. * pwm_expired is called, it will post the waitsem and
  294. * clear the waiting flag.
  295. */
  296. int tmp = nxsem_wait(&upper->waitsem);
  297. DEBUGASSERT(tmp == OK || tmp == -EINTR);
  298. }
  299. }
  300. else
  301. {
  302. /* Looks like we won't be waiting after all */
  303. pwminfo("start failed: %d\n", ret);
  304. upper->started = false;
  305. upper->waiting = false;
  306. }
  307. leave_critical_section(flags);
  308. }
  309. return ret;
  310. }
  311. #else
  312. static int pwm_start(FAR struct pwm_upperhalf_s *upper, unsigned int oflags)
  313. {
  314. FAR struct pwm_lowerhalf_s *lower;
  315. int ret = OK;
  316. DEBUGASSERT(upper != NULL);
  317. lower = upper->dev;
  318. DEBUGASSERT(lower != NULL && lower->ops->start != NULL);
  319. /* Verify that the PWM is not already running */
  320. if (!upper->started)
  321. {
  322. /* Invoke the bottom half method to start the pulse train */
  323. ret = lower->ops->start(lower, &upper->info);
  324. /* A return value of zero means that the pulse train was started
  325. * successfully.
  326. */
  327. if (ret == OK)
  328. {
  329. /* Indicate that the pulse train has started */
  330. upper->started = true;
  331. }
  332. }
  333. return ret;
  334. }
  335. #endif
  336. /****************************************************************************
  337. * Name: pwm_ioctl
  338. *
  339. * Description:
  340. * The standard ioctl method. This is where ALL of the PWM work is done.
  341. *
  342. ****************************************************************************/
  343. static int pwm_ioctl(FAR struct file *filep, int cmd, unsigned long arg)
  344. {
  345. FAR struct inode *inode = filep->f_inode;
  346. FAR struct pwm_upperhalf_s *upper = inode->i_private;
  347. FAR struct pwm_lowerhalf_s *lower = upper->dev;
  348. int ret;
  349. pwminfo("cmd: %d arg: %ld\n", cmd, arg);
  350. /* Get exclusive access to the device structures */
  351. ret = nxsem_wait(&upper->exclsem);
  352. if (ret < 0)
  353. {
  354. return ret;
  355. }
  356. /* Handle built-in ioctl commands */
  357. switch (cmd)
  358. {
  359. /* PWMIOC_SETCHARACTERISTICS - Set the characteristics of the next pulsed
  360. * output. This command will neither start nor stop the pulsed output.
  361. * It will either setup the configuration that will be used when the
  362. * output is started; or it will change the characteristics of the pulsed
  363. * output on the fly if the timer is already started.
  364. *
  365. * ioctl argument: A read-only reference to struct pwm_info_s that provides
  366. * the characteristics of the pulsed output.
  367. */
  368. case PWMIOC_SETCHARACTERISTICS:
  369. {
  370. FAR const struct pwm_info_s *info = (FAR const struct pwm_info_s *)((uintptr_t)arg);
  371. DEBUGASSERT(info != NULL && lower->ops->start != NULL);
  372. pwm_dump("PWMIOC_SETCHARACTERISTICS", info, upper->started);
  373. /* Save the pulse train characteristics */
  374. memcpy(&upper->info, info, sizeof(struct pwm_info_s));
  375. /* If PWM is already running, then re-start it with the new characteristics */
  376. if (upper->started)
  377. {
  378. #ifdef CONFIG_PWM_PULSECOUNT
  379. ret = lower->ops->start(lower, &upper->info, upper);
  380. #else
  381. ret = lower->ops->start(lower, &upper->info);
  382. #endif
  383. }
  384. }
  385. break;
  386. /* PWMIOC_GETCHARACTERISTICS - Get the currently selected characteristics of
  387. * the pulsed output (independent of whether the output is start or stopped).
  388. *
  389. * ioctl argument: A reference to struct pwm_info_s to receive the
  390. * characteristics of the pulsed output.
  391. */
  392. case PWMIOC_GETCHARACTERISTICS:
  393. {
  394. FAR struct pwm_info_s *info = (FAR struct pwm_info_s *)((uintptr_t)arg);
  395. DEBUGASSERT(info != NULL);
  396. memcpy(info, &upper->info, sizeof(struct pwm_info_s));
  397. pwm_dump("PWMIOC_GETCHARACTERISTICS", info, upper->started);
  398. }
  399. break;
  400. /* PWMIOC_START - Start the pulsed output. The PWMIOC_SETCHARACTERISTICS
  401. * command must have previously been sent.
  402. *
  403. * ioctl argument: None
  404. */
  405. case PWMIOC_START:
  406. {
  407. pwm_dump("PWMIOC_START", &upper->info, upper->started);
  408. DEBUGASSERT(lower->ops->start != NULL);
  409. /* Start the pulse train */
  410. ret = pwm_start(upper, filep->f_oflags);
  411. }
  412. break;
  413. /* PWMIOC_STOP - Stop the pulsed output.
  414. *
  415. * ioctl argument: None
  416. */
  417. case PWMIOC_STOP:
  418. {
  419. pwminfo("PWMIOC_STOP: started: %d\n", upper->started);
  420. DEBUGASSERT(lower->ops->stop != NULL);
  421. if (upper->started)
  422. {
  423. ret = lower->ops->stop(lower);
  424. upper->started = false;
  425. #ifdef CONFIG_PWM_PULSECOUNT
  426. if (upper->waiting)
  427. {
  428. upper->waiting = false;
  429. }
  430. #endif
  431. }
  432. }
  433. break;
  434. /* Any unrecognized IOCTL commands might be platform-specific ioctl commands */
  435. default:
  436. {
  437. pwminfo("Forwarding unrecognized cmd: %d arg: %ld\n", cmd, arg);
  438. DEBUGASSERT(lower->ops->ioctl != NULL);
  439. ret = lower->ops->ioctl(lower, cmd, arg);
  440. }
  441. break;
  442. }
  443. nxsem_post(&upper->exclsem);
  444. return ret;
  445. }
  446. /****************************************************************************
  447. * Public Functions
  448. ****************************************************************************/
  449. /****************************************************************************
  450. * Name: pwm_register
  451. *
  452. * Description:
  453. * This function binds an instance of a "lower half" timer driver with the
  454. * "upper half" PWM device and registers that device so that can be used
  455. * by application code.
  456. *
  457. * When this function is called, the "lower half" driver should be in the
  458. * reset state (as if the shutdown() method had already been called).
  459. *
  460. * Input Parameters:
  461. * path - The full path to the driver to be registered in the NuttX pseudo-
  462. * filesystem. The recommended convention is to name all PWM drivers
  463. * as "/dev/pwm0", "/dev/pwm1", etc. where the driver path differs only
  464. * in the "minor" number at the end of the device name.
  465. * dev - A pointer to an instance of lower half timer driver. This instance
  466. * is bound to the PWM driver and must persists as long as the driver
  467. * persists.
  468. *
  469. * Returned Value:
  470. * Zero on success; a negated errno value on failure.
  471. *
  472. ****************************************************************************/
  473. int pwm_register(FAR const char *path, FAR struct pwm_lowerhalf_s *dev)
  474. {
  475. FAR struct pwm_upperhalf_s *upper;
  476. /* Allocate the upper-half data structure */
  477. upper = (FAR struct pwm_upperhalf_s *)kmm_zalloc(sizeof(struct pwm_upperhalf_s));
  478. if (!upper)
  479. {
  480. pwmerr("Allocation failed\n");
  481. return -ENOMEM;
  482. }
  483. /* Initialize the PWM device structure (it was already zeroed by kmm_zalloc()) */
  484. nxsem_init(&upper->exclsem, 0, 1);
  485. #ifdef CONFIG_PWM_PULSECOUNT
  486. nxsem_init(&upper->waitsem, 0, 0);
  487. /* The wait semaphore is used for signaling and, hence, should not have priority
  488. * inheritance enabled.
  489. */
  490. nxsem_setprotocol(&upper->waitsem, SEM_PRIO_NONE);
  491. #endif
  492. upper->dev = dev;
  493. /* Register the PWM device */
  494. pwminfo("Registering %s\n", path);
  495. return register_driver(path, &g_pwmops, 0666, upper);
  496. }
  497. /****************************************************************************
  498. * Name: pwm_expired
  499. *
  500. * Description:
  501. * If CONFIG_PWM_PULSECOUNT is defined and the pulse count was configured
  502. * to a non-zero value, then the "upper half" driver will wait for the
  503. * pulse count to expire. The sequence of expected events is as follows:
  504. *
  505. * 1. The upper half driver calls the start method, providing the lower
  506. * half driver with the pulse train characteristics. If a fixed
  507. * number of pulses is required, the 'count' value will be nonzero.
  508. * 2. The lower half driver's start() methoc must verify that it can
  509. * support the request pulse train (frequency, duty, AND pulse count).
  510. * If it cannot, it should return an error. If the pulse count is
  511. * non-zero, it should set up the hardware for that number of pulses
  512. * and return success. NOTE: That is CONFIG_PWM_PULSECOUNT is
  513. * defined, the start() method receives an additional parameter
  514. * that must be used in this callback.
  515. * 3. When the start() method returns success, the upper half driver
  516. * will "sleep" until the pwm_expired method is called.
  517. * 4. When the lower half detects that the pulse count has expired
  518. * (probably through an interrupt), it must call the pwm_expired
  519. * interface using the handle that was previously passed to the
  520. * start() method
  521. *
  522. * Input Parameters:
  523. * handle - This is the handle that was provided to the lower-half
  524. * start() method.
  525. *
  526. * Returned Value:
  527. * None
  528. *
  529. * Assumptions:
  530. * This function may be called from an interrupt handler.
  531. *
  532. ****************************************************************************/
  533. #ifdef CONFIG_PWM_PULSECOUNT
  534. void pwm_expired(FAR void *handle)
  535. {
  536. FAR struct pwm_upperhalf_s *upper = (FAR struct pwm_upperhalf_s *)handle;
  537. pwminfo("started: %d waiting: %d\n", upper->started, upper->waiting);
  538. /* Make sure that the PWM is started */
  539. if (upper->started)
  540. {
  541. /* Is there a thread waiting for the pulse train to complete? */
  542. if (upper->waiting)
  543. {
  544. /* Yes.. clear the waiting flag and awakened the waiting thread */
  545. upper->waiting = false;
  546. nxsem_post(&upper->waitsem);
  547. }
  548. /* The PWM is now stopped */
  549. upper->started = false;
  550. }
  551. }
  552. #endif
  553. #endif /* CONFIG_PWM */