# generating square wave using pic18f4520

#### محمد نور

Joined Dec 17, 2016
45
Hi
I'm trying to program PIC to generate two different square waves according to a switch state.
The first one is 1KHz with 0.5 duty cycle and the second is 5KHz with 0.2 duty cycle.
The first one is working but this is what I get for the second state.

And this is the code
C:
(
#include <p18F4520.h>
#include <xc.h>
#pragma config OSC=INTIO67,WDT=OFF,MCLRE=OFF
#include<Delays.h>
void main (void)
{
OSCCON=0x70;
TRISA0=1;
TRISC0=0;
while(1)
{
while(RA0==1)
{
RC0=1;
Delay100TCYx(10);
RC0=(~RC0);
Delay100TCYx(10);
}
while(RA0==0)
{
RC0=1;
Delay100TCYx(0.8);
RC0=(~RC0);
Delay100TCYx(3.2);
}
}
}
Note:TCY is machine cycle and equals to 0.5 micro Second.
Mod edit: code tags

Last edited by a moderator:

#### AlbertHall

Joined Jun 4, 2014
9,270
The argument to Delay100TCYx should be an integer value not floating point.
Try Delay10TCYx with the arguments multiplied by 10; i.e. 8 and 32.

#### spinnaker

Joined Oct 29, 2009
7,837
And much easier to use __delay_ms and __delay_us though you do have to remember to define _XTAL_FREQ

example: #define _XTAL_FREQ 16000000

I haven't checked but Delay100TCYx and similar functions are likely to have been depreciated. They are legacy functions from the hi-tech c days.

#### محمد نور

Joined Dec 17, 2016
45
The argument to Delay100TCYx should be an integer value not floating point.
Try Delay10TCYx with the arguments multiplied by 10; i.e. 8 and 32.
Thank you so much

#### spinnaker

Joined Oct 29, 2009
7,837
Are you certain RA0 is changing state? If not RC0 will never change.

#### spinnaker

Joined Oct 29, 2009
7,837
And you don't need to include #include <p18F4520.h> if you are using xc8. I am surprised it did not cause compile errors.