Syndicate content Hackaday
Fresh hacks every day
ถูกปรับปรุง 5 min 32 sec ก่อน

Friction Welding… Wood?

อาทิตย์, 11/08/2015 - 22:00

You’d think writing for Hack a Day means we probably don’t get surprised very often by projects… but then we see something we never thought was possible — in this case, the linear friction welding of wood to join it.

Friction welding (also known as stir welding), is the process of taking two pieces of material (typically metal, or plastic), and vibrating one of them super fast while pushing against a stationary piece of the same material — the resulting friction causes a massive heat buildup that can then literally weld the two pieces of material together.

It’s an easy way to bond plastic parts together using a dremel and some 3D printing filament, and while doing it with metal is significantly harder, it is possible to do at home as well.

But according to the video after the break — it’s actually possible to do this with wood.

They’re using a linear friction welding machine which oscillates the sample at about 200hz. Their best guess is linen lignin cells within the wood are melting, interlocking and rejoining — resulting in a surprisingly strong bond.

They say further research is to be performed but the video is a few years old now and we still don’t see any updates on it — have you ever heard of using friction welding to bond wood?

[Thanks for the tip Karl Rosenqvist!]

Filed under: tool hacks

Casting Turbines For A World Speed Record Motorcycle

อาทิตย์, 11/08/2015 - 19:00

[Anders] is going to beat the land speed record for a turbine-powered motorcycle. It’s a project he’s been working on for years now, and just this week, he put the finishing touches on the latest part of the build. He successfully cast the compressor for a gas turbine engine that’s twice as powerful as the one he has now.

This compressor piece was first 3D printed, and this print was used as a positive for a sand – or more specifically petrobond – mold. The material used in the casting is aluminum, fluxed and degassed, and with a relatively simple process, [Anders] came away with a very nice looking cast that only needs a little bit of milling, lathing, and welding to complete the part.

In the interests of accuracy, and just to make sure there’s no confusion, this ‘jet’ engine is actually a gas turbine, of which there are many configurations and uses. The proper nomenclature for this engine is a ‘turboshaft’ because the power is directed to a shaft which drives something else. This is not a new build; we’ve been covering [Anders]’ build for the better part of two years now, and although [Anders] intends to break the world record at the Bonneville salt flats eventually, he won’t be beating the ultimate land speed record – that title goes to a car – and he won’t be beating the speed record for all motorcycles. Instead, [Anders] plans to break the record for experimental propulsion motorcycles, or motorcycles powered by electric motors, steam, jet engines, or in this case, ‘turboshafts’.

It should also be noted that [Anders] frequently does not wear hearing or eye protection when testing his gas turbine engine. That is an exceedingly bad idea, and something that should not be attempted by anyone.

As an additional note for safety, in the video below of [Anders] pouring aluminum into his mold, the ground looks wet. This is terrifically dangerous, and steam explosions can kill and maim even innocent bystanders. This is not something that should be attempted by anyone, but we do thank [Anders] for sharing his project with us.

Filed under: 3d Printer hacks, tool hacks

Weather Word Clock Warns You Of Impending Winter

อาทิตย์, 11/08/2015 - 16:01

Word clocks are pretty popular “artsy” ways of telling time, but [doktorinjh] wanted to try something a little different. So instead of showing the time — it shows the weather.

He’s using an Arduino Yun to access the Weather Underground API for data and then sends the data out to a grid of 100 individually addressable RGB LEDs — NeoPixels to be precise. The LEDs are overlayed with a laser cut acrylic sheet with various words and weather icons to allow for a pretty specific depiction of current (or future) weather conditions.

The frame is made out of colonial style molding and since it’s a weather clock, he turned the grid of LEDs into a rainbow effect, because, why not?

He’s got more photos and a build log in his photo album, which you could use to create your own.

As far as word clocks go, we’re quite partial to this entirely laser cut one, and we have to give mention to what is probably the world’s smallest word clock as well!

Filed under: clock hacks, laser hacks

Compressorhead: Best Robot Band Ever?

อาทิตย์, 11/08/2015 - 13:01

We’ve written about Compressorhead before but we’re writing about them again. Why? Because Compressorhead is the most amazing robot band you’ve ever seen, and because they’ve just opened up a Kickstarter to fund building a lead singer robot and recording an album.

And because they’ve released a bunch of new videos, one of which you’ll find below the break.

Animatronic bands playing to pre-recorded background music are Chuck-E-Cheesy. Compressorhead, in contrast, slays it. We don’t know if it’s the fact that they’re actually playing real instruments “live” or if it’s just that the folks behind the scenes are really brilliant MIDI programmers, but Compressorhead sounds really good.

What’s more, they look really good. Dig the mini-me version of the drummer robot that’s headbanging and stomping on the hi-hat pedal with his little robot feet wearing actual boots and a gas mask. His mohawk is made of valve-lifters. No further questions, your honor.

The bass player bot’s bobbing head and the way he leans forward from time to time is uncanny. And the guitarist has a limited variety of moves besides bobbing his head, but makes up for being immobile by having 78 fingers on his fretting hand.

If you can’t get enough Compressorhead, visit their regular website and check out this hour-long concert they played last year in Moscow. By the end, you’ll probably agree that are the most amazing music bots you’ve seen, and that they desperately need a lead singer to tie the whole thing together. We’re hoping that the bot has at least a bit more stage presence than Courtey Love.

Filed under: Crowd Funding, musical hacks, robots hacks

Measuring Tire Pressure By Cutting A Hole In An Inner Tube

อาทิตย์, 11/08/2015 - 10:01

RFID tags are really very primitive pieces of technology. Yes, they harvest energy from an RFID reader and are able to communicate a few bits of data, but for a long time these tags have been unable to provide useful data beyond a simple ID number. [CaptMcAllister] found a new RFID sensor platform from TI and managed to make a wireless pressure sensor that fits in the inner tube of his bike.

The sensor [Capt] is using comes from TI’s RF430 series that include a few neat sensors that don’t require batteries, but are still able to communicate sensor data to a cell phone or other RFID reader. With a pressure sensor, this tiny microcontroller can receive power from an RFID reader and send it back to a phone app, all without wires.

