void protocol_main_loop() { // Perform some machine checks to make sure everything is good to go. #ifdef CHECK_LIMITS_AT_INIT if (bit_istrue(settings.flags, BITFLAG_HARD_LIMIT_ENABLE)) { if (limits_get_state()) { sys.state = STATE_ALARM; // Ensure alarm state is active. report_feedback_message(MESSAGE_CHECK_LIMITS); } } #endif // Check for and report alarm state after a reset, error, or an initial power up. // NOTE: Sleep mode disables the stepper drivers and position can’t be guaranteed. // Re-initialize the sleep state as an ALARM mode to ensure user homes or acknowledges. if (sys.state & (STATE_ALARM | STATE_SLEEP)) { report_feedback_message(MESSAGE_ALARM_LOCK); sys.state = STATE_ALARM; // Ensure alarm state is set. } else { // Check if the safety door is open. sys.state = STATE_IDLE; // if (system_check_safety_door_ajar()) { // bit_true(sys_rt_exec_state, EXEC_SAFETY_DOOR); // protocol_execute_realtime(); // Enter safety door mode. Should return as IDLE state. // } // All systems go! system_execute_startup(line); // Execute startup script. } // --------------------------------------------------------------------------------- // Primary loop! Upon a system abort, this exits back to main() to reset the system. // This is also where Grbl idles while waiting for something to do. // --------------------------------------------------------------------------------- uint8_t line_flags = 0; uint8_t char_counter = 0; char c; for (;;) { // Process one line of incoming serial data, as the data becomes available. Performs an // initial filtering by removing spaces and comments and capitalizing all letters. while(Getc(&c) == 0) { if ((c == '\n') || (c == '\r')) { // End of line reached protocol_execute_realtime(); // Runtime command check point. if (sys.abort) { return; } // Bail to calling function upon system abort line[char_counter] = 0; // Set string termination character. #ifdef REPORT_ECHO_LINE_RECEIVED report_echo_line_received(line); #endif // Direct and execute one line of formatted input, and report status of execution. if (line_flags & LINE_FLAG_OVERFLOW) { // Report line overflow error. report_status_message(STATUS_OVERFLOW); } else if (line[0] == 0) { // Empty or comment line. For syncing purposes. report_status_message(STATUS_OK); } else if (line[0] == '$') { // Grbl '$' system command report_status_message(system_execute_line(line)); } else if (sys.state & (STATE_ALARM | STATE_JOG)) { // Everything else is gcode. Block if in alarm or jog mode. report_status_message(STATUS_SYSTEM_GC_LOCK); } else { // Parse and execute g-code block. report_status_message(gc_execute_line(line)); } // Reset tracking data for next line. line_flags = 0; char_counter = 0; } else { if (line_flags) { // Throw away all (except EOL) comment characters and overflow characters. if (c == ')') { // End of '()' comment. Resume line allowed. if (line_flags & LINE_FLAG_COMMENT_PARENTHESES) { line_flags &= ~(LINE_FLAG_COMMENT_PARENTHESES); } } } else { if (c <= ' ') { } else if (c == '/') { } else if (c == '(') { line_flags |= LINE_FLAG_COMMENT_PARENTHESES; } else if (c == ';') { line_flags |= LINE_FLAG_COMMENT_SEMICOLON; } else if (char_counter >= (LINE_BUFFER_SIZE-1)) { line_flags |= LINE_FLAG_OVERFLOW; } else if (c >= 'a' && c <= 'z') { // Upcase lowercase line[char_counter++] = c-'a'+'A'; } else { line[char_counter++] = c; } } } } protocol_auto_cycle_start(); protocol_execute_realtime(); // Runtime command check point. if (sys.abort) { return; } // Bail to main() program loop to reset system. } return; /* Never reached */ }

时间: 2025-07-11 19:53:29 浏览: 8
<think>好的,我现在要分析用户提供的`void protocol_main_loop()`函数代码,并尝试理解其结构和功能。首先,我需要仔细阅读代码,了解每个部分的作用,然后按照用户的要求,用中文清晰地解释这个函数。 首先,函数开头有一些预处理指令,比如`#ifdef CHECK_LIMITS_AT_INIT`,这里检查是否启用了硬限制,如果检测到限位触发,系统会进入报警状态。这部分属于初始化时的机器状态检查,确保一切正常。接下来,代码检查系统状态是否为`STATE_ALARM`或`STATE_SLEEP`,如果是,则报告报警锁定,确保系统处于报警状态。否则,系统进入空闲状态,并可能执行启动脚本。 接下来是主循环部分,注释里提到这是主循环,处理系统中断等情况会退出到main()函数。主循环内部有一个无限循环`for (;;)`,里面包含处理串口数据的逻辑。这里使用`Getc(&c)`来逐个读取字符,直到遇到换行符`\n`或`\r`,表示一行结束。处理过程中会过滤空格、注释,并将小写字母转换为大写。 当一行数据接收完毕后,会执行`protocol_execute_realtime()`进行实时命令检查,如果系统终止则返回。然后处理接收到的行数据,根据不同的情况执行相应的操作:如果是空行或注释,返回OK状态;如果是$命令,执行系统命令;如果系统处于报警或点动模式,则锁定;否则解析执行G代码。 处理完一行后,重置行标志和字符计数器,继续下一行处理。之后调用`protocol_auto_cycle_start()`可能用于自动循环启动,再次执行实时命令检查,确保系统没有终止。 在分析过程中,我需要确认每个函数和变量的作用,例如`system_execute_startup`、`gc_execute_line`等,可能需要查找相关定义,但用户提供的代码中没有这些部分,所以只能根据命名推测。例如,`gc_execute_line`可能用于执行G代码行。 需要注意到代码中的条件编译部分,如`#ifdef REPORT_ECHO_LINE_RECEIVED`,这些部分可能根据不同的配置启用或禁用某些功能,比如回显接收到的行。 另外,关于字符处理部分,代码过滤了空格和注释,小写转大写,这可能是为了统一输入的格式,确保后续处理的一致性。行溢出标志的处理也需要注意,当字符数超过缓冲区大小时会设置溢出标志,并报告错误。 在协议执行过程中,实时命令检查点可能处理如急停、重置等实时操作,确保系统响应及时。主循环的设计使得Grbl在等待任务时保持空闲,能够高效处理输入指令。 总结来说,这个函数是Grbl固件的主循环,负责初始化检查、处理输入指令、执行相应的操作(系统命令或G代码),并确保实时响应系统状态变化。需要将各部分功能分解,逐步解释,确保用户能够理解整个流程。</think>`void protocol_main_loop()` 是 Grbl 固件的主控制循环函数,负责系统初始化检查、实时指令处理及串口数据解析。以下是其核心逻辑的逐步解析: --- ### **1. 系统初始化与状态检查** ```c #ifdef CHECK_LIMITS_AT_INIT if (bit_istrue(settings.flags, BITFLAG_HARD_LIMIT_ENABLE)) { if (limits_get_state()) { sys.state = STATE_ALARM; // 触发限位报警 report_feedback_message(MESSAGE_CHECK_LIMITS); } } #endif ``` - **功能**:在初始化时检查硬件限位开关状态。 - **条件**:若启用硬限位(`BITFLAG_HARD_LIMIT_ENABLE`)且限位触发,系统进入报警状态(`STATE_ALARM`),并发送反馈消息。 --- ### **2. 报警与休眠状态处理** ```c if (sys.state & (STATE_ALARM | STATE_SLEEP)) { report_feedback_message(MESSAGE_ALARM_LOCK); sys.state = STATE_ALARM; // 强制锁定为报警状态 } else { sys.state = STATE_IDLE; system_execute_startup(line); // 执行启动脚本 } ``` - **报警状态**:若系统处于报警或休眠状态,发送报警锁定消息,并确保状态为 `STATE_ALARM`。 - **空闲状态**:否则系统进入空闲(`STATE_IDLE`)并执行启动脚本(如初始化运动参数)。 --- ### **3. 主循环逻辑** ```c for (;;) { while(Getc(&c) == 0) { // 处理串口输入的单个字符 if ((c == '\n') || (c == '\r')) { // 行结束处理 protocol_execute_realtime(); // 实时命令检查 if (sys.abort) return; // 系统终止时退出 line[char_counter] = 0; // 终止符 // 根据输入内容执行不同操作 if (line_flags & LINE_FLAG_OVERFLOW) { report_status_message(STATUS_OVERFLOW); // 行溢出错误 } else if (line[0] == 0) { report_status_message(STATUS_OK); // 空行/注释 } else if (line[0] == '$') { system_execute_line(line); // 执行系统命令 } else if (sys.state & (STATE_ALARM | STATE_JOG)) { report_status_message(STATUS_SYSTEM_GC_LOCK); // 报警/点动模式下锁定 } else { gc_execute_line(line); // 解析并执行G代码 } // 重置行状态 line_flags = 0; char_counter = 0; } else { // 字符过滤与处理 if (c == '(') line_flags |= LINE_FLAG_COMMENT_PARENTHESES; // 过滤括号注释 else if (c == ';') line_flags |= LINE_FLAG_COMMENT_SEMICOLON; // 分号注释 else if (char_counter >= (LINE_BUFFER_SIZE-1)) line_flags |= LINE_FLAG_OVERFLOW; // 行溢出 else if (c >= 'a' && c <= 'z') line[char_counter++] = c-'a'+'A'; // 小写转大写 else line[char_counter++] = c; // 存储有效字符 } } protocol_auto_cycle_start(); // 自动循环启动(如加工任务) protocol_execute_realtime(); // 再次检查实时命令 if (sys.abort) return; // 终止时退出 } ``` --- ### **4. 关键子流程说明** - **实时命令检查 (`protocol_execute_realtime()`)** - 处理紧急停止(`!`)、重置(`^X`)等实时指令。 - 确保系统及时响应高优先级事件。 - **G代码解析 (`gc_execute_line()`)** - 将输入行解析为G代码指令(如 `G0 X10 Y20`)。 - 校验语法并生成运动规划。 - **系统命令 (`system_execute_line()`)** - 处理以 `$` 开头的配置命令(如 `$G` 查看状态,`$H` 归零)。 - 修改系统参数或返回状态信息。 --- ### **5. 错误处理与反馈** - **行溢出错误**:当输入行超过缓冲区大小时报告 `STATUS_OVERFLOW`。 - **报警锁定**:在 `STATE_ALARM` 或 `STATE_JOG` 状态下拒绝执行新指令。 - **状态反馈**:通过 `report_status_message()` 返回执行结果(如 `STATUS_OK`)。 --- ### **总结** `protocol_main_loop()` 是 Grbl 的核心调度器,其职责包括: 1. **系统状态监控**(限位、报警、休眠)。 2. **串口数据解析**(过滤注释、格式化输入)。 3. **指令分发**(实时命令、系统命令、G代码)。 4. **实时响应**(急停、复位等中断处理)。 该循环确保 Grbl 在高效执行任务的同时,始终保持对硬件状态和用户输入的实时响应。
阅读全文

相关推荐

/************************************************************************************************** Filename: ZMain.c Revised: $Date: 2010-09-17 16:25:30 -0700 (Fri, 17 Sep 2010) $ Revision: $Revision: 23835 $ Description: Startup and shutdown code for ZStack Notes: This version targets the Chipcon CC2530 Copyright 2005-2010 Texas Instruments Incorporated. All rights reserved. IMPORTANT: Your use of this Software is limited to those specific rights granted under the terms of a software license agreement between the user who downloaded the software, his/her employer (which must be your employer) and Texas Instruments Incorporated (the "License"). You may not use this Software unless you agree to abide by the terms of the License. The License limits your use, and you acknowledge, that the Software may not be modified, copied or distributed unless embedded on a Texas Instruments microcontroller or used solely and exclusively in conjunction with a Texas Instruments radio frequency transceiver, which is integrated into your product. Other than for the foregoing purpose, you may not use, reproduce, copy, prepare derivative works of, modify, distribute, perform, display or sell this Software and/or its documentation for any purpose. YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE PROVIDED 揂S IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. Should you have any questions regarding your right to use this Software, contact Texas Instruments Incorporated at www.TI.com. **************************************************************************************************/ /********************************************************************* * INCLUDES */ #ifndef NONWK #include "AF.h" #endif #include "hal_adc.h" #include "hal_flash.h" #include "hal_lcd.h" #include "hal_led.h" #include "hal_drivers.h" #include "OnBoard.h" #include "OSAL.h" #include "OSAL_Nv.h" #include "ZComDef.h" #include "ZMAC.h" /********************************************************************* * LOCAL FUNCTIONS */ static void zmain_ext_addr( void ); #if defined ZCL_KEY_ESTABLISH static void zmain_cert_init( void ); #endif static void zmain_dev_info( void ); static void zmain_vdd_check( void ); #ifdef LCD_SUPPORTED static void zmain_lcd_init( void ); #endif /********************************************************************* * @fn main * @brief First function called after startup. * @return don't care */ int main( void ) { // Turn off interrupts osal_int_disable( INTS_ALL );//关闭中断 // Initialization for board related stuff such as LEDs HAL_BOARD_INIT();//电路板初始化 // Make sure supply voltage is high enough to run zmain_vdd_check();//供电电压检测 // Initialize board I/O InitBoard( OB_COLD );//初始电路板IO口 // Initialze HAL drivers HalDriverInit();//初始化硬件抽样层驱动 // Initialize NV System osal_nv_init( NULL );//初始化NVFLASH // Initialize the MAC ZMacInit();//初始化MAC地址 // Determine the extended address zmain_ext_addr();//读取扩展地址 #if defined ZCL_KEY_ESTABLISH // Initialize the Certicom certificate information. zmain_cert_init(); #endif // Initialize basic NV items zgInit(); #ifndef NONWK // Since the AF isn't a task, call it's initialization routine afInit(); #endif // Initialize the operating system osal_init_system(); // Allow interrupts osal_int_enable( INTS_ALL ); // Final board initialization InitBoard( OB_READY ); // Display information about this device zmain_dev_info(); /* Display the device info on the LCD */ #ifdef LCD_SUPPORTED zmain_lcd_init(); #endif #ifdef WDT_IN_PM1 /* If WDT is used, this is a good place to enable it. */ WatchDogEnable( WDTIMX ); #endif osal_start_system(); // No Return from here return 0; // Shouldn't get here. } // main() /********************************************************************* * @fn zmain_vdd_check * @brief Check if the Vdd is OK to run the processor. * @return Return if Vdd is ok; otherwise, flash LED, then reset *********************************************************************/ static void zmain_vdd_check( void ) { uint8 cnt = 16; do { while (!HalAdcCheckVdd(VDD_MIN_RUN)); } while (--cnt); } /************************************************************************************************** * @fn zmain_ext_addr * * @brief Execute a prioritized search for a valid extended address and write the results * into the OSAL NV system for use by the system. Temporary address not saved to NV. * * input parameters * * None. * * output parameters * * None. * * @return None. ************************************************************************************************** */ static void zmain_ext_addr(void) { uint8 nullAddr[Z_EXTADDR_LEN] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; uint8 writeNV = TRUE; // First check whether a non-erased extended address exists in the OSAL NV. if ((SUCCESS != osal_nv_item_init(ZCD_NV_EXTADDR, Z_EXTADDR_LEN, NULL)) || (SUCCESS != osal_nv_read(ZCD_NV_EXTADDR, 0, Z_EXTADDR_LEN, aExtendedAddress)) || (osal_memcmp(aExtendedAddress, nullAddr, Z_EXTADDR_LEN))) { // Attempt to read the extended address from the location on the lock bits page // where the programming tools know to reserve it. HalFlashRead(HAL_FLASH_IEEE_PAGE, HAL_FLASH_IEEE_OSET, aExtendedAddress, Z_EXTADDR_LEN); if (osal_memcmp(aExtendedAddress, nullAddr, Z_EXTADDR_LEN)) { // Attempt to read the extended address from the designated location in the Info Page. if (!osal_memcmp((uint8 *)(P_INFOPAGE+HAL_INFOP_IEEE_OSET), nullAddr, Z_EXTADDR_LEN)) { osal_memcpy(aExtendedAddress, (uint8 *)(P_INFOPAGE+HAL_INFOP_IEEE_OSET), Z_EXTADDR_LEN); } else // No valid extended address was found. { uint8 idx; #if !defined ( NV_RESTORE ) writeNV = FALSE; // Make this a temporary IEEE address #endif /* Attempt to create a sufficiently random extended address for expediency. * Note: this is only valid/legal in a test environment and * must never be used for a commercial product. */ for (idx = 0; idx < (Z_EXTADDR_LEN - 2);) { uint16 randy = osal_rand(); aExtendedAddress[idx++] = LO_UINT16(randy); aExtendedAddress[idx++] = HI_UINT16(randy); } // Next-to-MSB identifies ZigBee devicetype. #if ZG_BUILD_COORDINATOR_TYPE && !ZG_BUILD_JOINING_TYPE aExtendedAddress[idx++] = 0x10; #elif ZG_BUILD_RTRONLY_TYPE aExtendedAddress[idx++] = 0x20; #else aExtendedAddress[idx++] = 0x30; #endif // MSB has historical signficance. aExtendedAddress[idx] = 0xF8; } } if (writeNV) { (void)osal_nv_write(ZCD_NV_EXTADDR, 0, Z_EXTADDR_LEN, aExtendedAddress); } } // Set the MAC PIB extended address according to results from above. (void)ZMacSetReq(MAC_EXTENDED_ADDRESS, aExtendedAddress); } #if defined ZCL_KEY_ESTABLISH /************************************************************************************************** * @fn zmain_cert_init * * @brief Initialize the Certicom certificate information. * * input parameters * * None. * * output parameters * * None. * * @return None. ************************************************************************************************** */ static void zmain_cert_init(void) { uint8 certData[ZCL_KE_IMPLICIT_CERTIFICATE_LEN]; uint8 nullData[ZCL_KE_IMPLICIT_CERTIFICATE_LEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; (void)osal_nv_item_init(ZCD_NV_IMPLICIT_CERTIFICATE, ZCL_KE_IMPLICIT_CERTIFICATE_LEN, NULL); (void)osal_nv_item_init(ZCD_NV_DEVICE_PRIVATE_KEY, ZCL_KE_DEVICE_PRIVATE_KEY_LEN, NULL); // First check whether non-null certificate data exists in the OSAL NV. To save on code space, // just use the ZCD_NV_CA_PUBLIC_KEY as the bellwether for all three. if ((SUCCESS != osal_nv_item_init(ZCD_NV_CA_PUBLIC_KEY, ZCL_KE_CA_PUBLIC_KEY_LEN, NULL)) || (SUCCESS != osal_nv_read(ZCD_NV_CA_PUBLIC_KEY, 0, ZCL_KE_CA_PUBLIC_KEY_LEN, certData)) || (osal_memcmp(certData, nullData, ZCL_KE_CA_PUBLIC_KEY_LEN))) { // Attempt to read the certificate data from its corresponding location on the lock bits page. HalFlashRead(HAL_FLASH_IEEE_PAGE, HAL_FLASH_CA_PUBLIC_KEY_OSET, certData, ZCL_KE_CA_PUBLIC_KEY_LEN); // If the certificate data is not NULL, use it to update the corresponding NV items. if (!osal_memcmp(certData, nullData, ZCL_KE_CA_PUBLIC_KEY_LEN)) { (void)osal_nv_write(ZCD_NV_CA_PUBLIC_KEY, 0, ZCL_KE_CA_PUBLIC_KEY_LEN, certData); HalFlashRead(HAL_FLASH_IEEE_PAGE, HAL_FLASH_IMPLICIT_CERT_OSET, certData, ZCL_KE_IMPLICIT_CERTIFICATE_LEN); (void)osal_nv_write(ZCD_NV_IMPLICIT_CERTIFICATE, 0, ZCL_KE_IMPLICIT_CERTIFICATE_LEN, certData); HalFlashRead(HAL_FLASH_IEEE_PAGE, HAL_FLASH_DEV_PRIVATE_KEY_OSET, certData, ZCL_KE_DEVICE_PRIVATE_KEY_LEN); (void)osal_nv_write(ZCD_NV_DEVICE_PRIVATE_KEY, 0, ZCL_KE_DEVICE_PRIVATE_KEY_LEN, certData); } } } #endif /************************************************************************************************** * @fn zmain_dev_info * * @brief This displays the IEEE (MSB to LSB) on the LCD. * * input parameters * * None. * * output parameters * * None. * * @return None. ************************************************************************************************** */ static void zmain_dev_info(void) { #ifdef LCD_SUPPORTED uint8 i; uint8 *xad; uint8 lcd_buf[Z_EXTADDR_LEN*2+1]; // Display the extended address. xad = aExtendedAddress + Z_EXTADDR_LEN - 1; for (i = 0; i < Z_EXTADDR_LEN*2; xad--) { uint8 ch; ch = (*xad >> 4) & 0x0F; lcd_buf[i++] = ch + (( ch < 10 ) ? '0' : '7'); ch = *xad & 0x0F; lcd_buf[i++] = ch + (( ch < 10 ) ? '0' : '7'); } lcd_buf[Z_EXTADDR_LEN*2] = '\0'; HalLcdWriteString( "IEEE: ", HAL_LCD_LINE_1 ); HalLcdWriteString( (char*)lcd_buf, HAL_LCD_LINE_2 ); #endif } #ifdef LCD_SUPPORTED /********************************************************************* * @fn zmain_lcd_init * @brief Initialize LCD at start up. * @return none *********************************************************************/ static void zmain_lcd_init ( void ) { #ifdef SERIAL_DEBUG_SUPPORTED { HalLcdWriteString( "TexasInstruments", HAL_LCD_LINE_1 ); #if defined( MT_MAC_FUNC ) #if defined( ZDO_COORDINATOR ) HalLcdWriteString( "MAC-MT Coord", HAL_LCD_LINE_2 ); #else HalLcdWriteString( "MAC-MT Device", HAL_LCD_LINE_2 ); #endif // ZDO #elif defined( MT_NWK_FUNC ) #if defined( ZDO_COORDINATOR ) HalLcdWriteString( "NWK Coordinator", HAL_LCD_LINE_2 ); #else HalLcdWriteString( "NWK Device", HAL_LCD_LINE_2 ); #endif // ZDO #endif // MT_FUNC } #endif // SERIAL_DEBUG_SUPPORTED } #endif /********************************************************************* *********************************************************************/ 以上是DHT11代码,请帮我生成一个光敏代码

int main(void) { /*HW semaphore Clock enable*/ __HAL_RCC_HSEM_CLK_ENABLE(); /* Activate HSEM notification for Cortex-M4*/ HAL_HSEM_ActivateNotification(__HAL_HSEM_SEMID_TO_MASK(HSEM_ID_0)); /* Domain D2 goes to STOP mode (Cortex-M4 in deep-sleep) waiting for Cortex-M7 to perform system initialization (system clock config, external memory configuration.. ) */ HAL_PWREx_ClearPendingEvent(); HAL_PWREx_EnterSTOPMode(PWR_MAINREGULATOR_ON, PWR_STOPENTRY_WFE, PWR_D2_DOMAIN); /* Clear HSEM flag */ __HAL_HSEM_CLEAR_FLAG(__HAL_HSEM_SEMID_TO_MASK(HSEM_ID_0)); /* STM32H7xx HAL library initialization: - Systick timer is configured by default as source of time base, but user can eventually implement his proper time base source (a general purpose timer for example or other time source), keeping in mind that Time base duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and handled in milliseconds basis. - Set NVIC Group Priority to 4 - Low Level Initialization */ HAL_Init(); /* Infinite loop */ while (1) { } } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* Infinite loop */ while (1) { } } #endif /** * @} */ /** * @} */

