Raspberry Pi是一款广受欢迎的微型计算机,因其小巧的体积和低成本而受到许多爱好者的喜爱。然而,它并不自带电源供应,通常需要通过USB接口供电。本文将介绍如何制作一个简单的电源开关,用于控制Raspberry Pi的启动和关闭。
自制的电源开关包括以下几个部分:
当电源连接时,Attiny85被供电,继电器处于关闭状态,Pi未供电。Attiny85等待按钮被按下。当按钮被按下时,继电器被切换,Pi被供电并启动。当按钮再次被按下时,程序向Pi发送一个信号以执行关机。Pi上运行着一个Python脚本,监听GPIO端口的信号。当接收到信号时,Pi将执行关机命令。程序通过监测GPIO14(UART TX)(电压<0.1)来等待Pi完全关机。一旦确认Pi完全关机,程序将继电器切换到关闭状态,Pi的电源将被切断。
电路图如下所示:
更多详细信息请访问:
首先,将草图安装到Attiny85中。使用的是Digispark USB开发板()。
在Raspberry Pi上运行关机脚本()。
以下是代码中一些关键点的解释:
int SHUTDOWN_PIN = 3;
int RELAY_PIN = 0;
int BUTTON_PIN = 2;
int LED_PIN = 1;
变量powerstatus
用于跟踪Pi的电源状态。
int powerstatus = 0;
//Power Toggle Mode
// 0 Power off
// 1 Powering On (not used for now)
// 2 Powered on
// 3 Powering off
// 4 Waiting for Safe Shutdown to finish
// 5 Hard Shutdown
每个循环延迟50ms,使得时间控制变得简单(例如,按钮被按下了多长时间)。
if (buttondowncount >= 60 && buttonupcount > 2) {
//Long Pressed Button
buttondowncount = 0;
buttonupcount = 0;
powerstatus = 5;
}
如果按钮被长时间按下(60 * 50ms = 3s),则强制关机。
else if (buttondowncount >= 3 && buttonupcount > 2) {
//Button Pressed
buttondowncount = 0;
buttonupcount = 0;
if (powerstatus == 0)
powerstatus = 2;
else if (powerstatus == 2)
powerstatus = 3;
}
如果按钮被短时间按下(3 * 50ms = 150ms),则从关机状态(powerstatus 0到1)或开始关机序列(powerstatus 2到3)。
以下是根据powerstatus
执行的动作:
if (powerstatus == 2) {
digitalWrite(SHUTDOWN_PIN, LOW);
digitalWrite(LED_PIN, HIGH);
digitalWrite(RELAY_PIN, HIGH);
}
else if (powerstatus == 3) {
//Start Shutdown Sequence
//Trigger shutdown script in Pi
digitalWrite(SHUTDOWN_PIN, HIGH);
delay(100);
digitalWrite(SHUTDOWN_PIN, LOW);
powerstatus = 4;
checkOffCount = 0;
}
else if (powerstatus == 4) {
//Waiting for fully power off signal in TX pin
//Blink LED to signal powering off
digitalWrite(LED_PIN, LOW);
delay(300);
digitalWrite(LED_PIN, HIGH);
delay(200);
//Check if it's off 5 times before shutting down
if (checkPiOff())
checkOffCount = checkOffCount + 1;
else
checkOffCount = 0;
if (checkOffCount == 10) {
//It's really off
digitalWrite(LED_PIN, LOW);
digitalWrite(RELAY_PIN, LOW);
powerstatus = 0;
checkOffCount = 0;
}
}
else if (powerstatus == 5) {
//Hard shutdown
digitalWrite(LED_PIN, LOW);
digitalWrite(RELAY_PIN, LOW);
powerstatus = 0;
checkOffCount = 0;
}
最有趣的部分是powerstatus==3
和4
。以下是触发Pi并运行关机命令,并将powerstatus
设置为4
(等待安全关机完成)。
digitalWrite(SHUTDOWN_PIN, HIGH);
delay(100);
digitalWrite(SHUTDOWN_PIN, LOW);
powerstatus = 4;
然后在powerstatus == 4
中,它闪烁LED灯并监控Pi是否完全关机。
else if (powerstatus == 4) {
digitalWrite(LED_PIN, LOW);
delay(300);
digitalWrite(LED_PIN, HIGH);
delay(200);
//Check if it's off 5 times before shutting down
if (checkPiOff())
checkOffCount = checkOffCount + 1;
else
checkOffCount = 0;
if (checkOffCount == 5) {
//It's really off
digitalWrite(LED_PIN, LOW);
digitalWrite(RELAY_PIN, LOW);
powerstatus = 0;
checkOffCount = 0;
}
}