Using ATMega16's timer0 for sound generation - audio

I am trying to make use of the ATMega16's timer0 to generate PWM pulses and output sound on a basic buzzer..
But i am facing a problem figuring out how i can be able to change the frequency of the waves im creating (to generate different notes)
I saw on the datasheet that with the timer0 you can use ICR for TOP values and that way you can change the frequency and with OCR you'll be able to change the duty cycle..
Is there a similar way but on either timer0 or timer2 ?
I am already using timer1 to control something else so i'm wondering if i have to start over :(
Thanks in advance,
Any idea is appreciated

Generally, when "running out of" timers, simple software routines based on timer interrupts will take you pretty far.
For example, using one of the timer compare interrupts you could easily generate almost all frequencies:
In the timer compare ISR just toggle the respective output pin and (let the timer be) reset to 0. The set compare value determines the generated frequency in terms of fractions of the timer's frequency.
There are many more elaborate ways to use a limited number of available timers to perform a lot of timer tasks at the same time. It is basically all just based on thoughtfully used ISRs.

Related

Solution of pure transport first order hyperbolic PDE with delay, using COMSOL Multiphysics

I am working on a project to solve a first order hyperbolic pure transport PDE with time delay using COMSOL multiphysics. Is it possible to do this using COMSOL? if yes, what physics to include? and how to include time delay in the process? the system is close to injecting a dye on the laft side of a pipe and a time delay will happen until the dye is observed at the outlet enter image description here
My goal is to solve the system numerically using COMSOL, what do you think the parameters that should be watched in this system in order to compare this system with the basic one without time delay.

Estimating WCET of a task on Linux

I want to approximate the Worst Case Execution Time (WCET) for a set of tasks on linux. Most professional tools are either expensive (1000s $), or don't support my processor architecture.
Since, I don't need a tight bound, my line of thought is that I :
disable frequency scaling
disbale unnecesary background services and tasks
set the program affinity to run on a specified core
run the program for 50,000 times with various inputs
Profiling it and storing the total number of cycles it had completed to
execute.
Given the largest clock cycle count and knowing the core frequency, I can get an estimate
Is this is a sound Practical approach?
Secondly, to account for interference from other tasks, I will run the whole task set (40) tasks in parallel with each randomly assigned a core and do the same thing for 50,000 times.
Once I get the estimate, a 10% safe margin will be added to account for unforseeble interference and untested path. This 10% margin has been suggested in the paper "Approximation of Worst Case Execution time in Preepmtive Multitasking Systems" by Corti, Brega and Gross
Some comments:
1) Even attempting to compute worst case bounds in this way means making assumptions that there aren't uncommon inputs that cause tasks to take much more or even much less time. An extreme example would be a bug that causes one of the tasks to go into an infinite loop, or that causes the whole thing to deadlock. You need something like a code review to establish that the time taken will always be pretty much the same, regardless of input.
2) It is possible that the input data does influence the time taken to some extent. Even if this isn't apparent to you, it could happen because of the details of the implementation of some library function that you call. So you need to run your tests on a representative selection of real life data.
3) When you have got your 50K test results, I would draw some sort of probability plot - see e.g. http://www.itl.nist.gov/div898/handbook/eda/section3/normprpl.htm and links off it. I would be looking for isolated points that show that in a few cases some runs were suspiciously slow or suspiciously fast, because the code review from (1) said there shouldn't be runs like this. I would also want to check that adding 10% to the maximum seen takes me a good distance away from the points I have plotted. You could also plot time taken against different parameters from the input data to check that there wasn't any pattern there.
4) If you want to try a very sophisticated approach, you could try fitting a statistical distribution to the values you have found - see e.g. https://en.wikipedia.org/wiki/Generalized_Pareto_distribution. But plotting the data and looking at it is probably the most important thing to do.

digitalWrite best practice in Arduino

I have a loop checking the status of a sensor. If it's in one state, I light a LED using digitalWrite (1,HIGH), otherwise, I write LOW. This happens in a tight loop many times a second.
Is it fine to write so many times, or is it better practice to set a flag and only write if the flag has changed?
It shouldn't be a problem for the board. You could also add a short delay at the end of the loop (delay(5);)

Progress bar and multiple threads, decoupling GUI and logic - which design pattern would be the best?

I'm looking for a design pattern that would fit my application design.
My application processes large amounts of data and produces some graphs.
Data processing (fetching from files, CPU intensive calculations) and graph operations (drawing, updating) are done in seperate threads.
Graph can be scrolled - in this case new data portions need to be processed.
Because there can be several series on a graph, multiple threads can be spawned (two threads per serie, one for dataset update and one for graph update).
I don't want to create multiple progress bars. Instead, I'd like to have single progress bar that inform about global progress. At the moment I can think of MVC and Observer/Observable, but it's a little bit blurry :) Maybe somebody could point me in a right direction, thanks.
I once spent the best part of a week trying to make a smooth, non-hiccupy progress bar over a very complex algorithm.
The algorithm had 6 different steps. Each step had timing characteristics that were seriously dependent on A) the underlying data being processed, not just the "amount" of data but also the "type" of data and B) 2 of the steps scaled extremely well with increasing number of cpus, 2 steps ran in 2 threads and 2 steps were effectively single-threaded.
The mix of data effectively had a much larger impact on execution time of each step than number of cores.
The solution that finally cracked it was really quite simple. I made 6 functions that analyzed the data set and tried to predict the actual run-time of each analysis step. The heuristic in each function analyzed both the data sets under analysis and the number of cpus. Based on run-time data from my own 4 core machine, each function basically returned the number of milliseconds it was expected to take, on my machine.
f1(..) + f2(..) + f3(..) + f4(..) + f5(..) + f6(..) = total runtime in milliseconds
Now given this information, you can effectively know what percentage of the total execution time each step is supposed to take. Now if you say step1 is supposed to take 40% of the execution time, you basically need to find out how to emit 40 1% events from that algorithm. Say the for-loop is processing 100,000 items, you could probably do:
for (int i = 0; i < numItems; i++){
if (i % (numItems / percentageOfTotalForThisStep) == 0) emitProgressEvent();
.. do the actual processing ..
}
This algorithm gave us a silky smooth progress bar that performed flawlessly. Your implementation technology can have different forms of scaling and features available in the progress bar, but the basic way of thinking about the problem is the same.
And yes, it did not really matter that the heuristic reference numbers were worked out on my machine - the only real problem is if you want to change the numbers when running on a different machine. But you still know the ratio (which is the only really important thing here), so you can see how your local hardware runs differently from the one I had.
Now the average SO reader may wonder why on earth someone would spend a week making a smooth progress bar. The feature was requested by the head salesman, and I believe he used it in sales meetings to get contracts. Money talks ;)
In situations with threads or asynchronous processes/tasks like this, I find it helpful to have an abstract type or object in the main thread that represents (and ideally encapsulates) each process. So, for each worker thread, there will presumably be an object (let's call it Operation) in the main thread to manage that worker, and obviously there will be some kind of list-like data structure to hold these Operations.
Where applicable, each Operation provides the start/stop methods for its worker, and in some cases - such as yours - numeric properties representing the progress and expected total time or work of that particular Operation's task. The units don't necessarily need to be time-based, if you know you'll be performing 6,230 calculations, you can just think of these properties as calculation counts. Furthermore, each task will need to have some way of updating its owning Operation of its current progress in whatever mechanism is appropriate (callbacks, closures, event dispatching, or whatever mechanism your programming language/threading framework provides).
So while your actual work is being performed off in separate threads, a corresponding Operation object in the "main" thread is continually being updated/notified of its worker's progress. The progress bar can update itself accordingly, mapping the total of the Operations' "expected" times to its total, and the total of the Operations' "progress" times to its current progress, in whatever way makes sense for your progress bar framework.
Obviously there's a ton of other considerations/work that needs be done in actually implementing this, but I hope this gives you the gist of it.
Multiple progress bars aren't such a bad idea, mind you. Or maybe a complex progress bar that shows several threads running (like download manager programs sometimes have). As long as the UI is intuitive, your users will appreciate the extra data.
When I try to answer such design questions I first try to look at similar or analogous problems in other application, and how they're solved. So I would suggest you do some research by considering other applications that display complex progress (like the download manager example) and try to adapt an existing solution to your application.
Sorry I can't offer more specific design, this is just general advice. :)
Stick with Observer/Observable for this kind of thing. Some object observes the various series processing threads and reports status by updating the summary bar.

Multithreading or green threading in actionscript?

I was wondering if there are any code or class libraries out there on how to implement multithreading or "green threading" in ActionScript.
As you've might seen, Scott Peterson is developing some kind of toolset, but I haven't found any more info on this other than his performance on the Adobe MAX Chicago event.
Regards Niclas
Here's a Green Threading lib from Drew Cummins:
http://blog.generalrelativity.org/?p=29
There's no built-in way to do green threading in ActionScript. You have to write code to handle it.
Make a function that performs one iteration of whatever operation you want to do. It should return true or false depending on if its job is done or not. Now, you have to compute the time interval left to the next screen update on the ENTER_FRAME event. This can be done using flash.utils.getTimer.
start = getTimer();
//thread is a ui component added to system manager that is redrawn each frame
var fr:Number = Math.floor(1000 / thread.systemManager.stage.frameRate);
due = start + fr;
Keep on executing your function while checking the function's return value each time and checking if due time has been crossed by comparing getTimer() with due.
This has been implemented into a usable class by Alex Harui in the blog entry - Threads in ActionScript
It's an old article, but quasimondo's method of launching multiple swfs and then sharing the data over a LocalConnection may also be of interest. They were saying that the back and forth of using the LocalConnection may eat up a few cycles, but if the iterations being processed are complex enough it shouldn't be too much of a problem.
I'm a graphics guy, not a programmer, so I'm not sure this will help you. BUT!
I make all my GUIs multi-frame "movies" and write each gui thread on a different frame. Make sure that you only have 1-3 threads, and set your FPS to 30 or 60.
This is useful for little projects because its bug-resistant and implementation is done for you.

Resources