Coder Social home page Coder Social logo

khoih-prog / dx_slow_pwm Goto Github PK

View Code? Open in Web Editor NEW
0.0 2.0 0.0 803 KB

This library enables you to use ISR-based PWM channels on Arduino AVRDx-based boards (AVR128Dx, AVR64Dx, AVR32Dx, etc.), using DxCore, to create and output PWM any GPIO pin. It now supports up to 64 ISR-based PWM channels, while consuming only 1 Hardware Timer. PWM channel interval can be very long (ulong microsecs / millisecs). The most important feature is they're ISR-based PWM channels, supporting lower PWM frequencies with suitable accuracy. Their executions are not blocked by bad-behaving functions or tasks. This important feature is absolutely necessary for mission-critical tasks. These ISR-based PWMs, still work even if other software functions are blocking. Moreover, they are much more precise (certainly depending on clock frequency accuracy) than other software-based PWM using millis() or micros(). That's necessary if you need to control devices requiring high precision. Now you can change the PWM settings on-the-fly.

License: MIT License

C 58.48% C++ 41.21% Shell 0.31%
duty-cycle hardware-timer isr isr-based isr-based-pmw megaavr multi-channel-pwm on-the-fly pwm pwm-driver

dx_slow_pwm's Introduction

Dx_Slow_PWM Library

arduino-library-badge GitHub release GitHub contributions welcome GitHub issues

Donate to my libraries using BuyMeACoffee



Table of Contents



Important Note for Arduino IDE

With some Arduino IDE versions, such as v1.8.19, upload directly via USB to some boards, such as Curiosity_AVR128DA48 or Curiosity_AVR128DB48 can't be done without unknown-to-me fix. We'll get the following error when uploading

avrdude: Version 6.3-20201216
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "/home/kh/.arduino15/packages/DxCore/hardware/megaavr/1.4.10/avrdude.conf"
     User configuration file is "/home/kh/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

     Using Port                    : usb
     Using Programmer              : curiosity_updi
avrdude: usbdev_open(): Found nEDBG CMSIS-DAP, serno: MCHP3280041800002682
avrdude: usbdev_open(): WARNING: failed to set configuration 1: Device or resource busy
avrdude: Found CMSIS-DAP compliant device, using EDBG protocol
avrdude: usbdev_send(): wrote -5 out of 912 bytes, err = Input/output error
avrdude: jtag3_edbg_prepare(): failed to send command to serial port

avrdude done.  Thank you.

the selected serial port 
 does not exist or your board is not connected

We can use drag-and-drop method to drag-and-drop the compiled hex file to CURIOSITY virtual drive.

If success, The LED blinks slowly for 2 sec. The LED will blinks rapidly for 2 sec if failure

For example, to run Change_Interval example, use Arduino IDE to compile, and get the Change_Interval.ino.hex file. For Ubuntu Linux, the file is stored in directory /tmp/arduino_build_xxxxxx

After drag-and-drop the Change_Interval.ino.hex into CURIOSITY virtual drive, the code will run immediately if successfully loaded (LED blinks slowly)



Why do we need this Dx_Slow_PWM library

Features

This library enables you to use ISR-based PWM channels on Arduino AVRDx-based boards (AVR128Dx, AVR64Dx, AVR32Dx, etc.), using DxCore, to create and output PWM any GPIO pin. Because this library doesn't use the powerful purely hardware-controlled PWM with many limitations, the maximum PWM frequency is currently limited at 1000Hz, which is still suitable for many real-life applications. Now you can change the PWM settings on-the-fly


This library enables you to use Interrupt from Hardware Timers on AVRDx-based boards to create and output PWM to pins. It now supports 64 ISR-based synchronized PWM channels, while consuming only 1 Hardware Timer. PWM interval can be very long (uint64_t microsecs / millisecs). The most important feature is they're ISR-based PWM channels. Therefore, their executions are not blocked by bad-behaving functions or tasks. This important feature is absolutely necessary for mission-critical tasks. These hardware PWM channels, using interrupt, still work even if other functions are blocking. Moreover, they are much more precise (certainly depending on clock frequency accuracy) than other software PWM using millis() or micros(). That's necessary if you need to measure some data requiring better accuracy.

As Hardware Timers are rare, and very precious assets of any board, this library now enables you to use up to 64 ISR-based synchronized PWM channels, while consuming only 1 Hardware Timer. Timers' interval is very long (ulong millisecs).

Now with these new 64 ISR-based PWM-channels, the maximum interval is practically unlimited (limited only by unsigned long milliseconds) while the accuracy is nearly perfect compared to software PWM channels.

The most important feature is they're ISR-based PWM channels. Therefore, their executions are not blocked by bad-behaving functions / tasks. This important feature is absolutely necessary for mission-critical tasks.

The ISR_8_PWMs_Array_Complex example will demonstrate the nearly perfect accuracy, compared to software PWM, by printing the actual period / duty-cycle in microsecs of each of PWM-channels.

Being ISR-based PWM, their executions are not blocked by bad-behaving functions / tasks, such as connecting to WiFi, Internet or Blynk services. You can also have many (up to 64) PWM channels to use.

This non-being-blocked important feature is absolutely necessary for mission-critical tasks.

You'll see software-based SimpleTimer is blocked while system is connecting to WiFi / Internet / Blynk, as well as by blocking task in loop(), using delay() function as an example. The elapsed time then is very unaccurate


Why using ISR-based PWM is better

Imagine you have a system with a mission-critical function, measuring water level and control the sump pump or doing something much more important. You normally use a software timer to poll, or even place the function in loop(). But what if another function is blocking the loop() or setup().

So your function might not be executed, and the result would be disastrous.

You'd prefer to have your function called, no matter what happening with other functions (busy loop, bug, etc.).

The correct choice is to use a Hardware Timer with Interrupt to call your function.

These hardware PWM channels, using interrupt, still work even if other functions are blocking. Moreover, they are much more precise (certainly depending on clock frequency accuracy) than other software PWM channels using millis() or micros(). That's necessary if you need to measure some data requiring better accuracy.

Functions using normal software PWM channels, relying on loop() and calling millis(), won't work if the loop() or setup() is blocked by certain operation. For example, certain function is blocking while it's connecting to WiFi or some services.

The catch is your function is now part of an ISR (Interrupt Service Routine), and must be lean / mean, and follow certain rules. More to read on:

HOWTO Attach Interrupt


Currently supported Boards

  • AVRDA-based boards (AVR128DA, AVR64DA, AVR32DA, etc.) using DxCore

  • AVRDB-based boards (AVR128DB, AVR64DB, AVR32DB, etc.) using DxCore

  • AVRDD-based boards (AVR64DB, AVR32DB, AVR16DB, etc.) using DxCore v1.5.1+


Important Notes about ISR

  1. Inside the attached function, delay() won’t work and the value returned by millis() will not increment. Serial data received while in the function may be lost. You should declare as volatile any variables that you modify within the attached function.

  2. Typically global variables are used to pass data between an ISR and the main program. To make sure variables shared between an ISR and the main program are updated correctly, declare them as volatile.



Prerequisites

Prerequisites

  1. Arduino IDE 1.8.19+ for Arduino. GitHub release
  2. SpenceKonde DxCore core 1.5.1+ for Arduino AVRDx boards. GitHub release. Follow DxCore Installation.
  3. To use with certain example


Installation

Use Arduino Library Manager

The best and easiest way is to use Arduino Library Manager. Search for Dx_Slow_PWM, then select / install the latest version. You can also use this link arduino-library-badge for more detailed instructions.

Manual Install

Another way to install is to:

  1. Navigate to Dx_Slow_PWM page.
  2. Download the latest release Dx_Slow_PWM-main.zip.
  3. Extract the zip file to Dx_Slow_PWM-main directory
  4. Copy whole Dx_Slow_PWM-main folder to Arduino libraries' directory such as ~/Arduino/libraries/.

VS Code & PlatformIO

  1. Install VS Code
  2. Install PlatformIO
  3. Install Dx_Slow_PWM library by using Library Manager. Search for Dx_Slow_PWM in Platform.io Author's Libraries
  4. Use included platformio.ini file from examples to ensure that all dependent libraries will installed automatically. Please visit documentation for the other options and examples at Project Configuration File


HOWTO Fix Multiple Definitions Linker Error

The current library implementation, using xyz-Impl.h instead of standard xyz.cpp, possibly creates certain Multiple Definitions Linker error in certain use cases.

You can include this .hpp file

// Can be included as many times as necessary, without `Multiple Definitions` Linker Error
#include "Dx_Slow_PWM.hpp"          //https://github.com/khoih-prog/Dx_Slow_PWM

in many files. But be sure to use the following .h file in just 1 .h, .cpp or .ino file, which must not be included in any other file, to avoid Multiple Definitions Linker Error

// To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error
#include "Dx_Slow_PWM.h"            //https://github.com/khoih-prog/Dx_Slow_PWM

Check the new multiFileProject example for a HOWTO demo.

Have a look at the discussion in Different behaviour using the src_cpp or src_h lib #80



More useful Information

1. Documents

  1. Arduino 101: Timers and Interrupts
  2. Getting Started with Timer/Counter Type B (TCB)
  3. DXCore README.md
  4. AVR128DA48-Curiosity-Nano-Hardware-User Guide
  5. AVR128DB48-Curiosity-Nano-Hardware-User Guide

2. Timer TCB0-TCB4

TCB0-TCB4 are 16-bit timers

The AVRDx boards with 14, 20, 28 or 32 pins, such as AVRDx28, will have only 3 TCB timers, (TCB0-TCB2)

The AVRDx with 48 pins, such as Curiosity Nano AVRDA48, Curiosity Nano AVRDB48, will have 4 TCB timers, (TCB0-TCB3)

The AVRDx with 64 pins, such as AVRDA64, AVRDB64, will have 5 TCB timers, (TCB0-TCB4)

The number of TCB timers will be automatically configured by the library.



Usage

Before using any Timer, you have to make sure the Timer has not been used by any other purpose.

1. Init Hardware Timer

// Select USING_FULL_CLOCK      == true for  24/16MHz to Timer TCBx => shorter timer, but better accuracy
// Select USING_HALF_CLOCK      == true for  12/ 8MHz to Timer TCBx => shorter timer, but better accuracy
// Select USING_250KHZ          == true for 250KHz to Timer TCBx => longer timer,  but worse  accuracy
// Not select for default 250KHz to Timer TCBx => longer timer,  but worse accuracy
#define USING_FULL_CLOCK      true
#define USING_HALF_CLOCK      false
#define USING_250KHZ          false         // Not supported now

#define USE_TIMER_0           false
#define USE_TIMER_1           true
#define USE_TIMER_2           false         // Normally used by millis(). Don't use
#define USE_TIMER_3           false
#define USE_TIMER_4           false

#if USE_TIMER_0
  #define CurrentTimer   ITimer0
#elif USE_TIMER_1
  #define CurrentTimer   ITimer1
#elif USE_TIMER_2
  #define CurrentTimer   ITimer2
#elif USE_TIMER_3
  #define CurrentTimer   ITimer3
#elif USE_TIMER_4
  #define CurrentTimer   ITimer4
#else
  #error You must select one Timer  
#endif

// Init Dx_Slow_PWM, each can service 64 different ISR-based PWM channels
Dx_Slow_PWM ISR_PWM;

2. Set PWM Frequency, dutycycle, attach irqCallbackStartFunc and irqCallbackStopFunc functions

void irqCallbackStartFunc()
{

}

void irqCallbackStopFunc()
{

}

void setup()
{
  ....
  
  // You can use this with PWM_Freq in Hz
  ISR_PWM.setPWM(PWM_Pin, PWM_Freq, PWM_DutyCycle, irqCallbackStartFunc, irqCallbackStopFunc);
                   
  ....                 
}  


Examples:

  1. ISR_8_PWMs_Array
  2. ISR_8_PWMs_Array_Complex
  3. ISR_8_PWMs_Array_Simple
  4. ISR_Changing_PWM
  5. ISR_Modify_PWM
  6. multiFileProject New


