Using Atmega TCNT1 - atmega

I'm trying to use an arduino uno to show some students how to make their own 'auto tune' however the code that I wrote is not outputting any signal. The goal is to sample values into an array at one rate and output the data from the array(FIFO)at a slower rate. My understanding is that TCNT1 increments each clock tick, I'm using 16 MHz in my case, and that I can base if logic on the value of TCNT1, I use a mod function here to take and store a single adc value and then play that value to the dac at a later time. acdT dacT represent my timing logic. I've built an external DAC to read only 8 (of 10) bit values from d0-d7 (PORTD). Why am I not seeing a signal?
int i = 0;
int j = 0;
int adcT = 328; // 329 clock tics
int dacT = 349; // 350 clock tics
int buff[15]; // 16 length buffer to store adc values
void setup ()
{
PRR &= ~(1<<PRADC); //ADC turned on
ADMUX = 0x60; //AVcc, left adjusted, ADC0 pin
ADCSRA = 0xC0;//ADC Enabled, no auto trigger
DDRD=0xFF; // set portd to d0 thru d7 digital pins
DDRC=0x00; // accept input from any analog input
TCCR1B |= 1<<CS10; // sets the clock to the system clock ie no pre scaler
}
void loop ()
{
if((TCNT1%acdT == 0) || TCNT1 == 0) // execute at 0 and mod329 clock tics
{
ADCSRA|=(1<<ADSC); // take one adc reading
while(!(ADCSRA & (1<<ADIF))); // wait until the reading is complete
ADCSRA|=(1<<ADIF); //reset adc for next command
buff[i] = ADCH; // take the adc value into the array
i++ // increment
}
if((TCNT1%dacT == 0)) %% TCNT1 ~= 0// execute at mod350 clock tics
{
PORTD = buff[j]; // send the adc reading to digital output
j++;
}
if(TCNT1 == 5262 ) // LCM/3 of 329(16samples) and 350(15samples)
{
TCNT1 = 0;// reset ticker
i = 0;
j = 0;
}
if(TCNT1 == 336)
{
PORTD = buff[15]; // play 16th adc sample to clear array
}
}

TCCR1B |= 1<<CS10; // sets the clock to the system clock ie no pre scaler
And there's your problem. You're attempting to find the modulus of a counter that runs faster than your code. Use the output capture and other features of the timer to trigger interrupts and reset the timer at the appropriate times instead of trying to catch a passing bullet with your bare hands.

Related

setting right ADC prescaler on the Arduino Due in timer and interrupt driven multi-channel ADC acquisition