[CaptMcAllister] cut open an inner tube for his bike, epoxied his PCB to a patch, and sealed everything back up again. After a quick test for leaks, [Capt] found the data coming from the sensor was extraordinarily accurate, and should hold up well enough to be used in his bike.

Filed under: Microcontrollers, slider

Air Quality Surveillance for Whole Cities

อาทิตย์, 11/08/2015 - 07:01

Air quality is becoming a major issue these days, and not just for cities like Beijing and Los Angeles. It’s important for health, our environment, and our economy no matter where we live. To that end, [Radu] has been working on air quality monitors that will be widely deployed in order to give a high-resolution air quality picture, and he’s starting in his home city of Timisoara, Romania.

[Radu] built a similar device to measure background radiation (a 2014 Hackaday Prize Semifinalist), and another to measure air quality in several ways (a 2015 Hackaday Prize Finalist and a Best Product Finalist; winners will be announced next weekend). He is using the platforms as models for his new meter. The device will use a VOC air sensor and an optical dust sensor in a mobile unit connected to a car to gather data, and from that a heat map of air quality will be generated. There are also sensors for temperature, pressure, humidity, and background radiation. The backbone of the project is a smart phone which will upload the data to a server.

We’ve seen other air quality meters before as well, and even ones based around the Raspberry Pi,  but this one has a much broader range of data that it is acquiring. Its ability to be implemented as an array of sensors to gather data for an entire city is impressive as well. We can envision sensor networks installed on public transportation but to get to all parts of every neighborhood it would be interesting to team up with the Google Streetview Cars, Uber, or UPS.

Filed under: green hacks

Low Power and Pin-Constrained

อาทิตย์, 11/08/2015 - 04:01

We’ve all been there. You’re building up a microcontroller project and you wish that you could just add “one more feature” but you’re limited by the hardware. Time to start thinking. (Or, arguably, buy the next model up.)

[Sam Feller] found himself in this position, adding a knob to set the time and a button to arm the alarm for his Analog Voltmeter Clock, and he came up with a way to implement an on-off switch, and poll a button and a potentiometer with only two pins of a microcontroller.

The problem with potentiometers in low-power designs is that they’re always leaking power. That is, unless you switch them off when you’re not using them. So the ideal solution is to power the potentiometer from one GPIO pin on the microcontroller, and read its value with another. That’s two GPIO pins just for the potentiometer. But [Sam] needed to read input from a button too, and he was out of pins.

His clever solution is to switch two resistors in or out of the circuit depending on the status of the pushbutton, so that the voltage range at the potentiometer is between either VCC and VCC/2 when the switch is pressed, or between VCC/2 and GND when the switch is not pressed.

If the ADC reads something higher than VCC/2, the microcontroller knows that the button is pressed, and vice-versa. The potentiometer’s setting determines exactly where the voltage lies within either range.

Done and done. If you find yourself in the similar situation of needing to read in values from a whole bunch of buttons instead of a potentiometer, then you can try using an R-2R DAC wired up to the pushbuttons and reading the (analog) value to figure out which buttons are pressed. (If you squint your eyes just right, this solution is the same as the R-2R DAC one with the potentiometer replacing all but the most-significant bit of the R-2R DAC.)

Another tool for the toolbox. Thanks [Sam].

Filed under: Microcontrollers, misc hacks

Converting Live 2D Video to 3D

อาทิตย์, 11/08/2015 - 01:01

Here’s some good news for all the fools who thought 3D TV was going to be the next big thing back in 2013. Researchers at MIT have developed a system that converts 2D video into 3D. The resulting 2D video can be played on an Oculus Rift, a Google Cardboard, or even that 3D TV sitting in the living room.

Right now, the system only works on 2D broadcasts of football, but this is merely a product of how the researchers solved this problem. The problem was first approached by looking at screencaps of the game FIFA 13. Using an analysis tool called PIX, the researchers both stored the display data and extracted the corresponding 3D map of the pitch, players, ball, and stadium. To generate 3D video of a 2D football broadcast, the system then looks at every frame of the 2D broadcast and searches for a 3D dataset that corresponds to the action on the field. This depth information is then added to the video feed, producing a 3D broadcast using only traditional 2D cameras.

Grab your red and blue filter shades and check out the product of their research below.

Filed under: video hacks

Hacklet 83 – Tiny Robot Projects

เสาร์, 11/07/2015 - 22:01

Hackers, makers, and engineers have been hacking on robot projects since the era of clockwork mechanics. Any robot is a cool project, but there is something particularly attractive about small ones. Maybe it’s the skill required to assemble them, or perhaps it’s the low-cost. Either way, there are lots of palm-sized robot projects on Hackaday.io. This week on the Hacklet, we’re going to highlight a few of them!

We start with the granddaddy of them all, [shlonkin] and Tiny robot family. [Shlonkin] built line following robots that can hide under a US half-dollar coin. The robots are simple circuits – an ATtiny85 with an LED and pair of phototransistors. The code is provided both in Arduino’s wiring, and in straight C++. Two coreless motors, normally used in cell phones vibrators or quadcopters, provide the locomotion. These robots only know one thing – moving forward and following a line. They do it well though! We love this project so much that we hosted a tiny robot workshop at the 10th anniversary back in 2014.

When it comes to tiny walking robots, [Radomir Dopieralski] is the king. Many of his projects are small biped, quadruped, or even hexapod robots. He’s done things with 9 gram nano servos that we thought were impossible. Tote, an affordable spider robot, is his latest creation. Tote is a four-legged bot utilizing 12 9 gram servos. [Radomir] created a custom PCB for Tote, which acts as a carrier for its Arduino Pro Mini Brain. This robot is easily expandable – [Radomir] has experimented with the Teensy 3 series as well. Controlling the robot can be anything from an ESP8266 to an infrared remote control.

[Alan Kilian] may well have the ultimate tease project with Hand-wound inductors for a tiny robot. [Alan] was using some tiny GM-10 motors on his micro-bot. The motors didn’t have inductance for the locked-antiphase drive controller. His solution was to wind some coils to provide a bit of added inductance. The mod worked, current consumption dropped from 116 ma to about 6 ma. We want to know more about that ‘bot though! It’s controlled by a Megabitty, [Monty Goodson’s] ATmega8 controller board from sometime around 2003. The lilliputian board has been very popular with the nano sumo crowd. Other than the controller, motors, and the plywood frame, [Alan] has left us guessing about his robot. If you see him, tell [Alan] to give us more info on his micro robot’s design and construction!


[Ccates] jumped on the tiny robot bandwagon with Tiny wi-fi robot. Rather than go with an Arduino for control, [Ccates] grabbed the popular ESP-8266 WiFi module. The construction of the bot is inspired by [shlonkin’s] tiny robot family up above. This bot is controlled by the Xtensa processor embedded in the ESP-8266. Since it only drives forward, it only takes two GPIO pins to control the transistors driving the motors. Even the diminutive ESP-01 module has enough I/O for that. We’d love see some sensors and a full H-bridge on this micro beastie!


If you want to see more palm-sized robot projects, check out our new tiny robot projects list! These ‘bots are small, so I may have missed yours. If that’s the case, don’t be shy, just drop me a message on Hackaday.io. That’s it for this week’s Hacklet. As always, see you next week. Same hack time, same hack channel, bringing you the best of Hackaday.io!

Filed under: news

Knappa Tutu: Some Dancing Required

เสาร์, 11/07/2015 - 19:01

Sometimes, you see a lamp shade and you’re just intoxicated enough to put it on your head like a hat and dance around on the table. Other times, you see the same lamp shade, and decide to wire it up with Neopixels, an accelerometer, and an Arduino and make a flowery, motion-activated light show when you wear it as a dress. Or at least that’s what we’ve heard.

[Cheng] gets full marks for the neo-IKEA name for the project and bonus points for clean execution and some nice animations to boot. The build is straightforward: build up the lamp so that it fits around your waist, zip-tie in the RGB LED strip, and connect up accelerometer and microcontroller. A tiny bit of coding later, and you’re off to the disco. It looks like a ridiculous amount of fun, and a sweet weekend build.

The code is up on GitHub if you’re doing your own accelerometer-to-color-patterns device. Tweak the animations and make them your own, or just leave them as-is and count on your individualistic rump-shaking skills to avoid the eventual embarrassment when someone else steps into the club wearing the same dress as you.

Oh, and we love this image of the builder wearing the dress, lit up, with laptop in her hand tweaking the code. “Dress up and debug” indeed!

Thanks [Michael Philetus Weller] for the tip!

Filed under: led hacks, misc hacks, wearable hacks

Breaking Out A Game Boy Link Cable

เสาร์, 11/07/2015 - 16:01

[Samuel] is working on one of the most important electronics projects of our generation. He’s building a device for the Game Boy that will allow Pokemon trades between generation II and III. Yes, This means bringing your Charmander from Pokemon Red to your team in Pokemon Ruby, Sapphire, or Emerald. and finally completing the National Dex you’ve been working on for 20 years. Before he gets to designing this system, he first needs to listen in on the Game Boy Link Cable, and that means creating a breakout board.

The Game Boy Link Cable – sometimes inaccurately referred to as the Zelda cable – is a special proprietary connector. The design is well documented, but unlike the Wii Nunchuck controller, there’s no readily available breakout board available for this piece of obsolete technology.

Together with a his friend [David], [Samuel] loaded up a copy of Eagle and designed a board that will fit on a small piece of copper clad FR4. This design was then sent over to a small CNC mill, The traces were machined away, and a sextet of pins were soldered into the holes.

With a breakout board for the Game Boy Link Cable, [Samuel] now has a great platform for peering into the strange and magical world of Pokemon. He’ll be using a Teensy microcontroller for his trading device, and with several similar projects already completed by others around the Internet, the potential for a Gen II to Gen III Pokemon trader is palpable.

Filed under: classic hacks, cnc hacks

BitDrones are Awesome, Ridiculous at Same Time

เสาร์, 11/07/2015 - 13:01

At first we thought it was awesome, then we thought it was ridiculous, and now we’re pretty much settled on “ridiculawesome”.

Bitdrones is a prototype of a human-computer interaction that uses tiny quadcopters as pixels in a 3D immersive display. That’s the super-cool part. “PixelDrones” have an LED on top. “ShapeDrones” have a gauzy cage that get illuminated by color LEDs, making them into life-size color voxels. (Cool!) Finally, a “DisplayDrone” has a touchscreen mounted to it. A computer tracks each drone’s location in the room, and they work together to create a walk-in 3D “display”. So far, so awesome.

It gets even better. Because the program that commands the drones knows where each drone is, it can tell when you’ve moved a drone around in space. That’s extremely cool, and opens up the platform to new interactions. And the DisplayDrone is like a tiny flying cellphone, so you can chat hands-free with your friends who hover around your room. Check out the video embedded below the break.

On the other hand, for a human-computer interface, we have to say that the examples they picked just aren’t a good fit. For instance, have a look in the video where the drones are used to represent files in a directory (42 seconds in). Either there are only three files in the directory, or they ran out of drones. And rotating through the three is a bit slow because the physical drones have to fly to new locations to select a file. We’re thinking of that directory with 200 photos that we just downloaded from our camera.

The section of the video where they use the three ShapeDrones to stand in for a 3D physical model (52 seconds in) is awesome again. The user positions the drones in space, and they hover there and presumably this moves around some part of a 3D model in a computer somewhere. We love it. But again they run into the difference between virtual and real; three voxels, even if they are very elegant and in RGB color, isn’t enough for any serious modeling. Even a modest real-world project is going to take a fleet of these things, which would be fantastic but incredibly expensive.

Finally, epitomizing the simultaneous awesome and head-scratching of this project, they translate the pinch gesture (to enlarge or shrink an image) from the touchscreen to the real world (1:52 into the video). That’s super cool in principle, and we love the movement. But in the video, the demo guy nearly gets hit on the shoulder by the third pixel shrinking inwards toward the other two. We’re imagining a user with long hair and a model with many more copters. The horror!

In the end, using an interaction design term, the virtual and physical worlds have different affordances, and that’s a physical fact that the project either tries to blur or ignore. Quadcopters aren’t pixels: you can’t have a million of them, and even if you could they’re slow to reconfigure and harder to manipulate. That said, something beautiful has been designed here, and we’re absolutely sure that there’s an application out there that fits it.

So, for navigating files, we’ll stick with the mouse. But we totally want a room full of flying RGB cubes!

Filed under: drone hacks, slider

The USB Killer – Now A Crowdfunding Campaign

เสาร์, 11/07/2015 - 10:00

Kickstarter, Indiegogo, and every other crowdfunding site out there frequently have projects that should never be products. The latest promises to protect you from security breaches and identity theft by blowing up your computer. It’s the USB Killer, and for only $99 USD, you too can destroy the USB port in your computer and everything else attached to it.

The USB Killer is a device that plugs into the USB port on any computer, charges up several caps, and dumps all that voltage back into the computer. The process repeats until something breaks. We’ve seen it used on a poor Thinkpad X60, and from the video evidence it does exactly what it’s designed to do: kill a computer.

The Indiegogo campaign for the USB killer comes with a web page for the campaign that goes over the function of the device in much more detail. Inside the USB killer is a DC/DC converter that charges a few capacitors to -110V. When the caps are charged, that voltage is dumped back into the USB port where something will happen. Somewhat surprisingly, the folks behind the USB Killer have a video of a computer not dying when the USB Killer is plugged in. Only killing the USB port in a computer is not a guaranteed functionality, as the Indiegogo campaign has the following disclaimer: “Please be aware: USB Killer may cause damage to the motherboard, depending on your computer. By making a pre-order you acknowledge that you are aware of this fact.”

Filed under: Crowd Funding

Three Watt Individually Addressable RGB LEDs

เสาร์, 11/07/2015 - 07:00

While the gold standard for colorful blinky projects are individually controllable RGB LEDs, the usual offerings aren’t really that impressive. Yes, a few hundred Neopixels, WS2812, or other RGB LEDs will sear your retinas, but what if you wanted blinky glowy stuff that is so over the top as to be an affront to whatever creator you believe in?

This is it. [Ytai Ben-Tsvi] created an individually addressable RGB LED called the Pixie that is perfect for all the times when you need something bright, colorful, and want to blind a few people in the process.

