Posts | Comments

Planet Arduino

Archive for the ‘Skills’ Category

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

I am a crappy software coder when it comes down to it. I didn’t pay attention when everything went object oriented and my roots were always assembly language and Real Time Operating Systems (RTOS) anyways.

So it only natural that I would reach for a true In-Circuit-Emulator (ICE) to finish of my little OBDII bus to speed pulse generator widget. ICE is a hardware device used to debug embedded systems. It communicates with the microcontroller on your board, allowing you to view what is going on by pausing execution and inspecting or changing values in the hardware registers. If you want to be great at embedded development you need to be great at using in-circuit emulation.

Not only do I get to watch my mistakes in near real time, I get to make a video about it also.

Getting Data Out of a Vehicle

I’ve been working on a small board which will plug into my car and give direct access to speed reported on the Controller Area Network (CAN bus).

To back up a bit, my last video post was about my inane desire to make a small assembly that could plug into the OBDII port on my truck and create a series of pulses representing the speed of the vehicle for my GPS to function much more accurately. While there was a wire buried deep in the multiple bundles of wires connected to the vehicle’s Engine Control Module, I have decided for numerous reasons to create my own signal source.

At the heart of my project is the need to convert the OBDII port and the underlying CAN protocol to a simple variable representing the speed, and to then covert that value to a pulse stream where the frequency varied based on speed. The OBDII/CAN Protocol is handled by the STN1110 chip and converted to ASCII, and I am using an ATmega328 like found on a multitude of Arduino’ish boards for the ASCII to pulse conversion. I’m using hardware interrupts to control the signal output for rock-solid, jitter-free timing.

Walk through the process of using an In-Circuit Emulator in the video below, and join me after the break for a few more details on the process.

The Hardware

I revised the board since the last video and removed the support for the various protocols other than CAN, which is the non-obsolete protocol of the bunch. By removing a bunch of parts I was able to change the package style to through-hole which is easier for many home hobbyists, so you can leave the solder-paste in the ‘fridge.

The “Other Connector” on your Arduino

Unlike the Arduino which is ready to talk to your USB port when you take it out of the box, the ATmega chips arrive without any knowledge of how to go and download code, in other words it doesn’t have a boot loader. Consequently I have the In-Circuit-Serial-Programming (ICSP) pins routed to a pin header on my board so that I can program the part directly.

On this connector you’ll find the Reset line, which means with this header I can use a true ICE utilizing the debugWIRE protocol. Since the vast majority of designs that use an AVR chip do not repurpose the reset pin for GPIO, it is a perfect pin to use for ICE. All of the communications during the debug process will take place on the reset pin.

Enter the ICE

When designing a computer from scratch there is always the stage where nothing yet works. Simply put, a microprocessor circuit cannot work until almost every part of the design works; RAM, ROM, and the underlying buses all need to (mostly) work before simple things can be done. As a hardware engineer by trade I would always reach for an ICE to kick off the implementation; only after the Beta release would the ICE start to gather dust in the corner.

In the case of the ATmega, the debugging capabilities are built into the microcontroller itself. This is a much more straightforward implementation than the early days when we had to have a second isolated processor running off-board with its own local RAM/ROM.

One note mentioned in the video is that a standard Arduino’ish board needs to have the filter capacitors removed from the RESET line to allow the high speed data on the line for its debugWIRE usage.

The ICE I am using here is the one made by Atmel, and is compatible with Atmel Studio, there are also other models available such as the AVR Dragon.

ICEyness

The ICE allows us to download and single step our code while being able to observe and overwrite RAM and I/O Registers from the keyboard. We are able to watch the program step by step or look underneath at the actual assembly code generated by the compiler. We can watch variables and locations directly in RAM or watch the C language counterparts. It’s also possible to jump over a sub-routine call in the instance of just wanting to see the result without all of the processing.

It’s worth your time to see even a glimpse of the capabilities of an ICE in action. I recommend that you watch the video where the debugging begin.

Final Words

This video was really about finishing the OBDII circuit so I didn’t really have the time to go over everything an ICE can do, maybe I will do a post dedicated to just the ICE and development environment next time.


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

In a recent post, I talked about using the “Blue Pill” STM32 module with the Arduino IDE. I’m not a big fan of the Arduino IDE, but I will admit it is simple to use which makes it good for simple things.

I’m not a big fan of integrated development environments (IDE), in general. I’ve used plenty of them, especially when they are tightly tied to the tool I’m trying to use at the time. But when I’m not doing anything special, I tend to just write my code in emacs. Thinking about it, I suppose I really don’t mind an IDE if it has tools that actually help me. But if it is just a text editor and launches a few commands, I can do that from emacs or another editor of my choice. The chances that your favorite IDE is going to have as much editing capability and customization as emacs are close to zero. Even if you don’t like emacs, why learn another editor if there isn’t a clear benefit in doing so?

There are ways, of course, to use other tools with the Arduino and other frameworks and I decided to start looking at them. After all, how hard can it be to build Arduino code? If you want to jump straight to the punch line, you can check out the video, below.

Turns Out…

It turns out, the Arduino IDE does a lot more than providing a bare-bones editor and launching a few command line tools. It also manages a very convoluted build process. The build process joins a lot of your files together, adds headers based on what it thinks you are doing, and generally compiles one big file, unless you’ve expressly included .cpp or .c files in your build.

That means just copying your normal Arduino code (I hate to say sketch) doesn’t give you anything you can build with a normal compiler. While there are plenty of makefile-based solutions, there’s also a tool called PlatformIO that purports to be a general-purpose solution for building on lots of embedded platforms, including Arduino.

About PlatformIO

Although PlatformIO claims to be an IDE, it really is a plugin for the open source Atom editor. However, it also has plugins for a lot of other IDEs. Interestingly enough, it even supports emacs. I know not everyone appreciates emacs, so I decided to investigate some of the other options. I’m not talking about VIM, either.

I wound up experimenting with two IDEs: Atom and Microsoft Visual Studio Code. Since PlatformIO has their 2.0 version in preview, I decided to try it. You might be surprised that I’m using Microsoft’s Code tool. Surprisingly, it runs on Linux and supports many things through plugins, including an Arduino module and, of course, PlatformIO. It is even available as source under an MIT license. The two editors actually look a lot alike, as you can see.

PlatformIO supports a staggering number of boards ranging from Arduino to ESP82666 to mBed boards to Raspberry Pi. It also supports different frameworks and IDEs. If you are like me and just like to be at the command line, you can use PlatformIO Core which is command line-driven.

In fact, that’s one of the things you first notice about PlatformIO is that it can’t decide if it is a GUI tool or a command line tool. I suspect some of that is in the IDE choice, too. For example, with Code, you have to run the projection initialization tool in a shell prompt. Granted, you can open a shell inside Code, but it is still a command line. Even on the PlatformIO IDE (actually, Atom), changing the Blue Pill framework from Arduino to mBed requires opening an INI file and changing it. Setting the upload path for an FRDM-KL46 required the same sort of change.

Is it Easy?

Don’t get me wrong. I personally don’t mind editing a file or issuing a command from a prompt. However, it seems like this kind of tool will mostly appeal to someone who does. I like that the command line tools exist. But it does make it seem odd when some changes are done in a GUI and some are done from the command line.

That’s fixable, of course. However, I do have another complaint that I feel bad for voicing because I don’t have a better solution. PlatformIO does too much. In theory, that’s the strength of it. I can write my code and not care how the mBed libraries or written or the Arduino tools munge my source code. I don’t even have to set up a tool chain because PlatformIO downloads everything I need the first time I use it.

When that works it is really great. The problem is when it doesn’t. For example, on the older version of PlatformIO, I had trouble getting the mBed libraries to build for a different target. I dug around and found the issue but it wasn’t easy. Had I built the toolchain and been in control of the process, I would have known better how to troubleshoot.

In the end, too, you will have to troubleshoot. PlatformIO aims at moving targets. Every time the Arduino IDE or the mBed frameworks or anything else changes, there is a good chance it will break something. When it does, you are going to have to work to fix it until the developers fix it for you. If you can do that, it is a cost in time. But I suspect the people who will be most interested in PlatformIO will be least able to fix it when it breaks.

Bottom Line

If you want to experiment with a different way of building programs — and more importantly, a single way to create and build — you should give PlatformIO a spin. When it works, it works well. Here are a few links to get you started:

Bottom line, when it works, it works great. When it doesn’t it is painful. Should you use it? It is handy, there’s no doubt about that. The integration with Code is pretty minimal. The Atom integration — while not perfect — is much more seamless. However, if you learn to use the command line tools, it almost doesn’t matter. Use whatever editor you like, and I do like that. If you do use it, just hope it doesn’t break and maybe have a backup plan if it does.


Filed under: Arduino Hacks, ARM, Hackaday Columns, reviews, Skills
Gen
07

Learn a New Skill in the New Year – Getting Started with Arduino

arduino, getting started, Maker Shed, Maker Shed Deals, Open source hardware, Skills Commenti disabilitati su Learn a New Skill in the New Year – Getting Started with Arduino 

MSGSA-2Why not add learning a new skill to your repertoire in the New Year? I know you've seen loads of projects that use the Arduino, and with special deals on our Getting Started with Arduino Kit, there's no better time to learn how to use this versatile microcontroller.

Read the full article on MAKE



  • 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