main.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. /**
  2. * Copyright (c) 2016 - 2020, Nordic Semiconductor ASA
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without modification,
  7. * are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form, except as embedded into a Nordic
  13. * Semiconductor ASA integrated circuit in a product or a software update for
  14. * such product, must reproduce the above copyright notice, this list of
  15. * conditions and the following disclaimer in the documentation and/or other
  16. * materials provided with the distribution.
  17. *
  18. * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
  19. * contributors may be used to endorse or promote products derived from this
  20. * software without specific prior written permission.
  21. *
  22. * 4. This software, with or without modification, must only be used with a
  23. * Nordic Semiconductor ASA integrated circuit.
  24. *
  25. * 5. Any software provided in binary form under this license must not be reverse
  26. * engineered, decompiled, modified and/or disassembled.
  27. *
  28. * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
  29. * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  30. * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
  31. * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
  32. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  33. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  34. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  35. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  36. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  37. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. *
  39. */
  40. /** @file
  41. *
  42. * @defgroup usbd_msc main.c
  43. * @{
  44. * @ingroup usbd_msc
  45. * @brief usbd msc application main file
  46. *
  47. * This file contains the source code for a sample application to blink LEDs.
  48. *
  49. * Note: Limitation when setting "APP_USBD_CONFIG_EVENT_QUEUE_ENABLE = 0":
  50. * when USB cable is unplugged and re-plugged, the application goes into an endless
  51. * loop.
  52. */
  53. #include <stdint.h>
  54. #include <stdbool.h>
  55. #include <stddef.h>
  56. #include <inttypes.h>
  57. #include <stdlib.h>
  58. #include "nrf.h"
  59. #include "nrf_block_dev.h"
  60. #include "nrf_block_dev_ram.h"
  61. #include "nrf_block_dev_empty.h"
  62. #include "nrf_block_dev_qspi.h"
  63. #include "nrf_block_dev_sdc.h"
  64. #include "nrf_drv_usbd.h"
  65. #include "nrf_drv_clock.h"
  66. #include "nrf_gpio.h"
  67. #include "nrf_atomic.h"
  68. #include "nrf_drv_power.h"
  69. #include "ff.h"
  70. #include "diskio_blkdev.h"
  71. #include "app_usbd.h"
  72. #include "app_usbd_core.h"
  73. #include "app_usbd_string_desc.h"
  74. #include "app_usbd_msc.h"
  75. #include "app_error.h"
  76. #include "app_timer.h"
  77. #include "bsp.h"
  78. #include "nrf_log.h"
  79. #include "nrf_log_ctrl.h"
  80. #include "nrf_log_default_backends.h"
  81. /**@file
  82. * @defgroup usbd_msc_example main.c
  83. * @{
  84. * @ingroup usbd_msc_example
  85. * @brief USBD MSC example
  86. *
  87. */
  88. #define LED_USB_RESUME (BSP_BOARD_LED_0)
  89. #define LED_USB_START (BSP_BOARD_LED_1)
  90. #define BTN_RANDOM_FILE 0
  91. #define BTN_LIST_DIR 1
  92. #define BTN_MKFS 2
  93. #define KEY_EV_RANDOM_FILE_MSK (1U << BTN_RANDOM_FILE)
  94. #define KEY_EV_LIST_DIR_MSK (1U << BTN_LIST_DIR )
  95. #define KEY_EV_MKFS_MSK (1U << BTN_MKFS )
  96. /**
  97. * @brief Enable power USB detection
  98. *
  99. * Configure if example supports USB port connection
  100. */
  101. #ifndef USBD_POWER_DETECTION
  102. #define USBD_POWER_DETECTION true
  103. #endif
  104. /**
  105. * @brief SD card enable/disable
  106. */
  107. #define USE_SD_CARD 0
  108. /**
  109. * @brief FatFS for QPSI enable/disable
  110. */
  111. #define USE_FATFS_QSPI 1
  112. /**
  113. * @brief Mass storage class user event handler
  114. */
  115. static void msc_user_ev_handler(app_usbd_class_inst_t const * p_inst,
  116. app_usbd_msc_user_event_t event);
  117. /**
  118. * @brief Ram block device size
  119. *
  120. * @note Windows fails to format volumes smaller than 190KB
  121. */
  122. #define RAM_BLOCK_DEVICE_SIZE (380 * 512)
  123. /**
  124. * @brief RAM block device work buffer
  125. */
  126. static uint8_t m_block_dev_ram_buff[RAM_BLOCK_DEVICE_SIZE];
  127. /**
  128. * @brief RAM block device definition
  129. */
  130. NRF_BLOCK_DEV_RAM_DEFINE(
  131. m_block_dev_ram,
  132. NRF_BLOCK_DEV_RAM_CONFIG(512, m_block_dev_ram_buff, sizeof(m_block_dev_ram_buff)),
  133. NFR_BLOCK_DEV_INFO_CONFIG("Nordic", "RAM", "1.00")
  134. );
  135. /**
  136. * @brief Empty block device definition
  137. */
  138. NRF_BLOCK_DEV_EMPTY_DEFINE(
  139. m_block_dev_empty,
  140. NRF_BLOCK_DEV_EMPTY_CONFIG(512, 1024 * 1024),
  141. NFR_BLOCK_DEV_INFO_CONFIG("Nordic", "EMPTY", "1.00")
  142. );
  143. /**
  144. * @brief QSPI block device definition
  145. */
  146. NRF_BLOCK_DEV_QSPI_DEFINE(
  147. m_block_dev_qspi,
  148. NRF_BLOCK_DEV_QSPI_CONFIG(
  149. 512,
  150. NRF_BLOCK_DEV_QSPI_FLAG_CACHE_WRITEBACK,
  151. NRF_DRV_QSPI_DEFAULT_CONFIG
  152. ),
  153. NFR_BLOCK_DEV_INFO_CONFIG("Nordic", "QSPI", "1.00")
  154. );
  155. #if USE_SD_CARD
  156. #define SDC_SCK_PIN (27) ///< SDC serial clock (SCK) pin.
  157. #define SDC_MOSI_PIN (26) ///< SDC serial data in (DI) pin.
  158. #define SDC_MISO_PIN (2) ///< SDC serial data out (DO) pin.
  159. #define SDC_CS_PIN (32 + 15) ///< SDC chip select (CS) pin.
  160. /**
  161. * @brief SDC block device definition
  162. */
  163. NRF_BLOCK_DEV_SDC_DEFINE(
  164. m_block_dev_sdc,
  165. NRF_BLOCK_DEV_SDC_CONFIG(
  166. SDC_SECTOR_SIZE,
  167. APP_SDCARD_CONFIG(SDC_MOSI_PIN, SDC_MISO_PIN, SDC_SCK_PIN, SDC_CS_PIN)
  168. ),
  169. NFR_BLOCK_DEV_INFO_CONFIG("Nordic", "SDC", "1.00")
  170. );
  171. /**
  172. * @brief Block devices list passed to @ref APP_USBD_MSC_GLOBAL_DEF
  173. */
  174. #define BLOCKDEV_LIST() ( \
  175. NRF_BLOCKDEV_BASE_ADDR(m_block_dev_ram, block_dev), \
  176. NRF_BLOCKDEV_BASE_ADDR(m_block_dev_empty, block_dev), \
  177. NRF_BLOCKDEV_BASE_ADDR(m_block_dev_qspi, block_dev), \
  178. NRF_BLOCKDEV_BASE_ADDR(m_block_dev_sdc, block_dev) \
  179. )
  180. #else
  181. #define BLOCKDEV_LIST() ( \
  182. NRF_BLOCKDEV_BASE_ADDR(m_block_dev_ram, block_dev), \
  183. NRF_BLOCKDEV_BASE_ADDR(m_block_dev_empty, block_dev), \
  184. NRF_BLOCKDEV_BASE_ADDR(m_block_dev_qspi, block_dev) \
  185. )
  186. #endif
  187. /**
  188. * @brief Endpoint list passed to @ref APP_USBD_MSC_GLOBAL_DEF
  189. */
  190. #define ENDPOINT_LIST() APP_USBD_MSC_ENDPOINT_LIST(1, 1)
  191. /**
  192. * @brief Mass storage class work buffer size
  193. */
  194. #define MSC_WORKBUFFER_SIZE (1024)
  195. /*lint -save -e26 -e64 -e123 -e505 -e651*/
  196. /**
  197. * @brief Mass storage class instance
  198. */
  199. APP_USBD_MSC_GLOBAL_DEF(m_app_msc,
  200. 0,
  201. msc_user_ev_handler,
  202. ENDPOINT_LIST(),
  203. BLOCKDEV_LIST(),
  204. MSC_WORKBUFFER_SIZE);
  205. /*lint -restore*/
  206. /**
  207. * @brief Events from keys
  208. */
  209. static nrf_atomic_u32_t m_key_events;
  210. /**
  211. * @brief USB connection status
  212. */
  213. static bool m_usb_connected = false;
  214. #if USE_FATFS_QSPI
  215. static FATFS m_filesystem;
  216. static bool fatfs_init(void)
  217. {
  218. FRESULT ff_result;
  219. DSTATUS disk_state = STA_NOINIT;
  220. memset(&m_filesystem, 0, sizeof(FATFS));
  221. // Initialize FATFS disk I/O interface by providing the block device.
  222. static diskio_blkdev_t drives[] =
  223. {
  224. DISKIO_BLOCKDEV_CONFIG(NRF_BLOCKDEV_BASE_ADDR(m_block_dev_qspi, block_dev), NULL)
  225. };
  226. diskio_blockdev_register(drives, ARRAY_SIZE(drives));
  227. NRF_LOG_INFO("Initializing disk 0 (QSPI)...");
  228. disk_state = disk_initialize(0);
  229. if (disk_state)
  230. {
  231. NRF_LOG_ERROR("Disk initialization failed.");
  232. return false;
  233. }
  234. NRF_LOG_INFO("Mounting volume...");
  235. ff_result = f_mount(&m_filesystem, "", 1);
  236. if (ff_result != FR_OK)
  237. {
  238. if (ff_result == FR_NO_FILESYSTEM)
  239. {
  240. NRF_LOG_ERROR("Mount failed. Filesystem not found. Please format device.");
  241. }
  242. else
  243. {
  244. NRF_LOG_ERROR("Mount failed: %u", ff_result);
  245. }
  246. return false;
  247. }
  248. return true;
  249. }
  250. static void fatfs_mkfs(void)
  251. {
  252. FRESULT ff_result;
  253. if (m_usb_connected)
  254. {
  255. NRF_LOG_ERROR("Unable to operate on filesystem while USB is connected");
  256. return;
  257. }
  258. NRF_LOG_INFO("\r\nCreating filesystem...");
  259. static uint8_t buf[512];
  260. ff_result = f_mkfs("", FM_FAT, 1024, buf, sizeof(buf));
  261. if (ff_result != FR_OK)
  262. {
  263. NRF_LOG_ERROR("Mkfs failed.");
  264. return;
  265. }
  266. NRF_LOG_INFO("Mounting volume...");
  267. ff_result = f_mount(&m_filesystem, "", 1);
  268. if (ff_result != FR_OK)
  269. {
  270. NRF_LOG_ERROR("Mount failed.");
  271. return;
  272. }
  273. NRF_LOG_INFO("Done");
  274. }
  275. static void fatfs_ls(void)
  276. {
  277. DIR dir;
  278. FRESULT ff_result;
  279. FILINFO fno;
  280. if (m_usb_connected)
  281. {
  282. NRF_LOG_ERROR("Unable to operate on filesystem while USB is connected");
  283. return;
  284. }
  285. NRF_LOG_INFO("\r\nListing directory: /");
  286. ff_result = f_opendir(&dir, "/");
  287. if (ff_result != FR_OK)
  288. {
  289. NRF_LOG_ERROR("Directory listing failed: %u", ff_result);
  290. return;
  291. }
  292. uint32_t entries_count = 0;
  293. do
  294. {
  295. ff_result = f_readdir(&dir, &fno);
  296. if (ff_result != FR_OK)
  297. {
  298. NRF_LOG_ERROR("Directory read failed: %u", ff_result);
  299. return;
  300. }
  301. if (fno.fname[0])
  302. {
  303. if (fno.fattrib & AM_DIR)
  304. {
  305. NRF_LOG_RAW_INFO(" <DIR> %s\r\n",(uint32_t)fno.fname);
  306. }
  307. else
  308. {
  309. NRF_LOG_RAW_INFO("%9lu %s\r\n", fno.fsize, (uint32_t)fno.fname);
  310. }
  311. }
  312. ++entries_count;
  313. NRF_LOG_FLUSH();
  314. } while (fno.fname[0]);
  315. NRF_LOG_RAW_INFO("Entries count: %u\r\n", entries_count);
  316. }
  317. static void fatfs_file_create(void)
  318. {
  319. FRESULT ff_result;
  320. FIL file;
  321. char filename[16];
  322. if (m_usb_connected)
  323. {
  324. NRF_LOG_ERROR("Unable to operate on filesystem while USB is connected");
  325. return;
  326. }
  327. (void)snprintf(filename, sizeof(filename), "%08x.txt", rand());
  328. NRF_LOG_RAW_INFO("Creating random file: %s ...", (uint32_t)filename);
  329. NRF_LOG_FLUSH();
  330. ff_result = f_open(&file, filename, FA_CREATE_ALWAYS | FA_WRITE);
  331. if (ff_result != FR_OK)
  332. {
  333. NRF_LOG_ERROR("\r\nUnable to open or create file: %u", ff_result);
  334. NRF_LOG_FLUSH();
  335. return;
  336. }
  337. ff_result = f_close(&file);
  338. if (ff_result != FR_OK)
  339. {
  340. NRF_LOG_ERROR("\r\nUnable to close file: %u", ff_result);
  341. NRF_LOG_FLUSH();
  342. return;
  343. }
  344. NRF_LOG_RAW_INFO("done\r\n");
  345. }
  346. static void fatfs_uninit(void)
  347. {
  348. NRF_LOG_INFO("Un-initializing disk 0 (QSPI)...");
  349. UNUSED_RETURN_VALUE(disk_uninitialize(0));
  350. }
  351. #else //USE_FATFS_QSPI
  352. #define fatfs_init() false
  353. #define fatfs_mkfs() do { } while (0)
  354. #define fatfs_ls() do { } while (0)
  355. #define fatfs_file_create() do { } while (0)
  356. #define fatfs_uninit() do { } while (0)
  357. #endif
  358. /**
  359. * @brief Class specific event handler.
  360. *
  361. * @param p_inst Class instance.
  362. * @param event Class specific event.
  363. */
  364. static void msc_user_ev_handler(app_usbd_class_inst_t const * p_inst,
  365. app_usbd_msc_user_event_t event)
  366. {
  367. UNUSED_PARAMETER(p_inst);
  368. UNUSED_PARAMETER(event);
  369. }
  370. /**
  371. * @brief USBD library specific event handler.
  372. *
  373. * @param event USBD library event.
  374. */
  375. static void usbd_user_ev_handler(app_usbd_event_type_t event)
  376. {
  377. switch (event)
  378. {
  379. case APP_USBD_EVT_DRV_SUSPEND:
  380. bsp_board_led_off(LED_USB_RESUME);
  381. break;
  382. case APP_USBD_EVT_DRV_RESUME:
  383. bsp_board_led_on(LED_USB_RESUME);
  384. break;
  385. case APP_USBD_EVT_STARTED:
  386. bsp_board_led_on(LED_USB_START);
  387. break;
  388. case APP_USBD_EVT_STOPPED:
  389. UNUSED_RETURN_VALUE(fatfs_init());
  390. app_usbd_disable();
  391. bsp_board_leds_off();
  392. break;
  393. case APP_USBD_EVT_POWER_DETECTED:
  394. NRF_LOG_INFO("USB power detected");
  395. if (!nrf_drv_usbd_is_enabled())
  396. {
  397. fatfs_uninit();
  398. app_usbd_enable();
  399. }
  400. break;
  401. case APP_USBD_EVT_POWER_REMOVED:
  402. NRF_LOG_INFO("USB power removed");
  403. app_usbd_stop();
  404. m_usb_connected = false;
  405. break;
  406. case APP_USBD_EVT_POWER_READY:
  407. NRF_LOG_INFO("USB ready");
  408. app_usbd_start();
  409. m_usb_connected = true;
  410. break;
  411. default:
  412. break;
  413. }
  414. }
  415. static void bsp_event_callback(bsp_event_t ev)
  416. {
  417. switch (ev)
  418. {
  419. /* Just set a flag to be processed in the main loop */
  420. case CONCAT_2(BSP_EVENT_KEY_, BTN_RANDOM_FILE):
  421. UNUSED_RETURN_VALUE(nrf_atomic_u32_or(&m_key_events, KEY_EV_RANDOM_FILE_MSK));
  422. break;
  423. case CONCAT_2(BSP_EVENT_KEY_, BTN_LIST_DIR):
  424. UNUSED_RETURN_VALUE(nrf_atomic_u32_or(&m_key_events, KEY_EV_LIST_DIR_MSK));
  425. break;
  426. case CONCAT_2(BSP_EVENT_KEY_, BTN_MKFS):
  427. UNUSED_RETURN_VALUE(nrf_atomic_u32_or(&m_key_events, KEY_EV_MKFS_MSK));
  428. break;
  429. default:
  430. return; // no implementation needed
  431. }
  432. }
  433. int main(void)
  434. {
  435. ret_code_t ret;
  436. static const app_usbd_config_t usbd_config = {
  437. .ev_state_proc = usbd_user_ev_handler
  438. };
  439. ret = NRF_LOG_INIT(app_usbd_sof_timestamp_get);
  440. APP_ERROR_CHECK(ret);
  441. NRF_LOG_DEFAULT_BACKENDS_INIT();
  442. ret = nrf_drv_clock_init();
  443. APP_ERROR_CHECK(ret);
  444. /* Fill whole RAM block device buffer */
  445. for (size_t i = 0; i < sizeof(m_block_dev_ram_buff); ++i)
  446. {
  447. m_block_dev_ram_buff[i] = i;
  448. }
  449. /* Configure LEDs and buttons */
  450. nrf_drv_clock_lfclk_request(NULL);
  451. ret = app_timer_init();
  452. APP_ERROR_CHECK(ret);
  453. ret = bsp_init(BSP_INIT_BUTTONS, bsp_event_callback);
  454. APP_ERROR_CHECK(ret);
  455. bsp_board_init(BSP_INIT_LEDS);
  456. if (fatfs_init())
  457. {
  458. fatfs_ls();
  459. fatfs_file_create();
  460. }
  461. ret = app_usbd_init(&usbd_config);
  462. APP_ERROR_CHECK(ret);
  463. app_usbd_class_inst_t const * class_inst_msc = app_usbd_msc_class_inst_get(&m_app_msc);
  464. ret = app_usbd_class_append(class_inst_msc);
  465. APP_ERROR_CHECK(ret);
  466. NRF_LOG_INFO("USBD MSC example started.");
  467. if (USBD_POWER_DETECTION)
  468. {
  469. ret = app_usbd_power_events_enable();
  470. APP_ERROR_CHECK(ret);
  471. }
  472. else
  473. {
  474. NRF_LOG_INFO("No USB power detection enabled\r\nStarting USB now");
  475. app_usbd_enable();
  476. app_usbd_start();
  477. m_usb_connected = true;
  478. }
  479. while (true)
  480. {
  481. while (app_usbd_event_queue_process())
  482. {
  483. /* Nothing to do */
  484. }
  485. /* Process BSP key events flags.*/
  486. uint32_t events = nrf_atomic_u32_fetch_store(&m_key_events, 0);
  487. if (events & KEY_EV_RANDOM_FILE_MSK)
  488. {
  489. fatfs_file_create();
  490. }
  491. if (events & KEY_EV_LIST_DIR_MSK)
  492. {
  493. fatfs_ls();
  494. }
  495. if (events & KEY_EV_MKFS_MSK)
  496. {
  497. fatfs_mkfs();
  498. }
  499. UNUSED_RETURN_VALUE(NRF_LOG_PROCESS());
  500. /* Sleep CPU only if there was no interrupt since last loop processing */
  501. __WFE();
  502. }
  503. }
  504. /** @} */