Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

120khz square wave generation

Status
Not open for further replies.
Hey. Here is my code. Please let me know if this code is right. I have decided to use a 12Mhz crystal instead of the 7.805Mhz.

Just to recap:
I want to generate a 120Khz square wave that will last for 1ms (done by gating the RC2 pin) on RC2 when a switch connected to portD.5 is pressed.

Using the formulaes:
PWM period= [((PR2)+1)*4*Tosc*TMR2 prescalar value] and
PWM duty cycle = (CCPR1L:CCP1CON<5:4>)*Tosc*TMR2 prescalar value,

I decided to use the prescale value =1, this then gave me the following values:
PR2= 24 (0b00011000)
CCPR1L:CCP1CON<5:4> = 50 (0b0000110010)-{10 bit value}
Since CCP1CON<5:4> is the 2 LSb value = "10"--> CCP1CON="0b00101100"
therefore: CCPR1L=8 Msb="0b00001100"

CODE
------------------------------------------------------------------------------------

#include "16F877.h"
#include "DEFS_877.H"

#include "string.h"
#include <stdlib.h>
#include <stdio.h>

#use delay (clock=12000000)
#fuses HS,NOWDT,PROTECT,NOLVP,BROWNOUT,PUT
#use rs232(baud=56000,parity=N,xmit=PIN_C6,rcv=PIN_C7)

set_tris_d(0xff); //setting port d as input

void squarewave (void)
{

PR2=0b00011000; //set PWM period to 8.3333us
CCPR1L=0b00001100; //sets Duty cycle to 50%
CCP1CON=0b00101100; //Dc=50%
T2CON=0b00000100; //enables timer 2 and sets the prescalar value
set_tris_C(0x00); //output pwm to pin RC2
}


void main (void)
{
//just initailises and clears port c initially
set_tris_c(0xFF); //set port c as input
PortC=0; //clear portC

while(1)
{
if (!input(PIN_D5)) //if switch is closed/pressed
{
squarewave();
delay_ms(1); //wave on RC2 for a period of 1ms
set_tris_c(0xFF); //sets RC2 as input, so no more
//Pwm present on this pin
}
}
}
-----------------------------------------------------------------------------------

Please take a look at my code and let me know if its accurate and correct. Thanks a lot:)
 
Re your PM. I tried the above code in BoostC and it appears to work as intended. There was some problems but I think that might be just compiler differences. However, the line,

set_tris_d(0xff); //setting port d as input

will never get executed.

Mike.
 
Because execution always starts at main. I'm surprised the complier doesn't error with that line.

Mike.
 
Status
Not open for further replies.

New Articles From Microcontroller Tips

Back
Top