procoach code sketch

//
// ProCoach program for dsPIC33FJ32MC202
//

#include <libpic30.h>
#include <p33fj32mc202.h>
#include <stdio.h>
#include <math.h>

// Configuration settings
_FOSC(CSW_FSCM_OFF & FRC_PLL16); // Fosc=16x7.5MHz, Fcy=30MHz
_FWDT(WDT_OFF);                  // Watchdog timer off
_FBORPOR(MCLR_DIS);              // Disable reset pin

// Function prototypes
void setup();
unsigned int read_analog_channel(int n);

int main()
{
	// Set up digital i/o, analog input, PWM, UART and interrupt
	setup();

	// Flash LEDs on RD0 and RD1 at 1Hz for 4 seconds
	while (1)
	{
		_LATD0 = 0;
		__delay32(15000000);
		_LATD0 = 1;
		__delay32(15000000);
	}

	return 0;
}

// This function sets up digital i/o, analog input, UART
void setup()
{
	// Configure all four port D pins (RD0, RD1, RD2, RD3)
	// as digital outputs
	LATD = 0;
	TRISD = 0b1111111111110000;

	// Configure all three port C pins (RC13, RC14, RC15)
	// as digital inputs
	TRISC = 0b1111111111111111;

	// Configure AN0-AN8 as analog inputs
	TRISB = 0x01FF;      // All 9 port B pins are inputs
	ADPCFG = 0xFE00;     // Lowest 9 PORTB pins are analog inputs
	ADCON1 = 0;          // Manually clear SAMP to end sampling, start conversion
	ADCON2 = 0;          // Voltage reference from AVDD and AVSS
	ADCON3 = 0x0005;     // Manual Sample, ADCS=5 -> Tad = 3*Tcy
	ADCON1bits.ADON = 1; // Turn ADC ON

	// Set up UART
	// Default is 8 data bits, 1 stop bit, no parity bit
	U1BRG = 48;            // 38400 baud @ 30 MIPS
	U1MODEbits.UARTEN = 1; // Enable UART
	U1STAbits.UTXISEL = 1; // interrupt when TX buffer is empty
	U1STAbits.UTXEN = 1;   // Enable TX
}

// This function reads a single sample from the specified
// analog input. It should take less than 2.5us if the chip
// is running at about 30 MIPS.
// Because the dsPIC30F4011 has a 10-bit ADC, the value
// returned will be between 0 and 1023.
unsigned int read_analog_channel(int channel)
{
	ADCHS = channel;          // Select the requested channel
	ADCON1bits.SAMP = 1;      // Start sampling
	__delay32(30);            // 1us delay @ 30 MIPS
	ADCON1bits.SAMP = 0;      // Start Converting
	while (!ADCON1bits.DONE); // Should take 12 * Tad = 1.2us
	return ADCBUF0;
}

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s