C 로 구현한 PWM(Pulse Width Modulation) 제어기
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // For usleep (Linux systems)
// Function to generate PWM signal
void pwm_control(int duty_cycle, int frequency, int duration_ms) {
// Validate input
if (duty_cycle < 0 || duty_cycle > 100) {
printf("Error: Duty cycle must be between 0 and 100.\n");
return;
}
if (frequency <= 0) {
printf("Error: Frequency must be greater than 0.\n");
return;
}
if (duration_ms <= 0) {
printf("Error: Duration must be greater than 0.\n");
return;
}
// Calculate the period in microseconds
int period_us = 1000000 / frequency;
// Calculate the ON and OFF time in microseconds
int on_time_us = (duty_cycle * period_us) / 100;
int off_time_us = period_us - on_time_us;
printf("PWM Control Parameters:\n");
printf("Duty Cycle: %d%%\n", duty_cycle);
printf("Frequency: %d Hz\n", frequency);
printf("Period: %d us\n", period_us);
printf("ON Time: %d us\n", on_time_us);
printf("OFF Time: %d us\n", off_time_us);
// Calculate the number of cycles to run
int cycles = (duration_ms * 1000) / period_us;
for (int i = 0; i < cycles; i++) {
// Simulate ON state
printf("ON\n");
usleep(on_time_us);
// Simulate OFF state
printf("OFF\n");
usleep(off_time_us);
}
}
int main() {
int duty_cycle, frequency, duration_ms;
// Get user input
printf("Enter duty cycle (0-100%%): ");
scanf("%d", &duty_cycle);
printf("Enter frequency (Hz): ");
scanf("%d", &frequency);
printf("Enter duration (ms): ");
scanf("%d", &duration_ms);
// Run the PWM control function
pwm_control(duty_cycle, frequency, duration_ms);
return 0;
}
위의 코드는 PWM(Pulse Width Modulation) 신호를 생성하는 C 코드입니다.
주요 구성 요소:
duty_cycle
:- PWM 신호의 ON 상태의 비율(%)입니다.
frequency
:- PWM 신호의 주파수(Hz)로, 신호의 반복 속도를 결정합니다.
duration_ms
:- PWM 신호를 실행할 총 지속 시간(ms)입니다.
- ON/OFF 시간 계산:
- 주기(period)는 마이크로초로 계산됩니다.
- ON 시간과 OFF 시간은 주기와 듀티 사이클을 기반으로 나뉩니다.
코드 실행:
- 사용자 입력을 받아 듀티 사이클, 주파수, 지속 시간을 설정합니다.
- 계산된 ON 및 OFF 시간을 기반으로
usleep
함수로 신호를 생성합니다. - ON 및 OFF 상태를 시뮬레이션하여 콘솔에 출력합니다.
실행 예제:
입력:
Enter duty cycle (0-100%): 50
Enter frequency (Hz): 2
Enter duration (ms): 2000
출력:
PWM Control Parameters:
Duty Cycle: 50%
Frequency: 2 Hz
Period: 500000 us
ON Time: 250000 us
OFF Time: 250000 us
ON
OFF
ON
OFF
...
이 코드는 간단한 PWM 제어를 시뮬레이션할 수 있으며, 실제 시스템에서는 GPIO 핀을 제어하는 코드로 확장할 수 있습니다. 필요에 따라 하드웨어에 맞게 조정하십시오.