main.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  1. /**
  2. * Copyright (c) 2014 - 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 ble_sdk_uart_over_ble_main main.c
  43. * @{
  44. * @ingroup ble_sdk_app_nus_eval
  45. * @brief UART over BLE application main file.
  46. *
  47. * This file contains the source code for a sample application that uses the Nordic UART service.
  48. * This application uses the @ref srvlib_conn_params module.
  49. */
  50. #include <stdint.h>
  51. #include <string.h>
  52. #include "nordic_common.h"
  53. #include "nrf.h"
  54. #include "ble_hci.h"
  55. #include "ble_advdata.h"
  56. #include "ble_advertising.h"
  57. #include "ble_conn_params.h"
  58. #include "nrf_sdh.h"
  59. #include "nrf_sdh_soc.h"
  60. #include "nrf_sdh_ble.h"
  61. #include "nrf_ble_gatt.h"
  62. #include "nrf_ble_qwr.h"
  63. #include "app_timer.h"
  64. #include "ble_nus.h"
  65. #include "app_uart.h"
  66. #include "app_util_platform.h"
  67. #include "bsp_btn_ble.h"
  68. #include "nrf_pwr_mgmt.h"
  69. #include "user_Sleep.h"
  70. #include "twi_master.h"
  71. #include "mpu6050.h"
  72. #include "footPDR.h"
  73. #include "MSE5611.h"
  74. #include "nrf_drv_timer.h"
  75. #include "nrf_drv_gpiote.h"
  76. #include "nrf_drv_saadc.h"
  77. #include "nrf_saadc.h"
  78. #include "nrf_drv_timer.h"
  79. #include "app_timer.h"
  80. #include "main.h"
  81. #include "app.h"
  82. //#include "mpu6050.h"
  83. //#include "inv_mpu.h"
  84. //#include "inv_mpu_dmp_motion_driver.h"
  85. //#include "imu.h"
  86. //#include "mpu9250.h"
  87. #include "nrf_delay.h"
  88. #if defined (UART_PRESENT)
  89. #include "nrf_uart.h"
  90. #endif
  91. #if defined (UARTE_PRESENT)
  92. #include "nrf_uarte.h"
  93. #endif
  94. #include "nrf_log.h"
  95. #include "nrf_log_ctrl.h"
  96. #include "nrf_log_default_backends.h"
  97. #define PIN_OUT 16
  98. #define APP_BLE_CONN_CFG_TAG 1 /**< A tag identifying the SoftDevice BLE configuration. */
  99. #define DEVICE_NAME "SH_chen" /**< Name of device. Will be included in the advertising data. */
  100. #define NUS_SERVICE_UUID_TYPE BLE_UUID_TYPE_VENDOR_BEGIN /**< UUID type for the Nordic UART Service (vendor specific). */
  101. #define APP_BLE_OBSERVER_PRIO 3 /**< Application's BLE observer priority. You shouldn't need to modify this value. */
  102. #define APP_ADV_INTERVAL 64 /**< The advertising interval (in units of 0.625 ms. This value corresponds to 40 ms). */
  103. #define APP_ADV_DURATION 18000 /**< The advertising duration (180 seconds) in units of 10 milliseconds. */
  104. #define MIN_CONN_INTERVAL MSEC_TO_UNITS(20, UNIT_1_25_MS) /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
  105. #define MAX_CONN_INTERVAL MSEC_TO_UNITS(75, UNIT_1_25_MS) /**< Maximum acceptable connection interval (75 ms), Connection interval uses 1.25 ms units. */
  106. #define SLAVE_LATENCY 0 /**< Slave latency. */
  107. #define CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS) /**< Connection supervisory timeout (4 seconds), Supervision Timeout uses 10 ms units. */
  108. #define FIRST_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(5000) /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
  109. #define NEXT_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(30000) /**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
  110. #define MAX_CONN_PARAMS_UPDATE_COUNT 3 /**< Number of attempts before giving up the connection parameter negotiation. */
  111. #define DEAD_BEEF 0xDEADBEEF /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */
  112. #define UART_TX_BUF_SIZE 256 /**< UART TX buffer size. */
  113. #define UART_RX_BUF_SIZE 256 /**< UART RX buffer size. */
  114. BLE_NUS_DEF(m_nus, NRF_SDH_BLE_TOTAL_LINK_COUNT); /**< BLE NUS service instance. */
  115. NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
  116. NRF_BLE_QWR_DEF(m_qwr); /**< Context for the Queued Write module.*/
  117. BLE_ADVERTISING_DEF(m_advertising); /**< Advertising module instance. */
  118. static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the current connection. */
  119. static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - 3; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
  120. static ble_uuid_t m_adv_uuids[] = /**< Universally unique service identifier. */
  121. {
  122. {BLE_UUID_NUS_SERVICE, NUS_SERVICE_UUID_TYPE}
  123. };
  124. /**@brief Function for assert macro callback.
  125. *
  126. * @details This function will be called in case of an assert in the SoftDevice.
  127. *
  128. * @warning This handler is an example only and does not fit a final product. You need to analyse
  129. * how your product is supposed to react in case of Assert.
  130. * @warning On assert from the SoftDevice, the system can only recover on reset.
  131. *
  132. * @param[in] line_num Line number of the failing ASSERT call.
  133. * @param[in] p_file_name File name of the failing ASSERT call.
  134. */
  135. void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
  136. {
  137. app_error_handler(DEAD_BEEF, line_num, p_file_name);
  138. }
  139. /**@brief Function for initializing the timer module.
  140. */
  141. static void timers_init(void)
  142. {
  143. ret_code_t err_code = app_timer_init();
  144. APP_ERROR_CHECK(err_code);
  145. }
  146. /**@brief Function for the GAP initialization.
  147. *
  148. * @details This function will set up all the necessary GAP (Generic Access Profile) parameters of
  149. * the device. It also sets the permissions and appearance.
  150. */
  151. static void gap_params_init(void)
  152. {
  153. uint32_t err_code;
  154. ble_gap_addr_t m_my_addr;
  155. ble_gap_conn_params_t gap_conn_params;
  156. ble_gap_conn_sec_mode_t sec_mode;
  157. char BleReallyName[30]={0};
  158. BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
  159. err_code = sd_ble_gap_addr_get(&m_my_addr);
  160. APP_ERROR_CHECK(err_code);
  161. //sprintf(BleReallyName,"%s_%02x%02x%02x",DEVICE_NAME,m_my_addr.addr[2],m_my_addr.addr[1],m_my_addr.addr[0]);
  162. err_code = sd_ble_gap_device_name_set(&sec_mode,
  163. (const uint8_t *) DEVICE_NAME,
  164. strlen(DEVICE_NAME));
  165. APP_ERROR_CHECK(err_code);
  166. memset(&gap_conn_params, 0, sizeof(gap_conn_params));
  167. gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
  168. gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
  169. gap_conn_params.slave_latency = SLAVE_LATENCY;
  170. gap_conn_params.conn_sup_timeout = CONN_SUP_TIMEOUT;
  171. err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
  172. APP_ERROR_CHECK(err_code);
  173. }
  174. /**@brief Function for handling Queued Write Module errors.
  175. *
  176. * @details A pointer to this function will be passed to each service which may need to inform the
  177. * application about an error.
  178. *
  179. * @param[in] nrf_error Error code containing information about what went wrong.
  180. */
  181. static void nrf_qwr_error_handler(uint32_t nrf_error)
  182. {
  183. APP_ERROR_HANDLER(nrf_error);
  184. }
  185. /**@brief Function for handling the data from the Nordic UART Service.
  186. *
  187. * @details This function will process the data received from the Nordic UART BLE Service and send
  188. * it to the UART module.
  189. *
  190. * @param[in] p_evt Nordic UART Service event.
  191. */
  192. /**@snippet [Handling the data received over BLE] */
  193. static void nus_data_handler(ble_nus_evt_t * p_evt)
  194. {
  195. if (p_evt->type == BLE_NUS_EVT_RX_DATA)
  196. {
  197. uint32_t err_code;
  198. // printf("Received data from BLE NUS. Writing data on UART.");
  199. NRF_LOG_HEXDUMP_DEBUG(p_evt->params.rx_data.p_data, p_evt->params.rx_data.length);
  200. ble_phone_command_callback(p_evt->params.rx_data.p_data,p_evt->params.rx_data.length);
  201. for (uint32_t i = 0; i < p_evt->params.rx_data.length; i++)
  202. {
  203. do
  204. {
  205. err_code = app_uart_put(p_evt->params.rx_data.p_data[i]);
  206. if ((err_code != NRF_SUCCESS) && (err_code != NRF_ERROR_BUSY))
  207. {
  208. // printf("Failed receiving NUS message. Error 0x%x. ", err_code);
  209. APP_ERROR_CHECK(err_code);
  210. }
  211. } while (err_code == NRF_ERROR_BUSY);
  212. }
  213. // if (p_evt->params.rx_data.p_data[p_evt->params.rx_data.length - 1] == '\r')
  214. // {
  215. // while (app_uart_put('\n') == NRF_ERROR_BUSY);
  216. // }
  217. }
  218. }
  219. /**@snippet [Handling the data received over BLE] */
  220. /**@brief Function for initializing services that will be used by the application.
  221. */
  222. static void services_init(void)
  223. {
  224. uint32_t err_code;
  225. ble_nus_init_t nus_init;
  226. nrf_ble_qwr_init_t qwr_init = {0};
  227. // Initialize Queued Write Module.
  228. qwr_init.error_handler = nrf_qwr_error_handler;
  229. err_code = nrf_ble_qwr_init(&m_qwr, &qwr_init);
  230. APP_ERROR_CHECK(err_code);
  231. // Initialize NUS.
  232. memset(&nus_init, 0, sizeof(nus_init));
  233. nus_init.data_handler = nus_data_handler;
  234. err_code = ble_nus_init(&m_nus, &nus_init);
  235. APP_ERROR_CHECK(err_code);
  236. }
  237. /**@brief Function for handling an event from the Connection Parameters Module.
  238. *
  239. * @details This function will be called for all events in the Connection Parameters Module
  240. * which are passed to the application.
  241. *
  242. * @note All this function does is to disconnect. This could have been done by simply setting
  243. * the disconnect_on_fail config parameter, but instead we use the event handler
  244. * mechanism to demonstrate its use.
  245. *
  246. * @param[in] p_evt Event received from the Connection Parameters Module.
  247. */
  248. static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
  249. {
  250. uint32_t err_code;
  251. if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
  252. {
  253. err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
  254. APP_ERROR_CHECK(err_code);
  255. }
  256. }
  257. /**@brief Function for handling errors from the Connection Parameters module.
  258. *
  259. * @param[in] nrf_error Error code containing information about what went wrong.
  260. */
  261. static void conn_params_error_handler(uint32_t nrf_error)
  262. {
  263. APP_ERROR_HANDLER(nrf_error);
  264. }
  265. /**@brief Function for initializing the Connection Parameters module.
  266. */
  267. static void conn_params_init(void)
  268. {
  269. uint32_t err_code;
  270. ble_conn_params_init_t cp_init;
  271. memset(&cp_init, 0, sizeof(cp_init));
  272. cp_init.p_conn_params = NULL;
  273. cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
  274. cp_init.next_conn_params_update_delay = NEXT_CONN_PARAMS_UPDATE_DELAY;
  275. cp_init.max_conn_params_update_count = MAX_CONN_PARAMS_UPDATE_COUNT;
  276. cp_init.start_on_notify_cccd_handle = BLE_GATT_HANDLE_INVALID;
  277. cp_init.disconnect_on_fail = false;
  278. cp_init.evt_handler = on_conn_params_evt;
  279. cp_init.error_handler = conn_params_error_handler;
  280. err_code = ble_conn_params_init(&cp_init);
  281. APP_ERROR_CHECK(err_code);
  282. }
  283. /**@brief Function for putting the chip into sleep mode.
  284. *
  285. * @note This function will not return.
  286. */
  287. static void sleep_mode_enter(void)
  288. {
  289. uint32_t err_code = bsp_indication_set(BSP_INDICATE_IDLE);
  290. APP_ERROR_CHECK(err_code);
  291. // Prepare wakeup buttons.
  292. err_code = bsp_btn_ble_sleep_mode_prepare();
  293. APP_ERROR_CHECK(err_code);
  294. // Go to system-off mode (this function will not return; wakeup will cause a reset).
  295. err_code = sd_power_system_off();
  296. APP_ERROR_CHECK(err_code);
  297. }
  298. /**@brief Function for starting advertising.
  299. */
  300. void advertising_start(void)
  301. {
  302. uint32_t err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
  303. APP_ERROR_CHECK(err_code);
  304. }
  305. /**@brief Function for handling advertising events.
  306. *
  307. * @details This function will be called for advertising events which are passed to the application.
  308. *
  309. * @param[in] ble_adv_evt Advertising event.
  310. */
  311. static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
  312. {
  313. uint32_t err_code;
  314. switch (ble_adv_evt)
  315. {
  316. case BLE_ADV_EVT_FAST:
  317. err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
  318. APP_ERROR_CHECK(err_code);
  319. break;
  320. case BLE_ADV_EVT_IDLE:
  321. //advertising_start();
  322. //low_power_in();
  323. break;
  324. default:
  325. break;
  326. }
  327. }
  328. /**@brief Function for handling BLE events.
  329. *
  330. * @param[in] p_ble_evt Bluetooth stack event.
  331. * @param[in] p_context Unused.
  332. */
  333. static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
  334. {
  335. uint32_t err_code;
  336. switch (p_ble_evt->header.evt_id)
  337. {
  338. case BLE_GAP_EVT_CONNECTED:
  339. printf("Connected\r\n");
  340. nrf_drv_gpiote_out_clear(PIN_OUT);
  341. err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
  342. APP_ERROR_CHECK(err_code);
  343. m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
  344. err_code = nrf_ble_qwr_conn_handle_assign(&m_qwr, m_conn_handle);
  345. APP_ERROR_CHECK(err_code);
  346. break;
  347. case BLE_GAP_EVT_DISCONNECTED:
  348. printf("Disconnected\r\n");
  349. nrf_drv_gpiote_out_set(PIN_OUT);
  350. // LED indication will be changed when advertising starts.
  351. m_conn_handle = BLE_CONN_HANDLE_INVALID;
  352. break;
  353. case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
  354. {
  355. printf("PHY update request.");
  356. ble_gap_phys_t const phys =
  357. {
  358. .rx_phys = BLE_GAP_PHY_AUTO,
  359. .tx_phys = BLE_GAP_PHY_AUTO,
  360. };
  361. err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
  362. APP_ERROR_CHECK(err_code);
  363. } break;
  364. case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
  365. // Pairing not supported
  366. err_code = sd_ble_gap_sec_params_reply(m_conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
  367. APP_ERROR_CHECK(err_code);
  368. break;
  369. case BLE_GATTS_EVT_SYS_ATTR_MISSING:
  370. // No system attributes have been stored.
  371. err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0, 0);
  372. APP_ERROR_CHECK(err_code);
  373. break;
  374. case BLE_GATTC_EVT_TIMEOUT:
  375. // Disconnect on GATT Client timeout event.
  376. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
  377. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  378. APP_ERROR_CHECK(err_code);
  379. break;
  380. case BLE_GATTS_EVT_TIMEOUT:
  381. // Disconnect on GATT Server timeout event.
  382. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
  383. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  384. APP_ERROR_CHECK(err_code);
  385. break;
  386. default:
  387. // No implementation needed.
  388. break;
  389. }
  390. }
  391. /**@brief Function for the SoftDevice initialization.
  392. *
  393. * @details This function initializes the SoftDevice and the BLE event interrupt.
  394. */
  395. static void ble_stack_init(void)
  396. {
  397. ret_code_t err_code;
  398. err_code = nrf_sdh_enable_request();
  399. APP_ERROR_CHECK(err_code);
  400. // Configure the BLE stack using the default settings.
  401. // Fetch the start address of the application RAM.
  402. uint32_t ram_start = 0;
  403. err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
  404. APP_ERROR_CHECK(err_code);
  405. // Enable BLE stack.
  406. err_code = nrf_sdh_ble_enable(&ram_start);
  407. APP_ERROR_CHECK(err_code);
  408. // Register a handler for BLE events.
  409. NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
  410. }
  411. /**@brief Function for handling events from the GATT library. */
  412. void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt)
  413. {
  414. if ((m_conn_handle == p_evt->conn_handle) && (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED))
  415. {
  416. m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
  417. printf("Data len is set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
  418. }
  419. printf("ATT MTU exchange completed. central 0x%x peripheral 0x%x",
  420. p_gatt->att_mtu_desired_central,
  421. p_gatt->att_mtu_desired_periph);
  422. }
  423. /**@brief Function for initializing the GATT library. */
  424. void gatt_init(void)
  425. {
  426. ret_code_t err_code;
  427. err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
  428. APP_ERROR_CHECK(err_code);
  429. err_code = nrf_ble_gatt_att_mtu_periph_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
  430. APP_ERROR_CHECK(err_code);
  431. }
  432. /**@brief Function for handling events from the BSP module.
  433. *
  434. * @param[in] event Event generated by button press.
  435. */
  436. void bsp_event_handler(bsp_event_t event)
  437. {
  438. uint32_t err_code;
  439. switch (event)
  440. {
  441. case BSP_EVENT_SLEEP:
  442. printf("BSP_EVENT_SLEEP \r\n");
  443. // sleep_mode_enter();
  444. advertising_start();
  445. break;
  446. case BSP_EVENT_DISCONNECT:
  447. printf("BSP_EVENT_DISCONNECT \r\n");
  448. err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  449. if (err_code != NRF_ERROR_INVALID_STATE)
  450. {
  451. APP_ERROR_CHECK(err_code);
  452. }
  453. break;
  454. case BSP_EVENT_WHITELIST_OFF:
  455. printf("BSP_EVENT_WHITELIST_OFF \r\n");
  456. if (m_conn_handle == BLE_CONN_HANDLE_INVALID)
  457. {
  458. err_code = ble_advertising_restart_without_whitelist(&m_advertising);
  459. if (err_code != NRF_ERROR_INVALID_STATE)
  460. {
  461. APP_ERROR_CHECK(err_code);
  462. }
  463. }
  464. break;
  465. case BSP_EVENT_KEY_0:
  466. printf("1");
  467. break;
  468. default:
  469. break;
  470. }
  471. }
  472. /**@brief Function for handling app_uart events.
  473. *
  474. * @details This function will receive a single character from the app_uart module and append it to
  475. * a string. The string will be be sent over BLE when the last character received was a
  476. * 'new line' '\n' (hex 0x0A) or if the string has reached the maximum data length.
  477. */
  478. /**@snippet [Handling the data received over UART] */
  479. void uart_event_handle(app_uart_evt_t * p_event)
  480. {
  481. static uint8_t state = 0;
  482. static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
  483. static uint8_t index = 0;
  484. static uint8_t len = 0;
  485. uint8_t i;
  486. uint32_t err_code;
  487. int rev=-1;
  488. switch (p_event->evt_type)
  489. {
  490. case APP_UART_DATA_READY:
  491. UNUSED_VARIABLE(app_uart_get(&data_array[index]));
  492. index++;
  493. switch(state){
  494. case 0:{
  495. if(index>=3){
  496. // for(i=0;i<index;i++){printf("%02X ",data_array[i]);}printf("\r\n");
  497. if(data_array[0]==0xAA && data_array[1]==(uint8_t)(~data_array[2])){
  498. len = data_array[1];
  499. state = 1;
  500. }else{
  501. index--;
  502. for(i=0;i<index;i++){
  503. data_array[i] = data_array[i+1];
  504. }
  505. }
  506. }
  507. }break;
  508. case 1:{
  509. if(index>=len){
  510. uint8_t ver = 0;
  511. for(i=0;i<len-1;i++){
  512. ver += data_array[i];
  513. }
  514. if(ver==data_array[len-1])
  515. { //校验成功
  516. rev=uart_command_callback(data_array,len);
  517. // if(rev==CMD_MOTION)
  518. // {
  519. // do{
  520. // uint16_t len_send = len;
  521. // err_code = ble_nus_data_send(&m_nus, data_array, &len_send, m_conn_handle);
  522. // if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_ERROR_RESOURCES) && (err_code != NRF_ERROR_NOT_FOUND)){
  523. // APP_ERROR_CHECK(err_code);
  524. // }
  525. // } while (err_code == NRF_ERROR_RESOURCES);
  526. // }
  527. index = index-len;
  528. }
  529. else
  530. {
  531. index--;
  532. for(i=0;i<index;i++){
  533. data_array[i] = data_array[i+1];
  534. }
  535. }
  536. state = 0;
  537. }
  538. }break;
  539. default:state = 0;index=0;break;
  540. }
  541. case APP_UART_COMMUNICATION_ERROR:
  542. // APP_ERROR_HANDLER(p_event->data.error_communication);
  543. break;
  544. case APP_UART_FIFO_ERROR:
  545. printf("APP_UART_FIFO_ERROR\r\n");
  546. APP_ERROR_HANDLER(p_event->data.error_code);
  547. break;
  548. default:
  549. break;
  550. }
  551. }
  552. int Send_bytes_to_Ble(unsigned char *bytes,int len)
  553. {
  554. uint32_t err_code;
  555. do{
  556. uint16_t len_send = len;
  557. err_code = ble_nus_data_send(&m_nus, bytes, &len_send, m_conn_handle);
  558. if ((err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_ERROR_RESOURCES) && (err_code != NRF_ERROR_NOT_FOUND)){
  559. APP_ERROR_CHECK(err_code);
  560. }
  561. } while (err_code == NRF_ERROR_RESOURCES);
  562. }
  563. /**@snippet [Handling the data received over UART] */
  564. /**@brief Function for initializing the UART module.
  565. */
  566. /**@snippet [UART Initialization] */
  567. void uart_init(void)
  568. {
  569. uint32_t err_code;
  570. app_uart_comm_params_t const comm_params =
  571. {
  572. .rx_pin_no = RX_PIN_NUMBER,
  573. .tx_pin_no = TX_PIN_NUMBER,
  574. .rts_pin_no = RTS_PIN_NUMBER,
  575. .cts_pin_no = CTS_PIN_NUMBER,
  576. .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
  577. .use_parity = false,
  578. #if defined (UART_PRESENT)
  579. .baud_rate = NRF_UART_BAUDRATE_115200
  580. #else
  581. .baud_rate = NRF_UARTE_BAUDRATE_115200
  582. #endif
  583. };
  584. APP_UART_FIFO_INIT(&comm_params,
  585. UART_RX_BUF_SIZE,
  586. UART_TX_BUF_SIZE,
  587. uart_event_handle,
  588. APP_IRQ_PRIORITY_LOWEST,
  589. err_code);
  590. APP_ERROR_CHECK(err_code);
  591. }
  592. /**@snippet [UART Initialization] */
  593. /**@brief Function for initializing the Advertising functionality.
  594. */
  595. static void advertising_init(void)
  596. {
  597. uint32_t err_code;
  598. ble_advertising_init_t init;
  599. memset(&init, 0, sizeof(init));
  600. init.advdata.name_type = BLE_ADVDATA_FULL_NAME;
  601. init.advdata.include_appearance = false;
  602. init.advdata.flags = BLE_GAP_ADV_FLAGS_LE_ONLY_LIMITED_DISC_MODE;
  603. init.srdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
  604. init.srdata.uuids_complete.p_uuids = m_adv_uuids;
  605. init.config.ble_adv_fast_enabled = true;
  606. init.config.ble_adv_fast_interval = APP_ADV_INTERVAL;
  607. init.config.ble_adv_fast_timeout = APP_ADV_DURATION;
  608. init.evt_handler = on_adv_evt;
  609. err_code = ble_advertising_init(&m_advertising, &init);
  610. APP_ERROR_CHECK(err_code);
  611. ble_advertising_conn_cfg_tag_set(&m_advertising, APP_BLE_CONN_CFG_TAG);
  612. }
  613. /**@brief Function for initializing the nrf log module.
  614. */
  615. static void log_init(void)
  616. {
  617. ret_code_t err_code = NRF_LOG_INIT(NULL);
  618. APP_ERROR_CHECK(err_code);
  619. NRF_LOG_DEFAULT_BACKENDS_INIT();
  620. }
  621. /**@brief Function for initializing power management.
  622. */
  623. static void power_management_init(void)
  624. {
  625. ret_code_t err_code;
  626. err_code = nrf_pwr_mgmt_init();
  627. APP_ERROR_CHECK(err_code);
  628. }
  629. /**@brief Function for handling the idle state (main loop).
  630. *
  631. * @details If there is no pending log operation, then sleep until next the next event occurs.
  632. */static void idle_state_handle(void)
  633. {
  634. if (NRF_LOG_PROCESS() == false)
  635. {
  636. nrf_pwr_mgmt_run();
  637. }
  638. }
  639. /***********************************************************************************************/
  640. void send_to_ble_nus(uint8_t index,uint8_t cmd,uint8_t* dat,uint8_t datLen)
  641. {
  642. // uint32_t err_code;
  643. uint8_t buf[255];
  644. uint16_t Len = datLen+8;
  645. uint16_t L=0;
  646. uint8_t i;
  647. uint8_t ver = 0;
  648. if(Len>255) return;
  649. buf[L++] = 0xAA; ver += 0xAA; //帧头
  650. buf[L++] = Len; ver += Len; //长度
  651. buf[L++] = ~Len; ver += (~Len);//长度反码
  652. buf[L++] = cmd; ver += cmd; //命令
  653. for(i=0;i<datLen;i++){ buf[L++] = dat[i]; ver += dat[i];} //数据
  654. buf[L++] = ver; //校验
  655. // for(i=0;i<L;i++) app_uart_put(buf[i]); //串口输出数据
  656. // buf[0] = '1';
  657. // L = 1;
  658. ble_nus_data_send(&m_nus, buf, &L, m_conn_handle);
  659. // do{
  660. // err_code = ble_nus_data_send(&m_nus, buf, &L, m_conn_handle);
  661. // if ((err_code != NRF_ERROR_INVALID_STATE) &&
  662. // (err_code != NRF_ERROR_RESOURCES) &&
  663. // (err_code != NRF_ERROR_NOT_FOUND))
  664. // {
  665. // APP_ERROR_CHECK(err_code);
  666. // }
  667. // } while (err_code == NRF_ERROR_RESOURCES);
  668. }
  669. void send_ble_data_f(float* acc_val,int32_t press_val,int32_t* signal_out)
  670. {
  671. uint8_t buf[255];
  672. uint8_t L=0;
  673. int32_t temp;
  674. temp = (int32_t)(acc_val[0]*1000);
  675. buf[L++] = (uint8_t)(temp>>24);
  676. buf[L++] = (uint8_t)(temp>>16);
  677. buf[L++] = (uint8_t)(temp>>8);
  678. buf[L++] = (uint8_t)(temp>>0);
  679. temp = (int32_t)(acc_val[1]*1000);
  680. buf[L++] = (uint8_t)(temp>>24);
  681. buf[L++] = (uint8_t)(temp>>16);
  682. buf[L++] = (uint8_t)(temp>>8);
  683. buf[L++] = (uint8_t)(temp>>0);
  684. temp = (int32_t)(acc_val[2]*1000);
  685. buf[L++] = (uint8_t)(temp>>24);
  686. buf[L++] = (uint8_t)(temp>>16);
  687. buf[L++] = (uint8_t)(temp>>8);
  688. buf[L++] = (uint8_t)(temp>>0);
  689. buf[L++] = (uint8_t)(press_val>>24);
  690. buf[L++] = (uint8_t)(press_val>>16);
  691. buf[L++] = (uint8_t)(press_val>>8);
  692. buf[L++] = (uint8_t)(press_val>>0);
  693. buf[L++] = (uint8_t)(signal_out[0]>>24);
  694. buf[L++] = (uint8_t)(signal_out[0]>>16);
  695. buf[L++] = (uint8_t)(signal_out[0]>>8);
  696. buf[L++] = (uint8_t)(signal_out[0]>>0);
  697. buf[L++] = (uint8_t)(signal_out[1]>>24);
  698. buf[L++] = (uint8_t)(signal_out[1]>>16);
  699. buf[L++] = (uint8_t)(signal_out[1]>>8);
  700. buf[L++] = (uint8_t)(signal_out[1]>>0);
  701. buf[L++] = (uint8_t)(signal_out[2]>>24);
  702. buf[L++] = (uint8_t)(signal_out[2]>>16);
  703. buf[L++] = (uint8_t)(signal_out[2]>>8);
  704. buf[L++] = (uint8_t)(signal_out[2]>>0);
  705. send_to_ble_nus(DEX_NUM,CMD_HEART,buf,L);
  706. }
  707. void send_ble_data_int(short* acc_val,short* gry_val,int32_t press_val,int32_t* signal_out,float* signal_float)
  708. {
  709. uint8_t buf[255];
  710. uint8_t L=0;
  711. int32_t temp;
  712. buf[L++] = (uint8_t)(acc_val[0]>>8);
  713. buf[L++] = (uint8_t)(acc_val[0]>>0);
  714. buf[L++] = (uint8_t)(acc_val[1]>>8);
  715. buf[L++] = (uint8_t)(acc_val[1]>>0);
  716. buf[L++] = (uint8_t)(acc_val[2]>>8);
  717. buf[L++] = (uint8_t)(acc_val[2]>>0);
  718. buf[L++] = (uint8_t)(gry_val[0]>>8);
  719. buf[L++] = (uint8_t)(gry_val[0]>>0);
  720. buf[L++] = (uint8_t)(gry_val[1]>>8);
  721. buf[L++] = (uint8_t)(gry_val[1]>>0);
  722. buf[L++] = (uint8_t)(gry_val[2]>>8);
  723. buf[L++] = (uint8_t)(gry_val[2]>>0);
  724. buf[L++] = (uint8_t)(press_val>>24);
  725. buf[L++] = (uint8_t)(press_val>>16);
  726. buf[L++] = (uint8_t)(press_val>>8);
  727. buf[L++] = (uint8_t)(press_val>>0);
  728. buf[L++] = (uint8_t)(signal_out[0]>>24);
  729. buf[L++] = (uint8_t)(signal_out[0]>>16);
  730. buf[L++] = (uint8_t)(signal_out[0]>>8);
  731. buf[L++] = (uint8_t)(signal_out[0]>>0);
  732. buf[L++] = (uint8_t)(signal_out[1]>>24);
  733. buf[L++] = (uint8_t)(signal_out[1]>>16);
  734. buf[L++] = (uint8_t)(signal_out[1]>>8);
  735. buf[L++] = (uint8_t)(signal_out[1]>>0);
  736. buf[L++] = (uint8_t)(signal_out[2]>>24);
  737. buf[L++] = (uint8_t)(signal_out[2]>>8);
  738. buf[L++] = (uint8_t)(signal_out[2]>>0);
  739. buf[L++] = (uint8_t)(signal_out[3]>>24);
  740. buf[L++] = (uint8_t)(signal_out[3]>>16);
  741. buf[L++] = (uint8_t)(signal_out[3]>>8);
  742. buf[L++] = (uint8_t)(signal_out[3]>>0);
  743. temp = (int32_t)signal_float[0];
  744. buf[L++] = (uint8_t)(temp>>24);
  745. buf[L++] = (uint8_t)(temp>>16);
  746. buf[L++] = (uint8_t)(temp>>8);
  747. buf[L++] = (uint8_t)(temp>>0);
  748. temp = (int32_t)signal_float[1];
  749. buf[L++] = (uint8_t)(temp>>24);
  750. buf[L++] = (uint8_t)(temp>>16);
  751. buf[L++] = (uint8_t)(temp>>8);
  752. buf[L++] = (uint8_t)(temp>>0);
  753. send_to_ble_nus(DEX_NUM,CMD_HEART,buf,L);
  754. }
  755. void send_ble_data_press(int32_t press_val,short ts)
  756. {
  757. uint8_t buf[32];
  758. uint8_t L=0;
  759. buf[L++] = (uint8_t)(press_val>>24);
  760. buf[L++] = (uint8_t)(press_val>>16);
  761. buf[L++] = (uint8_t)(press_val>>8);
  762. buf[L++] = (uint8_t)(press_val>>0);
  763. buf[L++] = (uint8_t)(ts>>8);
  764. buf[L++] = (uint8_t)(ts>>0);
  765. send_to_ble_nus(DEX_NUM,CMD_HEART,buf,L);
  766. }
  767. static uint16_t cmd_ntimes[NUMBERS_OF_MOTION];
  768. static uint16_t cmd_timestamp[NUMBERS_OF_MOTION];
  769. void send_ble_motion_process(void)
  770. {
  771. uint8_t buf[255];
  772. uint8_t L=0;
  773. int i;
  774. for(i=0;i<NUMBERS_OF_MOTION;i++){
  775. if(cmd_ntimes[i]>0){
  776. cmd_ntimes[i]--;
  777. buf[L++] = (uint8_t)(i>>0);
  778. buf[L++] = (uint8_t)(cmd_timestamp[i]>>8);
  779. buf[L++] = (uint8_t)(cmd_timestamp[i]>>0);
  780. send_to_ble_nus(DEX_NUM,CMD_MOTION,buf,L);
  781. }
  782. }
  783. }
  784. void send_ble_motion(uint8_t motion,uint16_t ts)
  785. {
  786. if(motion>=NUMBERS_OF_MOTION) return;
  787. cmd_ntimes[motion] = 10;
  788. cmd_timestamp[motion] = ts;
  789. }
  790. /**
  791. * @brief 卡尔曼滤波函数
  792. * @param None
  793. * @retval None
  794. */
  795. float kalmanFilter_x(float new_zk)
  796. {
  797. static float preBestResult=0;
  798. static float p=10.0,q=0.000001,r=0.0000101,kg=0;
  799. p=p+q;
  800. kg=p/(p+r);
  801. new_zk=preBestResult+(kg*(new_zk-preBestResult));
  802. p=(1-kg)*p;
  803. preBestResult=new_zk;
  804. return new_zk;
  805. }
  806. /**
  807. * @brief 卡尔曼滤波函数
  808. * @param None
  809. * @retval None
  810. */
  811. float kalmanFilter_y(float new_zk)
  812. {
  813. static float preBestResult=0;
  814. static float p=10.0,q=0.000001,r=0.0000101,kg=0;
  815. p=p+q;
  816. kg=p/(p+r);
  817. new_zk=preBestResult+(kg*(new_zk-preBestResult));
  818. p=(1-kg)*p;
  819. preBestResult=new_zk;
  820. return new_zk;
  821. }
  822. /**
  823. * @brief 卡尔曼滤波函数
  824. * @param None
  825. * @retval None
  826. */
  827. float kalmanFilter_z(float new_zk)
  828. {
  829. static float preBestResult=0;
  830. static float p=10.0,q=0.000001,r=0.0000101,kg=0;
  831. p=p+q;
  832. kg=p/(p+r);
  833. new_zk=preBestResult+(kg*(new_zk-preBestResult));
  834. p=(1-kg)*p;
  835. preBestResult=new_zk;
  836. return new_zk;
  837. }
  838. float kalmanFilter_f(float new_zk)
  839. {
  840. static float preBestResult=0;
  841. static float p=10.0,q=0.000001,r=0.0000101,kg=0;
  842. p=p+q;
  843. kg=p/(p+r);
  844. new_zk=preBestResult+(kg*(new_zk-preBestResult));
  845. p=(1-kg)*p;
  846. preBestResult=new_zk;
  847. return new_zk;
  848. }
  849. /*************************************************************************/
  850. #ifdef BSP_BUTTON_0
  851. #define PIN_IN BSP_BUTTON_0
  852. #endif
  853. #ifndef PIN_IN
  854. #error "Please indicate input pin"
  855. #endif
  856. nrf_saadc_value_t saadc_val[2];
  857. short gyro[3], accel[3];
  858. float quat[4];
  859. uint16_t timestamp_ble = 0;
  860. int32_t out[7];
  861. short adc_send[4];
  862. //#define filter_mid_averange_number 10
  863. void bubble_sort(short* a, short n)
  864. {
  865. short i,j,temp;
  866. for(i=0;i<n-1;i++){
  867. for(j=n-1;j>i;j--){
  868. if(a[j]<a[j-1]){
  869. temp=a[j];
  870. a[j]=a[j-1];
  871. a[j-1]=temp;
  872. }
  873. }
  874. }
  875. }
  876. #define filter_mid_averange_number 5
  877. short filter_mid_averange(short* p)
  878. {
  879. int i;
  880. short buf[filter_mid_averange_number];
  881. for(i=0;i<filter_mid_averange_number;i++){
  882. buf[i] = p[i];
  883. }
  884. bubble_sort(buf,filter_mid_averange_number);
  885. return buf[filter_mid_averange_number>>1];
  886. }
  887. short filter_mid(short val)
  888. {
  889. static short buf[filter_mid_averange_number];
  890. static int dex = 0;
  891. buf[dex] = val;
  892. if(++dex>=filter_mid_averange_number) dex = 0;
  893. return filter_mid_averange(buf);
  894. }
  895. short filter_mid_slide(short val)
  896. {
  897. static short buf[filter_mid_averange_number] = {0};
  898. static int dex = 0;
  899. static int32_t sum = 0;
  900. sum = sum - buf[dex];
  901. buf[dex] = val;
  902. if(++dex>=filter_mid_averange_number) dex = 0;
  903. sum += val;
  904. return sum/filter_mid_averange_number;
  905. }
  906. short filter_adc1(short val)
  907. {
  908. static short buf[filter_mid_averange_number];
  909. static int dex = 0;
  910. buf[dex] = val;
  911. if(++dex>=filter_mid_averange_number) dex = 0;
  912. return filter_mid_slide(filter_mid_averange(buf));
  913. }
  914. short filter_adc1_slide(short val)
  915. {
  916. #define filter_adc1_slide_num 5
  917. static short buf[filter_adc1_slide_num] = {0};
  918. static int dex = 0;
  919. static int32_t sum = 0;
  920. sum = sum - buf[dex];
  921. buf[dex] = val;
  922. if(++dex>=filter_adc1_slide_num) dex = 0;
  923. sum += val;
  924. return sum/filter_adc1_slide_num;
  925. }
  926. short filter_adc1_squat_slide(short val)
  927. {
  928. #define filter_adc1_d_slide_num 10
  929. static short buf[filter_adc1_d_slide_num] = {0};
  930. static int dex = 0;
  931. static int32_t sum = 0;
  932. sum = sum - buf[dex];
  933. buf[dex] = val;
  934. if(++dex>=filter_adc1_d_slide_num) dex = 0;
  935. sum += val;
  936. return sum/filter_adc1_d_slide_num;
  937. }
  938. short filter_accy_slide(short val)
  939. {
  940. #define filter_accy_slide_number 5
  941. static short buf[filter_accy_slide_number] = {0};
  942. static int dex = 0;
  943. static int32_t sum = 0;
  944. sum = sum - buf[dex];
  945. buf[dex] = val;
  946. if(++dex>=filter_accy_slide_number) dex = 0;
  947. sum += val;
  948. return sum/filter_accy_slide_number;
  949. }
  950. short filter_accz_slide(short val)
  951. {
  952. #define filter_accz_slide_number 5
  953. static short buf[filter_accz_slide_number] = {0};
  954. static int dex = 0;
  955. static int32_t sum = 0;
  956. sum = sum - buf[dex];
  957. buf[dex] = val;
  958. if(++dex>=filter_accz_slide_number) dex = 0;
  959. sum += val;
  960. return sum/filter_accz_slide_number;
  961. }
  962. float quatdianc(const float* Q,const float* P)
  963. {
  964. float result;
  965. result=P[0]*Q[0] + P[1]*Q[1] + P[2]*Q[2] + P[3]*Q[3];
  966. return result;
  967. }
  968. void quatconj2(const float *Quat,float *out)
  969. {
  970. out[0]= Quat[0];
  971. out[1]=-Quat[1];
  972. out[2]=-Quat[2];
  973. out[3]=-Quat[3];
  974. }
  975. //????
  976. void quatinv(const float* Q,float *quatinvQ)
  977. {
  978. float mod;
  979. float temp[4];
  980. quatconj2(Q,temp);
  981. mod=quatdianc(temp,temp);
  982. quatinvQ[0]=temp[0]/mod;
  983. quatinvQ[1]=temp[1]/mod;
  984. quatinvQ[2]=temp[2]/mod;
  985. quatinvQ[3]=temp[3]/mod;
  986. }
  987. void quatmultiply(const float * Q,const float * P,float *QP)
  988. {
  989. QP[0]=P[0]*Q[0] - P[1]*Q[1] - P[2]*Q[2] - P[3]*Q[3];
  990. QP[1]=P[0]*Q[1] + P[1]*Q[0] + P[2]*Q[3] - P[3]*Q[2];
  991. QP[2]=P[0]*Q[2] + P[2]*Q[0] + P[3]*Q[1] - P[1]*Q[3];
  992. QP[3]=P[0]*Q[3] + P[3]*Q[0] + P[1]*Q[2] - P[2]*Q[1];
  993. }
  994. void quatrotate(float* sour_pion,const float* Q,float *out_poin)
  995. {
  996. float Quaternion_p[4];
  997. float temp[4];
  998. float temp1[4];
  999. float temp2[4];
  1000. Quaternion_p[0]=0;
  1001. Quaternion_p[1]=sour_pion[0];
  1002. Quaternion_p[2]=sour_pion[1];
  1003. Quaternion_p[3]=sour_pion[2];
  1004. quatmultiply(Q,Quaternion_p,temp);
  1005. quatinv(Q,temp2);
  1006. quatmultiply(temp,temp2,temp1);
  1007. out_poin[0]=temp1[1];
  1008. out_poin[1]=temp1[2];
  1009. out_poin[2]=temp1[3];
  1010. }
  1011. void Separate_G(float* soure_acc,const float* Q,float *NogAcc)//???????
  1012. {
  1013. float temp[4];
  1014. float temp1[3];
  1015. quatconj2(Q,temp);
  1016. quatrotate(soure_acc,temp,temp1);//?????????????
  1017. // temp1[2]-=1;//???????
  1018. NogAcc[0] = temp1[0];
  1019. NogAcc[1] = temp1[1];
  1020. NogAcc[2] = temp1[2];
  1021. // quatrotate(temp1,Q,NogAcc);//?????????????
  1022. }
  1023. short acc_0[3];
  1024. short gyr_0[3];
  1025. long quat_0[4];
  1026. int32_t press_0;
  1027. #define press_zero_offer 50000
  1028. static int32_t press_zero_0 = 0;
  1029. static int32_t press_sub = 0;
  1030. static int32_t press_sub_dt = 0;
  1031. static uint32_t ble_timestamp = 0;
  1032. static int32_t is_runnig = 0;
  1033. float out_f[8];
  1034. static int32_t press_window_dt_val = 0;
  1035. void press_filter_Increasing(int32_t val)
  1036. {
  1037. static int32_t press_last = 0;
  1038. if(press_last<val)
  1039. out[1] = 1;
  1040. else
  1041. out[1] = 0;
  1042. press_last = val;
  1043. }
  1044. int32_t press_filter_slide(int32_t val)
  1045. {
  1046. #define press_filter_slide_num 10
  1047. static int32_t buf[press_filter_slide_num] = {0};
  1048. static int dex = 0;
  1049. static long sum = 0;
  1050. sum = sum - buf[dex];
  1051. buf[dex] = val;
  1052. if(++dex>=press_filter_slide_num) dex = 0;
  1053. sum += val;
  1054. return sum/press_filter_slide_num;
  1055. }
  1056. int32_t press_filter_dt(int32_t val)
  1057. {
  1058. static int32_t press_last = 0;
  1059. int32_t sub = val - press_last;
  1060. press_last = val;
  1061. return sub;
  1062. }
  1063. int32_t press_dt(int32_t val)
  1064. {
  1065. static int32_t press_last = 0;
  1066. int32_t sub = val - press_last;
  1067. press_last = val;
  1068. return sub;
  1069. }
  1070. int32_t press_window_dt(int32_t val)
  1071. {
  1072. #define press_window_len 15
  1073. int i;
  1074. int32_t temp_max = 0;
  1075. int32_t temp_min = 0;
  1076. int temp_max_i = 0;
  1077. int temp_min_i = 0;
  1078. static int32_t press_window[press_window_len];
  1079. static int dex = 0;
  1080. press_window[dex] = val;
  1081. temp_max = press_window[0];temp_max_i = press_window_len-1-dex;
  1082. temp_min = press_window[0];temp_min_i = press_window_len-1-dex;
  1083. for(i=1;i<press_window_len;i++){
  1084. if(temp_max<press_window[i]){
  1085. temp_max = press_window[i];
  1086. if(i>dex){
  1087. temp_max_i = i-1-dex;
  1088. }else{
  1089. temp_max_i = press_window_len-1-(dex-i);
  1090. }
  1091. }
  1092. if(temp_min>press_window[i]){
  1093. temp_min = press_window[i];
  1094. if(i>dex){
  1095. temp_min_i = i-1-dex;
  1096. }else{
  1097. temp_min_i = press_window_len-1-(dex-i);
  1098. }
  1099. }
  1100. }
  1101. if(++dex>=press_window_len) dex = 0;
  1102. if(temp_max_i>temp_min_i)
  1103. return temp_max-temp_min;
  1104. else
  1105. return temp_min-temp_max;
  1106. }
  1107. int32_t accz_dt(short val)
  1108. {
  1109. static int32_t accz_last = 0;
  1110. int32_t sub = abs(val - accz_last);
  1111. accz_last = val;
  1112. return sub;
  1113. }
  1114. int check_accy_stop(void)
  1115. {
  1116. #define accy_stop_num 20
  1117. static short buf[accy_stop_num];
  1118. static short dex = 0;
  1119. int i;
  1120. buf[dex] = acc_0[2];
  1121. if(++dex>=accy_stop_num) dex = 0;
  1122. for(i=0;i<accy_stop_num;i++){
  1123. if(buf[i]>500 || buf[i]<-500) return 1;
  1124. }
  1125. return 0;
  1126. }
  1127. int check_accz_stop(void)
  1128. {
  1129. #define accz_stop_num 20
  1130. static short buf[accz_stop_num];
  1131. static short dex = 0;
  1132. int i;
  1133. buf[dex] = acc_0[2];
  1134. if(++dex>=accz_stop_num) dex = 0;
  1135. for(i=0;i<accz_stop_num;i++){
  1136. if(buf[i]>500 || buf[i]<-500) return 1;
  1137. }
  1138. return 0;
  1139. }
  1140. void check_press_zero(int32_t val)
  1141. {
  1142. static int32_t press_zero_arr[300];
  1143. static int dex = 0;
  1144. static int32_t press_zero_max = 0;
  1145. static int32_t press_zero_min = 0;
  1146. press_zero_arr[dex] = val;
  1147. if(dex==0){
  1148. press_zero_max = press_zero_arr[dex];
  1149. press_zero_min = press_zero_arr[dex];
  1150. }else{
  1151. if(press_zero_max<press_zero_arr[dex]) press_zero_max = press_zero_arr[dex];
  1152. if(press_zero_min>press_zero_arr[dex]) press_zero_min = press_zero_arr[dex];
  1153. }
  1154. if(++dex>=300){dex = 0;
  1155. // if(press_zero_max - press_zero_min<5000){
  1156. // if(press_zero_0==0){
  1157. // press_zero_0 = press_zero_max;
  1158. // out[0] = press_zero_0;
  1159. // }else if(press_zero_max<press_zero_0){
  1160. // press_zero_0 = press_zero_max;
  1161. // out[0] = press_zero_0;
  1162. // }
  1163. // }
  1164. if(press_zero_max - press_zero_min<3000){
  1165. press_zero_0 = press_zero_max;
  1166. out[0] = press_zero_0;
  1167. send_ble_motion(MOTION_STOP,ble_timestamp);
  1168. is_runnig = 0;
  1169. }
  1170. }
  1171. }
  1172. void check_motion(void)
  1173. {
  1174. static int32_t vy_n = 0;
  1175. static int32_t sy_n = 0;
  1176. static int32_t cnt = 0;
  1177. static int32_t gy_n = 0;
  1178. static uint32_t cnt_down = 0;
  1179. static short acc_yy[3];
  1180. static short acc_yh[10];
  1181. acc_yy[0] = acc_yy[1];
  1182. acc_yy[1] = acc_yy[2];
  1183. acc_yy[2] = acc_0[2];
  1184. acc_0[2] = acc_yy[0];
  1185. if(cnt_down<100) cnt_down++;
  1186. if(press_sub_dt<=0){
  1187. vy_n += acc_0[1];
  1188. sy_n += vy_n;
  1189. gy_n = 0;
  1190. }else{
  1191. vy_n = 0;
  1192. sy_n = 0;
  1193. gy_n += gyr_0[1];
  1194. if(gy_n<-8000){
  1195. if(cnt_down==100){
  1196. send_ble_motion(MOTION_DOWN,ble_timestamp);
  1197. }
  1198. cnt_down = 0;
  1199. }
  1200. }
  1201. if(press_sub==0){ //离地
  1202. if(cnt<150){//1.5秒之内 判断
  1203. if(cnt<5){
  1204. acc_yh[cnt] = acc_0[2];
  1205. if(acc_yh[cnt] - acc_yh[0]>2500){
  1206. send_ble_motion(MOTION_JUMP,ble_timestamp);
  1207. }
  1208. }
  1209. if(sy_n>150000){
  1210. send_ble_motion(MOTION_RIGHT,ble_timestamp);
  1211. cnt = 200;
  1212. }else if(sy_n<-150000){
  1213. send_ble_motion(MOTION_LEFT,ble_timestamp);
  1214. cnt = 200;
  1215. }else{
  1216. cnt++;
  1217. }
  1218. }else{
  1219. vy_n = 0;
  1220. sy_n = 0;
  1221. }
  1222. }else{ //在地上
  1223. if(is_runnig==0){
  1224. is_runnig = 1;
  1225. send_ble_motion(MOTION_RUN,ble_timestamp);
  1226. }
  1227. cnt = 0;
  1228. }
  1229. }
  1230. int32_t mean_value(int32_t* p,int len)
  1231. {
  1232. int32_t sum = 0;
  1233. int i;
  1234. for(i=0;i<len;i++){
  1235. sum += p[i];
  1236. }
  1237. return sum/len;
  1238. }
  1239. int32_t variance_value(int32_t* p,int len)
  1240. {
  1241. int32_t sum = 0;
  1242. int i;
  1243. int32_t mean = mean_value(p,len);
  1244. for(i=0;i<len;i++){
  1245. sum += (p[i]-mean)*(p[i]-mean);
  1246. }
  1247. return sum/len;
  1248. }
  1249. void linear_regression(int32_t* y,int len,float* k,float* b)
  1250. {
  1251. int i;
  1252. int n = len;
  1253. float kk,bb, sum_x, sum_y, lxy, xiSubSqr;
  1254. kk = bb = sum_x = sum_y = lxy = xiSubSqr = 0.0;
  1255. for(i=0;i<n;i++){
  1256. sum_x += i;
  1257. sum_y += y[i];
  1258. }
  1259. float x_ave = sum_x/n;
  1260. float y_ave = sum_y/n;
  1261. for(i=0;i<n;i++){
  1262. lxy += (i - x_ave) * (y[i] - y_ave);
  1263. xiSubSqr += (i - x_ave) * (i - x_ave);
  1264. }
  1265. kk = lxy / xiSubSqr;
  1266. bb = y_ave - kk * x_ave;
  1267. *k = kk;
  1268. *b = bb;
  1269. }
  1270. void check_down(int32_t val)
  1271. {
  1272. static int32_t window_press_arr[500];
  1273. static int32_t window_val_arr[500];
  1274. static int dex = 0;
  1275. out[2] = 0;
  1276. out[3] = 0;
  1277. out_f[0] = 0;
  1278. out_f[1] = 0;
  1279. if(val>0){
  1280. window_val_arr[dex] = val/10000;
  1281. window_press_arr[dex] = press_sub/10000;
  1282. if(++dex>=500) dex = 0;
  1283. out[2] = mean_value(window_val_arr,dex);
  1284. out[3] = variance_value(window_val_arr,dex);
  1285. linear_regression(window_press_arr,dex,&out_f[0],&out_f[1]);
  1286. }else{
  1287. dex = 0;
  1288. }
  1289. }
  1290. int32_t press_window_dt_dt(int32_t val)
  1291. {
  1292. static int32_t press_last = 0;
  1293. int32_t sub = val - press_last;
  1294. press_last = val;
  1295. return sub;
  1296. }
  1297. void process_motion(void)
  1298. {
  1299. check_press_zero(press_0);
  1300. if(press_zero_0==0) return;
  1301. press_sub = press_0-press_zero_0;
  1302. if(press_sub<press_zero_offer) press_sub = 0;
  1303. press_sub_dt = press_dt(press_sub);
  1304. out[0] = press_sub_dt;
  1305. press_window_dt_val = press_window_dt(press_sub);
  1306. out[1] = press_window_dt_val;
  1307. check_motion();
  1308. }
  1309. void in_pin_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action)
  1310. {
  1311. #ifdef USE_DMP
  1312. // nrf_drv_gpiote_out_toggle(PIN_OUT);
  1313. // nrf_drv_gpiote_out_set(PIN_OUT);
  1314. ReadPressure_Pre();
  1315. if(mpu6050_get_linear_data_int(gyr_0,acc_0,quat_0)==0){
  1316. press_0 = ReadPressure();
  1317. // printf("press=%d\n",press_0);
  1318. process_motion();
  1319. // send_ble_data_int(acc_0,gyr_0,press_sub,out,out_f);
  1320. send_ble_data_int(acc_0,gyr_0,ble_timestamp,out,out_f);
  1321. // send_ble_motion_process();
  1322. }
  1323. ble_timestamp++;
  1324. // nrf_drv_gpiote_out_clear(PIN_OUT);
  1325. #endif
  1326. }
  1327. #ifndef USE_DMP
  1328. APP_TIMER_DEF(s_testTimer);
  1329. #define TEST_PERIOD APP_TIMER_TICKS(10)
  1330. static void timer_testCallback(void *arg)
  1331. {
  1332. UNUSED_PARAMETER(arg);
  1333. timer_callback_Chen();
  1334. ble_timestamp++;
  1335. }
  1336. #endif
  1337. /**
  1338. * @brief Function for configuring: PIN_IN pin for input, PIN_OUT pin for output,
  1339. * and configures GPIOTE to give an interrupt on pin change.
  1340. */
  1341. static void gpio_init(void)
  1342. {
  1343. ret_code_t err_code;
  1344. err_code = nrf_drv_gpiote_init();
  1345. APP_ERROR_CHECK(err_code);
  1346. nrf_drv_gpiote_out_config_t out_config = GPIOTE_CONFIG_OUT_SIMPLE(false);
  1347. err_code = nrf_drv_gpiote_out_init(PIN_OUT, &out_config);
  1348. APP_ERROR_CHECK(err_code);
  1349. nrf_drv_gpiote_in_config_t in_config = GPIOTE_CONFIG_IN_SENSE_HITOLO(true);
  1350. in_config.pull = NRF_GPIO_PIN_PULLUP;
  1351. err_code = nrf_drv_gpiote_in_init(PIN_IN, &in_config, in_pin_handler);
  1352. APP_ERROR_CHECK(err_code);
  1353. nrf_drv_gpiote_in_event_enable(PIN_IN, true);
  1354. nrf_drv_gpiote_out_set(PIN_OUT);
  1355. }
  1356. //saadc回调函数
  1357. void saadc_callback(nrf_drv_saadc_evt_t const *p_event){}
  1358. //saadc初始化函数
  1359. void saadc_init(void)
  1360. {
  1361. ret_code_t err_code;
  1362. //定义SAADC初始化结构体
  1363. //使用默认的宏初始化时需要指定该通道的模拟输入引脚
  1364. //具体的引脚分布参考数据手册
  1365. nrf_saadc_channel_config_t saadc_0 = NRF_DRV_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN2);
  1366. nrf_saadc_channel_config_t saadc_1 = NRF_DRV_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN3);
  1367. //初始化SAADC,注册事件回调函数,注意因为使用了阻塞模式
  1368. //所以可以不用回调函数,但是nrf_drv_saadc_init()要求必须提供回调函数
  1369. //所以这里要注册回调函数,无论有没有用到
  1370. err_code=nrf_drv_saadc_init(NULL,saadc_callback);
  1371. APP_ERROR_CHECK(err_code);
  1372. //初始化SAADC通道0
  1373. err_code = nrf_drv_saadc_channel_init(0, &saadc_0);
  1374. err_code = nrf_drv_saadc_channel_init(1, &saadc_1);
  1375. APP_ERROR_CHECK(err_code);
  1376. }
  1377. int main(void)
  1378. {
  1379. uart_init();
  1380. log_init();
  1381. app_timer_create(&s_testTimer, APP_TIMER_MODE_REPEATED, timer_testCallback);
  1382. config_file_init();
  1383. timers_init();
  1384. gpio_init();
  1385. power_management_init();
  1386. ble_stack_init();
  1387. gap_params_init();
  1388. gatt_init();
  1389. services_init();
  1390. advertising_init();
  1391. conn_params_init();
  1392. advertising_start();
  1393. app_timer_start(s_testTimer, TEST_PERIOD, NULL);
  1394. //rtc_config();
  1395. printf("starting... \r\n");
  1396. for (;;)
  1397. {
  1398. idle_state_handle();
  1399. }
  1400. }
  1401. /**
  1402. * @}
  1403. */