I am trying to follow, adapt, understand (and clean up a bit) a variation around the code available there, for the Arduino Due: https://forum.arduino.cc/index.php?topic=589213.0 . I do not like the forum format, as things end up buried deep, so asking here instead. Unfortunately this means that there is quite a lot of explanations before the question. If you think this is wrong to post it here, let me know, and I can move.
Basically, the idea is to log several ADC channels in a buffer, using timer-based triggering. There is a bit of setup:
// sample rate in Hz
constexpr int sample_rate = 1000;
constexpr uint8_t channels[] = {7, 6, 5, 4, 3};
constexpr int nbr_channels = sizeof(channels);
Then time counter 0 channel 2 is set at the right frequency for triggering the ADC conversion:
// use time counter 0 channel 2 to generate the ADC start of conversion signal
// i.e. this sets a rising edge with the right frequency for triggering ADC conversions corresponding to sample_rate
// for more information about the timers: https://github.com/ivanseidel/DueTimer/blob/master/TimerCounter.md
// NOTE: TIOA2 should not be available on any due pin https://github.com/ivanseidel/DueTimer/issues/11
void tc_setup() {
PMC->PMC_PCER0 |= PMC_PCER0_PID29; // TC2 power ON : Timer Counter 0 channel 2 IS TC2
TC0->TC_CHANNEL[2].TC_CMR = TC_CMR_TCCLKS_TIMER_CLOCK2 // clock 2 has frequency MCK/8, clk on rising edge
| TC_CMR_WAVE // Waveform mode
| TC_CMR_WAVSEL_UP_RC // UP mode with automatic trigger on RC Compare
| TC_CMR_ACPA_CLEAR // Clear TIOA2 on RA compare match
| TC_CMR_ACPC_SET; // Set TIOA2 on RC compare match
constexpr int ticks_per_sample = F_CPU / 8 / sample_rate; // F_CPU / 8 is the timer clock frequency, see MCK/8 setup
constexpr int ticks_duty_cycle = ticks_per_sample / 2; // duty rate up vs down ticks over timer cycle; use 50%
TC0->TC_CHANNEL[2].TC_RC = ticks_per_sample;
TC0->TC_CHANNEL[2].TC_RA = ticks_duty_cycle;
TC0->TC_CHANNEL[2].TC_CCR = TC_CCR_SWTRG | TC_CCR_CLKEN; // Software trigger TC2 counter and enable
}
Finally this can be used to trigger the ADC:
// start ADC conversion on rising edge on time counter 0 channel 2
// perform ADC conversion on several channels in a row one after the other
// report finished conversion using ADC interrupt
void adc_setup() {
PMC->PMC_PCER1 |= PMC_PCER1_PID37; // ADC power on
ADC->ADC_CR = ADC_CR_SWRST; // Reset ADC
ADC->ADC_MR |= ADC_MR_TRGEN_EN | // Hardware trigger select
ADC_MR_PRESCAL(1) | // the pre-scaler: as high as possible for better accuracy, while still fast enough to measure everything
// see: https://arduino.stackexchange.com/questions/12723/how-to-slow-adc-clock-speed-to-1mhz-on-arduino-due
ADC_MR_TRGSEL_ADC_TRIG3; // Trigger by TIOA2 Rising edge
ADC->ADC_IDR = ~(0ul);
ADC->ADC_CHDR = ~(0ul);
for (int i = 0; i < nbr_channels; i++)
{
ADC->ADC_CHER |= ADC_CHER_CH0 << channels[i];
}
ADC->ADC_IER |= ADC_IER_EOC0 << channels[nbr_channels - 1];
ADC->ADC_PTCR |= ADC_PTCR_RXTDIS | ADC_PTCR_TXTDIS; // Disable PDC DMA
NVIC_EnableIRQ(ADC_IRQn); // Enable ADC interrupt
}
and the ADC output can be captured in the corresponding ISR:
void ADC_Handler() {
for (size_t i = 0; i < nbr_channels; i++)
{
SOME_BUFFER[i] = static_cast<volatile uint16_t>( * (ADC->ADC_CDR + channels[i]) & 0x0FFFF ); // get the output
}
}
I think this is quite understandable, but I have one question: the setting of the pre-scaler.
if I understand well discussions online, the pre-scaler should be set so that frq_ADC >= sample_rate * nbr_channels, basically because the chip is just multiplexing the ADC through several channels
if I understand well, we want to set such pre-scaler value as high as possible given the previous constraint, so that the ADC frequency is as low as possible, because this improves ADC conversion quality
Is that right?
The problem is that I am confused about how to set the pre-scaler, and what value corresponds to what, because what I find in the datasheet disagree with some other online responses I read.
From the datasheet https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf : "The ADC clock range is between MCK/2, if PRESCAL is 0, and MCK/512, if PRESCAL is set to 255 (0xFF).". This is consistent with what I find on page 1334: "ADCClock = MCK / ( (PRESCAL+1) * 2 )". But page 1318, it is written that the conversion rate is 1MHz. Then how is that compatible with having a MCK frequency of 84MHz on the Due? 84/2 = 48MHz, 84/512 = 0.164MHz, the high freq value is too high.
Then to add to the confusion I have found this issue: https://arduino.stackexchange.com/questions/12723/how-to-slow-adc-clock-speed-to-1mhz-on-arduino-due/21054#21054 that also seem to conflict with the 1MHz upper bound.
Any idea where I misunderstand something? (and any more comments around the general working of the program?).
Ok, so I did some tests with the code, checking when I was missing some conversions depending on the timer frequency and the prescaler value. The code is a bit long, so I post it at the end of the answer. Basically:
// pre-scalor analysis using 5 channels;
// quantities indicated are sampling frequency of the 5 channels
// i.e. necessary ADC sampling frequency is 5 x higher, and value
// of the prescaler ps
// --------------------
// 100kHz ps 1 ok
// 100kHz ps 2 ok
// 100kHz ps 3 fail
// 100kHz ps 255 fail
// 100kHz ps 256 ok
// this indicates: prescaler is 8 bits from 0 to 255, after this wraps up
// ADC frequency is max something like 1MHz in practice: 5 * 100 * 2 (may loose a bit
// due to other interrupts hitting ours?)
// --------------------
// 10kHz ps 38 ok
// 10kHz ps 39 fail
// 10 * 5 * 40 = 2000kHz: ADC is lower than 2MHz
// --------------------
// 1kHz ps 255 ok
// --------------------
I think this indicates that:
the pre-scaler value is well an 8 bits int, between 0 and 255, as it wraps up at 256
I have difficultie matching the results to the formula in the datasheet. I guess this is because there is some overhead switching channels etc (?). For example:
the results are consistent with ```ADC_freq = 1MHz / ( ps ) at the highest frequencies, but I suppose this is because there is a bit of overhead switching channels
the results are consistent with ```ADC_freq = 2MHz / ( ps ) at 10 kHz, and at 1kHz, even using the highest prescaler is fine.
The code I was using is the following, and the criterion for deciding that things fail is that the code reports a drop in the effective sample frequency over the 5 channels:
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// timer driven ADC convertion captured by interrupt on n adc_channels for Arduino Due
//
// this is for Arduino Due only!
//
// the interrupt based ADC measurement is adapted from:
// https://forum.arduino.cc/index.php?topic=589213.0
// i.e. adc_setup(), tc_setup(), ADC_handler() are inspired from the discussion there.
//
// written with VSCode + Platformio and Due board setup
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// make my linter happy
#include "Arduino.h"
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// some vital ADC grabbing setup
// sample rate in Hz, should be able to go up to several 10s ok kHz at least
constexpr int adc_sample_rate = 1000;
// size of the data buffers "in time"
// i.e. how many consecutive measurements we buffer for each channel
constexpr size_t adc_buffer_nbr_consec_meas = 5;
// the adc_channels to read, in uC reference, NOT in Arduino Due pinout reference
// for a mapping, see: https://components101.com/microcontrollers/arduino-due
// i.e. A0 is AD7
// A1 AD6
// A2 AD5
// A3 AD4
// A4 AD3
// A5 AD2
// A6 AD1
// A7 AD0
constexpr uint8_t adc_channels[] = {7, 6, 5, 4, 3};
constexpr int nbr_adc_channels = sizeof(adc_channels);
// the buffer containing the measurements for all adc_channels over several measurements in time
volatile uint16_t adc_meas_buffer[adc_buffer_nbr_consec_meas][nbr_adc_channels];
// flag when a full vector of conversions is available
volatile bool adc_flag_conversion = false;
// time index of the current measurement in the adc reads buffer
volatile size_t crrt_adc_meas_buffer_idx = 0;
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// some non-vital printing config
// a bit of time tracking, just to analyze how good performance
unsigned long current_us = 0;
unsigned long previous_us = 0;
unsigned long delta_us = 0;
float delta_us_as_s = 0;
float delta_us_as_ms = 0;
int nbr_readings_since_reduced_time_stats = 0;
unsigned long current_reduced_time_stats_us = 0;
unsigned long previous_reduced_time_stats_us = 0;
float delta_reduced_time_stats_us_as_s = 0;
float effective_logging_frequency = 0;
// decide what to print on serial
constexpr bool print_reduced_time_stats = true;
constexpr bool print_time_stats = false;
constexpr bool print_full_buffer = false;
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// low level functions for setting clock and ADC
// start ADC conversion on rising edge on time counter 0 channel 2
// perform ADC conversion on several adc_channels in a row one after the other
// report finished conversion using ADC interrupt
// tests about pre-scaler: formula should be:
// pre-scalor analysis using 5 channels;
// quantities indicated are sampling frequency of the 5 channels
// i.e. necessary ADC sampling frequency is 5 x higher, and value
// of the prescaler ps
// --------------------
// 100kHz ps 1 ok
// 100kHz ps 2 ok
// 100kHz ps 3 fail
// 100kHz ps 255 fail
// 100kHz ps 256 ok
// this indicates: prescaler is 8 bits from 0 to 255, after this wraps up
// ADC frequency is max something like 1MHz in practice: 5 * 100 * 2 (may loose a bit
// due to other interrupts hitting ours?)
// --------------------
// 10kHz ps 38 ok
// 10kHz ps 39 fail
// 10 * 5 * 40 = 2000kHz: ADC is lower than 2MHz
// --------------------
// 1kHz ps 255 ok
// --------------------
// CCL: use ps 2 at 100kHz with 5 channels, 20 at 10kHz, 200 at 1kHz
void adc_setup()
{
PMC->PMC_PCER1 |= PMC_PCER1_PID37; // ADC power on
ADC->ADC_CR = ADC_CR_SWRST; // Reset ADC
ADC->ADC_MR |= ADC_MR_TRGEN_EN | // Hardware trigger select
ADC_MR_PRESCAL(200) | // the pre-scaler: as high as possible for better accuracy, while still fast enough to measure everything
// see: https://arduino.stackexchange.com/questions/12723/how-to-slow-adc-clock-speed-to-1mhz-on-arduino-due
// unclear, asked: https://stackoverflow.com/questions/64243073/setting-right-adc-prescaler-on-the-arduino-due-in-timer-and-interrupt-driven-mul
ADC_MR_TRGSEL_ADC_TRIG3; // Trigger by TIOA2 Rising edge
ADC->ADC_IDR = ~(0ul);
ADC->ADC_CHDR = ~(0ul);
for (int i = 0; i < nbr_adc_channels; i++)
{
ADC->ADC_CHER |= ADC_CHER_CH0 << adc_channels[i];
}
ADC->ADC_IER |= ADC_IER_EOC0 << adc_channels[nbr_adc_channels - 1];
ADC->ADC_PTCR |= ADC_PTCR_RXTDIS | ADC_PTCR_TXTDIS; // Disable PDC DMA
NVIC_EnableIRQ(ADC_IRQn); // Enable ADC interrupt
}
// use time counter 0 channel 2 to generate the ADC start of conversion signal
// i.e. this sets a rising edge with the right frequency for triggering ADC conversions corresponding to adc_sample_rate
// for more information about the timers: https://github.com/ivanseidel/DueTimer/blob/master/TimerCounter.md
// NOTE: TIOA2 should not be available on any due pin https://github.com/ivanseidel/DueTimer/issues/11
void tc_setup()
{
PMC->PMC_PCER0 |= PMC_PCER0_PID29; // TC2 power ON : Timer Counter 0 channel 2 IS TC2
TC0->TC_CHANNEL[2].TC_CMR = TC_CMR_TCCLKS_TIMER_CLOCK2 // clock 2 has frequency MCK/8, clk on rising edge
| TC_CMR_WAVE // Waveform mode
| TC_CMR_WAVSEL_UP_RC // UP mode with automatic trigger on RC Compare
| TC_CMR_ACPA_CLEAR // Clear TIOA2 on RA compare match
| TC_CMR_ACPC_SET; // Set TIOA2 on RC compare match
constexpr int ticks_per_sample = F_CPU / 8 / adc_sample_rate; // F_CPU / 8 is the timer clock frequency, see MCK/8 setup
constexpr int ticks_duty_cycle = ticks_per_sample / 2; // duty rate up vs down ticks over timer cycle; use 50%
TC0->TC_CHANNEL[2].TC_RC = ticks_per_sample;
TC0->TC_CHANNEL[2].TC_RA = ticks_duty_cycle;
TC0->TC_CHANNEL[2].TC_CCR = TC_CCR_SWTRG | TC_CCR_CLKEN; // Software trigger TC2 counter and enable
}
// ISR for the ADC ready readout interrupt
// push the current ADC data on all adc_channels to the buffer
// update the time index
// set flag conversion ready
void ADC_Handler()
{
for (size_t i = 0; i < nbr_adc_channels; i++)
{
adc_meas_buffer[crrt_adc_meas_buffer_idx][i] = static_cast<volatile uint16_t>(*(ADC->ADC_CDR + adc_channels[i]) & 0x0FFFF);
}
crrt_adc_meas_buffer_idx = (crrt_adc_meas_buffer_idx + 1) % adc_buffer_nbr_consec_meas;
adc_flag_conversion = true;
}
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// a simple script: setup and print information
void setup()
{
Serial.begin(115200);
delay(100);
adc_setup();
tc_setup();
}
void loop()
{
if (adc_flag_conversion == true)
{
adc_flag_conversion = false;
if (print_reduced_time_stats)
{
nbr_readings_since_reduced_time_stats += 1;
if (nbr_readings_since_reduced_time_stats == adc_sample_rate)
{
current_reduced_time_stats_us = micros();
delta_reduced_time_stats_us_as_s = static_cast<float>(current_reduced_time_stats_us - previous_reduced_time_stats_us) / 1000000.0;
effective_logging_frequency = static_cast<float>(adc_sample_rate) / delta_reduced_time_stats_us_as_s;
previous_reduced_time_stats_us = current_reduced_time_stats_us;
Serial.print(F("Effective logging freq over nbr spls that should correspond to 1 second: "));
Serial.println(effective_logging_frequency);
nbr_readings_since_reduced_time_stats = 0;
}
}
if (print_time_stats)
{
current_us = micros();
delta_us = current_us - previous_us;
delta_us_as_s = static_cast<float>(delta_us) / 1000000.0;
delta_us_as_ms = static_cast<float>(delta_us) / 1000.0;
Serial.println(F("ADC avail at uS"));
Serial.println(micros());
Serial.println(F("elapsed us"));
Serial.println(delta_us);
Serial.println(F("elapsed ms"));
Serial.println(delta_us_as_ms);
Serial.println(F("elapsed s"));
Serial.println(delta_us_as_s);
Serial.println(F("updated idx:"));
size_t last_modified_buffer_idx;
if (crrt_adc_meas_buffer_idx > 0){
last_modified_buffer_idx = crrt_adc_meas_buffer_idx - 1;
}
else{
last_modified_buffer_idx = nbr_adc_channels - 1;
}
Serial.println(last_modified_buffer_idx);
previous_us = current_us;
}
if (print_full_buffer)
{
for (size_t i = 0; i < nbr_adc_channels; i++)
{
Serial.print(F(" ADC "));
Serial.print(adc_channels[i]);
Serial.println(F(" meas in time:"));
for (size_t j = 0; j < adc_buffer_nbr_consec_meas; j++)
{
Serial.print(adc_meas_buffer[j][i]);
Serial.print(F(" "));
}
Serial.println();
}
}
}
}

Incremental 65535 steps to increase LED brightness to maximum over time (in hours), stay on at maximum (for hours) and ramp down (opposite of starup)

Trying to understand timing / dimming and interrupts using an Arduino Uno (or any other AVR) is being made very difficult by a serious lack of example code. Having found a sketch that starts from zero and ramps up the brightness, I have tried to adapt the code to prevent the continuous loop which occurs when the 16-bit register overflows.
The attached sketch starts up from zero light output and increases over a period of time - currently using the delay() function.
Attempting to adapt the code to prevent the loop from starting the entire process again and to allow the led to remain at the "top" brightness output for x (variable) number of hours has proved to be most elusive. As one of the contributors have noted this area of coding is one of the most difficult to master.
Any advice or guidance which will put me in the right direction will be most appreciated.
...
//fade over 65535 steps
// 16 bit PWM on any pin
// Example uses built in LED on pin 13 (PORTB bit 5)
// https://forum.arduino.cc/index.php?topic=348170.0
void setup() {
pinMode(13, OUTPUT);
cli(); // Disable all interrupts
TCCR1A = 0; // Clear all flags in control register A
TCCR1B = 0; // Clear all flags in control register B
TCNT1 = 0; // Zero timer 1 count
OCR1A = 32768; // Preload compare match register (50% duty cycle)
// No prescaler
//TCCR1B |= _BV(CS12);
//TCCR1B |= _BV(CS11);
TCCR1B |= _BV(CS10);
TIMSK1 |= _BV(OCIE1A); // Enable timer compare interrupt
TIMSK1 |= _BV(TOIE1); // Enable timer overflow interrupt
sei(); // enable all interrupts
}
void loop() {
for (unsigned int x = 1; x < 65535; x++) {
//cli();
OCR1A = x;
//sei();
delay(20);
}
}
ISR(TIMER1_OVF_vect) { // Timer1 overflow interrupt service routine
PORTB |= _BV(PORTB5); // Turn LED (pin 13) on
}
ISR(TIMER1_COMPA_vect) { // Timer1 compare interrupt service routine
PORTB &= ~_BV(PORTB5); // Turn LED off
}
...

