adc early

This commit is contained in:
Christoph J. Scherr 2023-12-09 14:20:18 +01:00
parent a51532e059
commit 545af2648e
6 changed files with 47 additions and 4 deletions

View File

@ -13,7 +13,7 @@ else
-DARDUINO=10607 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR \ -DARDUINO=10607 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR \
-I/usr/avr/include \ -I/usr/avr/include \
-I/usr/lib/avr/include \ -I/usr/lib/avr/include \
../include/uart.c main.c -o $BUILD/main.elf ../include/uart.c ../include/rand.c ../include/adc.c main.c -o $BUILD/main.elf
avr-objcopy -O ihex -R .eeprom $BUILD/main.elf $BUILD/main.hex avr-objcopy -O ihex -R .eeprom $BUILD/main.elf $BUILD/main.hex

18
include/adc.c Normal file
View File

@ -0,0 +1,18 @@
#include "adc.h"
#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <util/delay.h>
void adc_init() {
//DDRA=0x0; // does not exist but is default?
ADCSRA = (1<<ADEN)|(1<<ADPS1)|(1<<ADPS2);
ADMUX = (1<<REFS0);
}
uint16_t adc_read(uint8_t channel) {
ADMUX &= 0xf0;
ADMUX |= (channel & 0x0f);
ADCSRA |= (1<<ADSC);
while((ADCSRA&(1<<ADIF))==0);
return ADCL + (ADCH << 8);
}

6
include/adc.h Normal file
View File

@ -0,0 +1,6 @@
#pragma once
#define F_CPU 16000000UL
#define __AVR_ATmega328P__
#include <stdio.h>
void adc_init();
uint16_t adc_read(uint8_t channel);

13
include/rand.c Normal file
View File

@ -0,0 +1,13 @@
int rand() {
static unsigned int seed = 1337191337;
unsigned int buf[] = {
(seed*31832)%677,
(seed*32932)%2332
};
seed = buf[1]*223238;
seed *= seed << 4;
seed %= 410829;
seed = buf[0] * 1892823 % 23891;
seed = buf[0];
return seed;
}

2
include/rand.h Normal file
View File

@ -0,0 +1,2 @@
#pragma once
unsigned int rand(void);

View File

@ -4,6 +4,8 @@
#include <avr/io.h> #include <avr/io.h>
#include <util/delay.h> #include <util/delay.h>
#include "../include/uart.h" #include "../include/uart.h"
#include "../include/adc.h"
#include "../include/rand.h"
#define BAUD 9600 #define BAUD 9600
#define MYUBRR F_CPU/16/BAUD-1 #define MYUBRR F_CPU/16/BAUD-1
@ -15,14 +17,16 @@ int main (void)
sei(); sei();
char buf[10]; char buf[10];
int sensor; int sensor[2];
while (1) while (1)
{ {
// lets say we read some value from a sensor // lets say we read some value from a sensor
sensor = 65; sensor[0] = adc_read(0);
sensor[1] = adc_read(1);
// we want to print this, so we store the ascii repr in our buffer // we want to print this, so we store the ascii repr in our buffer
uart_printi("sensor status: ", sensor); uart_printi("sensor 0: ", sensor[0]);
uart_printi("sensor 1: ", sensor[1]);
_delay_ms(1000); _delay_ms(1000);
} }
} }