drv_sdcard.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. #include <rtthread.h>
  12. #ifdef BSP_USING_SDCARD
  13. #include <dfs_elm.h>
  14. #include <dfs_fs.h>
  15. #include <dfs_file.h>
  16. #include <unistd.h>
  17. #include <stdio.h>
  18. #include <sys/stat.h>
  19. #include <sys/statfs.h>
  20. #include "drv_gpio.h"
  21. #include "drv_sdio.h"
  22. #define DBG_TAG "app.card"
  23. #define DBG_LVL DBG_INFO
  24. #include <rtdbg.h>
  25. /* SD Card hot plug detection pin */
  26. #define SD_CHECK_PIN GET_PIN(G, 2)
  27. static void _sdcard_mount(void)
  28. {
  29. rt_device_t device;
  30. device = rt_device_find("sd0");
  31. if (device == NULL)
  32. {
  33. mmcsd_wait_cd_changed(0);
  34. stm32_mmcsd_change();
  35. mmcsd_wait_cd_changed(RT_WAITING_FOREVER);
  36. device = rt_device_find("sd0");
  37. }
  38. if (device != RT_NULL)
  39. {
  40. if (dfs_mount("sd0", "/", "elm", 0, 0) == RT_EOK)
  41. {
  42. LOG_I("sd card mount to '/'");
  43. }
  44. else
  45. {
  46. LOG_W("sd card mount to '/' failed!");
  47. }
  48. }
  49. }
  50. static void _sdcard_unmount(void)
  51. {
  52. rt_thread_mdelay(200);
  53. dfs_unmount("/");
  54. LOG_I("Unmount \"/\"");
  55. mmcsd_wait_cd_changed(0);
  56. stm32_mmcsd_change();
  57. mmcsd_wait_cd_changed(RT_WAITING_FOREVER);
  58. }
  59. static void sd_mount(void *parameter)
  60. {
  61. rt_uint8_t re_sd_check_pin = 1;
  62. while (1)
  63. {
  64. rt_thread_mdelay(200);
  65. if(re_sd_check_pin && (re_sd_check_pin = rt_pin_read(SD_CHECK_PIN)) == 0)
  66. {
  67. _sdcard_mount();
  68. }
  69. if (!re_sd_check_pin && (re_sd_check_pin = rt_pin_read(SD_CHECK_PIN)) != 0)
  70. {
  71. _sdcard_unmount();
  72. }
  73. }
  74. }
  75. int stm32_sdcard_mount(void)
  76. {
  77. rt_thread_t tid;
  78. rt_pin_mode(SD_CHECK_PIN, PIN_MODE_INPUT_PULLUP);
  79. tid = rt_thread_create("sd_mount", sd_mount, RT_NULL,
  80. 1024, RT_THREAD_PRIORITY_MAX - 2, 20);
  81. if (tid != RT_NULL)
  82. {
  83. rt_thread_startup(tid);
  84. }
  85. else
  86. {
  87. LOG_E("create sd_mount thread err!");
  88. }
  89. return RT_EOK;
  90. }
  91. INIT_APP_EXPORT(stm32_sdcard_mount);
  92. #endif /* BSP_USING_SDCARD */