/***************************************************
     hb-midilib-analog.c
     Realtime MIDI Library for the MIT HandyBoard
     colby leider (cnl@dartmouth.edu)
     last updated 9.16.97

     http://music.dartmouth.edu/~colby/hb.html
***************************************************/



/* used by read_averaged_analog and return_averaged_analog */
#define _NUM_VALUES_TO_AVERAGE 5


/* read_analog:
        sets the memory location pointed to by the pointer
        'value' to contain the 8-bit digitized value of the
        sensor voltage in the given analog port, multiplied by
        'scale' with a DC offset of 'offset' */
/***************************************************************/
void
read_analog(int port_number, int *value, int offset, int scale)
{
    *value = analog(port_number) * scale + offset;
}


/* return_analog:
        returns an integer containing the 8-bit digitized value
        of the sensor voltage in the given analog port,
        multiplied by 'scale' with a DC offset of 'offset' */
/***************************************************************/
int
return_analog(int port_number, int offset, int scale)
{
    return (analog(port_number) * scale + offset);
}


/* read_averaged_analog:
        sets the memory location pointed to by the pointer 'value'
        to contain the average of the most recent 8-bit digitized
        value of the sensor voltage in the given analog port,
        multiplied by 'scale' with a DC offset of 'offset'.
        the number of averages taken is abstracted as
        _NUM_VALUES_TO_AVERAGE */
/***************************************************************/
void
read_averaged_analog(int port_number, int *value, int offset, int scale)
{
    int i;
    for (i=0; i<_NUM_VALUES_TO_AVERAGE; i++) {
        *value += analog(port_number) * scale + offset;
    }
    *value = *value/_NUM_VALUES_TO_AVERAGE; 
}


/* return_averaged_analog:
        returns an interger containing the average of the most
        recent 8-bit digitized values of the sensor voltage in
        the given analog port, multiplied by 'scale' with a DC
        offset of 'offset'.  the number of averages taken is
        abstracted as _NUM_VALUES_TO_AVERAGE */
/***************************************************************/
int
return_averaged_analog(int port_number, int offset, int scale)
{
    int i, sum;
    sum = 0;
    for (i=0; i<_NUM_VALUES_TO_AVERAGE; i++) {
        sum += analog(port_number) * scale + offset;
    }
    return (sum/_NUM_VALUES_TO_AVERAGE); 
}
