Skip to content

Instantly share code, notes, and snippets.

@hayview
Created October 3, 2015 03:24
Show Gist options
  • Save hayview/02461223a702338dc96e to your computer and use it in GitHub Desktop.
Save hayview/02461223a702338dc96e to your computer and use it in GitHub Desktop.
USB-CDC and HD44780 and DS18B20
#include "1wire.h"
void OW_DriveLow(void);
void OW_DriveHigh(void);
void OW_WriteBit(unsigned char OW_data_bit);
void OW_DriveLow(void)
{
OW_PIN_DIRECTION=OW_OUTPUT;
OW_WRITE_PIN=0;
}
void OW_DriveHigh(void)
{
OW_PIN_DIRECTION=OW_OUTPUT;
OW_WRITE_PIN=1;
}
void OW_WriteBit(unsigned char OW_data_bit)
{
if(OW_data_bit)
{
OW_DriveLow();
delay6MicroSecond();
OW_DriveHigh();
delay64MicroSecond();
}
else
{
OW_DriveLow();
delay60MicroSecond();
OW_DriveHigh();
delay10MicroSecond();
}
}
void OW_WriteByte(unsigned char OW_data_byte)
{
char i;
for (i=0;i<8;i++)
{
OW_WriteBit(OW_data_byte&0x01);
OW_data_byte=OW_data_byte>>1;
}
}
unsigned char OW_ReadBit(void)
{
unsigned char OW_data_bit=0;
OW_DriveLow();
delay6MicroSecond();
OW_DriveHigh();
delay9MicroSecond();
OW_PIN_DIRECTION=OW_INPUT;
OW_data_bit=OW_READ_PIN;
delay55MicroSecond();
return OW_data_bit;
}
unsigned char OW_ReadByte(void)
{
unsigned char OW_data_byte=0;
unsigned char i;
for (i=0;i<8;i++)
{
OW_data_byte=OW_data_byte>>1;
if (OW_ReadBit()==1) OW_data_byte=OW_data_byte|0x80;
}
return OW_data_byte;
}
unsigned char OW_ResetPulse(void)
{
unsigned char presence_detect;
OW_DriveLow();
delay480MicroSecond();
OW_DriveHigh();
delay70MicroSecond();
OW_PIN_DIRECTION=OW_INPUT;
if(OW_READ_PIN==0) presence_detect=1; // device present
if(OW_READ_PIN==1) presence_detect=0; // no device present
delay410MicroSecond();
OW_DriveHigh();
return presence_detect;
}
// MAXIM APPLICATION NOTE 126
#ifndef _OW_H
#define _OW_H
#include <p18cxxx.h>
#include <delays.h>
// PIN DEFINITION
#define OW_PIN_DIRECTION TRISCbits.RC2
#define OW_WRITE_PIN LATCbits.LATC2
#define OW_READ_PIN PORTCbits.RC2
#define OW_INPUT 1
#define OW_OUTPUT 0
// DELAY DEFINITION
#define delay6MicroSecond() {Delay10TCYx(7); Delay1TCY(); Delay1TCY();}
#define delay9MicroSecond() {Delay10TCYx(10); Delay1TCY(); Delay1TCY();\
Delay1TCY(); Delay1TCY(); Delay1TCY(); Delay1TCY(); Delay1TCY(); Delay1TCY();}
#define delay10MicroSecond() Delay10TCYx(12)
#define delay55MicroSecond() Delay10TCYx(66)
#define delay60MicroSecond() Delay10TCYx(72)
#define delay64MicroSecond() {Delay10TCYx(76); Delay1TCY(); Delay1TCY();\
Delay1TCY(); Delay1TCY(); Delay1TCY(); Delay1TCY(); Delay1TCY(); Delay1TCY();}
#define delay70MicroSecond() Delay10TCYx(84)
#define delay410MicroSecond(){Delay100TCYx(49); Delay10TCYx(2);}
#define delay480MicroSecond(){Delay100TCYx(57); Delay10TCYx(6);}
void OW_WriteByte(unsigned char OW_data_byte);
unsigned char OW_ReadBit(void);
unsigned char OW_ReadByte(void);
unsigned char OW_ResetPulse(void);
#endif
#ifndef DELAY_H_
#define DELAY_H_
#include <delays.h>
#define delay1MicroSecond() {Delay10TCYx(1); Delay1TCY(); Delay1TCY();}
#define delay5MicroSecond() Delay10TCYx(6)
#define delay10MicroSecond() Delay10TCYx(12)
#define delay50MicroSecond() Delay10TCYx(60)
#define delay100MicroSecond() Delay100TCYx(12)
#define delay200MicroSecond() Delay100TCYx(24)
#define delay1MiliSecond() Delay1KTCYx(12)
#define delay2MiliSecond() Delay1KTCYx(24)
#define delay5MiliSecond() Delay1KTCYx(60)
#define delay10MiliSecond() Delay10KTCYx(12)
#define delay50MiliSecond() Delay10KTCYx(60)
#define delay100MiliSecond() Delay10KTCYx(120)
#define delay200MiliSecond() Delay10KTCYx(240)
#define delay1Second() {Delay10KTCYx(240); Delay10KTCYx(240); Delay10KTCYx(240);\
Delay10KTCYx(240); Delay10KTCYx(240);}
#define delay2Second() {delay1Second(); delay1Second();}
#define delay5Second() {delay2Second(); delay2Second(); delay1Second();}
#define delay10Second() {delay5Second(); delay5Second();}
#endif
#include "ds18b20.h"
#include "1wire.h"
/*
Decimal point table - represent the floating point in integer
*/
rom unsigned int ds18b20_decimal[16]={
0,
625,
1250,
1875,
2500,
3125,
3750,
4375,
5000,
5625,
6250,
6875,
7500,
8125,
8750,
9375
};
unsigned char DS18B20_Init(void);
unsigned char DS18B20_Init(void)
{
if(OW_ResetPulse()) return DS18B20_PRESENT;
else return DS18B20_NO_DEVICE;
}
unsigned int DS18B20_ReadTemperature(void)
{
unsigned char temp_lsb, temp_msb;
unsigned int temp=0;
if(DS18B20_Init()==DS18B20_PRESENT)
{
OW_WriteByte(DS18B20_SKIP_ROM);
OW_WriteByte(DS18B20_CONVERT_T);
while(!OW_ReadBit());
OW_ResetPulse();
OW_WriteByte(DS18B20_SKIP_ROM);
OW_WriteByte(DS18B20_READ_SCRATCHPAD);
temp_lsb=OW_ReadByte();
temp_msb=OW_ReadByte();
temp=(unsigned int)temp_msb;
temp=temp<<8;
temp=temp&0xFF00;
temp=temp+temp_lsb;
}
return temp;
}
void DS18B20_RawTempToBCD(char *temp_BCD, char *BCD_length)
{
char temp_storage[9];
char i,j,k;
char BCD_data_pointer=0;
unsigned int temp, temp_int, temp_decimal;
temp=DS18B20_ReadTemperature();
if((temp>=0x0000)&&(temp<=0x07D0)) //positive temperature range
{
temp_int=temp>>4; //remove decimal number
temp_int=temp_int&0x00FF;
temp_decimal=ds18b20_decimal[(temp&0x000F)];//obtain decimal number
}
else if((temp>=0xFC90)&&(temp<=0xFFF8)) //negative temperature range
{
temp=~temp; //reverse the 2nd complement
temp=temp+1; //change it to positive value
temp_int=temp>>4; //remove decimal number
temp_int=temp_int&0x00FF;
temp_decimal=ds18b20_decimal[(temp&0x000F)];//get the decimal number
temp_storage[BCD_data_pointer]='-';
BCD_data_pointer++; //point to new blank space to store new data
}
//calculate the size of temp_int
if(temp_int<10) j=1;
else if(temp_int>=10 && temp_int<100) j=2;
else if(temp_int>100) j=3;
//convert temp_int to bcd
for(i=(BCD_data_pointer+j-1);i>=BCD_data_pointer;i--)
{
temp_storage[i]=(temp_int%10)+0x30;
temp_int=temp_int/10;
}
BCD_data_pointer=BCD_data_pointer+j; //point to new blank space
temp_storage[BCD_data_pointer]='.'; //store the dot
//process the decimal point
for(j=(BCD_data_pointer+4);j>BCD_data_pointer;j--)
{
temp_storage[j]=(temp_decimal%10)+0x30;
temp_decimal=temp_decimal/10;
}
BCD_data_pointer=BCD_data_pointer+4;
for(k=0;k<=BCD_data_pointer;k++)
{
*temp_BCD=temp_storage[k];
temp_BCD++;
}
*temp_BCD=0;
*BCD_length=(BCD_data_pointer+1);
}
void testbuffer(char *buffer)
{
char i=0;
while(i<5)
{
*buffer=*buffer+1;
buffer++;
i++;
}
}
#ifndef _DS18B20_H
#define _DS18B20_H
#include <p18cxxx.h>
//DS18B20 ROM Command Set
#define DS18B20_SEARCH_ROM 0xF0
#define DS18B20_READ_ROM 0x33
#define DS18B20_MATCH_ROM 0x55
#define DS18B20_SKIP_ROM 0xCC
#define DS18B20_ALARM_SEARCH 0xEC
//DS18B20 Resolution Set
#define DS18B20_RESOLUTION_9_BIT 0b00011111
#define DS18B20_RESOLUTION_10_BIT 0b00111111
#define DS18B20_RESOLUTION_11_BIT 0b01011111
#define DS18B20_RESOLUTION_12_BIT 0b01111111
//DS18B20 Function Command Set
#define DS18B20_CONVERT_T 0x44
#define DS18B20_READ_SCRATCHPAD 0xBE
#define DS18B20_WRITE_SCRATCHPAD 0x4E
#define DS18B20_COPY_SCRATCHPAD 0x48
#define DS18B20_RECALL_E2 0xB8
#define DS18B20_READ_POWER_SUPPLY 0xB4
//System Status
#define DS18B20_NO_DEVICE 0x01
#define DS18B20_PRESENT 0x02
unsigned int DS18B20_ReadTemperature(void);
void DS18B20_RawTempToBCD(char *temp_BCD, char *BCD_length);
void testbuffer(char *buffer);
#endif
#include "hd44780.h"
#include "delay.h"
void HD44780_Clock(void);
void HD44780_WriteByte(char reg, char dat);
void HD44780_WriteData(char dat);
void HD44780_WriteCommand(char dat);
void HD44780_Clock(void)
{
HD44780_EN_PIN=1; // starts data read
delay50MicroSecond();
HD44780_EN_PIN=0; // starts data write
}
void HD44780_WriteByte(char reg, char dat)
{
if(reg == HD44780_REGISTER_DATA)
{
HD44780_RS_PIN=1;
}
if(reg == HD44780_REGISTER_COMMAND)
{
HD44780_RS_PIN=0;
}
HD44780_EN_PIN=0;
HD44780_DATA_PORT = dat;
HD44780_Clock();
}
void HD44780_WriteData(char dat)
{
HD44780_WriteByte(HD44780_REGISTER_DATA, dat);
delay50MicroSecond();
}
void HD44780_WriteCommand(char dat)
{
HD44780_WriteByte(HD44780_REGISTER_COMMAND, dat);
delay2MiliSecond();
}
void HD44780_Init(void)
{
//Using initialize by instruction
//After power on Wait for LCD to Initialize
delay100MiliSecond();
HD44780_initPinIO();
HD44780_EN_PIN = 0;
HD44780_RS_PIN = 0;
HD44780_DATA_PORT = 0x30;
HD44780_Clock();
delay5MiliSecond();
HD44780_DATA_PORT = 0x30;
HD44780_Clock();
delay200MicroSecond();
HD44780_DATA_PORT = 0x30;
HD44780_Clock();
delay200MicroSecond();
// FUNCTION SET | 0 0 1 1 N F * * |
// BIN_OR_BIT_MASK: { 0 0 1 1 1 0 0 0 }
HD44780_WriteCommand(0x38); // N = 1; 2 lines, F = 0; 5x8 dots
delay5MiliSecond();
// DISPLAY OFF
HD44780_WriteCommand(0x0C);
delay5MiliSecond();
// DISPLAY CLEAR
HD44780_WriteCommand(0x01);
delay5MiliSecond();
// ENTRY MODE SET | 0 0 0 0 0 1 I/D S |
// BIN_OR_BIT_MASK: { 0 0 0 0 0 1 1 0 }
HD44780_WriteCommand(0x06); // I/D = 1; Increment by 1, S = 0; No shift
delay5MiliSecond();
// HOME POSITION
HD44780_WriteCommand(0x80);
}
void HD44780_WriteROMString(const rom char *s)
{
while(*s)
{
HD44780_WriteData(*s);
s++;
}
}
void HD44780_WriteRAMString(char *s)
{
while(*s)
{
HD44780_WriteData(*s);
s++;
}
}
void HD44780_WriteNumber(long number)
{
char number_array[10]={0,0,0,0,0,0,0,0,0,0};
char i;
if(number<0)
{
number=number*-1;
HD44780_WriteROMString("-");
}
for(i=7;i>0;i--)
{
number_array[i]=number%10;
number=number/10;
}
while(number_array[i]==0) i++;
while(i<8)
{
HD44780_WriteData(number_array[i]+0x30);
i++;
}
}
void HD44780_GoToPoint(char row, char col)
{
char DDRAM_address;
if(row<1) row=1; // first position user-defined as (1,1)
if(col<=1)col=0; // but HD44780 defines as (0,0)
else col=col-1;
if(row==1) DDRAM_address = 0x80+col; // 0x80 for set DDRAM address command
if(row==2) DDRAM_address = 0x80+0x40+col; // 0x40 for second line DDRAM address
HD44780_WriteCommand(DDRAM_address);
}
void HD44780_AddCharacter(char addr, const rom char *pattern)
{
char i;
// 0x40 for set CGRAM address command
HD44780_WriteCommand(0x40 + (addr<<3)); // bit3 to bit5 for CGRAM address
// bit0 to bit2 for character pattern line position
for(i=0;i<8;i++)
{
HD44780_WriteData(pattern[i]);
}
}
void HD44780_ClearDisplay(void)
{
HD44780_WriteCommand(HD44780_CLEAR_DISPLAY);
}
void HD44780_ReturnHome(void)
{
HD44780_WriteCommand(HD44780_RETURN_HOME);
}
#ifndef HD44780_H
#define HD44780_H
#include <p18cxxx.h>
#include "delay.h"
#define HD44780_CLEAR_DISPLAY 0b00000001 //82us-1.64ms
#define HD44780_RETURN_HOME 0b00000010 //40us-1.64ms
#define HD44780_REGISTER_COMMAND 0x10
#define HD44780_REGISTER_DATA 0x01
/*
#define HD44780_clearDisplay 0b00000001 //82us-1.64ms
#define HD44780_returnHome 0b0000001* //40us-1.64ms
*/
/*
#define HD44780_EN_PINteryModeSet 0b 0 0 0 0 0 1 I/D S //40us-1.64ms
I/D = 1: Increment
I/D = 0: Decrement
S = 1: Accompanies display shift
*/
/*
#define HD44780_displayOnOff 0b 0 0 0 0 1 D C B //40us
Sets entire display (D) on/off,
cursor on/off (C), and
blinking of cursor position
character (B).
*/
/*
#define HD44780_cursorDisplayShift 0b 0 0 0 1 S/C R/L * * //40us
S/C = 1: Display shift
S/C = 0: Cursor move
R/L = 1: Shift to the right
R/L = 0: Shift to the left
*/
/*
#define HD44780_functionSet 0b 0 0 1 DL N F * * //40us
DL = 1: 8 bits, DL = 0: 4 bits
N = 1: 2 lines, N = 0: 1 line
F = 1: 5'10 dots, F = 0: 5'8 dots
*/
/*
#define HD44780_setCGRAMAddress 0b01xxxxxx //40us
#define HD44780_setDDRAMAddress 0b1xxxxxxx //40us
*/
/*
DDRAM: Display data RAM
CGRAM: Character generator RAM
ACG: CGRAM address
ADD: DDRAM address (corresponds to cursor address)
AC: Address counter used for both DD and CGRAM addresses
*/
#define HD44780_initPinIO() {TRISBbits.RB4=0; TRISBbits.RB5=0; TRISD=0x00;}
#define HD44780_EN_PIN LATBbits.LATB5
#define HD44780_RS_PIN LATBbits.LATB4
#define HD44780_DATA_PORT LATD
void HD44780_Init(void);
void HD44780_WriteROMString(const rom char *s);
void HD44780_WriteRAMString(char *s);
void HD44780_WriteNumber(long number);
void HD44780_GoToPoint(char row, char col);
void HD44780_AddCharacter(char addr, const rom char *pattern);
void HD44780_WriteData(char dat);
void HD44780_ClearDisplay(void);
void HD44780_ReturnHome(void);
#endif
/********************************************************************
FileName: main.c
Dependencies: See INCLUDES section
Processor: PIC18, PIC24, dsPIC, and PIC32 USB Microcontrollers
Hardware: This demo is natively intended to be used on Microchip USB demo
boards supported by the MCHPFSUSB stack. See release notes for
support matrix. This demo can be modified for use on other
hardware platforms.
Complier: Microchip C18 (for PIC18), XC16 (for PIC24/dsPIC), XC32 (for PIC32)
Company: Microchip Technology, Inc.
Software License Agreement:
The software supplied herewith by Microchip Technology Incorporated
(the "Company") for its PIC(R) Microcontroller is intended and
supplied to you, the Company's customer, for use solely and
exclusively on Microchip PIC 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.
********************************************************************
File Description:
Change History:
Rev Description
---- -----------------------------------------
1.0 Initial release
2.1 Updated for simplicity and to use common
coding style
2.6a Added button debouncing using Start-of-Frame packets
2.7 Updated demo to place the PIC24F devices into sleep when the
USB is in suspend.
2.7b Improvements to USBCBSendResume(), to make it easier to use.
2.9f Adding new part support
2.9j Updates to support new bootloader features (ex: app version
fetching).
********************************************************************/
/** INCLUDES *******************************************************/
#include "./USB/usb.h"
#include "./USB/usb_function_cdc.h"
#include "HardwareProfile.h"
#include "hd44780.h"
#include "delay.h"
#include "ds18b20.h"
/** CONFIGURATION **************************************************/
#if defined(PICDEM_FS_USB) // Configuration bits for PICDEM FS USB Demo Board (based on PIC18F4550)
#pragma config PLLDIV = 5 // (20 MHz crystal on PICDEM FS USB board)
#if (USB_SPEED_OPTION == USB_FULL_SPEED)
#pragma config CPUDIV = OSC1_PLL2
#else
#pragma config CPUDIV = OSC3_PLL4
#endif
#pragma config USBDIV = 2 // Clock source from 96MHz PLL/2
#pragma config FOSC = HSPLL_HS
#pragma config FCMEN = OFF
#pragma config IESO = OFF
#pragma config PWRT = OFF
#pragma config BOR = ON
#pragma config BORV = 3
#pragma config VREGEN = ON //USB Voltage Regulator
#pragma config WDT = OFF
#pragma config WDTPS = 32768
#pragma config MCLRE = ON
#pragma config LPT1OSC = OFF
#pragma config PBADEN = OFF
// #pragma config CCP2MX = ON
#pragma config STVREN = ON
#pragma config LVP = OFF
// #pragma config ICPRT = OFF // Dedicated In-Circuit Debug/Programming
#pragma config XINST = OFF // Extended Instruction Set
#pragma config CP0 = OFF
#pragma config CP1 = OFF
// #pragma config CP2 = OFF
// #pragma config CP3 = OFF
#pragma config CPB = OFF
// #pragma config CPD = OFF
#pragma config WRT0 = OFF
#pragma config WRT1 = OFF
// #pragma config WRT2 = OFF
// #pragma config WRT3 = OFF
#pragma config WRTB = OFF // Boot Block Write Protection
#pragma config WRTC = OFF
// #pragma config WRTD = OFF
#pragma config EBTR0 = OFF
#pragma config EBTR1 = OFF
// #pragma config EBTR2 = OFF
// #pragma config EBTR3 = OFF
#pragma config EBTRB = OFF
#else
#error No hardware board defined, see "HardwareProfile.h" and __FILE__
#endif
/** I N C L U D E S **********************************************************/
#include "GenericTypeDefs.h"
#include "Compiler.h"
#include "usb_config.h"
#include "USB/usb_device.h"
#include "USB/usb.h"
#include "HardwareProfile.h"
/** V A R I A B L E S ********************************************************/
#if defined(__18CXX)
#pragma udata
#endif
char USB_In_Buffer[64];
char USB_Out_Buffer[64];
char DS18B20_Buffer[9];
BOOL stringPrinted;
volatile BOOL buttonPressed;
volatile BYTE buttonCount;
/** P R I V A T E P R O T O T Y P E S ***************************************/
static void InitializeSystem(void);
void ProcessIO(void);
void USBDeviceTasks(void);
void YourHighPriorityISRCode();
void YourLowPriorityISRCode();
void USBCBSendResume(void);
void BlinkUSBStatus(void);
void UserInit(void);
/** VECTOR REMAPPING ***********************************************/
#if defined(__18CXX)
//On PIC18 devices, addresses 0x00, 0x08, and 0x18 are used for
//the reset, high priority interrupt, and low priority interrupt
//vectors. However, the Microchip HID bootloader occupies the
//0x00-0xFFF program memory region. Therefore, the bootloader code remaps
//these vectors to new locations as indicated below. This remapping is
//only necessary if you wish to be able to (optionally) program the hex file
//generated from this project with the USB bootloader.
#define REMAPPED_RESET_VECTOR_ADDRESS 0x1000
#define REMAPPED_HIGH_INTERRUPT_VECTOR_ADDRESS 0x1008
#define REMAPPED_LOW_INTERRUPT_VECTOR_ADDRESS 0x1018
#define APP_VERSION_ADDRESS 0x1016 //Fixed location, so the App FW image version can be read by the bootloader.
#define APP_SIGNATURE_ADDRESS 0x1006 //Signature location that must be kept at blaknk value (0xFFFF) in this project (has special purpose for bootloader).
//--------------------------------------------------------------------------
//Application firmware image version values, as reported to the bootloader
//firmware. These are useful so the bootloader can potentially know if the
//user is trying to program an older firmware image onto a device that
//has already been programmed with a with a newer firmware image.
//Format is APP_FIRMWARE_VERSION_MAJOR.APP_FIRMWARE_VERSION_MINOR.
//The valid minor version is from 00 to 99. Example:
//if APP_FIRMWARE_VERSION_MAJOR == 1, APP_FIRMWARE_VERSION_MINOR == 1,
//then the version is "1.01"
#define APP_FIRMWARE_VERSION_MAJOR 1 //valid values 0-255
#define APP_FIRMWARE_VERSION_MINOR 0 //valid values 0-99
//--------------------------------------------------------------------------
#pragma romdata AppVersionAndSignatureSection = APP_VERSION_ADDRESS
ROM unsigned char AppVersion[2] = {APP_FIRMWARE_VERSION_MINOR, APP_FIRMWARE_VERSION_MAJOR};
#pragma romdata AppSignatureSection = APP_SIGNATURE_ADDRESS
ROM unsigned short int SignaturePlaceholder = 0xFFFF;
#pragma code HIGH_INTERRUPT_VECTOR = 0x08
void High_ISR (void)
{
_asm goto REMAPPED_HIGH_INTERRUPT_VECTOR_ADDRESS _endasm
}
#pragma code LOW_INTERRUPT_VECTOR = 0x18
void Low_ISR (void)
{
_asm goto REMAPPED_LOW_INTERRUPT_VECTOR_ADDRESS _endasm
}
extern void _startup (void); // See c018i.c in your C18 compiler dir
#pragma code REMAPPED_RESET_VECTOR = REMAPPED_RESET_VECTOR_ADDRESS
void _reset (void)
{
_asm goto _startup _endasm
}
#pragma code REMAPPED_HIGH_INTERRUPT_VECTOR = REMAPPED_HIGH_INTERRUPT_VECTOR_ADDRESS
void Remapped_High_ISR (void)
{
_asm goto YourHighPriorityISRCode _endasm
}
#pragma code REMAPPED_LOW_INTERRUPT_VECTOR = REMAPPED_LOW_INTERRUPT_VECTOR_ADDRESS
void Remapped_Low_ISR (void)
{
_asm goto YourLowPriorityISRCode _endasm
}
#pragma code
//These are your actual interrupt handling routines.
#pragma interrupt YourHighPriorityISRCode
void YourHighPriorityISRCode()
{
//Check which interrupt flag caused the interrupt.
//Service the interrupt
//Clear the interrupt flag
//Etc.
#if defined(USB_INTERRUPT)
USBDeviceTasks();
#endif
} //This return will be a "retfie fast", since this is in a #pragma interrupt section
#pragma interruptlow YourLowPriorityISRCode
void YourLowPriorityISRCode()
{
//Check which interrupt flag caused the interrupt.
//Service the interrupt
//Clear the interrupt flag
//Etc.
} //This return will be a "retfie", since this is in a #pragma interruptlow section
#endif
/** DECLARATIONS ***************************************************/
#if defined(__18CXX)
#pragma code
#endif
/******************************************************************************
* Function: void main(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: Main program entry point.
*
* Note: None
*****************************************************************************/
#if defined(__18CXX)
void main(void)
#else
int main(void)
#endif
{
InitializeSystem();
while(1)
{
#if defined(USB_INTERRUPT)
if(USB_BUS_SENSE && (USBGetDeviceState() == DETACHED_STATE))
{
USBDeviceAttach();
}
#endif
#if defined(USB_POLLING)
// Check bus status and service USB interrupts.
USBDeviceTasks(); // Interrupt or polling method. If using polling, must call
// this function periodically. This function will take care
// of processing and responding to SETUP transactions
// (such as during the enumeration process when you first
// plug in). USB hosts require that USB devices should accept
// and process SETUP packets in a timely fashion. Therefore,
// when using polling, this function should be called
// regularly (such as once every 1.8ms or faster** [see
// inline code comments in usb_device.c for explanation when
// "or faster" applies]) In most cases, the USBDeviceTasks()
// function does not take very long to execute (ex: <100
// instruction cycles) before it returns.
#endif
// Application-specific tasks.
// Application related code may be added here, or in the ProcessIO() function.
ProcessIO();
}//end while
}//end main
/********************************************************************
* Function: static void InitializeSystem(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: InitializeSystem is a centralize initialization
* routine. All required USB initialization routines
* are called from here.
*
* User application initialization routine should
* also be called from here.
*
* Note: None
*******************************************************************/
static void InitializeSystem(void)
{
#if (defined(__18CXX) & !defined(PIC18F87J50_PIM) & !defined(PIC18F97J94_FAMILY))
ADCON1 |= 0x0F; // Default all pins to digital
#endif
// The USB specifications require that USB peripheral devices must never source
// current onto the Vbus pin. Additionally, USB peripherals should not source
// current on D+ or D- when the host/hub is not actively powering the Vbus line.
// When designing a self powered (as opposed to bus powered) USB peripheral
// device, the firmware should make sure not to turn on the USB module and D+
// or D- pull up resistor unless Vbus is actively powered. Therefore, the
// firmware needs some means to detect when Vbus is being powered by the host.
// A 5V tolerant I/O pin can be connected to Vbus (through a resistor), and
// can be used to detect when Vbus is high (host actively powering), or low
// (host is shut down or otherwise not supplying power). The USB firmware
// can then periodically poll this I/O pin to know when it is okay to turn on
// the USB module/D+/D- pull up resistor. When designing a purely bus powered
// peripheral device, it is not possible to source current on D+ or D- when the
// host is not actively providing power on Vbus. Therefore, implementing this
// bus sense feature is optional. This firmware can be made to use this bus
// sense feature by making sure "USE_USB_BUS_SENSE_IO" has been defined in the
// HardwareProfile.h file.
#if defined(USE_USB_BUS_SENSE_IO)
tris_usb_bus_sense = INPUT_PIN; // See HardwareProfile.h
#endif
// If the host PC sends a GetStatus (device) request, the firmware must respond
// and let the host know if the USB peripheral device is currently bus powered
// or self powered. See chapter 9 in the official USB specifications for details
// regarding this request. If the peripheral device is capable of being both
// self and bus powered, it should not return a hard coded value for this request.
// Instead, firmware should check if it is currently self or bus powered, and
// respond accordingly. If the hardware has been configured like demonstrated
// on the PICDEM FS USB Demo Board, an I/O pin can be polled to determine the
// currently selected power source. On the PICDEM FS USB Demo Board, "RA2"
// is used for this purpose. If using this feature, make sure "USE_SELF_POWER_SENSE_IO"
// has been defined in HardwareProfile - (platform).h, and that an appropriate I/O pin
// has been mapped to it.
#if defined(USE_SELF_POWER_SENSE_IO)
tris_self_power = INPUT_PIN; // See HardwareProfile.h
#endif
UserInit();
USBDeviceInit(); //usb_device.c. Initializes USB module SFRs and firmware
//variables to known states.
}//end InitializeSystem
/******************************************************************************
* Function: void UserInit(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: This routine should take care of all of the demo code
* initialization that is required.
*
* Note:
*
*****************************************************************************/
void UserInit(void)
{
//Initialize all of the debouncing variables
buttonCount = 0;
buttonPressed = FALSE;
stringPrinted = TRUE;
//Initialize all of the LED pins
mInitAllLEDs();
//Initialize the pushbuttons
mInitAllSwitches();
//Initialize lcd16x2
HD44780_Init();
}//end UserInit
/********************************************************************
* 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)
{
BYTE numBytesRead;
char length, j;
//Blink the LEDs according to the USB device status
BlinkUSBStatus();
// User Application USB tasks
if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;
if(buttonPressed)
{
if(stringPrinted == FALSE)
{
if(mUSBUSARTIsTxTrfReady())
{
DS18B20_RawTempToBCD(DS18B20_Buffer, &length);
DS18B20_Buffer[length]=0x0A;
putUSBUSART(DS18B20_Buffer,length+1);
stringPrinted = TRUE;
}
}
}
else
{
stringPrinted = FALSE;
}
if(USBUSARTIsTxTrfReady())
{
numBytesRead = getsUSBUSART(USB_Out_Buffer,64);
if(numBytesRead != 0)
{
BYTE i;
HD44780_ClearDisplay();
for(i=0;i<numBytesRead-1;i++)
{
if(i==17)
{
HD44780_GoToPoint(2,1);
}
HD44780_WriteData(USB_Out_Buffer[i]);
}
// putUSBUSART(USB_In_Buffer,numBytesRead);
}
}
CDCTxService();
} //end ProcessIO
/********************************************************************
* 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 HardwareProfile.h
* USBDeviceState is declared and updated in
* usb_device.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(USBSuspendControl == 1)
{
if(led_count==0)
{
mLED_1_Toggle();
if(mGetLED_1())
{
mLED_2_On();
}
else
{
mLED_2_Off();
}
}//end if
}
else
{
if(USBDeviceState == DETACHED_STATE)
{
mLED_Both_Off();
}
else if(USBDeviceState == ATTACHED_STATE)
{
mLED_Both_On();
}
else if(USBDeviceState == POWERED_STATE)
{
mLED_Only_1_On();
}
else if(USBDeviceState == DEFAULT_STATE)
{
mLED_Only_2_On();
}
else if(USBDeviceState == ADDRESS_STATE)
{
if(led_count == 0)
{
mLED_1_Toggle();
mLED_2_Off();
}//end if
}
else if(USBDeviceState == CONFIGURED_STATE)
{
if(led_count==0)
{
mLED_1_Toggle();
if(mGetLED_1())
{
mLED_2_Off();
}
else
{
mLED_2_On();
}
}//end if
}//end if(...)
}//end if(UCONbits.SUSPND...)
}//end BlinkUSBStatus
// ******************************************************************************************************
// ************** USB Callback Functions ****************************************************************
// ******************************************************************************************************
// The USB firmware stack will call the callback functions USBCBxxx() in response to certain USB related
// events. For example, if the host PC is powering down, it will stop sending out Start of Frame (SOF)
// packets to your device. In response to this, all USB devices are supposed to decrease their power
// consumption from the USB Vbus to <2.5mA* each. The USB module detects this condition (which according
// to the USB specifications is 3+ms of no bus activity/SOF packets) and then calls the USBCBSuspend()
// function. You should modify these callback functions to take appropriate actions for each of these
// conditions. For example, in the USBCBSuspend(), you may wish to add code that will decrease power
// consumption from Vbus to <2.5mA (such as by clock switching, turning off LEDs, putting the
// microcontroller to sleep, etc.). Then, in the USBCBWakeFromSuspend() function, you may then wish to
// add code that undoes the power saving things done in the USBCBSuspend() function.
// The USBCBSendResume() function is special, in that the USB stack will not automatically call this
// function. This function is meant to be called from the application firmware instead. See the
// additional comments near the function.
// Note *: The "usb_20.pdf" specs indicate 500uA or 2.5mA, depending upon device classification. However,
// the USB-IF has officially issued an ECN (engineering change notice) changing this to 2.5mA for all
// devices. Make sure to re-download the latest specifications to get all of the newest ECNs.
/******************************************************************************
* Function: void USBCBSuspend(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: Call back that is invoked when a USB suspend is detected
*
* Note: None
*****************************************************************************/
void USBCBSuspend(void)
{
//Example power saving code. Insert appropriate code here for the desired
//application behavior. If the microcontroller will be put to sleep, a
//process similar to that shown below may be used:
//ConfigureIOPinsForLowPower();
//SaveStateOfAllInterruptEnableBits();
//DisableAllInterruptEnableBits();
//EnableOnlyTheInterruptsWhichWillBeUsedToWakeTheMicro(); //should enable at least USBActivityIF as a wake source
//Sleep();
//RestoreStateOfAllPreviouslySavedInterruptEnableBits(); //Preferrably, this should be done in the USBCBWakeFromSuspend() function instead.
//RestoreIOPinsToNormal(); //Preferrably, this should be done in the USBCBWakeFromSuspend() function instead.
//IMPORTANT NOTE: Do not clear the USBActivityIF (ACTVIF) bit here. This bit is
//cleared inside the usb_device.c file. Clearing USBActivityIF here will cause
//things to not work as intended.
#if defined(__C30__) || defined __XC16__
USBSleepOnSuspend();
#endif
}
/******************************************************************************
* Function: void USBCBWakeFromSuspend(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: The host may put USB peripheral devices in low power
* suspend mode (by "sending" 3+ms of idle). Once in suspend
* mode, the host may wake the device back up by sending non-
* idle state signalling.
*
* This call back is invoked when a wakeup from USB suspend
* is detected.
*
* Note: None
*****************************************************************************/
void USBCBWakeFromSuspend(void)
{
// If clock switching or other power savings measures were taken when
// executing the USBCBSuspend() function, now would be a good time to
// switch back to normal full power run mode conditions. The host allows
// 10+ milliseconds of wakeup time, after which the device must be
// fully back to normal, and capable of receiving and processing USB
// packets. In order to do this, the USB module must receive proper
// clocking (IE: 48MHz clock must be available to SIE for full speed USB
// operation).
// Make sure the selected oscillator settings are consistent with USB
// operation before returning from this function.
}
/********************************************************************
* Function: void USBCB_SOF_Handler(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: The USB host sends out a SOF packet to full-speed
* devices every 1 ms. This interrupt may be useful
* for isochronous pipes. End designers should
* implement callback routine as necessary.
*
* Note: None
*******************************************************************/
void USBCB_SOF_Handler(void)
{
// No need to clear UIRbits.SOFIF to 0 here.
// Callback caller is already doing that.
//This is reverse logic since the pushbutton is active low
if(buttonPressed == sw2)
{
if(buttonCount != 0)
{
buttonCount--;
}
else
{
//This is reverse logic since the pushbutton is active low
buttonPressed = !sw2;
//Wait 100ms before the next press can be generated
buttonCount = 100;
}
}
else
{
if(buttonCount != 0)
{
buttonCount--;
}
}
}
/*******************************************************************
* Function: void USBCBErrorHandler(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: The purpose of this callback is mainly for
* debugging during development. Check UEIR to see
* which error causes the interrupt.
*
* Note: None
*******************************************************************/
void USBCBErrorHandler(void)
{
// No need to clear UEIR to 0 here.
// Callback caller is already doing that.
// Typically, user firmware does not need to do anything special
// if a USB error occurs. For example, if the host sends an OUT
// packet to your device, but the packet gets corrupted (ex:
// because of a bad connection, or the user unplugs the
// USB cable during the transmission) this will typically set
// one or more USB error interrupt flags. Nothing specific
// needs to be done however, since the SIE will automatically
// send a "NAK" packet to the host. In response to this, the
// host will normally retry to send the packet again, and no
// data loss occurs. The system will typically recover
// automatically, without the need for application firmware
// intervention.
// Nevertheless, this callback function is provided, such as
// for debugging purposes.
}
/*******************************************************************
* Function: void USBCBCheckOtherReq(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: When SETUP packets arrive from the host, some
* firmware must process the request and respond
* appropriately to fulfill the request. Some of
* the SETUP packets will be for standard
* USB "chapter 9" (as in, fulfilling chapter 9 of
* the official USB specifications) requests, while
* others may be specific to the USB device class
* that is being implemented. For example, a HID
* class device needs to be able to respond to
* "GET REPORT" type of requests. This
* is not a standard USB chapter 9 request, and
* therefore not handled by usb_device.c. Instead
* this request should be handled by class specific
* firmware, such as that contained in usb_function_hid.c.
*
* Note: None
*******************************************************************/
void USBCBCheckOtherReq(void)
{
USBCheckCDCRequest();
}//end
/*******************************************************************
* Function: void USBCBStdSetDscHandler(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: The USBCBStdSetDscHandler() callback function is
* called when a SETUP, bRequest: SET_DESCRIPTOR request
* arrives. Typically SET_DESCRIPTOR requests are
* not used in most applications, and it is
* optional to support this type of request.
*
* Note: None
*******************************************************************/
void USBCBStdSetDscHandler(void)
{
// Must claim session ownership if supporting this request
}//end
/*******************************************************************
* Function: void USBCBInitEP(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: This function is called when the device becomes
* initialized, which occurs after the host sends a
* SET_CONFIGURATION (wValue not = 0) request. This
* callback function should initialize the endpoints
* for the device's usage according to the current
* configuration.
*
* Note: None
*******************************************************************/
void USBCBInitEP(void)
{
//Enable the CDC data endpoints
CDCInitEP();
}
/********************************************************************
* Function: void USBCBSendResume(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: The USB specifications allow some types of USB
* peripheral devices to wake up a host PC (such
* as if it is in a low power suspend to RAM state).
* This can be a very useful feature in some
* USB applications, such as an Infrared remote
* control receiver. If a user presses the "power"
* button on a remote control, it is nice that the
* IR receiver can detect this signalling, and then
* send a USB "command" to the PC to wake up.
*
* The USBCBSendResume() "callback" function is used
* to send this special USB signalling which wakes
* up the PC. This function may be called by
* application firmware to wake up the PC. This
* function will only be able to wake up the host if
* all of the below are true:
*
* 1. The USB driver used on the host PC supports
* the remote wakeup capability.
* 2. The USB configuration descriptor indicates
* the device is remote wakeup capable in the
* bmAttributes field.
* 3. The USB host PC is currently sleeping,
* and has previously sent your device a SET
* FEATURE setup packet which "armed" the
* remote wakeup capability.
*
* If the host has not armed the device to perform remote wakeup,
* then this function will return without actually performing a
* remote wakeup sequence. This is the required behavior,
* as a USB device that has not been armed to perform remote
* wakeup must not drive remote wakeup signalling onto the bus;
* doing so will cause USB compliance testing failure.
*
* This callback should send a RESUME signal that
* has the period of 1-15ms.
*
* Note: This function does nothing and returns quickly, if the USB
* bus and host are not in a suspended condition, or are
* otherwise not in a remote wakeup ready state. Therefore, it
* is safe to optionally call this function regularly, ex:
* anytime application stimulus occurs, as the function will
* have no effect, until the bus really is in a state ready
* to accept remote wakeup.
*
* When this function executes, it may perform clock switching,
* depending upon the application specific code in
* USBCBWakeFromSuspend(). This is needed, since the USB
* bus will no longer be suspended by the time this function
* returns. Therefore, the USB module will need to be ready
* to receive traffic from the host.
*
* The modifiable section in this routine may be changed
* to meet the application needs. Current implementation
* temporary blocks other functions from executing for a
* period of ~3-15 ms depending on the core frequency.
*
* According to USB 2.0 specification section 7.1.7.7,
* "The remote wakeup device must hold the resume signaling
* for at least 1 ms but for no more than 15 ms."
* The idea here is to use a delay counter loop, using a
* common value that would work over a wide range of core
* frequencies.
* That value selected is 1800. See table below:
* ==========================================================
* Core Freq(MHz) MIP RESUME Signal Period (ms)
* ==========================================================
* 48 12 1.05
* 4 1 12.6
* ==========================================================
* * These timing could be incorrect when using code
* optimization or extended instruction mode,
* or when having other interrupts enabled.
* Make sure to verify using the MPLAB SIM's Stopwatch
* and verify the actual signal on an oscilloscope.
*******************************************************************/
void USBCBSendResume(void)
{
static WORD delay_count;
//First verify that the host has armed us to perform remote wakeup.
//It does this by sending a SET_FEATURE request to enable remote wakeup,
//usually just before the host goes to standby mode (note: it will only
//send this SET_FEATURE request if the configuration descriptor declares
//the device as remote wakeup capable, AND, if the feature is enabled
//on the host (ex: on Windows based hosts, in the device manager
//properties page for the USB device, power management tab, the
//"Allow this device to bring the computer out of standby." checkbox
//should be checked).
if(USBGetRemoteWakeupStatus() == TRUE)
{
//Verify that the USB bus is in fact suspended, before we send
//remote wakeup signalling.
if(USBIsBusSuspended() == TRUE)
{
USBMaskInterrupts();
//Clock switch to settings consistent with normal USB operation.
USBCBWakeFromSuspend();
USBSuspendControl = 0;
USBBusIsSuspended = FALSE; //So we don't execute this code again,
//until a new suspend condition is detected.
//Section 7.1.7.7 of the USB 2.0 specifications indicates a USB
//device must continuously see 5ms+ of idle on the bus, before it sends
//remote wakeup signalling. One way to be certain that this parameter
//gets met, is to add a 2ms+ blocking delay here (2ms plus at
//least 3ms from bus idle to USBIsBusSuspended() == TRUE, yeilds
//5ms+ total delay since start of idle).
delay_count = 3600U;
do
{
delay_count--;
}while(delay_count);
//Now drive the resume K-state signalling onto the USB bus.
USBResumeControl = 1; // Start RESUME signaling
delay_count = 1800U; // Set RESUME line for 1-13 ms
do
{
delay_count--;
}while(delay_count);
USBResumeControl = 0; //Finished driving resume signalling
USBUnmaskInterrupts();
}
}
}
/*******************************************************************
* Function: void USBCBEP0DataReceived(void)
*
* PreCondition: ENABLE_EP0_DATA_RECEIVED_CALLBACK must be
* defined already (in usb_config.h)
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: This function is called whenever a EP0 data
* packet is received. This gives the user (and
* thus the various class examples a way to get
* data that is received via the control endpoint.
* This function needs to be used in conjunction
* with the USBCBCheckOtherReq() function since
* the USBCBCheckOtherReq() function is the apps
* method for getting the initial control transfer
* before the data arrives.
*
* Note: None
*******************************************************************/
#if defined(ENABLE_EP0_DATA_RECEIVED_CALLBACK)
void USBCBEP0DataReceived(void)
{
}
#endif
/*******************************************************************
* Function: BOOL USER_USB_CALLBACK_EVENT_HANDLER(
* int event, void *pdata, WORD size)
*
* PreCondition: None
*
* Input: int event - the type of event
* void *pdata - pointer to the event data
* WORD size - size of the event data
*
* Output: None
*
* Side Effects: None
*
* Overview: This function is called from the USB stack to
* notify a user application that a USB event
* occured. This callback is in interrupt context
* when the USB_INTERRUPT option is selected.
*
* Note: None
*******************************************************************/
BOOL USER_USB_CALLBACK_EVENT_HANDLER(int event, void *pdata, WORD size)
{
switch( event )
{
case EVENT_TRANSFER:
//Add application specific callback task or callback function here if desired.
break;
case EVENT_SOF:
USBCB_SOF_Handler();
break;
case EVENT_SUSPEND:
USBCBSuspend();
break;
case EVENT_RESUME:
USBCBWakeFromSuspend();
break;
case EVENT_CONFIGURED:
USBCBInitEP();
break;
case EVENT_SET_DESCRIPTOR:
USBCBStdSetDscHandler();
break;
case EVENT_EP0_REQUEST:
USBCBCheckOtherReq();
break;
case EVENT_BUS_ERROR:
USBCBErrorHandler();
break;
case EVENT_TRANSFER_TERMINATED:
//Add application specific callback task or callback function here if desired.
//The EVENT_TRANSFER_TERMINATED event occurs when the host performs a CLEAR
//FEATURE (endpoint halt) request on an application endpoint which was
//previously armed (UOWN was = 1). Here would be a good place to:
//1. Determine which endpoint the transaction that just got terminated was
// on, by checking the handle value in the *pdata.
//2. Re-arm the endpoint if desired (typically would be the case for OUT
// endpoints).
break;
default:
break;
}
return TRUE;
}
/** EOF main.c *************************************************/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment