2 * Copyright Droids Corporation, Microb Technology, Eirbot (2005)
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 * Copyright Droids-corporation - Olivier MATZ - 2009
23 #include <aversive/parts.h>
24 #include <aversive/timers.h>
28 /* value to be used for limiting inputs */
29 #define PWM_SIGNIFICANT_BITS 12
30 #define PWM_MAX ((1<< PWM_SIGNIFICANT_BITS)-1)
31 #define PWM_MIN (-PWM_MAX)
33 #define PWM_NG_TYPE_8 0
34 #define PWM_NG_TYPE_16 1
36 #define PWM_NG_NBITS_8 0
37 #define PWM_NG_NBITS_9 1
38 #define PWM_NG_NBITS_10 2
40 void pwm_ng_init(struct pwm_ng *pwm, uint8_t timer_nbits,
41 uint8_t pwm_nbits, uint8_t pwm_mode,
43 uint8_t com0, volatile uint8_t *tccrn,
44 volatile uint8_t *pwm_port, uint8_t pwm_bit,
45 volatile uint8_t *sign_port, uint8_t sign_bit)
47 memset(pwm, 0, sizeof(*pwm));
49 if (timer_nbits == 8) {
50 pwm->type = PWM_NG_TYPE_8;
55 pwm->type = PWM_NG_TYPE_16;
61 pwm->nbits = PWM_NG_NBITS_9;
64 pwm->nbits = PWM_NG_NBITS_10;
68 pwm->nbits = PWM_NG_NBITS_8;
73 *tccrn &= ~(0x03 << com0);
74 if (pwm_mode & PWM_NG_MODE_REVERSE)
75 *tccrn |= (0x01 << com0);
77 *tccrn |= (0x02 << com0);
79 DDR(*pwm_port) |= (1 << pwm_bit);
81 if ((pwm_mode & PWM_NG_MODE_SIGNED) && (sign_port))
82 DDR(*sign_port) |= (1 << sign_bit);
83 pwm->sign_port = sign_port;
84 pwm->sign_bit = sign_bit;
87 static inline void pwm_sign_set(struct pwm_ng *pwm)
89 if (pwm->mode & PWM_NG_MODE_SIGN_INVERTED)
90 *pwm->sign_port &= ~(1 << pwm->sign_bit);
92 *pwm->sign_port |= (1 << pwm->sign_bit);
95 static inline void pwm_sign_reset(struct pwm_ng *pwm)
97 if (pwm->mode &PWM_NG_MODE_SIGN_INVERTED)
98 *pwm->sign_port |= (1 << pwm->sign_bit);
100 *pwm->sign_port &= ~(1 << pwm->sign_bit);
103 static inline int32_t pwm_invert_value(struct pwm_ng *pwm, int32_t value)
105 if (pwm->mode & PWM_NG_MODE_SPECIAL_SIGN)
106 return value & PWM_MAX;
112 void pwm_ng_set(void *data, int32_t value)
114 struct pwm_ng *pwm = data;
115 uint8_t nbits = 8 + pwm->nbits;
118 if (pwm->mode & PWM_NG_MODE_SIGNED) {
122 value = pwm_invert_value(pwm, value);
131 if (pwm->type == PWM_NG_TYPE_8)
132 *pwm->u.ocr8 = (uint8_t) (value >> (PWM_SIGNIFICANT_BITS - 8));
134 *pwm->u.ocr16 = (value >> (PWM_SIGNIFICANT_BITS - nbits));