Hi, I am currently using PIC16F877 to control L293D for the motor. The issue is I was unable to set the time control to stop the motor when the time is up... No matter how big the value in my C programming. It will still stop less than 1sec time. Please advice. Thanks!
Below is my coding:
#ifndef __CPU_16F877__
#error "This program is tailored for PIC16F877 controller"
#endif
void DelayUs(int count)
{
int i;
int j;
for(i=0;i<count;i++)
{
for(j=0;j<500000000;j++);
//This for loop has 5 NOPs & wastes 1 uS for our PIC clock frequency of 20MHz.
}
}
void initialize_IO_ports(void)
{
//set the digital IO ports as per requirement.
TRISB = 0x01 ; //portA as input.
TRISD = 0x00 ; //portD as output.
//clear the output ports at the beginning.
PORTD = 0x00 ; //clear portD.
}
void initialize_timer1(void)
{
TMR1CS=0;
// set prescalar value of 1:8 i.e. timer1 count=8x200ns=1600nS.
T1CKPS1=1;
T1CKPS0=1;
//Refer to the datasheet for the organization of interrupts.
GIE=1; //global interrupt enabled.
PEIE=1; //peripheral interrupt enabled.
TMR1IE=1; //enable timer1 interrupt.
}
// This function loads timer_value in timer1, & enables it.
void load_timer1(int timer_value)
{
TMR1ON=0; //disable timer1 before loading the values.
TMR1IF=0; //timer1 flag cleared.
TMR1H=(0xFFFF-timer_value)>>8; //load timer1 high register.
TMR1L=0xFFFF-timer_value; //load timer1 low register.
TMR1ON=1; //enable timer1.
}
int main()
{
int motor_switch=0;
int i;
RB0 = motor_switch;
initialize_IO_ports();
initialize_timer1();
load_timer1(timer_value);
One thing I have noticed is that j, a 16-bit integer can only have a maximum value of 65535.
Code:
void DelayUs(int count)
{
int i;
int j;
for(i = 0; i < count; i++)
{
for(j = 0; j < 500000000; j++);
//This for loop has 5 NOPs & wastes 1 uS for our PIC clock frequency of 20MHz.
}
}
oh... so i should edit it to 65535 for the maximum?
void DelayUs(int count)
{
int i;
int j;
for(i = 0; i < count; i++)
{
for(j = 0; j < 65535; j++);
//This for loop has 5 NOPs & wastes 1 uS for our PIC clock frequency of 20MHz.
}
}
Thanks! I had tried with it. But nothing has changed. I did not use mplab sim to try as my lab do not have this software.
I have noticed that my output (portD) does not have any voltage flow between the PIC controller and the IC chip. I have been trying to solve this problem but no good result appear.
We cannot use "for loops" if exact time delay is required moreover in embedded designs, as we don't know the exact time a loop takes to execute.
Instead use timers to give exact delay you are wishing for.
Small doubt...you initialised timer, but not using for any specific purpose I feel.
Use this timer inside the if condition to give delay instead of the forloop.
you are using int j;
and a value of 65535 , its wrong by default if you are not specifying the compiler takes it as signed so the limit is -32768 to +32767
so either reduce the value to 32767 or use a unsigned int j;