I do not use a timer, its a steady square wave, I use a timer I see a additional falling edge all throughout the duty cycle flashing on and off of the oscilloscope. The atmega328p is supplied with Vin and using KU5021S28-HL-ND potentiometer military and commercial suitable. My LED flickers way to much. I have small code and picture.
int analogInPin = A0;
long sensorValueTimer2Pin3;
long z;
void sens(){
sensorValueTimer2Pin3 = ((analogRead(analogInPin)*249L)/1023);
}
void updateTimer(){
sens();
z = sensorValueTimer2Pin3;
OCR2B = z;
Serial.println(z);
}
void setup() {
Serial.begin(9600);
TCCR2A |= (1<<COM2A1);
TCCR2A &= ~(1<<COM2A0);
TCCR2A |= (1<<COM2B1);
TCCR2A &= ~(1<<COM2B0);
TCCR2A |= (1<<WGM21);
TCCR2A |= (1<<WGM20);
TCCR2B |= (1<<WGM22);
TCCR2B |= (1<<CS22);
TCCR2B &= ~(1<<CS21);
TCCR2B &= ~(1<<CS20);
OCR2A = 249;
TCNT2 = 0;
pinMode(analogInPin,INPUT);
pinMode(3,OUTPUT);
}
void loop() {
updateTimer();
//analogWrite(3, z);
}
analogRead returns a value between 0 and 1023. You then multiply that by 249, then divide the result by 1023. Arduino have 16-bit integers. What is, say, 1023 * 249? What happens when you jam that into a 16-bit int?
And, you are jamming it into the compare register totally asynchronously. What happens if the counter has already counted PAST the new value?
I can assure you, the counter works EXACTLY as is it supposed to....
Regards,
Ray L.
It should be 1024, not 1023. Was the first post edited? I see a 249L not 249. Later in the code I see the problems mentioned in reply #1. You started out okay, though...
Interestingly, you did a serial debug print of 'z' for example. What values were printed?
I think your saying the problem is a 4-byte pointer pointing to a 2-byte of allocated memory is overwriting some adjacent memory. Is the solution to check that the pointer and pointee data types are compatible with a type of casting. If so how would I implement one of these types of casting, Static cast, Reinterpret cast, Dynamic cast, Const cast, C-style cast.
This is as far as I have gone because of this link c++ - Regular cast vs. static_cast vs. dynamic_cast - Stack Overflow
int z = static_cast(sensorValueTimer2Pin3);
Also, when I serial print 'z' it will plus or minus 1 rapidly.
I would just map the pot reading to the OCR2B range.
void sens(){
int val = analogRead(analogInPin);
sensorValueTimer2Pin3 = map(val, 0, 1023, 0, 249);
}
If there are issues with the synchronization of the compare match duty cycle changes, that can be addressed by making the changes in an overflow interrupt.