en-us_commands:reference:analogread2avg
This is an old revision of the document!
Table of Contents
analogRead2Avg()
analogRead2Avg() returns an integer average of 4~20mA input values.
int32_t analogRead2Avg(uint8_t ch, uint8_t samples)
Commands
| Command | Arguments | Return Value | Operation |
|---|---|---|---|
analogRead2Avg(ch, samples) | uint8_t ch — MPINO: analog pin such as A0; MPAINO: overall module channel number starting at 0uint8_t samples — Number of moving-average read samples; up to 20 | int32_t | Returns an integer average of 4~20mA input values. |
Example
void setup() { Serial.begin(115200); } void loop() { uint16_t raw2 = analogRead2(0); int32_t filtered2 = analogRead2Avg(0, 5); float filtered2f = analogRead2Avgf(0, 5); float currentmA = IanalogRead2f(0, 4.0F, 20.0F); if (raw2 == ANALOG_READ2_ERROR || filtered2 == ANALOG_READ2_AVG_ERROR || filtered2f == (float)ANALOG_READ2_AVG_ERROR || currentmA == (float)ANALOG_READ2_ERROR) { Serial.println("4-20mA input error"); delay(500); return; } int32_t percent = Iscale((int32_t)raw2, 0, 32767, 0, 100); IanalogWrite2(0, 0, 100, 50); // 50% → approx. 12mA IanalogWrite2f(1, 0.0F, 10.0F, 2.5F); // 25% → approx. 8mA Serial.print("4-20mA raw: "); Serial.println(raw2); Serial.print("4-20mA filtered: "); Serial.println(filtered2); Serial.print("4-20mA filtered float: "); Serial.println(filtered2f, 2); Serial.print("percent: "); Serial.println(percent); Serial.print("current: "); Serial.println(currentmA, 2); delay(500); }
Precautions
- Set the module DIP switches and wiring for 0~20mA current I/O.
- An input of approximately 3.6~4.0mA returns the normal value
0; inputs below 3.6mA return an error value. - Error values help detect open circuits. The user must implement final alarms and safety actions in the program.
IanalogRead2()andIanalogRead2f()also return65535on error, rather than a user-range value. Check for errors before using the result.- The full
int32_trange is available formin~maxinIanalogRead2(), but if the normal range includes65535, it cannot be distinguished from an error value. analogRead2Avgf()uses state and a buffer separate fromanalogRead2Avg(). Using both increases SRAM usage.- If
samplesis0or memory allocation fails inanalogRead2Avgf(), it returns the current valid corrected value as afloat. - On MPINO, do not use
analogRead2()on voltage/NTC channels that are not 4~20mA inputs. - For MPINO products requiring
analogReference(EXTERNAL), set it first insetup(). IanalogWrite2()andIanalogWrite2f()are convenience outputs dedicated to 4~20mA. Avoid alternating them withIanalogWrite()on the same channel.- The analog output circuit requires an external 12~24V supply. USB power alone may not provide normal output.
- Verify actual current input/output with measuring instruments after preparing a test product.
en-us_commands/reference/analogread2avg.1788785565.txt.gz · Last modified: by 127.0.0.1
