Society of Robots - Robot Forum

Software => Software => Topic started by: airman00 on November 16, 2008, 07:52:23 AM

Title: Does PWM run in the background?
Post by: airman00 on November 16, 2008, 07:52:23 AM
Hello,
When I do a PWM on a pin does the PWM run in the background? Using the example below , will the LED turn on after the PWM went through 1000 pulses , or will it turn on while the PWM is doing it's 1000 pulses?

Code: [Select]
// do simultaneous pulse output on OC1A and OC1B pins with different frequencies
//OC1A will be at  50Hz for 20 seconds (1000 pulses)

// start OC1A output
pulseT1ASetFreq(50);
pulseT1ARun(1000);

LED_on;   // turn on the status LED
Title: Re: Does PWM run in the background?
Post by: mbateman on November 16, 2008, 08:33:44 AM
I'm not sure how the specific calls you reference work, but if you directly use the OCRnA settings, it will run in the background. Here is a link to my post that has some code I wrote for the Axon, but should be easy to modify for any of the atMega chips.

http://www.societyofrobots.com/robotforum/index.php?topic=5590.0

Also, typically the "1000" is would be the length of the PWM pulse, not the number of pulses.
Title: Re: Does PWM run in the background?
Post by: Half Shell on November 17, 2008, 11:17:02 PM
The unfortunate answer: depends.

Many microcontrollers have PWM modules that, when called, will take care of PWM signal generation seperate of the chip's main processes. This means signal generation does not take precious processor time! This isn't always the case though, especially when you're generating PWM on a chip that doesn't have these modules.

Look at the data sheet for your uC - the answer should be there!
Title: Re: Does PWM run in the background?
Post by: izua on November 18, 2008, 06:26:15 AM
Always check what happens in the source code: http://ccrma.stanford.edu/courses/250a-fall-2002/docs/avrlib/pulse_8c-source.html
Pulse t1a toys with the channel A of timer 1. So, it will alter the hardware's channel settings. Which should mean - in this case - that it will 'run' in the background.
Title: Re: Does PWM run in the background?
Post by: airman00 on November 18, 2008, 06:52:41 AM
Specifically on the ATmega168 there are 6 PWM channels. Does PWM on those pins run in the background?

Also what exactly am I looking for in the datasheet. What kind of phrasing?

Thanks
Title: Re: Does PWM run in the background?
Post by: creedcradle on November 18, 2008, 07:16:53 AM
Specifically on the ATmega168 there are 6 PWM channels. Does PWM on those pins run in the background?

Also what exactly am I looking for in the datasheet. What kind of phrasing?

Thanks
Actually you are referring to a multi-threading process. Say, you have the following tasks to do:

PWM1(20hz)
PWM2(30hz)
PWM3(100Khz)

Then, you can not execute this easily with a simple "bitbang" (for MCU with no built-in PWM) thus, the solution is multithreading...

Here's a good example by zer0w1ng from his home page:
http://geekzone.freehostia.com/

or visit the forum discussion
http://www.electronicslab.ph/forum/index.php?topic=1509.40

-creedcradle
Title: Re: Does PWM run in the background?
Post by: airman00 on November 18, 2008, 08:09:36 AM
Here's a good example by zer0w1ng from his home page:
http://geekzone.freehostia.com/
Where exactly is it there?

Also if I am not bit-banging and I have hardware PWM channels, then I could do PWM1 ,PWM2, PWM3 successively and it will run in the background , right?
Title: Re: Does PWM run in the background?
Post by: mbateman on November 18, 2008, 08:56:44 AM
For what you are doing on the atMega, this will effectively run in the background. It is based on hardware and uses internal timers and compare logic. You will not be able to use the accociated timers for anything else, but once set up, they will pump out a steady stream of the correct PWM on their own until you change the value of the compare register. Then they will start sending PWM of the new duty cycle. Your code can set the value and then forget it until it needs to change to a different value. The rest happens without taking cycles from your application.

Also remember that 3 pins share the same timer. This means that you have the same base period for all 3 (typically 20mS for servos), but can have separate duty cycles (pulse width) on each one.
Title: Re: Does PWM run in the background?
Post by: mbateman on November 18, 2008, 09:04:57 AM
I just noticed that you are using the atMega168. It has 2 pins on each timer instead of 3. Also, only Timer1 is 16 bit, so you will need to do some work on the clock div and OCRxx values on the 8 bit counters to get them to the right base period and pulse widths.

Also, using all 6 PWM will use up all of your timers (0,1,2) so that may cause other problems if you need timers elsewhere. You can still read them, but you should not change or reset them, and you must understand what they are doing for PWM if you intend to use those readings for anything else.
Title: Re: Does PWM run in the background?
Post by: airman00 on November 18, 2008, 09:38:37 AM
heres my application : ATmega168 that uses UART and control 6 PWM channels based on what data the UART receives.
The UART is getting data in a constant stream , now you know why I need the PWM to run in the background.
Title: Re: Does PWM run in the background?
Post by: mbateman on November 18, 2008, 10:20:29 AM
That will work, but the problem you are going to have with the atMega168 is that two of the three sets of PWM are on 8 bit timers. It is nearly impossible to get much resolution in the range you need. For example if you are trying to drive servos at appox 50Hz, and you have a 1Mz clock, you would need to use prescale of /64 to get a top value that fits in 8 bits (156). Then to get typical servo pulse widths, you would have the following settings for the OCRxx registers.
1.0 mS = 8
1.5 mS = 12
2.0 mS = 16

That gives you a total of 8 steps using integer values.

It would be much easier and get better resolution if you use a chip with enough PWM on 16-bit timers such as the atMega640.
Title: Re: Does PWM run in the background?
Post by: airman00 on November 18, 2008, 11:25:06 AM
I'm not necessarily controlling servos, rather LEDs . I would definitely want more than 8 steps - more like 256. I need PWM because I have three LEDs- Red , Green, Blue. I use PWM to change the colors.

 
value that fits in 8 bits (156)
You mean 256 , right?

So any chip you'd recommend that has 1 UART and 6 PWM channels . And I guess I would need 16 bit timers by each channel?
I'm only confused because shouldnt a 8 bit timer should have 256 resolution , right?
Title: Re: Does PWM run in the background?
Post by: mbateman on November 18, 2008, 12:17:24 PM
With PWM, you have two durations that are important. 1) The base frequency. 2) The pulse width. Using the built-in PWM functions, you use ICRx to set the base period (with respect to the system clock divided by the prescale). Then you use OCRxx to set the pulse width.

ICR = Clock freq / (base frequency * PRE * 2). This needs to fit into the size of your timer. So for an 8 bit timer, this must be less than 256.

So in my example of a 50Hz servo and a 1Mhz sys clock, you would use an /64 prescaler and an ICR setting of 156.

You would then be able to use OCRxx settings of 1 to 155 to get the full range of possible duty cycles. With a servo, only a tiny range of duty cycles is used, so your number of possible steps would be greatly reduced since most of the possible 155 settings are not within the range the servo uses.

Now for your LEDs, you probably want to use the whole range of duty cycles and don't care as much about the base freqency, so you can get the whole 255 range from each one with the 8-bit timers and it would work fine.

You could use a prescale of /64 and an ICR of 255 which with your 1MHz chip would be a base freqency of approximately 30Hz. Then use OCRxx settings of 1-254 to get the full range of duty cycles on each pin. You could also use a prescale of /8 and have a base frequency of approx 244Hz.
Title: Re: Does PWM run in the background?
Post by: dunk on November 18, 2008, 02:02:08 PM
hey Airman,
have you read this:
http://members.shaw.ca/climber/avrtimers.html (http://members.shaw.ca/climber/avrtimers.html)
it's a good starting point on AVR hardware timers and PWM.


dunk.
Title: Re: Does PWM run in the background?
Post by: airman00 on November 18, 2008, 03:52:12 PM
Quote
You could use a prescale of /64 and an ICR of 255 which with your 1MHz chip would be a base freqency of approximately 30Hz. Then use OCRxx settings of 1-254 to get the full range of duty cycles on each pin. You could also use a prescale of /8 and have a base frequency of approx 244Hz.
I am running my chip at 8mhz, so how would that affect it? It would increase the amount of "steps" in the PWM to the maximum 255 ( for 8 bit) , right?

@dunk
Thanks , I'm going to read it tonight
Title: Re: Does PWM run in the background?
Post by: mbateman on November 18, 2008, 04:26:02 PM
Basically you just need to determine which base freqency is most suited to your needs. At 8Mhz system clock, you could various ICR settings to get a full 256 resolution. To do that, use an ICR of 255, and then the following prescalers will determine your base frequency:

/1 1.953 KHz
/8 244 Hz
/64 30.5 Hz

Base Freqency = Clock Freq / (ICR * prescaler *2)

Then just use OCRxx of 1-254 to set your duty cycle.

This is all assuming you use Phase Correct PWM mode. If you use Fast PWM mode, you will get 2x those numbers for the base freqency. It sounds like you are just trying to set the intensity of the LEDs using PWM, so you can use Fast PWM without issue, I would think.
Title: Re: Does PWM run in the background?
Post by: creedcradle on November 18, 2008, 07:12:48 PM
Here's a good example by zer0w1ng from his home page:
http://geekzone.freehostia.com/
Where exactly is it there?

Also if I am not bit-banging and I have hardware PWM channels, then I could do PWM1 ,PWM2, PWM3 successively and it will run in the background , right?
My bad airman00. His page has been updated but I have his old page here :
http://www.microelektronics.com/index.php?sel=free

Quote
Tiny Threads - Tiny Multitasking Threads for Microcontrollers
by: Regulus Berdin

    * Idea based on http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html.
    * Only 1 byte RAM needed per thread.
    * Very small overhead context switching.

Limitations:

    * Maximum 254 lines per thread.
    * Thread context switching will not work within a switch block.

Usage example:

     TT_DEF(1)
     {
        TT_BEGIN(1);
        while (1)
        {
           ...
           TT_SWITCH(1);
           ...
           ...
           TT_WAIT_UNTIL(1,keypress);
        }
        TT_END(1);
     }
     
     TT_DEF(LED_TASK)
     {
         TT_BEGIN(LED_TASK);
         while (1)
         {
             LedOn();
             delay=DELAY_1_SECOND;
             TT_WAIT_UNTIL(LED_TASK,delay==0);
             LedOff();
             delay=DELAY_1_SECOND;
             TT_WAIT_UNTIL(LED_TASK,delay==0);
         }
         TT_END(LED_TASK);
     }
     
     void main(void)
     {
         ...
         ...
         while(1)
         {
             TT_SCHED(1);
             TT_SCHED(LED_TASK);
         }
     }

Download for the header file and example is on the same page.

-creedcradle
Title: Re: Does PWM run in the background?
Post by: Webbot on November 18, 2008, 08:39:02 PM
Since you're only controlling LEDs and so the PWM doesn't need to be 100% accurate then you could always use the scheduler from:
http://www.societyofrobots.com/robotforum/index.php?topic=541.0 (http://www.societyofrobots.com/robotforum/index.php?topic=541.0)

This only uses one timer and you can use the service routine to flip the port  pin on any pin - so now you can make any, or all, of your IO pins into PWM

Title: Re: Does PWM run in the background?
Post by: izua on November 18, 2008, 10:22:15 PM
I wouldn't rely on threading if the MCU is not fast enough, except maybe very slow tasks (blinking a led, sending 2400 baud data, reading a button).
Software PWM in separate threads is an easy way to ask for trouble
Title: Re: Does PWM run in the background?
Post by: creedcradle on November 18, 2008, 11:10:58 PM
Software PWM in separate threads is an easy way to ask for trouble
Yeah. This is just the same thought with what I had before. But tiny thread has magic in it.
Speed of the MCU is not a deal. Try it for yourself first. Give it a chance.  ;)

-creedlcradle
Title: Re: Does PWM run in the background?
Post by: airman00 on November 19, 2008, 06:54:26 AM
Since you're only controlling LEDs and so the PWM doesn't need to be 100% accurate then you could always use the scheduler from:
http://www.societyofrobots.com/robotforum/index.php?topic=541.0 (http://www.societyofrobots.com/robotforum/index.php?topic=541.0)

This only uses one timer and you can use the service routine to flip the port  pin on any pin - so now you can make any, or all, of your IO pins into PWM

Webbot does that service routine run in the background , and also can I run multiple PWMs at the same time using that routine.

Let me be a bit more clear about my application
I am sending packets from RF and in between each packet ( which is 4 bytes) is a 2ms delay. The receiver outputs teh UART data that it receives to the microcontroller . Now the microcontroller has 2ms in between packets to do all six PWMs at the same time. The six PWM channels are connected to two RGB LEDs, so I use PWM to dim either the R,G,or B.

@mbateman I think I understand now . I'll do some more research at it.
Thanks
Title: Re: Does PWM run in the background?
Post by: TrickyNekro on November 19, 2008, 07:26:28 AM
I don't know exactly man... But you can use timer for that...
Set timer to run as a timer not as counter, Set whatever prescaler you want
Set the compare value and finally enable the output at OSC pin...

Now, if you get a continuous stream of data why don't you just use the RX interrupt when
you are not using the PWM and get any new value...
I really did something like this with two servos and a continuous stream of data...

I had one microcontroller to collect data from photoresistors and another to
drive the servos, as a neuron system...

But you can definitely use a timer and RX buffers, simultaneously!

Best Regards,
Lefteris
Title: Re: Does PWM run in the background?
Post by: airman00 on November 20, 2008, 06:20:24 AM
But still can I run mutliple PWM at the same time using the timer?

Also , I only have 2ms between packets to do PWM on six pins . You think I will be able to do a regular software PWM ( the same type of technique used to control servos) for all six pins at the same time - I would have to do the PWM on a resolution of uS in the code , right?
Title: Re: Does PWM run in the background?
Post by: Webbot on November 20, 2008, 06:23:50 PM
Sorry for my delay in responding. Been away - and recovering from some of the nonsense that people have posted.

@izua
Quote
I wouldn't rely on threading if the MCU is not fast enough, except maybe very slow tasks (blinking a led, sending 2400 baud data, reading a button).
Software PWM in separate threads is an easy way to ask for trouble
This isn't threading - its doing stuff under interrupts. Surely you dont have a problem with that - else you must have a problem with AVRlib as it does that all that time by attaching callback methods to the timer interrupt. The post I referenced just gives a very elegant (IMHO) routine for you to be able to queue up lots of call backs to happen at certain times in the future. Also airman00s specific question was about 'blinking LEDs' so you've shot yourself in the foot anyway ( as in - 'Hey airman dont use this to blink LEDs unless you want to blink LEDs'). Perhaps you would like to explain why its asking for trouble? I use this method to PWM motors/servos (by having a timer that is interrupted quite often) and it works like a dream. So you must know something that has never happened in my real world and I'd like to know what it is. If your servo/motor control is critical then you would have an encoder anyway to help adjust it to the correct place and this would make up for the small inaccuracies of the scheduler.

@airman00 The link I gave just allows you to queue up some code that is called later on under interrupts (in the background). The scheduler code keeps track of all the items in the queue and is well optimised so that the 'next' callback is easily tracked. So on every timer interrupt it can quickly check if something needs to be called. So in the case of PWM you can queue up events to toggle the output pins where the delay between on/off is dictated by the duty cycle. So 'yes' you can do PWM on whatever IO pins you want (unless its very high frequency PWM whereby the interrupt scheduler takes longer to run than the PWM cycle time). The granularity of the scheduler depends on how often the timer interrupt happens. So, for example, if the timer interrupt only happened every 1ms then the callbacks could only happen every multiple of 1ms - not good for servos. But you can always make the timer interrupt happen more often. The number of PWM channels is dictated purely by the size of the queue and the scheduler allows you to easily allocate more memory to the queue to allow for more queued callbacks.

At the end of the day - my link showed some code that works. Whether it works for you unmodified, or needs to be (easily) changed for smaller timer intervals, the fact is that its a very useful piece of code that works very well. I 'tip my hat' to the author 'groovy9' and regret that he hasn't returned to SoR for nearly 2 years - we would all benefit from such contributors.





Title: Re: Does PWM run in the background?
Post by: airman00 on November 20, 2008, 06:36:54 PM
Thanks for all teh replies guys

Heres what I think is the easiest thing to do right now
Code: [Select]
UART on interrupt
when it isnt in an interrupt do a PWM on the pins using servo-type software or hardware timer based

From what I understand I can use one hardware timer to generate the proper PWM for six pins at the SAME time. Is this correct?
Also if I were to do PWM using the servo type software - ( set high , wait certain amount of time, set low ), would I have to do the "certain amount of time to wait" in a resolution of uS(instead of the usual mS that servos use) , so I get a better PWM , because if it were in mS the UART interrupt could disturb the PWM frequency ?Obviously the delay after the software PWM would be more than the usual 50hz that servos use. Can anyone clear this up for me?
Title: Re: Does PWM run in the background?
Post by: Webbot on November 20, 2008, 07:41:13 PM
Quote
From what I understand I can use one hardware timer to generate the proper PWM for six pins at the SAME time. Is this correct?
Yes - you can set the output high and use the scheduler to set the output low at a later date - under the tiimer interrupt in the background

