The Linux Throwie: A Non-Spacefaring Satellite

Throwies occupy a special place in hardware culture — a coin cell battery, LED, and a magnet that can be thrown into an inaccessible place and stick there as a little beacon of colored light. Many of us will fondly remember this as a first project. Alas, time marches inevitably on, and launching cheerful lights no longer teaches me new skills. With a nod to those simpler times, I’ve been working on the unusual idea of building a fully functional server that can be left in remote places and remain functional, like a throwie (please don’t actually throw it). It’s a little kooky, yet should still deliver a few years of occasional remote access if you leave it somewhere with sunlight.

A short while ago, I described the power stages for this solar-powered, cloud accessible Linux server. It only activates on demand, so a small solar cell and modest battery are sufficient to keep the whole show running.

Where we left off, I had a solar cell that could charge a battery, and provide regulated 12 V and 5 V output. For it to be a functional device, there are three high level problems to solve:

  1. It must be possible to set up the device without direct physical access
  2. You must be able to remotely turn it on and off as needed.
  3. It needs to be accessible from the Internet.

The funny thing is, this hardware reminds me of a satellite. Of course it’s not meant to go into space, but I do plan to put it somewhere not easy to get to again, it runs off of solar power, and there’s a special subsystem (ESP8266) to tend the power, check for remote activation, and turn the main computer (Raspberry Pi 3) on and off as necessary. This sounds a lot like space race tech, right?

As I have a bit more code than usual to share with you today, I’ll discuss the most interesting parts, and provide links to the full firmware files at the end of the article.

Continue reading “The Linux Throwie: A Non-Spacefaring Satellite”

The Linux Throwie: Powering A Linux Server With A 0.3W Solar Panel

Have you ever had one of those moments, when you’re rummaging through your spare parts heap, and have a rather bizarre project idea that you can’t quite get out of your head? You know, the ones that have no clear use, but simply demand to be born, of glass and steel and silicon?

This time, the stubborn idea in question was sort of like a solar-rechargeable LED throwie, but instead of a blinking light, it has a fully cloud-accessible embedded Linux server in the form of a Raspberry Pi 3 Model B+. Your choice of embedded Linux board should work — I just happen to have a lot of these due to a shipping error.

There were two main challenges here: First, it would have to combine the smallest practical combination of solar panel, power supply, and Li-ion cell that could run the Raspberry Pi. Second, we’ll need to remotely activate and access the Pi regardless of where it is, as well as be able to connect it to WiFi without direct physical access. In this article we’ll be dealing with the first set of problems — stay tuned for the rest.

Continue reading “The Linux Throwie: Powering A Linux Server With A 0.3W Solar Panel”

Selling Everything, Moving To Asia, And Setting Up A Company

Today I don’t have a hack for you. I have a story, one that I hope will prove useful to a few of you who are considering a move to Asia to chase opportunities here.

Seven years ago, I was a pretty stereotypical starving hacker. I had five jobs: A full-time dead-end job in biotech, and four part-time or contract gigs that were either electronic hardware design or programming. I worked perhaps 50 hours a week, and was barely past the poverty line – I was starting to wonder why I spent so much time in school. I saw the economic growth in Asia as an attractive but risky opportunity.

Check out that image above…France? No, this is Shenzhen and let’s face it: many exciting things are made there (even the copies). After a short visit to the region, I decided to take that risk but not in Shenzhen. I sold everything I owned and moved from Canada to Vietnam and started a company. Over the last seven years things have worked out well, although I certainly wish I had known more about the process before I got on a plane. This article is about the general path I took to get where I am. Obviously I don’t know the legal framework of every country in Asia, but speaking in generalities I hope that I can cover some interesting points for the curious and adventurous.

Continue reading “Selling Everything, Moving To Asia, And Setting Up A Company”

Track Everything, Everywhere With An IoT Barcode Scanner

I’ve always considered barcodes to be one of those invisible innovations that profoundly changed the world. What we might recognize as modern barcodes were originally designed as a labor-saving device in the rail and retail industries, but were quickly adopted by factories for automation, hospitals to help prevent medication errors, and a wide variety of other industries to track the movements of goods.

Medication errors in hospitals are serious and scary: enter the humble barcode to save lives. Source: The State and Trends of Barcode, RFID, Biometric and Pharmacy Automation Technologies in US Hospitals

The technology is accessible, since all you really need is a printer to make barcodes. If you’re already printing packaging for a product, it only costs you ink, or perhaps a small sticker. Barcodes are so ubiquitous that we’ve ceased noticing them; as an experiment I took a moment to count all of them on my (cluttered) desk – I found 43 and probably didn’t find them all.

Despite that, I’ve only used them in exactly one project: a consultant and friend of mine asked me to build a reference database out of his fairly extensive library. I had a tablet with a camera in 2011, and used it to scan the ISBN barcodes to a list. That list was used to get the information needed to automatically enter the reference to a simple database, all I had to do was quickly verify that it was correct.