// Important Note: To use drag-and-drop into CURIOSITY virtual drive if you can program via Arduino IDE
// For example, check https://ww1.microchip.com/downloads/en/DeviceDoc/AVR128DB48-Curiosity-Nano-HW-UserG-DS50003037A.pdf
#if !defined(DXCORE)
#error This is designed only for DXCORE megaAVR board! Please check your Tools->Board setting
#endif
// These define's must be placed at the beginning before #include "Dx_Slow_PWM.h"
// _PWM_LOGLEVEL_ from 0 to 4
// Don't define _PWM_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define _PWM_LOGLEVEL_ 1
#if defined(__AVR_AVR128DA48__)
#define SerialDebug Serial1
#elif defined(__AVR_AVR128DB48__)
#define SerialDebug Serial3
#else
// standard Serial
#define SerialDebug Serial
#endif
#define PWM_GENERIC_DEBUG_PORT SerialDebug
// Be careful when using MAX_NUMBER_CHANNELS > 16. Max pemissible MAX_NUMBER_CHANNELS is 64
#define MAX_NUMBER_CHANNELS 16
// Select USING_FULL_CLOCK == true for 24/16MHz to Timer TCBx => shorter timer, but better accuracy
// Select USING_HALF_CLOCK == true for 12/ 8MHz to Timer TCBx => shorter timer, but better accuracy
// Select USING_250KHZ == true for 250KHz to Timer TCBx => longer timer, but worse accuracy
// Not select for default 250KHz to Timer TCBx => longer timer, but worse accuracy
#define USING_FULL_CLOCK true
#define USING_HALF_CLOCK false
#define USING_250KHZ false // Not supported now
#define USE_TIMER_0 false // Used by core. Don't use
#define USE_TIMER_1 true
#define USE_TIMER_2 false // Normally used by millis(). Don't use
#define USE_TIMER_3 false
#define USE_TIMER_4 false
#if USE_TIMER_0
#define CurrentTimer ITimer0
#elif USE_TIMER_1
#define CurrentTimer ITimer1
#elif USE_TIMER_2
#define CurrentTimer ITimer2
#elif USE_TIMER_3
#define CurrentTimer ITimer3
#elif USE_TIMER_4
#define CurrentTimer ITimer4
#else
#error You must select one Timer
#endif
#define USING_MICROS_RESOLUTION true //false
// To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error
#include "Dx_Slow_PWM.h"
#include <SimpleTimer.h> // https://github.com/jfturcot/SimpleTimer
#define LED_OFF HIGH
#define LED_ON LOW
#ifdef LED_BUILTIN
#undef LED_BUILTIN
// To modify according to your board
// For Curiosity Nano AVR128DA48 => PIN_PC6
// For Curiosity Nano AVR128DB48 => PIN_PB3
#if defined(__AVR_AVR128DA48__)
#define LED_BUILTIN PIN_PC6 // PIN_PB3, 13
#elif defined(__AVR_AVR128DB48__)
#define LED_BUILTIN PIN_PB3 // PIN_PC6, 13
#else
// standard Arduino pin 13
#define LED_BUILTIN 13
#endif
#endif
#if defined(__AVR_AVR128DA48__)
#define SerialDebug Serial1
#elif defined(__AVR_AVR128DB48__)
#define SerialDebug Serial3
#else
// standard Serial
#define SerialDebug Serial
#endif
#define USING_HW_TIMER_INTERVAL_MS false //true
// Don't change these numbers to make higher Timer freq. System can hang
#define HW_TIMER_INTERVAL_MS 0.0333f
#define HW_TIMER_INTERVAL_FREQ 30000L
volatile uint32_t startMicros = 0;
// Init DX_SLOW_PWM, each can service max 48 different ISR-based PWM channels
DX_SLOW_PWM_ISR ISR_PWM;
//////////////////////////////////////////////////////
void TimerHandler()
{
ISR_PWM.run();
}
/////////////////////////////////////////////////
#define PIN_D0 0
#define PIN_D1 1
#define PIN_D2 2
#define PIN_D3 3
#define PIN_D4 4
#define PIN_D5 5
#define PIN_D6 6
// You can assign pins here. Be careful to select good pin to use or crash, e.g pin 6-11
uint32_t PWM_Pin[] =
{
LED_BUILTIN, PIN_D0, PIN_D1, PIN_D2, PIN_D3, PIN_D4, PIN_D5, PIN_D6
};
#define NUMBER_ISR_PWMS ( sizeof(PWM_Pin) / sizeof(uint32_t) )
typedef void (*irqCallback) ();
//////////////////////////////////////////////////////
#define USE_COMPLEX_STRUCT true
//////////////////////////////////////////////////////
#if USE_COMPLEX_STRUCT
typedef struct
{
uint32_t PWM_Pin;
irqCallback irqCallbackStartFunc;
irqCallback irqCallbackStopFunc;
uint32_t PWM_Freq;
uint32_t PWM_DutyCycle;
uint32_t deltaMicrosStart;
uint32_t previousMicrosStart;
uint32_t deltaMicrosStop;
uint32_t previousMicrosStop;
} ISR_PWM_Data;
// In AVRDx, avoid doing something fancy in ISR, for example SerialDebug.print()
// The pure simple SerialDebug.prints here are just for demonstration and testing. Must be eliminate in working environment
// Or you can get this run-time error / crash
void doingSomethingStart(int index);
void doingSomethingStop(int index);
#else // #if USE_COMPLEX_STRUCT
volatile unsigned long deltaMicrosStart [] = { 0, 0, 0, 0, 0, 0, 0, 0 };
volatile unsigned long previousMicrosStart [] = { 0, 0, 0, 0, 0, 0, 0, 0 };
volatile unsigned long deltaMicrosStop [] = { 0, 0, 0, 0, 0, 0, 0, 0 };
volatile unsigned long previousMicrosStop [] = { 0, 0, 0, 0, 0, 0, 0, 0 };
// You can assign any interval for any timer here, in Microseconds
uint32_t PWM_Period[] =
{
1000L, 500L, 333L, 250L, 200L, 166L, 142L, 125L
};
// You can assign any interval for any timer here, in Hz
float PWM_Freq[] =
{
1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f,
};
// You can assign any interval for any timer here, in Microseconds
float PWM_DutyCycle[] =
{
5.0, 10.0, 20.0, 30.0, 40.0, 45.0, 50.0, 55.0
};
void doingSomethingStart(int index)
{
unsigned long currentMicros = micros();
deltaMicrosStart[index] = currentMicros - previousMicrosStart[index];
previousMicrosStart[index] = currentMicros;
}
void doingSomethingStop(int index)
{
unsigned long currentMicros = micros();
// Count from start to stop PWM pulse
deltaMicrosStop[index] = currentMicros - previousMicrosStart[index];
previousMicrosStop[index] = currentMicros;
}
#endif // #if USE_COMPLEX_STRUCT
////////////////////////////////////
// Shared
////////////////////////////////////
void doingSomethingStart0()
{
doingSomethingStart(0);
}
void doingSomethingStart1()
{
doingSomethingStart(1);
}
void doingSomethingStart2()
{
doingSomethingStart(2);
}
void doingSomethingStart3()
{
doingSomethingStart(3);
}
void doingSomethingStart4()
{
doingSomethingStart(4);
}
void doingSomethingStart5()
{
doingSomethingStart(5);
}
void doingSomethingStart6()
{
doingSomethingStart(6);
}
void doingSomethingStart7()
{
doingSomethingStart(7);
}
//////////////////////////////////////////////////////
void doingSomethingStop0()
{
doingSomethingStop(0);
}
void doingSomethingStop1()
{
doingSomethingStop(1);
}
void doingSomethingStop2()
{
doingSomethingStop(2);
}
void doingSomethingStop3()
{
doingSomethingStop(3);
}
void doingSomethingStop4()
{
doingSomethingStop(4);
}
void doingSomethingStop5()
{
doingSomethingStop(5);
}
void doingSomethingStop6()
{
doingSomethingStop(6);
}
void doingSomethingStop7()
{
doingSomethingStop(7);
}
//////////////////////////////////////////////////////
#if USE_COMPLEX_STRUCT
ISR_PWM_Data curISR_PWM_Data[] =
{
// pin, irqCallbackStartFunc, irqCallbackStopFunc, PWM_Freq, PWM_DutyCycle, deltaMicrosStart, previousMicrosStart, deltaMicrosStop, previousMicrosStop
{ LED_BUILTIN, doingSomethingStart0, doingSomethingStop0, 1, 5, 0, 0, 0, 0 },
{ PIN_D0, doingSomethingStart1, doingSomethingStop1, 2, 10, 0, 0, 0, 0 },
{ PIN_D1, doingSomethingStart2, doingSomethingStop2, 3, 20, 0, 0, 0, 0 },
{ PIN_D2, doingSomethingStart3, doingSomethingStop3, 4, 30, 0, 0, 0, 0 },
{ PIN_D3, doingSomethingStart4, doingSomethingStop4, 5, 40, 0, 0, 0, 0 },
{ PIN_D4, doingSomethingStart5, doingSomethingStop5, 6, 45, 0, 0, 0, 0 },
{ PIN_D5, doingSomethingStart6, doingSomethingStop6, 7, 50, 0, 0, 0, 0 },
{ PIN_D6, doingSomethingStart7, doingSomethingStop7, 8, 55, 0, 0, 0, 0 },
};
void doingSomethingStart(int index)
{
unsigned long currentMicros = micros();
curISR_PWM_Data[index].deltaMicrosStart = currentMicros - curISR_PWM_Data[index].previousMicrosStart;
curISR_PWM_Data[index].previousMicrosStart = currentMicros;
}
void doingSomethingStop(int index)
{
unsigned long currentMicros = micros();
//curISR_PWM_Data[index].deltaMicrosStop = currentMicros - curISR_PWM_Data[index].previousMicrosStop;
// Count from start to stop PWM pulse
curISR_PWM_Data[index].deltaMicrosStop = currentMicros - curISR_PWM_Data[index].previousMicrosStart;
curISR_PWM_Data[index].previousMicrosStop = currentMicros;
}
#else // #if USE_COMPLEX_STRUCT
irqCallback irqCallbackStartFunc[] =
{
doingSomethingStart0, doingSomethingStart1, doingSomethingStart2, doingSomethingStart3,
doingSomethingStart4, doingSomethingStart5, doingSomethingStart6, doingSomethingStart7
};
irqCallback irqCallbackStopFunc[] =
{
doingSomethingStop0, doingSomethingStop1, doingSomethingStop2, doingSomethingStop3,
doingSomethingStop4, doingSomethingStop5, doingSomethingStop6, doingSomethingStop7
};
#endif // #if USE_COMPLEX_STRUCT
//////////////////////////////////////////////////////
#define SIMPLE_TIMER_MS 2000L
// Init SimpleTimer
SimpleTimer simpleTimer;
// Here is software Timer, you can do somewhat fancy stuffs without many issues.
// But always avoid
// 1. Long delay() it just doing nothing and pain-without-gain wasting CPU power.Plan and design your code / strategy ahead
// 2. Very long "do", "while", "for" loops without predetermined exit time.
void simpleTimerDoingSomething2s()
{
static unsigned long previousMicrosStart = startMicros;
unsigned long currMicros = micros();
SerialDebug.print(F("SimpleTimer (us): "));
SerialDebug.print(SIMPLE_TIMER_MS);
SerialDebug.print(F(", us : "));
SerialDebug.print(currMicros);
SerialDebug.print(F(", Dus : "));
SerialDebug.println(currMicros - previousMicrosStart);
for (uint16_t i = 0; i < NUMBER_ISR_PWMS; i++)
{
#if USE_COMPLEX_STRUCT
SerialDebug.print(F("PWM Channel : "));
SerialDebug.print(i);
SerialDebug.print(F(", prog Period (ms): "));
SerialDebug.print(1000.f / curISR_PWM_Data[i].PWM_Freq);
SerialDebug.print(F(", actual : "));
SerialDebug.print((uint32_t) curISR_PWM_Data[i].deltaMicrosStart);
SerialDebug.print(F(", prog DutyCycle : "));
SerialDebug.print(curISR_PWM_Data[i].PWM_DutyCycle);
SerialDebug.print(F(", actual : "));
SerialDebug.println((float) curISR_PWM_Data[i].deltaMicrosStop * 100.0f / curISR_PWM_Data[i].deltaMicrosStart);
//SerialDebug.print(F(", actual deltaMicrosStop : ")); SerialDebug.println(curISR_PWM_Data[i].deltaMicrosStop);
//SerialDebug.print(F(", actual deltaMicrosStart : ")); SerialDebug.println(curISR_PWM_Data[i].deltaMicrosStart);
#else
SerialDebug.print(F("PWM Channel : "));
SerialDebug.print(i);
SerialDebug.print(1000 / PWM_Freq[i]);
SerialDebug.print(F(", prog. Period (us): "));
SerialDebug.print(PWM_Period[i]);
SerialDebug.print(F(", actual : "));
SerialDebug.print(deltaMicrosStart[i]);
SerialDebug.print(F(", prog DutyCycle : "));
SerialDebug.print(PWM_DutyCycle[i]);
SerialDebug.print(F(", actual : "));
SerialDebug.println( (float) deltaMicrosStop[i] * 100.0f / deltaMicrosStart[i]);
//SerialDebug.print(F(", actual deltaMicrosStop : ")); SerialDebug.println(deltaMicrosStop[i]);
//SerialDebug.print(F(", actual deltaMicrosStart : ")); SerialDebug.println(deltaMicrosStart[i]);
#endif
}
previousMicrosStart = currMicros;
}
void setup()
{
SerialDebug.begin(115200);
while (!SerialDebug && millis() < 5000);
SerialDebug.print(F("\nStarting ISR_8_PWMs_Array_Complex on "));
SerialDebug.println(BOARD_NAME);
SerialDebug.println(DX_SLOW_PWM_VERSION);
SerialDebug.print(F("CPU Frequency = "));
SerialDebug.print(F_CPU / 1000000);
SerialDebug.println(F(" MHz"));
SerialDebug.print(F("Max number PWM channels = "));
SerialDebug.println(MAX_NUMBER_CHANNELS);
SerialDebug.print(F("TCB Clock Frequency = "));
#if USING_FULL_CLOCK
SerialDebug.println(F("Full clock (24/16MHz, etc) for highest accuracy"));
#elif USING_HALF_CLOCK
SerialDebug.println(F("Half clock (12/8MHz, etc.) for high accuracy"));
#else
SerialDebug.println(F("250KHz for lower accuracy but longer time"));
#endif
#if USING_HW_TIMER_INTERVAL_MS
CurrentTimer.init();
if (CurrentTimer.attachInterruptInterval(HW_TIMER_INTERVAL_MS, TimerHandler))
{
SerialDebug.print(F("Starting ITimer1 OK, micros() = "));
SerialDebug.println(micros());
}
else
SerialDebug.println(F("Can't set CurrentTimer. Select another freq. or timer"));
#else
CurrentTimer.init();
if (CurrentTimer.attachInterrupt(HW_TIMER_INTERVAL_FREQ, TimerHandler))
{
SerialDebug.print(F("Starting ITimer1 OK, micros() = "));
SerialDebug.println(micros());
}
else
SerialDebug.println(F("Can't set CurrentTimer. Select another freq. or timer"));
#endif // USING_HW_TIMER_INTERVAL_MS
startMicros = micros();
// Just to demonstrate, don't use too many ISR Timers if not absolutely necessary
// You can use up to 16 timer for each ISR_PWM
for (uint16_t i = 0; i < NUMBER_ISR_PWMS; i++)
{
#if USE_COMPLEX_STRUCT
curISR_PWM_Data[i].previousMicrosStart = startMicros;
//ISR_PWM.setInterval(curISR_PWM_Data[i].PWM_Period, curISR_PWM_Data[i].irqCallbackStartFunc);
//void setPWM(uint32_t pin, float frequency, float dutycycle
// , timer_callback_p StartCallback = nullptr, timer_callback_p StopCallback = nullptr)
// You can use this with PWM_Freq in Hz
ISR_PWM.setPWM(curISR_PWM_Data[i].PWM_Pin, curISR_PWM_Data[i].PWM_Freq, curISR_PWM_Data[i].PWM_DutyCycle,
curISR_PWM_Data[i].irqCallbackStartFunc, curISR_PWM_Data[i].irqCallbackStopFunc);
#else
previousMicrosStart[i] = micros();
// You can use this with PWM_Freq in Hz
ISR_PWM.setPWM(PWM_Pin[i], PWM_Freq[i], PWM_DutyCycle[i], irqCallbackStartFunc[i], irqCallbackStopFunc[i]);
#endif
}
// You need this timer for non-critical tasks. Avoid abusing ISR if not absolutely necessary.
simpleTimer.setInterval(SIMPLE_TIMER_MS, simpleTimerDoingSomething2s);
}
#define BLOCKING_TIME_MS 10000L
void loop()
{
// This unadvised blocking task is used to demonstrate the blocking effects onto the execution and accuracy to Software timer
// You see the time elapse of ISR_PWM still accurate, whereas very unaccurate for Software Timer
// The time elapse for 2000ms software timer now becomes 3000ms (BLOCKING_TIME_MS)
// While that of ISR_PWM is still prefect.
delay(BLOCKING_TIME_MS);
// You need this Software timer for non-critical tasks. Avoid abusing ISR if not absolutely necessary
// You don't need to and never call ISR_PWM.run() here in the loop(). It's already handled by ISR timer.
simpleTimer.run();
}



Debug Terminal Output Samples

1. ISR_8_PWMs_Array_Complex on AVR128DB

The following is the sample terminal output when running example ISR_8_PWMs_Array_Complex Curiosity Nano AVR128DB48 to demonstrate how to use multiple PWM channels with complex callback functions, the accuracy of ISR Hardware PWM-channels, especially when system is very busy. The ISR PWM-channels is running exactly according to corresponding programmed periods and duty-cycles

Starting ISR_8_PWMs_Array_Complex on AVR128DB
Dx_Slow_PWM v1.1.0
CPU Frequency = 24 MHz
TCB Clock Frequency = Full clock (24/16MHz, etc) for highest accuracy
Starting  ITimer1 OK, micros() = 13691
SimpleTimer (us): 2000, us : 10073297, Dus : 10058568
PWM Channel : 0, prog Period (ms): 1000.00, actual : 1000015, prog DutyCycle : 5, actual : 5.00
PWM Channel : 1, prog Period (ms): 500.00, actual : 500025, prog DutyCycle : 10, actual : 10.00
PWM Channel : 2, prog Period (ms): 333.33, actual : 333348, prog DutyCycle : 20, actual : 19.98
PWM Channel : 3, prog Period (ms): 250.00, actual : 250042, prog DutyCycle : 30, actual : 29.98
PWM Channel : 4, prog Period (ms): 200.00, actual : 200046, prog DutyCycle : 40, actual : 39.98
PWM Channel : 5, prog Period (ms): 166.67, actual : 166671, prog DutyCycle : 45, actual : 44.98
PWM Channel : 6, prog Period (ms): 142.86, actual : 142908, prog DutyCycle : 50, actual : 49.98
PWM Channel : 7, prog Period (ms): 125.00, actual : 125018, prog DutyCycle : 55, actual : 54.94
SimpleTimer (us): 2000, us : 20140201, Dus : 10066904
PWM Channel : 0, prog Period (ms): 1000.00, actual : 1000014, prog DutyCycle : 5, actual : 5.00
PWM Channel : 1, prog Period (ms): 500.00, actual : 500022, prog DutyCycle : 10, actual : 10.00
PWM Channel : 2, prog Period (ms): 333.33, actual : 333347, prog DutyCycle : 20, actual : 19.99
PWM Channel : 3, prog Period (ms): 250.00, actual : 250040, prog DutyCycle : 30, actual : 29.98
PWM Channel : 4, prog Period (ms): 200.00, actual : 200047, prog DutyCycle : 40, actual : 39.98
PWM Channel : 5, prog Period (ms): 166.67, actual : 166671, prog DutyCycle : 45, actual : 44.98
PWM Channel : 6, prog Period (ms): 142.86, actual : 142908, prog DutyCycle : 50, actual : 49.98
PWM Channel : 7, prog Period (ms): 125.00, actual : 125027, prog DutyCycle : 55, actual : 54.94
SimpleTimer (us): 2000, us : 30207240, Dus : 10067039
PWM Channel : 0, prog Period (ms): 1000.00, actual : 1000014, prog DutyCycle : 5, actual : 5.00
PWM Channel : 1, prog Period (ms): 500.00, actual : 500024, prog DutyCycle : 10, actual : 10.00
PWM Channel : 2, prog Period (ms): 333.33, actual : 333347, prog DutyCycle : 20, actual : 19.99
PWM Channel : 3, prog Period (ms): 250.00, actual : 250041, prog DutyCycle : 30, actual : 29.98
PWM Channel : 4, prog Period (ms): 200.00, actual : 200045, prog DutyCycle : 40, actual : 39.98
PWM Channel : 5, prog Period (ms): 166.67, actual : 166680, prog DutyCycle : 45, actual : 44.98
PWM Channel : 6, prog Period (ms): 142.86, actual : 142918, prog DutyCycle : 50, actual : 49.98
PWM Channel : 7, prog Period (ms): 125.00, actual : 125028, prog DutyCycle : 55, actual : 54.93
...

