drv_sdcard.c 2.2 KB

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