While this saved me a lot of time, I learned that using tablet or smartphone cameras to scan barcodes was actually very cumbersome when you have a lot of them to process. And so I looked into what it takes to hack together a robust barcode system without breaking the bank.

Continue reading “Track Everything, Everywhere With An IoT Barcode Scanner”

Move Aside Mercury: Measuring Temperature Accurately With An RTD

Temperature is one of the most frequently measured physical quantities, and features prominently in many of our projects, from weather stations to 3D printers. Most commonly we’ll see thermistors, thermocouples, infrared sensors, or a dedicated IC used to measure temperature. It’s even possible to use only an ordinary diode, leading to some interesting techniques.

Often we only need to know the temperature within a degree Celsius or two, and any of these tools are fine. Until fairly recently, when we needed to know the temperature precisely, reliably, and over a wide range we used mercury thermometers. The devices themselves were marvels of instrumentation, but mercury is a hazardous substance, and since 2011 NIST will no longer calibrate mercury thermometers.

A typical Pt100 RTD probe

Luckily, resistance temperature detectors (RTDs) are an excellent alternative. These usually consist of very thin wires of pure platinum, and are identified by their resistance at 0 °C. For example, a Pt100 RTD has a resistance of 100 Ω at 0 °C.

An accuracy of +/- 0.15 °C at 0 °C is typical, but accuracies down to +/- 0.03 °C are available. The functional temperature range is typically quite high, with -70 °C to 200 °C being common, with some specialized probes working well over 900 °C.

It’s not uncommon for the lead wires on these probes to be a meter or more in length, and this can be a significant source of error. To account for this, you will see that RTD probes are sold in two, three, and four wire configurations. Two-wire configurations do not account for lead wire resistance, three-wire probes account for lead resistance but assume all lead wires have the same resistance, and four-wire configurations are most effective at eliminating this error.

In this article we’ll be using a 3-wire probe as it’s a good balance between cost, space, and accuracy. I found this detailed treatment of the differences between probe types useful in making this decision.

Continue reading “Move Aside Mercury: Measuring Temperature Accurately With An RTD”

Internet Of Smells: Giving A Machine The Job Of Sniffing Out Spoiled Food

Has the food in your pantry turned? Sometimes it’s the sickening smell of rot that tells you there’s something amiss. But is there a way to catch this before it makes life unpleasant? If only there were machines that could smell spoiled food before it stinks up the whole place.

In early May, I was lucky enough to attend the fourth FabLab Asia Network Conference (Fan4). The theme of their event this year was ‘Co-Create a Better World’. One of the major features of the conference was that there were a number of projects featured, often from rural areas, that were requesting assistance throughout the course of the conference.

Overall there were many bright people tackling difficult problems with limited resources. This is how I met [Yogesh Kulkarni] who runs a FabLab in Pabal, a farming community not far from Pune, India. [Yogesh] has also appeared on TED Talks (video here). He explained to me that in his area, vendors sell milk-based desserts. These are not exactly refrigerated, and sometimes people become ill from eating them. It would be nice if there was a way for the vendors to avoid selling the occasional harmful product.

I’ve had similar concerns with food safety in my area (Vietnam), and while it has been fine nearly all of the time, a few years ago I nearly died from a preventable food-borne illness. I had sufficient motivation to do a little research.

Continue reading “Internet Of Smells: Giving A Machine The Job Of Sniffing Out Spoiled Food”

Simple Ethereum Vending Machines With NodeMCU

Recently, we covered how to use the Etherscan API to query data (a wallet balance) from the Ethereum blockchain with NodeMCU. It’s a very useful method for retrieving information from a blockchain on embedded systems where storage and memory are an issue.

It has some limitations though. Most notably, it’s polling the API at some interval to retrieve information whether it has changed or not. I would like to be able to receive data more efficiently than this, and quickly enough to make simple vending machines possible. While we’ve seen videos of Bitcoin-based Red Bull vending machines before, they required an NFC card to use.

If we could receive information about Ethereum transactions quickly and reliably enough, we could build a similar vending machine without requiring an NFC card as an intermediary. Simply send to an address via some method, and receive goods!

It turns out we can do exactly that with NodeMCU using WebSocket. Like HTTP, WebSocket is a communications protocol that uses TCP connections (typically over port 80), but it allows full-duplex communication. In other words, you can establish a connection to a server, and send/receive messages without needing to poll the server.

As in the previous example, we’ll use a NodeMCU running Lua. You may wish to refer to it for compile options and information about the screen, which will be the same in this case. Unlike the previous article, you will not need an API key from Etherscan to use this service (not yet, anyway). As usual, we’ll start off by connecting to WiFi:

station_cfg.ssid="Your SSID"
station_cfg.pwd="Your Password"

Connecting to a server with WebSockets is easy, but since we’re not using HTTP, we’ll have to remove the https:// and replace that with ws://. (Note: not wss:// because we’ve not enabled encryption yet.)


