Using A Configuration File
One if the challenges to creating reusable code for all our students is giving them dozens of example programs that can all run on their specific hardware configuration where they might have changed the pins on their LEDs and sensors. If we hard-code the pin numbers in each of the 20 example programs the students would need to change each of the 20 programs to get their code to work.
The way to solve this problem is to isolate all the pin numbers
in a single file called a config.py
file. By just editing
this single file, the entire set of 20 programs can now be used.
This may not be important for simple programs like our NeoPixel labs that just have two numbers: a pin number and a number of pixels. These numbers can be quickly changes with your text editor. However, once your projects has many pins like our Cytron Robots, making all these changes can be time consuming and distracts from learning.
Example Config File
Let's start out with a simple NeoPixel example that just has two numbers: a NeoPixel Pin number and the number of pins. Here is a sample configuration file for this program:
1 2 |
|
Now you can simply reference your config.py file and use the numbers when you
prefix the parameters with the config.
string like this:
1 2 3 4 |
|
Note that when a user opens this file they don't actually see the values of the pins.
If they are not aware of how config.py
files are used they might not
know they have to change the config.py
file. So there are always tradeoffs.
Putting all your hardware configuration information in a separate file is called abstraction and it is one of the critical skills we use in computational thinking.