I have been looking for someway to do software pwm myself, but when i goggle, i end up with some code i don't understand, like your example.
So i tried to make a simple sketch on my Uno to do it, and it works, but maybe it will be too slow.
Anyway here is the idea:
A pwm periode is 255 long (in my example)
If you use spwm(255,1) the on loop wil use the whole period, meaning the LED will be on the whole period.
The same for spwm(0,1) the LED will be off the whole period.
But fx.; spwm(127,1) the LED wil be on half the period and off the other half, resulting in a LED dimmed to 50%.
Btw. if you use Coding Badly's core for the attiny85 you can use pwm on pin 1,2,4 , so you are only missing two.
void spwm(int freq,int spin){
// On period
for (int x=0;x<freq;x++){
digitalWrite(spin,HIGH);
}
// Off period
for(int x=0;x<(255-freq);x++){
digitalWrite(spin,LOW);
}
} //spwm
Example using spwm function
int led1=12;
int led2=8;
void setup(){
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
}
void loop(){
for (int x=0;x<254;x++){
spwm(x,led1);
delay(5);
}
for (int x=254;x>0;x--){
spwm(x,led1);
delay(5);
}
for (int x=0;x<254;x++){
spwm(x,led2);
delay(5);
}
for (int x=254;x>0;x--){
spwm(x,led2);
delay(5);
}
}
void spwm(int freq,int spin){
// On period
for (int x=0;x<freq;x++){
digitalWrite(spin,HIGH);
}
// Off period
for(int x=0;x<(255-freq);x++){
digitalWrite(spin,LOW);
}
} //spwm