Skip to content

Instantly share code, notes, and snippets.

@wattnotions
Created May 25, 2014 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wattnotions/db7da120d64eab1f26d9 to your computer and use it in GitHub Desktop.
Save wattnotions/db7da120d64eab1f26d9 to your computer and use it in GitHub Desktop.
sends values read from the analog channel of a pic microcontroller over UART
#include <xc.h>
#include <stdio.h>
#include <delays.h>
#pragma config FOSC=IRC,MCLRE=OFF,WDTEN=0,LVP=OFF,BOREN=OFF
//Functions
void setup(void);
unsigned int read_analog_channel(void);
void config_usart(void);
//Variables
int value,voltage = 0;
void main(void)
{
setup();
config_usart();
while(1)
{
value = read_analog_channel();
printf("%d\n", value);
Delay10KTCYx(30);
}
}
void putch(char data) // this function is required for printf to work properly, got it from the xc8 manual
{
while (!TXIF)
continue;
TXREG = data;
}
void setup(void)
{
OSCCON = 0b01100011; //internal oscillator block, 8MHz clock speed.
ANSELbits.ANS4 = 1; // pin 3 configured as an analog input
TRISC = 0b00000000;
TRISB = 0b00000000;
ADCON0 = 0b00010000;// AN4 is the channel being looked at, analog channel currently disabled, ( less power consumption)
ADCON2 = 0b00000011;// a/d conversion clock (dedicated clock)
}
void config_usart(void)
{
TXSTAbits.TXEN = 1; // transmit enabled
TXSTAbits.SYNC = 0; // asynchronous mode
RCSTAbits.SPEN = 1; // usart enabled, tx set as output
SPBRG = 12; // baud rate = 9600
}
unsigned int read_analog_channel (void)
{
voltage = 0;
ADCON0bits.ADON = 1;
Delay1TCY();
Delay1TCY();// 8us Delay for capacitor charge
ADCON0bits.GO = 1;
while(ADCON0bits.GO); // wait for conversion to complete
voltage = ADRESH;
voltage = (voltage<<2) + (ADRESL>>6);
Delay1TCY();
return voltage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment