PDA

View Full Version : giai thich nay e voi


vinhlec4
02-05-2010, 11:43 AM
#include<16F648A.h>
# fuses NOLVP, NOMCLR, INTRC, NOWDT, NOPROTECT, NOCPD
# use delay (clock=4M)//4MHz clock
# DEFINE SPEED1 20 // 15 RPM
# DEFINE SPEED2 10 // 30 RPM
# DEFINE SPEED3 5 // 60 RPM
# DEFINE SPEED4 2 // 120 RPM
/*Declare Global Variables*/
int LUTBLE[4]={0X09,0X0C,0X06,0X03};
int tableindex1 = 0, tableindex2 = 0;


/*The struct below is for the pin layout*/
struct EE2A
{
int motor1_direction:1;
int motor1_speed:2;
int motor2_direction:1;
int motor2_speed:2;
int unused:2; // 2 unused pins on Port A
int motoutput1:4;// 4 outputs for motor1
int motoutput2:4;// 4 outputs for motor2
};

struct EE2A IOPort; //initialise struct for inputs
struct EE2A TrisPort; //initialise struct for outputs
#byte IOPort=0x05 //set inputs to PortA
#byte TrisPort=0x85 //Tris bits for PortA
#int_RTCC //Interrupt


void Timer0_isr()//Set the interrupt to run motor 2 when the timer overflows
{
int increase2;
// if direction is true then assign positive value for forward motion
// else assign negative value for reverse motion of motor
// tableindex2 indicates the order in which the look-up-table is run
increase2 = IOPort.motor2_direction ? 0x01 : 0xFF;
tableindex2=(tableindex2 + increase2)%4;// value of increase2 determines direction
IOPort.motoutput2=LUTBLE[tableindex2];
}


void main()
{
int stepdelay,increase1;
// set pins on PIC to corresponding variables in the program
TrisPort.motor1_direction=0b1;
TrisPort.motor2_direction=0b1;
TrisPort.motor1_speed=0b11;
TrisPort.motor2_speed=0b11;
TrisPort.motoutput1=0b0000;
TrisPort.motoutput2=0b0000;
enable_interrupts(INT_RTCC); //enable the interrupts
enable_interrupts(GLOBAL); //enable the global interrupts
IOPort.motoutput1 = IOPort.motoutput2 = LUTBLE[0]; // Both motors use the same look up table for the step sequence

while (true) /* run forever*/
{
if ((IOPort.motor2_speed)==0b00)
{
SETUP_TIMER_0(RTCC_INTERNAL|RTCC_DIV_16); //Time Delay between steps
}
if ((IOPort.motor2_speed)==0b01)
{
SETUP_TIMER_0(RTCC_INTERNAL|RTCC_DIV_32); //Time Delay between steps
}
if((IOPort.motor2_speed)==0b10)
{
SETUP_TIMER_0(RTCC_INTERNAL|RTCC_DIV_64); //Time Delay between steps
}
if((IOPort.motor2_speed)==0b11)
{
SETUP_TIMER_0(RTCC_INTERNAL|RTCC_DIV_128); //Time Delay between steps
}



//set up the speeds
if((IOPort.motor1_speed)==0b00)
{
stepdelay=SPEED1;
}
if((IOPort.motor1_speed)==0b01)
{
stepdelay=SPEED2;
}
if ((IOPort.motor1_speed)==0b10)
{
stepdelay=SPEED3;
}
if ((IOPort.motor1_speed)==0b11)
{
stepdelay=SPEED4;
}
// if direction is true then assign positive value for forward motion
// else assign negative value for reverse motion of motor
increase1= IOPort.motor1_direction ? 0x01 : 0xFF;
tableindex1=(tableindex1 + increase1)%4;
IOPort.motoutput1=LUTBLE[tableindex1];
Delay_ms(stepdelay);
}
}