with timer1 as fixed sample rate of 1ms

This commit is contained in:
Jonathan Wyss 2024-03-01 20:34:42 +01:00
parent 4b8c5a46e9
commit a412db2b88

53
main.c
View File

@ -9,7 +9,7 @@
#define STARTADC ADCSRA |= (1<<ADSC)
#define PB_mic PB0
#define NOISE 100
#define SCALE_FACTOR 8
#define SCALE_FACTOR 10
//resolution fft calc:
//https://3roam.com/fft-resolution-bandwidth-calculator/
//128 samples , 1kSPS = 7.8Hz
@ -31,6 +31,7 @@
//
const float log_scale = 64./log(64./SCALE_FACTOR + 1.);
int msec;
int main (void)
{
int i,i2;
@ -41,9 +42,12 @@ int main (void)
char im[64];
char buff[64];
char temp;
msec=0;
struct cRGB led_bar1[8];
//DDRB = (1<<mic);//would be setting output, default is input so no need for setting
setupADC();
setupTimer();
OSCCAL = 240;//overclock!!! to 30MHz
for(i=0;i<8;i++)
{
@ -55,19 +59,23 @@ int main (void)
{
buff[i]=0;
}
sei();
while(1)
{
//######RECORD SAMPLES######
sum = 0;
for(i=0;i<64;i++)
{
msec=0;
STARTADC;
sample[i] = (ADCH-128); //read Analog value register 8bit center -128
//sample[i] = (sample[i] <= NOISE) ? 0 : (sample[i] - NOISE); //noise reduction
im[i]=0; //pseudo data for funciton
//
sum+=sample[i];//dc-bias
//while(msec==0);
}
avg = sum/64;//calculate bias
for(i=0;i<64;i++)
@ -79,11 +87,12 @@ int main (void)
//
for(i=0;i<64;i++)
{
sample[i] = sample[i] *SCALE_FACTOR;
sample[i] = (sample[i]*0.6 + buff[i]*0.5);
buff[i] = sample[i];
if(sample[i]<0) sample[i] = 0;
if(sample[i]>64) sample[i]=64;
sample[i] = sample[i] *SCALE_FACTOR;
sample[i] = (sample[i]*0.7 + buff[i]*0.3);
buff[i] = sample[i];
}
for(i=0;i<8;i++)
{
@ -93,23 +102,23 @@ int main (void)
}
//avg written to sample[0..7]
if(sample[i]<30)
if(sample[i]<20)
{
led_bar1[i].r=0;
led_bar1[i].g=0;
led_bar1[i].b=sample[i];
}
else if(sample[i]<50)
else if(sample[i]<40)
{
led_bar1[i].r=0;
led_bar1[i].g=sample[i];
led_bar1[i].b=0;
led_bar1[i].b=sample[i]/2;
}
else if(sample[i]<100)
else if(sample[i]<60)
{
led_bar1[i].r=sample[i];
led_bar1[i].g=0;
led_bar1[i].b=0;
led_bar1[i].b=sample[i]/2;
}
}
@ -128,14 +137,28 @@ int map(int value, int old_min, int old_max,int new_min, int new_max)
void setupTimer(void)
{
TCCR1 = (1<<CS13)|(1<<CS12)|(1<<CS11)|(1<<CS10)| //CK/16384
(1<<CTC1); //clear timer on compare match
TCCR1 = (1<<CS13)|(1<<CS10)|(1<<CTC1); //clear timer on compare match
GTCCR = 0; //default values should be ok
OCR1A = 255; //Compare value of timer / overflow , sets OCF1A
//
OCR1C = 117; //Compare value of timer / overflow , sets OCF1A
OCR1A = 117;
TIMSK = (1<<OCIE1A);//|(1<<TOIE1); //enable interupt compare a
TIFR = (1<<OCF1A); //flag register "aka when to interrupt
}
/*
* 1/(30Mhz/16384) *255 = 0.139264s Time for one overflow
* 1024 = 0.008704s
* 2024 = 0.017204s
* 255/0.017204*0.001=15 counts = 1ms
* 256 gives 1ms
*/
void wait_period(void)
{
// TIFR |=(1<<TOV1); //clear overflow flag
}
ISR(TIMER1_COMPA_vect)
{
msec++;
}