48 lines
1.2 KiB
Go
48 lines
1.2 KiB
Go
// gpio_controller.go
|
|
package business
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
const BuzzerGPIO = 109
|
|
|
|
// TriggerBuzzer 触发蜂鸣器响指定秒数
|
|
func TriggerBuzzer(seconds int) {
|
|
if seconds <= 0 {
|
|
seconds = 10
|
|
}
|
|
|
|
// 必须用同步!异步 goroutine 在某些系统里会被静默丢弃
|
|
fmt.Printf("蜂鸣器开始响铃 %d 秒...\n", seconds)
|
|
|
|
gpioPath := fmt.Sprintf("/sys/class/gpio/gpio%d", BuzzerGPIO)
|
|
|
|
// 1. 强制导出(即使已经导出也没事)
|
|
os.WriteFile("/sys/class/gpio/export", []byte(strconv.Itoa(BuzzerGPIO)), 0666)
|
|
time.Sleep(50 * time.Millisecond)
|
|
|
|
// 2. 强制设为输出
|
|
os.WriteFile(fmt.Sprintf("%s/direction", gpioPath), []byte("out"), 0666)
|
|
time.Sleep(10 * time.Millisecond)
|
|
|
|
// 3. 拉高 → 响
|
|
if err := os.WriteFile(fmt.Sprintf("%s/value", gpioPath), []byte("1"), 0666); err != nil {
|
|
fmt.Printf("GPIO拉高失败: %v\n", err)
|
|
} else {
|
|
fmt.Println("GPIO109 已拉高 → 蜂鸣器响!")
|
|
}
|
|
|
|
time.Sleep(time.Duration(seconds) * time.Second)
|
|
|
|
// 4. 拉低 → 停
|
|
if err := os.WriteFile(fmt.Sprintf("%s/value", gpioPath), []byte("0"), 0666); err != nil {
|
|
fmt.Printf("GPIO拉低失败: %v\n", err)
|
|
} else {
|
|
fmt.Println("GPIO109 已拉低 → 蜂鸣器停止")
|
|
}
|
|
}
|