The Japanino, arrays and functions
There are two last topics to talk about before pulling out the big guns - arrays and making your own functions.
An array is just a collection of variables of the same type given the same name. You can make pretty complex array structures, but the Japanino only has 1K worth of variable memory so you're forced to keep it simple. I use an array for holding patterns to display on the P.O.V. LED stick. A sample pattern is:
byte bitmap[] = {
0b01000001, // 0 X Pattern
0b00100010, // 1
0b00010100, // 2
0b00001000, // 3
0b00010100, // 4
0b00100010, // 5
0b01000001
};
You start out by declaring the data type (in this case an 8-bit
byte
), followed by the array name, the required square brackets, and then the data for initializing the array if you don't pre-specify the array size.
int some_nums[6];
The above code creates the array
some_nums
as being 6 elements long (element numbering starts at 0, so we're really going from
some_nums[0]
to
some_nums[5].
Now, as for functions, we've been using functions all along.
setup()
and
loop()
are two pre-defined functions supplied by the Arduino IDE compiler. We can make our own functions, too.
datatype function_name(datatype variable1, datatype variable2...) {
commands
return value;
}
If you don't want the function to return a value, use "
void
" as the datatype.
Example that returns a value:
int x;
int y = 7;
loop() {
x = myfunc(y, 2);
}
int myfunc(int val1, int val2) {
return val1 * val2;
}
The reason for describing arrays and functions here may become apparent in the following exercise. Again, there's no comments, so try to figure out what it's doing on your own.
-----------------
// Pretty Lights Sketch
#define SWPIN 6
#define SPKR 14
int ledPin = 7;
int number_of_LEDs = 7;
boolean play_tone = 0;
boolean tripped;
unsigned long start_time;
byte bitmap[] = {
0b01000001, // 0 X in
0b00100010, // 1
0b00010100, // 2
0b00001000, // 3
0b00010100, // 4
0b00100010, // 5
0b01000001 // 6
};
void setup() {
for(int x=ledPin; x < ledPin + number_of_LEDs; x++) {
pinMode(x, OUTPUT);
}
pinMode(SWPIN, INPUT);
digitalWrite(SWPIN, HIGH);
}
void loop() {
for(int ptr = 0; ptr <= 6; ptr++) {
display_pattern(bitmap[ptr]);
}
}
void display_pattern(byte val) {
for(int i = 0; i < number_of_LEDs; i++) {
digitalWrite(ledPin + number_of_LEDs - 1 - i, (val >> i) & 0b00000001);
}
if(play_tone) {
tone(SPKR, 200, 100);
}
tripped = 0;
start_time = millis();
while(millis() - start_time < 100) {
if(digitalRead(SWPIN) == LOW && ! tripped) {
play_tone =! play_tone;
tripped = 1;
}
}
}
---------------------------------
=================================
---------------------------------
Things to keep in mind when programming the Japanino.