Posts | Comments

Planet Arduino

Archive for the ‘random number generator’ Category

Often when working with Arduino projects, you’ll need to generate a random number. There’s a random() function built into the IDE that works acceptably in many cases, but maker_ATOM wanted to take things to the next level, creating an “over engineered true random value generator.”

This device sits on top of an Arduino Uno as a shield, and features input from a floating pin a seed value. It adds light input as a second seed value with an LDR, and ambient noise via a microphone as a third value. These are used to choose from an array of Pi digit values, which are also random, revealing outputs on its OLED display at the push of a button that would be exceedingly difficult to predict! 

More details on the project can be found in maker_ATOM’s Instructables post.

Are you running out of ways to entertain yourself and your family? If you’ve read all the books and watched all the movies, it might be time to explore the psychic abilities of silicon. [Hari Wiguna] has just the trick to keep them guessing for a good long time.

This trick doesn’t take much, just a couple of Arduinos, some momentary buttons, a number pad, and a large helping of math. As you can see in the demo after the break, there is nothing connecting the two, not even 802.11(n). On the randomizer Arduino, [Hari] generates random numbers with the push of a button until the audience sees one they like. Then [Hari] locks in the number with the other button.

What happens next is key: the randomizer generates another random number, but uses it as a hint to set a sentinel digit. The randomizer Arduino subtracts the larger of the two digits in the number from nine and stores the result as the flag. When the next number comes up that has the flag digit in the correct place, the number after that will be the random number chosen at the beginning.

The psychic Arduino’s secret is that it knows the first guess it receives is special. It does the same sentinel digit math as the randomizer, so when the guesser enters the guess with the sentinel digit, it knows the next number entered is the winner. Clear as mud? Check out the second video below where [Hari] explains the trick, a new take on a magic classic.

Looking for a more exciting way to generate random numbers? Try using fish tanks, lava lamps, or muons from outer space.

Are you waiting for something that may never happen? Maybe it’s the end of your ennui, or the release of Half Life 3. While you wait, why not build a Godot Machine? Then you can diversify your portfolio and wait for two things that could happen today, tomorrow, or at sunrise on the 12th of Never.

The Godot Machine is a functional art piece that uses a solar panel and a joule thief to charge a bank of capacitors up to 5V. Whenever that happens, the Arduino comes online and generates a 20-bit random number, which is displayed on an LED bar. If the generated number matches the super-secret number that was generated at first boot and then stashed away in EEPROM, the Machine emits a victory beep and lights a green LED. Then you can go back to complaining about whatever.

We like that [kajnjaps] made his own chaos-based random number generator instead of just calling random(). It uses a guitar string to collect ambient electronic noise and an entropy generator to amplify it. Then the four least significant digits are used to seed the logistical map, so the initial value is always different.

You don’t have to create your own entropy for truly random numbers, though it’s probably more fun that way. Did you know that someone wrote an Arduino entropy library?

There’s not much time left now. If you’re going to put something together to give the youngsters some night terrors in exchange for all that sweet candy, you better do it quick. This late to the game you might not have time to do anything too elaborate, but luckily we’ve come across a few quick Halloween hacks that can get you some pretty cool effects even if it’s only a few hours before the big night.

As a perfect example, these LED “blinking eyes” were created by [Will Moser]. Using nothing more exotic than some bare LEDs, an Arduino, and a cardboard box, these little gadgets can quickly and easily be deployed in your windows or bushes to produce an unsettling effect after the sun goes down. Thanks to the pseudorandom number generator in the Arduino code, the “eyes” even have a bit of variability to them, which helps sell the idea that your Halloween visitors are being watched by proper creatures of the night.

The hardware side of this project is very simple. [Will] takes a container such as a small cardboard box and cuts two holes in it to serve as the eyes. He notes that containers which are white or reflective on the inside work best. You’ll want to get a little artistic here and come up with a few different shaped sets of eyes, which is demonstrated in the video after the break. Inside each box goes a colored LED, wired back to the Arduino.

For the software, [Will] is using a floating analog pin as a source of random noise, and from there comes up with how often each LED will blink on and off, and for how long. Both the hardware and software sides of this project are perfect for beginners, so it might be a good way to get the Little Hackers involved in the festivities this year; if you’re the type of person who enjoys replicating small humans in addition to creeping them out.

LEDs seem to be the hacker’s decoration of choice come Halloween, from wearable LED eyes to remote controlled illuminated pumpkins.

What do you do, when you need a random number in your programming? The chances are that you reach for your environment’s function to do the job, usually something like rand() or similar. This returns the required number, and you go happily on your way.

A shift register configured as a pseudo-random number generator.
A shift register configured as a pseudo-random
number generator. [by KCAuXy4p CC0 1.0]
Except of course the reality isn’t quite that simple, and as many of you will know it all comes down to the level of randomness that you require. The simplest way to generate a random number in software is through a pseudo-random number generator, or PRNG. If you prefer to think in hardware terms, the most elementary PRNG is a shift register with a feedback loop from two of its cells through an XOR gate. While it provides a steady stream of bits it suffers from the fatal flaw that the stream is an endlessly repeating sequence rather than truly random. A PRNG is random enough to provide a level of chance in a computer game, but that predictability would make it entirely unsuitable to be used in cryptographic security for a financial transaction.

There is a handy way to deal with the PRNG predictability problem, and it lies in ensuring that its random number generation starts at a random point. Imagine the  shift register in the previous paragraph being initialised with a random number rather than a string of zeros. This random point is referred to as the seed, and if a PRNG algorithm can be started with a seed derived from a truly unpredictable source, then its output becomes no longer predictable.

Selecting Unpredictable Seeds

Computer systems that use a PRNG will therefore often have some form of seed() function alongside their rand() function. Sometimes this will take a number as an argument allowing the user to provide their own random number, at other times they will take a random number from some source of their own. The Sinclair 8-bit home computers for example took their seed from a count of the number of TV frames since switch-on.

The not-very-random result of a thousand analogRead() calls.
The not-very-random result of a thousand analogRead() calls.

The Arduino Uno has a random() function that returns a random number from a PRNG, and as you might expect it also has a randomSeed() function to ensure that the PRNG is seeded with something that will underpin its randomness. All well and good, you might think, but sadly the Atmel processor on which it depends has no hardware entropy source from which to derive that seed. The user is left to search for a random number of their own, and sadly as we were alerted by a Twitter conversation between @scanlime and @cybergibbons, this is the point at which matters start to go awry. The documentation for randomSeed() suggests reading the random noise on an unused pin via analogRead(), and using that figure does not return anything like the required level of entropy. A very quick test using the Arduino Graph example yields a stream of readings from a pin, and aggregating several thousand of them into a spreadsheet shows an extremely narrow distribution. Clearly a better source is called for.

Noisy Hardware or a Jittery Clock

As a slightly old-school electronic engineer, my thoughts turn straight to a piece of hardware. Source a nice and noisy germanium diode, give it a couple of op-amps to amplify and filter the noise before feeding it to that Arduino pin. Maybe you were thinking about radioactive decay and Geiger counters at that point, or even bouncing balls. Unfortunately though, even if they scratch the urge to make an interesting piece of engineering, these pieces of hardware run the risk of becoming overcomplex and perhaps a bit messy.

The significantly more random result of a thousand Arduino Entropy Library calls.
The significantly more random result of a thousand Arduino Entropy Library calls.

The best of the suggestions in the Twitter thread brings us to the Arduino Entropy Library, which uses jitter in the microcontroller clock to generate truly random numbers that can be used as seeds. Lifting code from the library’s random number example gave us a continuous stream of numbers, and taking a thousand of them for the same spreadsheet treatment shows a much more even distribution. The library performs as it should, though it should be noted that it’s not a particularly fast way to generate a random number.

