This short post is an extension to my earlier post . If you read that post you will have noticed that the calculations of <b>tusec_On </b> and <b>tusec_Off</b>, which or the on- and off times of the PWM dutycycle, were calculated in the same loop as the bit banging of the GPIO pin was done to generate the PWM signal. While these are two relatively small calculations, that will not affect noticeably the PWM signal, it is still a better approach no to have other things one in the PWM loop, besides the bit banging of the GPIO pin.

To have the dutycyle and the PWM frequency updated in real-time, they need to be calculated in a parallel (concurrent) thread. This is the goal for this post.

The Module Code

Following is the slightly modified kernel code for the PWM driver. Note that now linux/kthread.h is being included:

The difference between this code and the one from my earlier post is the threading block between line 67 and line 98. The calculations for the on- and off-times of the dutycycle are removed now from the pwm_run_init() function and moved to a thread function pwm_thread().
When pwm_thread_inti() is called on line 107, it sets off the function pwm_thread() from line 90 as a thread. The call kthread_run(threadfn, data, Namefmt, …) generates a new thread and has generally three arguments:

  1. Threadfn is the function name to run
  2. Data is a pointer to the function arguments
  3. Namefmt is the name of the thread (in ps) – Specified in a printf formatting string

The function kthread_should_stop() returns a 1 when kthread_stop(task) is called on the thread task. This is done when pwm_thread_exit() is called from the main function and executes kthread_stop(task) in line 96.

The Makefile

The Make file for this project is identical to the one from my earlier post (just the module name is changed:


This short post introduced threading for a “smoother” PWM driver. A simple thread was introduced to update in real-time the dutycycle parameters.