Quote
would I have to do the "certain amount of time to wait" in a resolution of uS(instead of the usual mS that servos use) , so I get a better PWM
Since servos tend to work in the range 1ms to 2ms (or thereabouts depending on manufacturer) then you need a better level of control than just ms. So uS is the next best bet. But don't do this in the foreground by just wasting time in a delay loop else you will neglect all the other servos and your main loop could grind to a halt.

Using the scheduler you can say: set the output high and queue an event so that in 1.5ms I will toggle the bit low. In the meantime you get on processing other servos. So your main loop doesn't suffer from 'delays' whilst processing each servo.
Title: Re: Does PWM run in the background?
Post by: airman00 on November 20, 2008, 08:27:49 PM
But doesnt the timer interrupt interfere with the UART interrupt ? Can I establish an interrupt "hierarchy"?
Title: Re: Does PWM run in the background?
Post by: Webbot on November 20, 2008, 08:48:16 PM
It doesn't 'interfere'. They are two seperate interrupts. The mcu will call each interrupt service routine in turn. NB I'm assuming that your UART is using the standard hardware Tx/Rx interrupts - if you are using AVRlib to perform software UART on other pins then it may be different.
Title: Re: Does PWM run in the background?
Post by: airman00 on November 20, 2008, 08:53:36 PM
I mean what happens in a scenario when the timer interrupt and a UART interrupt occur simultaneously , or if the UART interrupt occurs right before the timer interrupt is destined to be activated, thus screwing up the timer and the PWM.
Title: Re: Does PWM run in the background?
Post by: Webbot on November 20, 2008, 09:01:19 PM
The timer interrupt sets a hardware flag, and the UART sets a hardware flag. The mcu will call the service routine for one of them and (on return from your interrupt routine) will see that another interrupt is pending and call it. So the mcu does the prioritisation. So, as long as your interrupt routines are short, then nothing will get lost (and effects on your PWM will be brief if the UART code is called first and is quick).

If your interrupt routines are too long say: responding to a UART receive, then further 'receives' may get lost if you are processing one. So keep'em brief an all is fine.
Title: Re: Does PWM run in the background?
Post by: airman00 on November 20, 2008, 09:05:16 PM
OK thank you very much

I'll do some more research on timers and try to understand the scheduler routine. I'll be sure to be back with more questions , :P
Title: Re: Does PWM run in the background?
Post by: mbateman on November 21, 2008, 10:26:50 AM
I still think the hardware PWM is the way to go. You do have to use all three timers, but once set up, you only have to set the pulse-width setting and forget about it until you need to change it. Changing each one is just a single variable change, and 6 of those would easily fit between UART readings.
Title: Re: Does PWM run in the background?
Post by: airman00 on November 21, 2008, 11:44:35 AM
I still think the hardware PWM is the way to go. You do have to use all three timers, but once set up, you only have to set the pulse-width setting and forget about it until you need to change it. Changing each one is just a single variable change, and 6 of those would easily fit between UART readings.
I still don't understand how three timers could control PWM for 6 channels at the same time . Can someone please explain it?

Also is there an AVRlib file for PWM ?
Title: Re: Does PWM run in the background?
Post by: mbateman on November 21, 2008, 12:07:11 PM
On the atMega168, each timer has two Output Compare Registers (OCR). Those are used to independently trigger PWM waveforms on different pins based on the same timer. Here is the datasheet for the 168 http://www.atmel.com/dyn/resources/prod_documents/doc2545.pdf. Check out Chapter 14, especially figure 14.1 and section 14.5.

Here is a simplified version of what is happening...

- Timer will start at 0 and count up one unit each prescaled clock tick. When at zero, it sets all the enabled pins high.
- If timer value equals either of the OCR values, set the corresponding pin low
- If the timer value equals TOP, reset timer to zero and set all pins high

This is oversimplified, but it gives you the idea. In the PWM Phase Correct mode, it manages to do this in both directions of counting, but the concept is the same.

To initialize, you need the following steps:
- Set prescale value for counter
- Set top value for counter. This sets the total number of units that each cycle will have
- The two values above will set the base frequency for your PWM waveform
- Configure TCCRx to set the compare and WGM modes
- Set OCRxx values for each of the two pins

See my earlier post for a link to my code for the Axon. You will need to modify it since the 168 has different timer configs, but it is a place to start.
Title: Re: Does PWM run in the background?
Post by: airman00 on November 22, 2008, 04:44:21 PM
Thank you mbateman . Hardware PWM looks like the way to go.

