Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Sending ADC data to PC via USB for pic18f4550

Status
Not open for further replies.

prongs1911

Newbie level 6
Joined
Jun 15, 2012
Messages
11
Helped
4
Reputation
8
Reaction score
4
Trophy points
1,283
Activity points
1,352
Hi,
I am trying to send data from the inbuilt ADC of pic18f4550 to PC using USB. I successfully wrote a code for ADC to send data over serial port for testing.I have also modified the USB CDC-BASIC DEMO from microchip framework to echo back the data sent from PCand I was able to send and recieve data using realterm. But I have not been able to combine both. What I tried was, I wrote the ADC part of the code in void user(void) after if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;,but i was not getting any output on Realterm.
Is this the correct approach or do I need to do something else?
Please help. I have to submit this project in another 5 days.
ADC code:
Code:
#include <p18f4550.h>
#include <delays.h>
#include <adc.h>
#include <usart.h>
#include <stdlib.h>

  #pragma config FOSC = HSPLL_HS  // 20 MHz crystal.
        #pragma config PLLDIV = 5               // Divide by 5 to provide the 96 MHz PLL with 4 MHz input.
        #pragma config CPUDIV = OSC1_PLL2 // Divide 96 MHz PLL output by 2 to get 48 MHz system clock.
        #pragma config USBDIV = 2               // "USB clock source comes from the 96 MHz PLL divided by 2."
        #pragma config FCMEN = OFF // "Fail-Safe Clock Monitor disabled."
        #pragma config IESO = OFF  // "Oscillator Switchover mode disabled."
        #pragma config PWRT = OFF  // "PWRT disabled."
        #pragma config WDT = OFF   // "HW Disabled - SW Controlled."
        #pragma config MCLRE = ON  // "MCLR pin enabled; RE3 input pin disabled."
        #pragma config BOR = ON // Brown Out Reset enabled in hardware. In case of supply voltage drop, BOR resets the device to prevent erratic CPU behavior.
        #pragma config BORV = 3 // BOR occurs at 2V (1.2V below the minimum required voltage for the HSPLL oscillator mode).
        #pragma config VREGEN   = ON       //USB Voltage Regulator
        #pragma config LVP = OFF   // Disable low voltage ICSP
        #pragma config ICPRT = OFF // Disable dedicated programming port (44-pin devices)
        #pragma config CP0 = OFF   // Disable code protection	

#define LEDPin LATDbits.LATD2 //Define LEDPin as PORT D Pin 1
#define LEDTris TRISDbits.TRISD2 //Define LEDTris as TRISD Pin 1

void main()
{
	int delay;
	unsigned char result=0;
	unsigned char lsByte=0;
	unsigned char msByte=0;
	unsigned int ADCstate = 0;

	LEDTris = 0;//Set LED Pin data direction to OUTPUT
	LEDPin = 1;//Set LED Pin
	
	ADCON1 = 0b00001110;//VSS,VDD ref. AN0 analog only
	ADCON0 = 0x00;//clear ADCON0 to select channel 0 (AN0)
	ADCON2 = 0b00001110;//ADCON2 setup: Left justified, Tacq=2Tad, Tad=64*Tosc (or Fosc/64)
	ADCON0bits.ADON = 0x01;//Enable A/D module
	OpenUSART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_ASYNCH_MODE &
	USART_EIGHT_BIT & USART_CONT_RX & USART_BRGH_LOW, 255);
	
	while(1)
	{
	switch(ADCstate)
			{
				case 0:	SetChanADC(ADC_CH0);
						ADCstate++;
				break;
				case 1:	ConvertADC();
						ADCstate++;
				break;
				case 2: if(BusyADC())
						{	break;
						}
						else
						{	ADCstate++;
							break;
						}
				case 3: lsByte = ADRESL;
						msByte = ADRESH;
						ADCstate++;
				break;
				case 4: 
							putcUSART(msByte);
						ADCstate=0;
				break;
				default: ADCstate=0;
				break;
   			}
	}
}
USB-CDC echo code:
Code:
#include "p18f4550.h"
#include "./USB/usb.h"
#include "./USB/usb_function_cdc.h"
#include "main.h"

void user(void)
{  
        BYTE numBytesRead;

        //Blink the LEDs according to the USB device status
        BlinkUSBStatus();
        // User Application USB tasks
        if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;

        if(USBUSARTIsTxTrfReady())
        {
                numBytesRead = getsUSBUSART(USB_Out_Buffer,64);
                if(numBytesRead != 0)
                {
                        BYTE i;
                  
                        for(i=0;i<numBytesRead;i++)
                        {
                                switch(USB_Out_Buffer[i])
                                {
                                        case 0x0A:
                                        case 0x0D:
                                                USB_In_Buffer[i] = USB_Out_Buffer[i];
                                                break;
                                        default:
                                                USB_In_Buffer[i] = USB_Out_Buffer[i];// + 1;
                                                break;
                                }

                        }

                        putUSBUSART(USB_In_Buffer,numBytesRead);
                }
        }

        CDCTxService();
}
 

Can no one help me? I am totally stuck. I would really appreciate some suggestions.
 

Re: Sending ADC data to PC via USB for pic18f4550 (replace your user.c with this one)

/*********************************************************************
*
* Microchip USB C18 Firmware Version 1.2
*
*********************************************************************
* FileName: user.c
* Dependencies: See INCLUDES section below
* Processor: PIC18
* Compiler: C18 3.11+
* Company: Microchip Technology, Inc.
*
* Software License Agreement
*
* The software supplied herewith by Microchip Technology Incorporated
* (the “Company”) for its PICmicro® Microcontroller is intended and
* supplied to you, the Company’s customer, for use solely and
* exclusively on Microchip PICmicro Microcontroller products. The
* software is owned by the Company and/or its supplier, and is
* protected under applicable copyright laws. All rights are reserved.
* Any use in violation of the foregoing restrictions may subject the
* user to criminal sanctions under applicable laws, as well as to
* civil liability for the breach of the terms and conditions of this
* license.
*
* THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
* WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
* TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
* IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
* CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
*
* Author Date Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Rawin Rojvanit 11/19/04 Original.
* Rawin Rojvanit 05/14/07 A few updates.
********************************************************************/

/******************************************************************************
* CDC RS-232 Emulation Tutorial Instructions:
******************************************************************************
* Refer to Application Note AN956 for explanation of the CDC class.
*
* First take a look at Exercise_Example() and study how functions are called.
*
* There are five exercises, each one has a solution in the CDC\user\solutions.
* Scroll down and look for Exercise_01,_02,_03,_04, and _05.
* Instructions on what to do is inside each function. The exercises make use
* of LEDs, general purpose pushbuttons, and the temperature sensor found on
* the PICDEM FS USB Demo Board. Excercises 1 and 4 can be used directly
* on the PIC18F87J50 FS USB Plug-In Module board, but the other exercises use
* hardware items not phsyically present (such as temperature sensor) on the
* board.
*
*****************************************************************************/

/** I N C L U D E S **********************************************************/

#include <p18cxxx.h>
#include "system\typedefs.h"
#include "system\usb\usb.h"
#include "io_cfg.h" // I/O pin mapping
#include "user\user.h"
#include "user\temperature.h"
#define sw PORTEbits.RE2
/** V A R I A B L E S ********************************************************/
#pragma udata
byte old_sw2,old_sw3;

char input_buffer[64];
char output_buffer[64];
char adc0data[9];
char adc1data[11];
unsigned int data0=1234, data1;
unsigned int d1,d2,d3,d4,x,y;

rom char welcome[]={"Full-Speed USB - CDC RS-232 Emulation Demo\r\n\r\n"};
rom char ansi_clrscr[]={"\x1b[2J"}; // ANSI Clear Screen Command

/** P R I V A T E P R O T O T Y P E S ***************************************/
void InitializeUSART(void);
void BlinkUSBStatus(void);
BOOL Switch2IsPressed(void);
BOOL Switch3IsPressed(void);
void adc(unsigned char ch);
void Exercise_Example(void);
void adcusb();
void display0();
void display1();
//void dec2ascii(unsigned int dec,unsigned char c);
void dec2ascii(unsigned int dec);
void delay_s(unsigned char d);
void delay_ms(unsigned char d);
void Exercise_01(void);
void Exercise_02(void);
void Exercise_03(void);
void Exercise_04(void);
void Exercise_05(void);

/** D E C L A R A T I O N S **************************************************/
#pragma code
void UserInit(void)
{
mInitAllLEDs();
mInitAllSwitches();
old_sw2 = sw2;

#if defined(PIC18F4550_PICDEM_FS_USB)

old_sw3 = sw3;

InitTempSensor();

#endif

InitializeUSART();

}//end UserInit

