Microsecond variable Delay in MikroC

Home Forums Microcontrollers PIC Microcontroller Microsecond variable Delay in MikroC

Tagged: , ,

Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #11232
    Prasad
    Participant

    How to create “us” variable delay in MikroC

    #11234
    Ligo George
    Keymaster

    Micro second variable delays will be very difficult to create and it will not accurate too as each instructions will take a few microsecond to execute. That is why MikroC doesn’t implement this function.

    #11239
    Prasad
    Participant

    But I need to control a 180 deg servo with pic16f84a. PIC16f84a doesn’t have PWM.

    In servo motor datasheet it says that,

    1000us delay   = 0 deg

    1500us delay   = 90 deg

    2000us delay  = 180 deg

    So, how can I obtain a delay between 1000us and 2000us

     

    #11240
    Ligo George
    Keymaster

    Try like this :

    switch(angle)
    {
        case 0 : 
                PORTX.FX = 1;
                Delay_us(...);
                PORTX.FX = 0;
                Delay_us(...);
                break;
        case 1:
                PORTX.FX = 1;
                Delay_us(...);
                PORTX.FX = 0;
                Delay_us(...);
                break;
    }
    
    #11250
    Prasad
    Participant

    This method is correct for some specified angles. Because delay_us(), can’t have a variable value. It should be fixed. But I want to rotate Servo in random angles. That angle comes from some calculation.

    So the delay is in between 1000us and 2000us.

    ex

    1300, 1850 or something.

    How can I obtain that type of delay.

    #11251
    Ligo George
    Keymaster

    It is very difficult to obtain accurate variable microsecond delay function. Make the oscillator clock frequency as high as possible and you can use Delay_Cyc() in MikroC which creates delay based in clock cycle. You may also try creating your own delay function like the following (following code is not calibrated for microsecond).

    void Delay(unsigned int i)
    {
        for(;i>0;i--)
        {
        }
    }
    #11456
    Ligo George
    Keymaster

    Hi, the following variable microsecond delay functions will work with enough accuracy if you use clock 20MHz or more.
    For PIC 16F

    void Vdelay_us(unsigned time_us)
    {
      unsigned ncyc;
      ncyc = Clock_MHz()>>2;
      ncyc *= time_us>>4;
      while (ncyc--) 
      {
        asm nop;
        asm nop;
      }
    }
    

    For PIC 18F

    void Vdelay_us(unsigned time_us)
    {
      unsigned ncyc;
      ncyc = Clock_MHz()>>2;
      ncyc *= time_us>>4;
      while (ncyc--) 
      {
        asm nop;
        asm nop;
        asm nop;
      }
    }
    
Viewing 7 posts - 1 through 7 (of 7 total)
  • You must be logged in to reply to this topic.
>