scope_scene_run.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. #include <complex.h>
  2. #include <math.h>
  3. #include <float.h>
  4. #include <furi.h>
  5. #include <furi_hal.h>
  6. #include <furi_hal_resources.h>
  7. #include <gui/gui.h>
  8. #include <gui/view_dispatcher.h>
  9. #include <gui/scene_manager.h>
  10. #include <gui/modules/submenu.h>
  11. #include <gui/modules/variable_item_list.h>
  12. #include <gui/modules/widget.h>
  13. #include <gui/elements.h>
  14. #include <notification/notification_messages.h>
  15. #include "stm32wbxx_ll_adc.h"
  16. #include "stm32wbxx_ll_dma.h"
  17. #include "stm32wbxx_ll_crs.h"
  18. #include "stm32wbxx_ll_rcc.h"
  19. #include "stm32wbxx_ll_bus.h"
  20. #include "stm32wbxx_ll_system.h"
  21. #include "stm32wbxx_ll_exti.h"
  22. #include "stm32wbxx_ll_cortex.h"
  23. #include "stm32wbxx_ll_utils.h"
  24. #include "stm32wbxx_ll_pwr.h"
  25. #include "stm32wbxx_ll_tim.h"
  26. #include "stm32wbxx_ll_gpio.h"
  27. #include "../scope_app_i.h"
  28. #include "flipperscope_icons.h"
  29. #define USE_TIMEOUT 0
  30. #define DIGITAL_SCALE_12BITS ((uint32_t)0xFFF)
  31. #define VAR_CONVERTED_DATA_INIT_VALUE (DIGITAL_SCALE_12BITS + 1)
  32. #define VAR_CONVERTED_DATA_INIT_VALUE_16BITS (0xFFFF + 1U)
  33. #define __ADC_CALC_DATA_VOLTAGE(__VREFANALOG_VOLTAGE__, __ADC_DATA__) \
  34. ((__ADC_DATA__) * (__VREFANALOG_VOLTAGE__) / DIGITAL_SCALE_12BITS)
  35. #define VDDA_APPLI ((uint32_t)2500)
  36. #define TIMER_FREQUENCY_RANGE_MIN (1UL)
  37. #define TIMER_PRESCALER_MAX_VALUE (0xFFFF - 1UL)
  38. #define ADC_DELAY_CALIB_ENABLE_CPU_CYCLES (LL_ADC_DELAY_CALIB_ENABLE_ADC_CYCLES * 32)
  39. // ramVector found from - https://community.nxp.com/t5/i-MX-Processors/Relocate-vector-table-to-ITCM/m-p/1302304
  40. // the aligned aspect is key!
  41. #define TABLE_SIZE 79
  42. uint32_t ramVector[TABLE_SIZE + 1] __attribute__((aligned(512)));
  43. const uint32_t AHBPrescTable[16UL] =
  44. {1UL, 3UL, 5UL, 1UL, 1UL, 6UL, 10UL, 32UL, 2UL, 4UL, 8UL, 16UL, 64UL, 128UL, 256UL, 512UL};
  45. const uint32_t APBPrescTable[8UL] = {0UL, 0UL, 0UL, 0UL, 1UL, 2UL, 3UL, 4UL};
  46. const uint32_t MSIRangeTable[16UL] = {
  47. 100000UL,
  48. 200000UL,
  49. 400000UL,
  50. 800000UL,
  51. 1000000UL,
  52. 2000000UL,
  53. 4000000UL,
  54. 8000000UL,
  55. 16000000UL,
  56. 24000000UL,
  57. 32000000UL,
  58. 48000000UL,
  59. 0UL,
  60. 0UL,
  61. 0UL,
  62. 0UL}; /* 0UL values are incorrect cases */
  63. char* time; // Current time period text
  64. float scale; // Current scale
  65. double freq; // Current samplerate
  66. uint8_t pause = 0; // Whether we want to pause output or not
  67. enum measureenum type; // Type of measurement we are performing
  68. int toggle = 0; // Used for toggling output GPIO, only used in testing
  69. uint32_t adc_buffer; // ADC buffer size
  70. int16_t* index_crossings; // Indexes of zero crossings
  71. float* data; // Shift data across virtual zero line
  72. float* crossings;
  73. float complex* fft_data; // Real data, transformed to complex data via FFT
  74. float* fft_power; // Power data from FFT
  75. void Error_Handler() {
  76. while(1) {
  77. }
  78. }
  79. uint16_t* aADCxConvertedData; // Array that ADC data is copied to, via DMA
  80. __IO uint16_t* aADCxConvertedData_Voltage_mVoltA; // Data is converted to range from 0 to 2500
  81. __IO uint16_t* aADCxConvertedData_Voltage_mVoltB; // Data is converted to range from 0 to 2500
  82. __IO uint8_t ubDmaTransferStatus = 2; // DMA transfer status
  83. __IO uint16_t* mvoltWrite; // Pointer to area we write converted voltage data to
  84. __IO uint16_t* mvoltDisplay; // Pointer to area of memory we display
  85. void AdcDmaTransferComplete_Callback();
  86. void AdcDmaTransferHalf_Callback();
  87. void AdcGrpRegularOverrunError_Callback(void) {
  88. LL_ADC_DisableIT_OVR(ADC1);
  89. }
  90. void AdcDmaTransferError_Callback() {
  91. }
  92. void DMA1_Channel1_IRQHandler(void) {
  93. if(LL_DMA_IsActiveFlag_TC1(DMA1) == 1) {
  94. LL_DMA_ClearFlag_TC1(DMA1);
  95. AdcDmaTransferComplete_Callback();
  96. }
  97. if(LL_DMA_IsActiveFlag_HT1(DMA1) == 1) {
  98. LL_DMA_ClearFlag_HT1(DMA1);
  99. AdcDmaTransferHalf_Callback();
  100. }
  101. if(LL_DMA_IsActiveFlag_TE1(DMA1) == 1) {
  102. LL_DMA_ClearFlag_TE1(DMA1);
  103. AdcDmaTransferError_Callback();
  104. }
  105. }
  106. void ADC1_IRQHandler(void) {
  107. if(LL_ADC_IsActiveFlag_OVR(ADC1) != 0) {
  108. LL_ADC_ClearFlag_OVR(ADC1);
  109. AdcGrpRegularOverrunError_Callback();
  110. }
  111. }
  112. void TIM2_IRQHandler(void) {
  113. }
  114. static void MX_ADC1_Init(void) {
  115. LL_ADC_CommonInitTypeDef ADC_CommonInitStruct = {0};
  116. LL_ADC_InitTypeDef ADC_InitStruct = {0};
  117. LL_ADC_REG_InitTypeDef ADC_REG_InitStruct = {0};
  118. LL_GPIO_InitTypeDef GPIO_InitStruct = {0};
  119. LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_ADC);
  120. LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOC);
  121. GPIO_InitStruct.Pin = LL_GPIO_PIN_0;
  122. GPIO_InitStruct.Mode = LL_GPIO_MODE_ANALOG;
  123. GPIO_InitStruct.Pull = LL_GPIO_PULL_NO;
  124. LL_GPIO_Init(GPIOC, &GPIO_InitStruct);
  125. LL_DMA_SetPeriphRequest(DMA1, LL_DMA_CHANNEL_1, LL_DMAMUX_REQ_ADC1);
  126. LL_DMA_SetDataTransferDirection(DMA1, LL_DMA_CHANNEL_1, LL_DMA_DIRECTION_PERIPH_TO_MEMORY);
  127. LL_DMA_SetChannelPriorityLevel(DMA1, LL_DMA_CHANNEL_1, LL_DMA_PRIORITY_HIGH);
  128. LL_DMA_SetMode(DMA1, LL_DMA_CHANNEL_1, LL_DMA_MODE_CIRCULAR);
  129. LL_DMA_SetPeriphIncMode(DMA1, LL_DMA_CHANNEL_1, LL_DMA_PERIPH_NOINCREMENT);
  130. LL_DMA_SetMemoryIncMode(DMA1, LL_DMA_CHANNEL_1, LL_DMA_MEMORY_INCREMENT);
  131. LL_DMA_SetPeriphSize(DMA1, LL_DMA_CHANNEL_1, LL_DMA_PDATAALIGN_HALFWORD);
  132. LL_DMA_SetMemorySize(DMA1, LL_DMA_CHANNEL_1, LL_DMA_MDATAALIGN_HALFWORD);
  133. LL_DMAMUX_SetRequestID(DMAMUX1, LL_DMAMUX_CHANNEL_0, LL_DMAMUX_REQ_ADC1);
  134. LL_DMA_ConfigAddresses(
  135. DMA1,
  136. LL_DMA_CHANNEL_1,
  137. LL_ADC_DMA_GetRegAddr(ADC1, LL_ADC_DMA_REG_REGULAR_DATA),
  138. (uint32_t)aADCxConvertedData,
  139. LL_DMA_DIRECTION_PERIPH_TO_MEMORY);
  140. LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, adc_buffer);
  141. LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_1);
  142. LL_DMA_EnableIT_HT(DMA1, LL_DMA_CHANNEL_1);
  143. LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_1);
  144. LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1);
  145. NVIC_SetPriority(ADC1_IRQn, 0);
  146. NVIC_EnableIRQ(ADC1_IRQn);
  147. ADC_CommonInitStruct.CommonClock = LL_ADC_CLOCK_SYNC_PCLK_DIV2;
  148. LL_ADC_CommonInit(__LL_ADC_COMMON_INSTANCE(ADC1), &ADC_CommonInitStruct);
  149. ADC_InitStruct.Resolution = LL_ADC_RESOLUTION_12B;
  150. ADC_InitStruct.DataAlignment = LL_ADC_DATA_ALIGN_RIGHT;
  151. ADC_InitStruct.LowPowerMode = LL_ADC_LP_MODE_NONE;
  152. LL_ADC_Init(ADC1, &ADC_InitStruct);
  153. ADC_REG_InitStruct.TriggerSource = LL_ADC_REG_TRIG_EXT_TIM2_TRGO;
  154. ADC_REG_InitStruct.SequencerLength = LL_ADC_REG_SEQ_SCAN_DISABLE;
  155. ADC_REG_InitStruct.SequencerDiscont = LL_ADC_REG_SEQ_DISCONT_DISABLE;
  156. ADC_REG_InitStruct.ContinuousMode = LL_ADC_REG_CONV_SINGLE;
  157. ADC_REG_InitStruct.DMATransfer = LL_ADC_REG_DMA_TRANSFER_UNLIMITED;
  158. ADC_REG_InitStruct.Overrun = LL_ADC_REG_OVR_DATA_OVERWRITTEN;
  159. LL_ADC_REG_Init(ADC1, &ADC_REG_InitStruct);
  160. LL_ADC_SetOverSamplingScope(ADC1, LL_ADC_OVS_DISABLE);
  161. LL_ADC_REG_SetTriggerEdge(ADC1, LL_ADC_REG_TRIG_EXT_FALLING);
  162. LL_ADC_DisableDeepPowerDown(ADC1);
  163. LL_ADC_EnableInternalRegulator(ADC1);
  164. uint32_t wait_loop_index;
  165. wait_loop_index =
  166. ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US * (SystemCoreClock / (100000 * 2))) / 10);
  167. while(wait_loop_index != 0) {
  168. wait_loop_index--;
  169. }
  170. LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_1, LL_ADC_CHANNEL_1);
  171. LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_1, LL_ADC_SAMPLINGTIME_247CYCLES_5);
  172. LL_ADC_SetChannelSingleDiff(ADC1, LL_ADC_CHANNEL_1, LL_ADC_SINGLE_ENDED);
  173. LL_ADC_EnableIT_OVR(ADC1);
  174. }
  175. double abs_error(double num1, double num2) {
  176. return fabs((num1 - num2) / num1);
  177. }
  178. static void MX_TIM2_Init(int freq) {
  179. uint32_t timer_clock_frequency = 0; /* Timer clock frequency */
  180. uint32_t timer_prescaler =
  181. 0; /* Time base prescaler to have timebase aligned on minimum frequency possible */
  182. uint32_t timer_reload =
  183. 0; /* Timer reload value in function of timer prescaler to achieve time base period */
  184. LL_TIM_InitTypeDef TIM_InitStruct = {0};
  185. LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM2);
  186. if(LL_RCC_GetAPB1Prescaler() == LL_RCC_APB1_DIV_1) {
  187. timer_clock_frequency =
  188. __LL_RCC_CALC_PCLK1_FREQ(SystemCoreClock, LL_RCC_GetAPB1Prescaler());
  189. } else {
  190. timer_clock_frequency =
  191. (__LL_RCC_CALC_PCLK1_FREQ(SystemCoreClock, LL_RCC_GetAPB1Prescaler()) * 2);
  192. }
  193. //(PSC+1) * (ARR+1)
  194. double calc = timer_clock_frequency / (1 / (1 / (double)freq));
  195. double PSC;
  196. double ARR;
  197. double minerr = 10000;
  198. for(int i = 1; i < 65536; i++) {
  199. PSC = i - 1;
  200. ARR = calc / (PSC + 1);
  201. double error = abs_error((int)(ARR), ARR);
  202. if(error < (double)0.001 && error < minerr && ARR - 1 > 0) {
  203. timer_prescaler = PSC;
  204. timer_reload = ARR - 1;
  205. minerr = error;
  206. break;
  207. }
  208. }
  209. TIM_InitStruct.Prescaler = timer_prescaler;
  210. TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP;
  211. TIM_InitStruct.Autoreload = timer_reload;
  212. TIM_InitStruct.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1;
  213. LL_TIM_Init(TIM2, &TIM_InitStruct);
  214. LL_TIM_SetTriggerInput(TIM2, LL_TIM_TS_ITR0);
  215. LL_TIM_SetSlaveMode(TIM2, LL_TIM_SLAVEMODE_DISABLED);
  216. LL_TIM_DisableIT_TRIG(TIM2);
  217. LL_TIM_DisableDMAReq_TRIG(TIM2);
  218. LL_TIM_SetTriggerOutput(TIM2, LL_TIM_TRGO_UPDATE);
  219. LL_TIM_DisableMasterSlaveMode(TIM2);
  220. LL_TIM_SetTriggerOutput(TIM2, LL_TIM_TRGO_UPDATE);
  221. LL_TIM_EnableCounter(TIM2);
  222. }
  223. static void MX_DMA_Init(void) {
  224. LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMAMUX1);
  225. LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMA1);
  226. NVIC_SetPriority(DMA1_Channel1_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 1, 0));
  227. NVIC_EnableIRQ(DMA1_Channel1_IRQn);
  228. }
  229. static void MX_GPIO_Init(void) {
  230. LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA);
  231. LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOB);
  232. LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOC);
  233. }
  234. // Swap pointer addresses, used for double buffer
  235. void swap(__IO uint16_t** a, __IO uint16_t** b) {
  236. __IO uint16_t* tmp;
  237. tmp = *a;
  238. *a = *b;
  239. *b = tmp;
  240. }
  241. void AdcDmaTransferComplete_Callback() {
  242. uint32_t tmp_index = 0;
  243. for(tmp_index = (adc_buffer / 2); tmp_index < adc_buffer; tmp_index++) {
  244. mvoltWrite[tmp_index] = __LL_ADC_CALC_DATA_TO_VOLTAGE(
  245. VDDA_APPLI, aADCxConvertedData[tmp_index], LL_ADC_RESOLUTION_12B);
  246. }
  247. ubDmaTransferStatus = 1;
  248. if(!pause) swap(&mvoltWrite, &mvoltDisplay);
  249. }
  250. void AdcDmaTransferHalf_Callback() {
  251. uint32_t tmp_index = 0;
  252. for(tmp_index = 0; tmp_index < (adc_buffer / 2); tmp_index++) {
  253. mvoltWrite[tmp_index] = __LL_ADC_CALC_DATA_TO_VOLTAGE(
  254. VDDA_APPLI, aADCxConvertedData[tmp_index], LL_ADC_RESOLUTION_12B);
  255. }
  256. ubDmaTransferStatus = 0;
  257. }
  258. void Activate_ADC(void) {
  259. __IO uint32_t wait_loop_index = 0U;
  260. #if(USE_TIMEOUT == 1)
  261. uint32_t Timeout = 0U; /* Variable used for timeout management */
  262. #endif /* USE_TIMEOUT */
  263. if(LL_ADC_IsEnabled(ADC1) == 0) {
  264. LL_ADC_DisableDeepPowerDown(ADC1);
  265. LL_ADC_EnableInternalRegulator(ADC1);
  266. wait_loop_index =
  267. ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US * (SystemCoreClock / (100000 * 2))) / 10);
  268. while(wait_loop_index != 0) {
  269. wait_loop_index--;
  270. }
  271. LL_ADC_StartCalibration(ADC1, LL_ADC_SINGLE_ENDED);
  272. #if(USE_TIMEOUT == 1)
  273. Timeout = ADC_CALIBRATION_TIMEOUT_MS;
  274. #endif /* USE_TIMEOUT */
  275. while(LL_ADC_IsCalibrationOnGoing(ADC1) != 0) {
  276. #if(USE_TIMEOUT == 1)
  277. if(LL_SYSTICK_IsActiveCounterFlag()) {
  278. if(Timeout-- == 0) {
  279. }
  280. }
  281. #endif /* USE_TIMEOUT */
  282. }
  283. wait_loop_index = (ADC_DELAY_CALIB_ENABLE_CPU_CYCLES >> 1);
  284. while(wait_loop_index != 0) {
  285. wait_loop_index--;
  286. }
  287. LL_ADC_Enable(ADC1);
  288. #if(USE_TIMEOUT == 1)
  289. Timeout = ADC_ENABLE_TIMEOUT_MS;
  290. #endif /* USE_TIMEOUT */
  291. while(LL_ADC_IsActiveFlag_ADRDY(ADC1) == 0) {
  292. #if(USE_TIMEOUT == 1)
  293. /* Check Systick counter flag to decrement the time-out value */
  294. if(LL_SYSTICK_IsActiveCounterFlag()) {
  295. if(Timeout-- == 0) {
  296. /* Time-out occurred. Set LED to blinking mode */
  297. LED_Blinking(LED_BLINK_ERROR);
  298. }
  299. }
  300. #endif /* USE_TIMEOUT */
  301. }
  302. }
  303. }
  304. // Found from:
  305. // https://www.algorithm-archive.org/contents/cooley_tukey/cooley_tukey.html
  306. void bit_reverse(float complex* X, int N) {
  307. for(int i = 0; i < N; ++i) {
  308. int n = i;
  309. int a = i;
  310. int count = (int)ceil(log2((float)N)) - 1;
  311. n >>= 1;
  312. while(n > 0) {
  313. a = (a << 1) | (n & 1);
  314. count--;
  315. n >>= 1;
  316. }
  317. n = (a << count) & (int)((1 << (int)ceil(log2((float)N))) - 1);
  318. if(n > i) {
  319. float complex tmp = X[i];
  320. X[i] = X[n];
  321. X[n] = tmp;
  322. }
  323. }
  324. }
  325. // Found from:
  326. // https://www.algorithm-archive.org/contents/cooley_tukey/cooley_tukey.html
  327. //
  328. // Adapted slightly to use ceil, otherwise didn't seem to calculate
  329. // FFT correctly on the flipper zero
  330. void iterative_cooley_tukey(float complex* X, int N) {
  331. bit_reverse(X, N);
  332. for(int i = 1; i <= ceil(log2((float)N)); ++i) {
  333. int stride = (int)pow(2, i);
  334. float complex w = cexp(-2.0 * I * M_PI / (float)stride);
  335. for(int j = 0; j < N; j += stride) {
  336. float complex v = 1.0;
  337. for(int k = 0; k < stride / 2; ++k) {
  338. X[k + j + stride / 2] = X[k + j] - v * X[k + j + stride / 2];
  339. X[k + j] -= (X[k + j + stride / 2] - X[k + j]);
  340. v *= w;
  341. }
  342. }
  343. }
  344. }
  345. // Found from:
  346. // https://stackoverflow.com/questions/427477/fastest-way-to-clamp-a-real-fixed-floating-point-value
  347. double clamp(double d, double min, double max) {
  348. const double t = d < min ? min : d;
  349. return t > max ? max : t;
  350. }
  351. // Used to draw to display
  352. static void app_draw_callback(Canvas* canvas, void* ctx) {
  353. UNUSED(ctx);
  354. static char buf1[50];
  355. float max = 0.0;
  356. float min = FLT_MAX;
  357. int count = 0;
  358. if(type == m_capture) {
  359. if(!pause)
  360. elements_button_center(canvas, "Stop");
  361. else {
  362. elements_button_center(canvas, "REC");
  363. elements_button_right(canvas, "Save");
  364. }
  365. }
  366. if(pause)
  367. canvas_draw_icon(canvas, 116, 1, &I_pause_10x10);
  368. else
  369. canvas_draw_icon(canvas, 116, 1, &I_play_10x10);
  370. // Calculate voltage measurements
  371. for(uint32_t x = 0; x < adc_buffer; x++) {
  372. if(mvoltDisplay[x] < min) min = mvoltDisplay[x];
  373. if(mvoltDisplay[x] > max) max = mvoltDisplay[x];
  374. }
  375. max /= 1000;
  376. min /= 1000;
  377. switch(type) {
  378. case m_time: {
  379. // Display current scale
  380. snprintf(buf1, 50, "%.0fx", (double)scale);
  381. canvas_draw_str(canvas, 95, 10, buf1);
  382. // Display current time period
  383. snprintf(buf1, 50, "Time: %s", time);
  384. canvas_draw_str(canvas, 2, 10, buf1);
  385. // Shift waveform across a virtual 0 line, so it crosses 0
  386. for(uint32_t x = 0; x < adc_buffer; x++) {
  387. index_crossings[x] = -1;
  388. crossings[x] = -1.0;
  389. data[x] = ((float)mvoltDisplay[x] / 1000) - min;
  390. data[x] = ((2 / (max - min)) * data[x]) - 1;
  391. }
  392. // Find points at which waveform crosses virtual 0 line
  393. for(uint32_t x = 1; x < adc_buffer; x++) {
  394. if(data[x] >= 0 && data[x - 1] < 0) {
  395. index_crossings[count++] = x - 1;
  396. }
  397. }
  398. count = 0;
  399. // Linear interpolation to find zero crossings
  400. // see https://gist.github.com/endolith/255291 for Python version
  401. for(uint32_t x = 0; x < adc_buffer; x++) {
  402. if(index_crossings[x] == -1) break;
  403. crossings[count++] = (float)index_crossings[x] -
  404. data[index_crossings[x]] /
  405. (data[index_crossings[x] + 1] - data[index_crossings[x]]);
  406. }
  407. float avg = 0.0;
  408. float countv = 0.0;
  409. for(uint32_t x = 0; x < adc_buffer; x++) {
  410. if(x + 1 >= adc_buffer) break;
  411. if(crossings[x] == -1 || crossings[x + 1] == -1) break;
  412. avg += crossings[x + 1] - crossings[x];
  413. countv += 1;
  414. }
  415. avg /= countv;
  416. // Display frequency of waveform
  417. snprintf(buf1, 50, "Freq: %.1f Hz", (double)((float)freq / avg));
  418. canvas_draw_str(canvas, 2, 20, buf1);
  419. } break;
  420. case m_fft: {
  421. for(uint32_t i = 0; i < adc_buffer; i++) {
  422. fft_data[i] = ((float)mvoltDisplay[i] / 1000);
  423. }
  424. // Apply FFT
  425. iterative_cooley_tukey(fft_data, adc_buffer);
  426. // Find FFT bin, with highest power
  427. float max_val = -1;
  428. int idx = 0;
  429. for(uint32_t i = 1; i < adc_buffer / 2; i++) {
  430. float f = cabsf(fft_data[i]) * cabsf(fft_data[i]);
  431. if(f > max_val) {
  432. max_val = f;
  433. idx = i;
  434. }
  435. fft_power[i] = f;
  436. }
  437. // Display frequency of waveform
  438. snprintf(buf1, 50, "Freq: %.1fHz", (double)idx * ((double)freq / (double)adc_buffer));
  439. canvas_draw_str(canvas, 2, 10, buf1);
  440. } break;
  441. case m_voltage: {
  442. // Display current scale
  443. snprintf(buf1, 50, "%.0fx", (double)scale);
  444. canvas_draw_str(canvas, 95, 10, buf1);
  445. // Display max, min, peak-to-peak voltages
  446. snprintf(buf1, 50, "Max: %.2fV", (double)max);
  447. canvas_draw_str(canvas, 2, 10, buf1);
  448. snprintf(buf1, 50, "Min: %.2fV", (double)min);
  449. canvas_draw_str(canvas, 2, 20, buf1);
  450. snprintf(buf1, 50, "Vpp: %.2fV", (double)(max - min));
  451. canvas_draw_str(canvas, 2, 30, buf1);
  452. } break;
  453. default:
  454. break;
  455. }
  456. if(type != m_fft) {
  457. // Draw lines between each data point
  458. // y should range from 0 to 63
  459. for(uint32_t x = 1; x < adc_buffer; x++) {
  460. int32_t prev =
  461. 63 - (uint32_t)(((float)mvoltDisplay[x - 1] / (float)VDDA_APPLI) * scale * 63.0f);
  462. int32_t cur =
  463. 63 - (uint32_t)(((float)mvoltDisplay[x] / (float)VDDA_APPLI) * scale * 63.0f);
  464. if(!(prev < 0 && cur < 0))
  465. canvas_draw_line(canvas, x - 1, clamp(prev, 0, 63), x, clamp(cur, 0, 63));
  466. }
  467. } else {
  468. // Process FFT data - excluding bin 0
  469. float max = 0;
  470. for(uint32_t i = 1; i < adc_buffer / 2; i += adc_buffer / 2 / 128) {
  471. float sum = 0;
  472. for(uint32_t i2 = i; i2 < i + (adc_buffer / 2 / 128); i2++) {
  473. sum += fft_power[i2];
  474. }
  475. if(sum > max) {
  476. max = sum;
  477. }
  478. }
  479. uint32_t xpos = 0;
  480. // xpos: 0 to 126 for window size 256
  481. // xpos: 0 to 127 for window size 512
  482. // xpos: 0 to 127 for window size 1024
  483. // y should range from 0 to 63
  484. for(uint32_t i = 1; i < adc_buffer / 2; i += adc_buffer / 2 / 128) {
  485. float sum = 0;
  486. for(uint32_t i2 = i; i2 < i + (adc_buffer / 2 / 128); i2++) {
  487. sum += fft_power[i2];
  488. }
  489. canvas_draw_line(canvas, xpos, 63, xpos, 63 - (uint32_t)(((sum / max) * 63.0f)));
  490. xpos++;
  491. }
  492. }
  493. // Removing graph lines, to use extra pixel
  494. // Draw graph lines
  495. //canvas_draw_line(canvas, 0, 0, 0, 63);
  496. //canvas_draw_line(canvas, 0, 63, 127, 63);
  497. }
  498. static void app_input_callback(InputEvent* input_event, void* ctx) {
  499. furi_assert(ctx);
  500. FuriMessageQueue* event_queue = ctx;
  501. furi_message_queue_put(event_queue, input_event, FuriWaitForever);
  502. }
  503. // Free malloc'd data
  504. void free_all() {
  505. free(aADCxConvertedData);
  506. free((void*)aADCxConvertedData_Voltage_mVoltA);
  507. free((void*)aADCxConvertedData_Voltage_mVoltB);
  508. free(index_crossings);
  509. free(data);
  510. free(crossings);
  511. free(fft_data);
  512. free(fft_power);
  513. }
  514. void scope_scene_run_on_enter(void* context) {
  515. ScopeApp* app = context;
  516. // Find string representation of time period we're using
  517. for(uint32_t i = 0; i < COUNT_OF(time_list); i++) {
  518. if(time_list[i].time == app->time) {
  519. time = time_list[i].str;
  520. break;
  521. }
  522. }
  523. // Obtain scale value
  524. scale = app->scale;
  525. // Currently un-paused
  526. pause = 0;
  527. // What type of measurement are we performing
  528. type = app->measurement;
  529. adc_buffer = ADC_CONVERTED_DATA_BUFFER_SIZE;
  530. if(type == m_fft) adc_buffer = app->fft;
  531. aADCxConvertedData = malloc(adc_buffer * sizeof(uint16_t));
  532. aADCxConvertedData_Voltage_mVoltA = malloc(adc_buffer * sizeof(uint16_t));
  533. aADCxConvertedData_Voltage_mVoltB = malloc(adc_buffer * sizeof(uint16_t));
  534. index_crossings = malloc(adc_buffer * sizeof(int16_t));
  535. data = malloc(adc_buffer * sizeof(float));
  536. crossings = malloc(adc_buffer * sizeof(float));
  537. fft_data = malloc(adc_buffer * sizeof(float complex));
  538. fft_power = malloc(adc_buffer * sizeof(float));
  539. mvoltWrite =
  540. &aADCxConvertedData_Voltage_mVoltA[0]; // Pointer to area we write converted voltage data to
  541. mvoltDisplay = &aADCxConvertedData_Voltage_mVoltB[0]; // Pointer to area of memory we display
  542. // Copy vector table, modify to use our own IRQ handlers
  543. __disable_irq();
  544. memcpy(ramVector, (uint32_t*)(FLASH_BASE | SCB->VTOR), sizeof(uint32_t) * TABLE_SIZE);
  545. SCB->VTOR = (uint32_t)ramVector;
  546. ramVector[27] = (uint32_t)DMA1_Channel1_IRQHandler;
  547. ramVector[34] = (uint32_t)ADC1_IRQHandler;
  548. ramVector[44] = (uint32_t)TIM2_IRQHandler;
  549. __enable_irq();
  550. furi_hal_bus_enable(FuriHalBusTIM2);
  551. FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  552. uint32_t tmp_index_adc_converted_data = 0;
  553. MX_GPIO_Init();
  554. MX_DMA_Init();
  555. freq = 1 / app->time;
  556. MX_TIM2_Init((int)freq);
  557. // Set VREFBUF to 2.5V, as vref isn't connected to 3.3V itself in the flipper zero
  558. VREFBUF->CSR |= VREFBUF_CSR_ENVR;
  559. VREFBUF->CSR &= ~VREFBUF_CSR_HIZ;
  560. VREFBUF->CSR |= VREFBUF_CSR_VRS;
  561. while(!(VREFBUF->CSR & VREFBUF_CSR_VRR)) {
  562. };
  563. MX_ADC1_Init();
  564. // Setup initial values from ADC
  565. for(tmp_index_adc_converted_data = 0; tmp_index_adc_converted_data < adc_buffer;
  566. tmp_index_adc_converted_data++) {
  567. aADCxConvertedData[tmp_index_adc_converted_data] = VAR_CONVERTED_DATA_INIT_VALUE;
  568. aADCxConvertedData_Voltage_mVoltA[tmp_index_adc_converted_data] = 0;
  569. aADCxConvertedData_Voltage_mVoltB[tmp_index_adc_converted_data] = 0;
  570. }
  571. Activate_ADC();
  572. if((LL_ADC_IsEnabled(ADC1) == 1) && (LL_ADC_IsDisableOngoing(ADC1) == 0) &&
  573. (LL_ADC_REG_IsConversionOngoing(ADC1) == 0)) {
  574. LL_ADC_REG_StartConversion(ADC1);
  575. }
  576. ViewPort* view_port = view_port_alloc();
  577. view_port_draw_callback_set(view_port, app_draw_callback, view_port);
  578. view_port_input_callback_set(view_port, app_input_callback, event_queue);
  579. // Register view port in GUI
  580. Gui* gui = furi_record_open(RECORD_GUI);
  581. gui_add_view_port(gui, view_port, GuiLayerFullscreen);
  582. InputEvent event;
  583. bool running = true;
  584. bool save = false;
  585. while(running) {
  586. if(furi_message_queue_get(event_queue, &event, 150) == FuriStatusOk) {
  587. if((event.type == InputTypePress) || (event.type == InputTypeRepeat)) {
  588. switch(event.key) {
  589. case InputKeyLeft:
  590. break;
  591. case InputKeyRight: {
  592. // Save data if in capture mode
  593. if(type == m_capture && pause == 1) {
  594. running = false;
  595. save = true;
  596. }
  597. } break;
  598. case InputKeyUp:
  599. break;
  600. case InputKeyDown:
  601. break;
  602. case InputKeyOk:
  603. pause ^= 1;
  604. break;
  605. default:
  606. running = false;
  607. break;
  608. }
  609. }
  610. }
  611. view_port_update(view_port);
  612. }
  613. furi_hal_bus_disable(FuriHalBusTIM2);
  614. // Disable ADC interrupt and timer
  615. LL_ADC_DisableIT_OVR(ADC1);
  616. LL_TIM_DisableCounter(TIM2);
  617. // Stop DMA and switch back to original vector table
  618. LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_1);
  619. __disable_irq();
  620. SCB->VTOR = 0;
  621. __enable_irq();
  622. if(!save) {
  623. view_port_enabled_set(view_port, false);
  624. gui_remove_view_port(gui, view_port);
  625. view_port_free(view_port);
  626. free_all();
  627. // Switch back to original scene
  628. furi_record_close(RECORD_GUI);
  629. scene_manager_previous_scene(app->scene_manager);
  630. submenu_set_selected_item(app->submenu, 0);
  631. } else {
  632. view_port_enabled_set(view_port, false);
  633. gui_remove_view_port(gui, view_port);
  634. view_port_free(view_port);
  635. app->data = malloc(sizeof(uint16_t) * adc_buffer);
  636. memcpy(app->data, (uint16_t*)mvoltDisplay, sizeof(uint16_t) * adc_buffer);
  637. free_all();
  638. scene_manager_next_scene(app->scene_manager, ScopeSceneSave);
  639. }
  640. }
  641. bool scope_scene_run_on_event(void* context, SceneManagerEvent event) {
  642. UNUSED(context);
  643. UNUSED(event);
  644. return false;
  645. }
  646. void scope_scene_run_on_exit(void* context) {
  647. ScopeApp* app = context;
  648. // Clear views
  649. widget_reset(app->widget);
  650. }