130 lines
2.3 KiB
C
130 lines
2.3 KiB
C
#ifndef _PWM_H
|
|
#define _PWM_H
|
|
|
|
#include <avr/io.h>
|
|
#include <util/delay.h>
|
|
|
|
static inline void hbridge_init(void) {
|
|
DDRB |= (1 << PB2); // PWM
|
|
DDRB |= (1 << PB0) | (1 << PB1); // H1 L1
|
|
DDRB |= (1 << PB3) | (1 << PB4); // H2 L2
|
|
}
|
|
|
|
|
|
static inline void hbridge_set_h1(void) {
|
|
PORTB |= (1 << PB0);
|
|
}
|
|
static inline void hbridge_unset_h1(void) {
|
|
PORTB &= ~(1 << PB0);
|
|
}
|
|
|
|
static inline void hbridge_set_l1(void) {
|
|
PORTB |= (1 << PB1);
|
|
}
|
|
static inline void hbridge_unset_l1(void) {
|
|
PORTB &= ~(1 << PB1);
|
|
}
|
|
|
|
static inline void hbridge_set_h2(void) {
|
|
PORTB |= (1 << PB3);
|
|
}
|
|
static inline void hbridge_unset_h2(void) {
|
|
PORTB &= ~(1 << PB3);
|
|
}
|
|
|
|
static inline void hbridge_set_l2(void) {
|
|
PORTB |= (1 << PB4);
|
|
}
|
|
static inline void hbridge_unset_l2(void) {
|
|
PORTB &= ~(1 << PB4);
|
|
}
|
|
|
|
const double delay_time = 0.25;
|
|
|
|
static inline void pwm_delay(uint16_t slices) {
|
|
for(uint16_t i = 0; i < slices; i++) {
|
|
//Anything smaller here will lead to messed up timings
|
|
_delay_us(10);
|
|
}
|
|
}
|
|
|
|
static inline void pwm_cycle_backwards(uint8_t speed) {
|
|
uint16_t on_time = speed;
|
|
//Always have a a least on slice of off time to charge the bootstrap cap
|
|
uint16_t off_time = 256 - on_time;
|
|
|
|
if(on_time > 0) {
|
|
hbridge_unset_h1();
|
|
hbridge_set_h2();
|
|
hbridge_set_l1();
|
|
hbridge_unset_l2();
|
|
|
|
pwm_delay(on_time);
|
|
}
|
|
|
|
|
|
hbridge_unset_h1();
|
|
hbridge_unset_h2();
|
|
hbridge_unset_l1();
|
|
hbridge_set_l2();
|
|
|
|
pwm_delay(off_time);
|
|
|
|
hbridge_unset_h1();
|
|
hbridge_unset_h2();
|
|
hbridge_unset_l1();
|
|
hbridge_unset_l2();
|
|
}
|
|
|
|
|
|
static inline void pwm_cycle_forwards(uint8_t speed) {
|
|
uint16_t on_time = speed;
|
|
//Always have a a least on slice of off time to charge the bootstrap cap
|
|
uint16_t off_time = 256 - on_time;
|
|
|
|
if(on_time > 0) {
|
|
hbridge_set_h1();
|
|
hbridge_unset_h2();
|
|
hbridge_unset_l1();
|
|
hbridge_set_l2();
|
|
|
|
pwm_delay(on_time);
|
|
}
|
|
|
|
|
|
hbridge_unset_h1();
|
|
hbridge_unset_h2();
|
|
hbridge_set_l1();
|
|
hbridge_unset_l2();
|
|
|
|
pwm_delay(off_time);
|
|
|
|
hbridge_unset_h1();
|
|
hbridge_unset_h2();
|
|
hbridge_unset_l1();
|
|
hbridge_unset_l2();
|
|
}
|
|
|
|
static inline void pwm_cycle_break() {
|
|
hbridge_unset_h1();
|
|
hbridge_unset_h2();
|
|
hbridge_set_l1();
|
|
hbridge_unset_l2();
|
|
|
|
pwm_delay(128);
|
|
|
|
hbridge_unset_h1();
|
|
hbridge_unset_h2();
|
|
hbridge_unset_l1();
|
|
hbridge_set_l2();
|
|
|
|
pwm_delay(128);
|
|
|
|
hbridge_unset_h1();
|
|
hbridge_unset_h2();
|
|
hbridge_unset_l1();
|
|
hbridge_unset_l2();
|
|
}
|
|
|
|
#endif
|