subtracting values - analogRead - what am I not getting?

Hello and thanks for reading this!

I am working on a simple project with an ATTIny and programming it with the UNO in ISP mode which just works so well!

I am reading 2 analogue values in on 2 ports - one of the values is a reference and is subtracted from the sample input.

Simple enough - however it seems that this does not work - in the code here it

 int sampleIn = analogRead(samplePort3) - analogRead(refPort4);

It ignores the Ref and only returns the sample value. this could be an ATTIny issue and my next step is to do this with the UNO directly and use the serial monitor, but, I was hoping that you amazing people will say - "do this". This should be simple but having spent a day on this using Float instead of int thinking it was a negative number issue (it is the same if it is negative or positive - it I want a return of Zero if negative btw)

Anyway Thanks again -

Nothing wrong with that line. So time to start debugging :slight_smile: At least if both 'samplePort3' and 'refPort4' are analog ports.

PS is 'samplePort3' by any change A3 and 'refPort4' A4? Then the names are pretty stupid. Variable names are a tool for you to give them a useful name in light of the project. So here 'samplePort' and 'refPort'. Or better, 'samplePin' and 'refPin' because they are not ports but pins :wink:

At least for the purposes of debugging I would read the analogue values into variable before doing the calculation so that you can print the values that are being read.

Does the ATTIny have the same problem that the 328 has whereby there is only one ADC on the chip which means that some time is needed for the ADC to settle to the new value when changing analogue inputs ?

Rather than this

int sampleIn = analogRead(samplePort3) - analogRead(refPort4);

try this - the duplication is intentional in order to discard the first reading in case it is unreliable

int port3Val = analogRead(samplePort3);
port3Val = analogRead(samplePort3);

int port4Val = analogRead(refPort4);
port4Val = analogRead(refPort4);

int sampleIn = port3Val - port4Val;

...R

Thank you for your quick responses,

  • Yes time to debug, I will get this on A UNO but I am interested if the ADC can not handle the read one after the other. - it is a small chip and one I will look into - thankfully - non of the comments are showing a simple mistake on my part. - maybe not thankfully...

I will report back!

Thank you...

DJH55:
but I am interested if the ADC can not handle the read one after the other

It can if you do it the correct way. These are the joys of dealing directly with the computer hardware without an Operating System to protect you.

...R