Categories
Artificial Intelligence Hardware Programming

A Raspberry Pi battery life/vibe coding experiment

For the next little while, I’m going to share stories about my current coding projects. This first one is about a quick evening project I did the other night that features a Raspberry Pi, a dollar-store USB power pack, Python, and a little vibe coding.

The inspiration

Original cover of Andy Weir’s novel, “The Martian.”

My fictional engineer hero is Mark Watney, the protagonist of Andy Weir’s self-published sci-fi novel turned big hit, The Martian. A good chunk of the story is about how Watney, an astronaut stranded on Mars, would overcome problems by cobbling together some tool or device, using only the gear available at the Mars habitat, his technical know-how, and creative thinking. My love for the way Watney does things is so strong that I play the audiobook version as “background noise” whenever I’m working on a problem that seems intractable.

While the movie version adds a line that captures what Watney does throughout The Martian“I’m gonna have to science the shit out of this” — it condenses a lot of what he has to do, and covers only a small fraction of the clever guerilla engineering that he does in the novel on which it was based.

The book version has Watney narrating the problems he faces, and how he uses the available equipment and material to overcome them, which often involved adapting gear for purposes they weren’t made for, such as attaching solar cells meant for the habitat to the Mars Rover to extend its driving range.

The idea

Raspberry Pi 3B board, beside a U.S. $20 bill for scale. The Raspberry Pi is about two-thrids the size of the bill.

I’d been meaning to do some projects where I’d attach sensors to my old Raspberry Pi 3B and set it up somewhere outside. Of course, you can’t count on having an electrical outlet nearby in the great outdoors. However, the Raspberry Pi 3 series takes its power via a USB micro port.

This led to a couple of questions:

  • Could I power it with a one of those USB power packs that are typically used to recharge phones while on the go?
  • If so, how long could a USB power pack keep my Raspberry Pi running?

It was time to ask some questions and get the answer empirically!

Question 1: Can you run a Raspberry Pi from a USB power pack?

The short answer: yes. I plugged my least-powerful power pack, one those cheap ones that you’d expect to find at Dollar General or Five Below:

I don’t recall buying it. It’s probably something that a friend or family member gave me. People often give me their electronics cast-offs, and I either find a use for them or recycle them.

Fortunately, no matter how cheap these units are, they usually have their specs printed somewhere on their body:

The power pack outputs 800 milliamps (mA), which is enough to run a Raspberry Pi 3B, especially if I remove any USB devices and don’t connect it to a monitor. The Pi draws about 250 mA when idle, which I figured would give me plenty of “headroom” for when the Pi would be running my little program.

According to the specs printed on the power pack, its battery capacity is 2200 milliamp-hours (mAH). That means it should be able to run a device that consumes 2200 milliamps for an hour, or a device that consumes 1100 milliamps for two hours, or a device that consumes 550 milliamps for four hours.

Of course, this was an old power pack of unknown provenance that had been through an unknown number of power cycles. Its capacity was probably far less than advertised.

Here’s the Raspberry Pi, with some parts labeled:

I plugged the power pack into Raspberry Pi, and it booted. The OS displayed a “low voltage warning” message on the desktop as soon as it had completed booted…

…but it worked!

Question 2: How long will the Raspberry Pi run on this power pack, and how do you find out?

Before I give you my answer to the second question, give it some thought. How would you test how long a programmable device can run on a power pack?

I wrote this Python script:

// uptime.py

import time

with open("uptime.txt", "a") as f:
    while True:
        time.sleep(5)
        display_time = time.ctime(time.time())
        f.write(f"{display_time}\n")
        print(display_time)

Here’s what the script does:

  • It opens a file named uptime.txt if one exists. If there is no such file, it creates that file.
  • It starts an infinite loop that appends the current time to the file every five seconds.

Note that the code appends the current time to the file, resulting in a file full of timestamps that looks like this…

Wed May 28 14:16:28 2025
Wed May 28 14:16:33 2025
Wed May 28 14:16:38 2025

…instead of a file containing the most recent timestamp.

There’s a reason for this: if I simply had the application write to the file so that it contained only the most recent timestamp, there’s a chance that the power might go out in the middle of writing to the file, which means there’s a chance that the program would fail to write the current time, and I’d end up with a blank file.

By adding the latest timestamp to the end of a file full of timestamps every 5 seconds, I get around the problem of the power going out in the middle of the file operation. At worst, I’ll have a timestamp from 5 seconds before the Raspberry Pi lost power.

The test

I fired up the Raspberry Pi while it was connected to its regular power adapter, entered the script and saved it, powered it down, and then connected it to the power pack:

I then turned it on, hooked it up to a keyboard and monitor just long enough to start the script, then disconnected the keyboard and monitor. I then left the Raspberry Pi alone until its power light went out, which indicated that it had run the battery dry.

I ran this test a couple of times, and on average got 57 minutes of uptime.

Question 3: Would I get more uptime if I wrote the program in C instead of Python?

CPUs are really large collections of transistors:

In the case of the Raspberry Pi 3 B’s ARM Cortex A53 CPU, there are about 260 million of these transistors, each one being a tiny switch that uses a tiny bit of electricity. The harder you work them, the more power they use. Some of that power is released as heat, which is why your computer gets warm, especially if you’ve got it doing something that requires a lot of computation (such as videogames, mining cryptocurrency, or training and running artificial intelligence models).

You’ve probably seen this chart that’s been floating around the internet since its publication in the 2017 paper Energy Efficiency across Programming Languages. It shows how much energy, time, and memory a number of programming languages use to perform roughly the same tasks, and it appears that Python does poorly for energy efficiency:

In order to be an easier language to read and program in, with more expressiveness and flexibility than C Python makes it easier on programmer by putting more of the work on the processor. That’s why it’s a power hog. On the other hand, C, which is almost assembly language, is at the top of the power efficiency list.

So my thought was: what if I wrote the uptime program in C and ran it — would I get more uptime?

The C program, version 1

I was about to start coding in C when it occurred to me that while I knew how to write to a file in it, I couldn’t remember how to get the time.

I was about to look it up, when I thought: why not have Claude do it?

So I opened a browser to Claude and entered:

I need some C code that will append the current date and time to a file named “uptime.txt” every 5 seconds.

It provided me with the following code:

// uptime.c

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

volatile int running = 1;

void signal_handler(int sig) {
    running = 0;
    printf("\nReceived signal %d, shutting down gracefully...\n", sig);
}

int main() {
    FILE *file;
    time_t raw_time;
    struct tm *time_info;
    char time_string[100];
    
    // Set up signal handler for graceful shutdown
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    
    printf("Starting uptime logger. Writing to uptime.txt every 5 seconds.\n");
    printf("Press Ctrl+C to stop.\n\n");
    
    while (running) {
        // Get current time
        time(&raw_time);
        time_info = localtime(&raw_time);
        
        // Format time string
        strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info);
        
        // Open file in append mode
        file = fopen("uptime.txt", "a");
        if (file == NULL) {
            perror("Error opening file");
            return 1;
        }
        
        // Write timestamp to file
        fprintf(file, "%s\n", time_string);
        fclose(file);
        
        printf("Logged: %s\n", time_string);
        
        // Wait 5 seconds
        sleep(5);
    }
    
    printf("Uptime logger stopped.\n");
    return 0;
}

The C program, version 2

After looking over the code, I noticed something and decided to ask Claude about it:

What part of this code requires stdlib.h?

Claude’s response:

Good catch! Looking at the code, stdlib.h is only needed for the exit() function, but I’m not actually using exit() anywhere in the program.

The return statements use the standard return mechanism, and the signal handler just sets the running flag to 0 rather than calling exit(). So stdlib.h can be removed from the includes.

Let this be a lesson: always double-check the code an AI gives you.

It then provided this code:

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>

volatile int running = 1;

void signal_handler(int sig) {
    running = 0;
    printf("\nReceived signal %d, shutting down gracefully...\n", sig);
}

int main() {
    FILE *file;
    time_t raw_time;
    struct tm *time_info;
    char time_string[100];
    
    // Set up signal handler for graceful shutdown
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    
    printf("Starting uptime logger. Writing to uptime.txt every 5 seconds.\n");
    printf("Press Ctrl+C to stop.\n\n");
    
    while (running) {
        // Get current time
        time(&raw_time);
        time_info = localtime(&raw_time);
        
        // Format time string
        strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info);
        
        // Open file in append mode
        file = fopen("uptime.txt", "a");
        if (file == NULL) {
            perror("Error opening file");
            return 1;
        }
        
        // Write timestamp to file
        fprintf(file, "%s\n", time_string);
        fclose(file);
        
        printf("Logged: %s\n", time_string);
        
        // Wait 5 seconds
        sleep(5);
    }
    
    printf("Uptime logger stopped.\n");
    return 0;
}

The C program, version 3

This was an improvement, but there was still a little too much “gold plating” for my needs. I entered the following into Claude:

I don’t need the graceful exit, because this program is expected to run until the computer runs out of power.

Here’s the code it provided in its response:

#include <stdio.h>
#include <time.h>
#include <unistd.h>

int main() {
    FILE *file;
    time_t raw_time;
    struct tm *time_info;
    char time_string[100];
    
    printf("Starting uptime logger. Writing to uptime.txt every 5 seconds.\n\n");
    
    while (1) {
        // Get current time
        time(&raw_time);
        time_info = localtime(&raw_time);
        
        // Format time string
        strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", time_info);
        
        // Open file in append mode
        file = fopen("uptime.txt", "a");
        if (file == NULL) {
            perror("Error opening file");
            return 1;
        }
        
        // Write timestamp to file
        fprintf(file, "%s\n", time_string);
        fclose(file);
   
        printf("Logged: %s\n", time_string);
        
        // Wait 5 seconds
        sleep(5);
    }
    
    return 0;
}

Much better.

Once I got past this regularly recurring feeling…

…I compiled the program by entering this line in the terminal…

gcc -o uptime uptime.c
./uptime

…to compile and run it.

I ran this experiment a couple of times, and on average got 89 minutes of uptime. So yes, writing — or better yet, vibe coding — the “uptime” program in C got me more power efficiency and uptime!

Question 4: Did Claude “know” what I was trying to do?

I figured there was more than enough context for Claude to “know” what the “uptime” program was for, so I asked it:

Based on the information I’ve provided in this conversation, what do you think this program is for?

Here’s its complete reply:

Based on the context clues, this appears to be a simple system uptime monitor or power outage detector.

The key indicators are:

  • You mentioned it’s “expected to run until the computer runs out of power”
  • It logs timestamps every 5 seconds to track when the system is running
  • You don’t want graceful exit handling since power loss would be abrupt
  • The file is named “uptime.txt”

This suggests you want to track how long your system stays powered on, possibly to:

  • Monitor power reliability/outages in your area
  • Track system uptime for reliability analysis
  • Have a record of when power failures occur (gaps in the timestamps would indicate outages)
  • Monitor an unattended system or server

When power is restored and the system boots back up, you could restart this program and it would continue appending to the same file, giving you a complete timeline of system availability with clear gaps showing when outages occurred.

Not bad! In fact, the use case in that final paragraph was one I hadn’t thought of, which is a primary reason why I like using AIs for my work, which is:

No matter how smart, inventive, or creative you are (or think you are), you will never be able to write a list of ideas that you would never think of.

Lessons learned

  1. Yes, you can power a Raspberry Pi — at least a Raspberry Pi 3 — with a USB power pack, even a cheap one. I knew that you could power smaller boards this way, but you have to remember that a Raspberry Pi 3 is on par with a baseline 2010-era laptop, and those had much bigger batteries.
  2. Claude’s C code generation is pretty good, but you still need to be a programmer to correct it, and while it will show you how to compile and run a C program, it’s a good idea to know how to do so.
  3. Claude can figure out what a program is for, given enough context.

Watch this space — I’ll be posting more articles like this!

Categories
Uncategorized

Intel/Microsoft Parallel Programming One-Day Course: September 20th in Montreal

Xzibit: "Yo dawg, I heard you liked processors, so we put processors in your processor so you can process while you process!"(If you don’t get the joke, here’s a little explanation.)

Moore’s Law isn’t dead; it just ended up taking on a new form. Named after Intel co-founder Gordon Moore, it refers to the observation that for the same amount of money, the number of transistors that can be place on a chip would double every 18 months. Moore described this trend in 1965 and expected it would continue for at least a decade; it’s held true for almost 50 years.

For a while, this doubling of transistors translated into a doubling of processor speed. We entered the 1990s with 286 processors running at about 10 MHz and left the decade with chips closing in on the 1 Ghz mark. But we didn’t get that hundredfold speed increase in the following decade; those extra transistors became multiple cores, so instead of speed, we got parallel processing engines.

To take advantage of these cores and get the speed increases that we’d grown accustomed to, it’s going to take parallel programming. It’s tricky to get right, and I have personally ruined some good programs with some bad threads, and you might have too. That’s what Parallelism Techdays (no relation to the TechDays conferences we’re putting on across Canada) are all about.

Parallelism TechDays: Developers -- Learn from Intel and Microsoft - Free 1-day course on parallelism and threading

Parallelism Techdays is a FREE one-day course taught by Microsoft and Intel where you’ll learn about parallelism and threading. This is your chance to learn about threading your applications for multi-core platforms.

This course is aimed specifically at Windows C++ programmers using Visual Studio. You don’t need to be familiar with threads, but it’ll help. If you’ve got beginning to intermediate experience with threads in C++, this course is for you!

Here’s the agenda for the day:

  • Thinking in Parallel
    • Why go parallel?
    • Types of parallelism
    • Task-based parallelism vs. traditional methods
  • Getting Started with Parallelism
    • Approaches to converting serial code to parallel
    • Approaches to creating parallel code from scratch
    • Intel Parallel Advisor with test application
  • Implementing Parallelism
    • Choosing a parallelism environment
    • Reasons we will focus on Intel TBB/Microsoft PPL in this class
    • Overview of TBB/PPL
  • Debugging and Correctness (Introduction)
    • Overview of special bugs and parallel programs (deadlocks, data races)
    • Debugging a parallel program (demos of Microsoft Visual Studio 2010)
    • Correction of data races (demo of Intel Parallel Inspector)
    • General guidelines for parallel processing
  • Tuning
    • Understanding parallel performance
    • Performance tuning process
    • Demos: Intel Parallel Amplifier, Microsoft Visual Studio 2010
    • General strategies for solving parallel performance issues

The course starts at 9:00am and concludes at 4:00pm, with 6 hours of instructional time, plus breaks and lunch. Register now – the Montreal event is happening soon!

This article also appears in Canadian Developer Connection.

Categories
Uncategorized

Andrew Stellman’s C# “Inner Circle” Discussion, Game Challenge and C# Video Q&A

The Week-Long Discussion

Cover of the book "Head First C#"Andrew Stellman, co-author of O’Reilly’s excellent and easy-to-read C# intro, Head First C#, is holding a week-long “Inner Circle” discussion on C# and .NET 4.0 in the forums for O’Reilly’s “Head First” book series. In this discussion, he plans to cover a wide range of topics, including:

  • Why use C# instead of any other language?
  • C# best practices
  • Becoming a better C# developer
  • Dealing with objects
  • Productivity hints
  • The best of C#

If you want to follow the discussion, simply point your browser at the Head First Labs Forums’ “Head First C#” section and look for topics started by Andrew Stellman. You don’t have to log in to just read, but you’ll have to register for the forum if you want to join in the discussion and comment back.

The Challenge

Charlie Chaplin and the original IBM PC

In his first discussion topic, Andrew issues a challenge: build an old-school, text-mode game in C#! In the 1980s, the computing world was seen through the command line in an 80-character by 24-line grid (40 characters if you were on an Apple ][, Commodore 64 or Atari 400/800, even fewer if you were on a VIC-20), and that’s how we played a lot of games, whether they were commercial or typed in from source code in magazine or books like the ones scanned into the Atari Archives.

If you’ve never written a text-mode game before (or in my case, if it’s been a long, long time), he’s written an article to help out — Understanding C#: Use System.Console to Build Text-Mode Games.

Your efforts in building an old-school text-mode game will not go unrewarded. Submit a text-mode game and you can win a prize! He’ll judge them on the following criteria:

  • Game play
  • Fun
  • Technical coolness
  • General awesomeness
  • “Retro nostalgia” for extra point

The winner will receive five O’Reilly eBooks of his or her choice. He’ll also choose runners-up who will get a free O’Reilly eBook.

If you’re looking for ideas for an old-school text-mode game, check out these books at Atari Archives, with source code written in old-school line-numbered BASIC. Some of these take me back to my high school days:

Video Q&A: Stellman on C#

As a prelude to the discussion, Andrew recorded videos of his answers to questions about the C# programming language and the second edition of Head First C#

Why should developers learn C#?

What kind of applications can you build with C#?

How hard is C# to pick up?

What’s the toughest thing to learn in C#?

What’s new in the second edition of Head First C#?

This article also appears in Canadian Developer Connection.

Categories
Uncategorized

“C# in Depth” and “Azure in Action” for the Price of One Book–Today Only (August 15th)!

csharp in depth azure in action

For today only (that’s Sunday, August 15th), Manning is offering the pair of their books, C# in Depth, Second Edition and Azure in Action for the price of one! Just use the discount code dotd0815 in the Promotional Code box when you check out. You can order the final book in either dead-tree or PDF format.

Both these books are MEAP books – that’s short for Manning Early Access Program, a chance for you to get in-progress and final editions of books currently being written.

This article also appears in Canadian Developer Connection.

Categories
Uncategorized

Discuss C# with the “Head First C#” Author, Save Big Bucks on “Head First C#” Too!

Cover of "Head First C#, Second Edition"Want to learn C# or brush up on it? From Wednesday, August 18th through Tuesday, August 24th, you can join Head First C# co-author Andrew Stellman and other techies in a week-long exchange about C# in an O’Reilly “Inner Circle” discussion, where he’ll talk about C#, .NET 4.0 and Visual Studio 2010.

(If you’re a new programmer just getting started, Head First C# is a great book that will keep you engaged, even in those parts where the going gets a little tricky. If you’re an experienced programmer who’s new to C# – or like me, hadn’t used it in ages – it’s still a great read; just skip the basic parts and enjoy the “Head First” style in which it’s written. And yes, if you want to developer for Windows Phone 7, you’re going to need to know C#. Want to get Head First C# at a discounted price? See below for details.)

The discussion will span a wide range of topics, including:

  • Why use C# instead of any other language?
  • C# best practices
  • Becoming a better C# developer
  • Dealing with objects
  • Productivity hints
  • The best of C#

If you want to join in (I’ll be participating), register for the Andrew Stellman on C# discussion at O’Reilly. See you there!

Save Big Bucks on Head First C#!

O’Reilly have a deal on Head First C#, Second Edition (published this May, and it covers C# 4.0 and Visual Studio 2010): use the discount code BKCBD when ordering online from O’Reilly and save 40% off the dead-tree edition and 50% off the ebook!

This article also appears in Canadian Developer Connection.

Categories
Uncategorized

Windows API Code Pack for .NET Framework Released

Windows 7 logo and Microsoft .NET logoUntil now, taking advantage of the UI improvements in Windows 7 (and even some features in Vista) took a fair bit of work – there was a lot of stuff that wasn’t available through the .NET Framework. You’d have to either switch to C++ or resort to hacks in order to access these goodies.

That’s all changed with the newly-released Windows API Code Pack for Microsoft .NET Framework. Written in C# – with some DirectX stuff written in C++ – this library acts as a wrapper that gives managed code access to features including:

  • Windows 7 Taskbar Jump Lists, Icon Overlay, Progress Bar, Tabbed Thumbnails, and Thumbnail Toolbars.
  • Windows 7 Libraries, Known Folders, non-file system containers.
  • Windows Shell Search API support, a hierarchy of Shell Namespace entities, and Drag and Drop functionality for Shell Objects.
  • Explorer Browser Control.
  • Shell property system.
  • Windows Vista and Windows 7 Common File Dialogs, including custom controls.
  • Windows Vista and Windows 7 Task Dialogs.
  • Direct3D 11.0, Direct3D 10.1/10.0, DXGI 1.0/1.1, Direct2D 1.0, DirectWrite, Windows Imaging Component (WIC) APIs. (DirectWrite and WIC have partial support)
  • Sensor Platform APIs
  • Extended Linguistic Services APIs
  • Power Management APIs
  • Application Restart and Recovery APIs
  • Network List Manager APIs
  • Command Link control and System defined Shell icons
  • Shell search API support
  • Drag and drop functionality for Shell objects
  • Support for Direct2D/Direct3D interoperability
  • Support for typography and font enumeration DirectWrite APIs

The system requirements are:

We’ll cover the Windows API Code Pack for Microsoft .NET Framework over the next little while in a couple of places – certainly on this blog, as well as at the TechDays 2009 cross-Canada conference in the Optimizing Your Apps for the Windows 7 Experience session.

Down arrow

Download Windows API Code Pack for Microsoft .NET Framework (v1.0)

 

This article also appears in Canadian Developer Connection.

Categories
Uncategorized

My Interview at MeshU

No tech workshop is complete without a little goofing around on an accordion, and I certainly didn’t want the MeshU day of workshops (which preceded the Mesh Conference) to be incomplete. I did a quick interview with Anita Kuno in which I performed a classic computer programmer song parody and promoted The Empire, which you can see in the video below: