The Min-Max sketch

This sketch is a simple extension to the most-basic analogRead() example.
Instead of printing every single value read, it performs a series of 10000 reads of analog pin 0. Then it prints the minimum and maximum values sampled, as well as the span of values: Delta = Max – Min.

With this approach, the Serial Monitor does not get flooded with data and more time is spent in reading values, than in transferring them over Serial.

A single call to analogRead() takes about 0.1ms, so each loop() call takes roughly a second.

const int analogPin = 0;

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

void loop() {
    int mn = 1024; // mn only decreases
    int mx = 0;    // mx only increases

    // Perform 10000 reads. Update mn and mx for each one.
    for (int i = 0; i < 10000; ++i) {
        int val = analogRead(analogPin);
        mn = min(mn, val);
        mx = max(mx, val);
    }

    // Send min, max and delta over Serial
    Serial.print("m=");
    Serial.print(mn);
    Serial.print(" M=");
    Serial.print(mx);
    Serial.print(" D=");
    Serial.print(mx-mn);
    Serial.println();
}

Downloads

Advertisements

Posted on May 15, 2011, in Programming and tagged , , . Bookmark the permalink. 1 Comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: