An Arduino project to exemplify some intermediate/advanced programming concepts for Arduino. No hardware other than an Arduino required.
For many Makers, Arduino projects are one of the first contacts with coding and remain relatively basic. However, with a few a little more advanced concepts in (Arduino) programming, many Arduino projects can be brouhgt to the next level (i.e. more organized, more efficient and more reliable).
This project is a concise way to exemplifiy the following good-to-know techniques that are applicable to many programs:
- Cooperative multitasking (avoid delay())
- State machines (a mighty concept for more complex tasks)
- Classes (avoid duplicated code)
- Using the serial plotter (for visualization and debugging)
- Paramter setting via the serial input (save time when tuning parameters)
- Using a config.h file (all configurations in one place)
The Arduino runs two tasks: It lets its LED blink (with variable frequency) and runs three function generators (sine, cosine and square wave).
The blink task is implemented as a simple state machine.
The function generators are all instances of the same class funcGenerator.
The output is formatted so that it can be viewed on the IDE's built-in serial plotter.
At the same time, the user can set paramters and control the output via the IDE's (or any other) serial monitor.
The program can be configured via a config file - no need to touch any other files (e.g. comment out things here and there...)
- Metro library for cooperative multitasking (forked from the original work by thomasfredericks): https://github.com/LuSeKa/Metro (clone into the library folder of your Arduino IDE)
To simply see the program in action, compile and upload to the Arduino. Open the serial plotter (under Tools in the Arduino IDE) (115200baud) and watch the curves evolve.
Open the config.h and play with the parameters. For example, set a much lower frequency in line 8. Compile, upload, and watch the effect in the plotter.
Open a serial monitor (115200bps and Newline on enter) and type
g0
This will deactivate the spam.
(Alternatively, set PRINT_ON_STARTUP in line 9 of config.h to false.)
Set some new values, e.g. increase the amplitudes to 100 with
a100
Reactivate the outputs, e.g. at an interval of 10ms with
g10
and spot the difference!
If you want to see the difference on the plotter, you have to change the amplitude in the config.h, compile and upload.
The command
b
will return the current blink interval.
You can make the LED blink much faster, e.g. by typing
b50
Here ar some ideas for possible modifictaions:
- Modify the program so that the LED's blinking frequency changes in a sinusoidal manner, controlled by a funcGenerator
- If you have a potentiometer, make the function amplitudes controllable via analog input
- ...