1 /*
2 * Copyright (c) 2006-2021, RT-Thread Development Team
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 *
6 * Change Logs:
7 * Date Author Notes
8 * 2018-12-13 balanceTWK add sdcard port file
9 * 2019-06-11 WillianChan Add SD card hot plug detection
10 */
11
12 #include <rtthread.h>
13
14 #ifdef BSP_USING_SDCARD
15
16 #include <dfs_elm.h>
17 #include <dfs_fs.h>
18 #include <dfs_file.h>
19 #include <unistd.h>
20 #include <stdio.h>
21 #include <sys/stat.h>
22 #include <sys/statfs.h>
23 #include "drv_gpio.h"
24 #include "drv_sdio.h"
25
26 #define DBG_TAG "app.card"
27 #define DBG_LVL DBG_INFO
28 #include <rtdbg.h>
29
30 /* SD Card hot plug detection pin */
31 #define SD_CHECK_PIN GET_PIN(G, 2)
32
_sdcard_mount(void)33 static void _sdcard_mount(void)
34 {
35 rt_device_t device;
36
37 device = rt_device_find("sd0");
38 if (device == NULL)
39 {
40 mmcsd_wait_cd_changed(0);
41 stm32_mmcsd_change();
42 mmcsd_wait_cd_changed(RT_WAITING_FOREVER);
43 device = rt_device_find("sd0");
44 }
45 if (device != RT_NULL)
46 {
47 if (dfs_mount("sd0", "/", "elm", 0, 0) == RT_EOK)
48 {
49 LOG_I("sd card mount to '/'");
50 }
51 else
52 {
53 LOG_W("sd card mount to '/' failed!");
54 }
55 }
56 }
57
_sdcard_unmount(void)58 static void _sdcard_unmount(void)
59 {
60 rt_thread_mdelay(200);
61 dfs_unmount("/");
62 LOG_I("Unmount \"/\"");
63
64 mmcsd_wait_cd_changed(0);
65 stm32_mmcsd_change();
66 mmcsd_wait_cd_changed(RT_WAITING_FOREVER);
67 }
68
sd_mount(void * parameter)69 static void sd_mount(void *parameter)
70 {
71 rt_uint8_t re_sd_check_pin = 1;
72
73 while (1)
74 {
75 rt_thread_mdelay(200);
76 if(re_sd_check_pin && (re_sd_check_pin = rt_pin_read(SD_CHECK_PIN)) == 0)
77 {
78 _sdcard_mount();
79 }
80
81 if (!re_sd_check_pin && (re_sd_check_pin = rt_pin_read(SD_CHECK_PIN)) != 0)
82 {
83 _sdcard_unmount();
84 }
85 }
86 }
87
stm32_sdcard_mount(void)88 int stm32_sdcard_mount(void)
89 {
90 rt_thread_t tid;
91
92 rt_pin_mode(SD_CHECK_PIN, PIN_MODE_INPUT_PULLUP);
93
94 tid = rt_thread_create("sd_mount", sd_mount, RT_NULL,
95 1024, RT_THREAD_PRIORITY_MAX - 2, 20);
96 if (tid != RT_NULL)
97 {
98 rt_thread_startup(tid);
99 }
100 else
101 {
102 LOG_E("create sd_mount thread err!");
103 }
104 return RT_EOK;
105 }
106 INIT_APP_EXPORT(stm32_sdcard_mount);
107
108 #endif /* BSP_USING_SDCARD */
109