android
2024-07-25 2dcf9cc893a27c50d538baf8b5d47ff06fe495d8
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
#include <jni.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <android/log.h>
#define TAG "BuzzerApp"
#define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, TAG, fmt, ##args)
#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)
#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)
 
static char pwm_path[100];
 
extern "C"
JNIEXPORT jint JNICALL
Java_com_example_serial_BuzzerControl_openPwm(JNIEnv *env, jclass clazz, jstring id) {
    // TODO: implement openPwm()
    char *id_native;
    char  temp[100];
    int   fd;
    id_native = (char *)env->GetStringUTFChars(id, 0);
    memset(pwm_path, 0, sizeof (pwm_path));
    snprintf(pwm_path, sizeof (pwm_path), "/sys/class/pwm/pwmchip%s/pwm0", id_native);
 
    memset(temp, 0, sizeof (temp));
    if(access(pwm_path, F_OK))
    {
        snprintf(temp, sizeof (temp), "/sys/class/pwm/pwmchip%s/export", id_native);
        fd = open(temp, O_WRONLY);
        if(fd < 0)
        {
            LOGE("open %s error:%s\n", temp, strerror(errno));
            return -1;
        }
 
        if(1 != write(fd, "0", 1))
        {
            LOGE("Write '0' to pwmchip%s/export error\n", id_native);
            close(fd);
            return -2;
        }
        close(fd);
    }
    env->ReleaseStringUTFChars(id, id_native);
    return 0;
}