Subversion Repositories group.electronics

Rev

Blame | Last modification | View Log | RSS feed

#include <avr/io.h>

#include "util.h"
#include <util/delay.h>

#include <stdlib.h>

inline uint8_t map_8(uint8_t x, uint8_t in_min, uint8_t in_max, uint8_t out_min, uint8_t out_max) {
        return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

uint8_t analogRead(uint8_t channel) {
        ADMUX = (1<<ADLAR) | (1<<REFS0) | (0<<REFS1) | (channel & 0x0f);
        ADCSRA |= (1<<ADSC);            // Start converting

        while (((ADCSRA >> ADSC) & 1)) {}       //Wait until conversion finished
        uint8_t result = ADCH;
        //ADCSRA |= (0<<ADSC);          // Stop converting

        return result;
}

void analogInit() {
        ACSR |= (1<<ACD); // Disable analog comparator

        /*
        Setup ADC
        ADMUX: 8 bit mode, Avcc ref
        ADCSRA: Enable, 128 prescale
        */
        ADMUX = (1<<ADLAR) | (0<<REFS0) | (1<<REFS1);
        ADCSRA = (1<<ADEN) | (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0) ;
}