Until now I've been succesful in letting the motor run on various constant speeds using PWM. However, this is under constant load, which will not be the case for the final system.
If I let the motor run on a given speed I see a frequency of approximately 2000Hz on the oscilloscope for the PWM blocks. Where this frequency comes from is unclear to me. My attiny2313 uses a prescaler of 1 (TCCR0B = (1 << CS00); ), thus 8 MHz. Now I believe that a PWM block is devided by 256, as OCR0A = 255; gives a duty cycle of 100%, and OCR0A = 0; a duty cycle of 0%. Now if I multiply these numbers I find a pulsefrequency of 256 x 2000 = 512000 Hz, which is unequal to the expected 8 MHz. Is my reasoning correct here or am I missing something?
Next thing which is unclear to me is how the sequence of PWM and code is handeled.
Let's say I write
Where PD6 is the encoder which feedbacks counts per rotation. Is here the OCR0A handeled first, whereafter the pulseIn starts counting? Or after OCR0A is set to 128, the pulseIn starts counting immediatly? In what sequence is the code handeled? I have looked on google, but can't find the correct searching terms.
With the current code I get some strange oscilating behavior.
Is there some reason why you're hitting the hardware directly instead of using the Arduino Wiring runtime framework? You don't seem to be using the Arduino runtime at all. There's nothing wrong with doing that if you want, but in that case it might be more appropriate to ask for help on an AVR forum.