// // Cmd_cat - This function implements the "cat" command. It reads the contents // of a file and prints it to the console. This should only be used // on text files. If it is used on a binary file, then a bunch of // garbage is likely to printed on the console. // int Cmd_cat(int argc, char *argv[]) { FRESULT fresult; unsigned short usBytesRead; // // First, check to make sure that the current path (CWD), plus // the file name, plus a separator and trailing null, will all // fit in the temporary buffer that will be used to hold the // file name. The file name must be fully specified, with path, // to FatFs. // if(strlen(g_cCwdBuf) + strlen(argv[1]) + 1 + 1 > sizeof(g_cTmpBuf)) { UARTprintf("Resulting path name is too long\n"); return(0); } // // Copy the current path to the temporary buffer so it can be manipulated. // strcpy(g_cTmpBuf, g_cCwdBuf); // // If not already at the root level, then append a separator. // if(strcmp("/", g_cCwdBuf)) { strcat(g_cTmpBuf, "/"); } // // Now finally, append the file name to result in a fully specified file. // strcat(g_cTmpBuf, argv[1]); // // Open the file for reading. // fresult = f_open(&g_sFileObject, g_cTmpBuf, FA_READ); // // If there was some problem opening the file, then return // an error. // if(fresult != FR_OK) { return(fresult); } // // Enter a loop to repeatedly read data from the file and display it, // until the end of the file is reached. // do { // // Read a block of data from the file. Read as much as can fit // in the temporary buffer, including a space for the trailing null. // fresult = f_read(&g_sFileObject, g_cTmpBuf, sizeof(g_cTmpBuf) - 1, &usBytesRead); // // If there was an error reading, then print a newline and // return the error to the user. // if(fresult != FR_OK) { UARTprintf("\n"); return(fresult); } // // Null terminate the last block that was read to make it a // null terminated string that can be used with printf. // g_cTmpBuf[usBytesRead] = 0; // // Print the last chunk of the file that was received. // UARTprintf("%s", g_cTmpBuf); // // Continue reading until less than the full number of bytes are // read. That means the end of the buffer was reached. // } while(usBytesRead == sizeof(g_cTmpBuf) - 1); // // Return success. // return(0); }
//***************************************************************************** // // This is the main loop that runs the application. // //***************************************************************************** int main(void) { // // Turn on stacking of FPU registers if FPU is used in the ISR. // FPULazyStackingEnable(); // // Set the clocking to run from the PLL at 40MHz. // ROM_SysCtlClockSet(SYSCTL_SYSDIV_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // // Set the system tick to fire 100 times per second. // ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / SYSTICKS_PER_SECOND); ROM_SysTickIntEnable(); ROM_SysTickEnable(); // // Enable the Debug UART. // ConfigureUART(); // // Print the welcome message to the terminal. // UARTprintf("\033[2JAir Mouse Application\n"); // // Configure desired interrupt priorities. This makes certain that the DCM // is fed data at a consistent rate. Lower numbers equal higher priority. // ROM_IntPrioritySet(INT_I2C3, 0x00); ROM_IntPrioritySet(INT_GPIOB, 0x10); ROM_IntPrioritySet(FAULT_SYSTICK, 0x20); ROM_IntPrioritySet(INT_UART1, 0x60); ROM_IntPrioritySet(INT_UART0, 0x70); ROM_IntPrioritySet(INT_WTIMER5B, 0x80); // // Configure the USB D+ and D- pins. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD); ROM_GPIOPinTypeUSBAnalog(GPIO_PORTD_BASE, GPIO_PIN_5 | GPIO_PIN_4); // // Pass the USB library our device information, initialize the USB // controller and connect the device to the bus. // USBDHIDMouseCompositeInit(0, &g_sMouseDevice, &g_psCompDevices[0]); USBDHIDKeyboardCompositeInit(0, &g_sKeyboardDevice, &g_psCompDevices[1]); // // Set the USB stack mode to Force Device mode. // USBStackModeSet(0, eUSBModeForceDevice, 0); // // Pass the device information to the USB library and place the device // on the bus. // USBDCompositeInit(0, &g_sCompDevice, DESCRIPTOR_DATA_SIZE, g_pui8DescriptorData); // // User Interface Init // ButtonsInit(); RGBInit(0); RGBEnable(); // // Initialize the motion sub system. // MotionInit(); // // Initialize the Radio Systems. // LPRFInit(); // // Drop into the main loop. // while(1) { // // Check for and handle timer tick events. // if(HWREGBITW(&g_ui32Events, USB_TICK_EVENT) == 1) { // // Clear the Tick event flag. Set in SysTick interrupt handler. // HWREGBITW(&g_ui32Events, USB_TICK_EVENT) = 0; // // Each tick period handle wired mouse and keyboard. // if(HWREGBITW(&g_ui32USBFlags, FLAG_CONNECTED) == 1) { MouseMoveHandler(); KeyboardMain(); } } // // Check for LPRF tick events. LPRF Ticks are slower since UART to // RNP is much slower data connection than the USB. // if(HWREGBITW(&g_ui32Events, LPRF_TICK_EVENT) == 1) { // // Clear the event flag. // HWREGBITW(&g_ui32Events, LPRF_TICK_EVENT) = 0; // // Perform the LPRF Main task handling // LPRFMain(); } // // Check for and handle motion events. // if((HWREGBITW(&g_ui32Events, MOTION_EVENT) == 1) || (HWREGBITW(&g_ui32Events, MOTION_ERROR_EVENT) == 1)) { // // Clear the motion event flag. Set in the Motion I2C interrupt // handler when an I2C transaction to get sensor data is complete. // HWREGBITW(&g_ui32Events, MOTION_EVENT) = 0; // // Process the motion data that has been captured // MotionMain(); } } }
int sensor(void) { ui32CompDCMStarted = 0; // Go to sleep mode while waiting for data ready. // while(!g_vui8I2CDoneFlag) { ROM_SysCtlSleep(); } // // Clear the flag // g_vui8I2CDoneFlag = 0; // // Get floating point version of the Accel Data in m/s^2. // MPU9150DataAccelGetFloat(&g_sMPU9150Inst, pfAccel, pfAccel + 1, pfAccel + 2); // // Get floating point version of angular velocities in rad/sec // MPU9150DataGyroGetFloat(&g_sMPU9150Inst, pfGyro, pfGyro + 1, pfGyro + 2); // // Get floating point version of magnetic fields strength in tesla // MPU9150DataMagnetoGetFloat(&g_sMPU9150Inst, pfMag, pfMag + 1, pfMag + 2); // // Check if this is our first data ever. // if(ui32CompDCMStarted == 0) { // // Set flag indicating that DCM is started. // Perform the seeding of the DCM with the first data set. // ui32CompDCMStarted = 1; CompDCMMagnetoUpdate(&g_sCompDCMInst, pfMag[0], pfMag[1], pfMag[2]); CompDCMAccelUpdate(&g_sCompDCMInst, pfAccel[0], pfAccel[1], pfAccel[2]); CompDCMGyroUpdate(&g_sCompDCMInst, pfGyro[0], pfGyro[1], pfGyro[2]); CompDCMStart(&g_sCompDCMInst); } else { // // DCM Is already started. Perform the incremental update. // CompDCMMagnetoUpdate(&g_sCompDCMInst, pfMag[0], pfMag[1], pfMag[2]); CompDCMAccelUpdate(&g_sCompDCMInst, pfAccel[0], pfAccel[1], pfAccel[2]); CompDCMGyroUpdate(&g_sCompDCMInst, -pfGyro[0], -pfGyro[1], -pfGyro[2]); CompDCMUpdate(&g_sCompDCMInst); } // // Increment the skip counter. Skip counter is used so we do not // overflow the UART with data. // g_ui32PrintSkipCounter++; if(g_ui32PrintSkipCounter >= PRINT_SKIP_COUNT) { // // Reset skip counter. // g_ui32PrintSkipCounter = 0; // // Get Euler data. (Roll Pitch Yaw) // CompDCMComputeEulers(&g_sCompDCMInst, pfEulers, pfEulers + 1, pfEulers + 2); // // Get Quaternions. // CompDCMComputeQuaternion(&g_sCompDCMInst, pfQuaternion); // // convert mag data to micro-tesla for better human interpretation. // pfMag[0] *= 1e6; pfMag[1] *= 1e6; pfMag[2] *= 1e6; // // Convert Eulers to degrees. 180/PI = 57.29... // Convert Yaw to 0 to 360 to approximate compass headings. // pfEulers[0] *= 57.295779513082320876798154814105f; pfEulers[1] *= 57.295779513082320876798154814105f; pfEulers[2] *= 57.295779513082320876798154814105f; if(pfEulers[2] < 0) { pfEulers[2] += 360.0f; } // // Now drop back to using the data as a single array for the // purpose of decomposing the float into a integer part and a // fraction (decimal) part. // for(ui32Idx = 0; ui32Idx < 16; ui32Idx++) { // // Conver float value to a integer truncating the decimal part. // i32IPart[ui32Idx] = (int32_t) pfData[ui32Idx]; // // Multiply by 1000 to preserve first three decimal values. // Truncates at the 3rd decimal place. // i32FPart[ui32Idx] = (int32_t) (pfData[ui32Idx] * 1000.0f); // // Subtract off the integer part from this newly formed decimal // part. // i32FPart[ui32Idx] = i32FPart[ui32Idx] - (i32IPart[ui32Idx] * 1000); // // make the decimal part a positive number for display. // if(i32FPart[ui32Idx] < 0) { i32FPart[ui32Idx] *= -1; } } // // Print the acceleration numbers in the table. // UARTprintf("\033[5;17H%3d.%03d", i32IPart[0], i32FPart[0]); UARTprintf("\033[5;40H%3d.%03d", i32IPart[1], i32FPart[1]); UARTprintf("\033[5;63H%3d.%03d", i32IPart[2], i32FPart[2]); // // Print the angular velocities in the table. // UARTprintf("\033[7;17H%3d.%03d", i32IPart[3], i32FPart[3]); UARTprintf("\033[7;40H%3d.%03d", i32IPart[4], i32FPart[4]); UARTprintf("\033[7;63H%3d.%03d", i32IPart[5], i32FPart[5]); // // Print the magnetic data in the table. // UARTprintf("\033[9;17H%3d.%03d", i32IPart[6], i32FPart[6]); UARTprintf("\033[9;40H%3d.%03d", i32IPart[7], i32FPart[7]); UARTprintf("\033[9;63H%3d.%03d", i32IPart[8], i32FPart[8]); // // Print the Eulers in a table. // UARTprintf("\033[14;17H%3d.%03d", i32IPart[9], i32FPart[9]); UARTprintf("\033[14;40H%3d.%03d", i32IPart[10], i32FPart[10]); UARTprintf("\033[14;63H%3d.%03d", i32IPart[11], i32FPart[11]); // // Print the quaternions in a table format. // UARTprintf("\033[19;14H%3d.%03d", i32IPart[12], i32FPart[12]); UARTprintf("\033[19;32H%3d.%03d", i32IPart[13], i32FPart[13]); UARTprintf("\033[19;50H%3d.%03d", i32IPart[14], i32FPart[14]); UARTprintf("\033[19;68H%3d.%03d", i32IPart[15], i32FPart[15]); // currentSpeed=i32IPart[9]; how to get velocity from speed } return pitch= i32IPart[9]; }
//***************************************************************************** // // This is the main example program. It checks to see that the interrupts are // processed in the correct order when they have identical priorities, // increasing priorities, and decreasing priorities. This exercises interrupt // preemption and tail chaining. // //***************************************************************************** int main(void) { uint32_t ui32Error; // // Enable lazy stacking for interrupt handlers. This allows floating-point // instructions to be used within interrupt handlers, but at the expense of // extra stack usage. // ROM_FPULazyStackingEnable(); // // Set the clocking to run directly from the crystal. // ROM_SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // // Enable the peripherals used by this example. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE); // // Initialize the UART. // ConfigureUART(); UARTprintf("\033[2JInterrupts\n"); // // Configure the PB0-PB2 to be outputs to indicate entry/exit of one // of the interrupt handlers. // ROM_GPIOPinTypeGPIOOutput(GPIO_PORTE_BASE, GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3); ROM_GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3, 0); // // Set up and enable the SysTick timer. It will be used as a reference // for delay loops in the interrupt handlers. The SysTick timer period // will be set up for one second. // ROM_SysTickPeriodSet(ROM_SysCtlClockGet()); ROM_SysTickEnable(); // // Reset the error indicator. // ui32Error = 0; // // Enable interrupts to the processor. // ROM_IntMasterEnable(); // // Enable the interrupts. // ROM_IntEnable(INT_GPIOA); ROM_IntEnable(INT_GPIOB); ROM_IntEnable(INT_GPIOC); // // Indicate that the equal interrupt priority test is beginning. // UARTprintf("\nEqual Priority\n"); // // Set the interrupt priorities so they are all equal. // ROM_IntPrioritySet(INT_GPIOA, 0x00); ROM_IntPrioritySet(INT_GPIOB, 0x00); ROM_IntPrioritySet(INT_GPIOC, 0x00); // // Reset the interrupt flags. // g_ui32GPIOa = 0; g_ui32GPIOb = 0; g_ui32GPIOc = 0; g_ui32Index = 1; // // Trigger the interrupt for GPIO C. // HWREG(NVIC_SW_TRIG) = INT_GPIOC - 16; // // Put the current interrupt state on the LCD. // DisplayIntStatus(); // // Verify that the interrupts were processed in the correct order. // if((g_ui32GPIOa != 3) || (g_ui32GPIOb != 2) || (g_ui32GPIOc != 1)) { ui32Error |= 1; } // // Wait two seconds. // Delay(2); // // Indicate that the decreasing interrupt priority test is beginning. // UARTprintf("\nDecreasing Priority\n"); // // Set the interrupt priorities so that they are decreasing (i.e. C > B > // A). // ROM_IntPrioritySet(INT_GPIOA, 0x80); ROM_IntPrioritySet(INT_GPIOB, 0x40); ROM_IntPrioritySet(INT_GPIOC, 0x00); // // Reset the interrupt flags. // g_ui32GPIOa = 0; g_ui32GPIOb = 0; g_ui32GPIOc = 0; g_ui32Index = 1; // // Trigger the interrupt for GPIO C. // HWREG(NVIC_SW_TRIG) = INT_GPIOC - 16; // // Put the current interrupt state on the UART. // DisplayIntStatus(); // // Verify that the interrupts were processed in the correct order. // if((g_ui32GPIOa != 3) || (g_ui32GPIOb != 2) || (g_ui32GPIOc != 1)) { ui32Error |= 2; } // // Wait two seconds. // Delay(2); // // Indicate that the increasing interrupt priority test is beginning. // UARTprintf("\nIncreasing Priority\n"); // // Set the interrupt priorities so that they are increasing (i.e. C < B < // A). // ROM_IntPrioritySet(INT_GPIOA, 0x00); ROM_IntPrioritySet(INT_GPIOB, 0x40); ROM_IntPrioritySet(INT_GPIOC, 0x80); // // Reset the interrupt flags. // g_ui32GPIOa = 0; g_ui32GPIOb = 0; g_ui32GPIOc = 0; g_ui32Index = 1; // // Trigger the interrupt for GPIO C. // HWREG(NVIC_SW_TRIG) = INT_GPIOC - 16; // // Put the current interrupt state on the UART. // DisplayIntStatus(); // // Verify that the interrupts were processed in the correct order. // if((g_ui32GPIOa != 1) || (g_ui32GPIOb != 2) || (g_ui32GPIOc != 3)) { ui32Error |= 4; } // // Wait two seconds. // Delay(2); // // Disable the interrupts. // ROM_IntDisable(INT_GPIOA); ROM_IntDisable(INT_GPIOB); ROM_IntDisable(INT_GPIOC); // // Disable interrupts to the processor. // ROM_IntMasterDisable(); // // Print out the test results. // UARTprintf("\nInterrupt Priority =: %s >: %s <: %s\n", (ui32Error & 1) ? "Fail" : "Pass", (ui32Error & 2) ? "Fail" : "Pass", (ui32Error & 4) ? "Fail" : "Pass"); // // Loop forever. // while(1) { } }
//***************************************************************************** // This example demonstrates MIDI functionality and control methods //***************************************************************************** int main(void){ // Set the clocking to run directly from the crystal. SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // Enable the peripherals used by this VS1053. SysCtlPeripheralEnable(SYSCTL_PERIPH_UART1); // VS1053 Serial SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB); // VS1053 Serial SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE); // VS1053 Reset + EMG Input SysCtlPeripheralEnable(SYSCTL_PERIPH_ADC0); // EMG Input 1 // Enable PC Console InitSerial(); // Enable processor interrupts. IntMasterEnable(); // Set GPIO B0 and B1 as UART pins for VS1053 Control GPIOPinConfigure(GPIO_PB0_U1RX); GPIOPinConfigure(GPIO_PB1_U1TX); GPIOPinTypeUART(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1); // Set GPIO E4 as Hardware Reset pin and E5 as ADC Input GPIOPinTypeGPIOOutput(GPIO_PORTE_BASE, GPIO_PIN_4); GPIOPinTypeADC(GPIO_PORTE_BASE, GPIO_PIN_5); // Configure the UART1 as according to VS1053 Datasheet with baudrate of 31250 UARTConfigSetExpClk(UART1_BASE, ROM_SysCtlClockGet(), 31250, (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE)); // Setup ADC Sampling Sequences 3, configure step 0. // Note: Sequence 1 and 2 has 4 step, which would be great for 3-channel sampling ADCSequenceConfigure(ADC0_BASE, 3, ADC_TRIGGER_PROCESSOR, 0); ADCSequenceStepConfigure(ADC0_BASE, 3, 0, ADC_CTL_CH8 | ADC_CTL_IE | ADC_CTL_END); ADCSequenceEnable(ADC0_BASE, 3); ADCIntClear(ADC0_BASE, 3); // Example Started UARTprintf("VS1053 Test\n"); // Reset the VS1053 VS1053_Reset(); // Setup the MIDI Channel 0 midiSetChannelBank(0, VS1053_BANK_MELODY); midiSetInstrument(0, VS1053_GM1_OCARINA); midiSetChannelVolume(0, 127); midiNoteOn(0, 70, 127); Delay(1000); // Setup the MIDI Channel 1 midiSetChannelBank(1, VS1053_BANK_MELODY); midiSetInstrument(1, VS1053_GM1_OCARINA); midiSetChannelVolume(1, 0); midiNoteOn(1, 60, 127); // Setup variables for ADC uint32_t ADC_Output[1]; uint8_t volume; // Infinite Loop of execution while(1) { // ADC Sampling Procedures ADCProcessorTrigger(ADC0_BASE, 3); while(!ADCIntStatus(ADC0_BASE, 3, false)) {} ADCIntClear(ADC0_BASE, 3); ADCSequenceDataGet(ADC0_BASE, 3, ADC_Output); UARTprintf("AIN8 = %4d\n", ADC_Output[0]); // Play Sound as according to voltage level volume = inputMapping(ADC_Output[0], 3000, 4000, 50, 127); midiSetChannelVolume(0, volume); UARTprintf("Volume Level = %4d\n", volume); // Delay Delay(100); } }
//***************************************************************************** // // This is the generic callback from host stack. // // pvData is actually a pointer to a tEventInfo structure. // // This function will be called to inform the application when a USB event has // occurred that is outside those related to the keyboard device. At this // point this is used to detect unsupported devices being inserted and removed. // It is also used to inform the application when a power fault has occurred. // This function is required when the g_USBGenericEventDriver is included in // the host controller driver array that is passed in to the // USBHCDRegisterDrivers() function. // //***************************************************************************** void USBHCDEvents(void *pvData) { tEventInfo *pEventInfo; // // Cast this pointer to its actual type. // pEventInfo = (tEventInfo *)pvData; switch(pEventInfo->ulEvent) { // // New keyboard detected. // case USB_EVENT_CONNECTED: { // // See if this is a HID Keyboard. // if((USBHCDDevClass(pEventInfo->ulInstance, 0) == USB_CLASS_HID) && (USBHCDDevProtocol(pEventInfo->ulInstance, 0) == USB_HID_PROTOCOL_KEYB)) { // // Indicate that the keyboard has been detected. // UARTprintf("Keyboard Connected\n"); // // Proceed to the STATE_KEYBOARD_INIT state so that the main // loop can finish initialized the mouse since // USBHKeyboardInit() cannot be called from within a callback. // g_eUSBState = STATE_KEYBOARD_INIT; } break; } // // Unsupported device detected. // case USB_EVENT_UNKNOWN_CONNECTED: { UARTprintf("Unsupported Device Connected\n"); // // An unsupported device was detected. // g_eUSBState = STATE_UNKNOWN_DEVICE; UpdateStatus(); break; } // // Device has been unplugged. // case USB_EVENT_DISCONNECTED: { // // Indicate that the device has been disconnected. // UARTprintf("Device Disconnected\n"); // // Change the state so that the main loop knows that the device // is no longer present. // g_eUSBState = STATE_NO_DEVICE; // // Update the screen. // UpdateStatus(); break; } // // Power Fault has occurred. // case USB_EVENT_POWER_FAULT: { UARTprintf("Power Fault\n"); // // No power means no device is present. // g_eUSBState = STATE_POWER_FAULT; UpdateStatus(); break; } default: { break; } } }
//***************************************************************************** // // Main 'C' Language entry point. // //***************************************************************************** int main(void) { float fTemperature, fPressure, fAltitude; int32_t i32IntegerPart; int32_t i32FractionPart; // // Setup the system clock to run at 40 MHz from PLL with crystal reference // ROM_SysCtlClockSet(SYSCTL_SYSDIV_5 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN); // // Initialize the UART. // ConfigureUART(); // // Print the welcome message to the terminal. // UARTprintf("\033[2JBMP180 Example\n"); // // Set the color to a white approximation. // g_pui32Colors[RED] = 0x8000; g_pui32Colors[BLUE] = 0x8000; g_pui32Colors[GREEN] = 0x8000; // // Initialize RGB driver. Use a default intensity and blink rate. // RGBInit(0); RGBColorSet(g_pui32Colors); RGBIntensitySet(0.5f); RGBEnable(); // // The I2C3 peripheral must be enabled before use. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C3); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD); // // Configure the pin muxing for I2C3 functions on port D0 and D1. // This step is not necessary if your part does not support pin muxing. // ROM_GPIOPinConfigure(GPIO_PD0_I2C3SCL); ROM_GPIOPinConfigure(GPIO_PD1_I2C3SDA); // // Select the I2C function for these pins. This function will also // configure the GPIO pins pins for I2C operation, setting them to // open-drain operation with weak pull-ups. Consult the data sheet // to see which functions are allocated per pin. // GPIOPinTypeI2CSCL(GPIO_PORTD_BASE, GPIO_PIN_0); ROM_GPIOPinTypeI2C(GPIO_PORTD_BASE, GPIO_PIN_1); // // Initialize the GPIO for the LED. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF); ROM_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1); ROM_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, 0x00); // // Enable interrupts to the processor. // ROM_IntMasterEnable(); // // Initialize the I2C3 peripheral. // I2CMInit(&g_sI2CInst, I2C3_BASE, INT_I2C3, 0xff, 0xff, ROM_SysCtlClockGet()); // // Initialize the BMP180. // BMP180Init(&g_sBMP180Inst, &g_sI2CInst, BMP180_I2C_ADDRESS, BMP180AppCallback, &g_sBMP180Inst); // // Wait for initialization callback to indicate reset request is complete. // while(g_vui8DataFlag == 0) { // // Wait for I2C Transactions to complete. // } // // Reset the data ready flag // g_vui8DataFlag = 0; // // Enable the system ticks at 10 Hz. // ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / (10 * 3)); ROM_SysTickIntEnable(); ROM_SysTickEnable(); // // After all the init and config we start blink the LED // RGBBlinkRateSet(1.0f); // // Begin the data collection and printing. Loop Forever. // while(1) { // // Read the data from the BMP180 over I2C. This command starts a // temperature measurement. Then polls until temperature is ready. // Then automatically starts a pressure measurement and polls for that // to complete. When both measurement are complete and in the local // buffer then the application callback is called from the I2C // interrupt context. Polling is done on I2C interrupts allowing // processor to continue doing other tasks as needed. // BMP180DataRead(&g_sBMP180Inst, BMP180AppCallback, &g_sBMP180Inst); while(g_vui8DataFlag == 0) { // // Wait for the new data set to be available. // } // // Reset the data ready flag. // g_vui8DataFlag = 0; // // Get a local copy of the latest temperature data in float format. // BMP180DataTemperatureGetFloat(&g_sBMP180Inst, &fTemperature); // // Convert the floats to an integer part and fraction part for easy // print. // i32IntegerPart = (int32_t) fTemperature; i32FractionPart =(int32_t) (fTemperature * 1000.0f); i32FractionPart = i32FractionPart - (i32IntegerPart * 1000); if(i32FractionPart < 0) { i32FractionPart *= -1; } // // Print temperature with three digits of decimal precision. // UARTprintf("Temperature %3d.%03d\t\t", i32IntegerPart, i32FractionPart); // // Get a local copy of the latest air pressure data in float format. // BMP180DataPressureGetFloat(&g_sBMP180Inst, &fPressure); // // Convert the floats to an integer part and fraction part for easy // print. // i32IntegerPart = (int32_t) fPressure; i32FractionPart =(int32_t) (fPressure * 1000.0f); i32FractionPart = i32FractionPart - (i32IntegerPart * 1000); if(i32FractionPart < 0) { i32FractionPart *= -1; } // // Print Pressure with three digits of decimal precision. // UARTprintf("Pressure %3d.%03d\t\t", i32IntegerPart, i32FractionPart); // // Calculate the altitude. // fAltitude = 44330.0f * (1.0f - powf(fPressure / 101325.0f, 1.0f / 5.255f)); // // Convert the floats to an integer part and fraction part for easy // print. // i32IntegerPart = (int32_t) fAltitude; i32FractionPart =(int32_t) (fAltitude * 1000.0f); i32FractionPart = i32FractionPart - (i32IntegerPart * 1000); if(i32FractionPart < 0) { i32FractionPart *= -1; } // // Print altitude with three digits of decimal precision. // UARTprintf("Altitude %3d.%03d", i32IntegerPart, i32FractionPart); // // Print new line. // UARTprintf("\n"); // // Delay to keep printing speed reasonable. About 100 milliseconds. // ROM_SysCtlDelay(ROM_SysCtlClockGet() / (10 * 3)); }//while end }
//***************************************************************************** // // Initialize the DES and CCM modules. // //***************************************************************************** bool DESInit(void) { uint32_t ui32Loop; // // Check that the CCM peripheral is present. // if(!ROM_SysCtlPeripheralPresent(SYSCTL_PERIPH_CCM0)) { UARTprintf("No CCM peripheral found!\n"); // // Return failure. // return(false); } // // The hardware is available, enable it. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_CCM0); // // Wait for the peripheral to be ready. // ui32Loop = 0; while(!ROM_SysCtlPeripheralReady(SYSCTL_PERIPH_CCM0)) { // // Increment our poll counter. // ui32Loop++; if(ui32Loop > CCM_LOOP_TIMEOUT) { // // Timed out, notify and spin. // UARTprintf("Time out on CCM ready after enable.\n"); // // Return failure. // return(false); } } // // Reset the peripheral to ensure we are starting from a known condition. // ROM_SysCtlPeripheralReset(SYSCTL_PERIPH_CCM0); // // Wait for the peripheral to be ready again. // ui32Loop = 0; while(!ROM_SysCtlPeripheralReady(SYSCTL_PERIPH_CCM0)) { // // Increment our poll counter. // ui32Loop++; if(ui32Loop > CCM_LOOP_TIMEOUT) { // // Timed out, spin. // UARTprintf("Time out on CCM ready after reset.\n"); // // Return failure. // return(false); } } // // Return initialization success. // return(true); }
//***************************************************************************** // // This example encrypts blocks of plaintext using TDES in CBC mode. It // does the encryption first without uDMA and then with uDMA. The results // are checked after each operation. // //***************************************************************************** int main(void) { uint32_t pui32CipherText[16], ui32Errors, ui32Idx, ui32SysClock; // // Run from the PLL at 120 MHz. // ui32SysClock = MAP_SysCtlClockFreqSet((SYSCTL_XTAL_25MHZ | SYSCTL_OSC_MAIN | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_480), 120000000); // // Configure the device pins. // PinoutSet(false, false); // // Initialize local variables. // ui32Errors = 0; for(ui32Idx = 0; ui32Idx < 16; ui32Idx++) { pui32CipherText[ui32Idx] = 0; } // // Enable stacking for interrupt handlers. This allows floating-point // instructions to be used within interrupt handlers, but at the expense of // extra stack usage. // ROM_FPUStackingEnable(); // // Enable DES interrupts. // ROM_IntEnable(INT_DES0); // // Enable debug output on UART0 and print a welcome message. // ConfigureUART(); UARTprintf("Starting TDES CBC encryption demo.\n"); // // Enable the uDMA module. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_UDMA); // // Setup the control table. // ROM_uDMAEnable(); ROM_uDMAControlBaseSet(g_psDMAControlTable); // // Initialize the CCM and DES modules. // if(!DESInit()) { UARTprintf("Initialization of the DES module failed.\n"); ui32Errors |= 0x00000001; } // // Perform the encryption without uDMA. // UARTprintf("Performing encryption without uDMA.\n"); TDESCBCEncrypt(g_pui32TDESPlainText, pui32CipherText, g_pui32TDESKey, 64, g_pui32TDESIV, false); // // Check the result. // for(ui32Idx = 0; ui32Idx < 16; ui32Idx++) { if(pui32CipherText[ui32Idx] != g_pui32TDESCipherText[ui32Idx]) { UARTprintf("Ciphertext mismatch on word %d. Exp: 0x%x, Act: " "0x%x\n", ui32Idx, g_pui32TDESCipherText[ui32Idx], pui32CipherText[ui32Idx]); ui32Errors |= (ui32Idx << 16) | 0x00000002; } } // // Clear the array containing the ciphertext. // for(ui32Idx = 0; ui32Idx < 16; ui32Idx++) { pui32CipherText[ui32Idx] = 0; } // // Perform the encryption with uDMA. // UARTprintf("Performing encryption with uDMA.\n"); TDESCBCEncrypt(g_pui32TDESPlainText, pui32CipherText, g_pui32TDESKey, 64, g_pui32TDESIV, true); // // Check the result. // for(ui32Idx = 0; ui32Idx < 16; ui32Idx++) { if(pui32CipherText[ui32Idx] != g_pui32TDESCipherText[ui32Idx]) { UARTprintf("Ciphertext mismatch on word %d. Exp: 0x%x, Act: " "0x%x\n", ui32Idx, g_pui32TDESCipherText[ui32Idx], pui32CipherText[ui32Idx]); ui32Errors |= (ui32Idx << 16) | 0x00000004; } } // // Finished. // if(ui32Errors) { UARTprintf("Demo failed with error code 0x%x.\n", ui32Errors); LEDWrite(CLP_D3 | CLP_D4, CLP_D4); } else { UARTprintf("Demo completed successfully.\n"); LEDWrite(CLP_D3 | CLP_D4, CLP_D3); } while(1) { } }
// *************** NodeMain ************** // Main task for the sensor node. This task runs a simple sensor task "scheduler" // that runs periodically based on the GCF of all sensor's sampling rates, MinSampRate. // Every sensor is run after a certain number of MinSampRate intervals has passed. Note // that this is not a real-time scheduler. It assumes that all sensor tasks can run to // completion within the MinSampRate time, which is at most 1 second. static void NodeMain( void ) { SENSOR_MSG_T sensor_msg; Message transceiver_msg; char *transceiver_msg_data; unsigned long i; unsigned long delay_time; int (*task)( PORT_T *port ); #if ENABLE_UART_PRINTF UARTprintf( "\nNode Main\n" ); UARTprintf( "---------\n\n" ); #endif // XXX Need to add semaphore so NodeMain doesn't run while any sensorInit* tasks are running for( ;; ) { delay_time = 3; // Update the sampling rates if any sampling rate has changed if( 1 == SampRateChanged ) { taskENTER_CRITICAL(); updateSamplingRates(); SampRateChanged = 0; taskEXIT_CRITICAL(); } // Check if there are active sensors if( NumActiveSensors > 0 ) { LED_Off( LED2 ); if( 0 == MinSampRate ) { #if ENABLE_UART_PRINTF UARTprintf( "MinSampRate = 0 - put node to sleep\n" ); #endif } else { // Sensor Task Scheduler // Note that we assume all tasks can run in well under 1 second. If any tasks take // longer to run, we need to implement a "background task" that sensor drivers can use. delay_time = MinSampRate; for( i = 0; i < 1; i++ ) { if( SensorSampRateTicks[i] == 0 ) { SensorSampRateTicks[i] = SensorSampRateTicksReset[i]; switch ( i ) { case 0: SensorTask1( SensorPort[i] ); break; case 1: SensorTask2( SensorPort[i] ); break; case 2: SensorTask3( SensorPort[i] ); break; case 3: SensorTask4( SensorPort[i] ); break; default: break; } } else { if( SensorSampRateTicks[i] != -1 ) { SensorSampRateTicks[i]--; } } // Process messages sent by each sensor, send them either to the transceiver // or to another sensor on the node. Other destination IDs for sensor messages // could be added in the future. For example, messages could be sent to a // a message log on the node, or potentially to other nodes in the network. // XXX // Each sensor sends messages directly to the Transceiver Queue, more efficient // due to the implementation of the xQueue data structure (passing whole messages // is costly). An improved version would have message handling done here, so that // sensor messages could be sent to the transceiver or another location depending // on message id. This would allow messages between sensors, message backup, // message logging, etc. /* if( pdTRUE == xQueueReceive( (xQueueHandle)SensorPort[i]->tx_fifo, &sensor_msg, 0 ) ) { // Print message UARTprintf( "dest_id: %d\n", sensor_msg.dest_id ); UARTprintf( "data_size: %d\n", sensor_msg.data_size ); printDataHex( sensor_msg.data_size, sensor_msg.data ); UARTprintf( "\n" ); if( WSN_RECEIVER_ID == sensor_msg.dest_id ) { // Send this message to the transceiver // XXX need timeout here (and in Sensor_PushMessage) in case transceiver is not available //transceiver_msg.sensorID = SensorPort[i]->sensor_id; //transceiver_msg.dataSize = sensor_msg.data_size; //transceiver_msg_data = sensor_msg.data; //while( xQueueSend( Transceiver_TX_Queue, (void *)&transceiver_msg, (portTickType)0 ) != pdPASS ); } else { // Send this message to the appropriate location // XXX } } */ // Check for messages received from the WSN Receiver // Need a queue to handle "node control" messages from WSN Receiver. Process messages // from the queue here. I assume this is the Transceiver_Rx_Queue. // If transceiver interrupts when a message is received, the interrupt can put those messages // directly into each port's rx_fifo instead of the Transceiver_Rx_Queue. // XXX // Incomming messages are handled by the transceiver code, for similar reasons as above. } } } else { // If there are no sensors connected, put the node to sleep LED_On( LED2 ); #if ENABLE_UART_PRINTF UARTprintf( "no sensors connected\n" ); #endif } // Sleep // XXX This thread should sleep if there are no active sensors. Need to wake up // this thread when a new sensor is plugged in, or when Sensor_SendData() is // called from an ISR. vTaskDelay( delay_time*TICKS_IN_SEC ); } }
//***************************************************************************** // // Perform an encryption operation. // //***************************************************************************** bool TDESCBCEncrypt(uint32_t *pui32Src, uint32_t *pui32Dst, uint32_t *pui32Key, uint32_t ui32Length, uint32_t *pui32IV, bool bUseDMA) { // // Perform a soft reset. // ROM_DESReset(DES_BASE); // // Clear the interrupt flags. // g_bContextInIntFlag = false; g_bDataInIntFlag = false; g_bDataOutIntFlag = false; g_bContextInDMADoneIntFlag = false; g_bDataInDMADoneIntFlag = false; g_bDataOutDMADoneIntFlag = false; // // Enable all interrupts. // ROM_DESIntEnable(DES_BASE, (DES_INT_CONTEXT_IN | DES_INT_DATA_IN | DES_INT_DATA_OUT)); // // Configure the DES module. // ROM_DESConfigSet(DES_BASE, (DES_CFG_DIR_ENCRYPT | DES_CFG_TRIPLE | DES_CFG_MODE_CBC)); // // Write the key. // ROM_DESKeySet(DES_BASE, pui32Key); // // Write the IV. // ROM_DESIVSet(DES_BASE, pui32IV); // // Depending on the argument, perform the encryption // with or without uDMA. // if(bUseDMA) { // // Enable DMA interrupts. // ROM_DESIntEnable(DES_BASE, (DES_INT_DMA_CONTEXT_IN | DES_INT_DMA_DATA_IN | DES_INT_DMA_DATA_OUT)); // // Setup the DMA module to copy data in. // ROM_uDMAChannelAssign(UDMA_CH21_DES0DIN); ROM_uDMAChannelAttributeDisable(UDMA_CH21_DES0DIN, UDMA_ATTR_ALTSELECT | UDMA_ATTR_USEBURST | UDMA_ATTR_HIGH_PRIORITY | UDMA_ATTR_REQMASK); ROM_uDMAChannelControlSet(UDMA_CH21_DES0DIN | UDMA_PRI_SELECT, UDMA_SIZE_32 | UDMA_SRC_INC_32 | UDMA_DST_INC_NONE | UDMA_ARB_2 | UDMA_DST_PROT_PRIV); ROM_uDMAChannelTransferSet(UDMA_CH21_DES0DIN | UDMA_PRI_SELECT, UDMA_MODE_BASIC, (void *)pui32Src, (void *)(DES_BASE + DES_O_DATA_L), LengthRoundUp(ui32Length) / 4); UARTprintf("Data in DMA request enabled.\n"); // // Setup the DMA module to copy the data out. // ROM_uDMAChannelAssign(UDMA_CH22_DES0DOUT); ROM_uDMAChannelAttributeDisable(UDMA_CH22_DES0DOUT, UDMA_ATTR_ALTSELECT | UDMA_ATTR_USEBURST | UDMA_ATTR_HIGH_PRIORITY | UDMA_ATTR_REQMASK); ROM_uDMAChannelControlSet(UDMA_CH22_DES0DOUT | UDMA_PRI_SELECT, UDMA_SIZE_32 | UDMA_SRC_INC_NONE | UDMA_DST_INC_32 | UDMA_ARB_2 | UDMA_SRC_PROT_PRIV); ROM_uDMAChannelTransferSet(UDMA_CH22_DES0DOUT | UDMA_PRI_SELECT, UDMA_MODE_BASIC, (void *)(DES_BASE + DES_O_DATA_L), (void *)pui32Dst, LengthRoundUp(ui32Length) / 4); UARTprintf("Data out DMA request enabled.\n"); // // Enable DMA requests // ROM_DESDMAEnable(DES_BASE, DES_DMA_DATA_IN | DES_DMA_DATA_OUT); // // Write the length registers to start the process. // ROM_DESLengthSet(DES_BASE, ui32Length); // // Enable the DMA channels to start the transfers. This must be done after // writing the length to prevent data from copying before the context is // truly ready. // ROM_uDMAChannelEnable(UDMA_CH21_DES0DIN); ROM_uDMAChannelEnable(UDMA_CH22_DES0DOUT); // // Wait for the data in DMA done interrupt. // while(!g_bDataInDMADoneIntFlag) { } // // Wait for the data out DMA done interrupt. // while(!g_bDataOutDMADoneIntFlag) { } } else { // // Perform the encryption. // ROM_DESDataProcess(DES_BASE, pui32Src, pui32Dst, ui32Length); } return(true); }
//***************************************************************************** // // Prepares a font in the FATfs file system for use by the graphics library. // // This function must be called to prepare a font for use by the graphics // library. It opens the font file whose name is passed and reads the // header information. The value returned should be written into the // pucFontId field of the tFontWrapper structure that will be passed to // graphics library. // // This is a very simple (and slow) implementation. More complex wrappers // may also initialize a glyph cache here. // // \return On success, returns a non-zero pointer identifying the font. On // error, zero is returned. // //***************************************************************************** unsigned char * FATFontWrapperLoad(char *pcFilename) { FRESULT fresult; WORD ulRead, ulToRead; UARTprintf("Attempting to load font %s from FAT file system.\n", pcFilename); // // Make sure a font is not already open. // if(g_sFontFile.bInUse) { // // Oops - someone tried to load a new font without unloading the // previous one. // UARTprintf("Another font is already loaded!\n"); return(0); } // // Try to open the file whose name we've been given. // fresult = f_open(&g_sFontFile.sFile, pcFilename, FA_READ); if(fresult != FR_OK) { // // We can't open the file. Either the file doesn't exist or there is // no SDCard installed. Regardless, return an error. // UARTprintf("Error %s (%d) from f_open.\n", StringFromFresult(fresult), fresult); return(0); } // // We opened the file successfully. Does it seem to contain a valid // font? Read the header and see. // fresult = f_read(&g_sFontFile.sFile, &g_sFontFile.sFontHeader, sizeof(tFontWide), &ulRead); if((fresult == FR_OK) && (ulRead == sizeof(tFontWide))) { // // We read the font header. Is the format correct? We only support // wide fonts via wrappers. // if((g_sFontFile.sFontHeader.ucFormat != FONT_FMT_WIDE_UNCOMPRESSED) && (g_sFontFile.sFontHeader.ucFormat != FONT_FMT_WIDE_PIXEL_RLE)) { // // This is not a supported font format. // UARTprintf("Unrecognized font format. Failing " "FATFontWrapperLoad.\n"); f_close(&g_sFontFile.sFile); return(0); } // // The format seems to be correct so read as many block headers as we // have storage for. // ulToRead = (g_sFontFile.sFontHeader.usNumBlocks > MAX_FONT_BLOCKS) ? MAX_FONT_BLOCKS * sizeof(tFontBlock) : g_sFontFile.sFontHeader.usNumBlocks * sizeof(tFontBlock); fresult = f_read(&g_sFontFile.sFile, &g_sFontFile.pBlocks, ulToRead, &ulRead); if((fresult == FR_OK) && (ulRead == ulToRead)) { // // All is well. Tell the caller the font was opened successfully. // UARTprintf("Font %s opened successfully.\n", pcFilename); g_sFontFile.bInUse = true; return((unsigned char *)&g_sFontFile); } else { UARTprintf("Error %s (%d) reading block headers. Read %d, exp %d bytes.\n", StringFromFresult(fresult), fresult, ulRead, ulToRead); f_close(&g_sFontFile.sFile); return(0); } } else { // // We received an error while reading the file header so fail the call. // UARTprintf("Error %s (%d) reading font header.\n", StringFromFresult(fresult), fresult); f_close(&g_sFontFile.sFile); return(0); } }
//***************************************************************************** // // Returns information on the glyphs contained within a given font block. // //***************************************************************************** static unsigned long FATWrapperFontBlockCodepointsGet(unsigned char *pucFontId, unsigned short usBlockIndex, unsigned long *pulStart) { tFontBlock sBlock; tFontFile *pFont; tBoolean bRetcode; // // Parameter sanity check. // ASSERT(pucFontId); // // Get a pointer to our instance data. // pFont = (tFontFile *)pucFontId; ASSERT(pFont->bInUse); // // Have we been passed a valid block index? // if(usBlockIndex >= pFont->sFontHeader.usNumBlocks) { // // No - return an error. // return(0); } // // Is this block header cached? // if(usBlockIndex < MAX_FONT_BLOCKS) { // // Yes - return the information from our cached copy. // *pulStart = pFont->pBlocks[usBlockIndex].ulStartCodepoint; return(pFont->pBlocks[usBlockIndex].ulNumCodepoints); } else { // // We don't have the block header cached so read it from the // SDCard. First move the file pointer to the expected position. // bRetcode = FATWrapperFontBlockHeaderGet(&pFont->sFile, &sBlock, usBlockIndex); if(bRetcode) { *pulStart = sBlock.ulStartCodepoint; return(sBlock.ulNumCodepoints); } else { UARTprintf("Error reading block header!\n"); } } // // If we get here, something horrible happened so return a failure. // *pulStart = 0; return(0); }
// // Main - It performs initialization, then runs a command processing loop to // read commands from the console. // int main(void) { int nStatus; FRESULT fresult; // // Set the clocking to run from the PLL at 50MHz // SysCtlClockSet(SYSCTL_OSCSRC_OSC2 | SYSCTL_PLL_ENABLE | SYSCTL_IMULT(10) | SYSCTL_SYSDIV(2)); SysCtlAuxClockSet(SYSCTL_OSCSRC_OSC2 | SYSCTL_PLL_ENABLE | SYSCTL_IMULT(12) | SYSCTL_SYSDIV(2)); //60 MHz #ifdef _FLASH // // Copy time critical code and Flash setup code to RAM // This includes the following functions: InitFlash_Bank0(); // The RamfuncsLoadStart, RamfuncsLoadSize, and RamfuncsRunStart // symbols are created by the linker. Refer to the device .cmd file. // memcpy(&RamfuncsRunStart, &RamfuncsLoadStart, (size_t)&RamfuncsLoadSize); // // Call Flash Initialization to setup flash waitstates // This function must reside in RAM // InitFlash_Bank0(); #endif // // Initialize interrupt controller and vector table // InitPieCtrl(); InitPieVectTable(); // // Set the system tick to fire 100 times per second. // SysTickInit(); SysTickPeriodSet(SysCtlClockGet(SYSTEM_CLOCK_SPEED) / 100); SysTickIntRegister(SysTickHandler); SysTickIntEnable(); SysTickEnable(); // // Enable Interrupts // IntMasterEnable(); // // Configure UART0 for debug output. // ConfigureUART(); // // Print hello message to user. // UARTprintf("\n\nSD Card Example Program\n"); UARTprintf("Type \'help\' for help.\n"); // // Mount the file system, using logical disk 0. // fresult = f_mount(0, &g_sFatFs); if(fresult != FR_OK) { UARTprintf("f_mount error: %s\n", StringFromFresult(fresult)); return(1); } // // Enter an (almost) infinite loop for reading and processing commands from // the user. // while(1) { // // Print a prompt to the console. Show the CWD. // UARTprintf("\n%s> ", g_cCwdBuf); // // Get a line of text from the user. // UARTgets(g_cCmdBuf, sizeof(g_cCmdBuf)); // // Pass the line from the user to the command processor. // It will be parsed and valid commands executed. // nStatus = CmdLineProcess(g_cCmdBuf); // // Handle the case of bad command. // if(nStatus == CMDLINE_BAD_CMD) { UARTprintf("Bad command!\n"); } // // Handle the case of too many arguments. // else if(nStatus == CMDLINE_TOO_MANY_ARGS) { UARTprintf("Too many arguments for command processor!\n"); } // // Otherwise the command was executed. Print the error // code if one was returned. // else if(nStatus != 0) { UARTprintf("Command returned error code %s\n", StringFromFresult((FRESULT)nStatus)); } } }
void MPU9250_Init() { uint32_t Device_ID; SysCtlPeripheralEnable(SYSCTL_PERIPH_SSI0); SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA); GPIOPinTypeGPIOOutput(GPIO_PORTA_BASE, GPIO_PIN_7); GPIOPinConfigure(GPIO_PA2_SSI0CLK); GPIOPinConfigure(GPIO_PA3_SSI0FSS); GPIOPinConfigure(GPIO_PA4_SSI0RX); GPIOPinConfigure(GPIO_PA5_SSI0TX); GPIOPinTypeSSI(GPIO_PORTA_BASE, GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5); GPIOPadConfigSet(GPIO_PORTA_BASE, GPIO_PIN_3, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU); SSIConfigSetExpClk(SSI0_BASE, SysCtlClockGet(), SSI_FRF_MOTO_MODE_3, SSI_MODE_MASTER, 1000000, 8); SSIEnable(SSI0_BASE); // // Display the example setup on the console. // UARTprintf("\nPower up.\n"); // MPU-6500 Device ID check and initial Device_ID = 0x0; Device_ID = MPU9250_ReadReg(MPU6500_WHO_AM_I); if(Device_ID == MPU6500_Device_ID) { UARTprintf("MPU6500 Device ID: 0x%X\n--- MPU6500 Initialization done.\n", Device_ID); } else { OLED_Print(0,0,"MPU6500 ERR"); UARTprintf("MPU6500 Device ID: 0x%X\n--- MPU6500 Initialization error.\n", Device_ID); while (1); } MPU9250_SetParameter(); #ifdef USE_MAG // AK9875 Device ID check // if AK9875 ID check check failed with no reason, re-power-up the system. MPU9250_WriteAuxReg(AK8963_CNTL2, 0x01); //soft reset MPU9250_Delay_nop(100000); Device_ID = 0x00; Device_ID = MPU9250_ReadAuxReg(AK8963_WIA); if(Device_ID == AK8963_Device_ID) { UARTprintf("AK8963 Device ID: 0x%X\n--- AK8963 Initialization done.\n", Device_ID); LED_Blue_Off(); } else { UARTprintf("AK8963 Device ID: 0x%X\n--- AK8963 Initialization error.\n", Device_ID); OLED_Print(0,0,"AK8963 Init ERR"); LED_Red_Off(); LED_Green_Off(); } MPU9250_GetMagAdjValue(); MPU9250_WriteAuxReg(AK8963_CNTL1, 0x16); // 16-bits, Rate 100Hz //MPU9250_WriteAuxReg(AK8963_CNTL1, 0x2); // 14-bits, Rate 8Hz Device_ID = MPU9250_ReadAuxReg(AK8963_CNTL1); #else UARTprintf("AK8963 is disabled.\n"); #endif }
/** * Read block(s) from MMC/SD card. The implementation follows * '26.3.5 MMC/SD Mode Single-Block Read Operation Using EDMA' in 'spruh82a'. * @param mmcsdCtrlInfo It holds the mmcsd control information. * @param ptr It determines the address to where data has to read * @param block It determines from which block data to be read (block >= 0) * @param nblks It determines the number of blocks to be read (nblks >= 1) * @retval 1 success * @retval 0 fail */ unsigned int MMCSDReadCmdSend(mmcsdCtrlInfo *ctrl, void *ptr, unsigned int block, unsigned int nblks) { // TODO: workaround for buggy READ_MULTI_BLOCK if (nblks > 1) { for (unsigned int i = 0; i < nblks; ++i) { unsigned int res = MMCSDReadCmdSend(ctrl, ptr + i * MMCSD_MAX_BLOCK_LEN, block + i, 1); assert(res == 1); } return 1; } assert(nblks == 1); #if defined(DEBUG) // UARTprintf("----\r\n"); // UARTprintf("%s(0x%x)\r\n", __FUNCTION__, ctrl); // syslog(LOG_ERROR, "----"); syslog(LOG_ERROR, "%s(ctrl=0x%p,ptr=0x%p,block=%d,nblks=%d)", __FUNCTION__, ctrl, ptr, block, nblks); #endif assert(nblks * MMCSD_MAX_BLOCK_LEN <= sizeof(data_recv_buf)); // MMCSDDataTimeoutSet(ctrl->memBase, 0x0, 0x3FFFFFF);// Infinite wait for CMD response, maximum wait for data transfer // cmdTimeout = 0; // TODO: fix this (refactoring) // for(int i = 0; i < sizeof(data_recv_buf); ++i) data_recv_buf[i] = 0xFF; // Fill data_recv_buf for debug unsigned int status = 1; // 1 for success volatile struct st_mmcsd *mmc = ctrl->memBase; ER ercd; /* 1. Write the card's relative address to the MMC argument registers (MMCARGH and MMCARGL). */ mmcsdCardInfo *card = ctrl->card; unsigned int address; /* * TODO: check this -- ertl-liyixiao * Address is in blks for high cap cards and in actual bytes * for standard capacity cards */ assert(card->highCap); if (card->highCap) address = block; else address = block * card->blkLen; mmc->MMCARGHL = address; /* 2. Read card CSD to determine the card's maximum block length. */ // TODO: /* 3. Use the MMC command register (MMCCMD) to send the SET_BLOCKLEN command (if the block length is different than the length used in the previous operation). The block length must be a multiple of 512 bytes and less then the maximum block length specified in the CSD. */ // TODO: /* 4. Reset the FIFO (FIFORST bit in MMCFIFOCTL). */ mmc->MMCFIFOCTL |= MMCSD_MMCFIFOCTL_FIFORST; mmc->MMCFIFOCTL &= ~MMCSD_MMCFIFOCTL_FIFORST; /* 5. Set the FIFO direction to receive (FIFODIR bit in MMCFIFOCTL). */ mmc->MMCFIFOCTL &= ~MMCSD_MMCFIFOCTL_FIFODIR; /* 6. Set the access width (ACCWD bits in MMCFIFOCTL). */ mmc->MMCFIFOCTL &= ~MMCSD_MMCFIFOCTL_ACCWD; mmc->MMCFIFOCTL |= (MMCSD_MMCFIFOCTL_ACCWD_4BYTES << MMCSD_MMCFIFOCTL_ACCWD_SHIFT); // => 4 bytes /* 7. Set the FIFO threshold (FIFOLEV bit in MMCFIFOCTL). */ mmc->MMCFIFOCTL |= MMCSD_MMCFIFOCTL_FIFOLEV; // => 64 bytes /* 8. Set up DMA (DMA size needs to be greater than or equal to FIFOLEV setting). */ CacheDataCleanBuff(data_recv_buf, sizeof(data_recv_buf)); // Clean 'data_recv_buf' arm926_drain_write_buffer(); // Memory barrier for 'data_recv_buf' ctrl->xferSetup(ctrl, 1, data_recv_buf/*ptr*/, MMCSD_MAX_BLOCK_LEN, nblks); /* 9. Use MMCCMD to send the READ_BLOCK command to the card. */ #if defined(DEBUG) syslog(LOG_ERROR, "%s(): Use MMCCMD to send the READ_BLOCK/READ_MULTI_BLOCK command to the card.", __FUNCTION__); #endif // ercd = clr_flg(MMCSD_ISR_FLG, ~(MMCSD_ISR_FLGPTN_DATATIMEOUT)); // Clear data time-out flag // mmc->MMCIM |= MMCSD_MMCIM_ETOUTRD; // Enable data time-out interrupt assert(ercd == E_OK); mmcsdCmd cmd; cmd.flags = SD_CMDRSP_R1 | SD_CMDRSP_READ | SD_CMDRSP_DATA; cmd.arg = address; cmd.nblks = nblks; if (nblks > 1) { cmd.flags |= SD_CMDRSP_ABORT; cmd.idx = SD_CMD(18); } else { cmd.idx = SD_CMD(17); } status = MMCSDCmdSend(ctrl, &cmd); if (status == 0) { syslog(LOG_ERROR, "%s(): MMCSDCmdSend() failed.", __FUNCTION__); goto error_exit; } /* 10. Set the DMATRIG bit in MMCCMD to trigger the first data transfer. */ #if DEBUG_PRINT // syslog(LOG_ERROR, "%s(): Set the DMATRIG bit, MMCCMD: 0x%08x=>0x%08x", __FUNCTION__, mmc->MMCCMD, mmc->MMCCMD | MMCSD_MMCCMD_DMATRIG); #endif // mmc->MMCCMD /*|*/= MMCSD_MMCCMD_DMATRIG; /* 11. Wait for DMA sequence to complete. */ status = ctrl->xferStatusGet(ctrl); if (status == 0) { assert(false); goto error_exit; } /* Invalidate the data cache. */ CacheDataInvalidateBuff((unsigned int) data_recv_buf/*ptr*/, (MMCSD_MAX_BLOCK_LEN * nblks)); /* 12. Use the MMC status register 0 (MMCST0) to check for errors. */ // TODO: check this #if 0 syslog(LOG_ERROR, "%s(): MMCST0: 0x%08x", __FUNCTION__, mmc->MMCST0); syslog(LOG_ERROR, "%s(): MMCST1: 0x%08x", __FUNCTION__, mmc->MMCST1); syslog(LOG_ERROR, "%s(): MMCNBLK: %d", __FUNCTION__, mmc->MMCNBLK); syslog(LOG_ERROR, "%s(): MMCNBLC: %d", __FUNCTION__, mmc->MMCNBLC); #endif assert(sizeof(data_recv_buf) >= MMCSD_MAX_BLOCK_LEN * nblks); memcpy(ptr, data_recv_buf, MMCSD_MAX_BLOCK_LEN * nblks); // TODO: ertl-liyixiao #if defined(DEBUG) syslog(LOG_ERROR, "%s sector: %d, count: %d\n", __FUNCTION__, block, nblks); for(int i = 0; i < MMCSD_MAX_BLOCK_LEN * nblks;) { //((uint8_t*)ptr)[i] = ((uint8_t*)ptr)[i]; uint8_t *val = ((uint8_t*)ptr) + i; syslog(LOG_ERROR, "%02x %02x %02x %02x %02x", val[0], val[1], val[2], val[3], val[4]); //printf("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x \n", // val[0], val[1], val[2], val[3], val[4], val[5], val[6], val[7], val[8], val[9], val[10], val[11], val[12], val[13], val[14], val[15]); i += 5; } #endif #if 0 // TODO: !IMPORTANT! STOP_TRANSMISSION must not be sent since MMCSD_MMCNBLK has been set to the exact number. /* Send a STOP_TRANSMISSION after reading multiple blocks */ if (cmd.nblks > 1) { status = MMCSDStopCmdSend(ctrl); assert(status != 0); // TODO: check status } #endif error_exit: // mmc->MMCIM &= ~MMCSD_MMCIM_ETOUTRD; // Disable data time-out interrupt TODO: fix me return status; #if 0 // TODO: -- ertl-liyixiao #ifdef CACHE_SUPPORTED /* Clean the data cache. */ CacheDataCleanBuff((unsigned int) ptr, (MMCSD_MAX_BLOCK_LEN * nblks)); #endif mmcsd_reset_fifo(true); /* Send a STOP */ if (cmd.nblks > 1) { status = MMCSDStopCmdSend(ctrl); if (status == 0) { #if DEBUG_PRINT UARTprintf("%s(0x%x):MMCSDStopCmdSend() returned 0\r\n", __FUNCTION__, ctrl); #endif return 0; } } #endif }
//***************************************************************************** // // This function prints the character out the UART and into the text area of // the screen. // // \param ucChar is the character to print out. // // This function handles all of the detail of printing a character to both the // UART and to the text area of the screen on the evaluation board. The text // area of the screen will be cleared any time the text goes beyond the end // of the text area. // // \return None. // //***************************************************************************** void PrintChar(const char ucChar) { tRectangle sRect; // // If both the line and column have gone to zero then clear the screen. // if((g_ulLine == 0) && (g_ulColumn == 0)) { // // Form the rectangle that makes up the text box. // sRect.sXMin = 0; sRect.sYMin = DISPLAY_BANNER_HEIGHT + DISPLAY_TEXT_BORDER; sRect.sXMax = GrContextDpyWidthGet(&g_sContext) - DISPLAY_TEXT_BORDER; sRect.sYMax = GrContextDpyHeightGet(&g_sContext) - DISPLAY_BANNER_HEIGHT - DISPLAY_TEXT_BORDER; // // Change the foreground color to black and draw black rectangle to // clear the screen. // GrContextForegroundSet(&g_sContext, DISPLAY_TEXT_BG); GrRectFill(&g_sContext, &sRect); // // Reset the foreground color to the text color. // GrContextForegroundSet(&g_sContext, DISPLAY_TEXT_FG); } // // Send the character to the UART. // UARTprintf("%c", ucChar); // // Allow new lines to cause the column to go back to zero. // if(ucChar != '\n') { // // Print the character to the screen. // GrStringDraw(&g_sContext, &ucChar, 1, GrFontMaxWidthGet(g_pFontFixed6x8) * g_ulColumn, DISPLAY_BANNER_HEIGHT + DISPLAY_TEXT_BORDER + (g_ulLine * GrFontHeightGet(g_pFontFixed6x8)), 0); } else { // // This will allow the code below to properly handle the new line. // g_ulColumn = g_ulCharsPerLine; } // // Update the text row and column that the next character will use. // if(g_ulColumn < g_ulCharsPerLine) { // // No line wrap yet so move one column over. // g_ulColumn++; } else { // // Line wrapped so go back to the first column and update the line. // g_ulColumn = 0; g_ulLine++; // // The line has gone past the end so go back to the first line. // if(g_ulLine >= g_ulLinesPerScreen) { g_ulLine = 0; } } }
/** * Write block(s) from MMC/SD card. The implementation follows * '26.3.5 MMC/SD Mode Single-Block Read Operation Using EDMA' in 'spruh82a'. * @param mmcsdCtrlInfo It holds the mmcsd control information. * @param ptr It determines the address from where data has to written * @param block It determines to which block data to be written (block >= 0) * @param nblks It determines the number of blocks to be written (nblks >= 1) * @retval 1 success * @retval 0 fail */ unsigned int MMCSDWriteCmdSend(mmcsdCtrlInfo *ctrl, void *ptr, unsigned int block, unsigned int nblks) { // TODO: workaround for buggy WRITE_MULTI_BLOCK if (nblks > 1) { for (unsigned int i = 0; i < nblks; ++i) { unsigned int res = MMCSDWriteCmdSend(ctrl, ptr + i * MMCSD_MAX_BLOCK_LEN, block + i, 1); assert(res == 1); } return 1; } assert(nblks == 1); unsigned int status = 1; // 1 for success volatile struct st_mmcsd *mmc = ctrl->memBase; ER ercd; /* 1. Write the card's relative address to the MMC argument registers (MMCARGH and MMCARGL). */ mmcsdCardInfo *card = ctrl->card; unsigned int address; /* * TODO: check this -- ertl-liyixiao * Address is in blks for high cap cards and in actual bytes * for standard capacity cards */ assert(card->highCap); if (card->highCap) address = block; else address = block * card->blkLen; mmc->MMCARGHL = address; /* 2. Read card CSD to determine the card's maximum block length. */ // TODO: // syslog(LOG_ERROR, "card->raw_csd[0]: 0x%08x", card->raw_csd[0]); // syslog(LOG_ERROR, "card->raw_csd[1]: 0x%08x", card->raw_csd[1]); // syslog(LOG_ERROR, "card->raw_csd[2]: 0x%08x", card->raw_csd[2]); // syslog(LOG_ERROR, "card->raw_csd[3]: 0x%08x", card->raw_csd[3]); syslog(LOG_ERROR, "MMCCTL: 0x%08x", mmc->MMCCTL); /* 3. Use the MMC command register (MMCCMD) to send the SET_BLOCKLEN command (if the block length is different than the length used in the previous operation). The block length must be a multiple of 512 bytes and less then the maximum block length specified in the CSD. */ syslog(LOG_ERROR, "MMCCTL: 0x%08x", mmc->MMCCTL); syslog(LOG_ERROR, "MMCCLK: 0x%08x", mmc->MMCBLEN); // TODO: /* 4. Reset the FIFO (FIFORST bit in MMCFIFOCTL). */ mmc->MMCFIFOCTL |= MMCSD_MMCFIFOCTL_FIFORST; mmc->MMCFIFOCTL &= ~MMCSD_MMCFIFOCTL_FIFORST; /* 5. Set the FIFO direction to send (FIFODIR bit in MMCFIFOCTL). */ mmc->MMCFIFOCTL |= MMCSD_MMCFIFOCTL_FIFODIR; /* 6. Set the access width (ACCWD bits in MMCFIFOCTL). */ mmc->MMCFIFOCTL &= ~MMCSD_MMCFIFOCTL_ACCWD; mmc->MMCFIFOCTL |= (MMCSD_MMCFIFOCTL_ACCWD_4BYTES << MMCSD_MMCFIFOCTL_ACCWD_SHIFT); // => 4 bytes /* 7. Set the FIFO threshold (FIFOLEV bit in MMCFIFOCTL). */ mmc->MMCFIFOCTL |= MMCSD_MMCFIFOCTL_FIFOLEV; // => 64 bytes /* 8. Set up DMA (DMA size needs to be greater than or equal to FIFOLEV setting). */ CacheDataCleanBuff((unsigned int) ptr, (MMCSD_MAX_BLOCK_LEN * nblks)); // Clean data buffer to send arm926_drain_write_buffer(); // Memory barrier for data buffer to send ctrl->xferSetup(ctrl, 0, ptr, MMCSD_MAX_BLOCK_LEN, nblks); { syslog(LOG_ERROR, "origSrcAddr: 0x%08x", ptr); EDMA3CCPaRAMEntry param; EDMA3GetPaRAM(&EDMA3_CC0, EDMA3_CHA_MMCSD0_TX, ¶m); syslog(LOG_ERROR, "srcAddr: 0x%08x", param.srcAddr); } /* 9. Use MMCCMD to send the WRITE_BLOCK command to the card. */ #if defined(DEBUG) syslog(LOG_ERROR, "%s(): Use MMCCMD to send the WRITE_BLOCK/WRITE_MULTI_BLOCK command to the card.", __FUNCTION__); #endif mmcsdCmd cmd; cmd.flags = SD_CMDRSP_R1 | SD_CMDRSP_WRITE | SD_CMDRSP_DATA; cmd.arg = address; cmd.nblks = nblks; if (nblks > 1) { cmd.idx = SD_CMD(25); cmd.flags |= SD_CMDRSP_ABORT; } else { cmd.idx = SD_CMD(24); } status = MMCSDCmdSend(ctrl, &cmd); if (status == 0) { syslog(LOG_ERROR, "%s(): MMCSDCmdSend() failed.", __FUNCTION__); goto error_exit; } // CPU Mode // uint32_t *buf = ptr; // Assume uint32_t is little-endian // while (1) { // EDMA3CCPaRAMEntry param; //// syslog(LOG_ERROR, "MMCSD0.MMCST0: 0x%08x", MMCSD0.MMCST0); //// syslog(LOG_ERROR, "MMCSD0.MMCST1: 0x%08x", MMCSD0.MMCST1); //// syslog(LOG_ERROR, "EDMA3_CC0.ER: 0x%08x", EDMA3_CC0.ER); //// syslog(LOG_ERROR, "EDMA3_CC0.EMR: 0x%08x", EDMA3_CC0.EMR); //// syslog(LOG_ERROR, "EDMA3_CC0.SER: 0x%08x", EDMA3_CC0.SER); // EDMA3GetPaRAM(&EDMA3_CC0, EDMA3_CHA_MMCSD0_TX, ¶m); //// syslog(LOG_ERROR, "origSrcAddr: 0x%08x", ptr); // syslog(LOG_ERROR, "srcAddr: 0x%08x", param.srcAddr); //// syslog(LOG_ERROR, "CCNT: %d", param.cCnt); // // tslp_tsk(1000); // } /* 10. Set the DMATRIG bit in MMCCMD to trigger the first data transfer. */ #if DEBUG_PRINT // syslog(LOG_ERROR, "%s(): Set the DMATRIG bit, MMCCMD: 0x%08x=>0x%08x", __FUNCTION__, mmc->MMCCMD, mmc->MMCCMD | MMCSD_MMCCMD_DMATRIG); #endif // mmc->MMCCMD /*|*/= MMCSD_MMCCMD_DMATRIG; /* 11. Wait for DMA sequence to complete. */ status = ctrl->xferStatusGet(ctrl); if (status == 0) { assert(false); goto error_exit; } error_exit: return status; #if 0 mmcsdCardInfo *card = ctrl->card; unsigned int status = 0; unsigned int address; mmcsdCmd cmd; #if DEBUG_PRINT UARTprintf("----\r\n"); UARTprintf("%s(0x%x)\r\n", __FUNCTION__, ctrl); #endif }
//***************************************************************************** // // This is the main loop that runs the application. // //***************************************************************************** int main(void) { tRectangle sRect; // // Set the clocking to run directly from the crystal. // SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_8MHZ); // // Enable the peripherals used by this example. // SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0); SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB); // // Configure the relevant pins such that UART0 owns them. // SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA); GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1); // // Open UART0 for debug output. // UARTStdioInit(0); // // Enable the USB mux GPIO. // SysCtlPeripheralEnable(USB_MUX_GPIO_PERIPH); // // The LM3S3748 board uses a USB mux that must be switched to use the // host connector and not the device connector. // GPIOPinTypeGPIOOutput(USB_MUX_GPIO_BASE, USB_MUX_GPIO_PIN); GPIOPinWrite(USB_MUX_GPIO_BASE, USB_MUX_GPIO_PIN, USB_MUX_SEL_HOST); // // Configure the power pins for host controller. // GPIOPinTypeUSBDigital(GPIO_PORTH_BASE, GPIO_PIN_3 | GPIO_PIN_4); // // Initialize the display driver. // Formike128x128x16Init(); // // Turn on the backlight. // Formike128x128x16BacklightOn(); // // Initialize the graphics context. // GrContextInit(&g_sContext, &g_sFormike128x128x16); // // Fill the top 15 rows of the screen with blue to create the banner. // sRect.sXMin = 0; sRect.sYMin = 0; sRect.sXMax = GrContextDpyWidthGet(&g_sContext) - 1; sRect.sYMax = DISPLAY_BANNER_HEIGHT; GrContextForegroundSet(&g_sContext, DISPLAY_BANNER_BG); GrRectFill(&g_sContext, &sRect); // // Put a white box around the banner. // GrContextForegroundSet(&g_sContext, ClrWhite); GrRectDraw(&g_sContext, &sRect); // // Put the application name in the middle of the banner. // GrContextFontSet(&g_sContext, g_pFontFixed6x8); GrStringDrawCentered(&g_sContext, "usb_host_keyboard", -1, GrContextDpyWidthGet(&g_sContext) / 2, 7, 0); // // Calculate the number of characters that will fit on a line. // Make sure to leave a small border for the text box. // g_ulCharsPerLine = (GrContextDpyWidthGet(&g_sContext) - 4) / GrFontMaxWidthGet(g_pFontFixed6x8); // // Calculate the number of lines per usable text screen. This requires // taking off space for the top and bottom banners and adding a small bit // for a border. // g_ulLinesPerScreen = (GrContextDpyHeightGet(&g_sContext) - (2*(DISPLAY_BANNER_HEIGHT + 1)))/ GrFontHeightGet(g_pFontFixed6x8); // // Register the host class drivers. // USBHCDRegisterDrivers(0, g_ppHostClassDrivers, g_ulNumHostClassDrivers); // // Open and instance of the keyboard class driver. // UARTprintf("Host Keyboard Application\n"); // // Open an instance of the keyboard driver. The keyboard does not need // to be present at this time, this just save a place for it and allows // the applications to be notified when a keyboard is present. // g_ulKeyboardInstance = USBHKeyboardOpen(KeyboardCallback, g_pucBuffer, KEYBOARD_MEMORY_SIZE); // // Initialize the power configuration. This sets the power enable signal // to be active high and does not enable the power fault. // USBHCDPowerConfigInit(0, USBHCD_VBUS_AUTO_HIGH); // // Initialize the host controller stack. // USBHCDInit(0, g_pHCDPool, HCD_MEMORY_SIZE); // // Call the main loop for the Host controller driver. // USBHCDMain(); // // Initial update of the screen. // UpdateStatus(); // // The main loop for the application. // while(1) { switch(g_eUSBState) { // // This state is entered when they keyboard is first detected. // case STATE_KEYBOARD_INIT: { // // Initialized the newly connected keyboard. // USBHKeyboardInit(g_ulKeyboardInstance); // // Proceed to the keyboard connected state. // g_eUSBState = STATE_KEYBOARD_CONNECTED; USBHKeyboardModifierSet(g_ulKeyboardInstance, g_ulModifiers); // // Update the screen now that the keyboard has been // initialized. // UpdateStatus(); break; } case STATE_KEYBOARD_UPDATE: { // // If the application detected a change that required an // update to be sent to the keyboard to change the modifier // state then call it and return to the connected state. // g_eUSBState = STATE_KEYBOARD_CONNECTED; USBHKeyboardModifierSet(g_ulKeyboardInstance, g_ulModifiers); break; } case STATE_KEYBOARD_CONNECTED: { // // Nothing is currently done in the main loop when the keyboard // is connected. // break; } case STATE_UNKNOWN_DEVICE: { // // Nothing to do as the device is unknown. // break; } case STATE_NO_DEVICE: { // // Nothing is currently done in the main loop when the keyboard // is not connected. // break; } default: { break; } } // // Periodic call the main loop for the Host controller driver. // USBHCDMain(); } }
//***************************************************************************** // // Handles bulk driver notifications related to the receive channel (data from // the USB host). // // \param pvCBData is the client-supplied callback pointer for this channel. // \param ulEvent identifies the event that has been sent. // \param ulMsgValue is an event-specific value. // \param pvMsgData is an event-specific pointer. // // This function is called by the bulk driver to notify us of any events // related to operation of the receive data channel (the OUT channel carrying // data from the USB host). // // \return The return value is event-specific. // //***************************************************************************** unsigned long RxHandler(void *pvCBData, unsigned long ulEvent, unsigned long ulMsgValue, void *pvMsgData) { // // Which event was sent? // switch(ulEvent) { // // The host has connected. // case USB_EVENT_CONNECTED: { g_bUSBConfigured = true; UARTprintf("Host connected.\n"); // // Flush our buffers. // USBBufferFlush(&g_sTxBuffer); USBBufferFlush(&g_sRxBuffer); break; } // // The host has disconnected. // case USB_EVENT_DISCONNECTED: { g_bUSBConfigured = false; UARTprintf("Host disconnected.\n"); break; } // // A new packet has been received. // case USB_EVENT_RX_AVAILABLE: { tUSBDBulkDevice *psDevice; // // Get a pointer to our instance data from the callback data // parameter. // psDevice = (tUSBDBulkDevice *)pvCBData; // // Read the new packet and echo it back to the host. // return(EchoNewDataToHost(psDevice, pvMsgData, ulMsgValue)); } // // Ignore SUSPEND and RESUME for now. // case USB_EVENT_SUSPEND: case USB_EVENT_RESUME: { break; } // // Ignore all other events and return 0. // default: { break; } } return(0); }
//***************************************************************************** // // Configure Timer0B as a 16-bit one-shot counter with a single interrupt // after 1ms. // //***************************************************************************** int main(void) { // // Set the clocking to run directly from the external crystal/oscillator. // TODO: The SYSCTL_XTAL_ value must be changed to match the value of the // crystal on your board. // SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // // The Timer0 peripheral must be enabled for use. // SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0); // // Set up the serial console to use for displaying messages. This is // just for this example program and is not needed for Timer operation. // InitConsole(); // // Display the example setup on the console. // UARTprintf("16-Bit Timer Interrupt ->"); UARTprintf("\n Timer = Timer0B"); UARTprintf("\n Mode = One Shot"); UARTprintf("\n Rate = 1ms"); // // The Timer0 peripheral must be enabled for use. // TimerConfigure(TIMER0_BASE, TIMER_CFG_16_BIT_PAIR | TIMER_CFG_B_ONE_SHOT); // // Set the Timer0B load value to 1ms. // TimerLoadSet(TIMER0_BASE, TIMER_B, SysCtlClockGet() / 1000); // // Enable processor interrupts. // IntMasterEnable(); // // Configure the Timer0B interrupt for timer timeout. // TimerIntEnable(TIMER0_BASE, TIMER_TIMB_TIMEOUT); // // Enable the Timer0B interrupt on the processor (NVIC). // IntEnable(INT_TIMER0B); // // Enable Timer0B. // TimerEnable(TIMER0_BASE, TIMER_B); // // Wait for interrupt to occur // while(!g_ulIntFlag) { } // // Display a message indicating that the one shot interrupt was received. // UARTprintf("\n\nOne shot timer interrupt received."); // // Loop forever. // while(1) { } }
//***************************************************************************** // // This is the main application entry function. // //***************************************************************************** int main(void) { unsigned long ulTxCount; unsigned long ulRxCount; // // Set the clocking to run from the PLL at 50MHz // ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // // Enable the UART. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA); GPIOPinConfigure(GPIO_PA0_U0RX); GPIOPinConfigure(GPIO_PA1_U0TX); ROM_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1); UARTStdioInit(0); UARTprintf("\033[2JBulk device application\n"); // // Not configured initially. // g_bUSBConfigured = false; // // Enable the system tick. // ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / SYSTICKS_PER_SECOND); ROM_SysTickIntEnable(); ROM_SysTickEnable(); // // Initialize the transmit and receive buffers. // USBBufferInit(&g_sTxBuffer); USBBufferInit(&g_sRxBuffer); // // Set the USB stack mode to Device mode with VBUS monitoring. // USBStackModeSet(0, USB_MODE_DEVICE, 0); // // Pass our device information to the USB library and place the device // on the bus. // USBDBulkInit(0, &g_sBulkDevice); // // Wait for initial configuration to complete. // UARTprintf("Waiting for host...\n"); // // Clear our local byte counters. // ulRxCount = 0; ulTxCount = 0; // // Main application loop. // while(1) { // // See if any data has been transferred. // if((ulTxCount != g_ulTxCount) || (ulRxCount != g_ulRxCount)) { // // Take a snapshot of the latest transmit and receive counts. // ulTxCount = g_ulTxCount; ulRxCount = g_ulRxCount; // // Update the display of bytes transferred. // UARTprintf("\rTx: %d Rx: %d", ulTxCount, ulRxCount); } } }
/** * \brief This function sends the command to MMCSD. * * \param mmcsdCtrlInfo It holds the mmcsd control information. * * \param mmcsdCmd It determines the mmcsd cmd * * \return status of the command. * **/ unsigned int MMCSDLibCmdSend(mmcsdCtrlInfo *ctrl, mmcsdCmd *c) { unsigned int cmdType = MMCSD_CMD_TYPE_NORMAL; unsigned int dataPresent; unsigned int status = 0; unsigned int rspType; unsigned int cmdDir; unsigned int nblks; unsigned int cmd; #if DEBUG_PRINT // UARTprintf("%s(0x%p,0x%x=%d):", __FUNCTION__, ctrl, c->idx, c->idx); syslog(LOG_ERROR, "%s(0x%p,CMD%d):", __FUNCTION__, ctrl, c->idx); #endif if (c->flags & SD_CMDRSP_STOP) { cmdType = MMCSD_CMD_TYPE_SUSPEND; } else if (c->flags & SD_CMDRSP_FS) { cmdType = MMCSD_CMD_TYPE_FUNCSEL; } else if (c->flags & SD_CMDRSP_ABORT) { cmdType = MMCSD_CMD_TYPE_ABORT; } cmdDir = (c->flags & SD_CMDRSP_READ) ? MMCSD_CMD_DIR_READ : MMCSD_CMD_DIR_WRITE; dataPresent = (c->flags & SD_CMDRSP_DATA) ? 1 : 0; nblks = (dataPresent == 1) ? c->nblks : 0; #if DEBUG_PRINT UARTprintf("dir=%d,dp=%d,nblks=%d,",cmdDir,dataPresent,nblks); #endif if (c->flags & SD_CMDRSP_NONE) rspType = MMCSD_NO_RESPONSE; else if (c->flags & SD_CMDRSP_R1) rspType = MMCSD_R1_RESPONSE; else if (c->flags & SD_CMDRSP_R2) rspType = MMCSD_R2_RESPONSE; else if (c->flags & SD_CMDRSP_R3) rspType = MMCSD_R3_RESPONSE; else if (c->flags & SD_CMDRSP_R4) rspType = MMCSD_R4_RESPONSE; else if (c->flags & SD_CMDRSP_R5) rspType = MMCSD_R5_RESPONSE; else if (c->flags & SD_CMDRSP_R6) rspType = MMCSD_R6_RESPONSE; else if (c->flags & SD_CMDRSP_R7) rspType = MMCSD_R7_RESPONSE; else rspType = MMCSD_R1_RESPONSE; /* Assumes R1? */ if (c->flags & SD_CMDRSP_BUSY) rspType |= MMCSD_BUSY_RESPONSE; cmd = MMCSD_CMD(c->idx, cmdType, rspType, cmdDir); #if DEBUG_PRINT UARTprintf("rspType=%d,cmd=0x%x,arg=0x%x\r\n", rspType>>MMCSD_MMCCMD_RSPFMT_SHIFT,cmd,c->arg); #endif /* Shouldn't I do this every time? Everything below depends on the IRQs */ if (dataPresent) { #if DEBUG_PRINT unsigned int s; s = #endif MMCSDIntrStatusGetAndClr(ctrl->memBase); #if DEBUG_PRINT UARTprintf("%s(0x%p,0x%x):status=0x%x\r\n", __FUNCTION__, ctrl, c->idx, s); #endif } /* Start send. Status bits will get updated. Hopefully. */ /* This function sets MMCSD_MMCNBLK */ MMCSDCommandSend(ctrl->memBase, cmd, c->arg, (void*)dataPresent, nblks, ctrl->dmaEnable); /* Note that status does not changed unless there is a cmdStatusGet */ /* function. Intended? */ if (ctrl->cmdStatusGet) { /* This function will block until response is available. */ status = ctrl->cmdStatusGet(ctrl); } if (status == 1) { MMCSDResponseGet(ctrl->memBase, c->rsp); #if defined(DEBUG) // UARTprintf("%s(0x%p,0x%x):0x%08x,0x%08x,0x%08x,0x%08x\r\n", // __FUNCTION__, ctrl, c->idx, // c->rsp[0],c->rsp[1], c->rsp[2], c->rsp[3]); switch(rspType) { case MMCSD_R1_RESPONSE: syslog(LOG_ERROR, "%s() R1:status=0x%08x", __FUNCTION__, c->rsp[0]); break; case MMCSD_R1_RESPONSE | MMCSD_BUSY_RESPONSE: syslog(LOG_ERROR, "%s() R1b:status=0x%08x", __FUNCTION__, c->rsp[0]); break; default: syslog(LOG_ERROR, "%s(): Unknown response", __FUNCTION__); } #endif } return status; }
//***************************************************************************** // // This task reads the buttons' state and passes this information to LEDTask. // //***************************************************************************** static void SwitchTask(void *pvParameters) { portTickType ulLastTime; unsigned long ulSwitchDelay = 25; unsigned char ucCurButtonState, ucPrevButtonState; unsigned char ucMessage; ucCurButtonState = ucPrevButtonState = 0; // // Get the current tick count. // ulLastTime = xTaskGetTickCount(); // // Loop forever. // while(1) { // // Poll the debounced state of the buttons. // ucCurButtonState = ButtonsPoll(0, 0); // // Check if previous debounced state is equal to the current state. // if(ucCurButtonState != ucPrevButtonState) { ucPrevButtonState = ucCurButtonState; // // Check to make sure the change in state is due to button press // and not due to button release. // if((ucCurButtonState & ALL_BUTTONS) != 0) { if((ucCurButtonState & ALL_BUTTONS) == LEFT_BUTTON) { ucMessage = LEFT_BUTTON; // // Guard UART from concurrent access. // xSemaphoreTake(g_pUARTSemaphore, portMAX_DELAY); UARTprintf("Left Button is pressed.\n"); xSemaphoreGive(g_pUARTSemaphore); } else if((ucCurButtonState & ALL_BUTTONS) == RIGHT_BUTTON) { ucMessage = RIGHT_BUTTON; // // Guard UART from concurrent access. // xSemaphoreTake(g_pUARTSemaphore, portMAX_DELAY); UARTprintf("Right Button is pressed.\n"); xSemaphoreGive(g_pUARTSemaphore); } // // Pass the value of the button pressed to LEDTask. // if(xQueueSend(g_pLEDQueue, &ucMessage, portMAX_DELAY) != pdPASS) { // // Error. The queue should never be full. If so print the // error message on UART and wait for ever. // UARTprintf("\nQueue full. This should never happen.\n"); while(1) { } } } } // // Wait for the required amount of time to check back. // vTaskDelayUntil(&ulLastTime, ulSwitchDelay / portTICK_RATE_MS); } }
//***************************************************************************** // // Configure the CAN and enter a loop to transmit periodic CAN messages. // //***************************************************************************** int main(void) { // // Set the clocking to run directly from the external crystal/oscillator. // TODO: The SYSCTL_XTAL_ value must be changed to match the value of the // crystal on your board. // SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // // Set up the serial console to use for displaying messages. This is // just for this example program and is not needed for CAN operation. // InitConsole(); // // For this example CAN0 is used with RX and TX pins on port B4 and B5. // The actual port and pins used may be different on your part, consult // the data sheet for more information. // GPIO port B needs to be enabled so these pins can be used. // TODO: change this to whichever GPIO port you are using // SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB); // // Configure the GPIO pin muxing to select CAN0 functions for these pins. // This step selects which alternate function is available for these pins. // This is necessary if your part supports GPIO pin function muxing. // Consult the data sheet to see which functions are allocated per pin. // TODO: change this to select the port/pin you are using // GPIOPinConfigure(GPIO_PB4_CAN0RX); GPIOPinConfigure(GPIO_PB5_CAN0TX); // // Enable the alternate function on the GPIO pins. The above step selects // which alternate function is available. This step actually enables the // alternate function instead of GPIO for these pins. // TODO: change this to match the port/pin you are using // GPIOPinTypeCAN(GPIO_PORTB_BASE, GPIO_PIN_4 | GPIO_PIN_5); // // The GPIO port and pins have been set up for CAN. The CAN peripheral // must be enabled. // SysCtlPeripheralEnable(SYSCTL_PERIPH_CAN0); // // Initialize the CAN controller // CANInit(CAN0_BASE); // // Set up the bit rate for the CAN bus. This function sets up the CAN // bus timing for a nominal configuration. You can achieve more control // over the CAN bus timing by using the function CANBitTimingSet() instead // of this one, if needed. // In this example, the CAN bus is set to 500 kHz. In the function below, // the call to SysCtlClockGet() is used to determine the clock rate that // is used for clocking the CAN peripheral. This can be replaced with a // fixed value if you know the value of the system clock, saving the extra // function call. For some parts, the CAN peripheral is clocked by a fixed // 8 MHz regardless of the system clock in which case the call to // SysCtlClockGet() should be replaced with 8000000. Consult the data // sheet for more information about CAN peripheral clocking. // CANBitRateSet(CAN0_BASE, SysCtlClockGet(), 500000); // // Enable interrupts on the CAN peripheral. This example uses static // allocation of interrupt handlers which means the name of the handler // is in the vector table of startup code. If you want to use dynamic // allocation of the vector table, then you must also call CANIntRegister() // here. // // CANIntRegister(CAN0_BASE, CANIntHandler); // if using dynamic vectors // CANIntEnable(CAN0_BASE, CAN_INT_MASTER | CAN_INT_ERROR | CAN_INT_STATUS); // // Enable the CAN interrupt on the processor (NVIC). // IntEnable(INT_CAN0); // // Enable the CAN for operation. // CANEnable(CAN0_BASE); // // Initialize the message object that will be used for sending CAN // messages. The message will be 4 bytes that will contain an incrementing // value. Initially it will be set to 0. // // // Initialize message object 1 to be able to send CAN message 1. This // message object is not shared so it only needs to be initialized one // time, and can be used for repeatedly sending the same message ID. // g_sCANMsgObject1.ui32MsgID = 0x1001; g_sCANMsgObject1.ui32MsgIDMask = 0; g_sCANMsgObject1.ui32Flags = MSG_OBJ_TX_INT_ENABLE; g_sCANMsgObject1.ui32MsgLen = sizeof(g_pui8Msg1); g_sCANMsgObject1.pui8MsgData = g_pui8Msg1; // // Initialize message object 2 to be able to send CAN message 2. This // message object is not shared so it only needs to be initialized one // time, and can be used for repeatedly sending the same message ID. // g_sCANMsgObject2.ui32MsgID = 0x2001; g_sCANMsgObject2.ui32MsgIDMask = 0; g_sCANMsgObject2.ui32Flags = MSG_OBJ_TX_INT_ENABLE; g_sCANMsgObject2.ui32MsgLen = sizeof(g_pui8Msg2); g_sCANMsgObject2.pui8MsgData = g_pui8Msg2; // // Enter loop to send messages. Four messages will be sent once per // second. The contents of each message will be changed each time. // for(;;) { // // Send message 1 using CAN controller message object 1. This is // the only message sent using this message object. The // CANMessageSet() function will cause the message to be sent right // away. // PrintCANMessageInfo(&g_sCANMsgObject1, 1); CANMessageSet(CAN0_BASE, 1, &g_sCANMsgObject1, MSG_OBJ_TYPE_TX); // // Send message 2 using CAN controller message object 2. This is // the only message sent using this message object. The // CANMessageSet() function will cause the message to be sent right // away. // PrintCANMessageInfo(&g_sCANMsgObject2, 2); CANMessageSet(CAN0_BASE, 2, &g_sCANMsgObject2, MSG_OBJ_TYPE_TX); // // Load message object 3 with message 3. This is needs to be done each // time because message object 3 is being shared for two different // messages. // g_sCANMsgObject3.ui32MsgID = 0x3001; g_sCANMsgObject3.ui32MsgIDMask = 0; g_sCANMsgObject3.ui32Flags = MSG_OBJ_TX_INT_ENABLE; g_sCANMsgObject3.ui32MsgLen = sizeof(g_pui8Msg3); g_sCANMsgObject3.pui8MsgData = g_pui8Msg3; // // Clear the flag that indicates that message 3 has been sent. This // flag will be set in the interrupt handler when a message has been // sent using message object 3. // g_bMsgObj3Sent = 0; // // Now send message 3 using CAN controller message object 3. This is // the first message sent using this message object. The // CANMessageSet() function will cause the message to be sent right // away. // PrintCANMessageInfo(&g_sCANMsgObject3, 3); CANMessageSet(CAN0_BASE, 3, &g_sCANMsgObject3, MSG_OBJ_TYPE_TX); // // Wait for the indication from the interrupt handler that message // object 3 is done, because we are re-using it for another message. // while(!g_bMsgObj3Sent) { } // // Load message object 3 with message 4. This is needed because // message object 3 is being shared for two different messages. // g_sCANMsgObject3.ui32MsgID = 0x3002; g_sCANMsgObject3.ui32MsgIDMask = 0; g_sCANMsgObject3.ui32Flags = MSG_OBJ_TX_INT_ENABLE; g_sCANMsgObject3.ui32MsgLen = sizeof(g_pui8Msg4); g_sCANMsgObject3.pui8MsgData = g_pui8Msg4; // // Now send message 4 using CAN controller message object 3. This is // the second message sent using this message object. The // CANMessageSet() function will cause the message to be sent right // away. // PrintCANMessageInfo(&g_sCANMsgObject3, 3); CANMessageSet(CAN0_BASE, 3, &g_sCANMsgObject3, MSG_OBJ_TYPE_TX); // // Wait 1 second before continuing // SimpleDelay(); // // Check the error flag to see if errors occurred // if(g_bErrFlag) { UARTprintf(" error - cable connected?\n"); } else { // // If no errors then print the count of message sent // UARTprintf(" total count = %u\n", g_ui32Msg1Count + g_ui32Msg2Count + g_ui32Msg3Count); } // // Change the value in the message data for each of the messages. // (*(uint32_t *)g_pui8Msg1)++; (*(uint32_t *)g_pui8Msg2)++; (*(uint32_t *)g_pui8Msg3)++; (*(uint32_t *)&g_pui8Msg4[0])++; (*(uint32_t *)&g_pui8Msg4[4])--; } // // Return no errors // return(0); }
void alarmState(void) { /* Enter accurate button OFF value here */ while(temp[0] > 35) //Till User Doesn't Press the button { UARTprintf("ALARM TRIGGERED\n"); for(i=0; i<=800000;i++) { /*Configure ADC Peripheral for READING THE BUTTON*/ /*Configure ADC Sequence*/ ADCSequenceConfigure(ADC0_BASE, 0, ADC_TRIGGER_PROCESSOR, 0); /*Enable ADC sequence*/ ADCSequenceDisable(ADC0_BASE, 0); SysCtlDelay(SysCtlClockGet()/10); ADCSequenceEnable(ADC0_BASE, 0); /*Clear ADC Interrupt*/ ADCIntClear(ADC0_BASE, 0); IntMasterEnable(); ADCSequenceStepConfigure(ADC0_BASE, 0, 0, ADC_CTL_CH0 | ADC_CTL_IE | ADC_CTL_END); ADCProcessorTrigger(ADC0_BASE, 0); while(!ADCIntStatus(ADC0_BASE, 0, false)) { } ADCIntClear(ADC0_BASE, 0); ADCSequenceDataGet(ADC0_BASE, 0, temp); /*Check if button was pressed*/ if(temp[0] < 20) { /*Debounce the button if it IS READ */ for(i=0; i<=2000; i++) { } if(temp[0] > 20) { break; } } /*If button is not pressed the initiate alarm sequence */ GPIOPinWrite(relaycontrolbase, relaycontrolpin, relaycontrolpin); for(i=0; i<=3; i++) { speakerplay(); } GPIOPinWrite(relaycontrolbase, relaycontrolpin, 0); /* Give a missed call using GPS*/ //ENTER GSM MISSED CALL FUNCTION HERE } SysCtlDelay(SysCtlClockGet()); /*If the user doesnt PRESS the button */ if(i == 800000) { UARTprintf("NO REACTION\n"); delay(2000); UARTprintf("SYSTEM STALLED\n"); SysCtlDelay(SysCtlClockGet()/5); /*Send message using GPS*/ //ENTER FUNCTION FOR GSM MESSAGE HERE /*System will stall if driver was unable to push the safe button in stipulated time */ while(1) { GPIOPinWrite(relaycontrolbase, relaycontrolpin, relaycontrolpin); for(i=0; i<=100; i++) { speakerplay(); } GPIOPinWrite(relaycontrolbase, relaycontrolpin, 0); } } UARTprintf("ALARM\n"); delay(2000); UARTprintf("ESCAPED\n"); GPIOPinWrite(relaycontrolbase, relaycontrolpin, 0); SysCtlDelay(SysCtlClockGet()/2); } }
void initsensorhub(void) { // // Enable port B used for motion interrupt. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB); // // Initialize the UART. // ConfigureUART(); // // Print the welcome message to the terminal. // UARTprintf("\033[2JMPU9150 Raw Example\n"); // // Set the color to a purple approximation. // g_pui32Colors[RED] = 0x8000; g_pui32Colors[BLUE] = 0x8000; g_pui32Colors[GREEN] = 0x0000; // // Initialize RGB driver. // RGBInit(0); RGBColorSet(g_pui32Colors); RGBIntensitySet(0.5f); RGBEnable(); // // The I2C3 peripheral must be enabled before use. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C3); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD); // // Configure the pin muxing for I2C3 functions on port D0 and D1. // ROM_GPIOPinConfigure(GPIO_PD0_I2C3SCL); ROM_GPIOPinConfigure(GPIO_PD1_I2C3SDA); // // Select the I2C function for these pins. This function will also // configure the GPIO pins pins for I2C operation, setting them to // open-drain operation with weak pull-ups. Consult the data sheet // to see which functions are allocated per pin. // GPIOPinTypeI2CSCL(GPIO_PORTD_BASE, GPIO_PIN_0); ROM_GPIOPinTypeI2C(GPIO_PORTD_BASE, GPIO_PIN_1); // // Configure and Enable the GPIO interrupt. Used for INT signal from the // MPU9150 // ROM_GPIOPinTypeGPIOInput(GPIO_PORTB_BASE, GPIO_PIN_2); GPIOIntEnable(GPIO_PORTB_BASE, GPIO_PIN_2); ROM_GPIOIntTypeSet(GPIO_PORTB_BASE, GPIO_PIN_2, GPIO_FALLING_EDGE); ROM_IntEnable(INT_GPIOB); // // Keep only some parts of the systems running while in sleep mode. // GPIOB is for the MPU9150 interrupt pin. // UART0 is the virtual serial port // TIMER0, TIMER1 and WTIMER5 are used by the RGB driver // I2C3 is the I2C interface to the ISL29023 // ROM_SysCtlPeripheralClockGating(true); ROM_SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_GPIOB); ROM_SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_UART0); ROM_SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_TIMER0); ROM_SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_TIMER1); ROM_SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_I2C3); ROM_SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_WTIMER5); // // Enable interrupts to the processor. // ROM_IntMasterEnable(); // // Initialize I2C3 peripheral. // I2CMInit(&g_sI2CInst, I2C3_BASE, INT_I2C3, 0xff, 0xff, ROM_SysCtlClockGet()); // // Initialize the MPU9150 Driver. // MPU9150Init(&g_sMPU9150Inst, &g_sI2CInst, MPU9150_I2C_ADDRESS, MPU9150AppCallback, &g_sMPU9150Inst); // // Wait for transaction to complete // MPU9150AppI2CWait(__FILE__, __LINE__); // // Write application specifice sensor configuration such as filter settings // and sensor range settings. // g_sMPU9150Inst.pui8Data[0] = MPU9150_CONFIG_DLPF_CFG_94_98; g_sMPU9150Inst.pui8Data[1] = MPU9150_GYRO_CONFIG_FS_SEL_250; g_sMPU9150Inst.pui8Data[2] = (MPU9150_ACCEL_CONFIG_ACCEL_HPF_5HZ | MPU9150_ACCEL_CONFIG_AFS_SEL_2G); MPU9150Write(&g_sMPU9150Inst, MPU9150_O_CONFIG, g_sMPU9150Inst.pui8Data, 3, MPU9150AppCallback, &g_sMPU9150Inst); // // Wait for transaction to complete // MPU9150AppI2CWait(__FILE__, __LINE__); // // Configure the data ready interrupt pin output of the MPU9150. // g_sMPU9150Inst.pui8Data[0] = MPU9150_INT_PIN_CFG_INT_LEVEL | MPU9150_INT_PIN_CFG_INT_RD_CLEAR | MPU9150_INT_PIN_CFG_LATCH_INT_EN; g_sMPU9150Inst.pui8Data[1] = MPU9150_INT_ENABLE_DATA_RDY_EN; MPU9150Write(&g_sMPU9150Inst, MPU9150_O_INT_PIN_CFG, g_sMPU9150Inst.pui8Data, 2, MPU9150AppCallback, &g_sMPU9150Inst); // // Wait for transaction to complete // MPU9150AppI2CWait(__FILE__, __LINE__); // // Initialize the DCM system. 50 hz sample rate. // accel weight = .2, gyro weight = .8, mag weight = .2 // CompDCMInit(&g_sCompDCMInst, 1.0f / 50.0f, 0.2f, 0.6f, 0.2f); UARTprintf("\033[2J\033[H"); UARTprintf("MPU9150 9-Axis Simple Data Application Example\n\n"); UARTprintf("\033[20GX\033[31G|\033[43GY\033[54G|\033[66GZ\n\n"); UARTprintf("Accel\033[8G|\033[31G|\033[54G|\n\n"); UARTprintf("Gyro\033[8G|\033[31G|\033[54G|\n\n"); UARTprintf("Mag\033[8G|\033[31G|\033[54G|\n\n"); UARTprintf("\n\033[20GRoll\033[31G|\033[43GPitch\033[54G|\033[66GYaw\n\n"); UARTprintf("Eulers\033[8G|\033[31G|\033[54G|\n\n"); UARTprintf("\n\033[17GQ1\033[26G|\033[35GQ2\033[44G|\033[53GQ3\033[62G|" "\033[71GQ4\n\n"); UARTprintf("Q\033[8G|\033[26G|\033[44G|\033[62G|\n\n"); // // Enable blinking indicates config finished successfully // RGBBlinkRateSet(1.0f); // // Initialize convenience pointers that clean up and clarify the code // meaning. We want all the data in a single contiguous array so that // we can make our pretty printing easier later. // pfAccel = pfData; pfGyro = pfData + 3; pfMag = pfData + 6; pfEulers = pfData + 9; pfQuaternion = pfData + 12; }
int main(void) { /*Set the clocking to directly run from the crystal at 8MHz*/ SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN | SYSCTL_XTAL_8MHZ); /* Set the clock for the GPIO Ports */ SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA); SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB); SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOC); SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD); SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE); /*Enable ADC Peripheral*/ SysCtlPeripheralEnable(SYSCTL_PERIPH_ADC0); /* Set the type of the GPIO Pins required */ GPIOPinTypeGPIOOutput(GPIO_PORTC_BASE, GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7); //initialiing the on-board LEDs as outputs GPIOPinTypeGPIOOutput(digital2base, digital2pin); GPIOPinTypeGPIOOutput(digital3base, digital3pin); GPIOPinTypeGPIOOutput(digital4base, digital4pin); GPIOPinTypeGPIOOutput(digital5base, digital5pin); GPIOPinTypeGPIOOutput(digital6base, digital6pin); GPIOPinTypeGPIOOutput(digital7base, digital7pin); GPIOPinTypeGPIOOutput(digital8base, digital8pin); GPIOPinTypeGPIOOutput(digital9base, digital9pin); GPIOPinTypeGPIOOutput(digital10base, digital10pin); GPIOPinTypeGPIOOutput(digital11base, digital11pin); GPIOPinTypeGPIOOutput(digital12base, digital12pin); /* Set the GPIO Pins for the LCD as output */ GPIOPinTypeGPIOOutput(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_4| GPIO_PIN_5| GPIO_PIN_6| GPIO_PIN_7); /*Initialize digital control pins*/ GPIOPinWrite(relaycontrolbase, relaycontrolpin, 0); //relay switch off inside main() function GPIOPinWrite(speakerbase, speakerpin, 0); //speaker off inside main() function /* UART config */ InitConsole(); /* Enable is set low */ GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_6, 0); /* Set up the period for the SysTick timer. The SysTick timer period will be equal to 1ms.*/ SysTickPeriodSet(SysCtlClockGet()/1000); /* Enable SysTick. */ SysTickEnable(); ConfigureLCD(); /*WELCOME SCREEN */ UARTprintf("WELCOME\n"); delay(2000); /*AUTO CALIBRATION OF ACCELEROMETER TO PRESENT STATE ON RESET */ /*start of auto calibration */ /*Configure ADC Peripheral*/ /*Configure ADC Sequence*/ ADCSequenceConfigure(ADC0_BASE, 0, ADC_TRIGGER_PROCESSOR, 0); /*Enable ADC sequence*/ ADCSequenceDisable(ADC0_BASE, 0); SysCtlDelay(SysCtlClockGet()/10); ADCSequenceEnable(ADC0_BASE, 0); /*Clear ADC Interrupt*/ ADCIntClear(ADC0_BASE, 0); IntMasterEnable(); ADCSequenceStepConfigure(ADC0_BASE, 0, 0, ADC_CTL_CH1); ADCSequenceStepConfigure(ADC0_BASE, 0, 1, ADC_CTL_CH3 | ADC_CTL_IE | ADC_CTL_END); ADCProcessorTrigger(ADC0_BASE, 0); while(!ADCIntStatus(ADC0_BASE, 0, false)) { } ADCIntClear(ADC0_BASE, 0); unsigned int i= 0; unsigned long sumx = 0; unsigned long sumz = 0; unsigned int xref = 0; unsigned int zref = 0; SysCtlDelay(SysCtlClockGet()); for(i=0; i<= 100; i++) { SysCtlDelay(SysCtlClockGet()/50); ADCSequenceDataGet(ADC0_BASE, 0, temp); sumx = sumx + temp[1]; sumz = sumz + temp[0]; SysCtlDelay(SysCtlClockGet()/50); } xref = sumx/101; zref = sumz/101; UARTprintf("Xref = \n"); UARTprintf(xref); delay(3000); UARTprintf("Yref = \n"); UARTprintf(yref); delay(3000); /*end of auto calibration */ /*Configure ADC Peripheral*/ /*Configure ADC Sequence FOR READING JUST THE IR SENSOR*/ ADCSequenceConfigure(ADC0_BASE, 0, ADC_TRIGGER_ALWAYS, 0); // 0 for taking 8 samples as 6 channels of ADC are involved /*Enable ADC sequence*/ ADCSequenceDisable(ADC0_BASE, 0); SysCtlDelay(SysCtlClockGet()/10); ADCSequenceEnable(ADC0_BASE, 0); /*Clear ADC Interrupt*/ ADCIntClear(ADC0_BASE, 0); IntMasterEnable(); /* sensors are monitored on an infinite loop */ while(1) { /*Reinitiate blinkcounter*/ blinkcounter = 0; /*Reading just IR sensor values in a loop */ for(i=0; i<= 5; i++) { /*Configure ADC Sequence*/ ADCSequenceConfigure(ADC0_BASE, 0, ADC_TRIGGER_PROCESSOR, 0); /*Enable ADC sequence*/ ADCSequenceDisable(ADC0_BASE, 0); ADCSequenceEnable(ADC0_BASE, 0); /*Clear ADC Interrupt*/ ADCIntClear(ADC0_BASE, 0); IntMasterEnable(); ADCSequenceStepConfigure(ADC0_BASE, 0, 0, ADC_CTL_CH4 | ADC_CTL_IE | ADC_CTL_END); ADCProcessorTrigger(ADC0_BASE, 0); while(!ADCIntStatus(ADC0_BASE, 0, false)) { } ADCIntClear(ADC0_BASE, 0); ADCSequenceDataGet(ADC0_BASE, 0, temp); if(temp[0] < 1000) { blinkcounter++; } UARTprintf("IR value %04d\n", temp[0]); SysCtlDelay(SysCtlClockGet()/5); } /*Configure ADC Sample Collection from 4 Channels READ ALL OTHER SENSORS*/ ADCSequenceStepConfigure(ADC0_BASE, 0, 0, ADC_CTL_CH0); //button ADCSequenceStepConfigure(ADC0_BASE, 0, 1, ADC_CTL_CH1); //z axis ADCSequenceStepConfigure(ADC0_BASE, 0, 2, ADC_CTL_CH3); // x axis ADCSequenceStepConfigure(ADC0_BASE, 0, 3, ADC_CTL_CH5 | ADC_CTL_IE | ADC_CTL_END); //alcohol // For ADC Processor Triggering ADCProcessorTrigger(ADC0_BASE, 0); while(!ADCIntStatus(ADC0_BASE, 0, false)) { } ADCIntClear(ADC0_BASE, 0); /*assign sensor values to sensor variables */ alcoholsense = temp[3]; xval = temp[2]; zval = temp[1]; butval = temp[0]; UARTprintf("Xval = %04d\n",xval); SysCtlDelay(SysCtlClockGet()/3); UARTprintf("Yval = %04d\n", yval); SysCtlDelay(SysCtlClockGet()/3); UARTprintf("AlcoholVal = %04d\n",alcoholsense); SysCtlDelay(SysCtlClockGet()/3); UARTprintf("ButtonVal %04d\n", butval); SysCtlDelay(SysCtlClockGet()/3); /*calculate instataneous deviaton from reference values for head tilting */ deltax = abs(xref - xval); deltaz = abs(zref - zval); UARTprintf("Z DELTA = %04d\n", deltaz); SysCtlDelay(SysCtlClockGet()/3); UARTprintf("X DELTA = %04d\n", deltax); SysCtlDelay(SysCtlClockGet()/3); //Check first for alcohol detection. Completely shutdown the system. Alarm will constantly ring. if(alcoholsense > 1000) { UARTprintf("Alcohol\n"); UARTprintf("Present\n"); delay(1000); UARTprintf("Alarm\n"); UARTprintf("Triggered\n"); SysCtlDelay(SysCtlClockGet()/2); alcoholdetected(); } // Check for eyes being closed or blinking at a very fast rate or partially closed for long. if(blinkcounter >= 4) { UARTprintf("Fatigued State"); delay(2000); UARTprintf("Alarm Triggered"); delay(1000); SysCtlDelay(SysCtlClockGet()/2); alarmState(); } /*Check for accelerometer alert state*/ /*Reinitiate accelerometer Counter */ counter = 0; /*If one of the values in head position differs from auto calibrated values, re-sensing is done */ if((deltax >= 70) || (deltaz >= 70)) { for(count = 0; count <= 10; count++) { /*Configure ADC Sequence just for the accelerometer */ ADCSequenceConfigure(ADC0_BASE, 0, ADC_TRIGGER_PROCESSOR, 0); /*Enable ADC sequence*/ ADCSequenceDisable(ADC0_BASE, 0); SysCtlDelay(SysCtlClockGet()/10); ADCSequenceEnable(ADC0_BASE, 0); /*Clear ADC Interrupt*/ ADCIntClear(ADC0_BASE, 0); IntMasterEnable(); ADCSequenceStepConfigure(ADC0_BASE, 0, 0, ADC_CTL_CH1); ADCSequenceStepConfigure(ADC0_BASE, 0, 1, ADC_CTL_CH3 | ADC_CTL_IE | ADC_CTL_END); ADCProcessorTrigger(ADC0_BASE, 0); while(!ADCIntStatus(ADC0_BASE, 0, false)) { } ADCIntClear(ADC0_BASE, 0); ADCSequenceDataGet(ADC0_BASE, 0, temp); deltax = abs(xref - temp[1]); deltaz = abs(zref - temp[0]); if((deltax >= 70) || (deltaz >= 70)) { counter++; SysCtlDelay(SysCtlClockGet()/5); } } } if (counter >= 7) { UARTprintf("Head Tilted"); delay(2000); UARTprintf("ALARM Triggered"); SysCtlDelay(SysCtlClockGet()/2); alarmState(); } else { UARTprintf("NO ALARM DETECTED"); delay(1000); SysCtlDelay(SysCtlClockGet()/5); } } return 0; }
//***************************************************************************** // // Required by lwIP library to support any host-related timer functions. // //***************************************************************************** void lwIPHostTimerHandler(void) { uint32_t ui32Idx, ui32NewIPAddress; // // Get the current IP address. // ui32NewIPAddress = lwIPLocalIPAddrGet(); // // See if the IP address has changed. // if(ui32NewIPAddress != g_ui32IPAddress) { // // See if there is an IP address assigned. // if(ui32NewIPAddress == 0xffffffff) { // // Indicate that there is no link. // UARTprintf("Waiting for link.\n"); } else if(ui32NewIPAddress == 0) { // // There is no IP address, so indicate that the DHCP process is // running. // UARTprintf("Waiting for IP address.\n"); } else { // // Display the new IP address. // //UARTprintf("IP Address: "); //DisplayIPAddress(ui32NewIPAddress); //UARTprintf("\nOpen a browser and enter the IP address.\n"); } // // Save the new IP address. // g_ui32IPAddress = ui32NewIPAddress; // // Turn GPIO off. // MAP_GPIOPinWrite(GPIO_PORTN_BASE, GPIO_PIN_1, ~GPIO_PIN_1); } // // If there is not an IP address. // if((ui32NewIPAddress == 0) || (ui32NewIPAddress == 0xffffffff)) { // // Loop through the LED animation. // for(ui32Idx = 1; ui32Idx < 17; ui32Idx++) { // // Toggle the GPIO // MAP_GPIOPinWrite(GPIO_PORTN_BASE, GPIO_PIN_1, (MAP_GPIOPinRead(GPIO_PORTN_BASE, GPIO_PIN_1) ^ GPIO_PIN_1)); SysCtlDelay(120000000/(ui32Idx << 1)); } } }
// // Cmd_ls - This function implements the "ls" command. It opens the current // directory and enumerates through the contents, and prints a line // for each item it finds. It shows details such as file attributes, // time and date, and the file size, along with the name. It shows a // summary of file sizes at the end along with free space. // int Cmd_ls(int argc, char *argv[]) { unsigned long ulTotalSize, ulItemCount, ulFileCount, ulDirCount; FRESULT fresult; FATFS *pFatFs; // // Open the current directory for access. // fresult = f_opendir(&g_sDirObject, g_cCwdBuf); // // Check for error and return if there is a problem. // if(fresult != FR_OK) { return(fresult); } ulTotalSize = 0; ulFileCount = 0; ulDirCount = 0; ulItemCount = 0; // // Give an extra blank line before the listing. // UARTprintf("\n"); // // Enter loop to enumerate through all directory entries. // for(;;) { // // Read an entry from the directory. // fresult = f_readdir(&g_sDirObject, &g_sFileInfo); // // Check for error and return if there is a problem. // if(fresult != FR_OK) { return(fresult); } // // If the file name is blank, then this is the end of the // listing. // if(!g_sFileInfo.fname[0]) { break; } // // Print the entry information on a single line with formatting // to show the attributes, date, time, size, and name. // UARTprintf("%c%c%c%c%c %u/%02u/%02u %02u:%02u %9u %s\n", (g_sFileInfo.fattrib & AM_DIR) ? (uint32_t)'D' : (uint32_t)'-', (g_sFileInfo.fattrib & AM_RDO) ? (uint32_t)'R' : (uint32_t)'-', (g_sFileInfo.fattrib & AM_HID) ? (uint32_t)'H' : (uint32_t)'-', (g_sFileInfo.fattrib & AM_SYS) ? (uint32_t)'S' : (uint32_t)'-', (g_sFileInfo.fattrib & AM_ARC) ? (uint32_t)'A' : (uint32_t)'-', (uint32_t)((g_sFileInfo.fdate >> 9) + 1980), (uint32_t)((g_sFileInfo.fdate >> 5) & 15), (uint32_t)(g_sFileInfo.fdate & 31), (uint32_t)((g_sFileInfo.ftime >> 11)), (uint32_t)((g_sFileInfo.ftime >> 5) & 63), (uint32_t)(g_sFileInfo.fsize), g_sFileInfo.fname); // // Add the information as a line in the listbox widget. // if(ulItemCount < NUM_LIST_STRINGS) { usprintf(g_pcFilenames[ulItemCount], "(%c) %12s", (g_sFileInfo.fattrib & AM_DIR) ? 'D' : 'F', g_sFileInfo.fname); } // // If the attribute is directory, then increment the directory count. // if(g_sFileInfo.fattrib & AM_DIR) { ulDirCount++; } // // Otherwise, it is a file. Increment the file count, and // add in the file size to the total. // else { ulFileCount++; ulTotalSize += g_sFileInfo.fsize; } // // Move to the next entry in the item array we use to populate the // list box. // ulItemCount++; // // Wait for the UART transmit buffer to empty. // // UARTFlushTx(false); } // // Print summary lines showing the file, dir, and size totals. // UARTprintf("\n%4u File(s),%10u bytes total\n%4u Dir(s)", ulFileCount, ulTotalSize, ulDirCount); // // Get the free space. // fresult = f_getfree("/", &ulTotalSize, &pFatFs); // // Check for error and return if there is a problem. // if(fresult != FR_OK) { return(fresult); } // // Display the amount of free space that was calculated. // UARTprintf(", %10uK bytes free\n", ulTotalSize * pFatFs->sects_clust / 2); // // Wait for the UART transmit buffer to empty. // // UARTFlushTx(false); // // Made it to here, return with no errors. // return(0); }