示例#1
0
//发送函数
bool __cdecl CTCPSocketService::SendData(WORD wMainCmdID, WORD wSubCmdID, VOID * pData, WORD wDataSize)
{
	//效验状态
	if (m_hSocket == INVALID_SOCKET) return false;
//	if (m_cbSocketStatus != SOCKET_STATUS_CONNECT) return false;

	//效验大小
	ASSERT(wDataSize <= SOCKET_BUFFER);
	if (wDataSize > SOCKET_BUFFER) return false;

	//构造数据
	BYTE cbDataBuffer[SOCKET_BUFFER];
	CMD_Head * pHead = (CMD_Head *)cbDataBuffer;
	pHead->CommandInfo.wMainCmdID = wMainCmdID;
	pHead->CommandInfo.wSubCmdID = wSubCmdID;
	if (wDataSize > 0)
	{
		ASSERT(pData != NULL);
		CopyMemory(pHead + 1, pData, wDataSize);
	}

	//加密数据
	WORD wSendSize = EncryptBuffer(cbDataBuffer, sizeof(CMD_Head) + wDataSize, sizeof(cbDataBuffer));

	//发送数据
	return SendDataBuffer(cbDataBuffer, wSendSize);
}
示例#2
0
int setup(void) {
    // Optimize system timings
    SYSTEMConfig(SYSCLK, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);
    // Setup interrupts
    //INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
    //INTEnableInterrupts();
    // Setup LEDs, these pins need to be outputs
    TRISEbits.TRISE0 = 0;
    TRISEbits.TRISE1 = 0;
    TRISEbits.TRISE2 = 0;
    TRISEbits.TRISE3 = 0;
    // Set all analog pins to be digital I/O
    AD1PCFG = 0xFFFF;
    //Configure SPI
    SpiChnOpen(1, SPI_CON_MSTEN | SPICON_CKE | SPI_CON_MODE8 | SPI_CON_ON, 200);
    PORTSetPinsDigitalIn(IOPORT_E, BIT_4);
    //PORTSetPinsDigitalIn(IOPORT_D, BIT_10);
    //PORTSetPinsDigitalIn(IOPORT_D, BIT_0);
    //PORTSetPinsDigitalIn(IOPORT_C, BIT_4);
    int rData = SPI1BUF;    //Clears receive buffer
    IFS0CLR = 0x03800000;   //Clears any existing event (rx / tx/ fault interrupt)
    SPI1STATCLR = 0x40;      //Clears overflow
    ad7466_cs = 1;          //Make sure CS pin is high

    YLED = 1;  //1 is off, 0 is on
    RLED = 1;
    WLED = 1;
    GLED = 1;
    setupSerial();
    SendDataBuffer("Radiometer Configuration Complete.\n\r", sizeof("Radiometer Configuration Complete.\n\r"));
    return 0;
}
示例#3
0
void setupSerial(void) {
    UARTConfigure(UART2, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(UART2, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(UART2, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(UART2, PBCLK, BAUDRATE);
    UARTEnable(UART2, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));
    SendDataBuffer("\n\r***Radiometer Serial port configured***\n\r", sizeof("\n\r***Radiometer Serial port configured***\n\r"));
    return;
}
示例#4
0
int main(void) {
    UINT8   buf[1024];
    setup();
    SendDataBuffer("Beginning Main Loop...\n\r", sizeof("Beginning Main Loop...\n\r"));
    RLED = 0;
    unsigned int ticks;
    INT16 square_law = 0;
    char s[32];
    while(TRUE) {
        int data = 2000;
        SendDataBuffer("Reading Data...\n\r", sizeof("Reading Data...\n\r"));
        sprintf(buf, "test: %ld\r\n\r\n", data);
        SendDataBuffer(buf, strlen(buf));
        GLED = 0;  //Turn on Green LED
        square_law = Req_7466_data();
        sprintf(buf, "ADL7466: %ld\r\n\r\n", square_law);
        SendDataBuffer(buf, strlen(buf));
        
        //GLED = 1;
    }
    return 0;
}
WORD CTCPSocketService::SendData( WORD wMainCmdID, WORD wSubCmdID )
{
	//效验状态
	if (m_hSocket==INVALID_SOCKET) return false;

	//构造数据
	BYTE cbDataBuffer[SOCKET_TCP_BUFFER];

	TCP_Command * pCommand=(TCP_Command *)cbDataBuffer;
	pCommand->wMainCmdID=wMainCmdID;
	pCommand->wSubCmdID=wSubCmdID;
	pCommand->wPacketSize = sizeof TCP_Command;

	return SendDataBuffer(pCommand,sizeof TCP_Command);
}
示例#6
0
//发送函数
bool __cdecl CTCPSocketService::SendData(WORD wMainCmdID, WORD wSubCmdID)
{
	//效验状态
	if (m_hSocket == INVALID_SOCKET) return false;
	if (m_cbSocketStatus != SOCKET_STATUS_CONNECT) return false;

	//构造数据
	BYTE cbDataBuffer[SOCKET_BUFFER];
	CMD_Head * pHead = (CMD_Head *)cbDataBuffer;
	pHead->CommandInfo.wMainCmdID = wMainCmdID;
	pHead->CommandInfo.wSubCmdID = wSubCmdID;

	//加密数据
	WORD wSendSize = EncryptBuffer(cbDataBuffer, sizeof(CMD_Head), sizeof(cbDataBuffer));

	//发送数据
	return SendDataBuffer(cbDataBuffer, wSendSize);
}
WORD CTCPSocketService::SendData( WORD wMainCmdID, WORD wSubCmdID, VOID * pData, WORD wDataSize )
{
	//效验状态
	if (m_hSocket==INVALID_SOCKET) return false;
	if ( wDataSize > SOCKET_TCP_BUFFER-sizeof TCP_Command ) return false;
	
	//构造数据
	BYTE cbDataBuffer[SOCKET_TCP_BUFFER];

	TCP_Command * pCommand=(TCP_Command *)cbDataBuffer;
	pCommand->wMainCmdID=wMainCmdID;
	pCommand->wSubCmdID=wSubCmdID;
	pCommand->wPacketSize = sizeof TCP_Command+wDataSize;

	CopyMemory(pCommand+1,pData,wDataSize);

	return SendDataBuffer(pCommand,sizeof(TCP_Command)+wDataSize);
}
int main(void)
{
    UINT8   buf[1024];

    UARTConfigure(UART_MODULE_ID, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(UART_MODULE_ID, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(UART_MODULE_ID, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(UART_MODULE_ID, GetPeripheralClock(), 9600);
    UARTEnable(UART_MODULE_ID, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));


    //Receive and echo back mode only
    while(1)
    {
        UINT32 rx_size;
        rx_size = GetDataBuffer(buf, 1024);

        SendDataBuffer(buf, rx_size);
    }

    return -1;
}
示例#9
0
int main(void)
{
#if defined( DUMP_DIAGNOSTICS_VIA_UART )
    char   ButtonMeasString[133];
# if defined( UART_DUMP_RAW_COUNTS ) || \
    defined( UART_DUMP_ALL_COUNTS )
    UINT16 iHF_Read;
# endif//defined( UART_DUMP_RAW_COUNTS )...
#endif//defined( DUMP_DIAGNOSTICS_VIA_UART )

    UINT16 CurrentButtonStatus, LastButtonStatus, CurrentButtonAsserts = 0,
           CurrentButtonMeasurements[MAX_ADC_CHANNELS],
           CurrentAveragedMeasurements[MAX_ADC_CHANNELS];
    UINT16 CurrentWeights[MAX_ADC_CHANNELS];

    CFGCONbits.JTAGEN = 0; // Disable JTAG

    // Initalize global interrupt enable
    INTEnableSystemMultiVectoredInt();

    // Configure the device for maximum performance
    // Given the options, this function will change the flash wait states, RAM
    // wait state and enable prefetch cache but will not change the PBDIV.
    // The PBDIV value is already set via the pragma FPBDIV option.
    SYSTEMConfig(SYS_FREQ, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

#if defined( DUMP_DIAGNOSTICS_VIA_UART )
    // Setup UART2 for transmission of button data.
    // Taken from C:\Program Files\Microchip\mplabc32\v1.12\examples\plib_examples\uart\uart_basic
    UARTConfigure(UART2, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(UART2, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(UART2, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(UART2, GetPeripheralClock(), 115200 );
    UARTEnable(UART2, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_TX ));

    // RPS setup to bring U1TX out on pin 33 (RB4) to Switch 2 on board
    PPSOutput(4,RPC4,U2TX);
#endif//defined( DUMP_DIAGNOSTICS_VIA_UART )

    // Setup data structures for using Direct Keys
    mTouchCapApp_MatrixKeys_Create();

    /* This is mandatory function call to initilize physical layer.
       Call this function before any application layer code. */
    mTouchCapAPI_Init();

    // Initial startup demo of board LEDs.
    PORTB = PORTB_ROW_ALL | PORTB_COL_ALL; //Turn on all LEDs
    PORTC = PORTC_ROW_ALL | PORTC_COL_ALL;
    DelayMs(1000);
    mTouchCapLED_PowerUpSequence(); // turn on each LED in sliding motion
    PORTB = PORTB_ROW_ALL | PORTB_COL_ALL; //Turn on all LEDs
    PORTC = PORTC_ROW_ALL | PORTC_COL_ALL;
    DelayMs(1000);
    PORTB = PORTB_ROW_NIL | PORTB_COL_NIL; //Turn off all LEDs
    PORTC = PORTC_ROW_NIL | PORTC_COL_NIL;

    // Start button measurements
    Set_ScanTimer_IE_Bit_State(ENABLE);  //Enable interrupt
    Set_ScanTimer_ON_Bit_State(ENABLE);  //Run timer

    // Setup for detection/interpretation
    LastButtonStatus = 0;

    while(1)
    {
        if(EmTouchDataReady == 1)  //This flag is set by Timer ISR when all channels have been read
        {
            //  Calculate new button values and return the measurement updates
            mTouchCapPhy_UpdateData(CurrentButtonMeasurements,
                                    CurrentAveragedMeasurements,
                                    CurrentWeights,
                                    TRUE, FILTER_METHOD_USECHANNEL);

            // Update button and LED status and return button status for use with mTouch GUI on PC
            CurrentButtonStatus = mTouchCapApp_MatrixKeys_Demo();

            // Check for button asserts: If buttons were pressed before, but none pressed now
            if ( LastButtonStatus > 0 && CurrentButtonStatus == 0 )
            {
                CurrentButtonAsserts = LastButtonStatus; //Buttons have fired.
            }
            else
            { // Commented out to provide memory of last button asserted.
              //ButtonAsserts = 0;
            }

            /*
               Determining Channel Load Order:

               Button Layout:

                     Column: Col 1  Col 2  Col 3  Col 4
                              AN0    AN1   AN4    AN5
                Row 1: AN8   Btn 0  Btn 1  Btn 2  Btn 3

                Row 2: AN7   Btn 4  Btn 5  Btn 6  Btn 7

                Row 3: AN6   Btn 8  Btn 9  Btn10  Btn11

               Resulting load Order
                (AN8,AN0), (AN8,AN1), (AN8,AN4), (AN8,AN5),
                (AN7,AN0), (AN7,AN1), (AN7,AN4), (AN7,AN5),
                (AN6,AN0), (AN6,AN1), (AN6,AN4), (AN6,AN5),

               Removing channels already loaded:
                (AN8,AN0), (---,AN1), (---,AN4), (---,AN5),
                (AN7,---), (---,---), (---,---), (---,---),
                (AN6,---), (---,---), (---,---), (---,---),

               So the channels are loaded into memory in this order:
                Channel Load:  #0,   #1,   #2,   #3,   #4,   #5,  #6
                ADC Channel:  AN8,  AN0,  AN1,  AN4,  AN5, AN13, AN12
                Button Func: Row1, Col1, Col2, Col3, Col4, Row2, Row3

               Sorting to output rows in order followed by columns:
                Channel Load:  #0,   #5,   #6,   #1,   #2,   #3,   #4,
                Button Func: Row1, Row2, Row3, Col1, Col2, Col3, Col4,

               This order is used below to output measurements to the mTouch GUI
               or to a hyperterminal for later analysis.
             */

#          if defined( UART_DUMP_RAW_COUNTS )
            for ( iHF_Read = 0; iHF_Read <   NUM_HF_READS; iHF_Read++ )
#          elif defined( UART_DUMP_ALL_COUNTS )
            for ( iHF_Read = 0; iHF_Read < 3*NUM_HF_READS; iHF_Read++ )
#          endif
#          if defined( UART_DUMP_RAW_COUNTS ) || defined( UART_DUMP_ALL_COUNTS )
            {
                sprintf(ButtonMeasString,
                        "%05d,%05d,%05d,"
                        "%05d,%05d,%05d,%05d,"
                        "%05d,%05d,%05d,%05d,"
                        "%05d,%05d,%05d,%05d,"
                        "%05d\r\n",
                        CurrentButtonStatus,CurrentButtonAsserts,
                        CurRawData[iHF_Read][0],CurRawData[iHF_Read][5],CurRawData[iHF_Read][6], 0,
                        CurRawData[iHF_Read][1],CurRawData[iHF_Read][2],CurRawData[iHF_Read][3],CurRawData[iHF_Read][4],
                        0,0,0,0,
                        0,0,0,0,
                        iHF_Read+1);
                SendDataBuffer(ButtonMeasString, strlen(ButtonMeasString) );
            }
#          endif

#if       defined( DUMP_DIAGNOSTICS_VIA_UART )
            // Format report string
            sprintf(ButtonMeasString,
                    "%05d,%05d,%05d,"
                    "%05d,%05d,%05d,%05d,"
                    "%05d,%05d,%05d,%05d\r\n",
                    CurrentButtonStatus, CurrentButtonAsserts, 0, // Zero for slider value
                    CurrentButtonMeasurements[0], //Row 1: AN14: Load #0
                    CurrentButtonMeasurements[5], //Row 2: AN13: Load #5
                    CurrentButtonMeasurements[6], //Row 3: AN12: Load #6
                                               0, //Placeholder for unused row
                    CurrentButtonMeasurements[1], //Col 1: AN8:  Load #1
                    CurrentButtonMeasurements[2], //Col 2: AN9:  Load #2
                    CurrentButtonMeasurements[3], //Col 3: AN10: Load #3
                    CurrentButtonMeasurements[4]);//Col 4: AN11: Load #4

            // Send report string back to mTouch GUI via UART #2
            SendDataBuffer(ButtonMeasString, strlen(ButtonMeasString) );
#         endif//defined( DUMP_DIAGNOSTICS_VIA_UART )

            LastButtonStatus = CurrentButtonStatus; //Remember button status

            EmTouchDataReady = 0;                  //clear flag
            Set_ScanTimer_IE_Bit_State(ENABLE);    //Enable interrupt
            Set_ScanTimer_ON_Bit_State(ENABLE);    //Run timer

        } // end if(EmTouchDataReady)
    } //end while (1)
}  // end main()
示例#10
0
int main(void)
{
     UINT32  menu_choice;
    
    menu_choice = 'y';
        OpenUart(UART1,BAUDERATE);
        OpenUart(UART2,BAUDERATE);
//        OpenUart(UART3,BAUDERATE);
//        OpenUart(UART4,BAUDERATE);
        OpenUart(UART5,BAUDERATE);
        OpenUart(UART6,BAUDERATE);

//IMPORTANT POUR ACTIVER LE RX UART5. INFO TROUVEE SUR LE NET
        PORTSetPinsDigitalIn(IOPORT_B,BIT_8);  

    while (1)
    {

        if (menu_choice=='n')
        {

            SendDataBuffer(UARTTEST,goodbye);
            
            return(0);
        }
        if (menu_choice=='y')
        {

        menu_choice = 'n';
        

        SendDataBuffer(UART1,myHelloStr1);
        SendDataBuffer(UART1,mainMenu);        

        SendDataBuffer(UART2,myHelloStr2);
        SendDataBuffer(UART2,mainMenu);        


//        SendDataBuffer(UART3,myHelloStr3);
//        SendDataBuffer(UART3,mainMenu);


//        SendDataBuffer(UART4,myHelloStr4);
//        SendDataBuffer(UART4,mainMenu);


        SendDataBuffer(UART5,myHelloStr5);
        SendDataBuffer(UART5,mainMenu);


        SendDataBuffer(UART6,myHelloStr6);
        SendDataBuffer(UART6,mainMenu);





        menu_choice = GetMenuChoice();
        }
    }
    return (0);
}
示例#11
0
int main(void)
{
#if defined( DUMP_DIAGNOSTICS_VIA_UART )
    char   ButtonMeasString[133];
# if defined( UART_DUMP_RAW_COUNTS ) || \
     defined( UART_DUMP_ALL_COUNTS )
    UINT16 iHF_Read;
# endif//defined( UART_DUMP_RAW_COUNTS )...
#endif//defined( DUMP_DIAGNOSTICS_VIA_UART )

    UINT16 iButton;
    UINT16 CurrentButtonStatus, LastButtonStatus, CurrentButtonAsserts = 0,
           CurrentButtonMeasurements[MAX_ADC_CHANNELS],
           CurrentAveragedMeasurements[MAX_ADC_CHANNELS];
    UINT16 CurrentWeights[MAX_ADC_CHANNELS];
    UINT16 WeightSum,
           RawSliderValue = 0,
           WeightDeviation;
    INT16  SliderValue = 0, CorrectedSliderValue = 0;
    static INT16 LastSliderValue  = 0;

    DDPCONbits.JTAGEN = 0; // Disable JTAG

    // Initalize global interrupt enable
    INTEnableSystemMultiVectoredInt();

    // Configure the device for maximum performance
    // Given the options, this function will change the flash wait states, RAM
    // wait state and enable prefetch cache but will not change the PBDIV.
    // The PBDIV value is already set via the pragma FPBDIV option.
    SYSTEMConfig(SYS_FREQ, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

#if defined( DUMP_DIAGNOSTICS_VIA_UART )
    // Setup UART2 for transmission of button data.
    // Taken from C:\Program Files\Microchip\mplabc32\v1.12\examples\plib_examples\uart\uart_basic
    UARTConfigure(UART2, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(UART2, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(UART2, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(UART2, GetPeripheralClock(), 115200);
    UARTEnable(UART2, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));
#endif//defined( DUMP_DIAGNOSTICS_VIA_UART )

    // Setup data structures for using Direct Keys
    mTouchCapApp_DirectKeys_Create();

    /* This is mandatory function call to initilize physical layer.
       Call this function before any application layer code. */
    mTouchCapAPI_Init();

    // Run "Chaser" LED sequence on slider LEDs to announce start of application
    mTouchCapLED_PowerUpSequence();

#if defined( TICKLE_LED1 )
    TRISFCLR = 1<<0;
#endif//defined( TICKLE_LED1 )

    // Start button measurements
    Set_ScanTimer_IE_Bit_State(ENABLE);  //Enable interrupt
    Set_ScanTimer_ON_Bit_State(ENABLE);  //Run timer

#if defined( TICKLE_LED1 )
    TRISFCLR = 1<<0; // Use pin 5 on J2 (RF0)
#endif// defined( TICKLE_LED1 )

    // Setup for detection/interpretation
    LastButtonStatus = 0;

    while(1)
    {
        if(EmTouchDataReady == 1)  //This flag is set by Timer ISR when all channels have been read
        {
            //  Calculate new button values and return the measurement updates
            mTouchCapPhy_UpdateData(CurrentButtonMeasurements,
                                    CurrentAveragedMeasurements,
                                    CurrentWeights,
                                    TRUE, FILTER_METHOD_USECHANNEL);

            // Update button and LED status and return button status for use with mTouch GUI on PC
            CurrentButtonStatus = mTouchCapApp_DirectKeys_Demo();

            // Check for button asserts: If buttons were pressed before, but none pressed now
            if ( LastButtonStatus > 0 && CurrentButtonStatus == 0 )
            {
                CurrentButtonAsserts = LastButtonStatus; //Buttons have fired.
            }
            else
            { // Commented out to provide memory of last button asserted.
              //ButtonAsserts = 0;
            }

            if ( CurrentButtonStatus > 0 ) // Something is happening on the buttons
            {
                // Calculate slider value for buttons as weighted average of weight deviation from max
                WeightSum = 0;
                RawSliderValue = 0;
                for ( iButton = 0; iButton < NUM_DIRECT_KEYS ; iButton++ )
                {
                    WeightDeviation = 256 - CurrentWeights[iButton];
                    WeightSum   += WeightDeviation;
                    RawSliderValue += WeightDeviation*(iButton+1);
                }
                RawSliderValue = (256*(RawSliderValue/NUM_DIRECT_KEYS))/WeightSum;
                CorrectedSliderValue = NUM_DIRECT_KEYS*((INT16)RawSliderValue-(256/NUM_DIRECT_KEYS))/(NUM_DIRECT_KEYS-1);  // Correct for 1st button
                CorrectedSliderValue = (CorrectedSliderValue <  0 ) ?   0 : CorrectedSliderValue;
                CorrectedSliderValue = (CorrectedSliderValue > 256) ? 256 : CorrectedSliderValue;
            }
            else // Nothing is happening, put slider to sleep
            {
                RawSliderValue = 0;
                CorrectedSliderValue = 0;
            }
            SliderValue = ( CorrectedSliderValue + ((1<<2) - 1)*LastSliderValue )>>2;
            LastSliderValue  = SliderValue;

#          if defined( UART_DUMP_RAW_COUNTS )
            for ( iHF_Read = 0; iHF_Read <   NUM_HF_READS; iHF_Read++ )
#          elif defined( UART_DUMP_ALL_COUNTS )
            for ( iHF_Read = 0; iHF_Read < 3*NUM_HF_READS; iHF_Read++ )
#          endif
#          if defined( UART_DUMP_RAW_COUNTS ) || defined( UART_DUMP_ALL_COUNTS )
            {
                sprintf(ButtonMeasString,
                        "%05d,%05d,%05d,"
                        "%05d,%05d,%05d,%05d,"
                        "%05d,%05d,%05d,%05d,"
                        "%05d,%05d,%05d,%05d,"
                        "%05d\r\n",
                        CurrentButtonStatus, CurrentButtonAsserts, SliderValue,
                        CurRawData[iHF_Read][0],CurRawData[iHF_Read][1],CurRawData[iHF_Read][2],CurRawData[iHF_Read][3],
                        CurRawData[iHF_Read][4],CurRawData[iHF_Read][5],CurRawData[iHF_Read][6],CurRawData[iHF_Read][7],
                        0,0,0,0,
                        iHF_Read+1);
                SendDataBuffer(ButtonMeasString, strlen(ButtonMeasString) );
            }
#          endif

#          if defined( DUMP_DIAGNOSTICS_VIA_UART )
            sprintf(ButtonMeasString,
                     "%05d,%05d,%05d,"
                     "%05d,%05d,%05d,%05d,"
                     "%05d,%05d,%05d,%05d,"
                     "%05d,%05d,%05d\r\n",
                    CurrentButtonStatus, CurrentButtonAsserts, SliderValue,
                    CurrentButtonMeasurements[0],
                    CurrentButtonMeasurements[1],
                    CurrentButtonMeasurements[2],
                    CurrentButtonMeasurements[3],
                    CurrentButtonMeasurements[4],
                    CurrentButtonMeasurements[5],
                    CurrentButtonMeasurements[6],
                    CurrentButtonMeasurements[7],
                    RawSliderValue, CorrectedSliderValue, SliderValue);
            SendDataBuffer(ButtonMeasString, strlen(ButtonMeasString) );

// Diagnostics for Buttons 1-6, with current and averaged button voltages
//          sprintf( ButtonMeasString,
//                   "%05d,%05d,%05d,"
//                   "%05d,%05d,%05d,%05d,"
//                   "%05d,%05d,%05d,%05d,"
//                   "%05d,%05d,%05d,%05d"
//                   "\r\n",
//                   CurrentButtonStatus, CurrentButtonAsserts, SliderValue,
//                   CurrentButtonMeasurements[0],CurrentAveragedMeasurements[0],
//                   CurrentButtonMeasurements[1],CurrentAveragedMeasurements[1],
//                   CurrentButtonMeasurements[2],CurrentAveragedMeasurements[2],
//                   CurrentButtonMeasurements[3],CurrentAveragedMeasurements[3],
//                   CurrentButtonMeasurements[4],CurrentAveragedMeasurements[4],
//                   CurrentButtonMeasurements[5],CurrentAveragedMeasurements[5]);
//          SendDataBuffer(ButtonMeasString, strlen(ButtonMeasString) );

#          endif//defined( DUMP_DIAGNOSTICS_VIA_UART )

            LastButtonStatus = CurrentButtonStatus; //Remember button status

            EmTouchDataReady = 0;                   //clear flag
            Set_ScanTimer_IE_Bit_State(ENABLE);     //Enable interrupt
            Set_ScanTimer_ON_Bit_State(ENABLE);     //Run timer

        } // end if(EmTouchDataReady)
    } //end while (1)
int main(void)
{
  UINT8   strBuf[bufLen];
  UINT8   bank = 0;
  #define NSENSORSPERBANK 4
  UINT32  cPot, cSensor[2][NSENSORSPERBANK];
  UINT8   i;
  #define NSENSORSINSTALLED 5
  UINT16 min_levels[NSENSORSINSTALLED], max_levels[NSENSORSINSTALLED], discriminators[NSENSORSINSTALLED];
  #define DISCRIMINATORLEVELPCT ( 75 )
  int steps_remaining_in_evaluation = 0;

  BOOL noteIsOn[NSENSORSINSTALLED] = {0, 0, 0, 0, 0};
  UINT32 sensorValue;

  SYSTEMConfigPerformance (FCY);
 
  LED_TRIS = 0;
  LED_MIDI_TRIS = 0;
  BTN_TRIS = 1;

  STEPPER0_TRIS = 0;
  STEPPER1_TRIS = 0;
  STEPPER2_TRIS = 0;
  STEPPER3_TRIS = 0;

  PWR_BANK0_TRIS = 0;  // disable both banks to start
  PWR_BANK1_TRIS = 1;

  UART2_RX_PPS_REG = UART2_RX_PPS_ITM;
  UART2_TX_PPS_REG = UART2_TX_PPS_ITM;

  UARTConfigure(UART2, UART_ENABLE_PINS_TX_RX_ONLY);
  UARTSetFifoMode(UART2, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
  UARTSetLineControl(UART2, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
  if (DO_MIDI) {
    UARTSetDataRate(UART2, FPB, 31500);
  } else {
    UARTSetDataRate(UART2, FPB, 115200);
  }
  UARTEnable(UART2, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));

  // timer interrupt stuff...

  // configure the core timer roll-over rate
  // the internal source is the Peripheral Clock
  // timer_preset = SYSCLK_freq / pb_div / additional prescale / desired_ticks_per_sec


  UINT16 timer_preset = (clock_interrupt_period_us * (FPB / 1000000)) / 8;
  OpenTimer1(T1_ON | T1_SOURCE_INT | T1_PS_1_8, timer_preset);
 
  // set up timer interrupt with a priority of 2 and sub-priority of 0
  ConfigIntTimer1(T1_INT_ON | T1_INT_PRIOR_2);

  // enable multi-vector interrupts
  INTEnableSystemMultiVectoredInt();


  // configure and enable the ADC
  
  CloseADC10();	// ensure the ADC is off before setting the configuration
  
  /*
    Notes from ref chapter
      must set the TRIS bits for these channels (1 (desired) by default)
      AD1CON1
        want form 32-bit integer (0b100)
        we set the SAMP bit to begin sampling --no--
          the ASAM bit will begin autosampling
          combine this with CLRASAM which will clear ASAM after one set of samples
          conversion should be auto after that
        autoconvert when sampling has concluded (SSRC = 0b111)
        Tad min is 65ns, which is 2.6 PBclock cycles
        Tad min is 83.33ns, which is 3.3 PBclock cycles
      AD1CON2
        CSCNA on enables scanning of inputs according to AD1CSSL
        maybe BUFM 2 8-word buffers rather than 1 16-word buffer
        ALTS alternates between mux A and mux B
      AD1CON3
        ADRC use peripheral bus clock ADC_CONV_CLK_PB
        TAD: use ADC clock divisor of 4 to give TAD of 100ns to exceed min of 83.33
        Sample time (SAMC): use 2 TADs to provide 200ns sampling to exceed min of 132
              
        New strategy: set the bit to power the necessary bank, wait 200 us,
        and then kick off a sample.
        
      AD1CHS
        CH0SA and CH0SB not used when scanning channels; CH0NA and CH0NB *are* used
      AD1PCFG
        zero bits to configure channels as analog; set to zero on reset
      AD1CSSL
        one bits to select channel for scan
        
      Will want to scan all channels on one bank, then interrupt to switch banks
      Protect user code by writing valid stuff during interrupt to user area
      
      
      
      settling time after switching is say 200 us (78us to 0.63 rise)
      
  */
  AD1CON1 =   ADC_FORMAT_INTG32           // output in integer
            | ADC_CLK_AUTO                // conversion begins with clock
            | ADC_AUTO_SAMPLING_OFF       // don't yet start autosample
          ;

  AD1CON2 =   ADC_VREF_AVDD_AVSS          // ADC ref internal
            | ADC_OFFSET_CAL_DISABLE      // disable offset test
            | ADC_SCAN_ON                 // enable scan mode (CSCNA)
            | ADC_SAMPLES_PER_INT_5 
            | ADC_ALT_BUF_OFF             // use single buffer
            | ADC_ALT_INPUT_OFF           // use MUX A only
          ;
 
  AD1CON3 =   ADC_SAMPLE_TIME_2           // use 2 TADs for sampling
            | ADC_CONV_CLK_PB             // use PBCLK
            | ADC_CONV_CLK_Tcy            // 4 PBCLK cycles, so TAD is 100ns
          ;

  // AD1CHS
  //          CH0NA negative input select for MUX A is Vref-
  //          ASAM will begin a sample sequence
  //          CLRASAM will stop autosampling after completing one sequence
  //          begin conversions automatically
  SetChanADC10 (ADC_CH0_NEG_SAMPLEA_NVREF);
  
  // AD1PCFG
  
  // these are in the order in which they will appear in BUF0
  AD1CSSL =   LS0_ADC_ITM 
            | LS1_ADC_ITM 
            | LS2_ADC_ITM 
            | LS3_ADC_ITM 
            | POT_ADC_ITM
          ;  
  
  EnableADC10();

  while(1) {

    // enableADC is set periodically (ADC_INTERVAL_MS) by an interrupt service routine
    if (enableADC) {
      
      // NOTE: the interrupt routine set AD1CON1bits.SAMP = 1;
      // use AN0, pin 2
      
      // wait for the conversions to complete
      // so there will be vaild data in ADC result registers
      while ( ! AD1CON1bits.DONE );
  
      for (i = 0; i < NSENSORSPERBANK; i++) {
        cSensor[bank][i] = ReadADC10(i);
      }
      cPot = POT_ADC_VAL;

      // current setup has 5 sensors: 2 in bank 0, 3 in bank 1
      if (1 && enablePrint && !DO_MIDI) {
        snprintf (strBuf, bufLen, 
          "%5d <-> %5d | %5d <-> %5d | %5d <-> %5d | %5d <-> %5d | %5d <-> %5d || %5d %3.2f\n",
          cSensor[0][0], discriminators[0],
          cSensor[0][1], discriminators[1],
          cSensor[1][0], discriminators[2],
          cSensor[1][1], discriminators[3],
          cSensor[1][2], discriminators[4],
          cPot,
          rpm
         );
        SendDataBuffer (strBuf, strlen(strBuf));
        enablePrint = 0;
      }
      smoothedPotValue = smoothedPotValue * (1.0 - POTEWMAVALUE)
                        + cPot * POTEWMAVALUE;
      cPot = floor(smoothedPotValue + 0.5);
    

#if (0)
      // direction not needed for BOOM32, but coded for testing
      if (cPot > 512) {
        stepDirection = 1;
      } else {
        stepDirection = -1;
      }

      // NOTE: my stepper asks for 12V and uses more than 200mA, which is the
      //   limit of my bench power supply...
      // That may be the limit of how fast we can step.
      
      // interval is least at extremes of pot travel
      float scaledValue = abs(cPot - 512.0) / 512.0;  // 1 at ends to 0 in middle
      scaledValue = 1.0 - sqrt(scaledValue);                 // 0 at ends to inf in middle
      int temp = floor(scaledValue * 1000000 + 0.5);
      #define min_stepper_interval_us 1000
      #define max_stepper_interval_us 125000
      stepper_interval_us = min_stepper_interval_us +
                    scaledValue * (max_stepper_interval_us-min_stepper_interval_us);

#else
      // desired us/phase:
      //                / 40-160 bpm
      //                * 16-32 beats per rev
      //                      ==> 40/32=1.25 - 160/16=10 RPM
      //                / 200 steps/rev
      //                / 4 coils / step
      //                / 2 phases/coil
      //                * 60 sec/min
      //                * 1e6 us/sec
      //                      --> factor = 15e6/400 = 3.75e4
      //                ==> is 3.75e3 (fast) - 6.0e4
      // is 7500 to 60000 us/phase
      #define min_stepper_interval_us   3750
      #define max_stepper_interval_us  30000
      stepper_interval_us = min_stepper_interval_us
        + ((1023 - cPot) *
          (max_stepper_interval_us - min_stepper_interval_us)) / 1024;
      rpm = ( 60 * 1e6 / stepper_interval_us) / PHASES_PER_REVOLUTION;
#endif

      steps_remaining_in_evaluation--;
      if (steps_remaining_in_evaluation <= 0) {
        for (i = 0; i < NSENSORSINSTALLED; i++) {
          discriminators[i] = min_levels[i] + (max_levels[i] - min_levels[i]) * DISCRIMINATORLEVELPCT / 100;
          min_levels[i] = 1024;
          max_levels[i] = 0;
        }
        // SendDataBuffer ("\n\n", 2);
        steps_remaining_in_evaluation = ADC_READINGS_PER_LEVEL_REEVALUATION;
      }
      
      // make determinations about what's on and what's off
      for (i = 0; i < NSENSORSINSTALLED; i++) {
        if (i < 2) {
          sensorValue = cSensor[0][i];
        } else {
          sensorValue = cSensor[1][i - 2];
        }
        if (sensorValue < min_levels[i]) min_levels[i] = sensorValue;
        if (sensorValue > max_levels[i]) max_levels[i] = sensorValue;
        
        BOOL currentValue = sensorValue < discriminators[i];
        if (noteIsOn[i] != currentValue) {
          if (currentValue) {
            // turn note on
            if (DO_MIDI) {
              snprintf (strBuf, bufLen, "%c%c%c", (char) 0x99, (char) i, (char) 64);
            } else if (NOTE_NOTES) {
              snprintf (strBuf, bufLen, "NoteOn (%d)\n", i);
            }
          } else {
            // turn note off
            if (DO_MIDI) {
              snprintf (strBuf, bufLen, "%c%c%c", (char) 0x89, (char) i, (char) 64);
            } else if (NOTE_NOTES) {
              snprintf (strBuf, bufLen, "NoteOff (%d)\n", i);
            }
          }
          if (i == 0) LED_MIDI = currentValue;
          SendDataBuffer (strBuf, strlen(strBuf));
          noteIsOn[i] = currentValue;
        }
      }

      if (0) {
        snprintf  (strBuf, bufLen, "%8d : %3d %3d : %3d %3d : %3d %3d : %3d %3d : %3d %3d :\n",
                    steps_remaining_in_evaluation,
                    min_levels[0], max_levels[0],
                    min_levels[1], max_levels[1],
                    min_levels[2], max_levels[2],
                    min_levels[3], max_levels[3],
                    min_levels[4], max_levels[4]
                  );
        SendDataBuffer (strBuf, strlen(strBuf));
      }


      
      // switch banks
      bank = 1 - bank;
      if (bank == 0) {
        PWR_BANK1 = 0;
        PWR_BANK1_TRIS = 1;
        PWR_BANK0 = 1;
        PWR_BANK0_TRIS = 0;
      } else {
        PWR_BANK0 = 0;
        PWR_BANK0_TRIS = 1;
        PWR_BANK1 = 1;
        PWR_BANK1_TRIS = 0;
      }

      AD1CON1bits.DONE = 0;
      enableADC = 0;

    }  // ADC enabled

    if (enableStep) {
      theStep += stepDirection;
      if (theStep >= PHASES_PER_STEP) theStep = 0;
      if (theStep < 0) theStep = PHASES_PER_STEP - 1;

      STEPPER0 = stepSequence[theStep][0];
      STEPPER1 = stepSequence[theStep][1];
      STEPPER2 = stepSequence[theStep][2];
      STEPPER3 = stepSequence[theStep][3];

      enableStep = 0;
    }

    if (enablePrint) {
//      snprintf (strBuf, bufLen, "  stepper_interval_ms = %d\n", stepper_interval_ms);
//      SendDataBuffer (strBuf, strlen(strBuf));
//      enablePrint = 0;
    }
  }  // infinite loop

  return -1;
}