#----------------------------------------------------------------
# vcc 5V
# SDA i2c数据 --- pin3
# SDL i2c时钟 --- pin5
# GND
#----------------------------------------------------------------
import smbus #import SMBus module of I2C
import time
import math
import json
import paho.mqtt.client as mqtt
from datetime import datetime
from threading import Timer
broker = ' mqtt云服务器地址‘
port = 端口号
keepalive = 60 # 与代理通信之间允许的最长时间段(以秒为单位)
topic = 'MPU6050'
#some MPU6050 Registers and their Address
PWR_MGMT_1 = 0x6B
SMPLRT_DIV = 0x19
RA_CONFIG = 0x1A
GYRO_CONFIG = 0x1B
ACCEL_CONFIG = 0x1C
INT_ENABLE = 0x38
ACCEL_XOUT_H = 0x3B
ACCEL_YOUT_H = 0x3D
ACCEL_ZOUT_H = 0x3F
GYRO_XOUT_H = 0x43
GYRO_YOUT_H = 0x45
GYRO_ZOUT_H = 0x47
RA_TEMP_H = 0x41
bus = smbus.SMBus(1)
Device_Address = 0x68 # MPU6050 device address
def MPU_Init():
bus.write_byte_data(Device_Address, SMPLRT_DIV, 0x07) #陀螺仪采样率1KHz
bus.write_byte_data(Device_Address, PWR_MGMT_1, 0x00) #解除休眠状态
bus.write_byte_data(Device_Address, RA_CONFIG, 0x06) #低通滤波器设置(0),截至频率是1K,带宽是5K
bus.write_byte_data(Device_Address, GYRO_CONFIG, 0x18) #/陀螺仪自检及测量范围(24)
bus.write_byte_data(Device_Address, ACCEL_CONFIG, 0x01) #配置加速度传感器工作再16G模式
def read_raw_data(addr):
#Accelero and Gyro value are 16-bit
high = bus.read_byte_data(Device_Address, addr)
low = bus.read_byte_data(Device_Address, addr+1)
#concatenate higher and lower value
value = ((high << 8) | low)
#to get signed value from mpu6050
if(value > 32768):
value = value - 65536
return value
def get_data():
raw_temp = read_raw_data(RA_TEMP_H)
gyro_x = read_raw_data(GYRO_XOUT_H)
gyro_y = read_raw_data(GYRO_YOUT_H)
gyro_z = read_raw_data(GYRO_ZOUT_H)
acc_x = read_raw_data(ACCEL_XOUT_H)
acc_y = read_raw_data(ACCEL_YOUT_H)
acc_z = read_raw_data(ACCEL_ZOUT_H)
#Full scale range +/- 250 degree/C as per sensitivity scale factor
Gx = gyro_x/131.0
Gy = gyro_y/131.0
Gz = gyro_z/131.0
Ax = acc_x/16384.0
Ay = acc_y/16384.0
Az = acc_z/16384.0
actual_temp = (raw_temp / 340.0)+ 36.53
print('mpu6050_temp', round(actual_temp,3))
data = {
'Gx':round(Gx,3),
'Gy':round(Gy,3),
'Gz':round(Gz,3),
'Ax':round(Ax,3),
'Ay':round(Ay,3),
'Az':round(Az,3)
}
return json.dumps(data)
client = mqtt.Client()
client.connect(broker,port,keepalive)
print('mqtt conneted sucess')
client.loop_start()
MPU_Init()
print ("Reading Data of Gyroscope and Accelerometer")
print('mqtt conneted sucess')
Time_threading(60)
while True:
time.sleep(1) #通过延迟来解决aviod 121 IO erro或接GND接在pin39
msg =get_data()
client.publish(topic, msg)
print(number, 'SEND MPU6050 data: ', msg)