.. _avr-kernel: Help! My lights are making noise! ################################# .. include:: /references.inc .. wordcount:: .. vim:ft=rst spell .. _`AVR Studio`: http://www.atmel.com/microsite/atmel_studio6/ So far, we have written simple programs that do basically one thing at a time. What if we want to do multiple things? What we need to do is ``multi-task``. Now some folks are good at this, others not so good. Fortunately, we are not going to try to help people multi-task, we are going to help our microcontroller handle more than one thing at the same (well almost) time. So, what should we do? Well, to keep things simple, let's combine our blinky light code and our buzzer code and see if we can do both in one program! I want the buzzer to sound each time the LED lights. Just to make things a bit more interesting, let's also consider that we have one more thing to do, and we want that thing to happen about 50 times per second. Phew! How do we handle all this? Timing analysis *************** Before we get into how we will make more than one thing happen at the same time, we need to do a few simple calculations. First, remember that our processor is running at 16MHz, which means that we can run on the order of 16,000,000 instructions each second - sounds like a bunch. How many instructions will each job we have defined take to complete? My bet is - not that many! Buzzer timing ============= As we saw in our work on the buzzer, we need to cause the buzzer to pulse at a rate of 4000 times per second to get a reasonable noise out of our little piezo buzzer. In thinking about this, it seems we need to flip the pin on and off at that rate to cause one full cycle of the buzzer to occur. Than means we need to toggle (compliment) the outputs at twice that rate - or 8000 times per second. Given the speed of our little chip, that means we can run about 2000 instructions before we need to toggle the buzzer pins. That sounds like more than enough! Blinky LED timing ================== This one was easy, we want the light to blink on every second or so. Once again, if we want the light to come on at one second intervals, we toggle it twice each second! Blinking the LED is basically the same as toggling the buzzer pins, only here, we toggle a single pin. Special Task ============ The last, unnamed task needs to happen 50 times per second. What it will do, we will figure out later. For now, we will simply call a procedure to do something 50 times per second. To check that we have timed this right, we will toggle a pin on the Arduino_ and check it with an oscilloscope. Summary of basic timing ======================= With all of these simple calculations in mind, it looks like we need to set up a program to call a buzzer toggle routine 8000 times per second. If we can get interrupts happening at this rate, we have a good start on our program. We need to let 8000/50 = 160 interrupts go by before we call the special task code. Finally, we need to let 4000 interrupts go by before we call the LED blink toggle code. Sounds like an interesting chunk of code to develop! Wiring the Arduino_ ******************* This experiment will involve three separate signals. We will see one, hear another, and for the third we will need an oscilloscope! Defining the pins ================= The first thing we need to do is to define how the Arduino_ will be wired. Let's collect the pin assignments into a simple include file so our code is more generic, and it is easy to rearrange pin assignments if needed. This is my ``config.h`` file: .. literalinclude:: code/avr-kernel/config.h :linenos: :caption: config.h You can see that the include for the processor is in this file meaning all we need to do is to include this file in all of our assembly language files. Everything we need will be defined through that one include! Wiring this project is simple. Just add the buzzer you used for the previous project, and we will use the onboard LED. The third task must be checked with an oscilloscope I will bring to class. Organizing our code =================== To make it easy to keep track of all the parts of this project, we will try to isolate functions in files associated with those functions. * ``main.S`` - the main program for the project (configures the chip) * ``timer.S`` - set up timer and define timer interrupt handler * ``buzz_task.S`` - buzzer task * ``led_task.S`` - LED task * ``pulse_task.S`` - special purpose task * ``config.inc`` - definitions related to the project Since we have greatly simplified our Makefile, all you need to do is get a folder set up with the provided ``Makefile`` and these six files. On to the code ************** Now that we have the basic idea of what we want to do, let's see if we can get something working. We start off by noting that we need some kind of signal that will tell us to do something every 1/8000 of a second. Last time, we saw how to set up ``Timer0`` to generate just such a signal. But we have more than one thing to do, so how does this help. A Multi-tasking kernel ====================== What we will do is set up the timer to go off 8000 times a second. We will use an interrupt handler just like we did in our last lab, but this time all we will ask the handler to do is to set a trigger variable to one and quit! Huh? Remember what our main routine was doing while we used the interrupt to blink our light? Basically, it was doing nothing. This time, we will set up our main code to do all of our real work, but we will use the trigger variable to decide what we are to do and when! Here is how it works (in "C"): .. code-block:: c int trigger = 0; // will be set to 1 by ISR ... while(1) { if(trigger == 1) { // interrupt went off // do work trigger = 0; } } Now the main loop is looking to see if the trigger signal went off. This will happen when the interrupt handler is run. We will do some work, then clear the trigger variable. The main loop will then do nothing until the next interrupt. (It seems we are back to polling here, but we will make it more interesting in a bit.) In order for this to work, whatever we intend to do when the trigger is sensed must happen fast enough that we get done before the next interrupt goes off. For our experiment, this will be no problem. Let's expand this logic a bit and take care of the buzzer first. According to our calculations, we need to trigger the buzzer every time the trigger is sensed. Easy, just call a simple routine that includes the code we showed above to swap the signals on the two pins: .. code-block:: c while(1) { if(Trigger == 1) { BuzzerTask(); Trigger = 0; } } ... void BuzzerTask() { // swap signals on defined pins } Now, we actually have a number of tasks to take care of, so we can extend this code easily to deal with those: .. code-block:: c while(1) { if(trigger == 1){ BuzzerTask(); LEDTask(); AuxTask() } trigger = 0; } But wait! We said that the other tasks do not need to happen every time the trigger is set, but only every so often. How do we handle that? Well, if we set up a counter for each defined task, we can let the task code figure that out: .. code-block:: c int LEDcounter = 0; void LEDTask() { LEDcounter++ if(LEDcounter == 100) { // do work LEDcounter = 0; } } This would make the LED task only do real work when its counter reached 100 - or every 100th interrupt. See how it works? Using a scheme such as this will let you handle a bunch of simple tasks easily. Let's build the code and try it out! Building the Kernel code ************************ In our previous lecture on interrupts, we used ``Timer0`` to generate our interrupts. Timer 0 is an 8 bit timer that can only count to 255 before rolling over. We need to be able to count higher than that for this experiment, so we will need a bit of trickery to get things working! Timer routines ============== Basically, we will configure ``Timer0`` as before, but we will set it up to run at 1/8 the processor clock speed. By using the overflow scheme, that means we will be generating interrupts at a rate of 16000000 / 8 / 256 = 7812 times per second, close enough to our target rate of 8000. Here is the code we need to make the timer work this way (details are described in the processor data sheet): .. literalinclude:: code/avr-kernel/timer.S :linenos: :lines: 1-37 :caption: timer.S .. note:: This code is set up to use a counter to skip some number of interrups before setting a trigger variable to be used to launch the task code. We are not using that here, but it is useful for other experiments. The Timer ISR routines ====================== With the timer properly initialized, the ISR is pretty simple: .. literalinclude:: code/avr-kernel/timer.s :linenos: :lines: 39-65 :caption: timer.S All we need to do is set the trigger and we are done. This is almost too easy! Place this code in a ``timer.S`` together with the other timer setup code. The main routine ================ Here is the initialization we need in our main code: .. literalinclude:: code/avr-kernel/main.S :lines: 1-22 :caption: main.S At this point in our main code, the interrupt table is set up properly, but we need to initialize the chip, timer and all the tasks. We will set up initialization routines in each task file and simply call those routines here: .. literalinclude:: code/avr-kernel/main.S :linenos: :lines: 24-28 :caption: main.S .. note:: Since I have no need for the pulse task at the moment, I commented out that code. We have one more chunk of code to set up. Our main code needs to check the trigger variable and call the tasks into life. Place this code right after the call to the timer setup routine: .. literalinclude:: code/avr-kernel/main.S :linenos: :lines: 30-39 :caption: main.S The task framework ================== Now that we have an interrupt going off every so often, we can turn to the code needed to make our tasks work as we wish. Here is the framework for a single task. Modifying this code for each designated task is pretty easy: .. literalinclude:: code/avr-kernel/buzz_task.S :linenos: :lines: 1-8, 10-37, 44-52 We do the work needed for this task above the line labeled ``2`` above Testing our interrupts ---------------------- As a test of the basic logic we have presented here, I set up ``pulse_task`` to fire the logic to toggle the pulse pin each time it is called (max task count value is 1). I hooked an oscilloscope to the pulse pin to see how often they are being triggered. Here is what I saw: .. image:: images/KernelClock.png :align: center This figure shows an interrupt being triggered about every 125 microseconds, which works out to 8000 times per second, right on the money! Now, we can go off and set up the remaining tasks Blinking the LED ================ Now that we have the basic interrupt system running, let's slow things down and blink the light. In this task, we need to let about 4000 interrupts go by. That is too many to count with a simple 8 bit register, so we need a 16 bit counter to do the job. This code is a bit more involved, since we need to do 16-bit math. The AVR has a few registers it treats as 16 bit registers, used mainly for indirect addressing. Since we do not need any of that at the moment, we will use one register pair (r26, r27) as a 16 bit register. The AVR calls this pair ``X``: Here is our LED task: .. literalinclude:: code/avr-kernel/led_task.S :linenos: :lines: 1-18, 20-28, 30-47, 54-58 :caption: led_task.S Notice the code we need to check this 16 bit counter against the max defined value. Buzzing the buzzer ================== The code needed to make the buzzer work is placed in ``buzz_task`` above the line labeled 2: .. literalinclude:: code/avr-kernel/buzz_task.S :linenos: :lines: 44-48 :caption: buzz_task.S If you test the code at this point, the buzzer should sound and the LED should blink at about the right rate. Cool, but we wanted to cause the buzzer to sound when the light is on. So, we have a bit more work to do. Basically, we need to let one task talk to another task. We need to have the LED task set a variable when the LED goes on, and tell the buzzer task to shut things down when the LED is off. Hmmm - let's see if we can get this working! First, we need to set up the variable. We will define it in ``led_task`` and let ``buzz_task`` see it. .. literalinclude:: code/avr-kernel/led_task.S :linenos: :lines: 11-12, 16, 19 :caption: led_task.S And in ``buzz_task``: .. literalinclude:: code/avr-kernel/buzz_task.S :linenos: :lines: 9 :caption: buzz_task.S Now, we need to set this variable when the LED is on. Unfortunately, since we are just toggling the bit, we do not know if the LED is on or off, so we will just test the right bit. If it is a 1, the LED is on! .. literalinclude:: code/avr-kernel/led_task.S :linenos: :lines: 44-58 :caption: led_task.S With this change, we have the ``led_on`` variable set if the LED is on. Now, we can use this variable to decide if we should toggle the buzzer pins. (Skipping this will cause the buzzer to shut off.) .. literalinclude:: code/avr-kernel/buzz_task.S :linenos: :lines: 35-43, 49-52 :caption: buzz_task.S Try this change! With any luck, the buzzer will only sound when the LED is on!. Cool, multi-tasking working in a neat way! What about that last task? ************************** We had one last task to handle. This one is an example of a task that could be expanded to fire off a signal to a servo. If you look into the documentation for servos, you discover that they like to have a pulse sent their way about 50 times a second. (Actually, that number is soft, they work well with a range of values.) Let's set up a simple task and see if we can have is generate a short pulse we can look at on the oscilloscope. This will not be enough code to run the servo, but it should give you ideas. Here is the task we will use: .. literalinclude:: code/avr-kernel/pulse_task.S :linenos: :caption: pulse_task.S You should be able to add this task to your code. When I ran the resulting program, this is what I saw on the output pin we set up for ``Task3``: .. image:: images/Pulse.png :align: center That is one call every 20ms, which works out to our target of 50Hz. Looks like we have a program we can work with! Testing your code ***************** As your code gets more complex, you will soon wish you had better tools to help debug your code. Fortunately, there are many such tools available, some free, some not free. Here are some references to tools we might use: * `AVR Simulator `_ * `Logic Analyzers `_ Further Reading *************** In case you are interested in seeing a more sophisticated way to set up a multi-tasking kernel on the Arduino, here is a paper to get you started: * :download:`TinyRealTime.pdf` .. vim:set filetype=rst spell: