Thursday 17 March 2016

analogRead - Arduino

 The Arduino can read analog voltages.
It can be used to help analyse circuits.


This can only be done with the analog pins (A0 to A5)

In this example I'll use pin A3
 

Open your serial monitor.

We are getting the number 238
This is not a voltage
It's the scaled number between zero & 1023
I call this the readValue.
It's a 10bit number (1024 is 2 to the 10th)

0V = 0
5V = 1023

You can test this is we move out test probe to measure the reading @ the 5 volt rail.
We would expect a reading of 1023.
This is exactly what we get.
 
To calculate the voltage from the readValue use this formula.

Voltage  = (5/1023) x ReadValue

thus in this example,  V = (5/1023) x 238 = 1.163

The code:
------------------------------------------------
// declare your variables
int readPin=A3;
int V2=0;
int delayTime=500;

void setup()
{
  pinMode(readPin,INPUT);
  Serial.begin(9600);
}

void loop()
{
  V2=analogRead(readPin);
  Serial.println(V2);
    delay(delayTime);
}
----------------------------------------------------------

A useful variation of the program would be for the monitor to display the value in Volts.
To do this we need to do a few changes:
Add a new variable (readVal)
V2 must be a float
 
 readVal=analogRead(readPin);
  V2=(5./1023.)*readVal;
 

 The improved code:

------------------------------------------------
// declare your variables
int readPin=A3;
int readVal;
float V2=0;
int delayTime=500;

void setup()
{
  pinMode(readPin,INPUT);
  Serial.begin(9600);
}

void loop()
{
  readVal=analogRead(readPin);
  V2=(5./1023.)*readVal;
  Serial.println(V2);
    delay(delayTime);
}
-------------------------------------------------

Thanks to Paul McWhorter for his great inspirational videos
 
 
 ---------------------------------
-------------------------------------
 

No comments:

Post a Comment