void InitializeUSART(void)
{
TRISCbits.TRISC7=1; // RX
TRISCbits.TRISC6=0; // TX
SPBRG = 0x71;
#if defined(__18F87J50)||defined(__18F86J55)|| \
defined(__18F86J50)||defined(__18F85J50)|| \
defined(__18F67J50)||defined(__18F66J55)|| \
defined(__18F66J50)||defined(__18F65J50)
SPBRGH1 = 0x02; // 0x0271 for 48MHz -> 19200 baud
#else
SPBRGH = 0x02; // 0x0271 for 48MHz -> 19200 baud
#endif
TXSTA = 0x24; // TX enable BRGH=1
RCSTA = 0x90; // continuous RX
BAUDCON = 0x08; // BRG16 = 1
}//end InitializeUSART

void putsUSART(char *data)
{
do
{ // Transmit a byte
while(!TXSTAbits.TRMT);
TXREG = *data; // Write the data byte to the USART, 8-bit mode only
} while( *data++ );
}

/******************************************************************************
* Function: void ProcessIO(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: This function is a place holder for other user routines.
* It is a mixture of both USB and non-USB tasks.
*
* Note: None
*****************************************************************************/


void ProcessIO(void)
{
BlinkUSBStatus();
// User Application USB tasks
if((usb_device_state < CONFIGURED_STATE)||(UCONbits.SUSPND==1)) return;

//Exercise_Example();
//convert(1234);
//dec2ascii(1234);
//while(1)

adcusb();

//Exercise_01();
//Exercise_02();
//Exercise_03();
//Exercise_04();
//Exercise_05();

}//end ProcessIO


/*********************************************my ADC example************************************************/

void adcusb(void)
{
TRISEbits.TRISE2=1;
if(sw==0)
{
// ADCON1=0x0e; //Configure analog pins, voltage reference and digital I/O
adc(0);
display0();

//adc(1);
//display1();
}
}
/***********************************************/
void display0()
{
if(mUSBUSARTIsTxTrfReady())
{
mUSBUSARTTxRam((byte*)adc0data,9);
}
}

/***********************************************/
void display1()
{
if(mUSBUSARTIsTxTrfReady())
{
mUSBUSARTTxRam((byte*)adc1data,11);
}
}


/***********************************************/

void adc(unsigned char ch)
{
unsigned float x,y,z,r,a,c;
ADCON1=0x0e; //Configure analog pins, voltage reference and digital I/O
if(ch==0)
{
ADCON0bits.CHS0=0; //Analog Channel_0 Select bits
ADCON0bits.CHS1=0;
ADCON0bits.CHS2=0;
ADCON0bits.CHS3=0;
}
if(ch==1)
{
ADCON0bits.CHS0=1; //Analog Channel_1 Select bits
ADCON0bits.CHS1=0;
ADCON0bits.CHS2=0;
ADCON0bits.CHS3=0;
}
ADCON2bits.ACQT0=1; //A/D Acquisition Time Select bits
ADCON2bits.ACQT1=1;
ADCON2bits.ACQT2=1;
ADCON2bits.ADCS0=1; //A/D Conversion Clock Select bits
ADCON2bits.ADCS1=0;
ADCON2bits.ADCS2=1;
ADCON2bits.ADFM=1; //Data right adjusted
ADCON0bits.ADON=1; //A/D converter module is enabled
ADCON0bits.GO=1;//A/D Conversion Status bit
while(ADCON0bits.GO==1);//Waiting for A/D conversion to complete
delay_ms(2);
y=ADRESL;
x=ADRESH;
z=256*x+y;
/*
a=z*10;
c=a*4.8828125;
r=c/50;
*/
//if(ch==0)
dec2ascii(z);
/*
if(ch==1)
dec2ascii(z,1);
*/
}

void dec2ascii(unsigned int dec)
//void dec2ascii(unsigned int dec,unsigned char c)
{
unsigned int d1,d2,d3,d4,x,y;
d1=dec/1000;
x=dec%1000;
d2=x/100;
y=x%100;
d3=y/10;
d4=y%10;
d1=d1|0x30;
d2=d2|0x30;
d3=d3|0x30;
d4=d4|0x30;
//if(c==0)
{
adc0data[0]=d1|0x30;
adc0data[1]=d2|0x30;
adc0data[2]=d3|0x30;
adc0data[3]=('.');
adc0data[4]=d4|0x30;
adc0data[5]=('°');
adc0data[6]=('C');
adc0data[7]=('\r');
//adc0data[8]=('\n');
//adc0data[7]=(' ');
adc0data[8]=0x00;
}
/*
if(c==1)
{
adc1data[0]=d1|0x30;
adc1data[1]=d2|0x30;
adc1data[2]=d3|0x30;
adc1data[3]=('.');
adc1data[4]=d4|0x30;
adc1data[5]=('%');
adc1data[6]=('r');
adc1data[7]=('H');
adc1data[8]=('\r');
adc1data[9]=('\n');
adc1data[10]=0x00;
}
*/
}


/***********************************************************/
void delay_ms(unsigned char d)
{
unsigned char j,k;
int i;
for(j=0;j<d;j++)
{
for(k=0;k<1;k++)
for(i=0;i<235;i++);
}
}
/***********************************************************/
void delay_s(unsigned char d)
{
int i,j,k;
for(j=0;j<d;j++)
{
for(k=0;k<505;k++)
for(i=0;i<549;i++);
}
}

/*************************************************************************************************************/
/*************************************************************************************************************/
/*************************************************************************************************************/
/*************************************************************************************************************/
/*************************************************************************************************************/
/*************************************************************************************************************/
/*************************************************************************************************************/
void Exercise_Example(void)
{
static byte start_up_state = 0;

if(start_up_state == 0)
{
if(Switch2IsPressed())
start_up_state++;
}
else if(start_up_state == 1)
{
if(mUSBUSARTIsTxTrfReady())
{
putrsUSBUSART(ansi_clrscr);
start_up_state++;
}
}
else if(start_up_state == 2)
{
if(mUSBUSARTIsTxTrfReady())
{
putrsUSBUSART("\rMicrochip Technology Inc., 2007\r\n");
start_up_state++;
}
}
else if(start_up_state == 3)
{
if(mUSBUSARTIsTxTrfReady())
{
putrsUSBUSART(welcome);
start_up_state++;
}
}

}//end Exercise_Example

void Exercise_01(void)
{

//void Exercise_01(void)

/* Insert code here - 3 lines */
//if(Switch2IsPressed())
{
if(mUSBUSARTIsTxTrfReady())
{
putrsUSBUSART("usb data\r\n");
}
}
/*
* Write code in this function that sends a literal null-terminated
* string of text ("Hello World!\r\n") to the PC when switch 2 is
* pressed.
*
* Useful functions:
* Switch2IsPressed() returns '1' when switch 2 is pressed.
* putrsUSBUSART(...);
*
* See examples in Exercise_Example();
*
* Remember, you must check if cdc_trf_state is ready for another
* transfer or not. When it is ready, the value will equal CDC_TX_READY,
* or use macro: mUSBUSARTIsTxTrfReady()
*/

/* Insert code here - 3 lines */

/* End */

}//end Exercise_01


rom char ex02_string[]={"Type in a string here.\r\n"};
void Exercise_02(void)
{
/*
* Write code in this function that sends a null-terminated string
* of text stored in program memory pointed to by "ex02_string" to
* the PC when switch 3 is pressed.
*
* ex02_string is declared right above this function.
*
* Useful functions:
* Switch3IsPressed() returns '1' when switch 3 is pressed.
* putrsUSBUSART(...);
*
* See examples in Exercise_Example();
*
* Remember, you must check if cdc_trf_state is ready for another
* transfer or not. When it is ready, the value will equal CDC_TX_READY,
* or use macro: mUSBUSARTIsTxTrfReady()
*/

/* Insert code here - 3 lines*/

/* End */

}//end Exercise_02

void Exercise_03(void)
{
/*
* Write code in this function that reads data from USB and
* toggles LED D4 when the data read equals ASCII character '1' (0x31)
*
* Useful functions:
* byte getsUSBUSART(char *buffer, byte len) See cdc.c for details
* mLED_4_Toggle();
*
* Use input_buffer[] to store data read from USB.
*/

/* Insert code here - 3 lines */

/* End */

}//end Exercise_03

void Exercise_04(void)
{
/*
* Before starting Exercise_04(), comment out the call to Exercise_01()
* in ProcessIO(); This function will need to check Switch2IsPressed().
*
* Write code in this function that sends the following 4 bytes of
* data: 0x30,0x31,0x32,0x33 when switch 2 is pressed.
* Note that these data is not null-terminated and is located in
* the data memory.
*
* Useful functions:
* Switch2IsPressed() returns '1' when switch 2 is pressed.
* mUSBUSARTTxRam(byte *pData, byte len) See cdc.h for details.
*
* Use output_buffer[] to store the four bytes data.
*
* Remember, you must check if cdc_trf_state is ready for another
* transfer or not. When it is ready, the value will equal CDC_TX_READY,
* or use macro: mUSBUSARTIsTxTrfReady()
*/

/* Insert code here - 7 lines */

/* End */

}//end Exercise_04

