Analog read

We read the value from an analog pin using the analogRead() function. This function will return a value between 0 and 1023. This means that if the sensor is returning the full voltage of 5V, then the analogRead() function will return a value 1023, which results in a value of 0.0049V per unit (we will use this number in the sample code). The following code shows the syntax for the analogRead() function:

analogRead(pin);

The analogRead() function takes one parameter which is the pin to read from. The following code uses the analogRead() function with a tmp36 temperature sensor to determine the current temperature:

#define TEMP_PIN 5

void setup() {
  Serial.begin(9600);
}

void loop() {
  int pinValue = analogRead(TEMP_PIN);
  double voltage = pinValue * 0.0049;
  double tempC = (voltage - .5) * 100.0;
  double tempF = (tempC * 1.8) + 32;
  Serial.print(tempC);
  Serial.print(" -  ");
  Serial.println(tempF);
  delay(2000);
}

The preceding code starts off by defining the pin that the temperature sensor is attached to which is the analog pin 5. The setup() function configures the serial monitor so the application can print the temperature to it.

The loop() function begins by reading the analog pin and storing the value in the pinValue variable. To convert this value to the actual voltage, we multiply it by the 0.0049V value that we saw earlier in this section. If we look at the datasheet for the tmp36 temperature sensor, we will determine that the (voltage - .5) *100.0 is the correct formula to calculate the temperature in Celsius. We can then use the standard formula (celsiusTemp *1.8) + 32 to determine the temperature in Fahrenheit. Finally, we print these values to the serial monitor and delay for two seconds before beginning the loop again.

We will be using the digitalRead(), digitalWrite(), analogRead() and analogWrite() functions a lot in this book so you will be getting familiar with them.

Now let's look at structures.