2. ISR_8_PWMs_Array on AVR128DB

The following is the sample terminal output when running example ISR_8_PWMs_Array on AVR128DB to demonstrate how to use multiple PWM channels with simple callback functions.

Starting ISR_8_PWMs_Array on AVR128DB
Dx_Slow_PWM v1.1.0
CPU Frequency = 24 MHz
TCB Clock Frequency = Full clock (24/16MHz, etc) for highest accuracy
Starting  ITimer1 OK, micros() = 12894

3. ISR_8_PWMs_Array_Simple on AVR128DB

The following is the sample terminal output when running example ISR_8_PWMs_Array_Simple on AVR128DB to demonstrate how to use multiple PWM channels.

Starting ISR_8_PWMs_Array_Simple on AVR128DB
Dx_Slow_PWM v1.1.0
CPU Frequency = 24 MHz
TCB Clock Frequency = Full clock (24/16MHz, etc) for highest accuracy
Starting  ITimer1 OK, micros() = 14169

4. ISR_Modify_PWM on AVR128DB

The following is the sample terminal output when running example ISR_Modify_PWM on AVR128DB to demonstrate how to modify PWM settings on-the-fly without deleting the PWM channel

Starting ISR_Modify_PWM on AVR128DB
Dx_Slow_PWM v1.1.0
CPU Frequency = 24 MHz
TCB Clock Frequency = Full clock (24/16MHz, etc) for highest accuracy
Starting  ITimer1 OK, micros() = 12823
Using PWM Freq = 2.00, PWM DutyCycle = 10.00

