CH32系列做主机时管理设备睡眠与唤醒

     以下为操作CH32作主机时在原有的USBHS_HOSTKM的基础上提供简单操作,控制设备进入睡眠,设备可以唤醒设备,设备也可以远程唤醒主机。

1.首先需要打开20开外部中断线(全速主机应为18号中断线),配置事件唤醒:

RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO , ENABLE);//外部唤醒需要先配置AFIO时钟。

EXTI_InitStructure.EXTI_Line = EXTI_Line20;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Event;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init( &EXTI_InitStructure );

2.在头文件中ch32v30x_usbfs_host.c/h添加远程唤醒配置与清楚类命令

命令码

__attribute__((aligned(4))) static const uint8_t SetupFeature[ ] =
{
0x00, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00
};

__attribute__((aligned(4))) static const uint8_t SetupClearFeature[ ] =
{
0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00
};

类命令传输

uint8_t USBHSH_SetEndpFeature( uint8_t ep0_size, uint8_t endp_num )
{
memcpy( pUSBHS_SetupRequest, SetupFeature, sizeof( USB_SETUP_REQ ) );
pUSBHS_SetupRequest->wIndex = (uint16_t)endp_num;
return USBHSH_CtrlTransfer( ep0_size, NULL, NULL );
}
uint8_t USBHSH_ClearEndpFeature( uint8_t ep0_size, uint8_t endp_num )
{
memcpy( pUSBHS_SetupRequest, SetupClearFeature, sizeof( USB_SETUP_REQ ) );
pUSBHS_SetupRequest->wIndex = (uint16_t)endp_num;
return USBHSH_CtrlTransfer( ep0_size, NULL, NULL );
}

3.控制设备挂起与唤醒,当KEY_1_DOWN成立先发送类命令设置设备的远程唤醒有效,然后挂起设备,此时设备可以进入低功耗;当KEY_1_UP,此时主机会挂起,等待设备唤醒自己或者自己唤醒自己后再唤醒设备。

KeyCode = KEY_FIFO_Get(); /* 读取键值, 无键按下时返回 KEY_NONE = 0 */
if (KeyCode != KEY_NONE)
{
switch (KeyCode)
{
case KEY_1_DOWN: //挂起设备并睡眠
printf("设备挂起\r\n");
USBH_SetEndpFeature(1 , 0);      
USBHSH->HOST_CTRL |= USBHS_UH_TX_BUS_SUSPEND;//控制设备挂起,拉高USBHS_UH_TX_BUS_SUSPEND位10ms左右
Delay_Ms(12);
USBHSH->HOST_CTRL &= ~USBHS_UH_TX_BUS_SUSPEND;
USBHSH->INT_FG |= USBHS_UIF_SUSPEND;

break;
case KEY_1_UP:

TIM_ITConfig( TIM3, TIM_IT_Update, DISABLE ); //关闭定时器更新中断防止异常唤醒。
__WFE();
//__WFI();
printf("wake\r\n");

TIM_ITConfig( TIM3, TIM_IT_Update, ENABLE );   
USBHSH->HOST_CTRL |= USBHS_UH_TX_BUS_RESUME;
Delay_Us(1);
USBHSH->HOST_CTRL &= ~USBHS_UH_TX_BUS_RESUME;
Delay_Ms(40);
USBH_ClearEndpFeature(1, 0);//清楚唤醒标志
break;

case KEY_1_LONG:
break;
case KEY_2_DOWN: //唤醒设备

TIM_ITConfig( TIM3, TIM_IT_Update, ENABLE );
USBHSH->HOST_CTRL |= USBHS_UH_TX_BUS_RESUME;
Delay_Us(1);
USBHSH->HOST_CTRL &= ~USBHS_UH_TX_BUS_RESUME;
Delay_Ms(40);
USBH_ClearEndpFeature(1, 0);

break;
case KEY_2_UP:
break;
case KEY_3_DOWN: //挂起设备
printf("设备挂起\r\n");
USBH_SetEndpFeature(1 , 0);
USBHSH->HOST_CTRL |= USBHS_UH_TX_BUS_SUSPEND;
Delay_Ms(12);
USBHSH->HOST_CTRL &= ~USBHS_UH_TX_BUS_SUSPEND;
USBHSH->INT_FG |= USBHS_UIF_SUSPEND;
break;
case KEY_3_UP:
break;
default:
/* 其它的键值不处理 */
break;
}
}

 

posted @ 2023-12-28 13:36  WCH_CH32  阅读(122)  评论(0编辑  收藏  举报