Skip to content

Instantly share code, notes, and snippets.

@kinasmith
Last active March 21, 2018 03:40
Show Gist options
  • Save kinasmith/41c1f925183d3ddaa254c10b83444456 to your computer and use it in GitHub Desktop.
Save kinasmith/41c1f925183d3ddaa254c10b83444456 to your computer and use it in GitHub Desktop.
using an if statement to display binary numbers
int led1 = 9;
int led2 = 10;
int led4 = 11;
int led8 = 12;
//...etc
void setup() {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
//...etc
}
void loop() {
displayNumber(4);
//Try this!! (comment out the line above, uncomment the line below)
// displayNumber(millis()/1000); //millis() is a function that returns the number of milliseconds since the program started (powered on the arduino, reset, or uploaded code)
//what happens? Why?
}
//this is a better way of doing the number display.
//read this:
// http://www.toptechboy.com/arduino/lesson-14-if-statements-and-conditionals-in-arduino/
// and this about if and if-else loops. Or ask your dad how they work!
// https://learn.sparkfun.com/tutorials/digital-sandbox-arduino-companion/7-if-this-then-that
//it is still an additional FUNCTION, but this time we can give it an ARGUEMENT in the parenthasees like so.
//and when we CALL it in the loop FUNCTION above, it will PASS that ARGUEMENT into the FUNCTION and it will
//become the VARIABLE 'n'.
//try encorporating this code into your code. and using this if statement to display numbers instead.
void displayNumber(int n) {
if(n == 0) {
digitalWrite(led1, 0);
digitalWrite(led2, 0);
digitalWrite(led4, 0);
digitalWrite(led8, 0);
} else if(n == 1) {
digitalWrite(led1, 1);
digitalWrite(led2, 0);
digitalWrite(led4, 0);
digitalWrite(led8, 0);
} else if(n == 2) {
digitalWrite(led1, 0);
digitalWrite(led2, 1);
digitalWrite(led4, 0);
digitalWrite(led8, 0);
}
//...etc
}
// This is how it was....
// .....
// void one() {
// digitalWrite(led1, 1);
// digitalWrite(led2, 0);
// digitalWrite(led4, 0);
// digitalWrite(led8, 0);
// }
//
// void two() {
// //...etc
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment