-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathFastPwmPin.h
More file actions
57 lines (49 loc) · 2.37 KB
/
FastPwmPin.h
File metadata and controls
57 lines (49 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#ifndef __FASTPWMPIN_H__
#define __FASTPWMPIN_H__
#include <Arduino.h>
// For the blink example its nice to have LED_BUILTIN defined, also for ATtiny13 and ATtiny85.
// Depending on the core ATtiny44A may already have LED_BUILTIN as 8.
#ifndef LED_BUILTIN
#if defined(__AVR_ATtiny85__) || defined(__AVR_ATtiny13__) || defined(__AVR_ATtiny44__)
#define LED_BUILTIN 2
#endif
#endif
#define FASTPWMPIN_TOGGLE 50
// macro used for disabling PWM on a pin. Resets the specified bit of the specific register
#if !defined(cbi)
#define cbi(reg,bit) (reg &= ~(_BV(bit)))
#endif
class FastPwmPin
{
public:
FastPwmPin() {}; // constructor
/** Enable fast PWM on the preferred pin. Try to set frequency and period as close as possible
* @arg const int nPreferredPin - the preferred pin to be used (returns -1 if not available for PWM)
* @arg unsigned long ulFrequency - e.g. 250000L for 250 kHz
* @arg uint8_t nPeriodPercentage - 1-99 percentage of dutycycle. Default is 50%
*/
static int enablePwmPin(const int nPreferredPin=0, unsigned long ulFrequency=0L, uint8_t nPeriodPercentage=FASTPWMPIN_TOGGLE);
/** Disable PWM on the indicated pin. Should be a previously enabled pin
* @arg const int nPin - the pin for PWM to be disabled
* @arg uint8_t nPinState - state of pin after disabling. Default is LOW.
*/
static void disablePwmPin(const int nPin, uint8_t nPinState=LOW);
private:
static uint8_t findPrescaler(unsigned long ulFrequency, uint8_t nTimer=0);
static const uint16_t aPrescale1[]; // Set of prescalar values
#if !defined(__AVR_ATtiny13__) && !defined(__AVR_ATtiny85__) && !defined(__AVR_ATtiny45__) && !defined(__AVR_ATtiny25__)
static const uint16_t aPrescale2[]; // Extended set of prescalar values
#endif
};
#if (defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__))
// ATTiny24A/44A/84A uses Timer0 for Fast PWM on pins 7 and 8. This impacts delay() and millis().
// To mitigate that, the watchdog timer can be used to replace the original delay() and millis().
#define TINYX4_ENABLE_WDTMILLIS 1
#endif
#if defined(TINYX4_ENABLE_WDTMILLIS)
uint32_t wdt_millis();
void wdt_delay(uint16_t ms);
//#define delay(x) wdt_delay(x)
//#define millis(x) wdt_millis(x)
#endif // TINYX4_ENABLE_WDTMILLIS
#endif //__FASTPWMPIN_H__