5. ISR_Changing_PWM on AVR128DB

The following is the sample terminal output when running example ISR_Changing_PWM on AVR128DB to demonstrate how to modify PWM settings on-the-fly by deleting the PWM channel and reinit the PWM channel

Starting ISR_Changing_PWM on AVR128DB
Dx_Slow_PWM v1.1.0
CPU Frequency = 24 MHz
TCB Clock Frequency = Full clock (24/16MHz, etc) for highest accuracy
Starting  ITimer1 OK, micros() = 12998
Using PWM Freq = 1.00, PWM DutyCycle = 50.00
Using PWM Freq = 2.00, PWM DutyCycle = 90.00
Using PWM Freq = 1.00, PWM DutyCycle = 50.00
Using PWM Freq = 2.00, PWM DutyCycle = 90.00


Debug

Debug is enabled by default on Serial.

You can also change the debugging level _PWM_LOGLEVEL_ from 0 to 4

// Don't define _PWM_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define _PWM_LOGLEVEL_     0

Troubleshooting

If you get compilation errors, more often than not, you may need to install a newer version of the core for Arduino boards.

Sometimes, the library will only work if you update the board core to the latest version because I am using newly added functions.



Issues

Submit issues to: Dx_Slow_PWM issues


TO DO

  1. Search for bug and improvement

