📄 sqwave.c
字号:
#include "config.h"
#include "serial.c"
#include "serio.c"
#if defined(__18CXX)
void my_gets (char *s);
//return a string from the console
void my_gets (char *s){
char c;
do {
c = getche();
*s = c;
s++;
} while (c != '\r');
}
#endif
// generates a square wave using timer 2 and the CCP module
void main(void){
unsigned int i;
serial_init(95,1); // 19200 in HSPLL mode, crystal = 7.3728 MHz
if (POR == 0){ // bit 2 in RCON register, cleared to 0 on power-up reset
POR = 1; // setting to bit to 1 means that will remain a '1' for MCLR reset
printf("Power-on reset has occurred.");
pcrlf();
}
if (TO == 0) {
SWDTEN = 0; // disable watchdog timer
printf("Watchdog timer reset has occurred, press reset to recover.\n");
pcrlf();
while(1);
}
SWDTEN = 1; // enable watchdog timer
// configure timer 2
// post scale of 1
TOUTPS3 = 0; TOUTPS2 = 0; TOUTPS1 = 0; TOUTPS0 = 0;
// pre scale of 4
T2CKPS1 = 0; T2CKPS0 = 1;
// start timer 2
TMR2ON = 1 ;
// set up PWM
PR2 = 255; // set timer2 PR register
CCPR1L = (255 >> 1); // 50% duty cycle
bitclr(CCP1CON, 5);
bitclr(CCP1CON, 4);
// set CCP1 output
TRISC2 = 0;
// PWM Mode
bitset(CCP1CON, 3);
bitset(CCP1CON, 2);
while(1) {
printf ("Enter PR2 value: ");
#if defined(HI_TECH_C)
scanf("%d",&i);
#endif
#if defined(__18CXX)
{// MCC18 does not have scanf, just get string from console, use atoi
char buf[30];
my_gets(buf); // get a string from console
i = atoi(buf); // convert string to integer
}
#endif
pcrlf();
printf ("New PR2 value is %d ",i);
pcrlf();
PR2 = i ;
CCPR1L = i >> 1;
printf ("Enter prescale (1,4,16): ");
#if defined(HI_TECH_C)
scanf("%d",&i);
#endif
#if defined(__18CXX)
{// MCC18 does not have scanf, just get string from console, use atoi
char buf[30];
my_gets(buf); // get a string from console
i = atoi(buf); // convert string to integer
}
#endif
pcrlf();
if (i==1) {
// pre scale of 1
T2CKPS1 = 0; T2CKPS0 = 0;
}
if (i==4) {
// pre scale of 4
T2CKPS1 = 0; T2CKPS0 = 1;
}
if (i==16) {
// pre scale of 16
T2CKPS1 = 1;
// T2CKPS0 is a don't care
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -