Note, you haven't specified, which Arduino you are using. I'm assuming a Atmega328p based Arduino (Uno, Nano, Mini) here, though the principle works with every AVR microcontroller, that has this hardware).
With analogWrite()
are are not sending data bitwise out of a pin. It configures the hardware Timer for setting that pin at a specific frequency and with a specific duty cycle. So analogWrite()
actives a totally different piece of hardware inside the microcontroller.
To do this without the Arduino function analogWrite()
, you first need to decide, which way to go:
- You can generate an interrupt through the hardware Timer and then set the wanted pin by software inside the ISR (which gives you free choice of the pin, but also introduces some jitter in the signal)
- or you can let the hardware Timer itself toggle the pin, which does not involve any software for running (that means you can only use one of the 2 pins, that are associated with the corresponding Timer, but you will get a much more stable signal)
There are lots of tutorials on the web on how to do that. A search for "arduino timer register pwm" gave me some promising results, for example this one, where they explain, how to get PWM with the Timer1 registers and a free to choose frequency. (That is a 3 part series, one part for each Timer. Part 1 for Timer 0 is here, though you might want to keep Timer 0 as it is, so that functions like delay()
and millis()
still work as normal). There are also many such questions on this site, for example this one.
Another very important source for anything hardware related is the datasheet of the corresponding microcontroller. For the Uno, Nano or Mini that is the Atmega328p, which datasheet can be found on the microchip site here (or when googling for the microcontroller name)