In: Computer Science
Write a code to generate a 5 kHz signal using timer. Vary it's duty cycle. Don't use delay function.
using any language
#include <P32xxxx.h>
#include <math.h> // required to use the sine function
#define NUMPTS 64
int sine[NUMPTS], triangle[NUMPTS];
void initio(int freq) { // freq can be 5-6050 Hz
 TRISD = 0xFF00; // make the bottom 8 bits of PORT D outputs
 SPI2CONbits.ON = 0; // disable SPI to reset any previous state
 SPI2BRG = 9; // 1 MHz SPI clock
 SPI2CONbits.MSTEN = 1; // enable master mode
 SPI2CONbits.CKE = 1; // set clock-to-data timing
 SPI2CONbits.MODE16 = 1; // activate 16-bit mode
 SPI2CONbits.ON = 1; // turn SPI on
 TRISF = 0xFFFE; // make RF0 an output to control load and ce
 PORTFbits.RF0 = 1; // set RF0 = 1
 PR1 = (20e6/NUMPTS)/freq - 1; // set period register for desired wave
 // frequency
 T1CONbits.ON = 1; // turn Timer1 on
}
void initwavetables(void) {
 int i;
 for (i=0; i<NUMPTS; i++) {
 sine[i] = 2047*(sin(2*3.14159*i/NUMPTS) + 1); // 12-bit scale
 if (i<NUMPTS/2) triangle[i] = i*511/NUMPTS; // 8-bit scale
 else triangle[i] = 510-i*511/NUMPTS;
 }
}
void genwaves(void) {
 int i;
 while (1) {
 for (i=0; i<NUMPTS; i++) {
 IFS0bits.T1IF = 0; // clear timer overflow flag
 PORTFbits.RF0 = 1; // disable load while inputs are changing
 SPI2BUF = sine[i]; // send current points to the DACs
 PORTD = triangle[i];
 while (SPI2STATbits.SPIBUSY); // wait until transfer completes
 PORTFbits.RF0 = 0; // load new points into DACs
 while (!IFS0bits.T1IF); // wait until time to send next point
 }
 }
}
int main(void) {
 initio(5000);
 initwavetables();
 genwaves();
}
please upvote comment incase of any doubt