added adc example

This commit is contained in:
Sven Vogel 2023-12-09 14:59:12 +01:00
parent 8ce9c0f3d5
commit 4e1a92b1ff
5 changed files with 69 additions and 3 deletions

View File

@ -14,7 +14,7 @@ void uart_init(uint16_t baud);
uint8_t uart_read(); uint8_t uart_read();
void uart_read(uint8_t* buffer, size_t size); void uart_read_bytes(uint8_t* buffer, size_t size);
void uart_write(uint8_t frame); void uart_write(uint8_t frame);

View File

@ -14,6 +14,7 @@ board = nanoatmega328
framework = arduino framework = arduino
build_src_filter = build_src_filter =
+<*> +<*>
+*.c
-<.git/> -<.git/>
-<.svn/> -<.svn/>
-<blink/> -<blink/>
@ -22,4 +23,5 @@ build_src_filter =
-<trafficlight/> -<trafficlight/>
-<summer/> -<summer/>
-<summer_controlled/> -<summer_controlled/>
+<uart/> -<uart/>
+<adc/>

50
src/adc/adc.cpp Normal file
View File

@ -0,0 +1,50 @@
//
// Created by servostar on 09.12.23.
//
#include "adc.h"
#include <stdlib.h>
void adc_init() {
DDRC = 0x0;
SET_BIT(ADCSRA, ADEN); // enable ADC
// set prescaler / precision for conversion
SET_BIT(ADCSRA, ADPS0);
SET_BIT(ADCSRA, ADPS1);
SET_BIT(ADCSRA, ADPS2);
// set reference voltage
SET_BIT(ADMUX, REFS0);
}
uint16_t adc_read(uint8_t channel) {
ADMUX &= 0xF0;
ADMUX |= (channel & 0xF0);
// trigger adc conversion
ADCSRA |= (1 << ADSC);
// wait until converted
while((ADCSRA & (1 << ADIF)) == 0);
return ADCL + (ADCH << 8);
}
static uint16_t recent_adc = 0;
void init() {
uart_init(9600);
adc_init();
}
void loop() {
uint16_t adc_val = adc_read(0);
char buf[10] = { 0 };
itoa(adc_val, buf, 10);
if (recent_adc != adc_val) {
recent_adc = adc_val;
uart_write_string("Channel 0: ");
uart_write_string(buf);
uart_write_string("\n");
}
}

13
src/adc/adc.h Normal file
View File

@ -0,0 +1,13 @@
//
// Created by servostar on 09.12.23.
//
#ifndef ARDUINO_ADC_H
#define ARDUINO_ADC_H
#include "prelude.h"
void init();
void loop();
#endif //ARDUINO_ADC_H

View File

@ -8,7 +8,8 @@ extern void loop();
//#include "trafficlight/trafficlight.h" //#include "trafficlight/trafficlight.h"
//#include "summer/summer.h" //#include "summer/summer.h"
//#include "summer_controlled/summer.h" //#include "summer_controlled/summer.h"
#include "uart/uart_read_write.h" //#include "uart/uart_read_write.h"
#include "adc/adc.h"
int main() { int main() {
init(); init();