Advertisement
DrAungWinHtut

adc.c

Jul 12th, 2023
1,038
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.03 KB | None | 0 0
  1. #include <xc.h>
  2. #include <stdint.h>
  3.  
  4. // Function prototypes
  5. void ADC_Init();
  6. uint16_t ADC_Read(uint8_t channel);
  7.  
  8. void main(void) {
  9.     // Initialize ADC
  10.     ADC_Init();
  11.  
  12.     while (1) {
  13.         // Read analog input from channel 0
  14.         uint16_t adcValue = ADC_Read(0);
  15.  
  16.         // Process the ADC value as needed
  17.         // ...
  18.  
  19.         // Delay between consecutive readings
  20.         __delay_ms(500);
  21.     }
  22.  
  23.     return;
  24. }
  25.  
  26. void ADC_Init() {
  27.     // Configure ADC module
  28.     ADCON1bits.ADFM = 1;    // Right justify result
  29.     ADCON1bits.ADCS = 0b111;    // FOSC/64 as the conversion clock source
  30.     ADCON1bits.ADPREF = 0b00;   // VREF+ = AVDD, VREF- = AVSS
  31.     ADCON0bits.ADON = 1;    // Enable ADC module
  32. }
  33.  
  34. uint16_t ADC_Read(uint8_t channel) {
  35.     // Configure ADC channel
  36.     ADCON0bits.CHS = channel;
  37.  
  38.     // Start ADC conversion
  39.     ADCON0bits.ADGO = 1;
  40.  
  41.     // Wait for ADC conversion to complete
  42.     while (ADCON0bits.ADGO)
  43.         ;
  44.  
  45.     // Return the ADC result
  46.     return ((ADRESH << 8) + ADRESL);
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement