That's a lot of code I've "example'd!"

Not to say it isn't useful. I certainly hope it is.

Oh and it's that time of year where I switch out blogger templates. Maybe this time I'll make it more straightforward and automated. Maybe.

Which reminds me: this is the first year that my MUSH will be auto-deploying its Christmas theme. Pretty excited for that!

Anyway, that's all for now.

USB Fast Chargers

I've been a bit confused lately at what constitutes fast charging versus normal charging, and why newer Android devices complain repeatedly if you use the wrong cable, or the wrong charger, or the wrong cable AND charger. How does it know?

Then I found an article on LifeHacker that partially explains it, but this comment thread clarified in an excellent manner:

According to this article and the super helpful comment thread, the multiple things that affect an Android's ability to fast charge are:

  1. Battery current rating - I have a 3000mAh / 11.4Wh battery capacity (it is able to provide 3 amps at a nominal voltage for one hour or 11.4 Watts for one hour). P/I=V = 3.8V which is what this battery indicates it's able to deliver. This battery also has a minimum rating of 2940mAh / 11.2Wh (also 3.8V).
  2. USB Spec - Normally USB is supposed to output 5V +/- 0.25V. To convert from the 3.8V battery, we simply draw less current at the USB and convert it accordingly: (3.8V x 3A) = 11.4W. (11.4W / 5V) = 2.28A. So ideally my battery wants to present a current draw of 2.28A on the charger when acting as a load. With the 0.25V allowed voltage margin, this could be anywhere from 2.17A to 2.4A.
  3. A standard USB 2 port on a computer is rated only for 500mA (0.5A). If too many devices hang off of a USB port, you could start current limiting and the voltage to each device will drop, usually below the allowed 4.75V. This is why powered hubs are recommended. Even with a single device trying to draw more current than the port is capable of, this is when you get those errors that "your phone is charging slowly. Please use the charger and charging cable that came with your phone." A good charger should be able to provide all 2A needed for a standard charging rate the phone requires.
  4. Diameter of charging cable - USB 2.0 has five lines that it uses:
    • Rx
    • Tx
    • V+
    • V-
    • GND (braided shield)
    Normally the four main lines are all 28AWG. According to, this means that the charging lines will provide 0.23A before they start heating up and creating an appreciable resistance (higher than 213 Ohms per km) which will in essence place a second, noticeable load in series with the battery. The power lines (V+/V-) in the wire can be increased to 24AWG to allow 0.58A at 84.2 Ohms per km and thus decreasing this second parasitic load. Additionally, the load of the charging cable can also be reduced by shortening the cable itself.
    Gauge Test Current Impedance (per km) Wire length (km) (~6 feet) Cable Impedance
    28AWG 0.23 213 0.002 0.426
    24AWG 0.58 84.2 0.002 0.1684

    Volt drop (test) Voltage Left for Phone
    28AWG 0.09798 4.90202
    24AWG 0.097672 4.902328

    Volt drop (0.5A) Voltage Left for Phone
    28AWG 0.213 4.787
    24AWG 0.0842 4.9158

    Volt drop (2A) Voltage Left for Phone
    28AWG 0.852 4.148
    24AWG 0.3368 4.6632

    With a standard 0.5A charger, even a 28AWG 6-foot cable will be able to charge the phone at a standard voltage (4.79V being higher than the minimum allowed of 4.75V). However, if we wanted a full 2 Amps for fast charging, we would need a bigger cable (24AWG), which would even then present enough of a load to drop the voltage on the battery to 4.66V which, while better than 4.15V on the 28AWG wire, is still out of spec.
  5. Androids have the ability to detect a "fast charger." Fast chargers indicate their ability to provide 2A by a simple short between the unused Rx/Tx lines. If the android sees this "loop-back" connection on its data lines, it is programmed to assume that whatever its connected to is able to provide 2A. Otherwise it will only draw 0.5A.
  6. Additionally, some fast chargers which are paired with a standard length and gauge USB cable are able to do some rudimentary current sensing and output a voltage higher than 5.0V to compensate for the drop on the cable itself.

So in short, for a proper fast charger, two things should be used:
  1. A cable with higher diameter power lines
  2. A charger that is able to output the current required by the battery being charged

And an additional feature that could be desireable:
  • A charger that is able to sense the current, calculate the voltage drop across a known cable and boost its voltage output to compensate.

LetsEncrypt List of Useful Commands

Here are a few letsencrypt commands that I've found useful in the past few months of trying it out.


git clone
cd letsencrypt

Note: for a few Debian installations, you can also install with:
apt-get install letsencrypt python-letsencrypt-apache

Other OS's are also supported. See for details!

Generating new keys on Apache:

./letsencrypt-auto run --apache -d domain1 -d domain2 -d domain3

Loading pre-generated keys from a backup into a new installation:

#Need to have backed up /etc/letsencrypt/ to some 
# backup location. This will grab private keys, 
# public certs, symlinks to them, everything.
# More help at
#Simply running the command, even to load help, 
# will bootstrap dependency installations and set 
# up the Python scripts if they haven't been set up 
# already.
./letsencrypt-auto --help all

cp -R /path/to/backup/letsencrypt/* /etc/letsencrypt/

./letsencrypt-auto --install -d -d -d --cert-path /etc/letsencrypt/live/domain1/cert.pem --key-path /etc/letsencrypt/live/domain1/privkey.pem --fullchain-path /etc/letsencrypt/live/domain1/fullchain.pem

To renew keys (keeping them the same, but extending the expiration date another 90 days):

#Special bash scripts intended for datestamp 
# checking to refrain from renewing certs
# younger than 60 days old are no longer 
# needed in LE version 0.4. Simply run the 
# following:
./letsencrypt-auto renew

Typecasting struct to char* for idiots like me

Want to cast from a struct to a character string? Seen all those posts out there suggesting that reinterpret_cast will work, but is unsafe? Yeah, I tried it. Yeah, it's unsafe.

What about the ones saying you could just malloc()? Well, my own personal mantra says that direct memory manipulation is also rather unsafe if you don't count right or are not careful with stack memory and such. I have avoided malloc() like I have learned to avoid reinterpret_cast.

But just today I discovered a most elegant solution:

struct newStruct { //33 total bytes long
    int dw0;
    uint_16 s0, s1, s2, s3;
    float f0, f1, f2, f3;
    char b0;
    int i0;

void byteOperation(char *p) {
    // Treat input parameter "p" like a big character array and do things one byte at a time!!

newStruct v;
newStruct w[1];

byteOperation((char*)v); // Compiler error: Cannot cast from 'newStruct' to 'char *'
byteOperation((char*)w); // Will just work.

Embarcadero TThread Just Works

I've been annoyed for a large amount of time (years in fact) over some of our software we use and sell. In essence, what we have is a TCP GUI that communicates on a 250ms timer with a microcontroller that's serving up a two-way communications protocol over ModBus FC23 - we send commands either to write data to or read data from the unit.

The developer we had make the initial software for us decided to use Embarcadero's system timer object to control the 250ms polling. Not only that, but I had to put in an 8-second delay during socket initialization (via a TPing object) in the event that the unit was rebooted (we want to wait until the unit can finish booting before we say that it can't be found on the network). And I learned ALL of my Borland/Embarcadero, and even the majority of my C++ knowledge from this program and others I've patterned after it.

But both the timer and the timeout exist in the main method. So every time the TPing object waits for the unit's response, or every time the 250ms timer hung, the entire program would freeze. It's been very annoying to say the least.

The microcontroller library I use (Netburner uCOS) has a fairly straightforward way to set up "tasks," and particularly the MOD5282 has something called a periodic interrupt (PITR) which will run a very fast clock at some hardware-programmable rate that will set an IRQ interrupt flag (and hardware pin) every time it fires. These two things are really cool because not only do I have a very fast and very calibrated clock that I can run certain tasks on at a rapid rate, but I can do so within separate tasks which keep the entire program from freezing if set up correctly.

But it required a slight change in thinking. I cannot run intensive processing within the PITR (printf(), etc). I cannot use OSTimeDly(n) (essentially the Sleep() function of uCOS, which is also limited to 20ms minimum) within the PITR. And I cannot utilize critical sections or OSLock() for any more than a few essential operations at a time. Otherwise the watchdog timer of the microcontroller could hang and force it to reboot.

I also have to explicitly declare a task's stack memory on the Netburner and have to give each some priority to make sure that more important tasks continue to run properly.

Thing is, Netburner's documentation on Tasks is quite good once you know where to look.

Embarcadero's documentation is a bit more confusing.

Borland/Embarcadero uses something called the TThread class. I figured multithreading a GUI application would be simple - simply declare a "task," set it up to run by itself using numerous different parameters with timers and what-not. Not according to documentation.

According to documentation you have to set up an entirely separate TThread class and you have to Synchronize objects from the main form in order to change their values. And none of the example programs look very straightforward.

Of course, the only example program I have is some triple-sorting GUI with three threads other than the main one, each sorting a set of data with a different algorithm. Out of the box, it's really cool. You hit the button and watch the three bar graphs simultaneously sort themselves from high values to low values, some taking longer than others. A great example program.

But I don't do any sorting in my programs. All I WANT is to push a button in my GUI and have it attempt to connect to a remote unit for eight seconds without hanging. Meaning, if I know it's not there, I can simply push the disconnect button and cancel it. Or close the GUI completely because I realize I made some mistake in programming.

In short, MY need for multithreading exists on a much simpler level. I want to be able to interrupt something that would otherwise force me to wait, since it emulates the Sleep() function.

Then I figured it out. Threading is still my solution. Only getting it set up in the Embarcadero IDE is much much simpler than the scant documentation and example programs would lead you to believe.

Here's my example program:
1. Create a simple VCL form with a TLabel (or any other object that takes a String input and displays it).

2. Drop a TSpeedButton object, setting its GroupIndex to a positive integer (like 1) and setting its AllowAllUp property to true. Now we have a toggle switch.

3. Create a global bool variable and give it some name like "ThreadExecute."

4. Bind the OnClick event of the TSpeedButton to some function, namely its default "SpeedButton1Click(TObject *Sender)" and tell it to toggle the global boolean set in step 3 based on its Down boolean property:
void __fastcall TForm1::SpeedButton1Click(TObject *Sender) {
  // This ensures that the SpeedButton1->Down status is available globally for other things, such as the other thread.
  ThreadExecute = SpeedButton1->Down;

5. Now for the super simple part - File > New > Other > C++ Builder Files > Thread Object. This will create a new unit, a cpp and h file set with the same name that act like a single "unit" (hence the name) within the IDE. The class it automatically creates will be assigned to the TThread class type, just like the main form is assigned to the TForm class type. It will also create two default functions - a constructor for initializing internal variables or what-not when a TThread object of this class is created, and an Execute() function for when the thread is "started."

6. In the TThread::Execute() function, create some iterative process, like adding 1 to a number within an endless while loop:
int n = 0;

void __fastcall ThLooper::Execute() {
  // Note - A while(1) loop, particularly with a Sleep() delay at the end would most certainly freeze the main loop and make it unresponsive to any further user interaction.
  while (1) {
    // Only execute if Toggle button in the Main form is Down.
    if (ThreadExecute) {
    Sleep(250);  } // end while

7. In the main form, set up the TForm's constructor to initialize the Thread in its own object:
ThLooper *Thread1;
__fastcall TForm1::TForm1(TComponent *Owner) : TForm(Owner) {
  Thread1 = new ThLooper(true); // Note - the CreateSuspended parameter creates the Thread object without starting it automatically.
  Thread1->Start(); // Can also use Resume(). This is needed if the Thread was created with CreateSuspended == true.
8. We now will probably need to display the value of n in the main form. However note the comment in the Thread class file - "Methods and properties of objects in VCL can only be used in a method called using Synchronize." This means you must use the Synchronize() function in order to access Form1 objects like the Label we want to update the caption of:
int n = 0;
// Should declare this first. Can be done in the thread header file.
void __fastcall ThLooper::UpdateLabel(void);

void __fastcall ThLooper::Execute() {
  while (1) {
    if (ThreadExecute) {
      n++; // Note - we made this global to access it from a synchronize method call.
  } // end while

void __fastcall ThLooper::UpdateLabel() {
  Form1->Label1->Caption = (String)"N=" + n;


And that's it! That's all I needed to do to set up a thread that runs a constant process that would normally freeze the program outright. I can start the timer, or stop it using the toggle button, but the endless while loop will not freeze any portion of the main thread.

Looking at the documentation, there are also properties for setting a thread's priority to low or high, set it to destroy itself on an exception, and numerous other things.

And my knowledge of Netburner tasks simply verifies what I already know when Embarcadero highlights the following things to be aware of:
1. Too many threads consumes CPU time - limit yourself to 16 threads per CPU processor.
2. If multiple threads access the same resources, they must be synchronized to avoid conflict.
3. Updates to the form must be limited to the main thread. Updating a form element from within a thread should be done via thread synchronization such as TMultiReadExclusiveWriteSynchronizer.

This subject is not as complex as I had first believed!

Official Documentation:


#ifndef ExampleH
#define ExampleH


class TForm1 : public TForm {
__published:    // IDE-managed Components
    TLabel *Label1;
    TSpeedButton *SpeedButton1;
    void __fastcall SpeedButton1Click(TObject *Sender);
    void __fastcall FormShow(TObject *Sender);
private:    // User declarations
public:        // User declarations
    __fastcall TForm1(TComponent* Owner);

extern PACKAGE TForm1 *Form1;



#pragma hdrstop

#include "Example.h"
#include "ThLooper.h"

#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
ThLooper *Looper;

__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) {
    Looper = new ThLooper(true); // Initially suspended. We don't want to risk updating VCL components before they are completely created.

void __fastcall TForm1::FormShow(TObject *Sender) {
    Looper->Start(); // VCL Form has been fully created. Can now start Looper thread.

void __fastcall TForm1::SpeedButton1Click(TObject *Sender) {
    Label1->Caption = (SpeedButton1->Down)?"Running":"Halted";
    Looper->Go = SpeedButton1->Down;


#ifndef ThLooperH
#define ThLooperH

class ThLooper : public TThread {
  void __fastcall UpdateLabel(void);
  void __fastcall AnimateStatus(void);
  void __fastcall Execute();
  __fastcall ThLooper(bool CreateSuspended);
  bool Go;



#pragma hdrstop

#include "Example.h" // To update VCL form elements.
#include "ThLooper.h"
#pragma package(smart_init)

// AnimateStatus is a quick little text-based progress bar I made.
char ConnAniCtr = 0;
char ConnAniMax = 4;
char ConnAniDelay = 2;
char ConnAniDelayCtr = 0;
String ConnAni = "";
short N = 0;
void __fastcall ThLooper::AnimateStatus() {
  if (ConnAniDelayCtr < ConnAniDelay)
  else {
    ConnAniDelayCtr = 0;
    if (ConnAniCtr >= ConnAniMax)
      ConnAniCtr = 0;
  } // if

  ConnAni = StringOfChar('.',ConnAniCtr);
  Synchronize(&UpdateLabel); // Synchronously update VCL Form Label.

__fastcall ThLooper::ThLooper(bool CreateSuspended) : TThread(CreateSuspended) {
    Go = false; // Do not run initially.

void __fastcall ThLooper::Execute() {
  while (1) {
    if (Go) {
    Sleep(250); // Can comment this to see max speed of thread. Synchronize does not significantly pause thread execution.

void __fastcall ThLooper::UpdateLabel() {
  Form1->Label1->Caption = (String)"Running" + N + ConnAni;