代码示例_标准IO_fputc / fgetc

博客记录了fputc和fgetc的相关测试,测试文件为fput_fget.c,最终测试结果显示成功,并给出了转载来源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

fputc / fgetc

 


 

fput_fget.c

 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int main(void)
 5 {
 6     // 打开/创建 
 7     FILE *fp = fopen("./1.text","w+");
 8     if(fp==NULL){
 9         perror("fopen failed");
10         exit(1);
11     }
12     
13     // 写字符
14     int num = 66;
15     if(  fputc(num,fp)== EOF  ){
16         perror("fputc failed");
17         exit(1);
18     }
19     
20     // 关闭
21     fclose(fp);
22 
23 
24     // 打开/创建
25     fp = fopen("./1.text","r");
26     if(fp==NULL){
27         perror("fopen failed");
28         exit(1);
29     }
30     
31     // 读字符
32     int p = fgetc(fp);
33     if(p==EOF){
34         perror("fgetc failed");
35         exit(1);
36     }
37     printf("read : %c\n",p);
38 
39 
40     // 关闭
41     fclose(fp);
42 
43 
44     return 0 ;
45 }

 

 

测试:


 

 

 

 

success !

 

转载于:https://www.cnblogs.com/panda-w/p/11075389.html

当我输入1kHz的正弦波的时候 最后打印结果基波却是976Hz用这个算法不能很精确找到我想要的基波幅值 请给我解决这个问题 在我代码的基础上改/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * Copyright (c) 2025 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "adc.h" #include "dma.h" #include "tim.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include <stdio.h> #include "arm_math.h" #include "arm_const_structs.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ #define FFT_LENGTH 1024 #define SAMPLE_RATE 100000 //1000000.0f // 2MSPS采样率 #define NYQUIST_LIMIT (SAMPLE_RATE/2.0f) // 频谱分析结构体 typedef struct { float fundamental_freq; // 基波频率 float fundamental_mag; // 基波幅值 float thd; // 总谐波失真 float harmonics[5]; // 2-5次谐波幅值 } THD_Analysis; __IO uint8_t AdcConvEnd = 0; uint16_t adcBuff[FFT_LENGTH]; float fft_inputbuf[FFT_LENGTH * 2]; float fft_outputbuf[FFT_LENGTH]; THD_Analysis current_analysis; // 当前分析结果 uint16_t ADC_Value; // 频率分辨率 = 采样率/FFT点数 const float freq_resolution = SAMPLE_RATE / FFT_LENGTH; /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ #define MIN_FREQ 1000.0f // 最小基波频率 #define MAX_FREQ 100000.0f // 最大基波频率 /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ int fputc(int ch, FILE *f) { HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff); return ch; } int fgetc(FILE *f) { uint8_t ch = 0; HAL_UART_Receive(&huart1, &ch, 1, 0xffff); return ch; } // 抛物线插值法精确计算频率和幅值 void interpolate_peak(float *fft_mag, uint32_t peak_bin, float *exact_freq, float *exact_mag) { float left = fft_mag[peak_bin - 1]; float center = fft_mag[peak_bin]; float right = fft_mag[peak_bin + 1]; // 抛物线插值公式 float delta = 0.5f * (right - left) / (2.0f * center - left - right); *exact_mag = center - 0.25f * (left - right) * delta; // 精确频率计算 *exact_freq = (peak_bin + delta) * freq_resolution; } // 自适应窗口幅值计算 float calc_adaptive_magnitude(float *fft_mag, float target_freq) { // 计算理论索引位置 float exact_index = target_freq / freq_resolution; int center_index = (int)(exact_index + 0.5f); // 四舍五入 // 动态确定窗口大小(基于频率) int window_size; if(target_freq < 50000.0f) { window_size = 5; // 低频使用大窗口 } else if(target_freq < 150000.0f) { window_size = 3; // 中频使用中等窗口 } else { window_size = 1; // 高频使用单点 } int start_index = center_index - window_size/2; int end_index = center_index + window_size/2; // 边界保护 if(start_index < 1) start_index = 1; if(end_index >= FFT_LENGTH/2) end_index = FFT_LENGTH/2 - 1; // 计算窗口内点的RMS值 float sum_squares = 0.0f; int point_count = 0; for(int i = start_index; i <= end_index; i++) { sum_squares += fft_mag[i] * fft_mag[i]; point_count++; } return (point_count > 0) ? sqrtf(sum_squares / point_count) : 0.0f; } // THD计算函数 void THD_Calculation(float *fft_mag) { // 1. 在目标频段内搜索最大幅值点 uint32_t min_bin = (uint32_t)(MIN_FREQ / freq_resolution); uint32_t max_bin = (uint32_t)(MAX_FREQ / freq_resolution); if(min_bin < 1) min_bin = 1; if(max_bin >= FFT_LENGTH/2) max_bin = FFT_LENGTH/2 - 1; uint32_t peak_bin = min_bin; float peak_mag = 0.0f; for(uint32_t i = min_bin; i <= max_bin; i++) { if(fft_mag[i] > peak_mag) { peak_mag = fft_mag[i]; peak_bin = i; } } // 2. 使用插值法精确计算基波频率和幅值 float fundamental_freq, fundamental_mag; interpolate_peak(fft_mag, peak_bin, &fundamental_freq, &fundamental_mag); // 3. 计算谐波能量总和 (2~5次谐波) float harmonic_power = 0.0f; for(uint32_t h = 2; h <= 5; h++) { float harmonic_freq = fundamental_freq * h; // 检查是否超过Nyquist频率 if(harmonic_freq < NYQUIST_LIMIT) { float harmonic_mag = calc_adaptive_magnitude(fft_mag, harmonic_freq); current_analysis.harmonics[h-2] = harmonic_mag; harmonic_power += harmonic_mag * harmonic_mag; } else { current_analysis.harmonics[h-2] = 0.0f; } } // 4. 存储结果 current_analysis.fundamental_freq = fundamental_freq; current_analysis.fundamental_mag = fundamental_mag; current_analysis.thd = (sqrtf(harmonic_power) / fundamental_mag) * 100.0f; // 百分比形式 } // 打印分析结果 void print_analysis_results(void) { printf("\r\n===== 信号分析结果 =====\r\n"); printf("基波频率: %.1f Hz\r\n", current_analysis.fundamental_freq); printf("基波幅值: %.4f V\r\n", current_analysis.fundamental_mag); printf("THD: %.2f%%\r\n", current_analysis.thd); printf("\r\n谐波分量:\r\n"); for(int i = 0; i < 4; i++) { printf("%d次谐波: %.4f V (%.2f%%)\r\n", i+2, current_analysis.harmonics[i], (current_analysis.harmonics[i] / current_analysis.fundamental_mag) * 100.0f); } printf("========================\r\n\r\n"); } /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ // 四舍五入函数 int round_double(double num) { return (int)(num + 0.5); } /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_DMA_Init(); MX_ADC1_Init(); MX_TIM3_Init(); MX_USART1_UART_Init(); /* USER CODE BEGIN 2 */ // ��������ʼ�� CFFT �ṹ��ʵ�� // arm_cfft_instance_f32 cfft_inst; // HAL_TIM_Base_Start(&htim3); HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adcBuff, FFT_LENGTH); HAL_TIM_Base_Start(&htim3); while (!AdcConvEnd) //�ȴ�ת����� ; for (int i = 0; i < FFT_LENGTH; i++) { fft_inputbuf[i * 2] = adcBuff[i] * 3.3 / 4096;//ʵ����ֵ��* 3.3 / 4096��Ϊ�˽�ADC�ɼ�����ֵת����ʵ�ʵ�ѹ fft_inputbuf[i * 2 + 1] = 0;//�鲿��ֵ���̶�Ϊ0. } arm_cfft_f32(&arm_cfft_sR_f32_len1024, fft_inputbuf, 0, 1); arm_cmplx_mag_f32(fft_inputbuf, fft_outputbuf, FFT_LENGTH); fft_outputbuf[0] /= 1024; for (int i = 1; i < FFT_LENGTH; i++)//�������г����ֵ { fft_outputbuf[i] /= 512; } //printf("FFT Result:\r\n"); // 执行THD分析 THD_Calculation(fft_outputbuf); // 打印结果 print_analysis_results(); //for (int i = 0; i < FFT_LENGTH; i++)//�������г����ֵ //{ // // printf("%d:\t%.2f\r\n", i, fft_outputbuf[i]); //} /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Configure the main internal regulator output voltage */ __HAL_RCC_PWR_CLK_ENABLE(); __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; RCC_OscInitStruct.PLL.PLLM = 8; RCC_OscInitStruct.PLL.PLLN = 72; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 4; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ __disable_irq(); while (1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */
07-09
内容概要:本文档详细介绍了Analog Devices公司生产的AD8436真均方根-直流(RMS-to-DC)转换器的技术细节及其应用场景。AD8436由三个独立模块构成:轨到轨FET输入放大器、高动态范围均方根计算内核和精密轨到轨输出放大器。该器件不仅体积小巧、功耗低,而且具有广泛的输入电压范围和快速响应特性。文档涵盖了AD8436的工作原理、配置选项、外部组件选择(如电容)、增益调节、单电源供电、电流互感器配置、接地故障检测、三相电源监测等方面的内容。此外,还特别强调了PCB设计注意事项和误差源分析,旨在帮助工程师更好地理解和应用这款高性能的RMS-DC转换器。 适合人群:从事模拟电路设计的专业工程师和技术人员,尤其是那些需要精确测量交流电信号均方根值的应用开发者。 使用场景及目标:①用于工业自动化、医疗设备、电力监控等领域,实现对交流电压或电流的精准测量;②适用于手持式数字万用表及其他便携式仪器仪表,提供高效的单电源解决方案;③在电流互感器配置中,用于检测微小的电流变化,保障电气安全;④应用于三相电力系统监控,优化建立时间和转换精度。 其他说明:为了确保最佳性能,文档推荐使用高质量的电容器件,并给出了详细的PCB布局指导。同时提醒用户关注电介质吸收和泄漏电流等因素对测量准确性的影响。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值