B4R Tutorial Analog Read Example

Hi,

a simple analog read example which reads the temperature from sensor TMP36 and logs the result.
B4X:
Sub Process_Globals
    Public Serial1 As Serial
    Private TempSensorPin As Pin                            'Output pin connected from the TMP36 sensor
    Private TempSensorPinNumber As Byte = 0x00   'Pin number used is A0 (Analog)
    Private MeasureTimer As Timer                           'Timer for the sensor measurement
    Private MeasureTimerInterval As ULong  = 2        'Timerinterval in seconds
End Sub

Private Sub AppStart
  Serial1.Initialize(115200)
  Log("AppStart - TemperaturePin ", TempSensorPinNumber, " read every ", MeasureTimerInterval, " seconds")
  'Init the pin with TMP36 connected
  TempSensorPin.Initialize(TempSensorPinNumber, TempSensorPin.MODE_OUTPUT)
  'Init the timer
  MeasureTimer.Initialize("MeasureTimer_Tick", MeasureTimerInterval * 1000)
  'Start the timer
  MeasureTimer.Enabled = True
End Sub

'Handle the timer ticks
Private Sub MeasureTimer_Tick
  'Read the current state of the pin
  Dim rawvoltage As UInt = TempSensorPin.AnalogRead
  'Convert rawvoltage To celsius And fahrenheit
  Dim volts As Double = rawvoltage/205.0
  'Calculate Celsius
  Dim celsiustemp As Double = 100.0 * volts - 50   
  Log("Temperature: ", celsiustemp)
End Sub

B4X:
AppStart - Temperature Pin 0 read every 2 seconds
Temperature: 16.3415
Temperature: 17.8049
Temperature: 19.2683
Temperature: 20.2439
Temperature: 21.2195
Temperature: 20.2439
Temperature: 19.7561
 

rwblinn

Well-Known Member
Licensed User
Longtime User
Hi,

thanks for the spot = in principle you are right, but just curious and may be someone has an answer:
  • the result does not make a difference either using mode_input or mode_output. Did some tests and the log shows the same temperature.
  • the majority of the TMP36 example sketches for the Arduino, do not init the TMP36 signal pin connected to f.e. A0. After setup, in the loop
    analogRead(sensorPin) is used without an init. I have used the pin init to follow B4R definitions.

Appreciated
 

rwblinn

Well-Known Member
Licensed User
Longtime User
Thx for pointing to this, would say, must read for B4X developers.

For this TMP36 Sensor Analog Read and related examples, it means that the line below can be left out.

Please confirm: By doing so, B4R will give a "pin not initialized" warning but that can then be ignored or will this warning have any implications?

B4X:
'Init the pin with TMP36 connected
TempSensorPin.Initialize(TempSensorPinNumber, TempSensorPin.MODE_OUTPUT)
 
Top