Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <avr/io.h>
- #include <avr/interrupt.h>
- #include <avr/pgmspace.h>
- // #include <avr/eeprom.h>
- #include <util/delay.h>
- #include <stdlib.h>
- #include <string.h>
- #include <math.h>
- #include "lcd.h"
- // #include "spi.h"
- #define clockCyclesToMicroseconds(a) (((a) * 1000L)/(F_CPU / 1000L))
- #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
- #define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
- #define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000)>>3)
- #define FRACT_MAX (1000>>3)
- volatile float value = .0, rev = .0, last = .0;
- volatile uint16_t rpm = 0, count = 0;
- volatile uint16_t oldTime = 0, time = 0;
- volatile uint8_t counter = 0;
- volatile unsigned long int timer0_overflowCount = 0;
- volatile unsigned long int timer0_millis = 0;
- static unsigned char timer0_fract = 0;
- unsigned long int starttime = 0, endtime = 0;
- unsigned long int millis() {
- unsigned long int m = 0;
- uint8_t oldSREG = SREG;
- // Disable interrupts while we read timer0_millis or we might get an
- // Inconsistent value (e.g. in the middle of a write to timer0_millis)
- cli();
- m = timer0_millis;
- SREG = oldSREG;
- return m;
- }
- int main() {
- // VSS signal, injector signal and navigation buttons - Atmega 8
- DDRD &= ~((1<<PD3) | (1<<PD2)); // PD2/INT0 and PD3/INT1 input
- PORTD |= ((1<<PD3) | (1<<PD2)); // PD2/INT0 and PD3/INT1 internal pull-up resistor
- MCUCR |= ((1<<ISC01) | (1<<ISC00)); // RISING edge of INT0 generates interrupt
- GICR |= (1<<INT0);
- // 16 bit timer for VSS
- TCCR1A = 0; // Timer1 normal mode
- TCCR1B |= ((1<<CS10) | (1<<CS11)); // Prescaler 64, causes overflow every 0.524288 (8 MHz crystal, 0.262144s for 16 MHz)
- TCNT1 = 34286; // Counts from 34286 to 65535 - causes overflow every 0.25s (8 MHz crystal, 3036 for 16 MHz)
- // Counter for millis() function
- TCCR0 |= ((1<<CS01) | (1<<CS00)); // Prescaler 64
- TCNT0 = 0; // Counts from 0 to 255;
- // Enable timer overflow interrupt
- TIMSK = ((1<<TOIE1) | (1<<TOIE0));
- char buffer[16];
- LCD.init();
- sei(); // Enable global interrupts
- while(1) {
- LCD.cursor(1, 1);
- LCD.sends("RPM: ", 1); LCD.sends(itoa(rpm, buffer, 10), 1);
- LCD.render();
- LCD.clear();
- } return 0;
- }
- ISR(TIMER0_OVF_vect) {
- unsigned long int m = timer0_millis;
- unsigned char f = timer0_fract;
- m += MILLIS_INC;
- f += FRACT_INC;
- if(f >= FRACT_MAX) {
- f -= FRACT_MAX;
- m += 1;
- }
- timer0_fract = f;
- timer0_millis = m;
- timer0_overflowCount++;
- }
- ISR(TIMER1_OVF_vect) {
- counter++;
- if(counter > 3) {
- cli();
- time = millis()-oldTime;
- rpm = (rev/time)*60000;
- oldTime = millis();
- rev = 0;
- sei();
- } TCNT1 = 34286;
- last = rev;
- }
- // Hall signal interrupt
- ISR(INT0_vect) {
- rev++;
- count++;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement