3D prints: Stevenson screen

Building a basic weather station today is simple and cheap thanks to specialized integrated circuits featuring temperature, humidity and pressure sensing. Up to now my favorite is the Bosh bme280; you may easily find it ready for use on small PCBs, easy to connect on any prototyping platform. Adafruit industries is selling a very convenient shield PID: 2652

Running this nice shield is really easy. However, turning it to a real weather station is another story. No need to be a professional meteorologist to guess that leaving this outdoor module “as is” will lead to inaccurate readings and rapid degradation. We just need a proper shelter, a so-called Stevenson screen. This enclosure must leave enough space to place the sensor and break the sun’s rays as well as the wind flow. Here is a proposal for a compact Stevenson screen printed in several stackable parts.

The lower stage features a stand for the shield and two screws, a hole and a grove for the signal cable and two hexagonal carvings for a pair of nuts to be used with mounting screws.

Next stages feature a Z shaped cross section

Then come a top sealed stage and the final cover stage. The air space between these two last stages acts as a thermal insulator against direct solar radiation.

 Download the STL files > here <


Let’s celebrate Apollo XI !

I remember very well the 20th of July 1969… I was in a holiday camp and the director had the bright idea to get a portable TV set, to power it with the battery of his car and he managed to have as many kids as possible watching this event. At this time, I had no idea at all about what was happening, which were the roots of this project and which would be the consequences.

The image on the the TV screen was no better than my illustration, but god, that was almost incredible !

Years after, I discovered programming science through the use of hp 25 pocket calculators. These calculators were coming with the fabulous (at this time) lunar module landing game ! (More about this program). And a few years later, I joined hp and I got a calculator for free !

So I had the idea to clone this program on arduino just for fun !

I made it plain simple so that anyone can have some fun with it. When the game starts, you are 1000 m above the lunar surface, the LEM (Lunar Excursion Module) speed is 10 m/s, the fuel tank contains 150 arbitrary units while the moon gravity is 1.62 (1/6 compared to the earth gravity as you may know). Because the LEM is inexorably attracted by the moon, you need to fire the engines in order to decrease your downward speed and land at a speed equal or lower than 1 m/s …

To run the game, once the code has been uploaded, open the console and either repeatedly use the “Enter” key from your keyboard or use the button that you will attach between pin 2 and ground (or pin 2 and 3 like I did).
Next is the code. Again, plain simple:

Lunar module landing game
Didier Longueville July 2019

/* LEM variables */
const float _gPerFuelIUnit = 2.0;
const float _maxLandingSpeed = 3.4; 	/* eq to a freefall of 12 feet */
const float _initialSpeed = 10; 		/* m/s */
const int16_t _initialDistance = 1000;	/* m */
const uint8_t _initialFuelLevel = 150;	/* liters */
/* application variables */
float _speed;
int16_t _distance;
volatile uint8_t _fuelLevel;
uint8_t _lastFuelLevel;
/* timing variables */
const uint32_t _intervalMs = 500; 	/* in ms */
const float _intervalSec = (_intervalMs / 1000.0); /* in s */
uint32_t _lastTime; 				/* in ms */
/* constants */
float _lunarGravity = 1.62; 		/* lunar gravity m/(s*s)*/
/* hardware */
const uint8_t _interruptPin = 2;
const uint8_t _groundedPin = 3;
volatile bool _preset = false; /* this variable MUST be volatile because of its insertion with the ISR */

void interruptService(void)
	/* read button state and set state (GND true) */
	uint8_t state = (digitalRead(_interruptPin) == LOW);
	/* apply some debouncing using kind of flip-flop */
	if (state && !_preset)
		_preset = 1;
	else if (!state && _preset)
		_preset = 0;
		if (_fuelLevel > 0) 
			_fuelLevel -= 1;

void initGame(void)
	_speed = _initialSpeed;
	_distance = _initialDistance;
	_fuelLevel = _initialFuelLevel;	
	_lastFuelLevel = _fuelLevel;

