add better delay function, optimize carry-increment

master
Yorick van Pelt 2019-01-09 14:08:33 +01:00
parent 217dc375d1
commit eaf024a58a
Signed by: yorick
GPG Key ID: D8D3CC6D951384DE
1 changed files with 27 additions and 21 deletions

View File

@ -18,28 +18,38 @@ __code uint16_t __at (_CONFIG1) __configword = _FOSC_INTOSC & _CLKOUTEN_OFF & _W
// RA5, RA4, RC2, RC3 // RA5, RA4, RC2, RC3
// 'input' pin: RC5 // 'input' pin: RC5
// Uncalibrated delay, just waits a number of for-loop iterations // microsecond delay.
void delay(uint16_t iterations) static inline void delay(uint8_t us)
{ {
uint16_t i, j; TMR1L = 0;
while(TMR1L < us);
for (i = 0; i < iterations; i++) {
// Prevent this loop from being optimized away.
//for (j = 0; j < 12; j++) {
__asm nop __endasm;
//}
}
} }
#define ADDTOUINT16(REG, LIT) __asm \
BANKSEL REG \
MOVLW LIT \
ADDWF _##REG##L, F \
CLRW \
ADDWFC _##REG##H, F \
__endasm
#define SUBFROMUINT16(REG, LIT) __asm \
BANKSEL REG \
MOVLW LIT \
SUBWF _##REG##L, F \
CLRW \
SUBWFB _##REG##H, F \
__endasm
#define PPSO_PWM1 3 #define PPSO_PWM1 3
void main(void) void main(void)
{ {
OSCCON = 0xf0; OSCCON = 0xf0;
TRISC = 0; TRISC = 0;
T1CON = 0x31; // timer1 at 1 mhz, so 1us
ANSELA = 0;
TRISA = 0;
//SLRCONC = 0; //SLRCONC = 0;
OPTION_REGbits.PSA = 1;
LED_PORT = 0; LED_PORT = 0;
PWM1CLKCON = 0x00; // From Fosc w/o prescaler PWM1CLKCON = 0x00; // From Fosc w/o prescaler
PWM1PRH = PWM1PRL = 0xFF; PWM1PRH = PWM1PRL = 0xFF; // period: 32 mhz / 65535 = 488 Hz
PWM1PH = 0; PWM1PH = 0;
PWM1DCH = PWM1DCL = 0; PWM1DCH = PWM1DCL = 0;
PWM1OF = 0; PWM1OF = 0;
@ -52,23 +62,19 @@ void main(void)
PWM1CON = 0x80; // enable, standard PWM mode, active high output PWM1CON = 0x80; // enable, standard PWM mode, active high output
RC5PPS = PPSO_PWM1; RC5PPS = PPSO_PWM1;
//PWM1OUT = 1;
while(1) { while(1) {
delay(1);
while (PWM1DCL < 0xFF || PWM1DCH < 0xFE) { while (PWM1DCL < 0xFF || PWM1DCH < 0xFE) {
if (PWM1DCL == 0xFF) PWM1DCH++; ADDTOUINT16(PWM1DC, 1);
PWM1DCL++;
PWMLD = 1; PWMLD = 1;
delay(1); delay(50);
} }
while (PWM1DCL > 0 || PWM1DCH > 0) { while (PWM1DCL > 0 || PWM1DCH > 0) {
if (PWM1DCL == 0) PWM1DCH--; SUBFROMUINT16(PWM1DC, 1);
PWM1DCL--;
PWMLD = 1; PWMLD = 1;
delay(1); delay(50);
} }
} }
} }