software PLL to generate 3.2 Khz sampling freq locked with 1pps from GPS in arduino

I want to design a phase locked loop using Arduino. To generate 3.2 Khz sampling freqency locked with 1 PPS (from GPS), for my data aquisition module,
the sampling clock generated without using PLL get drifted over time. which leads to wrong sample collection. if sampling clock is generated using PLL locked with a reference freqency (1 PPS) :: data aquisition modules at different location will be able to collect sample at same instant.
You can make a phase-locked loop, literally.
You need two interrupts:
First will fire on the front of a pulse at 1 PPS input.
Second will be called 3200 times per second, each time when timer wraps around.
First, setup the timer cycle length to 5000 CPU cycles.
The timer interrupt is very simple just increases some counter variable, and when it reaches 3200, resets it to zero.
The one-second pulse interrupt acts as follows:
If the counter variable value is zero - that means timer works at the exact frequency - do nothing
If the counter variable value greater than 0 but less than 1600 (i.e. timer works faster than required) - increase the timer period by 1
If the counter variable value 1600 or greater (the once-per-second interrupt happened faster than the counter reached 3200) decrease the timer period by 1
For the first start, set the counter variable to 0, timer value to 2500 (half of the period), timer period to 5000, and wait until the first pulse appears, then start the timer.
The code example maybe like this (assuming usage of Arduino UNO, and 1 PPS connected to INT0 input, triggered by a rising edge):
volatile uint16_t counter = 0; // counter variable
ISR(TIMER1_COMPA_vect) { // Timer interrupt
if (++counter >= 3200) counter = 0;
}
// edited: INT0_vect
ISR(INT0_vect) { // External Interrupt Request 0
if ((TCCR1B & ((1 << CS12) | (1 << CS11) | (1 << CS10))) == 0) {
// if timer is not running (the first pulse)
TCCR1B = (1 << WGM12) | (1 << CS10); // Start in CTC mode, 1:1 prescaler
} else { // Once-per-second pulse
uint16_t cnt = counter;
if (cnt >= 1600) {
uint16_t ocr_val = OCR1A - 1; // edited: uint16_t
OCR1A = ocr_val;
if (TCNT1 >= ocr_val) { // for the case, when OCR1A was changed below the current value of TCNT1
TCNT1 = 0;
}
} else if (cnt > 0) {
OCR1A++;
}
}
}
// initialization code
TCCR1A = 0; // for now timer is disabled
TCCR1B = 0;
OCR1A = 4999; // 5000 timer period
TCNT1 = 2500; // starts from the middle of the first period
TIMSK1 = (1 << OCIE1A); // allow the output compare 1 interrupt
EICRA = (1 << ISC01) | (1 << ISC00); // The rising edge of INT0 generates an interrupt request
EIMSK = (1 << INT0); // Allow int0 interruput
sei(); // Enable interrupts.
If you want the output signal to be generated at OC1B pin, you may initialize the timer like this:
TCCR1A = (1 << COM1B1) | (1 << WGM11) | (1 << WGM10); // edited: COM1B1
OCR1B = 2499; // PWM with pulse length half of the period
DDRB |= (1 << DDB2); // edited: port initialization
and in the INT0 interrupt start the timer like this:
TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10); // Start in FastPWM - CTC mode, 1:1 prescaler
the output should appear at PB2/OC1B pin = Arduino UNO pin 10