void setup(void)
	/* init the "fuel trottle" pin */
	pinMode(_groundedPin, OUTPUT);	
	digitalWrite(_groundedPin, LOW);
	pinMode(_interruptPin, INPUT_PULLUP);	
	attachInterrupt(digitalPinToInterrupt(_interruptPin), interruptService, CHANGE);
	Serial.println("New landing...");

void loop(void)
	uint32_t now = millis();
	uint32_t elapsedTime = (now - _lastTime);
	if (elapsedTime >= _intervalMs) 
		/* compute */
		uint8_t fuelConsumption = (_lastFuelLevel - _fuelLevel);
		float gamma = (_lunarGravity - (fuelConsumption * _gPerFuelIUnit));
		_distance -= (((0.5 * gamma) * (_intervalSec * _intervalSec)) + (_speed * _intervalSec));
		if (_distance < 0)
			_distance = 0;
		_speed += (gamma * _intervalSec);
		_lastFuelLevel = _fuelLevel;
		/* display variables */
		Serial.print("s: ");
		Serial.print(_speed, 1);
		Serial.print("   d: ");
		Serial.print("   f: ");
		if (_distance == 0)
			if (_speed > _maxLandingSpeed)
				Serial.println(">>>>> CRASH ! <<<<<");
				Serial.println("--- You made it ! ---");
		/* timing stuff: record last event time */
		_lastTime += _intervalMs;
	if (Serial.available()) 
		while (Serial.available()) 
			if (_fuelLevel > 0) 
				_fuelLevel -= 1;

All in all, this code contains a few ideas for debouching without a timer (and thus not suspending operation to the button release) and timing the computing function.

Enjoy !

Date and time serial: how to bypass the lack of precision of floats

Data type is probably the first concern for any new programmer in c/c++. These language require in minimal knowledge about integers and floats (Check this thread). Although these data types look familiar to all educated people, the principle of significant figures, which should be the universal way of formatting data, is, most of the time, ambiguous, foggy, unsure, etc.. Pocket calculators are mainly responsible for this lack of understanding; at the time of slide rules, who would bother about the nth precision digit and carry these insignificant figures over a bunch of operations ? Nowadays, most students are happy to copy the full content of their display as the result of operations which lead to express physical measurements with quasi unit-less figures.

Back to to the world of 8 bits controllers, the range and precision of floats must be taken into account and results shall be carefully interpreted before releasing a code. As I was recently working on RTC drivers and applications, I faced the need for exporting time-stamped logged data to a PC based application.

The best idea I could find to express absolute date and time consists in using the “Microsoft” – nobody’s perfect – date and time serial. This float is made of an integer part which represents the number of days since the 1 Jan 1900 at 0:0:0 (date serial 1 because of the Lotus-1-2-3 bug which was agreed by Excel for compatibility reasons !); the fractional part is a fraction of 1 day, so as to say 1 s = (1 / 24 * 60 * 60). Using these rules, it is right now 43604.685417 and that’s a lot more precision than the float data type can handle. However, sticking to serial date and time makes a lot of sens as converting the serial in MS EXCEL or compatible spreadsheets such as LibreOffice Calc, is as easy as: year(A1) & “-” & month(A1) & “-” & day(A1) & ” ” & hour(A1) & “:” & minute(A1) & “:” & second(A1), with the serial data and time in cell A1.

The trick I used is rather simple: firstly, I recorded the date serial as a 32 bits integer (16 bits suffice if your are short in memory) and the time serial in a 32 bits float. Then I reconstruct the full data and time information for printing and exporting to an application which can handle doubles. Next is the simple function which concatenates both serials:

