I need some help on how to produce a pwm out to a certain port. From reading tutorials and other forum on this site I came across the method of using analog write and digital write + delay microseconds method. But I think I miss out on other methods to do so. I am currently searching for this as I wanted to use the pwm to control the motors of my sabertooth 2x12. I hope for the fast reply.
daisygrm:
I came across the method of using analog write and digital write + delay microseconds method.
That's the two methods. analogWrite() only works on the pins that support PWM, because those are connected to an internal timer. So that leaves toggling a pin manually. I'm not sure what other methods exist, aside from using dedicated PWM hardware.
Can also use blink without delay, and direct port manipulation.
I suppose you could also use a timer to trigger your own interrupt handler which updated the output pin.
Well, instead of just using analogwrite, I used this method which is bit-banging pulse width modulation. Is this correct? Or I missed out on something?
Any ideas how I could generate a PWM out to a certain port in arduino?
void setup()
{
pinMode(13, OUTPUT);
}
void loop()
{
digitalWrite(13, HIGH);
delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz
digitalWrite(13, LOW);
delayMicroseconds(1000 - 100);
}
void loop(){
currentTime = micros();
if ( (currentTime - previousTime)>=pulseWidth){
previousTime = previousTime + pulseWidth;
if(toggle==1){
toggle = 0;
PORTD = PORTD & B11111011; // clear bit 2
}
else {
toggle = 1;
PORTD = PORTD | B00000100; // set bit 2
}
// do other stuff while time passes
}
Could probably be done a little more efficiently.
Do you mean I have to replace the code in the original loop to the one that you have suggested or just add it on?
Isn't this a blind alley, it will only allow you to control a single channel, whereas analogWrite will give you upto six channels on an UNO, more on a mega.
Duane B