Can somebody help me out with this procedure, i have to cat it over to this:
procedure SETPWM(Port:Char; PIN:byte; Value:integer);
begin
// ???
end;
I Want to use PB2 to PWM output. For the Attiny2313A. Great thanks...
One way of doing this is to check for valid port & pin combinations, then configure the appropriate timer attached to that pin:
procedure SETPWM(Port: Char; pin: byte; value: uint16);
begin
if (Port = 'B') and (pin = 2) then
begin
// configure timer 0, channel A
TCCR0A := TCCR0A or (%10 shl COM0A) or (1 shl WGM0);
TCCR0B := TCCR0B or %101;
OCR0A := byte(value);
end
else if (Port = 'A') and (pin = 5) then
begin
// configure timer 0, channel B
end
else if (Port = 'B') and (pin = 3) then
begin
// configure timer 1, channel A
end
else if (Port = 'B') and (pin = 4) then
begin
// configure timer 1, channel B
end
else
// Do nothing, or output some error
end;
This is an outline of one possible method of coding the SETPWM function. This is the bare minimum functionality, more code would be required to make this robust.
While a SETPWM procedure may seem helpful, it will always generate code to configure all four PWM pins, even if you only use a single PWM pin. Also note that you will end up with some repeated code in the different if branches.
Note that timer0 is 8 bit, while timer1 is 16 bit. This means that this generic SETPWM function has to range check the value parameter depending on which timer is used. Perhaps an unsigned type for value is more useful since the timer only works with positive or zero values.
While Arduino has made this kind of abstraction popular, it comes at the cost of larger code size and slower execution because of the extra code required for the mapping. Just think about the complication of switching off PWM on a pin. Do you just disable the OCn output to the pin, but keep the timer running? Or do you check if both OCnA and OCnB are disabled before disabling the timer? All of this logic requires extra code, which is not required if you know you only use fixed PWM pins in your project.
A general recommendation on the AVRfreaks forum is that you typically use fixed pins in a project, so just configure those pins specifically and be done.