concatenate a 32 bits integer with a fractional 32 bits float to print a date 
and time serial (iiiii.ffffff)
void printDateAndTimeSerial(uint32_t date, float time)
	/* create char array buffer */
	char *ptrArray = (char*)malloc(11 * sizeof(char));
	/* convert the integer part in a char array */
	ptrArray = utoa(date, ptrArray, 10);
	/* create char array buffer for the float conversion */
	char *ptrFloat = (char*)malloc(8 * sizeof(char));
	/* convert the float in an char array */
	ptrFloat = dtostrf(time, 8, 6, ptrFloat);
	/* copy the fractional part of the float, including the decimal separator */
	memcpy(ptrArray + 5, ptrFloat + 1, 7);
	/* print result */
	/* free memory space */


Checking clock accuracy

This T&T explains how to check the accuracy of a Real Time Clock (RTC). Lets make it a little bit harder and say that you do not have access to the Internet…

Checking a RTC requires a highly accurate reference time base which can be read from a radio signal. Starting from there, two options are available: read the DCF77 radio signal, or the time stamps from a GPS receiver !

DCF77 is a German longwave time signal and standard-frequency radio station delivering a timestamp sent Coordinated Universal Time (UTC)+1 or UTC+2 depending on daylight saving time. Many, not to say most synchronized clocks and even watches read the DCF77 frames. The DCF77 frames feature:

  • Current date and time bits
  • Leap second warning bit
  • Imminent change of CET to CEST, or vice versa, Announcement bit
  • Central European Time (CET) / Central European Summer Time (CEST) bit
  • Abnormal transmitter operation identification bit
  • Several parity bits

Some restrictions must be taken into account: the radio signal may be disturbed and the emitter experiences some downtime over time (0.05 % downtime).

Many cheap (< 10€) receivers are available on the market such as this one below

As usual, the arduino community makes some nice code available

An alternate option consists in reading the time stamps from a GPS receiver. GPS receivers output a 1PPS (1 pulse per sec) signal which is to be used for synchronizing the timestamps readings using the BWC, GAG, GLL or the RMC sentences from the NMEA standards. Use the ZDA sentence to get the local time. The GPS time is as accurate as 40 ns, which far enough for my own needs.

I built a simplistic prototype to evaluate the Maxim-Dallas DS3231 RTC (datasheet).

After 4 months of continuous operation, after exposing the prototype to marge temperature changes (up to 20°C), I have been able to notice a 3 seconds shift which is better than the specification of the RTC (2 ppm @ >0°C and <40°C). which turns to less or equal 1 minute per year. In this way I managed to get a rough idea about the drift over 2, 5 or 10 years which represent the typical time scales for the IoT projects.


Code documentation (Part 1)

Part 1

Writing code is awesome. Have you ever compared coding works to the work of the potter ? He starts with a piece of clay, shapes it , refines it up to the final object. None from its production is fully identical to an other. Same thoughts apply to the coding works: the language is potter’s wheel, the bits, instructions, functions are the clay and the application is a plate, a jug, a vase. And we all know that we have our tricks, our fads, so that none from my code compares exactly to my colleagues.

As far as creativity is concerned, every thing is fine . However, the side effect of this statement relates to the documentation. As my own thoughts change along the time, my coding skills evolved too probably so that I am now confused when I get back to dated code which lacks critical documentation. I can remember very well a pretty tricky coding section that I worked on 8 years ago, that was so trivial to me at this time so that I did not document it exhaustively (apart from the basic standard line commenting). It took me an hour or two to reverse engineering this code up to the ascertainment that this was just a nice trick and not so much rocket science, however tricky enough to require some more comments.

Now that I handle x00.000 lines of code (actually 800 Mb of VB.NET code and 400 Mb of c/c++ code), documentation becomes quite critical. I paid a particular attention to my c/c++ libraries which are the fundamental basis for most of my applications and I decided to put some efforts on documenting my code, and improving the global description of the code in order to ease the use of these libraries and their inclusion in application code.

I searched the net, asked my colleagues about the de facto standard application for documenting c/c++ code and looked at what others did when writing code. In the end, Doxygen appeared to be the application I was looking for. The quite nice thing about Doxygen is its ability to run apart from the code (as long as you pass the proper parameters); most IDE’s feature optional plugins including Doxygen plugins, more or less sophisticated which help a lot in documenting the code, extracting the information and building the documentation files (html, chm and latex actually). The rules are quite easy to understand, quite flexible, and once again, you can write your comments and documentation blocks the way you like.

