Programming Arduino Getting Started with Sketches



Yüklə 5,42 Kb.
Pdf görüntüsü
səhifə54/78
tarix22.12.2023
ölçüsü5,42 Kb.
#189286
1   ...   50   51   52   53   54   55   56   57   ...   78
Arduino SimonMonk 2011

random(1, 10)
produces a random
number between one and nine.
Sketch 7-01 pumps out numbers between one and six to the Serial Monitor.


If you upload this sketch to your Arduino and open the Serial Monitor, you will see
something like 
Figure 7-1
.
If you run this a few times you will probably be surprised to see that, every time you
run the sketch, you get the same series of ‘random’ numbers.
The output is not really random; the numbers are called 
pseudo-random
numbers
because they have a random distribution. That is, if you ran this sketch and collected a
million numbers, you would get pretty much the same number of ones, twos, threes, and
so on. The numbers are not random in the sense of being unpredictable. In fact, it is so
against the workings of a microcontroller to be random that it just plain can’t do it without
some intervention from the real world.
Figure 7-1
Random numbers
You can provide this intervention to make your sequence of numbers less predictable by
seeding
the random number generator. This basically just gives it a starting point for the
sequence. But, if you think about it, you cannot just use 
random
to seed the random
number generator. A commonly used trick is to use the fact that (as discussed in the
previous chapter) an analog input will float. So you can use the value read from an analog
input to seed the random number generator.
The function that does this is called 
randomSeed
. Sketch 7-02 shows how you can add


a bit more randomness to your random number generator.
Try pressing the Reset button a few times. You should now see that your random
sequence is different every time.
This type of random number generation could not be used for any kind of lottery. For
much better random number generation, you would need hardware random number
generation, which is sometimes based on random events, such as cosmic ray events.
Math Functions
On rare occasions, you will need to do a lot of math on an Arduino, over and above the
odd bit of arithmetic. But, should you need to, there is a big library of math functions
available to you. The most useful of these functions are summarized in the following
table:



Yüklə 5,42 Kb.

Dostları ilə paylaş:
1   ...   50   51   52   53   54   55   56   57   ...   78




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin