0

我想确保我的代码看起来可以正常工作,因为明天我没有太多时间使用信号发生器,我想知道如何设置采样率。

我想用 Arduino MEGA 2560 以 6kHz 的采样率对 2kHz 信号进行采样。它不一定是实时的,所以我正在考虑填充一个缓冲区,然后通过串行连接发送这些信号。任何人都可以说如果这段代码绝对不能为此工作吗?我怎样才能将采样率设置为 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]);
}

}

谢谢你。

4

1 回答 1

0

好吧,正如我在另一个线程中提到的,您可以使用ADC(用于UNOATMega328p基于 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
}

此草图使用波特率 250000 但仍然太慢。空格字符可以用作分隔符,这样可以节省一个字符(因为换行通常是两个字符:\r\n)。一个值的长度可以是 1 到 4 个字符,因此对于值:

  • 0-9 - 3B 你需要波特率 3*10*6000 = 180000
  • 10-99 - 4B 你需要波特率 240000
  • 而对于其余的情况,你太慢了。

所以唯一的方法是发送这些整数二进制并且没有分隔符会更好。每个值 2B 导致最小波特率约为 120000 波特/秒。

于 2016-10-05T19:30:43.397 回答