Stap 9: Het lezen van een analoge waarde
Het programma kan tot nu toe een LED knipperen. Vervolgens laat geven het aantal input van de gebruiker. Wij zullen een potentiometer gebruiken om het maken van een analoog signaal dat de snelheid van de LED zal veranderen. De ADC neemt de spanning in een analoge en een digitale waarde-uitgang.
- Open in de browser project user.c onder bronbestanden
- Boven de InitApp-functie maakt u een nieuwe functie
void init_adc(void)
- Voer de volgende code om te initialiseren van de ADC-module
/** * Initialize the Analog to Digital Converter. */void init_adc(void){ TRISAbits.TRISA1 =0b1; // set pin as input ANCON0bits.ANSEL1 =0b1; // set pin as analog ADCON1bits.VCFG =0b00;// set v+ reference to Vdd ADCON1bits.VNCFG =0b0; // set v- reference to GND ADCON1bits.CHSN =0b000;// set negative input to GND ADCON2bits.ADFM =0b1; // right justify the output ADCON2bits.ACQT =0b110;// 16 TAD ADCON2bits.ADCS =0b101;// use Fosc/16 for clock source ADCON0bits.ADON =0b1; // turn on the ADC}
- Vervolgens maakt een andere functie onmiddellijk na genaamd
uint16_t adc_convert(uint8_t channel)
/** * Preform an analog to digital conversion. * channel The ADC input channel to use. * The value of the conversion. */ uint16_t adc_convert(uint8_t channel){ ADCON0bits.CHS = channel; // select the given channel ADCON0bits.GO =0b1; // start the conversion while(ADCON0bits.DONE); // wait for the conversion to finish return(ADRESH<<8)|ADRESL; // return the result}
- Voeg de lijn toe in de InitApp-functie
init_adc()
- Voeg het prototype in het bestand user.h
uint16_t adc_convert(uint8_t);
- Belangrijkste overeenkomen met de volgende wijziging:
voidmain(void){ uint16_t adc_value; // variable to hold ADC conversion result in /* Configure the oscillator for the device */ ConfigureOscillator(); /* Initialize I/O and Peripherals for application */ InitApp(); TRISAbits.TRISA0 =0; // set pin as output while(1) { LATAbits.LATA0 =0; // set pin LOW adc_value = adc_convert(1); // preform A/D conversion on channel 1 wait_ms(adc_value>>2); // wait 0.5 seconds LATAbits.LATA0 =1; // set pin HIGH adc_value = adc_convert(1); // preform A/D conversion on channel 1 wait_ms(adc_value>>2); // wait 0.5 seconds }}
- Bouwen en de code downloaden. Als je de POT draaien de LED knippert de snelheid moeten wijzigen