“Read Analog Voltage” sample rate

I want to make sure my code looks like working, since I don't have a lot of time with a signal generator tomorrow and I want to know how to set the sample rate.
I want to sample a 2kHz signal with a samplerate of 6kHz with a Arduino MEGA 2560.
It, doesn't have to be in real time, so i'm thinking of filling a buffer and then sending those over the serial connection.
Can anyone say if this code defenitly wouldn't work for this?
And how could i set the samplerate to 6kHz?
void setup() {
Serial.begin(9600);
}
void loop() {
for(int x = 0; x < 1000; x++){
// read the input on analog pin 0:
int sensorValue[x] = analogRead(A0);
}
for( x = 0; x < 1000; x++){
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage[x] = sensorValue[x] * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage[x]);
}
}
Thank you.
Well, as I've mentioned in another thread, you can use auto triggering mode of ADC (for UNO and ATMega328p based Arduinos):
void setup() {
Serial.begin(256000);
// ADC setup is done by arduino framework, but it's possible to change it slightly (for ATMega328) :
ADCSRB = _BV(ADTS2) | _BV(ADTS1) | _BV(ADTS0); // ADTS2..0 = 111, Timer 1 input capture event trigger source
ADCSRA |= _BV(ADATE); // enable auto trigger mode
ADCSRA |= _BV(ADIF); // reset conversion end flag (= interrupt flag)
// timer 1 setting:
TCCR1A = 0; // clear all
ICR1 = F_CPU/6000U; // 1 should be substracted here but result is about 2665.7 and it will be truncated to 2665
TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10); // CTC mode with ICR1 as TOP value, enabled with no prescaling
TIMSK1 = _BV(ICF1); // not working without this... Flag must be cleaned up after the trigger ADC, otherwise it's stucked
analogRead(A0); // dummy read to set correct channel and to start auto trigger mode
pinMode(13, OUTPUT);
}
void loop() {
if (ADCSRA & _BV(ADIF)) {
ADCSRA |= _BV(ADIF); // reset flag by writing logic 1
Serial.println(ADC);
}
}
ISR(TIMER1_CAPT_vect) { // to clear flag
PINB = _BV(PB5); // and toggle d13 so frequency can be measured (it'd be half of real rate)
// it might be enabled on PWM pin too by setting force output compare and some compare register to half of value ICR1
}
This sketch uses baud rate 250000 but it's still too slow. The space character can be used as an separator, this'll save one character (as new line are usually two characters: \r\n). One value can be 1 to 4 characters long so for values:
0-9 - 3B you need baud rate 3*10*6000 = 180000
10-99 - 4B and you need baud rate 240000
and for the rest of cases you're too slow.
So the only way is sending those integers binary and without separator it'd be even better. The 2B per value results into minimal baud rate around 120000 baud/s.

Reading Soft_Uart & Hardware Uart # same time

OK, so i have accomplished creating a software and hardware UART on PIC18f8680 in MikroC compiler. The Soft_Uart uses timer0 for interrupt and breaks the Soft_UART_read() line by a function called Soft_uart_Break().
everything is working fine, when i read a single character from both uart. but when i send a string on hardware uart, the string doesn't gets reads properly by these lines;
UART1_Read_Text(buffer, "OK", 100);
UART1_Write_Text(buffer);
I've found out whats causing this problem. that is, my main while loop gets stuck in Soft_UART_read() until it gets break by an interrupt. while its stuck over there, the hardware uart doesn't gets proper time to read the whole string, so as a result it displays some of the characters of that string.
how can i overcome this ? do i need to use a separate interrupt for hardware uart aswel ? or what ? any help would be highly appreciated.
here is a snip of my code;
void main() {
INTCON.GIE=1; //globle interrupt enable
INTCON.PEIE=1; //peripharel interrupt enable
INTCON.TMR0IF = 0x0; //Clear timer0 overflow interrupt flag
INTCON.TMR0IE = 1; //enable the timer0 by setting TRM0IE flag
T0CON.TMR0ON = 1; // Timer0 On/Off Control bit: 1=Enables Timer0 / 0=Stops Timer0
T0CON.T08BIT = 0; // Timer0 8-bit/16-bit Control bit: 1=8-bit timer/counter / 0=16-bit timer/counter
T0CON.T0CS = 0; // TMR0 Clock Source Select bit: 0=Internal Clock (CLKO) / 1=Transition on T0CKI pin
T0CON.T0SE = 0; // TMR0 Source Edge Select bit: 0=low/high / 1=high/low
T0CON.PSA = 1; // Prescaler Assignment bit: 0=Prescaler is assigned; 1=NOT assigned/bypassed
T0CON.T0PS2 = 0; // bits 2-0 PS2:PS0: Prescaler Select bits
T0CON.T0PS1 = 1;
T0CON.T0PS0 = 1;
TMR0H = 0xBD; // preset for Timer0 MSB register
TMR0L = 0xCD; // preset for Timer0 LSB register
while(1) {
data1 = Soft_UART_Read(&error);
Soft_UART_Write(data1);
if (data1 == 'b') {
for(x = 0; x <= strlen(alive); x++) {
Soft_UART_Write(alive[x]);
}
}
if (UART1_Data_Ready()) { // If data is received,
UART1_Read_Text(buffer, "OK", 100); // reads text until 'OK' is found
UART1_Write_Text(buffer); // sends back text
/*if (uart_rd == 'a') {
UART1_Write_Text("\rSensor 1 data\r");
}*/
//else
//UART1_Write(uart_rd); // and send data via UART
}
}
}
I had the same issue. Some of the example code and documentation in the MikroC manual seems to contradict itself.
The prototype is:
void UARTx_Read_Text(char *Output, char *Delimiter, char Attempts);
Your delimiter should be:
char delimit[] = "OK";
UART1_Read_Text(&dataIn,&delimit,attempts);
If you know the size of the data being received attempts should correspond to this.

Resources