#include <xc.h>
#include <math.h>
#define _XTAL_FREQ 8000000
#define SINE_TABLE_SIZE 32
unsigned char sineTable[SINE_TABLE_SIZE];
void generateSineTable() {
for (int i = 0; i < SINE_TABLE_SIZE; i++) {
sineTable
[i
] = (unsigned char
)((sin(2 * M_PI
* i
/ SINE_TABLE_SIZE
) + 1) * 127.5); }
}
void setPWMDuty(unsigned char dutyCycle) {
CCPR1L = dutyCycle >> 2;
CCP1CONbits.DC1B = dutyCycle & 3;
}
void setupPWM() {
TRISCbits.TRISC2 = 0;
T2CONbits.T2CKPS = 0b11;
PR2 = 199;
CCP1CONbits.CCP1M = 0b1100;
CCPR1L = 0;
CCP1CONbits.DC1B = 0;
T2CONbits.TMR2ON = 1;
}
void main() {
unsigned char index = 0;
generateSineTable();
setupPWM();
while (1) {
setPWMDuty(sineTable[index]);
index = (index + 1) % SINE_TABLE_SIZE;
__delay_ms(5);
}
}
I2luY2x1ZGUgPHhjLmg+CiNpbmNsdWRlIDxtYXRoLmg+CgojZGVmaW5lIF9YVEFMX0ZSRVEgODAwMDAwMAojZGVmaW5lIFNJTkVfVEFCTEVfU0laRSAzMgoKdW5zaWduZWQgY2hhciBzaW5lVGFibGVbU0lORV9UQUJMRV9TSVpFXTsKCnZvaWQgZ2VuZXJhdGVTaW5lVGFibGUoKSB7CiAgICBmb3IgKGludCBpID0gMDsgaSA8IFNJTkVfVEFCTEVfU0laRTsgaSsrKSB7CiAgICAgICAgc2luZVRhYmxlW2ldID0gKHVuc2lnbmVkIGNoYXIpKChzaW4oMiAqIE1fUEkgKiBpIC8gU0lORV9UQUJMRV9TSVpFKSArIDEpICogMTI3LjUpOwogICAgfQp9Cgp2b2lkIHNldFBXTUR1dHkodW5zaWduZWQgY2hhciBkdXR5Q3ljbGUpIHsKICAgIENDUFIxTCA9IGR1dHlDeWNsZSA+PiAyOwogICAgQ0NQMUNPTmJpdHMuREMxQiA9IGR1dHlDeWNsZSAmIDM7Cn0KCnZvaWQgc2V0dXBQV00oKSB7C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