IO Code Example - Light Dimmer & Control

In the code example the function scanEvent it states:

// Read the pot, scale to 0.0 - 1.0
local pot = pinPot.read() / 65536.0;
</div><div>However, shouldn't it be:</div><div><pre class="code c" style="padding: 0.5em; margin-top: 0px; font-family: monospace, serif; border: 1px dashed rgb(140, 172, 187); overflow: auto; background-color: rgb(247, 249, 250); text-align: justify; "><span class="co1" style="padding: 0px; margin: 0px; color: rgb(128, 128, 128); font-style: italic; ">// Read the pot, scale to 0.0 - 1.0</span>
local pot <span class="sy0" style="padding: 0px; margin: 0px; color: rgb(102, 204, 102); ">=</span> pinPot.<span class="me1" style="padding: 0px; margin: 0px; color: rgb(0, 102, 0); ">read</span><span class="br0" style="padding: 0px; margin: 0px; color: rgb(102, 204, 102); ">(</span><span class="br0" style="padding: 0px; margin: 0px; color: rgb(102, 204, 102); ">)</span> <span class="sy0" style="padding: 0px; margin: 0px; color: rgb(102, 204, 102); ">/</span> <span class="nu16" style="padding: 0px; margin: 0px; ">65520.0</span><span class="sy0" style="padding: 0px; margin: 0px; color: rgb(102, 204, 102); ">;</span>
... since that is the max of the analog's range?

Or am I missing something?

Yes, you’re correct. It’s a 12 bit ADC, shifted left 4 bits to fill it to 16 bits. 65520 is the correct maximum.

That’s a bug really, isn’t it? A 12-bit ADC “pretending” to be a 16-bit one (which is what it does for future expansion, in case we ever upgrade the imp internals with a part that has a real 16-bit ADC) shouldn’t be (n<<4), it should be (n<<4) | (n>>8) so that the maximum reading remains 65535.

Peter

how exactly would you implement a read from an analog sensor? very new and a bit unclear by reading the documentation. explanation greatly appreciated!

For reference, the documentation in question is…


http://devwiki.electricimp.com/doku.php?id=electricimpapi#pin_class

..under the read method.

If you're pretty confident in your power supply then you simply configure the pin as ANALOG_IN then read it to get an integer between 0 (corresponding to 0V) and 65535 (corresponding to 3.3V).

hardware.pin1.configure(ANALOG_IN);
result = hardware.pin1.read();

If you're running on an unstable power supply you can call hardware.voltage to read the supply rail and then scale your pin result appropriately. Most designs shouldn't be affected by this unless you need to be super accurate (and it's not a super accurate ADC anyway).

I plan to post a Hannah potentiometer example next week which will demonstrate this in practice, including the scaling.

Rob
Fen Consultants, UK

extremely helpful. I missed this section in the reference. Thanks a bunch