DONE

  1. Basic hardware multi-channel PWM for AVRDx-based boards (AVR128Dx, AVR64Dx, AVR32Dx, etc.) using DxCore
  2. Add Table of Contents
  3. Add functions to modify PWM settings on-the-fly
  4. Fix multiple-definitions linker error
  5. Optimize library code by using reference-passing instead of value-passing
  6. Improve accuracy by using float, instead of uint32_t for dutycycle
  7. DutyCycle to be optionally updated at the end current PWM period instead of immediately.
  8. Display informational warning only when _PWM_LOGLEVEL_ > 3 9 Make MAX_NUMBER_CHANNELS configurable to max 64 PWM channels
  9. Remove debug codes possibly causing hang
  10. Improve debug to use Serialx port automatically according to boards.
  11. Add support to AVRDD (AVR64DD, AVR32DD, AVR16DD, etc.)
  12. Modify to use either breaking DxCore v1.5.1+ or v1.4.10-


Contributions and Thanks

Many thanks for everyone for bug reporting, new feature suggesting, testing and contributing to the development of this library. Especially to these people who have directly or indirectly contributed to this Dx_TimerInterrupt library

  1. Thanks to good work of Spence Konde (aka Dr. Azzy) for the DxCore and megaTinyCore
  2. Thanks to LaurentR59 to request
SpenceKonde
⭐️⭐️ Spence Konde

LaurentR59
LaurentR59


Contributing

If you want to contribute to this project:

  • Report bugs and errors
  • Ask for enhancements
  • Create issues and pull requests
  • Tell other people about this library

License

  • The library is licensed under MIT

Copyright

Copyright (c) 2022- Khoi Hoang

dx_slow_pwm's People

Contributors

khoih-prog avatar

Watchers

 avatar  avatar

dx_slow_pwm's Issues

on exemples PWM_DutyCycle[] comment typo need to set [0;99] percentage

Describe the bug

Comment is

// You can assign any interval for any timer here, in Microseconds
float PWM_DutyCycle[] =
...

May be should be described like for a defined freqency (juste before this step) set the duty cycle according to value range [0;99] (or 100)
(add comment like duty cycle manage light itensity level on an avarage Vout on the define frequzency)
adjust frequency to avoid flikering
adjust ducty cycle for intensity (Vout average)

Steps to Reproduce

N/A

Expected behavior

N/A

MAy be need to precise that some step are requird to use a channel

0 define inital settings
1/ define pin
2/ set frequency
3/ set duty cycle

Actual behavior

N/A

Debug and AT-command log (if applicable)

N/A

Screenshots

If applicable, add screenshots to help explain your problem.

Information

Example

Additional context

Hpp file line 153 TIMER should be TIMER4

Describe the bug

Hpp file line 153 TIMER should be TIMER4

Steps to Reproduce

Steps to reproduce the behavior. Including the MRE sketches

Expected behavior

need to change TIMER3 TIMER4

Actual behavior

TIMER4 defined incorreclty (define as TIMER3 again)

Debug and AT-command log (if applicable)

set TIMER4

Screenshots

N/A

Information

Please ensure to specify the following:

N/A

Additional context

N/A

PWM to drive over 16 channels

Is your feature request related to a problem? Please describe.

if the need is over driving 16 channels, it means we must to use another object for 16 additionnal channels if I m not wrong?
juste to be sure how to process on that case.

So what happen if non other hardware TIMER still available?? (usually One is for millis(), one will be for ISR_Timer interupt generating this PWM, another one can be keep for core operations (in my case NMRA DCC signal management).... so few solution available!
Worst case on megatiny CPU with less TIMER ( A0 B0 B1 only)

Describe the solution you'd like

May it would be possible to limit frequency ( ex between 50hz-120hz range and add PWM channels on the 16 ones on the initial range as a way? (may be not at all!)

Describe alternatives you've considered

using biggest hardware on the family to have enough TCB Timer ressources is the intial possibility if available!

other is to get capacity or possibility to move millis() on a TIMER A type? (not sure it would be well managed by dx core or megacorex and megatinycore?)
May require some additionnal settings according optional links between TIMER A type and B type.

using millis on same timer as the one managing PWM? (stupid way? uncompatible?)

Additional context

optimisation of selected hardware according usages needs specially for limited TIMER numbers.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.