Hi, I used to work on PIC and AVR microcontrollers. There, while reading a battery voltage via ADC pin on MCU, I directly used potential divider and by using ‘adc=ADC_Read(1);’ command in miKro C pro, I could directly read the battery voltage. Now, if ADC reference = 5v then for a 10 bit ADC 5v could represent 1024. According to that I used to calculate another voltage values like 3v representing 614(approx.). According to that I performed operations. For example:

adc = ADC_Read(1); //get 10 bit result of AD conversion
//turn off the LED
//turn on the LED

NOW MY QUESTION IS: How to perform such kind of operation in electric imp? How to calculate the value of 3v? How to execute ‘if’ loop? How to compare such things?
Please help me. I am new to imp though I have read
and the hardware related doc

If you read an analog input voltage pin you get a value between 0 and 65535, where 65535 represents full scale which is your hardware.voltage(). If you are not concerned about the absolute voltage but just want to test if it is over half of Vcc, ignore the hardware voltage and just test if the input is over 32767.

If you read hardware.voltage() you get a float of typically 3.3v depending on your hardware. So if you take your reading, divide by 65535.0 (not an integer) and multiply by hardware.voltage() then you get the input pin voltage.

As for an “if loop”, Squirrel has similar syntax to C, so your example should work. There are loads of examples online, which is probably easier than cracking the rather terse Squirrel language reference. How I would like a “Squirrel in a Nutshell” from O’Reilly - I wonder what the cover picture could be!

Yes, Squirrel syntax and C syntax are very close. However, there is a significant difference between using an RTOS which imp has and raw microcontroller programming.

I know C is not Arduino, but Arduino is based on C so the reference below should help a lot. You want to avoid using an endless main loop and instead use event - driven programming techniques.

Thank You so much DrJack and mjkuwp94. I will try to do in a way you guys have told me.
But there is another query: In my example, I have calculated 614 (representing 3v) manually. And took this as a reference to compare with the actual analog value (adc is an actual analog value in my example). Is there any way to perform such manual operation here?

@PinkFloyd - the imp is a 3.3v device, and reading an ADC returns a 16-bit numbers.

You can determine the actual voltage of a particular analog pin by using hardware.voltage and your analog reading:

`function getPinVoltage(pin) {
local vdd = hardware.voltage();
local vpin =;
return (vpin / 65535.0) * vdd;


Thank you beardedinventor. :slight_smile: