Difference between revisions of "Example Writeup: Analog Input"

From Mech
Jump to navigationJump to search
Line 11: Line 11:


== Code ==
== Code ==

<nowiki>


/*
/*
AnalogInput.c m.peshkin 2007-12-24
AnalogInput.c m.peshkin 2007-12-24
Range of input voltages on pins AN0 to AN11 is 0 to 5 volts only
Range of input voltages on pins AN0 to AN11 is 0 to 5 volts only.
This maps to 0-255 ADC values if ADC is in 8 bit mode
This maps to 0-255 ADC values if ADC is in 8 bit mode,
Or to 0-1023 ADC values if ADC is in 10 bit mode
or to 0-1023 ADC values if ADC is in 10 bit mode.
There is only one ADC, with a switch to connect it to up to 12 input pins named AN0 to AN11
There is only one ADC, with a switch to connect it to up to 12 input pins named AN0 to AN11.
After you switch inputs, wait 10uS for the ADC to settle onto the new input
After you switch inputs, wait 10uS for the ADC to settle onto the new input
*/
*/


#include <18f4520.h>
#include <18f4520.h>

#DEVICE ADC=10 // set ADC to 10 bit accuracy, or it could be just 8
#DEVICE ADC=10 // set ADC to 10 bit accuracy, or it could be just 8

#fuses HS,NOLVP,NOWDT,NOPROTECT
#fuses HS,NOLVP,NOWDT,NOPROTECT
#use delay(clock=20000000)
#use delay(clock=20000000)
Line 50: Line 46:
}
}
}
}
</nowiki>

Revision as of 12:20, 26 January 2008

Original Assignment

Overview

Circuit

Code

/* AnalogInput.c m.peshkin 2007-12-24 Range of input voltages on pins AN0 to AN11 is 0 to 5 volts only. This maps to 0-255 ADC values if ADC is in 8 bit mode, or to 0-1023 ADC values if ADC is in 10 bit mode. There is only one ADC, with a switch to connect it to up to 12 input pins named AN0 to AN11. After you switch inputs, wait 10uS for the ADC to settle onto the new input

  • /
  1. include <18f4520.h>
  2. DEVICE ADC=10 // set ADC to 10 bit accuracy, or it could be just 8
  3. fuses HS,NOLVP,NOWDT,NOPROTECT
  4. use delay(clock=20000000)

int16 value; // if you selected 10 bit accuracy, don't use an 8 bit int

void main() {

  setup_adc_ports(AN0_TO_AN3);        // Enable analog inputs; choices run from just AN0, up to AN0_TO_AN11
  setup_adc(ADC_CLOCK_INTERNAL);      // the range selected has to start with AN0
  while (TRUE) {
  
     set_adc_channel(0);     // there's only one ADC so select which input to connect to it; here pin AN0
     delay_us(10);           // wait 10uS for ADC to settle to a newly selected input
     value = read_adc();     // now you can read ADC as frequently as you like
     
     output_d(value>>2);     // on port D show only the most significant 8 of the 10 bits; tricky >> means shift right 2 bits
     output_bit(PIN_C0, (value & 2)>>1);    // display the two least significant bits; tricky & is bitwise AND
     output_bit(PIN_C1, (value & 1));
     
  delay_ms(10);
  }

}