/****************************************************************************/ /* */ /* 音频测试:MIC_IN读取音频数据,从LINE_OUT播出 */ /* */ /* 2014年7月1日 */ /* */ /****************************************************************************/ #include "TL6748.h" // 创龙 DSP6748 开发板相关声明 #include "edma_event.h" #include "interrupt.h" #include "soc_OMAPL138.h" #include "hw_syscfg0_OMAPL138.h" #include "codecif.h" #include "mcasp.h" #include "aic31.h" #include "edma.h" #include "psc.h" #include "uartStdio.h" #include <string.h> /****************************************************************************** ** 宏定义 *******************************************************************************/ /* ** Values which are configurable */ /* Slot size to send/receive data */ #define SLOT_SIZE (16u) /* Word size to send/receive data. Word size <= Slot size */ #define WORD_SIZE (16u) /* Sampling Rate which will be used by both transmit and receive sections */ #define SAMPLING_RATE (48000u) /* Number of channels, L & R */ #define NUM_I2S_CHANNELS (2u) /* Number of samples to be used per audio buffer */ #define NUM_SAMPLES_PER_AUDIO_BUF (2000u) /* Number of buffers used per tx/rx */ #define NUM_BUF (3u) /* Number of linked parameter set used per tx/rx */ #define NUM_PAR (2u) /* Specify where the parameter set starting is */ #define PAR_ID_START (40u) /* Number of samples in loop buffer */ #define NUM_SAMPLES_LOOP_BUF (10u) /* AIC3106 codec address */ #define I2C_SLAVE_CODEC_AIC31 (0x18u) /* Interrupt channels to map in AINTC */ #define INT_CHANNEL_I2C (2u) #define INT_CHANNEL_MCASP (2u) #define INT_CHANNEL_EDMACC (2u) /* McASP Serializer for Receive */ #define MCASP_XSER_RX (12u) /* McASP Serializer for Transmit */ #define MCASP_XSER_TX (11u) /* ** Below Macros are calculated based on the above inputs */ #define NUM_TX_SERIALIZERS ((NUM_I2S_CHANNELS >> 1) \ + (NUM_I2S_CHANNELS & 0x01)) #define NUM_RX_SERIALIZERS ((NUM_I2S_CHANNELS >> 1) \ + (NUM_I2S_CHANNELS & 0x01)) #define I2S_SLOTS ((1 << NUM_I2S_CHANNELS) - 1) #define BYTES_PER_SAMPLE ((WORD_SIZE >> 3) \ * NUM_I2S_CHANNELS) #define AUDIO_BUF_SIZE (NUM_SAMPLES_PER_AUDIO_BUF \ * BYTES_PER_SAMPLE) #define TX_DMA_INT_ENABLE (EDMA3CC_OPT_TCC_SET(1) | (1 \ << EDMA3CC_OPT_TCINTEN_SHIFT)) #define RX_DMA_INT_ENABLE (EDMA3CC_OPT_TCC_SET(0) | (1 \ << EDMA3CC_OPT_TCINTEN_SHIFT)) #define PAR_RX_START (PAR_ID_START) #define PAR_TX_START (PAR_RX_START + NUM_PAR) /* ** Definitions which are not configurable */ #define SIZE_PARAMSET (32u) #define OPT_FIFO_WIDTH (0x02 << 8u) /****************************************************************************** ** 函数原型声明 *******************************************************************************/ static void McASPErrorIsr(void); static void McASPErrorIntSetup(void); static void AIC31I2SConfigure(void); static void McASPI2SConfigure(void); static void McASPTxDMAComplHandler(void); static void McASPRxDMAComplHandler(void); static void EDMA3CCComplIsr(void); static void I2SDataTxRxActivate(void); static void I2SDMAParamInit(void); static void ParamTxLoopJobSet(unsigned short parId); static void BufferTxDMAActivate(unsigned int txBuf, unsigned short numSamples, unsigned short parToUpdate, unsigned short linkAddr); static void BufferRxDMAActivate(unsigned int rxBuf, unsigned short parId, unsigned short parLink); /****************************************************************************/ /* 全局变量 */ /****************************************************************************/ static unsigned char loopBuf[NUM_SAMPLES_LOOP_BUF * BYTES_PER_SAMPLE] = {0}; /* ** Transmit buffers. If any new buffer is to be added, define it here and ** update the NUM_BUF. */ static unsigned char txBuf0[AUDIO_BUF_SIZE]; static unsigned char txBuf1[AUDIO_BUF_SIZE]; static unsigned char txBuf2[AUDIO_BUF_SIZE]; /* ** Receive buffers. If any new buffer is to be added, define it here and ** update the NUM_BUF. */ static unsigned char rxBuf0[AUDIO_BUF_SIZE]; static unsigned char rxBuf1[AUDIO_BUF_SIZE]; static unsigned char rxBuf2[AUDIO_BUF_SIZE]; /* ** Next buffer to receive data. The data will be received in this buffer. */ static volatile unsigned int nxtBufToRcv = 0; /* ** The RX buffer which filled latest. */ static volatile unsigned int lastFullRxBuf = 0; /* ** The offset of the paRAM ID, from the starting of the paRAM set. */ static volatile unsigned short parOffRcvd = 0; /* ** The offset of the paRAM ID sent, from starting of the paRAM set. */ static volatile unsigned short parOffSent = 0; /* ** The offset of the paRAM ID to be sent next, from starting of the paRAM set. */ static volatile unsigned short parOffTxToSend = 0; /* ** The transmit buffer which was sent last. */ static volatile unsigned int lastSentTxBuf = NUM_BUF - 1; /* Array of receive buffer pointers */ static unsigned int const rxBufPtr[NUM_BUF] = { (unsigned int) rxBuf0, (unsigned int) rxBuf1, (unsigned int) rxBuf2 }; /* Array of transmit buffer pointers */ static unsigned int const txBufPtr[NUM_BUF] = { (unsigned int) txBuf0, (unsigned int) txBuf1, (unsigned int) txBuf2 }; /* ** Default paRAM for Transmit section. This will be transmitting from ** a loop buffer. */ static struct EDMA3CCPaRAMEntry const txDefaultPar = { (unsigned int)(EDMA3CC_OPT_DAM | (0x02 << 8u)), /* Opt field */ (unsigned int)loopBuf, /* source address */ (unsigned short)(BYTES_PER_SAMPLE), /* aCnt */ (unsigned short)(NUM_SAMPLES_LOOP_BUF), /* bCnt */ (unsigned int) SOC_MCASP_0_DATA_REGS, /* dest address */ (short) (BYTES_PER_SAMPLE), /* source bIdx */ (short)(0), /* dest bIdx */ (unsigned short)(PAR_TX_START * SIZE_PARAMSET), /* link address */ (unsigned short)(0), /* bCnt reload value */ (short)(0), /* source cIdx */ (short)(0), /* dest cIdx */ (unsigned short)1 /* cCnt */ }; /* ** Default paRAM for Receive section. */ static struct EDMA3CCPaRAMEntry const rxDefaultPar = { (unsigned int)(EDMA3CC_OPT_SAM | (0x02 << 8u)), /* Opt field */ (unsigned int)SOC_MCASP_0_DATA_REGS, /* source address */ (unsigned short)(BYTES_PER_SAMPLE), /* aCnt */ (unsigned short)(1), /* bCnt */ (unsigned int)rxBuf0, /* dest address */ (short) (0), /* source bIdx */ (short)(BYTES_PER_SAMPLE), /* dest bIdx */ (unsigned short)(PAR_RX_START * SIZE_PARAMSET), /* link address */ (unsigned short)(0), /* bCnt reload value */ (short)(0), /* source cIdx */ (short)(0), /* dest cIdx */ (unsigned short)1 /* cCnt */ }; /****************************************************************************/ /* 函数声明 */ /****************************************************************************/ static void ParamTxLoopJobSet(unsigned short parId); static void I2SDMAParamInit(void); static void AIC31I2SConfigure(void); static void McASPI2SConfigure(void); static void EDMA3IntSetup(void); static void McASPErrorIntSetup(void); static void I2SDataTxRxActivate(void); void BufferTxDMAActivate(unsigned int txBuf, unsigned short numSamples, unsigned short parId, unsigned short linkPar); static void BufferRxDMAActivate(unsigned int rxBuf, unsigned short parId, unsigned short parLink); static void McASPRxDMAComplHandler(void); static void McASPTxDMAComplHandler(void); static void EDMA3CCComplIsr(void); static void McASPErrorIsr(void); /****************************************************************************/ /* 主函数 */ /****************************************************************************/ int main(void) { unsigned short parToSend; unsigned short parToLink; UARTStdioInit(); UARTPuts("\r\n ============Test Start===========.\r\n", -1); UARTPuts("Welcome to StarterWare Audio_MIC_In Demo application.\r\n\r\n", -1); UARTPuts("This application loops back the input at MIC_IN of the EVM to the LINE_OUT of the EVM\r\n\r\n", -1); /* Set up pin mux for I2C module 0 */ I2CPinMuxSetup(0); McASPPinMuxSetup(); /* Power up the McASP module */ PSCModuleControl(SOC_PSC_1_REGS, HW_PSC_MCASP0, PSC_POWERDOMAIN_ALWAYS_ON, PSC_MDCTL_NEXT_ENABLE); /* Power up EDMA3CC_0 and EDMA3TC_0 */ PSCModuleControl(SOC_PSC_0_REGS, HW_PSC_CC0, PSC_POWERDOMAIN_ALWAYS_ON, PSC_MDCTL_NEXT_ENABLE); PSCModuleControl(SOC_PSC_0_REGS, HW_PSC_TC0, PSC_POWERDOMAIN_ALWAYS_ON, PSC_MDCTL_NEXT_ENABLE); #ifdef _TMS320C6X // Initialize the DSP interrupt controller IntDSPINTCInit(); #else /* Initialize the ARM Interrupt Controller.*/ IntAINTCInit(); #endif /* Initialize the I2C 0 interface for the codec AIC31 */ I2CCodecIfInit(SOC_I2C_0_REGS, INT_CHANNEL_I2C, I2C_SLAVE_CODEC_AIC31); EDMA3Init(SOC_EDMA30CC_0_REGS, 0); EDMA3IntSetup(); McASPErrorIntSetup(); #ifdef _TMS320C6X IntGlobalEnable(); #else /* Enable the interrupts generation at global level */ IntMasterIRQEnable(); IntGlobalEnable(); IntIRQEnable(); #endif /* ** Request EDMA channels. Channel 0 is used for reception and ** Channel 1 is used for transmission */ EDMA3RequestChannel(SOC_EDMA30CC_0_REGS, EDMA3_CHANNEL_TYPE_DMA, EDMA3_CHA_MCASP0_TX, EDMA3_CHA_MCASP0_TX, 0); EDMA3RequestChannel(SOC_EDMA30CC_0_REGS, EDMA3_CHANNEL_TYPE_DMA, EDMA3_CHA_MCASP0_RX, EDMA3_CHA_MCASP0_RX, 0); /* Initialize the DMA parameters */ I2SDMAParamInit(); /* Configure the Codec for I2S mode */ AIC31I2SConfigure(); /* Configure the McASP for I2S */ McASPI2SConfigure(); /* Activate the audio transmission and reception */ I2SDataTxRxActivate(); /* ** Looop forever. if a new buffer is received, the lastFullRxBuf will be ** updated in the rx completion ISR. if it is not the lastSentTxBuf, ** buffer is to be sent. This has to be mapped to proper paRAM set. */ while(1) { if(lastFullRxBuf != lastSentTxBuf) { /* ** Start the transmission from the link paramset. The param set ** 1 will be linked to param set at PAR_TX_START. So do not ** update paRAM set1. */ parToSend = PAR_TX_START + (parOffTxToSend % NUM_PAR); parOffTxToSend = (parOffTxToSend + 1) % NUM_PAR; parToLink = PAR_TX_START + parOffTxToSend; lastSentTxBuf = (lastSentTxBuf + 1) % NUM_BUF; /* Copy the buffer */ memcpy((void *)txBufPtr[lastSentTxBuf], (void *)rxBufPtr[lastFullRxBuf], AUDIO_BUF_SIZE); /* ** Send the buffer by setting the DMA params accordingly. ** Here the buffer to send and number of samples are passed as ** parameters. This is important, if only transmit section ** is to be used. */ BufferTxDMAActivate(lastSentTxBuf, NUM_SAMPLES_PER_AUDIO_BUF, (unsigned short)parToSend, (unsigned short)parToLink); } } } /* ** Assigns loop job for a parameter set */ static void ParamTxLoopJobSet(unsigned short parId) { EDMA3CCPaRAMEntry paramSet; memcpy(¶mSet, &txDefaultPar, SIZE_PARAMSET - 2); /* link the paRAM to itself */ paramSet.linkAddr = parId * SIZE_PARAMSET; EDMA3SetPaRAM(SOC_EDMA30CC_0_REGS, parId, ¶mSet); } /* ** Initializes the DMA parameters. ** The RX basic paRAM set(channel) is 0 and TX basic paRAM set (channel) is 1. ** ** The RX paRAM set 0 will be initialized to receive data in the rx buffer 0. ** The transfer completion interrupt will not be enabled for paRAM set 0; ** paRAM set 0 will be linked to linked paRAM set starting (PAR_RX_START) of RX. ** and further reception only happens via linked paRAM set. ** For example, if the PAR_RX_START value is 40, and the number of paRAMS is 2, ** reception paRAM set linking will be initialized as 0-->40-->41-->40 ** ** The TX paRAM sets will be initialized to transmit from the loop buffer. ** The size of the loop buffer can be configured. ** The transfer completion interrupt will not be enabled for paRAM set 1; ** paRAM set 1 will be linked to linked paRAM set starting (PAR_TX_START) of TX. ** All other paRAM sets will be linked to itself. ** and further transmission only happens via linked paRAM set. ** For example, if the PAR_RX_START value is 42, and the number of paRAMS is 2, ** So transmission paRAM set linking will be initialized as 1-->42-->42, 43->43. */ static void I2SDMAParamInit(void) { EDMA3CCPaRAMEntry paramSet; int idx; /* Initialize the 0th paRAM set for receive */ memcpy(¶mSet, &rxDefaultPar, SIZE_PARAMSET - 2); EDMA3SetPaRAM(SOC_EDMA30CC_0_REGS, EDMA3_CHA_MCASP0_RX, ¶mSet); /* further paramsets, enable interrupt */ paramSet.opt |= RX_DMA_INT_ENABLE; for(idx = 0 ; idx < NUM_PAR; idx++) { paramSet.destAddr = rxBufPtr[idx]; paramSet.linkAddr = (PAR_RX_START + ((idx + 1) % NUM_PAR)) * (SIZE_PARAMSET); paramSet.bCnt = NUM_SAMPLES_PER_AUDIO_BUF; /* ** for the first linked paRAM set, start receiving the second ** sample only since the first sample is already received in ** rx buffer 0 itself. */ if( 0 == idx) { paramSet.destAddr += BYTES_PER_SAMPLE; paramSet.bCnt -= BYTES_PER_SAMPLE; } EDMA3SetPaRAM(SOC_EDMA30CC_0_REGS, (PAR_RX_START + idx), ¶mSet); } /* Initialize the required variables for reception */ nxtBufToRcv = idx % NUM_BUF; lastFullRxBuf = NUM_BUF - 1; parOffRcvd = 0; /* Initialize the 1st paRAM set for transmit */ memcpy(¶mSet, &txDefaultPar, SIZE_PARAMSET); EDMA3SetPaRAM(SOC_EDMA30CC_0_REGS, EDMA3_CHA_MCASP0_TX, ¶mSet); /* rest of the params, enable loop job */ for(idx = 0 ; idx < NUM_PAR; idx++) { ParamTxLoopJobSet(PAR_TX_START + idx); } /* Initialize the variables for transmit */ parOffSent = 0; lastSentTxBuf = NUM_BUF - 1; } /* ** Function to configure the codec for I2S mode */ static void AIC31I2SConfigure(void) { volatile unsigned int delay = 0xFFF; AIC31Reset(SOC_I2C_0_REGS); while(delay--); /* Configure the data format and sampling rate */ AIC31DataConfig(SOC_I2C_0_REGS, AIC31_DATATYPE_I2S, SLOT_SIZE, 0); AIC31SampleRateConfig(SOC_I2C_0_REGS, AIC31_MODE_BOTH, SAMPLING_RATE); /* Initialize both ADC and DAC */ AIC31ADCInit(SOC_I2C_0_REGS); AIC31DACInit(SOC_I2C_0_REGS); } /* ** Configures the McASP Transmit Section in I2S mode. */ static void McASPI2SConfigure(void) { McASPRxReset(SOC_MCASP_0_CTRL_REGS); McASPTxReset(SOC_MCASP_0_CTRL_REGS); /* Enable the FIFOs for DMA transfer */ McASPReadFifoEnable(SOC_MCASP_0_FIFO_REGS, 1, 1); McASPWriteFifoEnable(SOC_MCASP_0_FIFO_REGS, 1, 1); /* Set I2S format in the transmitter/receiver format units */ McASPRxFmtI2SSet(SOC_MCASP_0_CTRL_REGS, WORD_SIZE, SLOT_SIZE, MCASP_RX_MODE_DMA); McASPTxFmtI2SSet(SOC_MCASP_0_CTRL_REGS, WORD_SIZE, SLOT_SIZE, MCASP_TX_MODE_DMA); /* Configure the frame sync. I2S shall work in TDM format with 2 slots */ McASPRxFrameSyncCfg(SOC_MCASP_0_CTRL_REGS, 2, MCASP_RX_FS_WIDTH_WORD, MCASP_RX_FS_EXT_BEGIN_ON_FALL_EDGE); McASPTxFrameSyncCfg(SOC_MCASP_0_CTRL_REGS, 2, MCASP_TX_FS_WIDTH_WORD, MCASP_TX_FS_EXT_BEGIN_ON_RIS_EDGE); /* configure the clock for receiver */ McASPRxClkCfg(SOC_MCASP_0_CTRL_REGS, MCASP_RX_CLK_EXTERNAL, 0, 0); McASPRxClkPolaritySet(SOC_MCASP_0_CTRL_REGS, MCASP_RX_CLK_POL_RIS_EDGE); McASPRxClkCheckConfig(SOC_MCASP_0_CTRL_REGS, MCASP_RX_CLKCHCK_DIV32, 0x00, 0xFF); /* configure the clock for transmitter */ McASPTxClkCfg(SOC_MCASP_0_CTRL_REGS, MCASP_TX_CLK_EXTERNAL, 0, 0); McASPTxClkPolaritySet(SOC_MCASP_0_CTRL_REGS, MCASP_TX_CLK_POL_FALL_EDGE); McASPTxClkCheckConfig(SOC_MCASP_0_CTRL_REGS, MCASP_TX_CLKCHCK_DIV32, 0x00, 0xFF); /* Enable synchronization of RX and TX sections */ McASPTxRxClkSyncEnable(SOC_MCASP_0_CTRL_REGS); /* Enable the transmitter/receiver slots. I2S uses 2 slots */ McASPRxTimeSlotSet(SOC_MCASP_0_CTRL_REGS, I2S_SLOTS); McASPTxTimeSlotSet(SOC_MCASP_0_CTRL_REGS, I2S_SLOTS); /* ** Set the serializers, Currently only one serializer is set as ** transmitter and one serializer as receiver. */ McASPSerializerRxSet(SOC_MCASP_0_CTRL_REGS, MCASP_XSER_RX); McASPSerializerTxSet(SOC_MCASP_0_CTRL_REGS, MCASP_XSER_TX); /* ** Configure the McASP pins ** Input - Frame Sync, Clock and Serializer Rx ** Output - Serializer Tx is connected to the input of the codec */ McASPPinMcASPSet(SOC_MCASP_0_CTRL_REGS, 0xFFFFFFFF); McASPPinDirOutputSet(SOC_MCASP_0_CTRL_REGS,MCASP_PIN_AXR(MCASP_XSER_TX)); McASPPinDirInputSet(SOC_MCASP_0_CTRL_REGS, MCASP_PIN_AFSX | MCASP_PIN_ACLKX | MCASP_PIN_AHCLKX | MCASP_PIN_AXR(MCASP_XSER_RX)); /* Enable error interrupts for McASP */ McASPTxIntEnable(SOC_MCASP_0_CTRL_REGS, MCASP_TX_DMAERROR | MCASP_TX_CLKFAIL | MCASP_TX_SYNCERROR | MCASP_TX_UNDERRUN); McASPRxIntEnable(SOC_MCASP_0_CTRL_REGS, MCASP_RX_DMAERROR | MCASP_RX_CLKFAIL | MCASP_RX_SYNCERROR | MCASP_RX_OVERRUN); } /* ** Sets up the interrupts for EDMA in AINTC */ static void EDMA3IntSetup(void) { #ifdef _TMS320C6X IntRegister(C674X_MASK_INT5, EDMA3CCComplIsr); IntEventMap(C674X_MASK_INT5, SYS_INT_EDMA3_0_CC0_INT1); IntEnable(C674X_MASK_INT5); #else IntRegister(SYS_INT_CCINT0, EDMA3CCComplIsr); IntChannelSet(SYS_INT_CCINT0, INT_CHANNEL_EDMACC); IntSystemEnable(SYS_INT_CCINT0); #endif } /* ** Sets up the error interrupts for McASP in AINTC */ static void McASPErrorIntSetup(void) { #ifdef _TMS320C6X IntRegister(C674X_MASK_INT6, McASPErrorIsr); IntEventMap(C674X_MASK_INT6, SYS_INT_MCASP0_INT); IntEnable(C674X_MASK_INT6); #else /* Register the error ISR for McASP */ IntRegister(SYS_INT_MCASPINT, McASPErrorIsr); IntChannelSet(SYS_INT_MCASPINT, INT_CHANNEL_MCASP); IntSystemEnable(SYS_INT_MCASPINT); #endif } /* ** Activates the data transmission/reception ** The DMA parameters shall be ready before calling this function. */ static void I2SDataTxRxActivate(void) { /* Start the clocks */ McASPRxClkStart(SOC_MCASP_0_CTRL_REGS, MCASP_RX_CLK_EXTERNAL); McASPTxClkStart(SOC_MCASP_0_CTRL_REGS, MCASP_TX_CLK_EXTERNAL); /* Enable EDMA for the transfer */ EDMA3EnableTransfer(SOC_EDMA30CC_0_REGS, EDMA3_CHA_MCASP0_RX, EDMA3_TRIG_MODE_EVENT); EDMA3EnableTransfer(SOC_EDMA30CC_0_REGS, EDMA3_CHA_MCASP0_TX, EDMA3_TRIG_MODE_EVENT); /* Activate the serializers */ McASPRxSerActivate(SOC_MCASP_0_CTRL_REGS); McASPTxSerActivate(SOC_MCASP_0_CTRL_REGS); /* make sure that the XDATA bit is cleared to zero */ while(McASPTxStatusGet(SOC_MCASP_0_CTRL_REGS) & MCASP_TX_STAT_DATAREADY); /* Activate the state machines */ McASPRxEnable(SOC_MCASP_0_CTRL_REGS); McASPTxEnable(SOC_MCASP_0_CTRL_REGS); } /* ** Activates the DMA transfer for a parameterset from the given buffer. */ void BufferTxDMAActivate(unsigned int txBuf, unsigned short numSamples, unsigned short parId, unsigned short linkPar) { EDMA3CCPaRAMEntry paramSet; /* Copy the default paramset */ memcpy(¶mSet, &txDefaultPar, SIZE_PARAMSET - 2); /* Enable completion interrupt */ paramSet.opt |= TX_DMA_INT_ENABLE; paramSet.srcAddr = txBufPtr[txBuf]; paramSet.linkAddr = linkPar * SIZE_PARAMSET; paramSet.bCnt = numSamples; EDMA3SetPaRAM(SOC_EDMA30CC_0_REGS, parId, ¶mSet); } /* ** Activates the DMA transfer for a parameter set from the given buffer. */ static void BufferRxDMAActivate(unsigned int rxBuf, unsigned short parId, unsigned short parLink) { EDMA3CCPaRAMEntry paramSet; /* Copy the default paramset */ memcpy(¶mSet, &rxDefaultPar, SIZE_PARAMSET - 2); /* Enable completion interrupt */ paramSet.opt |= RX_DMA_INT_ENABLE; paramSet.destAddr = rxBufPtr[rxBuf]; paramSet.bCnt = NUM_SAMPLES_PER_AUDIO_BUF; paramSet.linkAddr = parLink * SIZE_PARAMSET ; EDMA3SetPaRAM(SOC_EDMA30CC_0_REGS, parId, ¶mSet); } /* ** This function will be called once receive DMA is completed */ static void McASPRxDMAComplHandler(void) { unsigned short nxtParToUpdate; /* ** Update lastFullRxBuf to indicate a new buffer reception ** is completed. */ lastFullRxBuf = (lastFullRxBuf + 1) % NUM_BUF; nxtParToUpdate = PAR_RX_START + parOffRcvd; parOffRcvd = (parOffRcvd + 1) % NUM_PAR; /* ** Update the DMA parameters for the received buffer to receive ** further data in proper buffer */ BufferRxDMAActivate(nxtBufToRcv, nxtParToUpdate, PAR_RX_START + parOffRcvd); /* update the next buffer to receive data */ nxtBufToRcv = (nxtBufToRcv + 1) % NUM_BUF; } /* ** This function will be called once transmit DMA is completed */ static void McASPTxDMAComplHandler(void) { ParamTxLoopJobSet((unsigned short)(PAR_TX_START + parOffSent)); parOffSent = (parOffSent + 1) % NUM_PAR; } /* ** EDMA transfer completion ISR */ static void EDMA3CCComplIsr(void) { #ifdef _TMS320C6X IntEventClear(SYS_INT_EDMA3_0_CC0_INT1); #else IntSystemStatusClear(SYS_INT_CCINT0); #endif /* Check if receive DMA completed */ if(EDMA3GetIntrStatus(SOC_EDMA30CC_0_REGS) & (1 << EDMA3_CHA_MCASP0_RX)) { /* Clear the interrupt status for the 0th channel */ EDMA3ClrIntr(SOC_EDMA30CC_0_REGS, EDMA3_CHA_MCASP0_RX); McASPRxDMAComplHandler(); } /* Check if transmit DMA completed */ if(EDMA3GetIntrStatus(SOC_EDMA30CC_0_REGS) & (1 << EDMA3_CHA_MCASP0_TX)) { /* Clear the interrupt status for the first channel */ EDMA3ClrIntr(SOC_EDMA30CC_0_REGS, EDMA3_CHA_MCASP0_TX); McASPTxDMAComplHandler(); } } /* ** Error ISR for McASP */ static void McASPErrorIsr(void) { #ifdef _TMS320C6X IntEventClear(SYS_INT_MCASP0_INT); #else IntSystemStatusClear(SYS_INT_MCASPINT); #endif ; /* Perform any error handling here.*/ } /***************************** End Of File ***********************************/ 将以上代码和以下代码合在一起:#include "math.h" #include "mathlib.h" #include "dsplib.h" #define PI 3.1415926535 #define F_TOL (1e-06) #define Tn 1024 #define Fs 48000.0 #define N 132 // 滤波器阶数(偶数) #define FilterCount 5 const float F1s[FilterCount] = {20.0, 400.0, 1200.0, 4000.0, 13000.0}; const float F2s[FilterCount] = {400.0, 1200.0, 4000.0, 13000.0, 20000.0}; #pragma DATA_ALIGN(FIR_In, 8); float FIR_In[Tn]; #pragma DATA_ALIGN(FIR_Outs, 8); float FIR_Outs[FilterCount][Tn]; #pragma DATA_ALIGN(FIR_CombinedOut, 8); float FIR_CombinedOut[Tn]; #pragma DATA_ALIGN(Bs, 8); float Bs[FilterCount][N]; void FIRTest(void); void design_blackman_bandpass_fir(float *h, int n, float f1, float f2, float fs); void blackman_window(float *w, int n); void normalize_filter_response(float *h, int n, float f1, float f2, float fs); int main(void) { int i; // 声明循环变量 for (i = 0; i < FilterCount; i++) { design_blackman_bandpass_fir(Bs[i], N, F1s[i], F2s[i], Fs); } FIRTest(); return 0; } void blackman_window(float *w, int n) { int i; // 声明循环变量 for (i = 0; i < n; i++) { w[i] = 0.42f - 0.5f * cosf(2.0f * PI * i / (n - 1)) + 0.08f * cosf(4.0f * PI * i / (n - 1)); } } void normalize_filter_response(float *h, int n, float f1, float f2, float fs) { float center_freq = (f1 + f2) / 2.0f; float omega = 2.0f * PI * center_freq / fs; float real_gain = 0.0f; int i; // 声明循环变量 for (i = 0; i < n; i++) { real_gain += h[i] * cosf(omega * (i - (n-1)/2.0f)); } if (fabsf(real_gain) > F_TOL) { for (i = 0; i < n; i++) { h[i] /= real_gain; } } } void design_blackman_bandpass_fir(float *h, int n, float f1, float f2, float fs) { float w[N]; float fc1 = f1 / fs; float fc2 = f2 / fs; int i; // 声明循环变量 blackman_window(w, n); for (i = 0; i < n; i++) { float m = i - (n - 1)/2.0f; h[i] = (fabsf(m) < F_TOL) ? 2.0f * (fc2 - fc1) : (sinf(2.0f * PI * fc2 * m) - sinf(2.0f * PI * fc1 * m)) / (PI * m); h[i] *= w[i]; } normalize_filter_response(h, n, f1, f2, fs); } void FIRTest(void) { int i, j; // 声明循环变量 // 生成测试信号 - 每个频段一个测试频率 for (i = 0; i < Tn; i++) { float t = (float)i / Fs; FIR_In[i] = 5.0f * sinf(2.0f * PI * 10.0f * t) + 5.0f * sinf(2.0f * PI * 15000.0f * t)+ 5.0f * sinf(2.0f * PI * 25000.0f * t); } // 初始化并处理滤波器输出 for (i = 0; i < Tn; i++) { FIR_CombinedOut[i] = 0.0f; } for (j = 0; j < FilterCount; j++) { DSPF_sp_fir_r2(FIR_In, Bs[j], FIR_Outs[j], N, Tn); // 累加各滤波器输出 for (i = 0; i < Tn; i++) { FIR_CombinedOut[i] += FIR_Outs[j][i]; } } } 将测试信号去掉,合成后的代码输入就是音频输入,输出就是音频输出,滤波器来处理数据

FAILED: MyTestHttp : && /usr/bin/c++ -g CMakeFiles/MyTestHttp.dir/main.cpp.o -o MyTestHttp && : /usr/bin/ld: CMakeFiles/MyTestHttp.dir/main.cpp.o: in function Http::Http()': /home/hy-20/project/MyTestHttp/main.cpp:20: undefined reference to curl_global_init' /usr/bin/ld: /home/hy-20/project/MyTestHttp/main.cpp:21: undefined reference to curl_easy_init' /usr/bin/ld: CMakeFiles/MyTestHttp.dir/main.cpp.o: in function Http::~Http()': /home/hy-20/project/MyTestHttp/main.cpp:25: undefined reference to curl_easy_cleanup' /usr/bin/ld: /home/hy-20/project/MyTestHttp/main.cpp:26: undefined reference to curl_global_cleanup' /usr/bin/ld: CMakeFiles/MyTestHttp.dir/main.cpp.o: in function Http::setUrl(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)': /home/hy-20/project/MyTestHttp/main.cpp:29: undefined reference to curl_easy_setopt' /usr/bin/ld: CMakeFiles/MyTestHttp.dir/main.cpp.o: in function Http::setPostFields(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)': /home/hy-20/project/MyTestHttp/main.cpp:31: undefined reference to curl_easy_setopt' /usr/bin/ld: CMakeFiles/MyTestHttp.dir/main.cpp.o: in function Http::setMethod(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)': /home/hy-20/project/MyTestHttp/main.cpp:35: undefined reference to curl_easy_setopt' /usr/bin/ld: /home/hy-20/project/MyTestHttp/main.cpp:36: undefined reference to curl_easy_setopt' /usr/bin/ld: CMakeFiles/MyTestHttp.dir/main.cpp.o: in function Http::setHeaders(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)': /home/hy-20/project/MyTestHttp/main.cpp:41: undefined reference to curl_slist_append' /usr/bin/ld: /home/hy-20/project/MyTestHttp/main.cpp:42: undefined reference to curl_easy_setopt' /usr/bin/ld: CMakeFiles/MyTestHttp.dir/main.cpp.o: in function Http::setWriteFunction(std::function<void (std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)> const&)': /home/hy-20/project/MyTestHttp/main.cpp:46: undefined reference to curl_easy_setopt' /usr/bin/ld: /home/hy-20/project/MyTestHttp/main.cpp:47: undefined reference to curl_easy_setopt' /usr/bin/ld: CMakeFiles/MyTestHttp.dir/main.cpp.o: in function Http::perform()': /home/hy-20/project/MyTestHttp/main.cpp:50: undefined reference to curl_easy_perform' collect2: error: ld returned 1 exit status ninja: build stopped: subcommand failed.

void rt_OneStep(void); void rt_OneStep(void) { static boolean_T OverrunFlag = false; /* Disable interrupts here */ /* Check for overrun */ if (OverrunFlag) { rtmSetErrorStatus(SteeingbyWireTest0711_M, "Overrun"); return; } OverrunFlag = true; /* Save FPU context here (if necessary) */ /* Re-enable timer or interrupt here */ /* Set model inputs here */ /* Step the model */ SteeingbyWireTest0711_step(); /* Get model outputs here */ /* Indicate task complete */ OverrunFlag = false; /* Disable interrupts here */ /* Restore FPU context here (if necessary) */ /* Enable interrupts here */ } /* * The example main function illustrates what is required by your * application code to initialize, execute, and terminate the generated code. * Attaching rt_OneStep to a real-time clock is target specific. This example * illustrates how you do this relative to initializing the model. */ int_T main(int_T argc, const char *argv[]) { /* Unused arguments */ (void)(argc); (void)(argv); /* Initialize model */ SteeingbyWireTest0711_initialize(); /* Attach rt_OneStep to a timer or interrupt service routine with * period 0.005 seconds (base rate of the model) here. * The call syntax for rt_OneStep is * * rt_OneStep(); */ printf("Warning: The simulation will run forever. " "Generated ERT main won't simulate model step behavior. " "To change this behavior select the 'MAT-file logging' option.\n"); fflush((NULL)); while (rtmGetErrorStatus(SteeingbyWireTest0711_M) == (NULL)) { /* Perform application tasks here */ } /* Terminate model */ SteeingbyWireTest0711_terminate(); return 0; } /* * File trailer for generated code. * * [EOF] 这是主函数,这里有调用onestep函数吗

/*********************************************************************************** Filename: light_switch.c Description: This application function either as a light or a switch toggling the ligh. The role of the application is chosen in the menu with the joystick at initialisation. Push S1 to enter the menu. Choose either switch or light and confirm choice with S1. Joystick Up: Sends data from switch to light ***********************************************************************************/ /*********************************************************************************** * INCLUDES */ #include <hal_lcd.h> #include <hal_led.h> #include <hal_joystick.h> #include <hal_assert.h> #include <hal_board.h> #include <hal_int.h> #include "hal_mcu.h" #include "hal_button.h" #include "hal_rf.h" #include "util_lcd.h" #include "basic_rf.h" /*********************************************************************************** * CONSTANTS */ // Application parameters #define RF_CHANNEL 25 // 2.4 GHz RF channel // BasicRF address definitions #define PAN_ID 0x2007 #define SWITCH_ADDR 0x2520 #define LIGHT_ADDR 0xBEEF #define APP_PAYLOAD_LENGTH 1 #define LIGHT_TOGGLE_CMD 0 // Application states #define IDLE 0 #define SEND_CMD 1 // Application role #define NONE 0 #define SWITCH 1 #define LIGHT 2 #define APP_MODES 2 /*********************************************************************************** * LOCAL VARIABLES */ static uint8 pTxData[APP_PAYLOAD_LENGTH]; static uint8 pRxData[APP_PAYLOAD_LENGTH]; static basicRfCfg_t basicRfConfig; // Mode menu static menuItem_t pMenuItems[] = { #ifdef ASSY_EXP4618_CC2420 // Using Softbaugh 7-seg display " L S ", SWITCH, " LIGHT ", LIGHT #else // SRF04EB and SRF05EB "Switch", SWITCH, "Light", LIGHT #endif }; static menu_t pMenu = { pMenuItems, N_ITEMS(pMenuItems) }; #ifdef SECURITY_CCM // Security key static uint8 key[]= { 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, }; #endif /*********************************************************************************** * LOCAL FUNCTIONS */ static void appLight(); static void appSwitch(); static uint8 appSelectMode(void); /*********************************************************************************** * @fn appLight * * @brief Application code for light application. Puts MCU in endless * loop waiting for user input from joystick. * * @param basicRfConfig - file scope variable. Basic RF configuration data * pRxData - file scope variable. Pointer to buffer for RX data * * @return none */ static void appLight() { // halLcdWriteLine(HAL_LCD_LINE_1, "Light"); // halLcdWriteLine(HAL_LCD_LINE_2, "Ready"); #ifdef ASSY_EXP4618_CC2420 halLcdClearLine(1); halLcdWriteSymbol(HAL_LCD_SYMBOL_RX, 1); #endif // Initialize BasicRF basicRfConfig.myAddr = LIGHT_ADDR; if(basicRfInit(&basicRfConfig)==FAILED) { HAL_ASSERT(FALSE); } basicRfReceiveOn(); // Main loop while (TRUE) { while(!basicRfPacketIsReady()); if(basicRfReceive(pRxData, APP_PAYLOAD_LENGTH, NULL)>0) { if(pRxData[0] == LIGHT_TOGGLE_CMD) { halLedToggle(1); } } } } /*********************************************************************************** * @fn appSwitch * * @brief Application code for switch application. Puts MCU in * endless loop to wait for commands from from switch * * @param basicRfConfig - file scope variable. Basic RF configuration data * pTxData - file scope variable. Pointer to buffer for TX * payload * appState - file scope variable. Holds application state * * @return none */ static void appSwitch() { // halLcdWriteLine(HAL_LCD_LINE_1, "Switch"); // halLcdWriteLine(HAL_LCD_LINE_2, "Joystick Push"); // halLcdWriteLine(HAL_LCD_LINE_3, "Send Command"); #ifdef ASSY_EXP4618_CC2420 halLcdClearLine(1); halLcdWriteSymbol(HAL_LCD_SYMBOL_TX, 1); #endif pTxData[0] = LIGHT_TOGGLE_CMD; // Initialize BasicRF basicRfConfig.myAddr = SWITCH_ADDR; if(basicRfInit(&basicRfConfig)==FAILED) { HAL_ASSERT(FALSE); } // Keep Receiver off when not needed to save power basicRfReceiveOff(); // Main loop while (TRUE) { // if( halJoystickPushed() ) { //bu qiujie tech if(halButtonPushed()==HAL_BUTTON_1){ basicRfSendPacket(LIGHT_ADDR, pTxData, APP_PAYLOAD_LENGTH); // Put MCU to sleep. It will wake up on joystick interrupt halIntOff(); halMcuSetLowPowerMode(HAL_MCU_LPM_3); // Will turn on global // interrupt enable halIntOn(); } } } /*********************************************************************************** * @fn main * * @brief This is the main entry of the "Light Switch" application. * After the application modes are chosen the switch can * send toggle commands to a light device. * * @param basicRfConfig - file scope variable. Basic RF configuration * data * appState - file scope variable. Holds application state * * @return none */ void main(void) { uint8 appMode = NONE; // Config basicRF basicRfConfig.panId = PAN_ID; basicRfConfig.channel = RF_CHANNEL; basicRfConfig.ackRequest = TRUE; #ifdef SECURITY_CCM basicRfConfig.securityKey = key; #endif // Initalise board peripherals halBoardInit(); // halJoystickInit();//BY QIUJIE // Initalise hal_rf if(halRfInit()==FAILED) { HAL_ASSERT(FALSE); } // Indicate that device is powered halLedSet(1); // Print Logo and splash screen on LCD // utilPrintLogo("Light Switch"); // Wait for user to press S1 to enter menu // while (halButtonPushed()!=HAL_BUTTON_1); // halMcuWaitMs(350); // halLcdClear(); // Set application role // appMode = appSelectMode(); // halLcdClear(); // appMode = SWITCH; // Transmitter application // if(appMode == SWITCH) { // No return from here //注:函数appSwitch()和appLight()只能打开一个 //作为开关板打开此函数(appSwitch) //appSwitch(); //被点灯的板打开此函数(appLight) appLight(); // } // Receiver application // else if(appMode == LIGHT) { // No return from here // } // Role is undefined. This code should not be reached // HAL_ASSERT(FALSE); } /**************************************************************************************** * @fn appSelectMode * * @brief Select application mode * * @param none * * @return uint8 - Application mode chosen */ static uint8 appSelectMode(void) { halLcdWriteLine(1, "Device Mode: "); return utilMenuSelect(&pMenu); } /**************************************************************************************** Copyright 2007 Texas Instruments Incorporated. All rights reserved. IMPORTANT: Your use of this Software is limited to those specific rights granted under the terms of a software license agreement between the user who downloaded the software, his/her employer (which must be your employer) and Texas Instruments Incorporated (the "License"). You may not use this Software unless you agree to abide by the terms of the License. The License limits your use, and you acknowledge, that the Software may not be modified, copied or distributed unless embedded on a Texas Instruments microcontroller or used solely and exclusively in conjunction with a Texas Instruments radio frequency transceiver, which is integrated into your product. Other than for the foregoing purpose, you may not use, reproduce, copy, prepare derivative works of, modify, distribute, perform, display or sell this Software and/or its documentation for any purpose. YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE PROVIDED 揂S IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. Should you have any questions regarding your right to use this Software, contact Texas Instruments Incorporated at www.TI.com. ***********************************************************************************/ 这是SW1控制LED1的代码,我想改为SW2控制LED2的代码

/*********************************************************************************** Filename: light_switch.c Description: This application function either as a light or a switch toggling the ligh. The role of the application is chosen in the menu with the joystick at initialisation. Push S1 to enter the menu. Choose either switch or light and confirm choice with S1. Joystick Up: Sends data from switch to light ***********************************************************************************/ /*********************************************************************************** * INCLUDES */ #include <hal_lcd.h> #include <hal_led.h> #include <hal_joystick.h> #include <hal_assert.h> #include <hal_board.h> #include <hal_int.h> #include "hal_mcu.h" #include "hal_button.h" #include "hal_rf.h" #include "util_lcd.h" #include "basic_rf.h" /*********************************************************************************** * CONSTANTS */ // Application parameters #define RF_CHANNEL 25 // 2.4 GHz RF channel // BasicRF address definitions #define PAN_ID 0x2126 #define SWITCH_ADDR 0x2520 #define LIGHT_ADDR 0xBEEF #define APP_PAYLOAD_LENGTH 1 #define LIGHT_TOGGLE_CMD 0 // Application states #define IDLE 0 #define SEND_CMD 1 // Application role #define NONE 0 #define SWITCH 1 #define LIGHT 2 #define APP_MODES 2 /*********************************************************************************** * LOCAL VARIABLES */ static uint8 pTxData[APP_PAYLOAD_LENGTH]; static uint8 pRxData[APP_PAYLOAD_LENGTH]; static basicRfCfg_t basicRfConfig; // Mode menu static menuItem_t pMenuItems[] = { #ifdef ASSY_EXP4618_CC2420 // Using Softbaugh 7-seg display " L S ", SWITCH, " LIGHT ", LIGHT #else // SRF04EB and SRF05EB "Switch", SWITCH, "Light", LIGHT #endif }; static menu_t pMenu = { pMenuItems, N_ITEMS(pMenuItems) }; #ifdef SECURITY_CCM // Security key static uint8 key[]= { 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, }; #endif /*********************************************************************************** * LOCAL FUNCTIONS */ static void appLight(); static void appSwitch(); static uint8 appSelectMode(void); /*********************************************************************************** * @fn appLight * * @brief Application code for light application. Puts MCU in endless * loop waiting for user input from joystick. * * @param basicRfConfig - file scope variable. Basic RF configuration data * pRxData - file scope variable. Pointer to buffer for RX data * * @return none */ static void appLight() { halLcdWriteLine(HAL_LCD_LINE_1, "Light"); halLcdWriteLine(HAL_LCD_LINE_2, "Ready"); #ifdef ASSY_EXP4618_CC2420 halLcdClearLine(1); halLcdWriteSymbol(HAL_LCD_SYMBOL_RX, 1); #endif // Initialize BasicRF basicRfConfig.myAddr = LIGHT_ADDR; if(basicRfInit(&basicRfConfig)==FAILED) { HAL_ASSERT(FALSE); } basicRfReceiveOn(); // Main loop while (TRUE) { while(!basicRfPacketIsReady()); if(basicRfReceive(pRxData, APP_PAYLOAD_LENGTH, NULL)>0) { if(pRxData[0] == LIGHT_TOGGLE_CMD) { halLedToggle(1); } } } } /*********************************************************************************** * @fn appSwitch * * @brief Application code for switch application. Puts MCU in * endless loop to wait for commands from from switch * * @param basicRfConfig - file scope variable. Basic RF configuration data * pTxData - file scope variable. Pointer to buffer for TX * payload * appState - file scope variable. Holds application state * * @return none */ static void appSwitch() { halLcdWriteLine(HAL_LCD_LINE_1, "Switch"); halLcdWriteLine(HAL_LCD_LINE_2, "Joystick Push"); halLcdWriteLine(HAL_LCD_LINE_3, "Send Command"); #ifdef ASSY_EXP4618_CC2420 halLcdClearLine(1); halLcdWriteSymbol(HAL_LCD_SYMBOL_TX, 1); #endif pTxData[0] = LIGHT_TOGGLE_CMD; // Initialize BasicRF basicRfConfig.myAddr = SWITCH_ADDR; // 示例:扩展为流水灯效果 if(pRxData[0] == LIGHT_TOGGLE_CMD) { static uint8_t ledPattern = 0; ledPattern = (ledPattern + 1) % 4; // 假设使用4个LED // 根据模式控制多个LED switch(ledPattern) { case 0: halLedSet(1); halLedClear(2); halLedClear(3); halLedClear(4); break; case 1: halLedClear(1); halLedSet(2); halLedClear(3); halLedClear(4); break; case 2: halLedClear(1); halLedClear(2); halLedSet(3); halLedClear(4); break; case 3: halLedClear(1); halLedClear(2); halLedClear(3); halLedSet(4); break; } } if(basicRfInit(&basicRfConfig)==FAILED) { HAL_ASSERT(FALSE); } // Keep Receiver off when not needed to save power basicRfReceiveOff(); // Main loop while (TRUE) { //if( halJoystickPushed() ) { if(halButtonPushed()==HAL_BUTTON_1){ basicRfSendPacket(LIGHT_ADDR, pTxData, APP_PAYLOAD_LENGTH); // Put MCU to sleep. It will wake up on joystick interrupt halIntOff(); halMcuSetLowPowerMode(HAL_MCU_LPM_3); // Will turn on global // interrupt enable halIntOn(); } } } /*********************************************************************************** * @fn main * * @brief This is the main entry of the "Light Switch" application. * After the application modes are chosen the switch can * send toggle commands to a light device. * * @param basicRfConfig - file scope variable. Basic RF configuration * data * appState - file scope variable. Holds application state * * @return none */ void main(void) { //uint8 appMode = NONE; uint8 appMode = LIGHT; // Config basicRF basicRfConfig.panId = PAN_ID; basicRfConfig.channel = RF_CHANNEL; basicRfConfig.ackRequest = TRUE; #ifdef SECURITY_CCM basicRfConfig.securityKey = key; #endif // Initalise board peripherals halBoardInit(); halJoystickInit(); // Initalise hal_rf if(halRfInit()==FAILED) { HAL_ASSERT(FALSE); } // Indicate that device is powered halLedSet(1); // Print Logo and splash screen on LCD //utilPrintLogo("Light Switch"); // Wait for user to press S1 to enter menu //while (halButtonPushed()!=HAL_BUTTON_1); halMcuWaitMs(350); halLcdClear(); // Set application role //appMode = appSelectMode(); halLcdClear(); // Transmitter application if(appMode == SWITCH) { // No return from here appSwitch(); } // Receiver application else if(appMode == LIGHT) { // No return from here appLight(); } // Role is undefined. This code should not be reached HAL_ASSERT(FALSE); } /**************************************************************************************** * @fn appSelectMode * * @brief Select application mode * * @param none * * @return uint8 - Application mode chosen */ static uint8 appSelectMode(void) { halLcdWriteLine(1, "Device Mode: "); return utilMenuSelect(&pMenu); } /**************************************************************************************** Copyright 2007 Texas Instruments Incorporated. All rights reserved. IMPORTANT: Your use of this Software is limited to those specific rights granted under the terms of a software license agreement between the user who downloaded the software, his/her employer (which must be your employer) and Texas Instruments Incorporated (the "License"). You may not use this Software unless you agree to abide by the terms of the License. The License limits your use, and you acknowledge, that the Software may not be modified, copied or distributed unless embedded on a Texas Instruments microcontroller or used solely and exclusively in conjunction with a Texas Instruments radio frequency transceiver, which is integrated into your product. Other than for the foregoing purpose, you may not use, reproduce, copy, prepare derivative works of, modify, distribute, perform, display or sell this Software and/or its documentation for any purpose. YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE PROVIDED 揂S IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. Should you have any questions regarding your right to use this Software, contact Texas Instruments Incorporated at www.TI.com. ***********************************************************************************/ 改为无线开关LED流水灯

