@@ -27,11 +27,12 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2727/* Standard Arduino PWM resolution */
2828static int _writeResolution = 8 ;
2929static int _readResolution = 10 ;
30-
30+ uint32_t maxResolutionValue = 0xFF ;
3131
3232void analogWriteResolution (int res )
3333{
3434 _writeResolution = res ;
35+ maxResolutionValue = 0xFFFFFFFF >> (32 - res );
3536}
3637
3738void analogReadResolution (int res )
@@ -49,7 +50,7 @@ static inline uint32_t mapResolution(uint32_t value, uint32_t from, uint32_t to)
4950 return value << (to - from );
5051}
5152
52- void analogWrite (uint8_t pin , int val )
53+ void analogWrite (uint8_t pin , uint32_t val )
5354{
5455 if (! digitalPinHasPWM (pin ))
5556 {
@@ -75,20 +76,12 @@ void analogWrite(uint8_t pin, int val)
7576 } else {
7677 /* PWM for everything in between */
7778 PinDescription * p = & g_APinDescription [pin ];
78- uint32_t hcnt = mapResolution (val , _writeResolution , PWM_RESOLUTION );
79- uint32_t lcnt = PWM_MAX_DUTY_CYCLE - hcnt ;
80- uint32_t offset ;
81-
82- /* For Arduino Uno compatibilty, we scale up frequency on certain pins */
83- hcnt >>= p -> ulPwmScale ;
84- lcnt >>= p -> ulPwmScale ;
85-
86- /* Each count must be > 0 */
87- if (hcnt < PWM_MIN_DUTY_CYCLE )
88- hcnt = PWM_MIN_DUTY_CYCLE ;
89- if (lcnt < PWM_MIN_DUTY_CYCLE )
90- lcnt = PWM_MIN_DUTY_CYCLE ;
9179
80+ uint32_t offset ;
81+
82+ uint32_t hcnt = (val /(float )maxResolutionValue ) * pwmPeriod [p -> ulPwmChan ];
83+ uint32_t lcnt = pwmPeriod [p -> ulPwmChan ] - hcnt ;
84+
9285 /* Set the high count period (duty cycle) */
9386 offset = ((p -> ulPwmChan * QRK_PWM_N_LCNT2_LEN ) + QRK_PWM_N_LOAD_COUNT2 );
9487 MMIO_REG_VAL (QRK_PWM_BASE_ADDR + offset ) = hcnt ;
@@ -139,6 +132,13 @@ uint32_t analogRead(uint32_t pin)
139132
140133}
141134
135+ void analogWriteFrequency (uint8_t pin , uint32_t freq )
136+ {
137+ //convert frequency to period in clock ticks
138+ PinDescription * p = & g_APinDescription [pin ];
139+ pwmPeriod [p -> ulPwmChan ] = F_CPU / freq ;
140+ }
141+
142142#ifdef __cplusplus
143143}
144144#endif
0 commit comments