main.cpp

Committer:
CSTritt
Date:
2021-10-15
Revision:
118:5b2bc88d441d
Parent:
117:b40379408898

File content as of revision 118:5b2bc88d441d:

/*
 Modified Program 8.3 "Calculating an average using functions" example
 from Horton's Beginning C, 5th ed.

 Note isolation of user I/O in two functions. Keep it out of main and 
 computation and other I/O functions.
 
 Updated to Mbed v. 5 in 2021. Normalized function naming. Removed VT100 
 sequences. Switched from return to sleep loop.

 Ported to mbed by C. S. Tritt
 Last revised: 10/15/21 (v. 1.3)
*/
#include "mbed.h"

// Construct a serial over our USB connection.
Serial pc(USBTX, USBRX, 9600); // Serial channel to PC.

const int MAX_COUNT=10; // Set globle limitnto protect against buffer overrun.

// Function prototypes (functions follow main in this file (uncommon))...
float mySum(float x[], int size); // Sums the values in a float array.
float myAverage(float x[], int size); // Averages the values in a float array.
int getData(float *data, int max_count); // Gets data from std Serial.
void userOut(float average); // Display average.

// main function - Console mode C/C++ execution starts here.
int main(void) {
    float samples[MAX_COUNT] = {0.0};  // Create & initialize sample array.
    // Note un-indexed arrays pass as pointers so content of samples can and is 
    // changed in this call.
    int sampleCount = getData(samples, MAX_COUNT); // Get values.
    float theAverage = myAverage(samples, sampleCount); // Find average.
    userOut(theAverage); // Display results.
    // Replace return(0) - PC console style, with infinite sleep loop.
    while (true) ThisThread::sleep_for(3000000);
}

// Function to calculate the sum of array elements. n is the number of elements
// in array x.
float mySum(float x[], int size) {
    float sum = 0.0;
    for(int i = 0 ; i < size ; ++i) sum += x[i];
    return sum;
}

// Function to calculate the average of array elements. Calls Sum.
float myAverage(float x[], int size) {
    return mySum(x, size)/size;
}

// Function to read in data items and store in data array. The function returns
// the number of items stored.
int getData(float *data, int max_size) {
    int nValues = 0;
    pc.printf("Assure Local Echo is activated!\n");
    pc.printf("Number of values to average (Maximum %d)? ", max_size);
    pc.scanf("%d", &nValues); // Caution: scanf is fragile.
    pc.printf("%d was read.\n", nValues); // added by cst.
    if (nValues > max_size) {
        pc.printf("Maximum count exceeded. %d items will be read.", max_size);
        nValues = max_size;
    }
    printf("Enter values:\n");
    for(int i = 0 ; i < nValues ; ++i) {
        pc.scanf("%f", &data[i]);
        pc.printf("%f was read.\n", data[i]); // added by cst.
    }
    return nValues;
}

// Function to display the average.
void userOut(float average) {
    // Display the average.    
    pc.printf("The average of the values you entered is: %.2f.\n", average);
}