Sunday, June 16, 2013

Read ADC of Arduino Due with Processing 2.0

This exercise demonstrate reading ADC in Arduino Due board, and send to PC running Processing 2.0 via serial port, then display in PC.



Code in PC side running Processing 2.0 is in next post.

Code in Arduino Due board.
int led = 13;
boolean ledon;

int analogInputA1 = A1;

const int MAX_INDEX = 400;
int var[MAX_INDEX];
int varIndex;

volatile boolean dataReady;

int FREQ_1KHz = 1000;

void TC3_Handler(){
    TC_GetStatus(TC1, 0);
    
    digitalWrite(led, ledon = !ledon);
    
    if(!dataReady){
      var[varIndex] = analogRead(analogInputA1);  //read ADC input
      varIndex++;
      if(varIndex == MAX_INDEX){
        varIndex = 0;
        dataReady = true;
      }
    }
    
}

void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq, uint32_t frequency){
  
    //Enable or disable write protect of PMC registers.
    pmc_set_writeprotect(false);
    //Enable the specified peripheral clock.
    pmc_enable_periph_clk((uint32_t)irq);  
    
    TC_Configure(tc, channel, TC_CMR_WAVE|TC_CMR_WAVSEL_UP_RC|TC_CMR_TCCLKS_TIMER_CLOCK4);
    uint32_t rc = VARIANT_MCK/128/frequency;
    
    TC_SetRA(tc, channel, rc/2);
    TC_SetRC(tc, channel, rc);
    TC_Start(tc, channel);
    
    tc->TC_CHANNEL[channel].TC_IER = TC_IER_CPCS;
    tc->TC_CHANNEL[channel].TC_IDR = ~TC_IER_CPCS;
    NVIC_EnableIRQ(irq);
}

void setup() {
  pinMode(led, OUTPUT);
  
  Serial.begin(19200);
  analogReadResolution(8);  //set ADC resolution to 8 bits
  dataReady = false;
  varIndex = 0;
  startTimer(TC1, 0, TC3_IRQn, FREQ_1KHz);
}

void loop() {
  
  if(dataReady){  
    for(int i = 0; i < MAX_INDEX; i++)
    {
      Serial.write(var[i]);
    }
    dataReady = false;
  }
}


download filesDownload the files.

No comments:

Post a Comment