This section explains how to use the Analog-to-Digital Converter (ADC) on the obniz IO pins to measure analog voltage.
Overview
By using the ad.get(IO) function, you can read the voltage applied to a specific IO pin as a numerical value. This is useful for retrieving data from analog sensors such as temperature, light, or pressure sensors.
Function Description
ad.get(pin_number)
- Description: Measures the voltage on the specified IO pin.
- Parameters:
pin_number(number): The ID of the IO pin you wish to measure.
- Return Value:
- Returns the measured voltage in Volts (V).
Code Example
The following Lua script demonstrates how to continuously read the analog voltage from IO Pin 1 and log it to the console.
-- This function runs repeatedly when the device is offline
function on_offline_loop()
loop()
end
-- This function runs repeatedly when the device is online
function on_online_loop()
loop()
end
-- Initialization
os.log(" - Lua Start");
-- Set Pin 1 to retain its state (keep it active for ADC)
io.retain(1, true);
-- Main Loop
function loop()
-- Wait for 100ms to prevent excessive processing
os.wait(100);
-- Retrieve voltage from Pin 1 and log the value
-- The value is returned in Volts (e.g., 1.25v)
os.log("AD1: " .. ad.get(1) .. "v");
end
Key Points
- io.retain: In this script,
io.retain(1, true)is used to ensure the pin remains in a state where it can be measured consistently. - Polling Interval: The
os.wait(100)is included to manage the sampling rate. You can adjust this value depending on how frequently you need to monitor the sensor data. - Unit: Note that the value returned by
ad.get()is already scaled to Volts, so no complex conversion from raw 10-bit or 12-bit integers is required.