guowenxue
5 days ago fe7aebb0fa469c98f4ac3bc52874738f84edb515
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  buzzer.c
 *    Description:  This file is linux kernel pwm-beeper driver test code.
 *                 
 *        Version:  1.0.0(12/17/2025)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "12/17/2025 09:44:08 PM"
 *                 
 ********************************************************************************/
 
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <linux/input.h>
#include <sys/time.h>
 
int main(int argc, char *argv[]) {
    int fd;
    struct input_event ev;
    int frequency = 10000;  // Default: 10kHz
    float duration = 0.5;  // Default: 0.5 seconds
    
    // Parse command line arguments
    if (argc >= 2) {
        frequency = atoi(argv[1]);
    }
    if (argc >= 3) {
        duration = atof(argv[2]);
    }
    
    // Open buzzer device
    fd = open("/dev/input/event0", O_WRONLY);
    if (fd < 0) {
        perror("Failed to open /dev/input/event0");
        return 1;
    }
    
    printf("=== PWM Buzzer Control ===\n");
    printf("Device: /dev/input/event0\n");
    printf("Frequency: %d Hz\n", frequency);
    printf("Duration: %.2f seconds\n", duration);
    
    // Clear event structure
    memset(&ev, 0, sizeof(ev));
    ev.type = EV_SND;      // 0x12 = Sound event
    ev.code = SND_TONE;    // 0x02 = Tone control
    ev.value = frequency;  // Frequency in Hz
    
    printf("\nStarting beep...\n");
    if (write(fd, &ev, sizeof(ev)) != sizeof(ev)) {
        perror("Failed to write start event");
        close(fd);
        return 1;
    }
    
    // Wait for specified duration
    usleep(duration * 1000000);
    
    // Stop beeping
    ev.value = 0;  // 0 Hz = stop
    printf("Stopping beep...\n");
    if (write(fd, &ev, sizeof(ev)) != sizeof(ev)) {
        perror("Failed to write stop event");
    }
    
    // Close device
    close(fd);
    printf("\nTest completed!\n");
    
    return 0;
}