EmonTx4 DS18B20 Temperature sensing & firmware release 1.5.7

2. The mechanism behind the error

Temperature sensing using the one-wire DS18B20 temperature sensors that we use relies on precise timing for the digital communication 1’s and 0s. This communication and timing is implemented using a bit-banging technique in software.

Here’s an example of what the OneWire write bit function looks like:

void OneWire::write_bit(uint8_t v)
{
	IO_REG_TYPE mask IO_REG_MASK_ATTR = bitmask;
	volatile IO_REG_TYPE *reg IO_REG_BASE_ATTR = baseReg;

	if (v & 1) {
		noInterrupts();
		DIRECT_WRITE_LOW(reg, mask);
		DIRECT_MODE_OUTPUT(reg, mask);	// drive output low
		delayMicroseconds(10);
		DIRECT_WRITE_HIGH(reg, mask);	// drive output high
		interrupts();
		delayMicroseconds(55);
	} else {
		noInterrupts();
		DIRECT_WRITE_LOW(reg, mask);
		DIRECT_MODE_OUTPUT(reg, mask);	// drive output low
		delayMicroseconds(65);
		DIRECT_WRITE_HIGH(reg, mask);	// drive output high
		interrupts();
		delayMicroseconds(5);
	}
}

The crucial part to note here is the way that it disables interrupts with noInterrupts(); delays for 65 microseconds and then enabled interrupts again with interrupts();

The one wire reset command has a similar 70 microsecond period with interrupts disabled.

Electricity monitoring on the EmonTx4 is implemented using ADC continuous conversion. The ADC performs the ADC sampling in the background firing an interrupt service routine (ISR) when each sample is ready. The configured sample rate on the EmonTx4 for each ADC sample is 39.4 microseconds. The ISR function is therefore called every 39.4 microseconds with the next sample ready for processing.

When the OneWire temperature sensing code disables interrupts it blocks the ISR interrupt generated by the ADC for a period of 65-70 microseconds (longer than the 39.4 microsecond sample rate). This in turn causes the ADC to lose it’s place in the sequence of channels that it is sampling.

The ~4W of consumption on CT6 in the example above is a small number of samples from the voltage channel, which was the next one in line to sample, being allocated to CT6 incorrectly.

With 3kW on CT1, CT3 & CT5 we again see the effect of the ADC code losing it’s place and allocating samples incorrectly. The effect is relatively small as the ADC regains the correct allocation by the next sample and the vast majority of samples are allocated correctly.

2 Likes