树莓派 UPS-18650

配置时钟

启用i2c

sudo raspi-config

在interfacing options 中选择启用i2c

运行

sudo i2cdetect -l

查看所有的i2c总线

这里回显

i2c-1   i2c             bcm2835 I2C adapter                     I2C adapter

查看i2c上连接的设备

sudo i2cdetect -y 1

回显

     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00: -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- 36 -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- 68 -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --

这里的0x36为MAX17040G的地址; 0x68为DS1307Z+的地址

加载 i2c 模块

sudo modprobe i2c-dev

切换到超级管理 su

在i2cx 新增一个设备, 名字为ds1307, 设备地址为 0x68

echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-1/new_device

查看我们的刚刚添加的硬件时钟的当前时间

hwclock -r

回显

2000-01-01 08:01:24.321813+0800

很显然这是刚添加的时钟, 还未同步正确的时间

将系统时间写入到硬件时钟

hwclock -w

这时我们再次读取硬件时钟的话

回显

2019-11-09 17:26:30.864206+0800

已经同步到系统时钟

同步硬件时钟到系统时钟

当我们的树莓派断电后, 再次启动后, 如果没有网络的话, 她是不能正确同步系统时间的, 但我们的 UPS 上有一颗时钟芯片, 并且一直有纽扣电池供电, 并不会丢失我们上面设置好的日期时间, 所以我们需要在树莓派启动时将硬件时钟的时间写入到树莓派的系统时间.

打开树莓派的启动文件rc.local

nano /etc/rc.local

在exit 0 前添加

modprobe i2c-dev
echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-1/new_device
hwclock -r
hwclock -s

重启在无网络的情况下可以测试系统时钟是否被正确同步

读取电量

这里我们先简单跑一下板方提供的脚本


#!/usr/bin/env python
import struct
import smbus
import sys
import time


def readVoltage(bus):

"This function returns as float the voltage from the Raspi UPS Hat via the provided SMBus object"
address = 0x36
read = bus.read_word_data(address, 2)
swapped = struct.unpack("<H", struct.pack(">H", read))[0]
voltage = swapped * 1.25 /1000/16
return voltage


def readCapacity(bus):
"This function returns as a float the remaining capacity of the battery connected to the Raspi UPS Hat via the provided SMBus object"
address = 0x36
read = bus.read_word_data(address, 4)
swapped = struct.unpack("<H", struct.pack(">H", read))[0]
capacity = swapped/256
return capacity


bus = smbus.SMBus(1) # 0 = /dev/i2c-0 (port I2C0), 1 = /dev/i2c-1 (port I2C1)

while True:

print "++++++++++++++++++++"
print "Voltage:%5.2fV" % readVoltage(bus)

print "Battery:%5i%%" % readCapacity(bus)

if readCapacity(bus) == 100:

print "Battery FULL"

if readCapacity(bus) < 20:

print "Battery LOW"
print "++++++++++++++++++++"
time.sleep(2)

回显

++++++++++++++++++++
Voltage: 3.64V
Battery: 8%
Battery LOW
++++++++++++++++++++

参考文章