So should you ever need a truly random number in your Arduino sketch rather than one that appears random enough for some purposes, you now know that you can safely disregard the documentation for a random seed and use the entropy library instead. Of course this comes at the expense of adding an extra library to the overhead of your sketch, but if space is at a premium you still have the option of some form of hardware noise generator. Meanwhile perhaps it is time for the Arduino folks to re-appraise their documentation.

The subject of entropy and generating random numbers is one that has appeared on these pages many times. [Voja Antonic] made a in-depth study using uninitialized RAM as an entropy source for microcontrollers. If you have an insatiable appetite for understanding Linux entropy, we point you at [Elliot Williams]’ comprehensive examination of the subject.

[Arduino image: DustyDingo Public domain]


Filed under: Arduino Hacks, Hackaday Columns, Microcontrollers, Skills

Your job is to create a random number generator.

Your device starts with a speaker and a membrane. On this membrane will sit a handful of small, marble-size copper balls. An audio source feeds the speaker and causes the balls to bounce to and fro. If a ball bounces high enough, it will gain the opportunity to travel down one of seven copper tubes. Optical sensors in each of the tubes detect the ball and feed data to an Ardunio Mega. When the ball reaches the end of the tube, a robotic hand will take the ball and put it back on the speaker membrane. The magic happens when we write an algorithm such that the audio output for the speaker is a function of how many balls fall down the pipes.

The above is a rough description of [::vtol::]’s art piece: kinetic random number generator. We’re pretty sure that there are easier ways to get some non-determinstic bits, but there may be none more fun to watch.

[::vtol::] is a frequent flyer here on Hackaday Airlines. Where else would you showcase your 8-bit Game Boy Photo Gun or your brainwave-activated ferrofluid monster bath? Would it shock you to find out that we’ve even covered another kinetic random number generator of his?  Fun stuff!


Filed under: Arduino Hacks

When [::vtol::] wants to generate random numbers he doesn’t simply type rand() into his Arduino IDE, no, he builds a piece of art. It all starts with a knob, presumably connected to a potentiometer, which sets a frequency. An Arduino UNO takes the reading and generates a tone for an upward-facing speaker. A tiny ball bounces on that speaker where it occasionally collides with a piezoelectric element. The intervals between collisions become our sufficiently random number.

The generated number travels up the Rube Goldberg-esque machine to an LCD mounted at the top where a word, corresponding to our generated number, is displayed. As long as the button is held, a tone will continue to sound and words will be generated so poetry pours forth.

If this take on beat poetry doesn’t suit you, the construction of the Ball-O-Bol has an aesthetic quality that’s eye-catching, whereas projects like his Tape-Head Robot That Listens to the Floor and 8-Bit Digital Photo Gun showed the electronic guts front and center with their own appeal.


Filed under: Arduino Hacks

Random number generators come in all shapes and sizes. Some are software based while others, known as true random number generators, are hardware based. These can be created from thermal noise, the photoelectric effect and other methods. But none of these were good enough for [M.daSilva]. He would base his off of the radioactive decay of Uranium 238, and construct a working nuclear powered random number generator.

diagram

Because radioactive decay is unpredictable by nature, it makes for an excellent source for truly random data. The process is fairly simple. A piece of old fiestaware plate is used for the radioactive source. Put it in a lead enclosure along with a Geiger tube. Then wire in some pulse shaping circuitry and a microcontroller to count the alpha particles. And that’s about it. [M.daSilva] still has to do some statistical analysis to ensure the numbers are truly random, along with making a nice case for his project. But all in all, it seems to be working quite well.

Be sure to check out the video for quick rundown of [M.daSilva’s] project. If randomness is your thing, make sure you check out entropy harvested from uninitialized RAM, and the story behind the NIST randomness beacon.

The 2015 Hackaday Prize is sponsored by:


Filed under: Arduino Hacks


  • Newsletter

    Sign up for the PlanetArduino Newsletter, which delivers the most popular articles via e-mail to your inbox every week. Just fill in the information below and submit.

  • Like Us on Facebook