Library to control a Graphics TFT connected to 4-wire SPI - revised for the Raio RA8875 Display Controller.

Dependents:   FRDM_RA8875_mPaint RA8875_Demo RA8875_KeyPadDemo SignalGenerator ... more

Fork of SPI_TFT by Peter Drescher

See Components - RA8875 Based Display

Enhanced touch-screen support - where it previous supported both the Resistive Touch and Capacitive Touch based on the FT5206 Touch Controller, now it also has support for the GSL1680 Touch Controller.

Offline Help Manual (Windows chm)

/media/uploads/WiredHome/ra8875.zip.bin (download, rename to .zip and unzip)

RA8875_Touch.cpp

Committer:
WiredHome
Date:
2014-12-28
Revision:
78:faf49c381591
Child:
79:544eb4964795

File content as of revision 78:faf49c381591:

/// This file contains the RA8875 Touch panel methods.
///

#include "RA8875.h"

// ### Touch Panel support code additions begin here

RetCode_t RA8875::TouchPanelInit(void)
{
    //TPCR0: Set enable bit, default sample time, wakeup, and ADC clock
    WriteCommand(TPCR0, TP_ENABLE | TP_ADC_SAMPLE_DEFAULT_CLKS | TP_ADC_CLKDIV_DEFAULT);
    // TPCR1: Set auto/manual, Ref voltage, debounce, manual mode params
    WriteCommand(TPCR1, TP_MODE_DEFAULT | TP_DEBOUNCE_DEFAULT);
    WriteCommand(INTC1, ReadCommand(INTC1) | RA8875_INT_TP);        // reg INTC1: Enable Touch Panel Interrupts (D2 = 1)
    WriteCommand(INTC2, RA8875_INT_TP);                            // reg INTC2: Clear any TP interrupt flag
    return noerror;
}

RetCode_t RA8875::TouchPanelInit(uint8_t bTpEnable, uint8_t bTpAutoManual, uint8_t bTpDebounce, uint8_t bTpManualMode, uint8_t bTpAdcClkDiv, uint8_t bTpAdcSampleTime)
{
    // Parameter bounds check
    if( \
            !(bTpEnable == TP_ENABLE || bTpEnable == TP_ENABLE) || \
            !(bTpAutoManual == TP_MODE_AUTO || bTpAutoManual == TP_MODE_MANUAL) || \
            !(bTpDebounce == TP_DEBOUNCE_OFF || bTpDebounce == TP_DEBOUNCE_ON) || \
            !(bTpManualMode <= TP_MANUAL_LATCH_Y) || \
            !(bTpAdcClkDiv <= TP_ADC_CLKDIV_128) || \
            !(bTpAdcSampleTime <= TP_ADC_SAMPLE_65536_CLKS) \
      ) return bad_parameter;
    // Construct the config byte for TPCR0 and write them
    WriteCommand(TPCR0, bTpEnable | bTpAdcClkDiv | bTpAdcSampleTime);    // Note: Wakeup is never enabled
    // Construct the config byte for TPCR1 and write them
    WriteCommand(TPCR1, bTpManualMode | bTpDebounce | bTpManualMode);    // Note: Always uses internal Vref.
    // Set up the interrupt flag and enable bits
    WriteCommand(INTC1, ReadCommand(INTC1) | RA8875_INT_TP);        // reg INTC1: Enable Touch Panel Interrupts (D2 = 1)
    WriteCommand(INTC2, RA8875_INT_TP);                            // reg INTC2: Clear any TP interrupt flag
    return noerror;
}

unsigned char RA8875::TouchPanelRead(loc_t *x, loc_t *y)
{
    unsigned char touchready;
    static int xbuf[TPBUFSIZE], ybuf[TPBUFSIZE], sample = 0;
    int i, j, temp;

    if( (ReadCommand(INTC2) & RA8875_INT_TP) ) {        // Test for TP Interrupt pending in register INTC2
        // Get the next data samples
        ybuf[sample] =  ReadCommand(TPYH) << 2 | ( (ReadCommand(TPXYL) & 0xC) >> 2 );   // D[9:2] from reg TPYH, D[1:0] from reg TPXYL[3:2]
        xbuf[sample] =  ReadCommand(TPXH) << 2 | ( (ReadCommand(TPXYL) & 0x3)      );   // D[9:2] from reg TPXH, D[1:0] from reg TPXYL[1:0]
        // Check for a complete set
        if(++sample == TPBUFSIZE) {
            // Buffers are full, so process them using Finn's method described in Analog Dialogue No. 44, Feb 2010
            // This requires sorting the samples in order of size, then discarding the top 25% and
            //   bottom 25% as noise spikes. Finally, the middle 50% of the values are averaged to
            //   reduce Gaussian noise.

            // Sort the Y buffer using an Insertion Sort
            for(i = 1; i <= TPBUFSIZE; i++) {
                temp = ybuf[i];
                j = i;
                while( j && (ybuf[j-1] > temp) ) {
                    ybuf[j] = ybuf[j-1];
                    j = j-1;
                }
                ybuf[j] = temp;
            } // End of Y sort
            // Sort the X buffer the same way
            for(i = 1; i <= TPBUFSIZE; i++) {
                temp = xbuf[i];
                j = i;
                while( j && (xbuf[j-1] > temp) ) {
                    xbuf[j] = xbuf[j-1];
                    j = j-1;
                }
                xbuf[j] = temp;
            } // End of X sort
            // Average the middle half of the  Y values and report them
            j = 0;
            for(i = (TPBUFSIZE/4) - 1; i < TPBUFSIZE - TPBUFSIZE/4; i++ ) {
                j += ybuf[i];
            }
            *y = j * (float)2/TPBUFSIZE;    // This is the average
            // Average the middle half of the  X values and report them
            j = 0;
            for(i = (TPBUFSIZE/4) - 1; i < TPBUFSIZE - TPBUFSIZE/4; i++ ) {
                j += xbuf[i];
            }
            *x = j * (float)2/TPBUFSIZE;    // This is the average
            // Tidy up and return
            touchready = 1;
            sample = 0;             // Ready to start on the next set of data samples
        } else {
            // Buffer not yet full, so do not return any results yet
            touchready = 0;
        }
        WriteCommand(INTC2, RA8875_INT_TP);            // reg INTC2: Clear that TP interrupt flag
    } // End of initial if -- data has been read and processed
    else
        touchready = 0;         // Touch Panel "Int" was not set
    return touchready;
}

unsigned char RA8875::TouchPanelReadRaw(loc_t *x, loc_t *y)
{
    unsigned char touchready;

    if( (ReadCommand(INTC2) & RA8875_INT_TP) ) {        // Test for TP Interrupt pending in register INTC2
        *y =  ReadCommand(TPYH) << 2 | ( (ReadCommand(TPXYL) & 0xC) >> 2 );   // D[9:2] from reg TPYH, D[1:0] from reg TPXYL[3:2]
        *x =  ReadCommand(TPXH) << 2 | ( (ReadCommand(TPXYL) & 0x3)      );   // D[9:2] from reg TPXH, D[1:0] from reg TPXYL[1:0]
        WriteCommand(INTC2, RA8875_INT_TP);            // reg INTC2: Clear that TP interrupt flag
        touchready = 1;
    } else
        touchready = 0;
    return touchready;
}

