This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

TM4C1231H6PGE: Best way to synchronize your main loop to the PWM frequency

Part Number: TM4C1231H6PGE

Hello,

This post comes in continuation to a question I already asked on the forum.
I'm designing a PID control system that does the following:

1. Takes linear and angular acceleration readings from a sensor via I2C.
2. Calculates the angle ( roll ) of the object I want to control.
3. Calculates the required Proportional , Integral and Derivative control values.
4. Sends the control command 400 times per second ( 400 MHz ) via PWM.

Because step 4 is slowest event in the system - I want to time everything to it.
The PWM is generated from one the TIVA's peripheral modules - which is also capable of generating an interrupt synchronous to the PWM frequency.
So my idea is to have steps 1 to 4 execute inside the PWM Interrupt Service Routine.


What do you think about this approach ?
Is it good ? Or perhaps there's a better / simpler way ?

  • It is usually a bad idea to put all of the calculations into an interrupt routine. I suggest in the interrupt routine that you start the I2C communications and return. Then use I2C interrupts as each new byte is sent or received. You can use a static variable (usually an enum) that keeps track of when to send the next byte or read and store the byte that you received. When you have read the last bit of data needed for your calculations, set a volatile static variable to let your main loop know that it can start the calculation process. This method prevents the CPU being consumed waiting for a peripheral to finish. If you can start some of the calculations with part of the data your read, you can have the flag take several states and you can be computing the first calculations while the interrupts feed the I2C to collect the rest of the data. While this may not be simpler, it allows the device to accomplish more in the time allowed.

    If you want to keep it simple, just use the volatile flag that you set in the PWM interrupt routine. In the main loop, you wait for the flag to be set. When it is, start all of the I2C communication and the calculations then clear the flag. This is similar to your original approach, but does not leave interrupts disabled while you are doing all of the work. Also, in the PWM interrupt routine, if you see the flag is still set from the previous interrupt, you know that the calculation did not complete in time.

    If your project grows more complex with several tasks to perform, you may want to consider using real time operating system like TI-RTOS. This adds some complications and a learning curve.