Next, we need to report back when the connection is established as the trigger to run additional code. It will return an error code if the connection fails to be established. Handling these error codes in a sensible way is an excellent feature, but we’ll handle that later:

ws:on("connection", function(ws)
    print('got ws connection')

Now, we need to extend the above to subscribe to an Eth address, and add some new code to do something when a transaction occurs. Note that the API requires that you subscribe to an address within 60 seconds of connecting. It also states that you have to send a ping event to the server every 20 seconds to keep the connection alive, so we’ll need to set a recurring timer for that.

If you’re using ESPlorer, you can send the ping request manually by entering =ws:send('{"event": "ping"}') and pressing Send. This is a useful way to test the connection status.

The address I used seems to have frequent transactions so is reasonable for testing. Be advised though that sitting and waiting for a transaction to happen to test the code creates a slow development cycle so some patience is necessary here.

ws = websocket.createClient()
ws:on("connection", function(ws)
    print('got ws connection')
    ws:send('{"event": "txlist", "address": "0x2a65aca4d5fc5b5c859090a6c34d164135398226"}')

ws:on("receive", function(_, msg, opcode)
    print('got message:', msg, opcode)

You should see something like what follows below. The first message is a simple confirmation of connection, the second confirms your subscription to an address, and the third is what you get sent when a transaction occurs. You can subscribe to up to 30 addresses with a single connected device! Note that the data is all in JSON format, which is something we’ll take advantage of later.

got message: {"event":"welcome"} 1
got message: {"event":"subscribe-txlist", "status":"1", "message":"OK, 0x2a65aca4d5fc5b5c859090a6c34d164135398226"} 1
got message: {"event":"txlist","address":"0x2a65aca4d5fc5b5c859090a6c34d164135398226","result":[{"blockNumber":"5532531","timeStamp":"1525098009","hash":"0xe5ec497cb5b38811e8bf5db67a056a2bdd4aa9b68df5c8e8225cb300cbcfa413","nonce":"3363391","blockHash":"0xf446f77d92ed29c221e8451b8048113969ed305a7dd49177e10b422e8e2c4bda","transactionIndex":"172","from":"0x2a65aca4d5fc5b5c859090a6c34d164135398226","to":"0xec5fdfba35c01c6ad7a00085e70e8f30cd121597","value":"24418350000000000","gas":"50000","gasPrice":"4000000000","input":"0x","contractAddress":"","cumulativeGasUsed":"7896403","gasUsed":"21000","confirmations":"1"}]} 1

That’s quite a mess of transaction data, and unfortunately the datum of interest is in the ‘result’ field – which is nested JSON. In the last article, we converted simple JSON to a Lua table using the excellent sjson module. We’ll do the same here after verifying the message type is a transaction (txlist).

ws:on("receive", function(_, msg, opcode)
    print('got message:', msg, opcode)
    ok, ethdata = pcall(sjson.decode, msg)
    if ok then
        msgtype = (ethdata["event"])
        if msgtype == "txlist" then

The NodeMCU documentation specifically notes that nested JSON can cause out-of-memory errors. For that reason we use pcall (protected call) to contain any such errors when decoding our JSON message. Next, we extract the contents of the ‘value’ field, nested within the ‘result’ field:

if msgtype == "txlist" then
    wei = ethdata.result[1].value
    print (wei)
    eth = wei/1000000000000000000
    print (eth)

It took me a few hours to figure out how to deal with nested tables, but in the end it was actually quite clean and easy — I was just being dense. Now, we need to add a basic provision to handle errors when the websocket is closed:

ws:on("close", function(_, status)
    print('connection closed', status)
    ws = nil -- required to Lua gc the websocket client
    tmr.alarm(0,4000,tmr.ALARM_SINGLE,transact) -- This reconnects after 4 seconds

To wrap it all up, we encase the code in a couple of functions — first, one to establish a connection, subscribe to the right address, and notify when there is a transaction. Next we need one to display the amount of Eth transferred. Finally, we need a ‘ping’ function to call every 20 seconds or less to keep the connection alive. Overall this turned out to be more robust than expected and has yet to encounter an error. Check out the full code listing here. Note that I’ve also added a little code above to interface with a 128×32 OLED screen, the same one we used previously.

Now that it works, let’s consider im/practical applications. It’s a neat way to display Ethereum transactions in real-time, say if you do livestreaming and accept Eth donations and want them to trigger something fancy. Or, you could make a somewhat insecure vending machine. Clearly, getting a secure WebSocket up and running is the next order of business.

You could also set a timer where the length depends on the amount of Eth received. This would allow for things like public advertisements that go away for a while if someone pays a fee. (Please don’t do this!) Maybe a conference room for rent with the power controlled this way? Hackerspace membership payment? An electric bicycle that charges you for power used?

In any case, it’s not legal to use cryptocurrency as a form of payment in my country so I can’t implement any of the above examples at this time. If you’ve got a better application, please share it in the comments!