/*   The following section is derived from Carlos E. Vidales.
 *
 *   Copyright (c) 2001, Carlos E. Vidales. All rights reserved.
 *
 *   This sample program was written and put in the public domain 
 *    by Carlos E. Vidales.  The program is provided "as is" 
 *    without warranty of any kind, either expressed or implied.
 *   If you choose to use the program within your own products
 *    you do so at your own risk, and assume the responsibility
 *    for servicing, repairing or correcting the program should
 *    it prove defective in any manner.
 *   You may copy and distribute the program's source code in any 
 *    medium, provided that you also include in each copy an
 *    appropriate copyright notice and disclaimer of warranty.
 *   You may also modify this program and distribute copies of
 *    it provided that you include prominent notices stating 
 *    that you changed the file(s) and the date of any change,
 *    and that you do not charge any royalties or licenses for 
 *    its use.
 * 
 *   This file contains functions that implement calculations 
 *    necessary to obtain calibration factors for a touch screen
 *    that suffers from multiple distortion effects: namely, 
 *    translation, scaling and rotation.
 *
 *   The following set of equations represent a valid display 
 *    point given a corresponding set of touch screen points:
 *
 *                                              /-     -\
 *              /-    -\     /-            -\   |       |
 *              |      |     |              |   |   Xs  |
 *              |  Xd  |     | A    B    C  |   |       |
 *              |      |  =  |              | * |   Ys  |
 *              |  Yd  |     | D    E    F  |   |       |
 *              |      |     |              |   |   1   |
 *              \-    -/     \-            -/   |       |
 *                                              \-     -/
 *    where:
 *           (Xd,Yd) represents the desired display point 
 *                    coordinates,
 *           (Xs,Ys) represents the available touch screen
 *                    coordinates, and the matrix
 *           /-   -\
 *           |A,B,C|
 *           |D,E,F| represents the factors used to translate
 *           \-   -/  the available touch screen point values
 *                    into the corresponding display 
 *                    coordinates.
 *    Note that for practical considerations, the utilities 
 *     within this file do not use the matrix coefficients as
 *     defined above, but instead use the following 
 *     equivalents, since floating point math is not used:
 *            A = An/Divider 
 *            B = Bn/Divider 
 *            C = Cn/Divider 
 *            D = Dn/Divider 
 *            E = En/Divider 
 *            F = Fn/Divider 
 *    The functions provided within this file are:
 *          setCalibrationMatrix() - calculates the set of factors
 *                                    in the above equation, given
 *                                    three sets of test points.
 *               getDisplayPoint() - returns the actual display
 *                                    coordinates, given a set of
 *                                    touch screen coordinates.
 * translateRawScreenCoordinates() - helper function to transform
 *                                    raw screen points into values
 *                                    scaled to the desired display
 *                                    resolution.
 */

/**********************************************************************
 *
 *     Function: setCalibrationMatrix()
 *
 *  Description: Calling this function with valid input data
 *                in the display and screen input arguments 
 *                causes the calibration factors between the
 *                screen and display points to be calculated,
 *                and the output argument - matrixPtr - to be 
 *                populated.
 *
 *               This function needs to be called only when new
 *                calibration factors are desired.
 *               
 *  
 *  Argument(s): displayPtr (input) - Pointer to an array of three 
 *                                     sample, reference points.
 *               screenPtr (input) - Pointer to the array of touch 
 *                                    screen points corresponding 
 *                                    to the reference display points.
 *               matrixPtr (output) - Pointer to the calibration 
 *                                     matrix computed for the set 
 *                                     of points being provided.
 *
 *
 *  From the article text, recall that the matrix coefficients are
 *   resolved to be the following:
 *
 *
 *      Divider =  (Xs0 - Xs2)*(Ys1 - Ys2) - (Xs1 - Xs2)*(Ys0 - Ys2)
 *
 *
 *
 *                 (Xd0 - Xd2)*(Ys1 - Ys2) - (Xd1 - Xd2)*(Ys0 - Ys2)
 *            A = ---------------------------------------------------
 *                                   Divider
 *
 *
 *                 (Xs0 - Xs2)*(Xd1 - Xd2) - (Xd0 - Xd2)*(Xs1 - Xs2)
 *            B = ---------------------------------------------------
 *                                   Divider
 *
 *
 *                 Ys0*(Xs2*Xd1 - Xs1*Xd2) + 
 *                             Ys1*(Xs0*Xd2 - Xs2*Xd0) + 
 *                                           Ys2*(Xs1*Xd0 - Xs0*Xd1)
 *            C = ---------------------------------------------------
 *                                   Divider
 *
 *
 *                 (Yd0 - Yd2)*(Ys1 - Ys2) - (Yd1 - Yd2)*(Ys0 - Ys2)
 *            D = ---------------------------------------------------
 *                                   Divider
 *
 *
 *                 (Xs0 - Xs2)*(Yd1 - Yd2) - (Yd0 - Yd2)*(Xs1 - Xs2)
 *            E = ---------------------------------------------------
 *                                   Divider
 *
 *
 *                 Ys0*(Xs2*Yd1 - Xs1*Yd2) + 
 *                             Ys1*(Xs0*Yd2 - Xs2*Yd0) + 
 *                                           Ys2*(Xs1*Yd0 - Xs0*Yd1)
 *            F = ---------------------------------------------------
 *                                   Divider
 *
 *
 *       Return: OK - the calibration matrix was correctly 
 *                     calculated and its value is in the 
 *                     output argument.
 *               NOT_OK - an error was detected and the 
 *                         function failed to return a valid
 *                         set of matrix values.
 *                        The only time this sample code returns
 *                        NOT_OK is when Divider == 0
 *
 *
 *
 *                 NOTE!    NOTE!    NOTE!
 *
 *  setCalibrationMatrix() and getDisplayPoint() will do fine
 *  for you as they are, provided that your digitizer         
 *  resolution does not exceed 10 bits (1024 values).  Higher
 *  resolutions may cause the integer operations to overflow
 *  and return incorrect values.  If you wish to use these   
 *  functions with digitizer resolutions of 12 bits (4096    
 *  values) you will either have to a) use 64-bit signed     
 *  integer variables and math, or b) judiciously modify the 
 *  operations to scale results by a factor of 2 or even 4.  
 *
 */
RetCode_t RA8875::TouchPanelCalibrate(point_t * displayPtr, point_t * screenPtr, tpMatrix_t * matrixPtr)
{
    RetCode_t retValue = noerror;

    tpMatrix.Divider = ((screenPtr[0].x - screenPtr[2].x) * (screenPtr[1].y - screenPtr[2].y)) -
                       ((screenPtr[1].x - screenPtr[2].x) * (screenPtr[0].y - screenPtr[2].y)) ;

    if( tpMatrix.Divider == 0 )  {
        retValue = bad_parameter;
    }  else   {
        tpMatrix.An = ((displayPtr[0].x - displayPtr[2].x) * (screenPtr[1].y - screenPtr[2].y)) -
                      ((displayPtr[1].x - displayPtr[2].x) * (screenPtr[0].y - screenPtr[2].y)) ;

        tpMatrix.Bn = ((screenPtr[0].x - screenPtr[2].x) * (displayPtr[1].x - displayPtr[2].x)) -
                      ((displayPtr[0].x - displayPtr[2].x) * (screenPtr[1].x - screenPtr[2].x)) ;

        tpMatrix.Cn = (screenPtr[2].x * displayPtr[1].x - screenPtr[1].x * displayPtr[2].x) * screenPtr[0].y +
                      (screenPtr[0].x * displayPtr[2].x - screenPtr[2].x * displayPtr[0].x) * screenPtr[1].y +
                      (screenPtr[1].x * displayPtr[0].x - screenPtr[0].x * displayPtr[1].x) * screenPtr[2].y ;

        tpMatrix.Dn = ((displayPtr[0].y - displayPtr[2].y) * (screenPtr[1].y - screenPtr[2].y)) -
                      ((displayPtr[1].y - displayPtr[2].y) * (screenPtr[0].y - screenPtr[2].y)) ;

        tpMatrix.En = ((screenPtr[0].x - screenPtr[2].x) * (displayPtr[1].y - displayPtr[2].y)) -
                      ((displayPtr[0].y - displayPtr[2].y) * (screenPtr[1].x - screenPtr[2].x)) ;

        tpMatrix.Fn = (screenPtr[2].x * displayPtr[1].y - screenPtr[1].x * displayPtr[2].y) * screenPtr[0].y +
                      (screenPtr[0].x * displayPtr[2].y - screenPtr[2].x * displayPtr[0].y) * screenPtr[1].y +
                      (screenPtr[1].x * displayPtr[0].y - screenPtr[0].x * displayPtr[1].y) * screenPtr[2].y ;
        if (matrixPtr)
            memcpy(matrixPtr, &tpMatrix, sizeof(tpMatrix_t));
    }
    return( retValue ) ;
}

/**********************************************************************
 *
 *     Function: getDisplayPoint()
 *
 *  Description: Given a valid set of calibration factors and a point
 *                value reported by the touch screen, this function
 *                calculates and returns the true (or closest to true)
 *                display point below the spot where the touch screen 
 *                was touched.
 * 
 *
 * 
 *  Argument(s): displayPtr (output) - Pointer to the calculated
 *                                      (true) display point.
 *               screenPtr (input) - Pointer to the reported touch
 *                                    screen point.
 *               matrixPtr (input) - Pointer to calibration factors
 *                                    matrix previously calculated
 *                                    from a call to 
 *                                    setCalibrationMatrix()
 * 
 *
 *  The function simply solves for Xd and Yd by implementing the 
 *   computations required by the translation matrix.  
 * 
 *                                              /-     -\
 *              /-    -\     /-            -\   |       |
 *              |      |     |              |   |   Xs  |
 *              |  Xd  |     | A    B    C  |   |       |
 *              |      |  =  |              | * |   Ys  |
 *              |  Yd  |     | D    E    F  |   |       |
 *              |      |     |              |   |   1   |
 *              \-    -/     \-            -/   |       |
 *                                              \-     -/
 * 
 *  It must be kept brief to avoid consuming CPU cycles.
 *
 *       Return: OK - the display point was correctly calculated 
 *                     and its value is in the output argument.
 *               NOT_OK - an error was detected and the function
 *                         failed to return a valid point.
 *
 *                 NOTE!    NOTE!    NOTE!
 *
 *  setCalibrationMatrix() and getDisplayPoint() will do fine
 *  for you as they are, provided that your digitizer         
 *  resolution does not exceed 10 bits (1024 values).  Higher
 *  resolutions may cause the integer operations to overflow
 *  and return incorrect values.  If you wish to use these   
 *  functions with digitizer resolutions of 12 bits (4096    
 *  values) you will either have to a) use 64-bit signed     
 *  integer variables and math, or b) judiciously modify the 
 *  operations to scale results by a factor of 2 or even 4.  
 *
 */
RetCode_t RA8875::TouchPanelPoint(point_t * TouchPoint)
{
    RetCode_t retValue = no_touch;
    point_t screenpoint = {0, 0};
    
    if (TouchPanelRead(&screenpoint.x, &screenpoint.y)) {
        retValue = touch;
        if (tpMatrix.Divider != 0 ) {
            /* Operation order is important since we are doing integer */
            /*  math. Make sure you add all terms together before      */
            /*  dividing, so that the remainder is not rounded off     */
            /*  prematurely.                                           */
            TouchPoint->x = ( (tpMatrix.An * screenpoint.x) +
                              (tpMatrix.Bn * screenpoint.y) +
                              tpMatrix.Cn
                            ) / tpMatrix.Divider ;

            TouchPoint->y = ( (tpMatrix.Dn * screenpoint.x) +
                              (tpMatrix.En * screenpoint.y) +
                              tpMatrix.Fn
                            ) / tpMatrix.Divider ;
        } else {
            retValue = bad_parameter ;
        }
    }
    return( retValue );
}


RetCode_t RA8875::TouchPanelSetMatrix(tpMatrix_t * matrixPtr)
{
    if (matrixPtr == NULL || matrixPtr->Divider == 0)
        return bad_parameter;
    memcpy(&tpMatrix, matrixPtr, sizeof(tpMatrix_t));
    return noerror;
}

// #### end of touch panel code additions