最新推荐

recommend-type

netty-all-4.1.23.Final.jar中文文档.zip

1、压缩文件中包含: 中文文档、jar包下载地址、Maven依赖、Gradle依赖、源代码下载地址。 2、使用方法: 解压最外层zip,再解压其中的zip包,双击 【index.html】 文件,即可用浏览器打开、进行查看。 3、特殊说明: (1)本文档为人性化翻译,精心制作,请放心使用; (2)只翻译了该翻译的内容,如:注释、说明、描述、用法讲解 等; (3)不该翻译的内容保持原样,如:类名、方法名、包名、类型、关键字、代码 等。 4、温馨提示: (1)为了防止解压后路径太长导致浏览器无法打开,推荐在解压时选择“解压到当前文件夹”(放心,自带文件夹,文件不会散落一地); (2)有时,一套Java组件会有多个jar,所以在下载前,请仔细阅读本篇描述,以确保这就是你需要的文件。 5、本文件关键字: jar中文文档.zip,java,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,中文API文档,手册,开发手册,使用手册,参考手册。
recommend-type

OKT507_修改默认界面显示_Linux_应用笔记_V1.0_20220627.pdf

OKT507_修改默认界面显示_Linux_应用笔记_V1.0_20220627
recommend-type

实现Struts2+IBatis+Spring集成的快速教程

### 知识点概览 #### 标题解析 - **Struts2**: Apache Struts2 是一个用于创建企业级Java Web应用的开源框架。它基于MVC(Model-View-Controller)设计模式,允许开发者将应用的业务逻辑、数据模型和用户界面视图进行分离。 - **iBatis**: iBatis 是一个基于 Java 的持久层框架,它提供了对象关系映射(ORM)的功能,简化了 Java 应用程序与数据库之间的交互。 - **Spring**: Spring 是一个开源的轻量级Java应用框架,提供了全面的编程和配置模型,用于现代基于Java的企业的开发。它提供了控制反转(IoC)和面向切面编程(AOP)的特性,用于简化企业应用开发。 #### 描述解析 描述中提到的“struts2+ibatis+spring集成的简单例子”,指的是将这三个流行的Java框架整合起来,形成一个统一的开发环境。开发者可以利用Struts2处理Web层的MVC设计模式,使用iBatis来简化数据库的CRUD(创建、读取、更新、删除)操作,同时通过Spring框架提供的依赖注入和事务管理等功能,将整个系统整合在一起。 #### 标签解析 - **Struts2**: 作为标签,意味着文档中会重点讲解关于Struts2框架的内容。 - **iBatis**: 作为标签,说明文档同样会包含关于iBatis框架的内容。 #### 文件名称列表解析 - **SSI**: 这个缩写可能代表“Server Side Include”,一种在Web服务器上运行的服务器端脚本语言。但鉴于描述中提到导入包太大,且没有具体文件列表,无法确切地解析SSI在此的具体含义。如果此处SSI代表实际的文件或者压缩包名称,则可能是一个缩写或别名,需要具体的上下文来确定。 ### 知识点详细说明 #### Struts2框架 Struts2的核心是一个Filter过滤器,称为`StrutsPrepareAndExecuteFilter`,它负责拦截用户请求并根据配置将请求分发到相应的Action类。Struts2框架的主要组件有: - **Action**: 在Struts2中,Action类是MVC模式中的C(控制器),负责接收用户的输入,执行业务逻辑,并将结果返回给用户界面。 - **Interceptor(拦截器)**: Struts2中的拦截器可以在Action执行前后添加额外的功能,比如表单验证、日志记录等。 - **ValueStack(值栈)**: Struts2使用值栈来存储Action和页面间传递的数据。 - **Result**: 结果是Action执行完成后返回的响应,可以是JSP页面、HTML片段、JSON数据等。 #### iBatis框架 iBatis允许开发者将SQL语句和Java类的映射关系存储在XML配置文件中,从而避免了复杂的SQL代码直接嵌入到Java代码中,使得代码的可读性和可维护性提高。iBatis的主要组件有: - **SQLMap配置文件**: 定义了数据库表与Java类之间的映射关系,以及具体的SQL语句。 - **SqlSessionFactory**: 负责创建和管理SqlSession对象。 - **SqlSession**: 在执行数据库操作时,SqlSession是一个与数据库交互的会话。它提供了操作数据库的方法,例如执行SQL语句、处理事务等。 #### Spring框架 Spring的核心理念是IoC(控制反转)和AOP(面向切面编程),它通过依赖注入(DI)来管理对象的生命周期和对象间的依赖关系。Spring框架的主要组件有: - **IoC容器**: 也称为依赖注入(DI),管理对象的创建和它们之间的依赖关系。 - **AOP**: 允许将横切关注点(如日志、安全等)与业务逻辑分离。 - **事务管理**: 提供了一致的事务管理接口,可以在多个事务管理器之间切换,支持声明式事务和编程式事务。 - **Spring MVC**: 是Spring提供的基于MVC设计模式的Web框架,与Struts2类似,但更灵活,且与Spring的其他组件集成得更紧密。 #### 集成Struts2, iBatis和Spring 集成这三种框架的目的是利用它们各自的优势,在同一个项目中形成互补,提高开发效率和系统的可维护性。这种集成通常涉及以下步骤: 1. **配置整合**:在`web.xml`中配置Struts2的`StrutsPrepareAndExecuteFilter`,以及Spring的`DispatcherServlet`。 2. **依赖注入配置**:在Spring的配置文件中声明Struts2和iBatis的组件,以及需要的其他bean,并通过依赖注入将它们整合。 3. **Action和SQL映射**:在Struts2中创建Action类,并在iBatis的SQLMap配置文件中定义对应的SQL语句,将Struts2的Action与iBatis的映射关联起来。 4. **事务管理**:利用Spring的事务管理功能来管理数据库操作的事务。 5. **安全和服务层**:通过Spring的AOP和IoC功能来实现业务逻辑的解耦合和事务的管理。 ### 结语 通过上述的整合,开发者可以有效地利用Struts2处理Web层的展示和用户交互,使用iBatis简化数据库操作,同时借助Spring强大的依赖注入和事务管理功能,创建一个结构良好、可维护性强的应用。这种集成方式在许多企业级Java Web应用中非常常见,是Java开发人员必须掌握的知识点。
recommend-type

【数据融合技术】:甘肃土壤类型空间分析中的专业性应用

# 摘要 数据融合技术作为一种集成多源数据信息的方法,在土壤类型空间分析中发挥着关键作用。本文介绍了数据融合技术的基本概念及其理论基础,阐述了数据预处理、同步整合及冲突解决等关键技术,并详细描述了甘肃土壤类型数据准备的流程,包括数据采集、质量评估、空间化处理及融合实践准备。通过具体案例分析,展示了数据融合在土壤类型空间分布分析、土壤质量评估及土壤保护规划中的应用。同时,文
recommend-type

Waymo使用稀疏图卷积处理LiDAR点云,目标检测精度提升15%

<think>好的,用户让我介绍一下Waymo使用稀疏图卷积处理LiDAR点云,目标检测精度提升15%的具体情况。我需要先回忆之前提供的回答中提到的相关案例,然后深入展开。 首先,用户可能已经知道稀疏图卷积的基本概念,但需要更详细的应用案例。他们可能对Waymo如何具体应用该技术感兴趣,比如技术细节、实现方式、提升的具体指标等。需要确保回答结构清晰,分点说明,同时保持技术准确性。 要考虑到用户可能的背景,可能是研究或工程领域的,需要技术细节,但避免过于复杂的数学公式,除非必要。之前回答中提到了应用案例,现在需要扩展这个部分。需要解释为什么稀疏图卷积在这里有效,比如处理LiDAR点云的稀疏性
recommend-type

Dwr实现无刷新分页功能的代码与数据库实例

### DWR简介 DWR(Direct Web Remoting)是一个用于允许Web页面中的JavaScript直接调用服务器端Java方法的开源库。它简化了Ajax应用的开发,并使得异步通信成为可能。DWR在幕后处理了所有的细节,包括将JavaScript函数调用转换为HTTP请求,以及将HTTP响应转换回JavaScript函数调用的参数。 ### 无刷新分页 无刷新分页是网页设计中的一种技术,它允许用户在不重新加载整个页面的情况下,通过Ajax与服务器进行交互,从而获取新的数据并显示。这通常用来优化用户体验,因为它加快了响应时间并减少了服务器负载。 ### 使用DWR实现无刷新分页的关键知识点 1. **Ajax通信机制:**Ajax(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。通过XMLHttpRequest对象,可以与服务器交换数据,并使用JavaScript来更新页面的局部内容。DWR利用Ajax技术来实现页面的无刷新分页。 2. **JSON数据格式:**DWR在进行Ajax调用时,通常会使用JSON(JavaScript Object Notation)作为数据交换格式。JSON是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。 3. **Java后端实现:**Java代码需要编写相应的后端逻辑来处理分页请求。这通常包括查询数据库、计算分页结果以及返回分页数据。DWR允许Java方法被暴露给前端JavaScript,从而实现前后端的交互。 4. **数据库操作:**在Java后端逻辑中,处理分页的关键之一是数据库查询。这通常涉及到编写SQL查询语句,并利用数据库管理系统(如MySQL、Oracle等)提供的分页功能。例如,使用LIMIT和OFFSET语句可以实现数据库查询的分页。 5. **前端页面设计:**前端页面需要设计成能够响应用户分页操作的界面。例如,提供“下一页”、“上一页”按钮,或是分页条。这些元素在用户点击时会触发JavaScript函数,从而通过DWR调用Java后端方法,获取新的分页数据,并动态更新页面内容。 ### 数据库操作的关键知识点 1. **SQL查询语句:**在数据库操作中,需要编写能够支持分页的SQL查询语句。这通常涉及到对特定字段进行排序,并通过LIMIT和OFFSET来控制返回数据的范围。 2. **分页算法:**分页算法需要考虑当前页码、每页显示的记录数以及数据库中记录的总数。SQL语句中的OFFSET计算方式通常为(当前页码 - 1)* 每页记录数。 3. **数据库优化:**在分页查询时,尤其是当数据量较大时,需要考虑到查询效率问题。可以通过建立索引、优化SQL语句或使用存储过程等方式来提高数据库操作的性能。 ### DWR无刷新分页实现的代码要点 1. **DWR配置:**在实现DWR无刷新分页时,首先需要配置DWR,以暴露Java方法给前端JavaScript调用。 2. **JavaScript调用:**编写JavaScript代码,使用DWR提供的API发起Ajax调用。这些调用将触发后端Java方法,并接收返回的分页数据。 3. **数据展示:**在获取到新的分页数据后,需要将这些数据显示在前端页面的相应位置。这通常需要操作DOM元素,将新数据插入到页面中。 ### 结论 通过结合上述知识点,可以使用DWR技术实现一个无刷新分页的动态Web应用。DWR简化了Ajax通信过程,让开发者可以专注于业务逻辑的实现。通过熟练掌握Java后端处理、数据库查询和前端页面设计的相关技术,便能高效地完成无刷新分页的开发任务。
recommend-type

【空间分布规律】:甘肃土壤类型与农业生产的关联性研究

# 摘要 本文对甘肃土壤类型及其在农业生产中的作用进行了系统性研究。首先概述了甘肃土壤类型的基础理论,并探讨了土壤类型与农业生产的理论联系。通过GIS技术分析,本文详细阐述了甘肃土壤的空间分布规律,并对其特征和影响因素进行了深入分析。此外,本文还研究了甘肃土壤类型对农业生产实际影响,包括不同区域土壤改良和作物种植案例,以及土壤养分、水分管理对作物生长周期和产量的具体影响。最后,提出了促进甘肃土壤与农业可持续发展的策略,包括土壤保护、退化防治对策以及土壤类型优化与农业创新的结合。本文旨在为
recommend-type

缓存延迟双删的实际解决方案通常怎么实现

<think>嗯,用户问的是关于缓存延迟双删的最佳实践和实际解决方案。首先,我需要回忆一下延迟双删的基本概念。根据引用[1]和[2],延迟双删主要是为了解决数据库和缓存之间的数据不一致问题,尤其是在分布式系统中。核心步骤应该是先删除缓存,再更新数据库,然后延迟一段时间再次删除缓存。但具体怎么操作呢? 用户可能已经知道延迟双删的基本思想,但需要更详细的步骤和注意事项。比如,为什么要延迟?延迟多久合适?这些都需要解释清楚。引用[3]提到先更新数据库再删除缓存是推荐的方法,但延迟双删可能是在某些特定场景下的优化。 接下来,我得考虑实现延迟双删的具体步骤。首先,第一次删除缓存是为了避免旧数据被后续
recommend-type

企业内部文档管理平台使用Asp.net技术构建

标题和描述中提到的知识点相当丰富,涉及到多个层面的IT技术和管理机制,具体如下: 1. Asp.net技术框架:Asp.net是微软公司开发的一个用于构建动态网站和网络应用程序的服务器端技术。它基于.NET平台,支持使用C#、VB.NET等多种编程语言开发应用程序。Asp.net企业信息文档管理系统使用Asp.net框架,意味着它将利用这一技术平台的特性,比如丰富的类库、集成开发环境(IDE)支持和面向对象的开发模型。 2.TreeView控件:TreeView是一种常用的Web控件,用于在网页上显示具有层次结构的数据,如目录、文件系统或组织结构。该控件通常用于提供给用户清晰的导航路径。在Asp.net企业信息文档管理系统中,TreeView控件被用于实现树状结构的文档管理功能,便于用户通过树状目录快速定位和管理文档。 3.系统模块设计:Asp.net企业信息文档管理系统被划分为多个模块,包括类别管理、文档管理、添加文档、浏览文档、附件管理、角色管理和用户管理等。这些模块化的设计能够让用户根据不同的功能需求进行操作,从而提高系统的可用性和灵活性。 4.角色管理:角色管理是企业信息管理系统中非常重要的一个部分,用于定义不同级别的用户权限和职责。在这个系统中,角色可以进行添加、编辑(修改角色名称)、删除以及上下移动(改变排列顺序)。这些操作满足了对用户权限细分和动态调整的需求。 5.操作逻辑:描述中详细说明了角色管理的操作步骤,如通过按钮选择进行角色的移动、修改和删除,提供了明确的用户交互流程,体现了系统设计的直观性。 6.系统安全性:系统提供了默认的管理帐号和密码(均为51aspx),这通常是一种简便的部署时临时设置。但在实际部署过程中,出于安全考虑,这些默认信息需要立即更改,并定期更新密码以避免潜在的安全风险。 7.文件结构:文件名称列表揭示了系统的文件结构和主要组成部分,比如Global.asax负责应用程序级别的事件处理,Default.aspx和Default.aspx.cs分别对应于系统的默认页面和后台代码文件,Web.Config用于存储和配置应用程序的设置,DocumentManager.sln和DocumentManager.suo分别指出了解决方案文件和解决方案用户选项文件,表明这是一个完整的Visual Studio解决方案。 通过上述知识点的梳理,我们可以看出Asp.net企业信息文档管理系统是一个集成了多个模块,具有良好用户体验设计、清晰操作逻辑和基本安全措施的IT解决方案。它不仅可以提高企业文档管理的效率,还能通过角色的权限管理确保信息的安全性和访问控制的合理性。同时,该系统还遵循了一定的软件工程实践,如模块化设计和配置文件的使用,以保障系统的可维护性和可扩展性。
recommend-type

【制图技术】:甘肃高质量土壤分布TIF图件的成图策略

# 摘要 本文针对甘肃土壤分布数据的TIF图件制作进行了系统研究。首先概述了甘肃土壤的分布情况,接着介绍了TIF图件的基础知识,包括其格式特点、空间数据表达以及质量控制方法。随后,文中构建了成图策略的理论框架,分析了土壤分布图的信息需求与数据处理流程,并探讨了成图原则与标准。在实践操作部分,详细阐述了制图软