* * Luke Woodbury * * */ // constants won't change. * * We are going to use the button example sketch as the basis to * create a sketch that will randomly choose between our red, * green or blue LED when a button is pressed. Copy and paste into you Arduino IDE, it may be easier to read. Here's a way using a nested if statement to select the right pin, you could also make use of a switch case if you wanted to. This can just be a boolean variable that is true if we need a new random number (i.e when the button has been released) or is false when the button remains pressed. When we hold the button it will keep creating random numbers and make the LED turn on all colours and go white, so we need to create a flag to check whether we actually need a new random number for our ledPin variable or should stick with the same one. Extra Credit: Make a random color generator. The seed should be a fairly random, wide ranging number. We need to use the random number we have created to select one of our pins, for example: if our random number is 0 choose ledPin 10. colors by having different analogWrite values for each color pin on your Arduino. The better approach is to 'seed' the default pseudorandom generator in Arduino library - which does approximate to flat distribution - with some kind of random value - either a timer counter or as discussed in the post, analogRead() on a floating pin. srandom simply sets the seed value used the next time random is called. The returned result is the seed for the next call. random takes a 32 bit seed value, performs some math on this value, and returns the result. ![]() ![]() Pay attention to the reference example for using random(), including creating a variable to hold the number above the code. There are two functions of interest from 'stdlib': random and srandom. We want to use random() to control the ledPin number, it will no longer be a constant (unchanging) number therefore we need to remove the 'const' from the front where we define our pins and variables at the top of the code.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |