Syndicate content Hackaday
Fresh hacks every day
ถูกปรับปรุง 3 hours 48 min ก่อน

Learning Verilog for FPGAs: Flip Flops

ศุกร์, 08/21/2015 - 00:00

Last time I talked about how to create an adder in Verilog with an eye to putting it into a Lattice iCEstick board. The adder is a combinatorial circuit and didn’t use a clock. This time, we’ll finish the demo design and add two clocked elements: a latch that remembers if the adder has ever generated a carry and also some counters to divide the 12 MHz clock down to a half-second pulse to blink some of the onboard LEDs.

Why Clocks?

Clocks are an important part of practical digital design. Suppose you have a two input AND gate. Then imagine both inputs go from zero to one, which should take the output from zero to one, also. On paper, that seems reasonable, but in real life, the two signals might not arrive at the same time. So there’s some small period of time where the output is “wrong.” For a single gate, this probably isn’t a big deal since the delay is probably minuscule. But the errors will add up and in a more complex circuit it would be easy to get glitches while the inputs to combinatorial gates change with different delays.

The most common solution to this is to only “look” at the signals (and store them in a flip flop) on a clock edge (usually, just the rising edge). Now the circuit will work fine if the longest delay from one flip flop’s output to the next flip flop’s input is less than the period of the clock. This makes things much simpler to design.

If you need a refresher on flip flops, they are elements that remember a single bit. A D flip flop will remember its input (named D) at the clock edge and hold that output until the next clock edge. There are other kinds of flip flops, like the T flip flop (which toggles state) or the JK flip flop which can perform several functions. With Verilog, you generally won’t create flip flops directly, but will let the compiler infer them from your code.

Let’s jump right in with some examples. I’ll explain these each in more details as we go. Consider this code:

reg myoutput; wire myinput; always @(posedge clk) myoutput<=myinput;

This would infer a D type flip flop. The compiler will recognize other types, too. For instance:

reg myoutput; wire myinput; always @(posedge clk) myoutput<=myinput?~myoutput:myoutput;

This would infer a T flip flop. Usually, though, the inference is not this direct. The input might be a logic expression. The compiler can also infer counters which are lots of flip flops:

reg [3:0] ctr; always @(posedge clk) begin if (ctr_reset) ctr<=4'b0; else ctr<=ctr+1; end

Just as using the plus operator allowed the Verilog compiler to do the best thing for an adder, the expression above will let it build an efficient counter without you having to worry about the details. You can build a counter out of individual modules that infer flip flops (or modules that your tool provides for you) but it is better to leave the details to the compiler.

Building a Flip Flop

The demo circuit had three distinct parts: the binary adder circuit from last time is already done. Another part of the example design is to provide an output that latches when a carry is generated. Here’s the part of the code that does that:

reg carrylatch; // latch carry result always @(posedge clk) begin if (reset==1'b1) carrylatch<=1'b0; else begin if (carry) carrylatch<=1'b1; end end

In English, this says that when the clock has a rising edge, check to see if the reset line is high. If it is, clear the carry latch. Otherwise, check to see if the carry is set and if so, set the carry latch. It will remain set until a reset clears it.

The Verilog tool will recognize this is a flip flop with synchronous reset. If you get really concerned about performance, you may want to investigate if your FPGA does better with an asynchronous reset and learn how your tool can be told to do that instead. But for now, this is sufficient. The realization will probably be a D type flip flop with a rising edge-sensitive clock input and a clock enable tied to the carry line. The D input will be tied to a logic 1.

Key Verilog Point #2: Blocking vs Non-Blocking Assignments

Did you notice that some assignments use = and some use <=? This is an important Verilog feature. When you are using assignments, you always use the equal sign. If you are writing a sequential block, you almost never want to use the single equal sign, even though Verilog will allow this. Here’s why:

always @(posedge clk) begin a<=1’b1; b<=a; end

Because the nonblocking assignment (<=) appears, the value of b will become whatever a was at the moment the clock edge occured. That is, all the assignments in the block happen all at one time. In simulation, that means they happen at the end statement since simulations have to pretend everything happens in parallel. In an FPGA, parallel execution is just how the hardware works.

The problem is, if you do not use a non-blocking assignment. Suppose we had:

always @(posedge clk) begin a=1’b1; b=a; end

The Verilog compiler is smart enough to know that b should equal 1 in this case and has to generate extra circuitry (a latch) to make sure b isn’t set at the same time as a. This can cause lots of timing issues and unless you are sure you need to do it and understand the ramifications, you should avoid it at all costs.

Key Verilog Point #3: Default Net Types

You may notice that some of the variables in the Verilog code are of type wire and some are of type reg. A wire has to be constantly driven to some value. A reg is more like a regular variable. A reg may, but doesn’t always, infer a flip flop. However, you can set a value in a reg and it sticks.

One problem you wind up with in Verilog is that if you make up a name, the compiler (by default) will assume you mean for it to be a wire unless you tell it otherwise. That sounds handy, but the problem is if you misspell a name, it just becomes a new wire and then you can’t figure out why your code doesn’t do what you want.

The answer is to always include this at the front of a Verilog file:

`default_nettype none

This causes the compiler to throw an error if you use an undeclared net. That will save you a lot of debugging time wondering why things aren’t working.

Counting and Dividing

The remainder of the Verilog takes the 12MHz clock and uses it to drive a 16 bit counter. When the counter overflows, another counter increases. When that counter reaches 91, the secondary counter goes to zero. This takes roughly 1/2 second at 12MHz.

You can figure that out by noting that 12MHz is 83 ns or .000083 us. A 16-bit counter will overflow on the 65536th count (two to the 16 power). Do the math and that comes out to nearly 5.5ms per overflow. If you let the secondary counter go to 91, that will take almost 497ms. If you go to 92, you go over (502 ms). Note that counting to 91 (or 92) only takes a 7 bit counter. A graphical representation of the situation is shown here with the code for it below.

// The 12MHz clock is too fast // The first counter will / 2^16 (about 5.46ms) // Then the second counter goes to 91 which is 0.497s // close enough to 1/2 second for our purpose always@(posedge clk) begin if (reset==1'b1) begin cnt1<=0; cnt2<=0; half_sec_pulse<=0; dec_cntr<=0; end else if (runstop==1'b0) // don't do anything unless enabled begin cnt1 <= cnt1 + 1; if (cnt1 == 0) if (cnt2 == 91) begin cnt2 <= 0; half_sec_pulse <= 1; end else cnt2 <= cnt2 + 1; else half_sec_pulse <= 0; if (half_sec_pulse == 1) dec_cntr <= dec_cntr + 1; // count half seconds end end

(Note: as mentioned in the comments below, there’s nothing special about a 16-bit counter. I just wanted to show a nested counter, but since this example doesn’t use the intermediate clock, you could have just as easily made a single longer counter to do the job with one division. The FPGA doesn’t care if you make a 2 bit counter or a 60 bit counter unless you run out of resources.)

This is a form of sequential circuit and the counters will turn into a chain of flip flops when synthesized. Here’s the definition for the counters:

// Manage 12MHz clock reg [15:0] cnt1; reg [6:0] cnt2; reg [1:0] dec_cntr; reg half_sec_pulse;

The counter declarations look like arrays, but they aren’t (Verilog does support arrays, but these are not arrays). The numbers in square brackets are telling you the number of bits in the value. So cnt1 has 16 bits numbered from 15 (the most significant) to 0 (the least significant).

We’ll use the array-like bit notation and the assign statement to make some LEDs blink too:

// Make the lights blink assign LED4 = (dec_cntr == 2); assign LED5 = dec_cntr[0]; Updating the Test Bench

Since the new design requires a clock, the testbench has to provide it. It would be very annoying to have to write each clock transition. Luckily, you don’t have to. Here’s how the clock generation works:

always begin #1   clk<=~clk; end

In English, this says: At all times, you should delay one clock cycle (the #1) and then invert the clock signal and keep doing that forever. Another item to consider is the FPGA reset:

rs=1'b0; // run/stop reset=1'b1; #10 reset=1'b0;

This bit of code sets the reset line, holds it for 10 clock cycles, and then clears it.

At the end of the test bench is a 400 cycle delay just to let the counters do something.

Simulation Specifics

There’s one small problem with the simulation. The 12 MHz divider won’t do anything interesting in “only” 400 cycles. It isn’t uncommon to change magic numbers to smaller values when simulating. In this case, I change the primary counter increment to 8000 hex so it will flip every other clock cycle and then changed the test for 91 down to a more reasonable value.

There are several ways you can do this, but to stay simple, I just commented out the real versions and later I’ll remove the comments and comment out the simulation versions.

You can see the entire code on EDAPlayground and you can even run the simulation from there. The waveform shown here will appear. If you want to know more about how it all works, check out the video and I’ll walk through it step by step.

Next Time

Next time, I’ll show you how to take the Verilog (which should work since it simulates correctly) and push it down to the FPGA board. If you’ve been paying attention, you should have at least one serious question: How do I tell someone that LED1, for example, maps to the LED on the board? That’s a great question, and I’ll answer it next time. Here’s a clue though: It doesn’t depend on the name of the net. I could have called that signal BigJim and I’d still be able to map it to the LED. If you plan to work along, you can get a head start by installing the open source tool kit now. Of course, if you don’t have an iCEstick, that won’t do you much good unless you just want to dry run the tools.

Selected Tutorials

If you are looking for a detailed Verilog tutorial, try these:

Filed under: FPGA

Tap On! Tap Off! The Backlight!

พฤ, 08/20/2015 - 22:31

We recently covered [TechnologyCatalyst’s] excellent $50 multimeter shoot out, and we weren’t surprised when the winner was the Uni-T UT61E. It’s jam packed with features, and has a lot of bang for your buck. But one thing that it’s missing is a backlight.

The 61E uses a chip form CyrusTek called the ES51922A. This chip has a back light features built into it, but Uni-T simply didn’t add the supporting circuitry and LEDs. This was done either to keep cost down, or to not take away sales from their higher end models – your guess is as good as ours. Even though several people have tried carefully soldering to this fine pitch chip package to add back lights, the backlight timer is set to turn off in 60 seconds.

[Nisei] on the EEVBlog forum came up with an elegant capacitive touch solution that we could see being used in many other applications. The mod centers around a using a TTP223 touch sensor module that you can find on eBay for $1 instead of tapping into the meter’s dormant backlight controller. Add in a voltage regulator, a resistor, 2 leds and some foil tape, and that’s about all you need. [Nisei] did a great job documenting the mod with graphics rather than pictures (that can be a bit ambiguous at times.) Also, in case you missed the $50 DMM review you can find it here.

With all that said, we’re thinking the next multimeter mod might just need to be the “Clap-On, Clap-off” meter.

Filed under: tool hacks

Drivers for 3D Printers and Why We Need Them

พฤ, 08/20/2015 - 21:01

Manufacturers of 3D printers have a lot to do before they catch up with makers of the cheapest 2D, paper-based printers. If you’ve ever taken an inkjet apart, you’ll most likely find some sort of closed-loop control on at least one of the axes. The 2D printer will tell you when you’re out of ink, when a 3D printer will go merrily along, printing in air without filament. File formats? Everything is Gcode on a 3D printer, and there are dozens, if not hundreds of page description languages for 2D printers.

The solution to some of these problems are drivers – software for a 3D printer that slowly consumes the slicing of an object, printer settings, and placing an object on the bed. It’s coming, and the people who are responsible for making your 2D printer work with your computer are busy at work messing up the toolchain for your 3D printer.

The latest version of CUPS (C Unix Printing System) adds support for 3D printers. This addition is based on meetings, white papers, and discussions in the Printer Working Group (PWG). There has already been a lot of talk about what is wrong with the current state of 3D printer toolchains, what can be improved, and what should be completely ignored. Let’s take a look at what all of this has accomplished.

What CUPS Offers

gcode to draw a circle [Image source]The most obvious question related to CUPS’ addition of 3D printer support is a glib. ‘why?’. 3D printers speak G Code, and any device can send that over a serial port. There’s no need for drivers to send ASCII strings to a device, is there?

Anyone who has ever dealt with a failed print will tell you this is not the case. Printers fail, sometimes spectacularly. From a white paper penned by [Michael Sweet] (PDF), lead developer of CUPS, driver support will include printer failures, a standard build platform, cameras, lasers, a replacement for the .STL file format, and the color of an object. It’s all there, an entire 3D printer toolchain, wrapped up in a single software package.

It’s somewhat remarkable when you consider what a user must do to print an object downloaded from the Internet. In the current 3D printer ecosystem, a user would download a model, set the temperture, of the hot ends and build platforms, slice the model, put it on a build plate, and finally send the G Code over to the printer. While this can be greatly simplified with fantastic host software such as Cura, a driver-like solution reduces all these processes down to a single, automatic step. Companies are interested, too: Ultimaker is already talking to PWG, and hopes in the PWG are high to get other printer manufacturers on board.

CUPS isn’t the only game in town, and in this case it’s a little behind the ball. In 2013, Microsoft released their 3D printing driver with spooling and queuing support, and an API for submitting jobs to manufacturers.

The Software is Ahead of the Hardware Filament detectors like this one are not standard hardware

While it may not seem like a necessity now, the problems being taken on by the CUPS devs and PWG are very interesting. A filament sensor before the extruder would solve a lot of problems found in 3D printers. When these sensors start appearing on printers, the software to make use of them will already be there. When UV resin printers make it big, CUPS will have support for it.

A 3D printer isn’t just G Code, and some layers of abstraction can make things much, much easier. With the features suggested for CUPS, we may soon have 3D printers usable by even the most technically inept among us. As long as we avoid the horror show of cheap inkjets and proprietary software stacks, this will be what takes 3D printing to every office in the world.

Filed under: 3d Printer hacks, news

Using a Capacitor as an Actuator?!

พฤ, 08/20/2015 - 18:01

[Dan Berard] has been using capacitors as actuators.

We’ve featured Dan’s awesome self built STM (scanning tunneling microscope) before. These microscopes work by moving a tip with nanometer precision across a surface. While the images he acquired are great, one disadvantage of the actuator he used is its poor rigidity. This limits the system to faster scan speeds.

In his search for a better actuator [Dan] thought he’d try using MLCC capacitors! While not known for their electromechanical properties, you may have encountered capacitors that appear to “sing” (PDF), emitting an audible tone. This is due to the piezoelectric properties of BaTiO3. Effectively the capacitor acts as a weak piezo electric speaker.

Using a 100V drive voltage [Dan] was able to get 300nm of deflection using the capacitor. To extend the range of the actuator he decided to ‘pole the ceramic dielectric’ this involved heating the capacitor above its Curie temperature of 120C. For this he used a transistor to heat the part as an ad-hoc hotplate. This increased the range of the actuator to 800nm, ideal for many STM (and other SPM) systems.

[Dan] is still weighing up his options for his next build, but MLCC capacitors are certainly a cheap and interesting choice.

Filed under: misc hacks

High Tech, Low Cost Digital Torque Meter

พฤ, 08/20/2015 - 15:01

Ever obsessed with stripping the hype from the reality of power tool marketing, and doing so on the cheap, [arduinoversusevil] has come up with a home-brew digital torque meter that does the job of commercial units costing hundreds of times as much.

For those of us used to [AvE]’s YouTube persona, his Instructables post can be a little confusing. No blue smoke is released, nothing is skookum or chowdered, and the weaknesses of specific brands of tools are not hilariously enumerated. For that treatment of this project, you’ll want to see the video after the break. Either way you choose, he shows us how a $6 load cell and a $10 amplifier can be used to accurately measure the torque of your favorite power driver with an Arduino. We’ve seen a few projects based on load cells, like this posture-correcting system, but most of them use the load cell to measure linear forces. [AvE]’s insight that a load cell doesn’t care whether it’s stretched or twisted is the key to making a torque meter that mere mortals can afford.

Looks like low-end load cells might not be up to measuring the output on your high-power pneumatic tools, at least not repeatedly, but they ought to hold up to most electric drivers just fine. And spoiler alert: the Milwaukee driver that [AvE] tested actually lived up to the marketing.

Filed under: Arduino Hacks, tool hacks

CCC 2015: Moon Robots, Data Destuction, and an Epic Thunderstorm

พฤ, 08/20/2015 - 12:01

Chaos Communication Camp 2015 is over, and most everyone’s returned home to warmer showers and slower Internet. In this last transmission from Camp 2015, we’ll cover the final two days of talks, the epic thunderstorm, and give a brief rundown of the challenges of networking up a rural park in Brandenburg.

The Talks

Planning on landing a robot on the moon? Well, this guy (and his team) is for the Google Lunar X-Prize, and his talk covers how they’re using a model of the moon to test things out here on earth. Even if you’re not going that far, the basic idea of creating an accurate practice mission could help you figure out where the glitches are.

[Ramiro Pareja] and [Rafa Boix] show you how to get started with microprocessor voltage glitching to bypass security applications. If you liked the 2014 Hackaday Prize entry, the Chip Whisperer, these guys show you how to do something similar on the cheap with a transistor and a relatively fast microprocessor, or by “optical fault injection” — just flashing a really bright light at it.

Keyboard/Mouse controller chips drilled out

If you need to destroy all data on your computer, why not learn from the pros? [Mustafa Al-Bassam] and [Richard Tynan] study the steps that the Guardian newspaper was ordered to take by the GHCQ to destroy the notebook provided to them by Edward Snowden. The surprise is that the spooks have them take an angle grinder to many more parts of the computer than you might have guessed. Watch the talk to find out what.

[Thilo Schumann] presented an overview of the state of the art in car hacking. If you haven’t been following all the things that you can do with your automobile over the CAN bus (wikipedia), give this video a look.

The Thunderstorm

It rained a couple of times at the Camp, but the night of Day Four saw a decent lightning storm pass through camp. (Animation of images from Blitzortung.org.)

When a lightning storm hits a nerd camp, everyone is either themselves an armchair physicist or is trapped in a Faraday cage with one. A few brave souls put their money where their mouths were and chose to sit the storm out inside the rusty metal railcars just across from the Munich camp.

Most of the crowd grumbled about having to put down their beverages, left their tents, and ran out in the rain to one of the old brick warehouses as instructed. To be fair, there have been a few incidents of people getting struck by lightning at recent summer festivals in Germany, sot it’s not entirely unreasonable to move people out of tents. One woman quipped, “at least we didn’t die, but now we all smell like wet dogs.”

Power was turned back on shortly after the storm passed, and the parties picked right back up where they left off. We all had something to talk about, and pretty pictures were made.

10-Gigabit Ethernet in the Country

It’s no exaggeration that the Internet at the Camp is better than most of us have at home. How did they do it? Like everything else at Camp, it involved a lot of know-how, a bunch of hard work, and cooperation and donations from named and un-named networking firms. It never hurts to have connections.

Luckily enough, there was a fiber cable that passed relatively close to camp, about 1.5 miles away. Connecting that up to the Camp was possible, and only took a few days, but involved running through fields and streams. It’s a good thing that the Network Operations crew includes certified climbers, riggers, and divers.

Shortly before the Camp opened, however, disaster struck in the form of (probably) a squirrel or marten that chewed through the cable. With all the professionalism that you’d expect from CCC volunteers, the fault was tracked down and repaired before the crowds arrived.

The end result was a faster network connection than any private individual has in Germany, in the middle of a campground surrounded by farms and lakes.

Alles hat ein Ende, nur die Wurst hat zwei.

The days following the official end of Camp still have volunteers on site taking stuff apart, preparing for the shipping companies, and generally cleaning up after the rest of us. If you’re still working on the Camp site, you have our gratitude. Take a well-deserved break for a while. We’re all looking forward to 2019.

Filed under: cons, Featured

Hackaday Prize Entry: Open-source Pulse Oximetry

พฤ, 08/20/2015 - 09:00

Chances are pretty good you’ve had a glowing probe clipped to your fingertip or earlobe in some clinic or doctor’s office. If you have, then you’re familiar with pulse oximetry, a cheap and non-invasive test that’s intended to measure how much oxygen your blood is carrying, with the bonus of an accurate count of your pulse rate. You can run down to the local drug store or big box and get a fingertip pulse oximeter for about $25USD, but if you want to learn more about photoplethysmography (PPG), [Rajendra Bhatt]’s open-source pulse oximeter might be a better choice.

PPG is based on the fact that oxygenated and deoxygenated hemoglobin have different optical characteristics. A simple probe with an LED floods your fingertip with IR light, and a photodiode reads the amount of light reflected by the hemoglobin. [Rajendra]’s Easy Pulse Plugin receives and amplifies the signal from the probe and sends it to a header, suitable for Arduino consumption. What you do with the signal from there is up to you – light an LED in time with your heartbeat, plot oxygen saturation as a function of time, or drive a display to show the current pulse and saturation.

We’ve seen some pretty slick DIY pulse oximeters before, and some with a decidedly home-brew feel, but this seems like a good balance between sophisticated design and open source hackability. And don’t forget that IR LEDs can be used for other non-invasive diagnostics too.

The 2015 Hackaday Prize is sponsored by:
Filed under: Arduino Hacks, Medical hacks, The Hackaday Prize

Steam-Powered Machine Shop

พฤ, 08/20/2015 - 06:01

It’s sometimes hard to believe how stuff was made over a hundred years ago when electricity wasn’t widely available. One of the most common ways of powering tools was via belt drive — powered by a water mill, or a steam engine, or even horses. [David Richards] has spent a good chunk of time making his own period accurate steam powered machine shop — and it’s fantastic.

It represents approximately what a 1920’s machine shop would look like in America. Not a single tool is newer than 1925. The whole shop is powered by a line shaft using steam power. A massive boiler provides steam for a Pennsylvania built 5 by 5 steam engine, dating back to approximately 1895. Using belts and clutches, it powers a few lathes, drill presses, a mill, and even a shaper — an identical machine to one in the Edison Museum!

It’s truly incredible seeing how stuff used to be made, and seeing the dedication [David] put in to building this shop. He posts regularly to YouTube under his channel, we’d highly recommend you check it out.

Filed under: tool hacks

Retrotechtacular: One Does Not Simply String Up a Half-Million VDC Transmission Line

พฤ, 08/20/2015 - 03:01

It takes strong and determined population to build a lasting civilization. If the civilization includes electricity and the inhabitants live in a hilly place with an often-unforgiving climate, the required strength and determination increases proportionally. Such is the case of the gentlemen who strung up the first half-million VDC transmission line across New Zealand, connecting the country’s two main islands.

Construction for the line known as the HVDC Inter-Island link began in 1961. It starts at the Benmore hydroelectric plant on the south island and runs north to Cook Strait via overhead cables. Then it travels 40km underwater to the north island and ends near Wellington. This is the kind of infrastructure project that required smaller, preliminary infrastructure projects. Hundreds of miles of New Zealand countryside had to be surveyed before breaking ground for the first tower support hole. In order to transport the materials and maintain the towers, some 270 miles of road were laid and ten bridges were built. Fifteen camps were set up to house the workers.

The country’s hilly terrain and high winds made the project even more challenging. But as you’ll see, these men were practically unfazed. They sent bundles of steel across steep canyons on zip lines and hand-walked wire haulage rope across gullies because they couldn’t otherwise do their job. Six of these men could erect a tower within a few hours, which the filmmakers prove with a cool time-lapse sequence.

Splicing the mile-long conductors is done with 100-ton compressors. Each connection is covered with steel sleeve that must be centered across the joint for optimum transmission. How did they check this? By taking a bunch of x-rays with a portable cesium-137 source.

Thanks for the tip, [Dave] and [Bryan Cockfield].

Retrotechtacular is a weekly column featuring hacks, technology, and kitsch from ages of yore. Help keep it fresh by sending in your ideas for future installments.

Filed under: Hackaday Columns, Retrotechtacular

Learning Verilog for FPGAs: The Tools and Building an Adder

พฤ, 08/20/2015 - 00:01

Over the last year we’ve had several posts about the Lattice Semiconductor iCEstick which is shown below. The board looks like an overgrown USB stick with no case, but it is really an FPGA development board. The specs are modest and there is a limited amount of I/O, but the price (about $22, depending on where you shop) is right. I’ve wanted to do a Verilog walk through video series for awhile, and decided this would be the right target platform. You can experiment with a real FPGA without breaking the bank.

In reality, you can learn a lot about FPGAs without ever using real hardware. As you’ll see, a lot of FPGA development occurs with simulated FPGAs that run on your PC. But if you are like me, blinking a virtual LED just isn’t as exciting as making a real one glow. However, for the first two examples I cover you don’t need any hardware beyond your computer. If you want to get ready, you can order an iCEstick and maybe it’ll arrive before Part III of this series if published.

I’m not going to directly try to teach Verilog. If you know C you can pick it up quickly and if you don’t there are plenty of text-based and video-based tutorials to choose from (I’ll add a few at the end of this post). However, I will point out a few key areas that trip up new FPGA designers and by following the example code, you’ll be up to speed in no time.

Choose a Verilog Simulator EDA Playground Simulates Verilog in the Browser

For part I, you need a Verilog simulator. I’m going to use EDAPlayground because it is free and it will run in your browser. No software to set up and no worry if you use some crazy operating system (like Windows). If you have a modern browser, you are all set.

I know some people don’t want to work on the Web or don’t want to create an account (honestly, though, this will just be tutorial code and making up a disposable e-mail address is easy enough). If you just can’t bear it, you can run all the examples on your desktop with Icarus Verilog (using GTKWave to display the results). I just won’t be talking about how to do that. You can read the Icarus introduction if you want to go that route. I still suggest you stick with EDAPlayground for the tutorial.

For the FPGA tools used in Part III, I’m using the open source Icestorm tools. I tried using the Lattice tools and it was heartbreakingly difficult to get them installed and licensed. I’ll have more to say about that in part III.

About the Target Hardware

The IceStick has a modest FPGA onboard. From its manual, it has the following features:

  • High-performance, low-power iCE40HX1K FPGA
  • FTDI 2232H USB device allows iCE device programming and UART interface to a PC
  • Vishay TFDU4101 IrDA transceiver
  • Five user LEDs (one green and four red)
  • 2 x 6 position Diligent Pmod compatible connector enables many other peripheral connections
  • Discera 12Mhz MEMS oscillator
  • Micron 32Mbit N25Q32 SPI flash
  • 16 LVCMOS/LVTTL (3.3V) digital I/O connections on 0.1” through-hole connections

The FPGA isn’t huge, but it is big enough to host a simple CPU (we covered the CPU earlier). We aren’t going to start with a CPU, though. We’ll start with something much more simple.

Let’s Build an Adder

There are two main kinds of circuits you build on any FPGA: combinatorial and sequential. The difference is simple: combinatorial logic is all logic gates. The past state of the circuit doesn’t matter. Given a certain set of inputs, the outputs will be the same. A sequential circuit (which almost always has a flip flop in it) has some memory of a previous state that changes the output. I wanted to show examples of both and how you map them to the board.

The example circuit we’ll build has three major parts. The first is a two-bit adder circuit that shows a binary sum and carry on two of the board’s five LEDs. This is a simple combinatorial circuit. It doesn’t make use of the onboard 12MHz clock. The other two portions will. The first sequential circuit will be a simple memory that latches true if a carry has ever been generated by the adder (after a reset, of course). The other sequential circuit is a set of counters that combine to provide a 1/2 second pulse from the 12MHz clock.

Verilog Versus Schematic Entry

For simple circuits, it is tempting to just draw a schematic like the one above and either machine translate that to the FPGA or hand translate it to Verilog. Some tools support this and you may think that’s the way to go. I know I did when I got started.

The truth is, through, that after you move away from simple things, the schematics can be very painful. For example, think of a seven segment decoder. If you took a few minutes you could probably work out the AND OR and NOT gates required to perform the function (that is, convert a four-bit binary number to a seven segment display). But it would take a few minutes.

If you use Verilog, you can take a simple approach and just write out the gates you want. That will work, but it is usually not the right answer. Instead, you should describe the circuit behavior you want and the Verilog compiler will infer what circuits it takes to create what you need. For the seven segment decoder this could be as simple as:

always @(*) case (number) 4'h0: dispoutput <= 7'b1111110; 4'h1: dispoutput <= 7'b0110000; 4'h2: dispoutput <= 7'b1101101; . . .

I promised I’d point out some of the stranger points of Verilog, so let’s look at that in a little more detail. The always statement tells Verilog that the code following should execute whenever any of the inputs you use in it change. This infers a combinatorial circuit since there is no clock. The case statement is like a switch statement in C. The funny looking numbers are four bit hex (4’h1) and 7 bit binary (7’b1101101). So the code instructs the FPGA (or, more accurately, the Verilog compiler) to examine the number and set dispoutput based on the input.

The <= character, by the way, are a non-blocking assignment. You could also use an equal sign here to create a blocking assignment. For now, the difference doesn’t matter, but we’ll revisit that topic when working with a sequential design.

From this description of what you want, the Verilog compiler will infer the right gates and may even be able to perform some optimizations. A key difference between an FPGA and building things on a microcontroller has to do with parallelism. If you wrote similar C code on, say, an Arduino, every copy of it would take some execution time. If you had, for example, 50 decoders, the CPU would have to service each one in turn. On the FPGA you’d just get 50 copies of the same circuit, all operating at once.

Key Verilog Point #1: Verilog isn’t Executable (Except when it is)

That’s a really important point. With an FPGA, the circuitry that drives each display just works all the time. Sure, there is a small delay through the gates (probably picoseconds) but that’s true even with discrete circuitry. It isn’t because the FPGA is executing lines of Verilog code or some equivalent structure. The Verilog becomes connecting wires that wire up circuit elements just as though you had a sea of gates on a PCB and you connected them with wire wrap.

There is an exception to this. During simulation, Verilog does act like a programming language, but it has very specific rules for keeping the timing the same as it will be on the FPGA. However, it also allows you to write constructs that would not be transferable to the FPGA. For example, a subroutine call doesn’t make sense in hardware, but you can do it during simulation. In general, you want to avoid non-synthesizable Verilog except when writing your testbench (the driver for your simulation; I’ll talk more about it in a minute).

Look back at the adder schematic. The sum is a simple XOR gate and the carry is an AND gate. I can express that in Verilog, if I want to, like this:

assign carry=inA&inB; assign sum=inA^inB;

It is smarter, though, to let Verilog figure that out. I can make a variable with two bits in it like this:

reg [1:0] fullsum;

Then I could say:

assign fullsum={1’b0, inA} + {1’b0, inB}; assign carry=fullsum[1]; assign sum=fullsum[0];

The braces turn the one bit wires inA and inB into two bit quantities. In this simple example, I might have actually stuck to the first method, but if you think back on the 7 segment decoder, you’ll see it makes sense to use this inferring style where possible.

Modules and Definitions

When you watch the video below or browse the code, you’ll notice there’s a few minor things I glossed over. For one, all of this code lives in a module. You can think of a module loosely as a subroutine or, better, a C++ class. Other modules can create copies of a module and map different signals to its inputs and outputs. There’s also definitions of all the nets used (we already talked about wires and regs):

module demo( output LED1, output LED2, output LED3, output LED4, output LED5, input PMOD1, // input A input PMOD2, // input B input PMOD3, // run/stop input PMOD4 // reset ); // Alias inputs wire inA; wire inB; assign inA=PMOD1; assign inB=PMOD2;

Note that I wanted the signals to have names associated with the physical hardware (like LED1 and PMOD2) but then later I wanted to use more meaningful names like inB. The assign statement makes this connection. This is a simple use of that statement. If you recall, one way to build the adder was to assign two bits using an expression. That kind of usage is far more common.

A Test Bench Makes The Simulation Possible

Before you commit your design to an FPGA, you’ll probably want to simulate it. Debugging is much easier during simulation because you can examine everything. When the Verilog simulator runs, it follows rules about timing that take into account how everything runs at the same time, so the behavior should be exactly what your FPGA will do.

The only thing many simulators won’t do is account for things like timing on the chip itself (although with the right tools, you can simulate that too). For example, your design may depend on an input changing before a clock edge (the set up time on the flip flop, for example) but because of the routing on the chip, the input won’t change in time.

This kind of timing violation is a real problem with large chips and high speeds. For this sort of small circuit, it shouldn’t be an issue. For now, we can assume if the simulation works, the FPGA should behave in the same way.

To test our code, we need a testbench which is just a way to say a piece of Verilog code that works like the outside world to our unit under test (in this case, the whole design). The code will never synthesize, so we can use strange Verilog features that we don’t normally use in our regular code.

The first thing to do is create a module for the testbench (the name isn’t important) and create an instance of the module we want to test:

`default_nettype none module tb; reg a, b; wire led1, led2, led3, led4, led5; demo dut(led1,led2,led3,led4,led5,a,b);

Note that there is a reg for each input we want to feed the device under test and a wire for each output it will drive. That means all of those reg variables need to be set up to our test conditions.

In English, this says: At all times, you should delay one clock cycle (the #1) and then invert the clock signal and keep doing that forever.

The variables need to be initialized. Verilog provides an initial block that is usually not valid for synthesis, but will be the main part of most test benches. Here’s the first part of it:

initial begin $dumpfile("dump.vcd"); $dumpvars(0, dut); a=1'b0; b=1'b0;

The two $ statements tell the testbench to dump variables from the device under test to a file called dump.vcd (this is where EDAPlayground looks for it, too, so don’t change it unless you are using your own Verilog simulator). We’ll be able to examine anything that gets dumped. You can also print things using $display, but I didn’t do that in this test.

The next thing you need is some test case stimulus. In the case of the counters, you don’t need anything other than the clock. But the adder-related circuitry needs some values:

#2 a=1'b1; #4 b=1'b1; #4 a=1'b0; #4 b=1'b0; #4 $finish; end

So at first, a=1 and b=0. Then after 4 cycles, a=1 and b=1. After another 4 cycles a=0, b=1. Then a=0, b=0. The $finish statement causes the simulation to end. Without this, the clock generator will cause the simulation to keep going forever.

You can find the code and the testbench on EDAPlayground (you can even run the simulation from there). When you run the simulation, a waveform will appear (see below). If you want to know more about how it works, check out the video below and I’ll walk through it step by step.

Next Time

In tomorrow’s installment of this series, I’ll show you how to add sequential (clocked) logic to the design and the testbench. Using clocks are an important part of making practical digital designs, as you’ll soon see. I’ll also have a few more Verilog key points.

Selected Tutorials

If you are looking for a detailed Verilog tutorial, try these:

Filed under: Featured, FPGA

Google’s OnHub Goes Toe to Toe with Amazon Echo

พุธ, 08/19/2015 - 22:31

Yesterday Google announced preorders for a new device called OnHub. Their marketing, and most of the coverage I’ve seen so far, touts OnHub as a better WiFi router than you are used to including improved signal, ease of setup, and a better system to get your friends onto your AP (using the ultrasonic communication technique we’ve also seen on the Amazon Dash buttons). Why would Google care about this? I don’t think they do, at least not enough to develop and manufacture a $199.99 cylindrical monolith. Nope, this is all about the Internet of Things, as much as it pains me to use the term.

OnHub boasts an array of “smart antennas” connected to its various radios. It has the 2.4 and 5 Gigahertz WiFi bands in all the flavors you would expect. The specs also show an AUX Wireless for 802.11 whose purpose is not entirely clear to me but may be the network congestion sensing built into the system (leave a comment if you think otherwise). Rounding out the communications array is support for ZigBee and Bluetooth 4.0.

I have long looked at Google’s acquisition of Nest and assumed that at some point Nest would become the Router for your Internet of Things, collecting data from your exercise equipment and bathroom scale which would then be sold to your health insurance provider so they may adjust your rates. I know, that’s a juicy piece of Orwellian hyperbole but it gets the point across rather quickly. The OnHub is a much more eloquent attempt at the same thing. Some people were turned off by the Nest because it “watches” you to learn your heating preferences. The same issue has arisen with the Amazon Echo which is “always listening”.

Google has foregone those built-in futuristic features and chosen a device to which almost  everyone has already grown accustom: the WiFi router. They promise better WiFi and I’m sure it will deliver. What’s the average age of a home WiFi AP at this point anyway? Any new hardware would be an improvement. Oh, and when you start buying those smart bulbs, fridges, bathroom scales, egg trays, and whatever else it’ll work for them as well.

As far as hacking and home automation, it’s hard to beat the voice-activated commands we’ve seen with Echo lately, like forcing it to control Nest or operate your Roku. Who wants to bet that we’ll see a Google-Now based IoT standalone device quickly following the shipment of OnHub?

Filed under: home hacks, news, wireless hacks

The EM Drive Might Not Work, but We Get Helicarriers If It Does

พุธ, 08/19/2015 - 21:01

There is a device under test out there that promises to take humans to another star in a single lifetime. It means vacations on the moon, retiring at Saturn, and hovercars. If it turns out to be real, it’s the greatest invention of the 21st century. If not, it will be relegated to the history of terrible science right underneath the cold fusion fiasco. It is the EM drive, the electromagnetic drive, a reactionless thruster that operates only on RF energy. It supposedly violates the laws of conservation of momentum, but multiple independent lab tests have shown that it produces thrust. What’s the real story? That’s a little more complicated.

The EM Drive is a device that turns RF energy — radio waves — directly into thrust. This has obvious applications for spacecraft, enabling vacations on Mars, manned explorations of Saturn, and serious consideration of human colonization of other solar systems. The EM drive, if proven successful, would be one of the greatest inventions of all time. Despite the amazing amount of innovation the EM drive would enable, it’s actually a fairly simple device, and something that can be built out of a few copper sheets.

The basic design of the EM drive is a truncated cone, called a ‘frustum’ in the proper engineering parlance. This hollow frustum is sealed at both ends. An antenna, or a simple piece of wire, is placed into the device, about halfway between the small and large ends of the frustum. This antenna is connected to an RF generator, in most cases a magnetron or something else that can generate microwave frequency RF.

The EM drive produces thrust because of a differential force on each end of the frustum. Because one end of the frustum is larger than the other, the net force is the difference between the forces on the large and small end of the cone. As far as a theoretical explanation of why the EM drive works (if it actually does), that’s about as good as you’re going to get. Understanding some of the proposed theories of how the EM drive works requires at least a Master’s in physics and many years of experience with RF systems. It’s not light reading.

Although the EM Drive and similar RF reactionless drives have made the news recently, the first inklings in academic literature are actually relatively old. [Roger Shawyer], the person who will be called the grandfather of the EM drive, started down his current path of research in the early 2000s. The paper that can be considered the birth of the EM drive is The Performance Analysis of Microwave Thrust without Propellant Based on the Quantum Theory, published by [Yang] in 2008. This paper by [F.O. Minotti] from 2013 investigates the possible theoretical background of the EM drive. It was not until NASA’s advanced propulsion research group, also known as Eagleworks, found anomalies during their test of an EM drive that the media clued into the potential of a device that produces thrust using only electricity.

EM Drive Tests and Statistics

Right now there are a few lab results that are not conclusive. They do, however, point to some sort of effect, and recent tests have further refined how large the EM drive effect actually is. This is where scientists are separated from amateurs, and where the probability of the EM drive being real increases, even though that might not be the case. 

To visualize the strange statistical aberrations, imagine the statistician’s favorite example, the archer. An archer, by profession or proclivity, shoots arrows at a target. At the beginning of his career, he’s not a very good archer, but he does manage to hit the target a few times before he runs out of arrows.

After practicing a few months, the archer’s accuracy improves. His shots don’t go as wide as before, and he doesn’t have to walk as far to collect his arrows. In fact, he’s even hitting his target more often. Obviously, he’s improving.

A few more month’s worth of training later, and the archer can’t seem to land a single arrow on the target. Of course, he barely has to walk at all to collect his arrows, and all his shots land on the same square foot of ground. He’s amazingly accurate for a medieval archer, but he just can’t hit the target.

For anyone with any experience at all in statistics, this is how the difference between accuracy and precision is taught. Accuracy is hitting the target, precision is getting a tight grouping. This difference means strange things can happen when you slowly refine the accuracy of a measurement.

In the graphic to the left, the center of the ‘hit box’ in each of the three cases is in exactly the same place relative to the bull’s eye. The only difference is the reduction in accuracy makes the archer less precise.

This effect can be seen everywhere if you pay attention; in late 2004, the asteroid Apophis was discovered and predicted to have a 1 in 233 chance of colliding with Earth in the year 2029. Days later, the probability of colliding with Earth increased to 1 in 37. It was not until more data were collected that the threat to Earth from the asteroid Apophis was brought down to comfortable levels; in 2029, this asteroid will miss the Earth entirely.

This effect is also seen in the results from various EM drive tests. From the Chinese lab tests to the testing done at NASA’s Eagleworks, the observed effect has been further refined, and the signal to experimental noise figures increased. This is exactly what you would expect from anything that is being studied in increasing detail, and an increase in the probability that the effect is real is not proof of the effect being real.

However, this does not stop people from dreaming. The best research points to the EM drive generating 30kN of thrust for each kilowatt of power dumped into the frustum. Put more simply, one kilowatt (the power to light ten 100 W light bulbs, or run a microwave oven) could lift a 3000 kg object and hover a few feet off the ground.

Lifting Really Big Things

To put this in more practical terms, a Tesla Roadster has a 58kWh battery and weighs about 1500 kg. Strap an EM drive to a Tesla, and you have a hovercar. Hovercars are cool, but the aircraft carrier USS Nimitz displaces about 100,000 metric tons, and is powered by two nuclear reactors that produce a total of 208MW. That’s a S.H.I.E.L.D helicarrier. Visiting another star with an EM drive is just one goal; if the EM drive works, we’re also going to get vehicles we can’t even imagine right now.

There’s still a lot of work to be done to tease the EM drive signal out from underneath experimental noise. It might not even turn out to be a real effect. However, multiple labs have tested versions of the EM drive and have found strange effects in their data sets. As it stands right now, the EM drive is only a few notches above a crazy guy who says he has a perpetual motion machine in his workshop. But even Galileo was labeled a heretic; the key is in proving the theory. The EM drive has stood up to tests so far, and if it turns out to be real, it will be an invention more important than the internal combustion engine.

Filed under: Featured, transportation hacks

Color by Number 3D Printing Style

พุธ, 08/19/2015 - 18:01

Remember paint-by-number kits? Your canvas has outlines with numbered regions that you paint with correspondingly numbered paints. When you are done, you’ve recreated the Mona Lisa. [KurtH3] uses a similar technique to coax multicolor prints from his 3D printer.

The technique isn’t general purpose, but it still is an interesting way to add some color to your usually monochrome prints. The idea is simple: You find a paint-by-number layout (apparently, you can find them with a Google search). Use your favorite method to get the outline into a CAD program. [KurtH3] doesn’t really get into the details about this, but some CAD programs will directly import images. Others will require you to trace in Inkscape (or a similar program) and convert to a vector format like DXF that the 3D CAD program can import.

Here’s the trick: instead of extruding the 2D image as one piece, you extrude the numeric regions to slightly different heights. Say you wanted to print a red, white, and blue flag to a thickness of about 5mm and you use 0.2mm layers. You could extrude the white part to 5mm, for example. Then the red parts could be extruded to 5.2mm (one layer higher) and the blue parts to 5.4mm. You could extend the idea to do multiple layers, although that will increase the surface roughness.

[KurtH3] pauses the print at the end of the layers to change filament, but we would probably edit the sliced G-Code to put pauses in the right places (for example, Repetier Host lets you put @pause in your file). You could also use software to split the G-Code as we’ve previously covered.  The resulting print, using our example, would be white from the bottom up but would have thin red and blue layers over the top in the right places. The few hundred microns difference from the white surface to the other colors means you won’t get a perfectly smooth surface, but a few hundred microns shouldn’t be too noticeable.

It isn’t a new idea to stop the printer and switch filament (see the video below, for example). The interesting idea here is starting with paint-by-number images and extruding based on the color.

Filed under: 3d Printer hacks

Microcontroller Adjustment of a DC to DC Converter

พุธ, 08/19/2015 - 15:01

[Hugatry] wanted to replace the adjustment pot on an LM2596 buck converter with a microprocessor-controlled voltage. The regulator IC uses a divider to generate a 1.25V reference from the output. The pot is part of a divider circuit that sets the output voltage. For example, if the divider is 10:1, the controller will keep the output at 1.25V and, therefore, the output voltage will be 12.5V.

[Hugatry’s] strategy was to use a filtered PWM signal from a microcontroller to offset the 1.25V signal. By adding a small voltage to the control point, the output voltage would not need to rise as high as before to maintain the 1.25V reference. For example, adding 0.25V to the reference input would only require 1V, which corresponds to a 10V output.

The video has a nice view of a scope showing the relationship between the PWM duty cycle and the output voltage. Although he didn’t mention it, it struck us that since PWM is proportional to the supply voltage, the voltage on the microcontroller and PWM output stage probably needs to be fixed. That implies you couldn’t use the buck converter to directly power the microcontroller itself. Then again, what kind of microcontroller needs to adjust its own power supply?

If you need a refresher on how DC to DC converters work, we’ve got you covered. Or, perhaps you’d rather measure PWM in the strangest way imaginable.

Filed under: Microcontrollers

Hackaday Prize Entry: The 70s Called. They Want This Calculator

พุธ, 08/19/2015 - 12:01

For those of us who grew up during TI’s calculator revolution, the concept of reverse polish notation (RPN) might be foreign. For other more worldly calculator users, however, the HP calculator was ubiquitous. Hewlett-Packard peaked (at least as far as calculators are concerned) decades ago and the market has remained dominated by TI since. Lucky for those few holdouts there is now a new microcode emulator of these classic calculators.

Called the NP25 (for Nonpariel Physical), the calculator fully emulates the HP-21, HP-25C and HP-33C. It’s a standalone microcode emulator, which means that these calculators work exactly as well as the original HP calculators of the 70s did. The new calculators, however, are powered by a low power MSP430G2553 processor and presumably uses many, many fewer batteries than the original did. It has an LED display to cut power costs as well, and was built with the goal of being buildable by the average electronics hobbyist.

Even if you didn’t grow up in the 70s with one of these in your desk drawer, it’d still be a great project and would help even the most avid TI user appreciate the fact that you don’t have to use RPN to input data into calculators anymore. Not that there’s anything wrong with that. This isn’t the only calculator we’ve featured here, either, so be sure to check out another free and open calculator for other calculator-based ideas.

The 2015 Hackaday Prize is sponsored by:
Filed under: Microcontrollers, The Hackaday Prize

Ferrofluid Clock is a Work of Art

พุธ, 08/19/2015 - 09:01

It is not usually too difficult to separate functionality from art. Consider a clock. It’s a machine that has a clear and distinct function. It provides information. Nothing could be more different from a clock on a wall than a piece of artwork.  A painting, for instance has no clear function and provides no information. It’s just…art. It’s nice to look at. If we were to ask you to build a functioning, information providing clock that is also a piece of artwork, you would surely have your hands full. Where would you even start? If your name was [Zelf Koelma], you’d grab a bottle of ferrofluid and build us a beautiful, almost mesmerizing clock.

There’s little to no information on the details of how the clock works other than the use of ferrofluid. But it’s not hard to guess that it uses dozens of electromagnets and an Arduino. You can even pick one up for a cool $8,300 if you’re lucky enough to get a spot on the list, as he’s only making 24 of them.

Want to make one of your own? Pick up some ferrofluid and keep us updated. We’d love to hear from you in the comments on how you’d implement a build like this one. We had a fun time hearing your ideas when we covered the clock made of clocks.

Thanks to [Itay] for the tip!

Filed under: clock hacks, slider

Reflow Solder Your Micro SD to Ensure it Doesnt Go Anywhere

พุธ, 08/19/2015 - 06:00

SD cards are great inexpensive storage for your embedded project. Using SPI,  they only take a few wires to hook up, and every micro-controller has a FAT file system interface to drop in your project. Problem with SD cards are the connectors.

Usually connectors cost more than the brains of your project,  and the friction fit, spring loaded contacts are not ideal for temperature swings, humidity and high vibration applications. Wouldn’t it be nice if you could just solder the thing down, especially if you know you are never going to remove it?

[Timothée] decided to try and succeeded in reflow soldering a Micro SD card direct to a breakout board. While starting as a what if experiment, the PCB was laid out in Ki-Cad and sent off to a fab. Once returned the Micro SD was fluxed, tinned and fluxed again, then reflowed using an IR setup.

The end result is a handy breakout board where you never have to worry about someone swiping the card to jam in their camera, and is ready for any breadboard project.

Filed under: Microcontrollers

Adventures With Vacuum Deposition Power Supplies

พุธ, 08/19/2015 - 03:01

[Jerry Biehler] called this a “fail of the week”, but of course failure is just another part of the hacker adventure. Fail and fail often!

[Jerry] has been slowly assembling a vacuum deposition system. These systems let you deposit thin films on a substrate. Vacuum deposition systems have all sorts of exciting applications, not only are they used in semiconductor manufacturing, but as [Ben Krasnow] has shown can create conductive transparent coatings. They’re even sometimes used for silvering mirrors.

A common feature of these systems is that they require high voltage, we’re not talking a few hundred volts or even a few thousand volts. But 10 to 20 kilovolts. You need such a high voltage in order to accelerate electrons and ions, which are used to eject atoms from a source and deposit them as a thin film on a substrate.

It was this HV supply [Jerry] was working on, cobbling the system together from parts found on eBay. Unfortunately [Jerry] could only reach 9kv unloaded, which we’d expect to drop considerably under load. So [Jerry] has now found a different solution. But this teardown and writeup still makes great reading.

We’re left to pondering on what projects the spare parts could be useful for: “I might be able to series the secondaries and get 30kv at 500ma! That would make one hell of a bug zapper! Actually these transformers scare the hell out of me….” me too Jerry! Me too!

Filed under: misc hacks

Embed with Elliot: The Volatile Keyword

พุธ, 08/19/2015 - 00:01

Last time on Embed with Elliot we covered the static keyword, which you can use while declaring a variable or function to increase the duration of the variable without enlarging the scope as you would with a global variable. This piqued the curiosity of a couple of our readers, and we thought we’d run over another (sometimes misunderstood) variable declaration option, namely the volatile keyword.

On its face, volatile is very simple. You use it to tell the compiler that the declared variable can change without notice, and this changes the way that the compiler optimizes with respect to this variable. In big-computer programming, you almost never end up using volatile in C. But in the embedded world, we end up using volatile in one trivial and two very important circumstances, so it’s worth taking a look.

Optimization and the Mind of the Compiler

volatile warns the optimizer that a variable can change without notice, so we need to know why that would ever matter. And for that, we’ll take a quick glimpse into the logic of (one type of) compiler optimization.

Since memory space is presumed to be scarce, a compiler’s going to want to make sure you’re not wasting it. One quick and easy way to do so is to check all the variables, and all the functions that call them, and see if they get changed or if they’re just constants in disguise. Simply put, that means that when the compiler sees something silly like this:

int a = 5; int b = 0; b = a + 2; printf("%d\n", b);

the compiler’s going to notice that you never use a anywhere in your code except that one place that you’ve set it equal to five, and that although you initialized b as zero but then all you do with it is add two to a and stored it in b. The compiler is going to see through all your foolery, and will compile the equivalent of the following code:

printf("%d\n", 7);

That’s optimization! It got rid of two variables that never really varied anyway, and freed up two bytes of RAM. But the takehome lesson for us here is that we’ll have to watch out for cases when we give the compiler the false impression that nothing’s changing when it actually is. And that’s the essential use of volatile.

And before we leave optimization, the “opposite” of volatile is not static as one might linguistically expect, but rather const which tells the compiler not only that the variable shouldn’t change, but also to throw a compiler error if you try to assign to it anywhere else in your code. Indeed, if you want to define a file-scoped, persistant variable that can change without warning (and this is common), you’d want static volatile.

Delay Loops

Maybe the first time a beginner would want to use volatile is in writing a delay routine. The simplest delay routine just has the CPU busy itself with counting up to some really big number. That is, you’ll try something like this:

int i; for (i=0; i<65000; ++i){ ; // just wait }

and expect it to slow the computer down, but it might not.

If you have optimization off, or if it’s set to a low-enough level, it’ll actually work. But with any real optimization on, the compiler will notice that you never actually use the variable i for anything, and it’ll optimize your code to the following:

That won’t serve very well as a delay function.

The solution is to declare i as volatile. The compiler now pretends that it doesn’t know when i can change, or when it’s going to be used by other functions, and it runs through the full for loop dutifully, just in case.

volatile int i; for (i=0; i<65000; ++i){ ; // run anyway, because something _could_ happen to i here }

(Note that this code works just as well to demonstrate the volatile qualifier on your desktop, but you won’t notice the delay unless you count up to a very large number. We tried out 65,000,000 instead, and it pauses for a tick on our desktop machine.)

That was the trivial example.  The next two are real bugs that catch real-life beginning embedded programmers all the time.

Interrupt Service Routines (ISRs)

ISRs are by their nature invoked only outside of the normal program flow, and this naturally confuses the compiler. Indeed, ISRs look to the compiler like functions that are never called, so the definition of ISR in AVR-GCC, for instance, includes the special “used” attribute so that the function doesn’t get thrown away entirely. So you can guess that things get ugly when you want to modify or use a variable from within a function that the compiler doesn’t know is even going to be used.

The good news is that you simply declare the variable as a volatile global variable (outside of the scope of main and the ISR in question) and everything works. The solution is super simple, but if you don’t do it, no errors will be thrown and your ISR simply will appear not to be working because the compiler will replace the variable with a constant.

Here’s what the right way looks like in a simple example:

volatile uint16_t counter=0; ISR(timer_interrupt_vector){ ++counter; } int main(void){ printf("%d\n", counter); }

If counter weren’t marked volatile, you can see how it looks like a constant within the context of main, right? Now you won’t fall for this common beginner pitfall.

Memory-mapped Hardware Registers

The second non-trivial use of volatile in embedded programming is in the declarations of memory-mapped hardware; a microcontroller interacts with the world by reading and writing voltages on its various pins, and the pin states are usually made available to your code as specially mapped locations in memory. When the pins are configured as input, for instance, your code can read a bit from a specific memory location to test if the pin is at a logic high or low voltage level. So far, so good.

But while you see pins on which the external voltages can change without notice, the compiler sees normal-looking memory locations, unless it’s taken care of in your code. In general, this is taken care of by the manufacturer’s libraries, so you’ve been able to pretend that nothing’s afoot. But as long as we’re looking into the volatile qualifier, let’s dig quickly into the chip-specific codebases.

For instance, in the pin definition files that get included with any AVR project, you can dig through a chain of definitions to get down to a volatile definition for the PIN registers which are used for reading input:

#define PINB _SFR_IO8 (0x03) // and #define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET) // and finally #define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

Phswew! That is, PINB turns into a volatile pointer to an eight-bit integer, where the specified memory address is built up as an IO address plus an offset. But the point here is that this pointer to this memory location is explicitly declared as volatile and that the compiler knows that it’s changeable.

The same goes for ARM chips. In the ARM-standard CMSIS port definitions, the GPIO memory locations are contained inside a bigger struct, GPIO_TypeDef, that takes care of the relative memory offsets, but if you look into those type definitions (here from ST’s implementation), you find:

// in stm32f4xx.h __IO uint32_t IDR; /*!< GPIO port input data register, Address offset: 0x10 */ // and in core_cm7.h /* IO definitions (access restrictions to peripheral registers) */ #define __IO volatile /*!< Defines 'read / write' permissions */

Tadaa! As promised. And it really had to be so, because otherwise the compiler would look at every instance where the data registers are called and notice that they never change.


So that’s it. volatile simply convinces the compiler not to optimize over a variable that’s apparently constant. But until you’ve been bitten by the resulting bugs, you might not have even known just exactly what types of things the compiler is able to optimize away, and thus which variables you need to flag as volatile. We’ve hit the most common pitfalls, but if we’ve missed any situations where you’d use volatile, please let us know in the comments below.

Filed under: Hackaday Columns, Microcontrollers

Arduboy Classic Plays On Original Game Boy Screen

อังคาร, 08/18/2015 - 22:31

The Arduboy is a Kickstarter backed, 8 bit video game console that mimics the look of a very tiny Nintendo Gameboy. The Arduboy Classic is actually using the case, button and LCD screen from a classic Game Boy.

[uXe] is using the same brains, an ATMEGA32U4, along with a 328 as a co-processor to handle the classic “creme-n-spinich” gameboy screen. 2K of dual port ram acts as a buffer between the two micro-controllers meaning they can not only run while not being in lock step with eachother, but that each micro can read or write to the ram at the same time.

Currently the whole setup is spread out on a breadboard while all the interfacing is worked out, but it is working quite well. Future plans are to make a drop in motherboard replacement for the classic game system, and there is ample room for all the new electronics on the original footprint.

If you’re unfamiliar with the Arduboy project, check out our interview with it’s creator, [Kevin Bates]. That and the demo of [uXe’s] hack based on the project are both found after the break.

Demos powered by Arduboy on Classic Display

Arduboy Interview with [Kevin Bates]

Filed under: Arduino Hacks, handhelds hacks, nintendo hacks