# 美光實習
## 溫度感測器
[ad590](https://www.shs.edu.tw/works/essay/2009/03/2009033116461249.pdf)
## 安裝grovepi+
輸入:`sudo i2cdetect -y 1`
安裝成功:
```bash=
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- 04 -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- 53 -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
```
表示grovepi有被樹莓派所偵測到。
### 安裝grovepi操作:
前提:
1. `sudo apt-get update`
2. `sudo apt-get upgrade`
- step 1 :`sudo curl -kL dexterindustries.com/update_grovepi | bash`
- step 2 : `mkdir ~/Dexter`
- step 3 :`cd /home/pi/Dexter`
- step 4 : `git clone https://github.com/Dexter/GrovePi`
- 建議是直接fork到你的github
- step 5 :`cd /home/pi/Dexter/GrovePi/Script`
- step 6 :`sudo chmod +x install.sh`
- step 7 : `ls -l`
- step 8 : `install` turn to green
- step 9 : `sudo ./install.sh`
- step 10 : ``sudo i2cdetect -y 1
[ fourier transform](http://ericstrong.org/fast-fourier-transforms-in-python/)
## adxl345:
```python=
# The MIT License (MIT)
#
# Copyright (c) 2016 Adafruit Industries
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import struct
# Minimal constants carried over from Arduino library
ADXL345_ADDRESS = 0x53 # data register can be change to 0x04
ADXL345_REG_DEVID = 0x00 # Device ID
ADXL345_REG_DATAX0 = 0x32 # X-axis data 0 (6 bytes for X/Y/Z)
ADXL345_REG_POWER_CTL = 0x2D # Power-saving features control
ADXL345_REG_DATA_FORMAT = 0x31 # search for data format
ADXL345_REG_BW_RATE = 0x2C
ADXL345_DATARATE_0_10_HZ = 0x00
ADXL345_DATARATE_0_20_HZ = 0x01
ADXL345_DATARATE_0_39_HZ = 0x02
ADXL345_DATARATE_0_78_HZ = 0x03
ADXL345_DATARATE_1_56_HZ = 0x04
ADXL345_DATARATE_3_13_HZ = 0x05
ADXL345_DATARATE_6_25HZ = 0x06
ADXL345_DATARATE_12_5_HZ = 0x07
ADXL345_DATARATE_25_HZ = 0x08
ADXL345_DATARATE_50_HZ = 0x09
ADXL345_DATARATE_100_HZ = 0x0A # (default)
ADXL345_DATARATE_200_HZ = 0x0B
ADXL345_DATARATE_400_HZ = 0x0C
ADXL345_DATARATE_800_HZ = 0x0D
ADXL345_DATARATE_1600_HZ = 0x0E
ADXL345_DATARATE_3200_HZ = 0x0F
ADXL345_RANGE_2_G = 0x00 # +/- 2g (default)
ADXL345_RANGE_4_G = 0x01 # +/- 4g
ADXL345_RANGE_8_G = 0x02 # +/- 8g
ADXL345_RANGE_16_G = 0x03 # +/- 16g
class ADXL345(object):
"""ADXL345 triple-axis accelerometer."""
def __init__(self, address=ADXL345_ADDRESS, i2c=None, **kwargs):
"""Initialize the ADXL345 accelerometer using its I2C interface.
"""
# Setup I2C interface for the device.
if i2c is None:
import Adafruit_GPIO.I2C as I2C
i2c = I2C
self._device = i2c.get_i2c_device(address, **kwargs)
# Check that the acclerometer is connected, then enable it.
if self._device.readU8(ADXL345_REG_DEVID) == 0xE5:
self._device.write8(ADXL345_REG_POWER_CTL, 0x08)
else:
raise RuntimeError('Failed to find the expected device ID register value, check your wiring.')
def set_range(self, value):
"""Set the range of the accelerometer to the provided value. Range value
should be one of these constants:
- ADXL345_RANGE_2_G = +/-2G
- ADXL345_RANGE_4_G = +/-4G
- ADXL345_RANGE_8_G = +/-8G
- ADXL345_RANGE_16_G = +/-16G
"""
# Read the data format register to preserve bits. Update the data
# rate, make sure that the FULL-RES bit is enabled for range scaling
format_reg = self._device.readU8(ADXL345_REG_DATA_FORMAT) & ~0x0F
format_reg |= value
format_reg |= 0x08 # FULL-RES bit enabled
# Write the updated format register.
self._device.write8(ADXL345_REG_DATA_FORMAT, format_reg)
def get_range(self):
"""Retrieve the current range of the accelerometer. See set_range for
the possible range constant values that will be returned.
"""
return self._device.readU8(ADXL345_REG_DATA_FORMAT) & 0x03
def set_data_rate(self, rate):
"""Set the data rate of the aceelerometer. Rate should be one of the
following constants:
- ADXL345_DATARATE_0_10_HZ = 0.1 hz
- ADXL345_DATARATE_0_20_HZ = 0.2 hz
- ADXL345_DATARATE_0_39_HZ = 0.39 hz
- ADXL345_DATARATE_0_78_HZ = 0.78 hz
- ADXL345_DATARATE_1_56_HZ = 1.56 hz
- ADXL345_DATARATE_3_13_HZ = 3.13 hz
- ADXL345_DATARATE_6_25HZ = 6.25 hz
- ADXL345_DATARATE_12_5_HZ = 12.5 hz
- ADXL345_DATARATE_25_HZ = 25 hz
- ADXL345_DATARATE_50_HZ = 50 hz
- ADXL345_DATARATE_100_HZ = 100 hz
- ADXL345_DATARATE_200_HZ = 200 hz
- ADXL345_DATARATE_400_HZ = 400 hz
- ADXL345_DATARATE_800_HZ = 800 hz
- ADXL345_DATARATE_1600_HZ = 1600 hz
- ADXL345_DATARATE_3200_HZ = 3200 hz
"""
# Note: The LOW_POWER bits are currently ignored,
# we always keep the device in 'normal' mode
self._device.write8(ADXL345_REG_BW_RATE, rate & 0x0F)
def get_data_rate(self):
"""Retrieve the current data rate. See set_data_rate for the possible
data rate constant values that will be returned.
"""
return self._device.readU8(ADXL345_REG_BW_RATE) & 0x0F
def read(self):
"""Read the current value of the accelerometer and return it as a tuple
of signed 16-bit X, Y, Z axis values.
"""
raw = self._device.readList(ADXL345_REG_DATAX0, 6)
return struct.unpack('<hhh', raw)
# Simple demo of of the ADXL345 accelerometer library. Will print the X, Y, Z
# axis acceleration values every half second.
# Author: Tony DiCola
# License: Public Domain
import time
# Import the ADXL345 module.
import Adafruit_ADXL345
# Import Mqtt as Server :
import paho.mqtt.client as mqtt
# setting for delay :
import time
# setting for concurrency calculation :
import threading
import numpy as np
from scipy import pi
import matplotlib.pyplot as plt
# matplotlib inline
# Create an ADXL345 instance.
# Alternatively you can specify the device address and I2C bus with parameters:
#accel = Adafruit_ADXL345.ADXL345(address=0x54, busnum=2)
# You can optionally change the range to one of:
# - ADXL345_RANGE_2_G = +/-2G (default)
# - ADXL345_RANGE_4_G = +/-4G
# - ADXL345_RANGE_8_G = +/-8G
# - ADXL345_RANGE_16_G = +/-16G
# For example to set to +/- 16G:
#accel.set_range(Adafruit_ADXL345.ADXL345_RANGE_16_G)
# Or change the data rate to one of:
# - ADXL345_DATARATE_0_10_HZ = 0.1 hz
# - ADXL345_DATARATE_0_20_HZ = 0.2 hz
# - ADXL345_DATARATE_0_39_HZ = 0.39 hz
# - ADXL345_DATARATE_0_78_HZ = 0.78 hz
# - ADXL345_DATARATE_1_56_HZ = 1.56 hz
# - ADXL345_DATARATE_3_13_HZ = 3.13 hz
# - ADXL345_DATARATE_6_25HZ = 6.25 hz
# - ADXL345_DATARATE_12_5_HZ = 12.5 hz
# - ADXL345_DATARATE_25_HZ = 25 hz
# - ADXL345_DATARATE_50_HZ = 50 hz
# - ADXL345_DATARATE_100_HZ = 100 hz (default)
# - ADXL345_DATARATE_200_HZ = 200 hz
# - ADXL345_DATARATE_400_HZ = 400 hz
# - ADXL345_DATARATE_800_HZ = 800 hz
# - ADXL345_DATARATE_1600_HZ = 1600 hz
# - ADXL345_DATARATE_3200_HZ = 3200 hz
# For example to set to 6.25 hz:
#accel.set_data_rate(Adafruit_ADXL345.ADXL345_DATARATE_6_25HZ)
accel = Adafruit_ADXL345.ADXL345()
# accel.set_data_rate(Adafruit_ADXL345.ADXL345_DATARATE_1600_HZ)
# accel.set_range(Adafruit_ADXL345.ADXL345_RANGE_16_G)
start_time = 0 # setting sstart time
global end_time
end_time = 30 # end at 2 seconds
sampling_rate = 1000 # sample_rate = 1000HZ
N = (end_time - start_time)*sampling_rate # array size
time1 = np.linspace(start_time, end_time, N)
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("IOT_NEAT_TOPIC01")
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
def thread1():
mqttc = mqtt.Client("python_pub")
_g_cst_ToMQTTTopicServerIP = "35.229.37.146"
_g_cst_ToMQTTTopicServerPort = 1883 #port
_g_cst_MQTTTopicName = "IOT_NEAT_TOPIC01" #TOPIC name
mqttc.connect(_g_cst_ToMQTTTopicServerIP, _g_cst_ToMQTTTopicServerPort)
while 1:
# x,y,z = accel.read()
mqttc.publish(_g_cst_MQTTTopicName, 'X={0}, Y={1}, Z={2}'.format(x, y, z))
time.sleep(0.1)
if clock == 30:
print('time is up')
break
def thread_sensor1():
while 1:
global x
global y
global z
global vib_data_x
vib_data_x = np.zeros(5000)
i=0
x,y,z=accel.read()
print('X_in_server={0}, Y_in_server={1}, Z_in_server={2}'.format(x, y, z))
if vib_data_x[i] == 0:
vib_data_x[i] = x
i+=1
time.sleep(0.1)
if clock == 30:
print('time is up ')
break
def thread_clock():
global clock
clock = 0
while 1:
clock += 1
print('clock is %d'%(clock))
time.sleep(1)
if clock == 30:
print('the time is up ')
break
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("35.229.37.146", 1883, 60)
my_thread1 = threading.Thread(target = thread1)
my_thread2 = threading.Thread(target = thread_sensor1)
my_thread3 = threading.Thread(target = thread_clock)
my_thread1.start()
my_thread2.start()
my_thread3.start()
print("this is main thread") # should not go here
# client.loop_forever()
```
:::danger
解決不同一個adxl345會去干擾到另一台的數據
:::
## 設定不同的I2C位址:
[I2C位址設定](https://www.instructables.com/id/Raspberry-PI-Multiple-I2c-Devices/)
[對應連結](https://github.com/pimoroni/adxl345-python/blob/master/adxl345.py)
https://learn.sparkfun.com/tutorials/raspberry-pi-spi-and-i2c-tutorial#i2c-on-pi

[I2C connect multi processor](https://electronics.stackexchange.com/questions/25278/how-to-connect-multiple-i2c-interface-devices-into-a-single-pin-a4-sda-and-a5/170752)
https://github.com/switchdoclabs/SDL_Pi_DataLogger/blob/master/SDL_Pi_TCA9545/testSDL_Pi_TCA9545.py
https://www.kickstarter.com/projects/sunair/really-useful-4-channel-i2c-multiplexer-with-grove?lang=zh
[SOLUTION? ](https://forum.dexterindustries.com/t/how-to-deal-with-two-conflicted-i2c-addresses/1496)
[Failure? ](https://forum.dexterindustries.com/t/i2c-address-changer/2355/2)
TCA9548A I2C Multiplexer
https://forums.adafruit.com/viewtopic.php?f=8&p=633907
[AM2315](https://github.com/kizniche/Mycodo/blob/master/mycodo/inputs/am2315.py)
https://forums.adafruit.com/viewtopic.php?f=19&t=83918&p=541562&hilit=TCA9548A#p541562
[source code](https://github.com/johnbryanmoore/VL53L0X_rasp_python)
[BUY](https://goods.ruten.com.tw/item/show?21643091531410)
[Adafruit_multiplexer](https://learn.adafruit.com/adafruit-tca9548a-1-to-8-i2c-multiplexer-breakout)
[test file ](https://bitbucket.org/kolon/my-pi-projects/src/8099b6b7391802973ad960680d7fc36def340caf/raspi-multiplex/multiplex.py?at=master)
```python=
from Adafruit_GPIO import I2C
tca = I2C.get_i2c_device(address=0x70)
def tca_select(channel):
"""Select an individual channel."""
if channel > 7:
return
tca.writeRaw8(1 << channel)
def tca_set(mask):
"""Select one or more channels.
chan = 76543210
mask = 0b00000000
"""
if mask > 0xff:
return
tca.writeRaw8(mask)
# Select channel 0
tca_select(0)
# you're now talking to OLED on channel 0
# Select channel 1
tca_select(1)
# you're now talking to OLED on channel 1
#
# etc
#
# Select channels 2 and 0
tca_set(0b0000101)
# you're now talking to OLED on channels 0 and 2 simultaneously
```
[ADAFruit_gpio](https://github.com/adafruit/Adafruit_Python_GPIO)
[setting the GPIO](https://raspi.tv/2013/how-to-use-interrupts-with-python-on-the-raspberry-pi-and-rpi-gpio-part-3)
[Digital pin sensor ](https://raspi.tv/2017/make-a-rain-alert-system-with-raspberry-pi)
[安裝程序](https://rmotex.blogspot.com/2018/02/raspberry-pi-3-grovepi.html)
[Grove Temperature](https://github.com/DexterInd/GrovePi/blob/master/Software/Python/grove_temperature_sensor.py)
```python=
#!/usr/bin/python
# Change channel of TCA9548A
# Example: sudo ./multiplexer_channel.py 0
import smbus
import time
import sys
I2C_address = 0x70
I2C_bus_number = 1
I2C_ch_0 = 0b00000001
I2C_ch_1 = 0b00000010
I2C_ch_2 = 0b00000100
I2C_ch_3 = 0b00001000
I2C_ch_4 = 0b00010000
I2C_ch_5 = 0b00100000
I2C_ch_6 = 0b01000000
I2C_ch_7 = 0b10000000
def I2C_setup(i2c_channel_setup):
bus = smbus.SMBus(I2C_bus_number)
bus.write_byte(I2C_address,i2c_channel_setup)
time.sleep(0.1)
print "TCA9548A I2C channel status:", bin(bus.read_byte(I2C_address))
I2C_setup(int(sys.argv[1]))
```
[Multiplexer data sheet ](https://cdn-shop.adafruit.com/datasheets/tca9548a.pdf)
[SMBUS I2C Write bytes data ](http://blog.ittraining.com.tw/2015/03/python-i2c-bus-on-raspberry-pi.html)
[one-wire Digital Temperature sensor_1](https://thepihut.com/blogs/raspberry-pi-tutorials/ds18b20-one-wire-digital-temperature-sensor-and-the-raspberry-pi)
[one-wire Digital Temperature sensor_2](https://www.mkompf.com/weather/pionewiremini.html)
[one wire Digital Temperature Sensor Trouble shooting](https://www.raspberrypi.org/forums/viewtopic.php?t=106041)
[trouble shooting](https://github.com/danjperron/BitBangingDS18B20/issues/5)
[Raspberry pi 3 setting the Temperature](https://www.electronicshub.org/raspberry-pi-ds18b20-tutorial/?amp)
## Temperature
```python=
import os
import time
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
temp_sensor = '/sys/bus/w1/devices/3b-0000001817de/w1_slave'
def temp_raw():
f = open(temp_sensor,'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
lines = temp_raw()
while lines[0].strip()[-3: ] != 'YES':
time.sleep(0.2)
lines = temp_raw()
temp_output = lines[1].find('t=')
if temp_output != -1:
temp_string = lines[1].strip()[temp_output+2:]
temp_c = float(temp_string)/1000.0
temp_f = temp_c * 9.0/5.0+32.0
return temp_c,temp_f
while True:
print(read_temp())
time.sleep(0.1)
```
[How to power and read multiple DS18B20 temperature sensors](https://www.raspberrypi.org/forums/viewtopic.php?t=204935)
[Multiple DS18B20 temperature sensors](https://lb.raspberrypi.org/forums/viewtopic.php?t=167896)
[W1-GPIO - One-Wire Interface](https://pinout.xyz/pinout/1_wire)
[documents](https://jumpnowtek.com/rpi/Using-DS18B20-1-wire-Temp-Sensors-with-the-Raspberry-Pi.html)
[ADXL345 Velocity](http://ijirae.com/volumes/Vol4/iss11/04.NVAE10086.pdf)
[積分 速度](https://www.itread01.com/content/1549331106.html)
[積分 速度_2](https://blog.csdn.net/liboxiu/article/details/79002088)
[list of dictionary_1 : ](https://www.programiz.com/python-programming/working-csv-files)
[list_of_dictionary_2 : ](https://bytes.com/topic/python/answers/781432-how-create-list-dictionaries)
[Mosquitto](http://www.steves-internet-guide.com/install-mosquitto-broker/)
[Mosquitto 安裝](http://rocksaying.tw/archives/2017/MQTT-4-Install-mosquitto-on-windows.html)
[Mosquitto_指令_1](http://guang.logdown.com/posts/235550-mqtt-mosquitto-teaching)
[Mosquitto_指令_2](http://www.steves-internet-guide.com/mosquitto_pub-sub-clients/)
[How to Install The Mosquitto MQTT Broker on Windows](http://www.steves-internet-guide.com/install-mosquitto-broker/)
mosquitto_sub -h 10.98.124.127 -p 1883 -t IOT_NEAT_TOPIC01
[儲存到MY_SQL](https://iotbytes.wordpress.com/store-mqtt-data-from-sensors-into-sql-database/)
[視覺化](https://oranwind.org/-data-visualization-python-chuan-jie-mosquitto-mqtt-broker-2/)
[git-hub: MY_SQL](https://github.com/pradeesi/Store_MQTT_Data_in_Database)
[SQLite3 教學](http://yhhuang1966.blogspot.com/2018/04/python-sqlite_28.html)
[如何使用PyMySQL操作mysql資料庫](https://www.pixpo.net/technology/0I3bD2FU.html)
[Python X MySql](https://ithelp.ithome.com.tw/articles/10207905)
[Python3資料庫操作包pymysql的操作方法](https://www.itread01.com/article/1531709043.html)
[MySQL 超新手入門](http://www.codedata.com.tw/database/mysql-tutorial-database-abc-mysql-installation)
[pymysql操作数据库-插入数据](https://blog.csdn.net/brucewong0516/article/details/79883100)