You are on page 1of 3

// CAN

// Yu HongYu 131229
// Arline 130850
// Date of creation: 15-04-2011
//Ecan communication for the Potentiometer
#include <p18f2580.h>
#include <ECAN.h>
#define OFF 0
#define ON 1
static void LED2(char);
static void LED3(char);
static void test(char);
static void LED2ON(void);
static void LED2OFF(void);
static void LED3ON(void);
static void LED3OFF(void);
//Program to send a Message
// Delays a multiple of 10s at 4 MHz using TMR0
void Delay_ms(int millisec)
{
char next = 0;
T0CON = 128+64+2;
// enable timer, 8 bit mode, internal clock
// prescaler divide Tmr-0 rate by 8
TMR0L = 0;
while (millisec > 0)
{
next += 125; // 125 * 8 *1 us = 1000 us
while (TMR0L != next) {; }
--millisec;
}
T0CONbits.TMR0ON=0;
}
void init(void)
{
PORTB = 0; // All OFF
TRISA = 0b11111111; // All inputs
TRISC = 0b11111111; // All inputs
TRISB = 0b00111111; // RB6,RB7,RB2 outputs
ADCON1= 0b00000000; //internal reference voltage
ADCON0= 0b00001100;
ADCON2= 0b00110001; //ADRESH
ADCON0bits.ADON=1; //Powering the ADC
}

char ADC(void)
{
ADCON0bits.GO=1; //start conversation
while (ADCON0bits.GO==1) //wait for conversion to be done
{;}
return ADRESH; //return result ADC
}
void LED2ON(void)
{
PORTBbits.RB6 = 1; // LED2ON = ON
}
void LED2OFF(void)
{
PORTBbits.RB6 = 0; // LED2OFF = ON
}
void LED3ON(void)
{
PORTBbits.RB7 = 1; // LED3ON = ON
}
void LED3OFF(void)
{
PORTBbits.RB7 = 0; // LED3OFF = ON
}
void PWM(void)
{
PR2=255; // Set the period
CCPR1L = 127; //Set the PWM duty cycle
TRISCbits.TRISC2 = 0;
T2CON = 0b00000001;
T2CONbits.TMR2ON=1;
CCP1CON = 0b000101100; // PWM operation
}
void main(void)
{
char HP;
int Result;
unsigned long id;
BYTE data[4];
BYTE dataLen;
ECAN_RX_MSG_FLAGS msgFLags;
dataLen = 3;
ECANInitialize();
init();
//ECAN_conf_modif()
//id = 127;
data[0] = 0; // For Potentiometer
data[1] = ADRESH;
data[2] = 0;
PWM();
while(1)
{
// Ecan Transmission for Potentiometer
ADC();
//CCPR1L = ADRESH; // Transmission for the Potentiometer
Result=ADRESH;
if(Result>=77)
{
LED2ON(); //Comparing the voltage(1.5V)
data[0] = 1;
data[1] = ADRESH;
}
else
{
LED2OFF();
data[0] = 0;
data[1] = ADRESH;
}
if(Result>=179)
{
LED3ON(); //Comparing the voltage(1.5V)
data[2] = 1;
data[1] = ADRESH;
}
else
{
LED3OFF();
data[2] = 0;
data[1] = ADRESH;
}
//Delay_ms(10000);
id=127;
while(!ECANSendMessage(id, data, 3, msgFLags));
Delay_ms(500);
if(!ECANReceiveMessage(&id, data, &dataLen, &msgFLags))
{
if (id == 126)
{
LED2(data[0]);
LED3(data[2]);
CCPR1L = data[1]; //Receive data for the potentiometer
}
}
}
}
void LED2(char in)
{
if (in == ON)
PORTBbits.RB6 = 1; // LED2 = ON
else
PORTBbits.RB6 = 0; // LED2 = OFF
}
void LED3(char in1)
{
if(in1 == ON)
PORTBbits.RB7 = 1; // LED3 = ON
else
PORTBbits.RB7 = 0; // LED3 = OFF
}

You might also like