void Exercise_05(void)
{
/*
* The PICDEM Full-Speed USB Demo Board is equipped with a
* temperature sensor. See temperature.c & .h for details.
*
* All necessary functions to collect temperature data have
* been called. This function updates the data a few times
* every second. The program currently sends out the
* temperature data to the PC via UART.
*
* You can check this by hooking up a serial cable and
* set your serial port to 19200 baud, 8 bit data, 1 Stop,
* no parity.
*
* The program assumes CPU Frequency = 48 MHz to generate
* the correct SPBRG value for 19200 baud transmission.
*
* Modify the code to send the ASCII string stored in
* tempString to the PC via USB instead of UART.
*
* The temperature data is stored in tempString array in
* ASCII format and is null-terminated.
*
* Useful function:
* putsUSBUSART(...);
*
* Note: It is 'puts' and not 'putrs' to be used here.
*
* Remember, you must check if cdc_trf_state is ready for another
* transfer or not. When it is ready, the value will equal CDC_TX_READY,
* or use macro: mUSBUSARTIsTxTrfReady()
*/

static word ex05_count;

if(ex05_count == 0)
{
#if defined(PIC18F4550_PICDEM_FS_USB)
AcquireTemperature(); // Read temperature from sensor
#endif
UpdateCelsiusASCII(); // Convert to ASCII, stored in
// "tempString", See temperature.c

/* Modify the code below - 3 lines */

putsUSART(tempString);
ex05_count = 10000;

/* End */
}
else
ex05_count--;

}//end Exercise_05

/******************************************************************************
* Function: void BlinkUSBStatus(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: BlinkUSBStatus turns on and off LEDs corresponding to
* the USB device state.
*
* Note: mLED macros can be found in io_cfg.h
* usb_device_state is declared in usbmmap.c and is modified
* in usbdrv.c, usbctrltrf.c, and usb9.c
*****************************************************************************/
void BlinkUSBStatus(void)
{
static word led_count=0;

if(led_count == 0)led_count = 10000U;
led_count--;

#define mLED_Both_Off() {mLED_1_Off();mLED_2_Off();}
#define mLED_Both_On() {mLED_1_On();mLED_2_On();}
#define mLED_Only_1_On() {mLED_1_On();mLED_2_Off();}
#define mLED_Only_2_On() {mLED_1_Off();mLED_2_On();}

if(UCONbits.SUSPND == 1)
{
if(led_count==0)
{
mLED_1_Toggle();
mLED_2 = mLED_1; // Both blink at the same time
}//end if
}
else
{
if(usb_device_state == DETACHED_STATE)
{
mLED_Both_Off();
}
else if(usb_device_state == ATTACHED_STATE)
{
mLED_Both_On();
}
else if(usb_device_state == POWERED_STATE)
{
mLED_Only_1_On();
}
else if(usb_device_state == DEFAULT_STATE)
{
mLED_Only_2_On();
}
else if(usb_device_state == ADDRESS_STATE)
{
if(led_count == 0)
{
mLED_1_Toggle();
mLED_2_Off();
}//end if
}
else if(usb_device_state == CONFIGURED_STATE)
{
if(led_count==0)
{
mLED_1_Toggle();
mLED_2 = !mLED_1; // Alternate blink
}//end if
}//end if(...)
}//end if(UCONbits.SUSPND...)

}//end BlinkUSBStatus

BOOL Switch2IsPressed(void)
{
if(sw2 != old_sw2)
{
old_sw2 = sw2; // Save new value
if(sw2 == 0) // If pressed
return TRUE; // Was pressed
}//end if
return FALSE; // Was not pressed
}//end Switch2IsPressed

#if defined(PIC18F4550_PICDEM_FS_USB)
BOOL Switch3IsPressed(void)
{
if(sw3 != old_sw3)
{
old_sw3 = sw3; // Save new value
if(sw3 == 0) // If pressed
return TRUE; // Was pressed
}//end if
return FALSE; // Was not pressed
}//end Switch3IsPressed
#endif

/** EOF user.c ***************************************************************/
 

Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top