Here are a few links to Doxygen:

Video of the day

I love these highly risky rescue operations !

They remind some blood icing situations and the immense joy of saving a bunch of critical bytes of data or restarting a critical equipment just in time. Any story to share here ?

Best wishes for 2019 !

For the first time since 1993, we welcomed the whole family at home ! Including my dear Mom, 87 years old, a tonic Grandma, now a Grand-Grandma for the third time who agreed to travel with the tribe for this event. She paid a visit to my secret lab and asked many many questions and had a look at all these couloured bits and pieces pell-mell on my desk that she found “pretty”.

Well, I guess we have a new geek in town…

I hope you had a pleasant Chrismast time too, and I send my best wishes to you all.

3D Printing (Part 14)

Part 123456789101112, 13, 14

The heating plate is made of two symmetric printed conductive layers ~1.5 Ohm each. As printed on the heating plate you may wire them for use with 12 V or 24 V power supplies. As we need to add an extra power supply the choice for a 24 V power supply is trivial as less current will flow through the switch and the wires. As the minimum power rating for the power supply is 192 W, a 200 W power supply (and above) will do the job without efforts.

Nota: When choosing the power supply, check for the thickness. Many power supplies are 50 mm high which will prevent a proper cooling because of the insufficient air gap below the power supply.

This is the power supply that I bought:

  • Voltage in: AC 110 V/220  v
  • Voltage out: DC 24 v
  • Current out: 0 to 10 A
  • Weight: 0.5 kg
  • Dimension: 165*99*39 mm
  • Enclosure: alumina
  • Protections: over voltages, over-currents, short-circuits
  • Operating temperature: 0 to 40°C
  • Humidity: 0 to 95%

For a few euros I went for an off the shelf power switch. I found no reason why I should spend time to built a more expensive one.

This switch is driven from the heat bed output of the Marlin board. The switching part is fully isolated with an optocoupler. The marked wire is the goes to the + terminal on the main board.

Next picture contains the schematics of the Marlin main board where I circled the heater control output and the temperature input:

Best is to use MTA-100 series connectors (1 x 2 pins and 1 x 4pins). However if you do not not have such connectors you may use headers as the pins spacing is 2.54 mm.

Nota: the wire gauge is so high (in other words, the wires are so thin) that I failed to crimp the wires in the connector so that I add to solder the wires in order to achieve a reliable connection.

Next pictures illustrate the configuration that I choose for installing the power supply and the switch. The idea was to keep the wires as short as possible and to leave the aperture unmasked as I find it very convenient for cleaning the cabinet.

Save a sufficient cable length so that the wires will not suffer from being twisted back and forth down to breakage. Check my suggestion in the next picture:

Before connecting all pieces together, check the power supply voltage

and the heater resistance

Before running any print, you need to update the slicer parameters.

Go to the Cura pane, click on the Filament pane and set the appropriate temperature: 50°C (more or less) for PLA and 100°C (more or less for ABS)

Then you might want to update the G-Code which is executed prior and after printing:

Start G-Code

g28 ; home
g90 ; absolute positioning
g21 ; set units to mm
g0 z5 f5000 ; extruder above bed
g0 x150 y15 f10000 ; move fast to front right
m190 s{BED} ; set extruder 0 temperature and wait for it
m109 s{TEMP0} ; set extruder 0 temperature and wait for it
g0 z0.2 f500 ; up tray (slowly)
g92 e0 ; reset extr length
g1 e10 f50 ; feed filament
g92 e0 ; reset extr length
g1 x50 e10 f500 ; print wire
g92 e0 ; reset extr length

This start G-Code feature a short print which allows a proper priming of the extruder, a nozzle cleaning and a simple printing quality check.

End G-Code

g0 z180; down tray
g91; Relative positioning
g1 e-1; retract filament
m104 t0 s0; switch off extruder temperature
g90; Absolute positioning
g92 e0; Reset extruder position
m140 s0; Disable heated bed
m84; switch off steppers
m107; switch off fan

And here we are at last !

I checked the heated bed with Xmas decoration. Thin stars (0.6 mm, so as to say 3 layers) were subject to wrapping. They are now perfect using the default 50°C bed temperature


3D Printing (Part 13)

Part 123456789101112, 13, 14

Many PLA rolls were fused in my Welleman k8400. So far, it has been a good servant in spite of few breakdowns, mainly due to clogged nozzle or improper adjustments. Careful cleaning and fine tuning solved all  these problems except one which is my fault. As I was taking apart the fusing module, I damaged the thread on the alumina plate that I add to replace. I also noticed few cracks on the body parts which occurred months after assembling my printer and which are probably due to over-tight bolts…

Except these minor problems, I have no particular complain and lots of enjoyment with this printer. Although PLA is very, very easy to print in most cases, it lacks to mechanical properties of ABS… And printing ABS on a non-heating bed is almost impossible. As I had to print a small ABS part in a hurry, I used an air dryer flushing hot air beneath the printing bed but this was some sort of desperate option although it proved to work fine. Months ago I ordered a heating plate and a spare DC power supply but I failed to find time to install the option and had no more particular reason to do it. Under the pressure of some Christmas presents that require some printed parts, I proceeded with the modification that I will now describe.

Removing the printing bed is plain easy. Some drilling in the metal plate is necessary and a drill press might be very useful for achieving a clean result. Draw carefully the center of the drilling locations (3.5 mm) using the heated plate as a template. Also, use a special conical cutting tool for removing enough metal from the heated bed so that the heads from the flat screws (M3x15) do not exceeds the surface (opposite to the heating layer).

Cut the original support plate to leave space for the electrical connections.

Cut the insulation rock wool sheet with a simple cutter.

Solder the 100 kOhm thermistor on the heater plate so that the little bulb sits in the dedicated hole. Put some thermal compound in this hole in order to improve the thermal joint.

Take special care to the connecting wires: they must not touch each other and must not touch the metal plate either.

Assemble the parts; use tooth lock washers and gently tighten the nuts. Solder the wires on the plate after checking the required configuration depending on the power supply used (12 or 24 V) and reinstall the whole assembly. Next is an illustration of the retaining springs that I used in the past: I reused the design for making larger springs as the printing bed got thicker.

Then you will need to move the Z axis stop sensor 8 mm downward. You have no other choice than to drill 2 new holes in the back panel of the printer. Adjust the stop position using the standard procedure.

Next post on same subject

TASCAM Sound Recorder (Part 4)

Part 1, 2, 3, 4, 5

And here is the driver code. Nothing exceptional just plain good’ol arduino code. Check the writeByte function which contains few tricks and optimizations that are mandatory to achieve a proper timing. Ultimately this code contains a pretty versatile bit-bang UART writer that you may want to reuse in various applications.

Enter the DR-40 commands through the key board of the console using the abbreviations from the commands:

  • ‘p’: PLAY
  • ‘s’: STOP
  • ‘r’: RECORD
  • ‘f’: FORWARD
  • ‘b’: BACK
  • ‘m’: MARK
  • ‘1’: F1
  • ‘2’: F2
  • ‘3’: F3
  • ‘4’: F4
uint8_t _TxMask;
uint8_t _TxMaskBar;
volatile uint8_t *_TxPort; 
uint16_t _timeInterval;
bool _invert;
bool _parity;
#define ONE_MILLION 1000000UL
#define STOP 		0x08
#define PLAY 		0x09
#define RECORD 		0x0B
#define FORWARD 	0x0E
#define BACK 		0x0F
#define MARK 		0x18
#define F1 			0x1C
#define F2 			0x1D
#define F3 			0x1E
#define F4 			0x1F

#define KEY_PRESS	0x40
#define KEY_DOWN	0x60
#define KEY_UP		0x00

