0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ADT7410から温度データを取得し、サーバーに送信する方法

Posted at

##環境
・ IoTデバイス : ESP-WROOM-32
・ ファームウエア : MicroPython1.13
・ 温度センサー : ADT7410
・ サーバー : Ubuntu 20.04 LTS

##ソースコード(ESP32)
・ ADT7410用ライブラリ

ADTLib.py
from machine import I2C, Pin
p21 = Pin(26, Pin.IN, Pin.PULL_UP)
p22 = Pin(27, Pin.IN, Pin.PULL_UP)

class ADT7410:
    def __init__(self):
        self.i2c = I2C(scl = Pin(27), sda = Pin(26), freq = 10000)

    def getTemperature(self):
        data = self.i2c.readfrom_mem(0x48, 0x00, 2)
        temp = (data[0] << 8 | data[1]) >> 3
        if(temp >= 4096):
            temp -= 8192
        value = temp * 0.0625
        return value

    def temperature(self):
        temp = self.getValue()
        return temp

・ ADT7410からデータを取得しサーバーに送信するプログラム

send.py
from machine import Pin, RTC
import network, urequests, utime
import ujson
import ADTLib
import usocket

#日付取得
def get_jst():
    rtc = RTC()
    url_jst = "http://worldtimeapi.org/api/timezone/Asia/Tokyo" # see http://worldtimeapi.org/timezones
    retry_delay = 5000 # interval time of retry after a failed Web query
    response = urequests.get(url_jst)
    # parse JSON
    parsed = response.json()
    #parsed=ujson.loads(res) # in case string
    datetime_str = str(parsed["datetime"])
    year = int(datetime_str[0:4])
    month = int(datetime_str[5:7])
    day = int(datetime_str[8:10])
    hour = int(datetime_str[11:13])
    minute = int(datetime_str[14:16])
    second = int(datetime_str[17:19])
    subsecond = int(round(int(datetime_str[20:26]) / 10000))
    # update internal RTC
    rtc.datetime((year, month, day, 0, hour, minute, second, subsecond))
    # setup day of the week
    daysOfTheWeek = "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
    tm = utime.localtime(utime.mktime(utime.localtime()))
    # generate formated date/time strings from internal RTC
    date_str = "{0:4d}/{1:02d}/{2:02d}".format(*rtc.datetime())
    time_str = "{4:02d}:{5:02d}:{6:02d}".format(*rtc.datetime())
    date_ok = date_str + " " + time_str
    return date_ok

HOST = 'IPアドレス'
PORT = 8080

date = get_jst()
#温度データ取得
adt = ADTLib.ADT7410()
temp = adt.getTemperature()

data = {"temp" : temp, "date" : date}

#ソケットの作成
sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
saddr = usocket.getaddrinfo(HOST, PORT)[0][-1]

#サーバーに接続
sock.connect(saddr)

#データ送信
sock.sendall(bytes(ujson.dumps(data), "utf-8"))

#終了
sock.close()

##ソースコード(サーバー)
・ データを受け取るプログラム

server.py
class MyTCPHandler(socketserver.BaseRequestHandler):

    def handle(self):
        self.data = self.request.recv(1024).strip()


        print("{} wrote:".format(self.client_address[0]))
        print(self.data)

if __name__ == "__main__":
    HOST, PORT = "IPアドレス", 8080

    with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
        server.serve_forever()

##実行結果
・ESP32側

{"date": "2021/07/15 23:27:37", "temp": 28.25}'

・ サーバー側

b'{"date": "2021/07/15 23:27:37", "temp": 28.25}'

##参考文献
[1]MicroPythonのTCP通信をパケットキャプチャする

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?