But I also would like to understand how I would do it software-wise. I mean lets say I didn't have the ATmega168 and I was stuck with a chip that has one UART but no PWM.

Would the following code
Code: [Select]
On for 1mS
Off for 20mS
Repeat
give the same voltage as this
Code: [Select]
On for 1uS
Off for 20uS
Repeat
Title: Re: Does PWM run in the background?
Post by: Ro-Bot-X on November 22, 2008, 06:14:06 PM
Thank you mbateman . Hardware PWM looks like the way to go.

But I also would like to understand how I would do it software-wise. I mean lets say I didn't have the ATmega168 and I was stuck with a chip that has one UART but no PWM.

Would the following code
Code: [Select]
On for 1mS
Off for 20mS
Repeat
give the same voltage as this
Code: [Select]
On for 1uS
Off for 20uS
Repeat

Yes, the "voltage" will be the same, just the frequency will be a lot higher for the second variant.
Title: Re: Does PWM run in the background?
Post by: airman00 on November 22, 2008, 11:19:49 PM
So the voltage that would be outputted from the microcontroller would be 
VOUT = VIN ∙ DutyCycle
      = VIN ∙  ( TON / TS )
      = 5 V ∙ ( 1 μs / 20 μs)
      = .25 V

An LED requires at least 1.7V to light up or a minimum duty cycle of 34%. I need 255 steps of PWM(where 255 is full 5V and 1 is 1.7V )How can I calculate the proper delay thats needed?

Thanks
Title: Re: Does PWM run in the background?
Post by: mbateman on November 23, 2008, 09:57:36 AM
Your formula is correct if you are talking average voltage out, but that is not really what is happening unless you add some RC circuit to it to smooth it out. If you just connect direct, you get a square wave with voltages of either Vin or 0. In the case of the LED, it will just flicker between on and off creating the illusion of dimming. There will be some inherent delay in the time it takes for it to turn on and off, so you may have to expirament with your base frequency to find what works best.

I did a quick test and 100uS (10kHz) base period seemed to work pretty well. Then you just set the duty cycle from 0 - 100% to control the brightness. So with an 8 bit timer and TOP set to 255, you can use 1-254 for the OCRxx settings to get the full range of brightness. You can't get 10kHz out of the freqency you have, but you can play with the prescaler to get something within an order of magnitude that should work. I have to run out now, but if I get some time later, I can help you with the settings.
Title: Re: Does PWM run in the background?
Post by: airman00 on November 23, 2008, 09:59:11 AM
In the case of the LED, it will just flicker between on and off creating the illusion of dimming. There will be some inherent delay in the time it takes for it to turn on and off, so you may have to expirament with your base frequency to find what works best
So you're saying it will work , because to the human eye it seems like its dimming ?

Did an experiment and it works perfectly.

My only problem now is deriving some equation for the software to work on . I guess I would need a standard delay between PWM , any ideas on how to calculate what that delay should be? I need 255 steps.
Title: Re: Does PWM run in the background?
Post by: mbateman on November 23, 2008, 06:00:51 PM
Not sure what you mean by...
Quote
I guess I would need a standard delay between PWM , any ideas on how to calculate what that delay should be?

The delays are already handled for you by the hardware PWM. Once you get a setting with a base frequency that works for you, all you have to do is change the OCRxx settting to change the duty cycle which sets the brightness. Each step would be 1/256, so to get 50% brightness, you would set OCRxx to 128. If you are using 8 bit values for each LED, you can just set OCRxx directly from the 8 bit variable. If you want to set a certain percentage of brightness, where Pis the desired percentage of brightness (0-100), you would set OCRxx to P * 256 / 100. Remember to use a 16 bit variable to do that calculation so it doesn't overflow. The end result will be from 0-256, but the interim calculations will be well above 256.
Title: Re: Does PWM run in the background?
Post by: airman00 on November 23, 2008, 06:44:10 PM
mbateman I understand hardware PWM, I'm talking about software based PWM
Title: Re: Does PWM run in the background?
Post by: airman00 on November 27, 2008, 02:24:14 PM
hey I think I know what I can do

take existing servo controller code for an ATmega and just tweak teh code to be in uS and then I will be able to get variable dimming. Can anyone point me to some servo controller code for the ATmega? I'm reffering to servo controllers that control like 16 servos at the same time.
Title: Re: Does PWM run in the background?
Post by: Ro-Bot-X on November 27, 2008, 08:15:15 PM
You can take a look at the SSC-32 code, it's on their site. But they use SPI to multiplex the servo... Or you can look at the ServoTimeTimer1 library for Arduino, maybe it helps...
Title: Re: Does PWM run in the background?
Post by: Admin on December 06, 2008, 01:37:57 AM
Quote
Each step would be 1/256, so to get 50% brightness, you would set OCRxx to 128.
I've found that its not so linear like that . . . At 50% PWM my green Axon LED gives me ~85% brightness. I haven't a clue why its being non-linear like that . . .
Title: Re: Does PWM run in the background?
Post by: Webbot on December 06, 2008, 10:50:46 AM
Perceived intensity is not linear.

see http://en.wikipedia.org/wiki/Weber-Fechner_law (http://en.wikipedia.org/wiki/Weber-Fechner_law)
and http://en.wikipedia.org/wiki/Apparent_magnitude (http://en.wikipedia.org/wiki/Apparent_magnitude)

So you may need a logarithmic look up table. The last article would suggest that:

Perceived intensity = 2.5 log (Real Intensity)

Which would go towards explaining the result that Admin 'perceives'
Title: Re: Does PWM run in the background?
Post by: Admin on December 06, 2008, 11:02:40 AM
It was definitely exponential, x^2.5 or more would sound about right . . .

Sooooo an optical illusion? Meaning, it got brighter but my eyes couldn't detect any further brightness . . . I guess . . .
Title: Re: Does PWM run in the background?
Post by: airman00 on December 06, 2008, 11:31:57 AM
very interesting about the perceived brightness. I'll take that into account.
Title: Re: Does PWM run in the background?
Post by: airman00 on December 09, 2008, 10:48:44 PM
Perceived intensity = 2.5 log (Real Intensity)

In this equation Perceived Intensity is a number between 0 and 5. Real Intensity is measured in percentage.
So for example we give an LED a real intensity of 50%
Perceived Intensity = 2.5log(50)
                            =4.24742501

Now to convert Perceived Intensity into voltage be merely multiply by 20 - so 4.24742501 * 20 = 84.9485002  or ~85%

So that makes sense but the following does not.
Lets say I want the LED to have a perceived intensity of 20%. So I would do
20 = 20 ( 2.5log(x) )
1= 2.5log(x)
and I solve and get that x = 2.5 . That makes no sense . How can an LED light if its only receiving 2.5% intensity or .125 volts? It won't even light up at .125 volts.

Can someone explain to me where I am wrong and how to calculate how much real intensity I need for 20% perceived intensity?
 
Title: Re: Does PWM run in the background?
Post by: mbateman on December 10, 2008, 09:47:03 AM
PWM is not setting a voltage, it is setting a duty cycle. If you are thinking of average voltage, then, yes, the average is .125V. But that is not what is happening. It is getting Vcc for 2.5% of the time. During that time, it is lit. The other 97.5% of the time it is off. If your base freqency is too slow, you will actually see it turn on and off. But if you set the base frequency high enough, your eyes/brain interpret it as a dim LED.
Title: Re: Does PWM run in the background?
Post by: airman00 on December 10, 2008, 10:07:09 AM
PWM is not setting a voltage, it is setting a duty cycle. If you are thinking of average voltage, then, yes, the average is .125V. But that is not what is happening. It is getting Vcc for 2.5% of the time. During that time, it is lit. The other 97.5% of the time it is off. If your base freqency is too slow, you will actually see it turn on and off. But if you set the base frequency high enough, your eyes/brain interpret it as a dim LED.

oh I understand now. Thank you.
Title: Re: Does PWM run in the background?
Post by: airman00 on December 11, 2008, 09:47:54 PM
Just in case anyone is wondering I got the following numbers

Brightness of LED             PWM Duty Cycle       
20%                                  2.5%
40%                                  6.3%
60%                                 15.8%
80%                                 39.8%
100%                               100%

They sorta make sense, I'm going to test it now
Tested it out and it looks all right
Title: Re: Does PWM run in the background?
Post by: airman00 on December 20, 2008, 11:53:42 PM
Perceived intensity is not linear.

see http://en.wikipedia.org/wiki/Weber-Fechner_law (http://en.wikipedia.org/wiki/Weber-Fechner_law)
and http://en.wikipedia.org/wiki/Apparent_magnitude (http://en.wikipedia.org/wiki/Apparent_magnitude)

So you may need a logarithmic look up table. The last article would suggest that:

Perceived intensity = 2.5 log (Real Intensity)

Which would go towards explaining the result that Admin 'perceives'

I have a problem , different colors have different sensitivity to the human eye. That means that green might need a lower PWM value to appear at 80% than blue would have needed to appear at 80%.
Here is a graph of the sensitivity of the human eye to certain colors;
(http://www.sbk-laser.ch/Lasers/eye%20sensibility.jpg)

Is there some equation that takes into account the sensitivity of the color to the human eye?
Title: Re: Does PWM run in the background?
Post by: airman00 on December 21, 2008, 12:10:54 AM
I think I solved my own question

I would do the following steps to get an accurate PWM for all the colors
Find the forward voltages of each of the color LEDs ( they have different ones)
Then for each of the LEDs I use their forward voltage and then add on the PWM I need. Basically its "biasing" the PWM for each LED's color.

Example : Red has a forward voltage of 1.95V so the range of the PWM for red would be from 1.95 to 5V.
    However Green has a forward voltage of 3.5V so the range of the PWM would be between 3.5V and 5V.
Title: Re: Does PWM run in the background?
Post by: Kirk on December 21, 2008, 09:47:43 PM
Dear Airman,
I see that you have gotten LOTS of advice.  Some of it good and some of it not so true.
The best advice that you have gotten is to read climber's write up on timers.
I also recommend his write up on interrupts

Some Facts:
1) On the mega 168 you have 6 hardware PWM channels
After getting the timers set up, all you need to do is load a value in the OCRxx register
OCR1A=189;
OCR2B=somevariable;
2) Zero CPU time is taken with this method. The PWMs are like separate circuits
3) the 16 bit timer can be configured as an 8 bit timer if you wish
4) You can still use the timer(s) for other things
    for example a timer overflow interrupt might decrement a volatile global variable as a way of keeping time for switch debouncing or some such activity

A must have link for avr users is
http://greschenz.dyndns.org/AvrWizOnline.php
This wizard writes all your initialization code. for timers, baud rates and more!
This wizard Rocks!

Merry Christmas
Kirk

PS
Interrupt hierarchy for the 168 is in the data sheet and is not user changeable
 doc2545 Rev. 2545M–AVR–09/07 page 57
Title: Re: Does PWM run in the background?
Post by: mbateman on December 22, 2008, 11:33:06 AM
Airman, you are still confusing duty cycle and average voltage. When dealing with LEDs, forget that you ever heard of the average voltage equations. Once you have chosen the series resister values for each LED, then this is a simple on/off (digital) circuit. At no time are you running it at anything other than Vcc or 0V. The average voltage has no meaning.

My suggestion is to choose resisters for each LED such that they appear to be the same brightness on all of all them when connected to Vcc. Then you use the PWM from 0 to 100% duty cycle to determine the perceived brightness. I say, "perceived", because the LED is either on or off. You are just turning it on and off quickly enough that the human eye interprets it as dimming.  As you have already noted, this is not linear, but you have already dealt with that in the equation.
Title: Re: Does PWM run in the background?
Post by: airman00 on December 22, 2008, 12:25:54 PM
Oh I see now , :P

But how can I set it up for red, blue ,green. It should be a unique equation for each color , shouldn't it?
Title: Re: Does PWM run in the background?
Post by: Webbot on December 22, 2008, 01:01:37 PM
Oh I see now , :P

But how can I set it up for red, blue ,green. It should be a unique equation for each color , shouldn't it?


Well either as mbateman said - by having a larger value resistor for the green. Alternatively: have different PWM lookup tables for each colour. So if green is perceived as brighter then send it, say, an 80% PWM duty cycle to represent 100% brightness; whereas the red gets 100%.

Don't forget this is nothing to do with voltages - its just to do with 'brightness'. So if you can find a PWM setting for each colour that gives the same perceived brightness then you can compute the rest of the figures with the equation I gave before.

At the end of the day - how accurate does this have to be throughout the scale and for each colour? Surely its just a perception and so doesn't need to be a masterpiece of physics - after all 'my eyes' may well work differently to 'your eyes'.
Title: Re: Does PWM run in the background?
Post by: Admin on December 27, 2008, 04:18:29 AM
based on this information I updated the LED tutorial (http://www.societyofrobots.com/electronics_led_tutorial.shtml)