#define PAR_NONE	0x00
#define PAR_EVEN	0x01
#define PAR_ODD		0x02

Initialize communication port 
Any pin on any port can be used
Baud rate goes up to 57600 
Parity may be none (0), odd (1) or even (2)
Data may be inverted or not (flip mark and spaces)
void begin(volatile uint8_t *TxPort, uint8_t TxPin, uint32_t baudRate = 9600, uint8_t parity = PAR_NONE, bool invert = true)
    /* Record global variables */
    _invert = invert;
    _parity = parity;
    /* Transmit port */
    _TxPort = TxPort;
    /* Transmit pin */
    _TxMask = (0x01 << TxPin);
    _TxMaskBar = ~_TxMask;
    /* Make TxPin an output pin */
    *(_TxPort - 1) |= _TxMask; 	
    /* Set idle mode */
    if  (!_invert) 
        *(_TxPort) |= _TxMask;
        *(_TxPort) &= _TxMaskBar;
    /* Set bits intervals  in us */
    _timeInterval = (ONE_MILLION / baudRate);

Write byte on serial port
global variables in use:

-----------     ---     ---     ---     ---    ---- --- ----   1 mark
           |Sta| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |Par|Stp|
            ---     ---     ---     ---     --- ---           0 space/break
void writeByte(const uint8_t data) 
    uint32_t now;
    uint16_t compositeBits = 0x00; /* Map data bits */
    /* compositeBits content: 76543210 */
    compositeBits |= data; /* Map data bits */
    uint8_t bits = 8;
    if (_parity != PAR_NONE)
        bool dataParity = parity(data);
        /* Append a mark as appropriate */
        if (((_parity == PAR_EVEN) && dataParity) || ((_parity == PAR_ODD) && !dataParity))
            /* compositeBits content: p76543210 */
            compositeBits |= (0x01 << bits);  /* Map parity bit */
        bits += 1; /* Actually 9 bits */
    /* compositeBits content: Sp76543210 or S76543210*/
    compositeBits |= (0x01 << bits);  /* Map stop bit (mark) */	
    /* compositeBits content: Sp76543210s or S76543210s */
    compositeBits <<= 1; /* Shift bits for start inclusion (space) */
    bits += 2;
    if (_invert)
        compositeBits= ~compositeBits;
    uint32_t lastTick = micros(); /* Record start time of bits transfer */
    /* Transfer composite bits starting from lower bits */
    for (uint8_t i = 0; i < bits; i++) 
        uint8_t bitValue = (compositeBits & 0x01); /* Extract lower bit value */
        if  (bitValue) 
            *(_TxPort) |= _TxMask;
            *(_TxPort) &= _TxMaskBar;
        compositeBits >>= 1; /* Shift bits */
        while((micros() - lastTick) < _timeInterval);
        lastTick += _timeInterval; /* Set next bit release time */

Send function key 
void sendKey(uint8_t function)
    writeByte(function | KEY_PRESS);
    writeByte(function | KEY_UP);

Computes the parity from a value. The function returns a true for an odd number
of bits and a false for an even number of bits.
bool parity(uint8_t n) 
    bool parity = 0; 
    while (n) 
        parity = !parity; 
        n = (n & (n - 1)); 

void setup()
    /* Configure serial port using default parameters */
    begin(&PORTB, PINB0, 9600, PAR_EVEN, true);

void loop()
    /* Listen to incoming bytes from the console */
    if (Serial.available() > 0)
        char inputByte = (char)Serial.read();
            case 'p': sendKey(PLAY); break;
            case 's': sendKey(STOP); break;
            case 'r': sendKey(RECORD); break;
            case 'f': sendKey(FORWARD); break;
            case 'b': sendKey(BACK); break;
            case 'm': sendKey(MARK); break;
            case '1': sendKey(F1); break;
            case '2': sendKey(F2); break;
            case '3': sendKey(F3); break;
            case '4': sendKey(F4); break;