WS2812s and Neopixels are basically RGB LEDs with a small microcontroller tucked tucked away inside, and so far there is no design house or fab plant in China that is crazy enough to add one of these tiny dies to an already overpowered LED. To build the Pixie, [Ytai] took a bare RGB LED module and added a microcontroller – a PIC12FF157X in this case. It’s not exactly a powerful microcontroller, but it can handle the shift register-like function of an individually addressable RGB, and adds gamma correction, over heating protection (something necessary when you’re dumping this much power into a tiny board, and other safeguards for each individual LED.

[Ytai] is working with Adafruit to produce these Pixies, and although they’re rather expensive at $15 per LED, you won’t need very many to blind yourself.

Filed under: led hacks

Stegosploit: Owned by a JPG

เสาร์, 11/07/2015 - 03:00

We’re primarily hardware hackers, but every once in a while we see a software hack that really tickles our fancy. One such hack is Stegosploit, by [Saumil Shah]. Stegosploit isn’t really an exploit, so much as it’s a means of delivering exploits to browsers by hiding them in pictures. Why? Because nobody expects a picture to contain executable code.

[Saumil] starts off by packing the real exploit code into an image. He demonstrates that you can do this directly, by encoding characters of the code in the color values of the pixels. But that would look strange, so instead the code is delivered steganographically by spreading the bits of the characters that represent the code among the least-significant bits in either a JPG or PNG image.

OK, so the exploit code is hidden in the picture. Reading it out is actually simple: the HTML canvas element has a built-in getImageData() method that reads the (numeric) value of a given pixel. A little bit of JavaScript later, and you’ve reconstructed your code from the image. This is sneaky because there’s exploit code that’s now runnable in your browser, but your anti-virus software won’t see it because it wasn’t ever written out — it was in the image and reconstructed on the fly by innocuous-looking “normal” JavaScript.

And here’s the coup de grâce. By packing HTML and JavaScript into the header data of the image file, you can end up with a valid image (JPG or PNG) file that will nonetheless be interpreted as HTML by a browser. The simplest way to do this is send your file myPic.JPG from the webserver with a Content-Type: text/html HTTP header. Even though it’s a totally valid image file, with an image file extension, a browser will treat it as HTML, render the page and run the script it finds within.

The end result of this is a single image that the browser thinks is HTML with JavaScript inside it, which displays the image in question and at the same time unpacks the exploit code that’s hidden in the shadows of the image and runs that as well. You’re owned by a single image file! And everything looks normal.

We like this because it combines two sweet tricks in one hack: steganography to deliver the exploit code, and “polyglot” files that can be read two ways, depending on which application is doing the reading. A quick tag-search of Hackaday will dig up a lot on steganography here, but polyglot files are a relatively new hack.

[Ange Ablertini] is the undisputed master of packing one file type inside another, so if you want to get into the nitty-gritty of [Ange]’s style of “polyglot” file types, watch his talk on “Funky File Formats” (YouTube). You’ll never look at a ZIP file the same again.

Sweet hack, right? Who says the hardware guys get to have all the fun?

Filed under: computer hacks, misc hacks, security hacks

Code Craft – Embedding C++: Classes

เสาร์, 11/07/2015 - 00:00

For many embedded C developers the most predominate and questionable feature of C++ is the class. The concern is that classes are complex and therefore will introduce code bloat and increase runtimes in systems where timing is critical. Those concerns implicate C++ as not suitable for embedded systems. I’ll bravely assert up front that these concerns are unfounded.

When [Bjarne Stroustrup] created C++ he built it upon C to continue that language’s heritage of performance. Additionally, he added features in a way that if you don’t use them, you don’t pay for them.

Data Hiding

Prior to the object-oriented paradigm shift in, roughly, the early 90s, structured programming was the technique to use. One of the principles that came with it was data or information hiding.

A good example for C programmers is the FILE pointer (FILE*). The only thing you know about a FILE* is that it points to a data structure somewhere in a library. You can open, read, write, and otherwise manipulate a FILE* through a set of functions. The actual data about the file you’re working with is hidden. In a sense, this is a step toward object- oriented programming. The FILE* points to the object, a struct, and the functions are the class methods that operate on the object, or instance.

[Stroustrup] took C’s struct and extended it to create a class based form of object-orientation. He might have taken another approach since there are other forms of object- orientation. For instance, if you work heavily with JavaScript you’re doing prototype object- oriented development.

Let’s look at classes and their non-existent code bloat in this article. We’ll encounter some other features of C++ along the way. I’m compiling with C++11 as implemented by the GNU Project GCC compilers to obtain the latest features of the language. I chose it because it’s the compiler used by the Arduino family of boards and can be used by the Raspberry Pi. It is often available for other processors, making it well suited for the hacker community.

I’ll be compiling the code for both an Uno and a Due board to illustrate that the type of processor is irrelevant. The Uno uses an ATmega328P 8-bit processor and the Due an ATSAM3X8E ARM Cortex-M3 CPU 32-bit processor, so there is quite a difference between them.

Declaring Classes

Classes are user defined types (UDTs). In C++ classes, structs, unions, and enums are all UDTs. A UDT is the equal of the data types you are familiar with in C: integer, char, float, double, etc. UDTs act just like built in data types in C++ statements: initialization, function calls, function return values. Operations on UDTs mimic the built in operations: arithmetic operations, logical operations. It was a design goal for C++ that UDTs and regular data types operate with no noticeable differences.

[Elliot] discussed ring buffers in a recent article, Embed with Elliot: Going ‘Round with Circular Buffer, so I borrowed his C code with a few modifications and created this equivalent C++ class:

namespace had { using uint8_t = unsigned char; const uint8_t bufferSize = 16; class RingBuffer { uint8_t data[bufferSize]; uint8_t newest_index; uint8_t oldest_index; public: enum BufferStatus { OK, EMPTY, FULL }; RingBuffer(); BufferStatus bufferWrite(const uint8_t byte); enum BufferStatus bufferRead(uint8_t& byte); }; }

The first new C++ features in the code are the namespace and using keywords. They aren’t specific to classes so let me defer explaining them for a few paragraphs.

A class declaration begins with the keyword class followed by a name, just as C creates structs. In fact, struct could be used here instead of class. The difference between the two is struct, by default, provides public access to data and member functions while a class restricts access by default.

The next three lines declare data members of the class exactly as you would do with a struct in C. Since this is a class the members are private and cannot be accessed from outside the class. This is how C++ supports and stringently enforces data hiding.

The public keyword says the following lines are openly available. These can be accessed outside the class. You can also use private in the same way as public to make the following lines not accessible. A third access keyword is protected but it is used for class inheritance, a more advanced discussion, and we’ll ignore it for now. These access control keywords can be mixed as you wish in a class.

Next an enum is specified. Here it works just like a C enum.

The next line declares the class constructor. The purpose of a constructor is, in my vernacular, to make the class sane when it is created. It should set all the variables in the class to default starting values and contain code that sets up the class for proper operation. That may mean allocating dynamic memory for the class to use. For instance, RingBuffer could be setup to handle buffers of a chosen length instead of a globally defined fixed length. The length would be passed as an argument to the constructor and used to size the dynamically allocate memory.

The next two lines are member functions for writing and reading bytes of data to and from the buffer, the array data, in the class. There is no difference between these declarations and similar ones in C, except for one more C++ feature that is again not specific to classes, the & in the parameter declaration for bufferRead(uint8_t& byte). The & indicates the parameter is passed by reference. We’ll add that to the list of additional features to discuss below.

These are the basics for classes as UDTs. There are a lot of details about their design and implementation but those are beyond the scope of this article. A key point is that a class encapsulates within it all the capabilities you would provide for a data structure in C.

Using the Class

The code using RingBuffer is just a skeleton to illustrate how classes are used:

had::RingBuffer r_buffer; void setup() { } void loop() { uint8_t tempCharStorage; // Fill the buffer for (int i = 0; r_buffer.bufferWrite('A' + i) == had::RingBuffer::OK; i++) { } // Read the buffer while (r_buffer.bufferRead(tempCharStorage) == had::RingBuffer::OK) { } }

Line 1 of the code is the definition of a RingBuffer variable. The had:: is a scoping operation that tells the compiler to use the RingBuffer declared in the had namespace. Similarly, on lines 9 and 12, the enums OK are scoped in had.

Calls to class member functions use the same dot-notation that C uses for accessing members of structs. The calls are just r_buffer.bufferWrite and r_buffer.bufferRead. If you want to call a class member function from a pointer to a variable the arrow-notation is used. Except for that adaptation, member functions calls are the same as C calls.

Behind the scenes, the compiler is passing r_buffer as a hidden parameter to the member functions. It is passed as a pointer and within the functions is accessed by the name this. You can access the member data using the this pointer like this->newest_index but it is typically unnecessary. There are situations where it is used.

C Version of Code

For completeness let’s look at the C version of the code. It’s remarkably similar. Here are the declarations:

typedef unsigned char uint8_t; enum BufferStatus {BUFFER_OK, BUFFER_EMPTY, BUFFER_FULL}; #define BUFFER_SIZE 16 struct LifoBuffer { uint8_t data[BUFFER_SIZE]; uint8_t newest_index; uint8_t oldest_index; }; void initBuffer(struct LifoBuffer* buffer); enum BufferStatus bufferWrite(struct LifoBuffer* buffer, uint8_t byte); enum BufferStatus bufferRead(struct LifoBuffer* buffer, uint8_t *byte);

We’ve got a typedef instead of the using, and a define instead of a const. After that LifoBuffer defines the same data, and the function declarations are about the same. The initBuffer serves basically the same purpose as the constructor. And we see a pointer instead of a reference.

One difference is the explicit passing of the pointer to the data structure. That is the same as the hidden this that C++ passes to member functions.

The calling routines look very similar also:

struct LifoBuffer buffer; void setup() { initBuffer(&buffer); } void loop() { uint8_t tempCharStorage; // Fill the buffer uint8_t i = 0; for (; bufferWrite(&buffer, 'A' + i) == BUFFER_OK; i++) { } // Read the buffer while (bufferRead(&buffer, &tempCharStorage) == BUFFER_OK) { } } Source Files

Sorry to disappoint, but I’m not going to post the complete source files. You wouldn’t see any more difference than in the calling routines. But here is a snippet from each to satisfy your curiosity. I’ll show the bufferRead function so you can see how the reference parameter is handled. First the C++:

RingBuffer::BufferStatus RingBuffer::bufferRead(uint8_t& byte) { if (newest_index == oldest_index) { return EMPTY; } byte = data[oldest_index]; oldest_index = nextIndex(oldest_index); return OK; }

Now the C version:

enum BufferStatus bufferRead(struct LifoBuffer* buffer, uint8_t *byte) { if (buffer->newest_index == buffer->;oldest_index) { return BUFFER_EMPTY; } *byte = buffer->data[buffer>oldest_index]; buffer->oldest_index = nextIndex(buffer->oldest_index); return BUFFER_OK; }

The major difference is the C++ version looks cleaner without the pointer dereferencing operators needed in C to access the buffer data structure. The parameter byte, the reference, also is accessed more easily. The main drawback with the C++ version is the need for the scoping operator, the ::, necessary to tell the compiler the functions and enums are part of the RingBuffer class.

There are two advantages to having the BufferStatus enum within the class RingBuffer that make using the scoping operator worth the effort. First, the enum names are shortened by having the buffer_ prefix removed. The scoping operator tells the developer and the compiler when these status values are valid. Second, it avoids name conflicts that can cause confusion. You might have other classes that use a status of OK or FAIL. Those may not use the same underlying values. If those classes are buried in a library you have no way of changing their values. One may say OK‘s value is 1, and the other 4. The scoping operator sorts out that problem, and the compiler enforces it by refusing to allow an enum from one class to be used with another.

Additional C++ Features

Let’s back up and look at the additional features of C++ we’ve encountered: namespaces, using, and references.


I didn’t intend to introduce namespaces in this article but the need to use them came up when I compiled the C++ code for the Due. I’d been compiling for the Uno without any problems; but when I switched to the Due, the compiler generated errors that it took me a few moments to understand: my RingBuffer class name was clashing with a RingBuffer class name used by the Due for serial communications.

Name clashes amongst libraries and user code is exactly the reason for having namespaces. I could have changed the name of my class to FifoBuffer which is actually a better name because it describes the usage while RingBuffer describes the implementation. Another name, more Computer Science oriented, is queue. I didn’t use it because the C++ standard library implementation of a FIFO is named queue. I left it at RingBuffer so I could discuss namespaces.

Creating a namespace is easy:

namespace <name> { // some code }

So is using one:

using namespace <name> { // some code }

I wrapped the entire header file, RingBuffer.h, and the source file, RingBuffer.cpp, in the namespace had, for HackADay.

In the Application.cpp file where I used the RingBuffer class I needed to qualify the constructor and the uses of the BufferStatus enums with the had namespace so the compiler knew I wanted them, not the ones from the library.

Aliases: Using and References

Both the using keyword and references create aliases. The ability to create aliases is a general feature of C++ that was extended and improved in C++11. For the most part, aliases allow the use of simpler names to refer to more complex expressions.


The using keyword creates an alias for a complex data type. Here the type unsigned char is given the alias uint8_t. This usage replaces the use of typedef, which still available to not break legacy code. If this simple example doesn’t impress you how about having an alias to simplify const unsigned long int* const or a pointer to a function with a large number of parameters.

Here are the two lines of code from above:

using uint8_t = unsigned char; const uint8_t bufferSize = 16;

Notice how the statements are similar. The second line creates the variable bufferSize and initializes it to the value 16. The first line creates the name uint8_t and sets it to the data type unsigned char. This parallelism of the constructs is why using was introduced. A big effort in C++11 was the standardizing of expression forms along these lines.


References are a feature of C++ that appear in many places. Since this is not a tutorial on C++ I won’t elaborate beyond their use as a function parameter.

Function arguments can be passed in multiple ways. One way is by value. This is the usual way in C/C++ for arguments: a copy of the value from the argument variable is passed. Any operations within the function modify the local value but have no affect on the argument variable.

C/C++ can also pass arguments by pointer, which is a form of reference passing. Operations affect the original value. We know that pointers are dangerous so C++ wanted to minimize their use.

A reference is an alias of the argument variable. Just as with a pointer the address of the argument variable is passed. The big difference is you cannot manipulate this address since it is not exposed as with a pointer. The original value of the argument variable is affected by any operations in the function.

Cost of Classes

I teased above about showing that there is no cost to using classes. This is 99.9999%, or something around there, true. In this article I’m only going to look at code size because someone looking at C++ classes and seeing their additional complexity expects there has to be a cost.

I used Eclipse with the Arduino plugin mentioned in Code Craft: Using Eclipse For Arduino Development to compile the code for the Arduino Uno and Due. Here are the results:

Clearly there is no major code bloat when using C++ on either processor. Let’s walk through the table first for the Uno and then come back to look at the Due results.

The line Buffer Routines is the code size for just the FIFO buffer code and empty Arduino setup() and loop() routines. I did this only for the Uno because I was too lazy to go back and strip the Due version down to the minimum. As we’ll see, it doesn’t matter.

The next line, File Scope Data, has the definitions of the data structures at file scope in the Application source file. The C++ code is 38 bytes larger because the class constructor is called. In order to call the constructor additional code is executed before main() is called. In any C/C++ application there is system specific initialization code executed to setup the application. C++ just adds a little more to call all the file scope constructors.

The next line shows that it is the initialization code as I suggested. An additional 4 data structures were added to both programs, with calls to their initialization inserted in the C version. The difference between the two versions remains at 38. That is a fixed overhead you’ll see on an Uno for using C++.

In the final line, I moved the definition of the data structure, and initialization for the C version, into loop(). That takes them out of file scope which means the C++ special initialization code is not needed. Now both versions have the same code size.

So, at least for the Uno, I rest my case. C++ classes do not cause code bloat.

The results for the Due are identical except for the case with multiple data structures at file scope. There is a 12 byte overhead for having a single data structure at file scope. Okay,I assumed that’s the C++ pre-main() initialization code. But that overhead reduced to only 4 bytes when the additional 3 data structures were added. What? This deserved additional investigation.

I went back to having one data structure at file scope then added more one at a time, recording the increase in code size. The C version alternately increases by 8 and 16 bytes. The C++ version increases by 16 bytes for the second data structure and by 8 bytes for each one after that. I could generate some guesses on this but frankly it’s not worth the effort since these differences are small.

As with the Uno, the final line demonstrates there is no code bloat. This is when the data structures and initialization are moved to within loop().

There it is. No code bloat from using classes in embedded systems.

Wrap Up

I just scratched the surface explaining classes in this article. I wanted to provide enough explanation so C developers would understand the concepts sufficiently to accept classes are not going to increase code size. More details would just be confusing, and there are a lot more details. I also don’t want to play language lawyer so the presentation is pragmatic, not pedantic.

Software development is a complex process. A continuing goal for language developers has been to provide a tool that is efficient to use both in writing and executing code. C++ classes not only are efficient in code size but they help avoid common errors made during development. One measure of development is that rate at which bugs are fixed. Even better is preventing bugs from occurring.

The class constructor is a bug preventor. When you instantiate a class the constructor is going to be called to initialize the variable. Consider the situation with the C code where I created FifoBuffer a number of times. For each of those variables I needed to add the call to init(). It’s very easy to forget that initialization, especially if you create the variable in a file other than where the initialization is to take place, like the setup() in an Arduino application.

The Embedding C++ Project

Over at Hackaday.io, I’ve created an Embedding C++ project. The project will maintain a list of these articles in the project description as a form of Table of Contents. Each article will have a project log entry for additional discussion. Those interested can delve deeper into the topics, raise questions, and share additional findings.

The project also will serve as a place for supplementary material from myself or collaborators. For instance, someone might want to take the code and report the results for other Arduino boards or even other embedded systems. Stop by and see what’s happening.

Filed under: Arduino Hacks, Hackaday Columns, Raspberry Pi, Software Development

Retrotechtacular: Cold War-Era Hardware Keyloggers

เสาร์, 11/07/2015 - 00:00

As Cold War tensions increased throughout the 1970s, the Soviets pulled out all the stops when it came to digging up information from US diplomats. This NSA memo from 2012 explains how several IBM Selectric typewriters used in the Moscow and Leningrad offices were successfully bugged with electromechanical devices that could possibly have been the world’s first keyloggers.

The Selectric prints with a ball that is spun and tilted to select the desired character. Two mechanical arms control the ball’s spin and tilt, and the keylogger read out the position of those arms. Thus, each character on the Selectric’s type element ball has its own signature. The sensing part of the keylogging mechanism was buried in part of the typewriter chassis, a metal bar that spans the width of the machine, and were so well hidden that they could only have been detected by complete dissassembly or x-ray.

A bugged Selectric power switch. Image source: NSA

Once the sensors detected a character, it was stored as a digital signal and compressed into four-bit words. When the bug’s buffer reached its eight-word limit, a transmitter in the metal bar sent the characters over RF to Soviet receivers. Despite being invisible to the naked eye, the Soviets wanted more protection from possible detection by frequency analyzer, so the bugs hid the signal by transmitting in the same band as the local television stations.

There wasn’t just one type of keylogger found in these typewriters, either. NSA analysts counted five different varieties. Early models ran on batteries, and later versions pulled AC power from the typewriter itself. And this was their downfall. A technician from the NSA’s COMSEC Standards and Advanced Technology Division grew suspicious upon finding an extra coil in one of the typewriters’ power switches, and the rest is history. Had the Soviets stuck with batteries, these bugs might have gone undetected.

Main image via Wikipedia.

Thanks for the tip, [Itay].

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

The Latest, Best WiFi Module Has Been Announced

ศุกร์, 11/06/2015 - 23:00

A little more than a year ago, a new product was released onto the vast, vast marketplace of cheap electronics. It was the ESP8266, and this tiny and cheap WiFi module has since taken over the space of hobbyist electronics and become the de facto standard for connecting tiny microcontrollers to the Internet.

Now there’s an upgrade on the horizon. [John Lee], the public face of Espressif, the makers of the ESP8266, has announced the next product they’re working on. It’s called the ESP32, and if the specs given are correct, it looks to be the next great thing for the Internet of Things.

The ESP32 will now contain two Tensilica processors running at 160MHz, compared to the ‘8266’s one processor running at 80 MHz. The amount of RAM has been increased to 400 kB, Bluetooth LE has been added, WiFi is faster, and there are even more peripherals tucked away in this tiny piece of silicon.

The new ESP32 includes new, simplified APIs and unlike when the ESP8266 was announced, documentation in English.

Right now, Espressif is beta testing the ESP32, with about 200 boards manufactured so far. If you’re one of the few lucky people who have one of these boards on your workbench, we’d love to see your take on it.

Filed under: Microcontrollers, news, slider

Winning the Console Wars – An In-Depth Architectural Study

ศุกร์, 11/06/2015 - 22:01

From time to time, we at Hackaday like to publish a few engineering war stories – the tales of bravery and intrigue in getting a product to market, getting a product cancelled, and why one technology won out over another. Today’s war story is from the most brutal and savage conflicts of our time, the console wars.

The thing most people don’t realize about the console wars is that it was never really about the consoles at all. While the war was divided along the Genesis / Mega Drive and the Super Nintendo fronts, the battles were between games. Mortal Kombat was a bloody battle, but in the end, Sega won that one. The 3D graphics campaign was hard, and the Starfox offensive would be compared to the Desert Fox’s success at the Kasserine Pass. In either case, only Sega’s 32X and the British 7th Armoured Division entering Tunis would bring hostilities to an end.

In any event, these pitched battles are consigned to be interpreted and reinterpreted by historians evermore. I can only offer my war story of the console wars, and that means a deconstruction of the hardware.

An Architectural Study of the Sega Genesis and Super Nintendo

The traditional comparison between two consoles is usually presented as a series of specs, a bunch of numbers, and tick marks indicating which system wins in each category. While this does illustrate the strengths and weaknesses of each console, it is a rhetorical technique that is grossly imprecise, given the different architectures. The usual benchmark comparison is as follows:

Conventional wisdom – and people arguing on the Internet – tells you that faster is better, and with the Sega console having a higher clock speed it’s capable of doing more calculations per second. Sure, it may not be able to draw as many sprites on the screen as the SNES, but the faster processor is what allowed the Genesis / Mega Drive to have ‘faster’ games – the Sonic series, for example, and the incredible library of sports games. It’s an argument wrapped up in specs so neatly this conventional wisdom has been largely unquestioned for nearly thirty years. Even the Internet’s best console experts fall victim to the trap of comparing specs between different architectures, and it’s complete and utter baloney.

Let’s take a look at one of these numbers – the CPU speed of the SNES and the Genesis/Mega Drive. The SNES CPU, a Ricoh 5A22 is based on the 65C816 core, an oft-forgotten 16-bit offshoot of the 6502 and related chips found in everything from the Apple II, Commodore 64, and even the original Nintendo NES. The 5A22 inside the SNES is clocked at around 2.68 MHz for most games. The Sega used a 68000 CPU clocked at 7.67 MHz. By comparing just these two numbers, the SNES wins, but this isn’t necessarily the truth.

In comparing the clock speed of two different CPUs, we’re merely looking at how frequently the bus is accessed, and not the number of instructions per second.

In the 68000, each instruction requires at least eight clock cycles to complete, whereas the 65C816 – like it’s younger 6502 brother – could execute an instruction every two or three clock cycles. This means the Sega could handle around 900,000 instructions per second, maximum. The SNES could compute around 1.7 Million instructions per second, despite it’s lower clock speed.

Even though the Sega console has a faster clock, it performs fewer instructions per second.

And so we come to the crux of the argument; the statistics of the great console wars, while not wrong, are frequently misinterpreted. How then do we decide an outcome?

The Architecture of the Sega Genesis / Mega Drive

While the Sega Genesis/Mega Drive is usually cited as having a 68000 CPU, this isn’t a complete picture of what’s going on inside the Sega console. In effect, the Genesis is a dual-processor computer with two CPUs dedicated to different tasks. The 68000 handles game logic and graphics, but surprisingly not much else. A Z80 — a CPU introduced a decade before the Genesis/Mega Drive — is used for reading the state of the game pads, and playing audio.

Interestingly, the Sega Genesis / Mega Drive contains most of the components of Sega’s earlier console, the Sega Master System. With the addition of a Power Base Converter, Master System games can be played while the 68000 CPU is in idle.

The  Architecture of the Super Nintendo

The SNES is a different beast entirely. Everything is controlled through the 5A22 / 65816 CPU. The controllers are fed right into the data lines of the 5A22, and DMA instructions are able to shuttle data between the two slightly different Picture Processing Units.

An interesting difference between the two consoles are the connections between the cartridge slot and various peripheral chips. Nearly the entire cartridge connector of the Sega machine is dedicated to the address and data lines for the 68000 CPU. While there are a few control signals thrown in, it’s not enough to allow the cartridge direct access to the video display unit or the FM synthesis chip.

The cartridge connector for the SNES, on the other hand, has direct access to one picture processing unit and the audio processor. The exploitation of this capability was seen in games ranging from Star Fox with it’s SuperFX chip, to Mega Man X games with its math coprocessor, to Super Mario RPG: Legend of the Seven Stars and its Super Accelerator 1 chip that is basically an upgraded version of the main SNES CPU, the 5A22.

Comparative designs, and who won the console wars

Time to make a holistic analysis of each competing platform. By far, the SNES is a more capable console; its cartridges are able to send data directly to the PPUs and audio processors, it’s faster, and there’s more work RAM, vRAM, and audio RAM.

The Sega ‘Tower of Power’. Image credit /u/bluenfee

The Genesis / Mega Drive may be seen as more expandable thanks to the Sega CD (the first CD-ROM based game console, the Sega 32X), an upgraded coprocessor for the Genesis, backwards compatibility with a Master System Power Base converter, and a number of strange cartridges like Sonic and Knuckles with ‘lock-on’ technology. However, it’s actually the SNES that is more expandable. This is most certainly not the conventional wisdom, and the difference is due to how expandability was implemented in each console.

To add additional capabilities to the SNES, game designers would add new chips to the game cartridge. Star Fox famously exploited this with the SuperFX chip, and the list of SNES enhancement chips is deserving of its own entry in Wikipedia.

In comparison, the Genesis / Mega Drive could only be expanded through kludges – either through abusing the ASIC chip between the 68000 and Z80 CPUs, or in the case of the 32X add-on, bypassing the video display unit entirely.

In any event, this is purely an academic exercise. Games sell consoles, and Nintendo’s IP portfolio – even in the early 90s – included characters that had their own cartoons, live action movies, and cereals.

While this academic exercise is completely unimportant today – there probably won’t be a game console that ships with cartridges any more – it is an interesting case study on extendable computer design.

Filed under: computer hacks, Featured, hardware

Tricking an Ancient Protocol To Play Tunes

ศุกร์, 11/06/2015 - 19:00

A lot of technological milestones were reached in 2007. The first iPhone, for example, was released that January, and New Horizons passed Jupiter later on that year. But even with all of these amazing achievements, Volvo still wasn’t putting auxiliary inputs on the stereo systems in their cars. They did have antiquated ports in their head units though, and [Kalle] went about engineering this connector to accommodate an auxiliary input.

The connector in question is an 8-pin DIN in the back, which in the days of yore (almost eight years ago) would have been used for a CD changer. Since CDs are old news now, [Kalle] made use of this feature for the hack. The first hurdle was that the CD changer isn’t selectable from the menu unless the head unit confirms that there’s something there. [Kalle] used an Arduino Nano to fool the head unit by simulating the protocol that the CD changer would have used. From there, the left and right audio pins on the same connector were used to connect the auxiliary cable.

If you have a nearly-antique Volvo like [Kalle] that doesn’t have an aux input and you want to try something like this, the source code for the Arduino is available on the project page. Of course, if you don’t have a Volvo, there are many other ways to go about hacking an auxiliary input into various other devices, like an 80s boombox or the ribbon cable on a regular CD player. Things don’t always go smoothly, though, so there are a few nonstandard options as well.

Filed under: car hacks, digital audio hacks