I am attempting to create a varying duty cycle PWM using the ATMega328P board. The PWM is generated by comparing the values of two lookup tables generated in MATLAB. one being a 60Hz sin wave, and the other being 2KHz Triangle wave. When the sin wave is greater than the triangle wave, the pwm output is set to high, and when it is lesser than the triangle wave, it is set to low. This creates a varying duty cycle pwm signal. In the end this signal will determine when the four switches on an H-Bridge will switch on and off.
However when measuring the output on an oscilloscope, there is an issue in which the high side of the square wave drops low inexplicably, splitting it in two. As seen below:
Oscilloscope PWM Signal of ATMega Operation
When simulated in MATLAB, this behavior doesn't occur:
Code below:
I have tried to improve/correct the boolean logic in several places
-abs(currentSIN) > abs(currentTRI)
-round(currentSIN) > round(currentTRI)
-currentSIN >= currentTRI
-SIN_Val(sincounter) > TRI_Val(tricounter)
None of these changes really helped.
I have also tried using different ports to verify there isn't a hardware issue, tried using uint8_t variables instead of bool variables, changed the frequency of the timer, and also generated new lookup tables, all of which have resulted in a similar behavior of the high part of the square wave being split in two.
You are indexing the uint8_t SIN_Val[167]
array out of range, because of the test
if(sincounter > 167) { sincounter = 0; }
which should be
if(sincounter >= 167) { sincounter = 0; }
because index 167
is illegal. This can cause the glitch that you are seeing.
You have similarly broken the array uint8_t TRI_Val[100]
with the same fault in bounds checking. It should be
if(tricounter >= 100) { tricounter = 0; }