고원빈

Merge branch 'Hardware'

Showing 45 changed files with 1591 additions and 0 deletions
1 +# 스마트 약병 IoT 하드웨어 및 연결단 개발
2 +
3 +## 지도교수
4 ++ 유인태 교수님
5 +
6 +## 개발담당자
7 ++ 2015100552 컴퓨터공학과 윤형선
8 +
9 +## 일정
10 ++ 2021.05.03: Init(개인 아두이노 코드 git에서 이전)
11 ++ 2021.05.11: Arduino 개발 중단, RaspberryPi Pico로 플랫폼 이전, C++ -> MicroPython
12 ++ 2021.05.12: RaspberryPi Pico v0.1 code complete. Now working on rpi4 with MQTT.
13 ++ 2021.05.13: RaspberryPi4 v0.1 code complete. with MQTT. + Pico code bug fix.
14 ++ 2021.05.13: Fritzing design add.
15 ++ 2021.05.16: RPI4 Code update
16 ++ 2021.05.22: 3D Modeling file add.(Ender3 Pro)
17 ++ 2021.05.25: 3D Printer gcode file updated.(Ender3 Pro+PLA)
...\ No newline at end of file ...\ No newline at end of file
No preview for this file type
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
1 +# RaspberryPi4용 코드
2 +
3 +- rpi.py
4 +```
5 +라즈베리파이 메인코드
6 +```
7 +- serverside_mqtt_stest.py
8 +```
9 +server에서 데이터 보낼 예제
10 +```
11 +- serverside_mqtt_rtest.py
12 +```
13 +server에서 수신한 데이터
14 +```
15 +python rpi.py동작 후, test코드 활용해서 테스트 가능
1 +paho-mqtt
...\ No newline at end of file ...\ No newline at end of file
1 +import paho.mqtt.client as mqtt
2 +import paho.mqtt.publish as publish
3 +
4 +from bluetooth import *
5 +import time
6 +
7 +MQTT_BLOCK = False
8 +
9 +BT_MAC_ADDRESS = '00:18:91:D8:24:39'
10 +MED_BOTT_NO = '1'
11 +
12 +client_socket = BluetoothSocket( RFCOMM )
13 +client_mqtt = mqtt.Client()
14 +
15 +# --------------------------------------------------- #
16 +# INTERNAL FUNCTIONS
17 +# --------------------------------------------------- #
18 +def _send_data(msg:str):
19 + ''' Bluetooth를 통해 데이터를 송신한다
20 + '''
21 + client_socket.send(msg)
22 +
23 +def _recv_data():
24 + ''' Bluetooth를 통해 데이터를 수신한다
25 + '''
26 + # 소켓에 2초간 받을 수 있는 시간을 준다
27 + client_socket.settimeout(2)
28 +
29 + # 데이터 받을 변수
30 + data = ''
31 +
32 + try:
33 + timeout_start = time.time()
34 + timeout = 2
35 + while time.time() < timeout_start + timeout:
36 + data += client_socket.recv(1024).decode('utf-8')
37 + except:
38 + print('INFO: DATA RECV TIMEOUT')
39 + finally:
40 + return data
41 +
42 +
43 +def _sub_mqtt(client, userdata, flags, rc):
44 + ''' MQTT에서 subscribe한다
45 + '''
46 + print("Connected with result code "+str(rc))
47 + client.subscribe(f'bottle/1/stb')
48 +
49 +def _work_mqtt(client, userdata, msg):
50 + ''' MQTT에서 데이터를 받으면 알맞게 로직을 수행한다
51 + '''
52 + print('DOING SOMETHING')
53 + global MQTT_BLOCK
54 + MQTT_BLOCK = True
55 +
56 + received_msg = msg.payload.decode('utf-8')
57 +
58 + data = ''
59 + data_list = []
60 +
61 + # 만약 req메시지를 받았다면
62 + if received_msg == 'req':
63 + # 데이터가 손실되어 왔을 경우 에러 처리
64 + if len(data_list[0]) == 0:
65 + data_list = []
66 + elif len(data_list[3]) == 0:
67 + data_list = []
68 + while len(data_list) != 4:
69 + _send_data('REQ')
70 + data = _recv_data()
71 + data_list = data.split('/')
72 + # 데이터가 손실되어 왔을 경우 에러 처리
73 + if len(data_list[0]) == 0:
74 + data_list = []
75 + elif len(data_list[3]) == 0:
76 + data_list = []
77 + # 데이터를 Publish한다
78 + _pub_mqtt(f'bottle/{MED_BOTT_NO}/bts', data, 'localhost')
79 +
80 + # 만약 res메시지를 받았다면
81 + elif received_msg.split('/')[0] == 'res':
82 + _send_data(received_msg.split('/')[1])
83 + data = _recv_data()
84 + data_list = data.split('/')
85 + # 데이터가 손실되어 왔을 경우 에러 처리
86 + if len(data_list[0]) == 0:
87 + data_list = []
88 + elif len(data_list[3]) == 0:
89 + data_list = []
90 +
91 + while len(data_list) != 4:
92 + _send_data('REQ')
93 + data = _recv_data()
94 + data_list = data.split('/')
95 + # 데이터가 손실되어 왔을 경우 에러 처리
96 + if len(data_list[0]) == 0:
97 + data_list = []
98 + elif len(data_list[3]) == 0:
99 + data_list = []
100 + # 데이터를 Publish한다
101 + # _pub_mqtt(f'bottle/{MED_BOTT_NO}/bts', data, 'localhost')
102 +
103 + print("DEBUG")
104 + print(data)
105 + print(data_list)
106 + print(received_msg)
107 + MQTT_BLOCK = False
108 +
109 +def _pub_mqtt(topic:str, payload:str, hostname:str):
110 + ''' MQTT를 통해 데이터를 publish한다
111 + '''
112 + publish.single(
113 + topic=topic,
114 + payload=payload,
115 + hostname=hostname)
116 +
117 +
118 +# --------------------------------------------------- #
119 +# MAIN
120 +# --------------------------------------------------- #
121 +def _run():
122 + # CONNECT BT
123 + client_socket.connect((BT_MAC_ADDRESS, 1))
124 + print('bluetooth connected!')
125 +
126 + # SUBSCRIBE MQTT
127 + client_mqtt.on_connect = _sub_mqtt
128 + client_mqtt.on_message = _work_mqtt
129 + client_mqtt.connect_async("localhost")
130 + client_mqtt.loop_start()
131 +
132 +
133 + while True:
134 + if MQTT_BLOCK is False:
135 + # 항상 데이터를 받을 상태로 있는다
136 + data = _recv_data()
137 +
138 + # 만약 데이터가 ''가 아니면 무언가 온 것이므로 처리한다
139 + if data != '':
140 + print('DATA IN')
141 + data_list = data.split('/')
142 +
143 + # 데이터가 손실되어 왔을 경우 에러 처리
144 + if len(data_list[0]) == 0:
145 + data_list = []
146 + elif len(data_list[3]) == 0:
147 + data_list = []
148 +
149 + # 만약 데이터가 불량하게 왔을 경우, 제대로 올때까지 반복시도한다
150 + while len(data_list) != 4:
151 + data = _recv_data()
152 + data_list = data.split('/')
153 + # 데이터가 손실되어 왔을 경우 에러 처리
154 + if len(data_list[0]) == 0:
155 + data_list = []
156 + elif len(data_list[3]) == 0:
157 + data_list = []
158 +
159 + # 데이터를 Publish한다
160 + _pub_mqtt(f'bottle/{MED_BOTT_NO}/bts', data, 'localhost')
161 +
162 + client_socket.close()
163 +
164 +if __name__ == '__main__':
165 + _run()
...\ No newline at end of file ...\ No newline at end of file
1 +import paho.mqtt.client as mqtt
2 +
3 +import time
4 +
5 +def on_connect(client, userdata, flags, rc):
6 + print("Connected with result code "+str(rc))
7 + client.subscribe("bottle/1/bts") # 요거 수정해서 확인하세요
8 +
9 +def on_message(client, userdata, msg):
10 + print(msg.topic)
11 + print(msg.payload.decode('utf-8'))
12 +
13 +client = mqtt.Client()
14 +client.on_connect = on_connect
15 +client.on_message = on_message
16 +
17 +client.connect_async("localhost")
18 +client.loop_start()
19 +
20 +while True:
21 + print("TESTing")
22 + time.sleep(1)
...\ No newline at end of file ...\ No newline at end of file
1 +import paho.mqtt.publish as publish
2 +
3 +# hub -> server
4 +# msgs = \
5 +# [
6 +# {
7 +# 'topic':"bottle/1/bts",
8 +# 'payload':"1/30.4/32.2/1"
9 +# }
10 +# ]
11 +
12 +# server -> hub with date
13 +# msgs = \
14 +# [
15 +# {
16 +# 'topic':"bottle/1/stb",
17 +# 'payload':"res/0513"
18 +# }
19 +# ]
20 +
21 +# server -> hub without date
22 +msgs = \
23 +[
24 + {
25 + 'topic':"bottle/1/stb",
26 + 'payload':"req"
27 + }
28 +]
29 +
30 +publish.multiple(msgs, hostname="localhost")
1 +"""
2 +MicroPython TM1637 quad 7-segment LED display driver
3 +https://github.com/mcauser/micropython-tm1637
4 +MIT License
5 +Copyright (c) 2016 Mike Causer
6 +Permission is hereby granted, free of charge, to any person obtaining a copy
7 +of this software and associated documentation files (the "Software"), to deal
8 +in the Software without restriction, including without limitation the rights
9 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 +copies of the Software, and to permit persons to whom the Software is
11 +furnished to do so, subject to the following conditions:
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 +SOFTWARE.
21 +"""
22 +
23 +from micropython import const
24 +from machine import Pin
25 +from time import sleep_us, sleep_ms
26 +
27 +TM1637_CMD1 = const(64) # 0x40 data command
28 +TM1637_CMD2 = const(192) # 0xC0 address command
29 +TM1637_CMD3 = const(128) # 0x80 display control command
30 +TM1637_DSP_ON = const(8) # 0x08 display on
31 +TM1637_DELAY = const(10) # 10us delay between clk/dio pulses
32 +TM1637_MSB = const(128) # msb is the decimal point or the colon depending on your display
33 +
34 +# 0-9, a-z, blank, dash, star
35 +_SEGMENTS = bytearray(b'\x3F\x06\x5B\x4F\x66\x6D\x7D\x07\x7F\x6F\x77\x7C\x39\x5E\x79\x71\x3D\x76\x06\x1E\x76\x38\x55\x54\x3F\x73\x67\x50\x6D\x78\x3E\x1C\x2A\x76\x6E\x5B\x00\x40\x63')
36 +
37 +class TM1637(object):
38 + """Library for quad 7-segment LED modules based on the TM1637 LED driver."""
39 + def __init__(self, clk, dio, brightness=7):
40 + self.clk = clk
41 + self.dio = dio
42 +
43 + if not 0 <= brightness <= 7:
44 + raise ValueError("Brightness out of range")
45 + self._brightness = brightness
46 +
47 + self.clk.init(Pin.OUT, value=0)
48 + self.dio.init(Pin.OUT, value=0)
49 + sleep_us(TM1637_DELAY)
50 +
51 + self._write_data_cmd()
52 + self._write_dsp_ctrl()
53 +
54 + def _start(self):
55 + self.dio(0)
56 + sleep_us(TM1637_DELAY)
57 + self.clk(0)
58 + sleep_us(TM1637_DELAY)
59 +
60 + def _stop(self):
61 + self.dio(0)
62 + sleep_us(TM1637_DELAY)
63 + self.clk(1)
64 + sleep_us(TM1637_DELAY)
65 + self.dio(1)
66 +
67 + def _write_data_cmd(self):
68 + # automatic address increment, normal mode
69 + self._start()
70 + self._write_byte(TM1637_CMD1)
71 + self._stop()
72 +
73 + def _write_dsp_ctrl(self):
74 + # display on, set brightness
75 + self._start()
76 + self._write_byte(TM1637_CMD3 | TM1637_DSP_ON | self._brightness)
77 + self._stop()
78 +
79 + def _write_byte(self, b):
80 + for i in range(8):
81 + self.dio((b >> i) & 1)
82 + sleep_us(TM1637_DELAY)
83 + self.clk(1)
84 + sleep_us(TM1637_DELAY)
85 + self.clk(0)
86 + sleep_us(TM1637_DELAY)
87 + self.clk(0)
88 + sleep_us(TM1637_DELAY)
89 + self.clk(1)
90 + sleep_us(TM1637_DELAY)
91 + self.clk(0)
92 + sleep_us(TM1637_DELAY)
93 +
94 + def brightness(self, val=None):
95 + """Set the display brightness 0-7."""
96 + # brightness 0 = 1/16th pulse width
97 + # brightness 7 = 14/16th pulse width
98 + if val is None:
99 + return self._brightness
100 + if not 0 <= val <= 7:
101 + raise ValueError("Brightness out of range")
102 +
103 + self._brightness = val
104 + self._write_data_cmd()
105 + self._write_dsp_ctrl()
106 +
107 + def write(self, segments, pos=0):
108 + """Display up to 6 segments moving right from a given position.
109 + The MSB in the 2nd segment controls the colon between the 2nd
110 + and 3rd segments."""
111 + if not 0 <= pos <= 5:
112 + raise ValueError("Position out of range")
113 + self._write_data_cmd()
114 + self._start()
115 +
116 + self._write_byte(TM1637_CMD2 | pos)
117 + for seg in segments:
118 + self._write_byte(seg)
119 + self._stop()
120 + self._write_dsp_ctrl()
121 +
122 + def encode_digit(self, digit):
123 + """Convert a character 0-9, a-f to a segment."""
124 + return _SEGMENTS[digit & 0x0f]
125 +
126 + def encode_string(self, string):
127 + """Convert an up to 4 character length string containing 0-9, a-z,
128 + space, dash, star to an array of segments, matching the length of the
129 + source string."""
130 + segments = bytearray(len(string))
131 + for i in range(len(string)):
132 + segments[i] = self.encode_char(string[i])
133 + return segments
134 +
135 + def encode_char(self, char):
136 + """Convert a character 0-9, a-z, space, dash or star to a segment."""
137 + o = ord(char)
138 + if o == 32:
139 + return _SEGMENTS[36] # space
140 + if o == 42:
141 + return _SEGMENTS[38] # star/degrees
142 + if o == 45:
143 + return _SEGMENTS[37] # dash
144 + if o >= 65 and o <= 90:
145 + return _SEGMENTS[o-55] # uppercase A-Z
146 + if o >= 97 and o <= 122:
147 + return _SEGMENTS[o-87] # lowercase a-z
148 + if o >= 48 and o <= 57:
149 + return _SEGMENTS[o-48] # 0-9
150 + raise ValueError("Character out of range: {:d} '{:s}'".format(o, chr(o)))
151 +
152 + def hex(self, val):
153 + """Display a hex value 0x0000 through 0xffff, right aligned."""
154 + string = '{:04x}'.format(val & 0xffff)
155 + self.write(self.encode_string(string))
156 +
157 + def number(self, num):
158 + """Display a numeric value -999 through 9999, right aligned."""
159 + # limit to range -999 to 9999
160 + num = max(-999, min(num, 9999))
161 + string = '{0: >4d}'.format(num)
162 + self.write(self.encode_string(string))
163 +
164 + def numbers(self, num1, num2, colon=True):
165 + """Display two numeric values -9 through 99, with leading zeros
166 + and separated by a colon."""
167 + num1 = max(-9, min(num1, 99))
168 + num2 = max(-9, min(num2, 99))
169 + segments = self.encode_string('{0:0>2d}{1:0>2d}'.format(num1, num2))
170 + if colon:
171 + segments[1] |= 0x80 # colon on
172 + self.write(segments)
173 +
174 + def temperature(self, num):
175 + if num < -9:
176 + self.show('lo') # low
177 + elif num > 99:
178 + self.show('hi') # high
179 + else:
180 + string = '{0: >2d}'.format(num)
181 + self.write(self.encode_string(string))
182 + self.write([_SEGMENTS[38], _SEGMENTS[12]], 2) # degrees C
183 +
184 + def show(self, string, colon=False):
185 + segments = self.encode_string(string)
186 + if len(segments) > 1 and colon:
187 + segments[1] |= 128
188 + self.write(segments[:4])
189 +
190 + def scroll(self, string, delay=250):
191 + segments = string if isinstance(string, list) else self.encode_string(string)
192 + data = [0] * 8
193 + data[4:0] = list(segments)
194 + for i in range(len(segments) + 5):
195 + self.write(data[0+i:4+i])
196 + sleep_ms(delay)
197 +
198 +
199 +class TM1637Decimal(TM1637):
200 + """Library for quad 7-segment LED modules based on the TM1637 LED driver.
201 + This class is meant to be used with decimal display modules (modules
202 + that have a decimal point after each 7-segment LED).
203 + """
204 +
205 + def encode_string(self, string):
206 + """Convert a string to LED segments.
207 + Convert an up to 4 character length string containing 0-9, a-z,
208 + space, dash, star and '.' to an array of segments, matching the length of
209 + the source string."""
210 + segments = bytearray(len(string.replace('.','')))
211 + j = 0
212 + for i in range(len(string)):
213 + if string[i] == '.' and j > 0:
214 + segments[j-1] |= TM1637_MSB
215 + continue
216 + segments[j] = self.encode_char(string[i])
217 + j += 1
218 + return segments
1 +import uos
2 +import machine
3 +import utime
4 +
5 +uart0 = machine.UART(0,baudrate=9600)
6 +
7 +# --------------------------------------------------- #
8 +# INTERNAL FUNCTIONS
9 +# --------------------------------------------------- #
10 +def _clartBuf(uart=uart0):
11 + ''' Clear Buffer
12 + '''
13 + while uart.any():
14 + print(uart.read(1))
15 +
16 +# --------------------------------------------------- #
17 +# FUNCTIONS
18 +# --------------------------------------------------- #
19 +def send_data_bt(sdata:str):
20 + ''' Send string data using Bluetooth
21 + '''
22 + _clartBuf()
23 + uart0.write(sdata)
24 +
25 +
26 +def recv_data_bt():
27 + ''' Receive string data using Bluetooth
28 + '''
29 + _clartBuf()
30 + prvMills = utime.ticks_ms()
31 + received_data = ''
32 +
33 + while (utime.ticks_ms()-prvMills)<2000:
34 + if uart0.any():
35 + single_data = uart0.read(1)
36 + received_data += single_data.decode('utf-8')
37 +
38 + return received_data
...\ No newline at end of file ...\ No newline at end of file
1 +''' Original code from https://www.raspberrypi.org/forums/viewtopic.php?t=303606
2 +'''
3 +import utime
4 +import rp2
5 +from rp2 import PIO, asm_pio
6 +from machine import Pin
7 +
8 +# --------------------------------------------------- #
9 +# INIT
10 +# --------------------------------------------------- #
11 +# For VCC
12 +dht_pwr = Pin(14, Pin.OUT)
13 +# For data
14 +dht_data = Pin(15, Pin.IN, Pin.PULL_UP)
15 +
16 +# Power on
17 +dht_pwr.value(1)
18 +# Create empty state
19 +sm=rp2.StateMachine(1)
20 +# Wait for DHT22 to start up
21 +utime.sleep(2)
22 +
23 +# --------------------------------------------------- #
24 +# INIT2
25 +# --------------------------------------------------- #
26 +@asm_pio(set_init=(PIO.OUT_HIGH),autopush=True, push_thresh=8) #output one byte at a time
27 +def DHT22():
28 + #drive output low for at least 20ms
29 + set(pindirs,1) #set pin to output
30 + set(pins,0) #set pin low
31 + set(y,31) #prepare countdown, y*x*100cycles
32 + label ('waity')
33 + set(x,31)
34 + label ('waitx')
35 + nop() [30]
36 + jmp(x_dec,'waitx') #decrement x reg every 100 cycles
37 + jmp(y_dec,'waity') #decrement y reg every time x reaches zero
38 +
39 + #begin reading from device
40 + set(pindirs,0) #set pin to input
41 + wait(1,pin,0) #check pin is high before starting
42 + wait(0,pin,0)
43 + wait(1,pin,0)
44 + wait(0,pin,0) #wait for start of data
45 +
46 + #read databit
47 + label('readdata')
48 + set(x,21) #reset x register to count down from 20
49 + wait(1,pin,0) #wait for high signal
50 + label('countdown')
51 + jmp(pin,'continue') #if pin still high continue counting
52 + #pin is low before countdown is complete - bit '0' detected
53 + set(y,0)
54 + in_(y, 1) #shift '0' into the isr
55 + jmp('readdata') #read the next bit
56 +
57 + label('continue')
58 + jmp(x_dec,'countdown') #decrement x reg and continue counting if x!=0
59 + #pin is still high after countdown complete - bit '1' detected
60 + set(y,1)
61 + in_(y, 1) #shift one bit into the isr
62 + wait(0,pin,0) #wait for low signal (next bit)
63 + jmp('readdata') #read the next bit
64 +
65 +
66 +# --------------------------------------------------- #
67 +# FUNCTIONS
68 +# --------------------------------------------------- #
69 +def work_dht():
70 + data=[]
71 + total=0
72 + sm.init(DHT22,freq=1600000,set_base=dht_data,in_base=dht_data,jmp_pin=dht_data)
73 + sm.active(1)
74 + for i in range(5): #data should be 40 bits (5 bytes) long
75 + data.append(sm.get()) #read byte
76 +
77 + #check checksum (lowest 8 bits of the sum of the first 4 bytes)
78 + for i in range(4):
79 + total=total+data[i]
80 + if((total & 255) == data[4]):
81 + humidity=((data[0]<<8) + data[1])/10.0
82 + temperature=(((data[2] &0x7f) << 8) + data[3]) /10.0
83 + if (data[2] & 0x80) == 0x80:
84 + temperature = -temperature
85 + return [humidity, temperature]
86 + else:
87 + return False
...\ No newline at end of file ...\ No newline at end of file
1 +import tm1637
2 +from machine import Pin
3 +from utime import sleep
4 +display4 = tm1637.TM1637(clk=Pin(12), dio=Pin(13))
5 +
6 +# --------------------------------------------------- #
7 +# FUNCTIONS
8 +# --------------------------------------------------- #
9 +def work_tm1637(data:str):
10 + display4.show(data)
11 +
12 +def off_tm1637():
13 + display4.show(' ')
14 +
15 +# # Show a word
16 +# mydisplay.show("Pico")
17 +# sleep(1)
18 +
19 +# #blank the screen
20 +# mydisplay.show(" ")
21 +# sleep(1)
22 +
23 +# #show numbers
24 +# mydisplay.number(-123)
25 +# sleep(1)
26 +
27 +# #show a time with colon
28 +# mydisplay.numbers(12,59)
29 +# sleep(1)
30 +
31 +# #adjust the brightness to make it lower
32 +# mydisplay.brightness(0)
33 +# sleep(1)
34 +
35 +# #show scrolling text
36 +# mydisplay.scroll("Hello World 123", delay=200)
37 +# sleep(1)
38 +
39 +# #show temperature
40 +# mydisplay.temperature(99)
41 +# sleep(1)
42 +
43 +# #blank the screen again
44 +# mydisplay.show(" ")
...\ No newline at end of file ...\ No newline at end of file
1 +import array, utime
2 +from machine import Pin
3 +import rp2
4 +
5 +import neopixel
6 +import dht
7 +import bluetoooth as bto
8 +import ultrasonic
9 +import reed
10 +import display4
11 +
12 +# --------------------------------------------------- #
13 +# FUNCTIONS
14 +# --------------------------------------------------- #
15 +def _collect_sensor_datas(reed_data:int) -> str:
16 + # Collect Humidity, Temperature
17 + dht_data = dht.work_dht()
18 + if dht_data == False:
19 + dht_data = [0,0]
20 + # Collect Ultrasonic distance
21 + ultrasonic_data = ultrasonic.work_sr04()
22 + # Make data string
23 + send_data_str = str(reed_data) + '/' + str(dht_data[1]) + '/' + str(dht_data[0]) + '/' + str(ultrasonic_data)
24 +
25 + return send_data_str
26 +
27 +# --------------------------------------------------- #
28 +# LOOP ENTRYPOINT
29 +# --------------------------------------------------- #
30 +def _run():
31 + # INIT REED STATE
32 + reed_data = -1
33 + # LOOP
34 + while True:
35 + # ------------------------------------------- #
36 + # DEFAULT LOOP
37 + # ------------------------------------------- #
38 + # Get data using BT(Standby)
39 + input_data = bto.recv_data_bt()
40 +
41 + # Get reed data from reed sensor
42 + current_reed_data = reed.work_reed()
43 +
44 + # ------------------------------------------- #
45 + # IF CONDITION MET
46 + # ------------------------------------------- #
47 + if input_data != '' or reed_data != current_reed_data:
48 + # Refine BT data
49 + input_data = input_data.strip()
50 + # Test code
51 + print('INPUT FOUND ', input_data)
52 +
53 + # IF INPUT MEANS GET MESSAGE or MEDICINE LID STATUS CHANGED
54 + if input_data == 'REQ' or reed_data != current_reed_data:
55 + # Send data using BT
56 + bto.send_data_bt(_collect_sensor_datas(current_reed_data))
57 + else:
58 + # Refine BT data
59 + input_data = input_data.strip()
60 + display4.work_tm1637(input_data)
61 + neopixel.work_led()
62 + display4.off_tm1637()
63 + # Send data using BT
64 + bto.send_data_bt(_collect_sensor_datas(current_reed_data))
65 +
66 + # Update reed state
67 + reed_data = current_reed_data
68 +
69 +
70 +
71 +if __name__ == '__main__':
72 + _run()
...\ No newline at end of file ...\ No newline at end of file
1 +''' Original code from https://core-electronics.com.au/tutorials/how-to-use-ws2812b-rgb-leds-with-raspberry-pi-pico.html
2 +'''
3 +import array, utime
4 +from machine import Pin
5 +import rp2
6 +
7 +# --------------------------------------------------- #
8 +# INIT
9 +# --------------------------------------------------- #
10 +NUM_LEDS = 8
11 +PIN_NUM = 22
12 +
13 +BLACK = (0, 0, 0)
14 +RED = (255, 0, 0)
15 +YELLOW = (255, 150, 0)
16 +GREEN = (0, 255, 0)
17 +CYAN = (0, 255, 255)
18 +BLUE = (0, 0, 255)
19 +PURPLE = (180, 0, 255)
20 +WHITE = (255, 255, 255)
21 +COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE, BLACK)
22 +
23 +# --------------------------------------------------- #
24 +# INIT2
25 +# --------------------------------------------------- #
26 +@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24)
27 +def ws2812():
28 + T1 = 2
29 + T2 = 5
30 + T3 = 3
31 + wrap_target()
32 + label("bitloop")
33 + out(x, 1) .side(0) [T3 - 1]
34 + jmp(not_x, "do_zero") .side(1) [T1 - 1]
35 + jmp("bitloop") .side(1) [T2 - 1]
36 + label("do_zero")
37 + nop() .side(0) [T2 - 1]
38 + wrap()
39 +
40 +# Create the StateMachine with the ws2812 program, outputting on pin
41 +sm = rp2.StateMachine(0, ws2812, freq=8_000_000, sideset_base=Pin(PIN_NUM))
42 +# Start the StateMachine, it will wait for data on its FIFO.
43 +sm.active(1)
44 +# Display a pattern on the LEDs via an array of LED RGB values.
45 +ar = array.array("I", [0 for _ in range(NUM_LEDS)])
46 +
47 +# --------------------------------------------------- #
48 +# INTERNAL FUNCTIONS
49 +# --------------------------------------------------- #
50 +def _pixels_show(brightness:int = 0.2):
51 + dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)])
52 + for i,c in enumerate(ar):
53 + r = int(((c >> 8) & 0xFF) * brightness)
54 + g = int(((c >> 16) & 0xFF) * brightness)
55 + b = int((c & 0xFF) * brightness)
56 + dimmer_ar[i] = (g<<16) + (r<<8) + b
57 + sm.put(dimmer_ar, 8)
58 + utime.sleep_ms(10)
59 +
60 +def _pixels_set(i, color):
61 + ar[i] = (color[1]<<16) + (color[0]<<8) + color[2]
62 +
63 +def _pixels_fill(color):
64 + for i in range(len(ar)):
65 + _pixels_set(i, color)
66 +
67 +
68 +# --------------------------------------------------- #
69 +# FUNCTIONS
70 +# --------------------------------------------------- #
71 +def work_led(brightness:int = 0.2):
72 + for color in COLORS:
73 + _pixels_fill(color)
74 + _pixels_show(brightness)
75 + utime.sleep(0.4)
1 +from machine import Pin, Signal
2 +
3 +data_pin = Pin(16, Pin.IN)
4 +
5 +# --------------------------------------------------- #
6 +# FUNCTIONS
7 +# --------------------------------------------------- #
8 +def work_reed() -> int:
9 + # 1 = Lid opened, 0 = Lid closed
10 + return data_pin.value()
1 +''' Original code from https://www.iottrends.tech/blog/how-to-use-ultrasonic-sensor-with-raspberry-pi-pico/
2 +'''
3 +from machine import Pin
4 +import utime
5 +trigger = Pin(26, Pin.OUT)
6 +echo = Pin(27, Pin.IN)
7 +
8 +# --------------------------------------------------- #
9 +# FUNCTIONS
10 +# --------------------------------------------------- #
11 +def work_sr04():
12 + trigger.low()
13 + utime.sleep_us(2)
14 + trigger.high()
15 + utime.sleep_us(5)
16 + trigger.low()
17 + while echo.value() == 0:
18 + signaloff = utime.ticks_us()
19 + while echo.value() == 1:
20 + signalon = utime.ticks_us()
21 + timepassed = signalon - signaloff
22 + distance = (timepassed * 0.0330) / 2
23 +
24 + return distance
1 +import uos
2 +import machine
3 +import utime
4 +
5 +uart0 = machine.UART(0,baudrate=9600)
6 +
7 +def _clartBuf(uart=uart0):
8 + print("Clear UART buffer "+ str(uart))
9 + while uart.any():
10 + print(uart.read(1))
11 +
12 +
13 +def send_data_bt(sdata:str):
14 + _clartBuf()
15 + uart0.write(sdata)
16 +
17 +
18 +def recv_data_bt():
19 + _clartBuf()
20 + prvMills = utime.ticks_ms()
21 + received_data = ''
22 +
23 + while (utime.ticks_ms()-prvMills)<2000:
24 + if uart0.any():
25 + single_data = uart0.read(1)
26 + received_data += single_data.decode('utf-8')
27 +
28 + return received_data
1 +import utime
2 +import rp2
3 +from rp2 import PIO, asm_pio
4 +from machine import Pin
5 +
6 +dht_pwr = Pin(14, Pin.OUT) #connect GPIO 14 to '+' on DHT11
7 +dht_data = Pin(15, Pin.IN, Pin.PULL_UP) #connect GPIO 15 to 'out' on DHT11
8 +
9 +dht_pwr.value(1) #power on DHT11
10 +sm=rp2.StateMachine(1) #create empty state machine
11 +utime.sleep(2) #wait for DHT11 to start up
12 +
13 +@asm_pio(set_init=(PIO.OUT_HIGH),autopush=True, push_thresh=8) #output one byte at a time
14 +def DHT22():
15 + #drive output low for at least 20ms
16 + set(pindirs,1) #set pin to output
17 + set(pins,0) #set pin low
18 + set(y,31) #prepare countdown, y*x*100cycles
19 + label ('waity')
20 + set(x,31)
21 + label ('waitx')
22 + nop() [30]
23 + jmp(x_dec,'waitx') #decrement x reg every 100 cycles
24 + jmp(y_dec,'waity') #decrement y reg every time x reaches zero
25 +
26 + #begin reading from device
27 + set(pindirs,0) #set pin to input
28 + wait(1,pin,0) #check pin is high before starting
29 + wait(0,pin,0)
30 + wait(1,pin,0)
31 + wait(0,pin,0) #wait for start of data
32 +
33 + #read databit
34 + label('readdata')
35 + set(x,21) #reset x register to count down from 20
36 + wait(1,pin,0) #wait for high signal
37 + label('countdown')
38 + jmp(pin,'continue') #if pin still high continue counting
39 + #pin is low before countdown is complete - bit '0' detected
40 + set(y,0)
41 + in_(y, 1) #shift '0' into the isr
42 + jmp('readdata') #read the next bit
43 +
44 + label('continue')
45 + jmp(x_dec,'countdown') #decrement x reg and continue counting if x!=0
46 + #pin is still high after countdown complete - bit '1' detected
47 + set(y,1)
48 + in_(y, 1) #shift one bit into the isr
49 + wait(0,pin,0) #wait for low signal (next bit)
50 + jmp('readdata') #read the next bit
51 +
52 +
53 +# --------------------------------------------------- #
54 +# ENTRYPOINT
55 +# --------------------------------------------------- #
56 +def work_dht():
57 + print("DHT22 WORKING")
58 + data=[]
59 + total=0
60 + sm.init(DHT22,freq=1600000,set_base=dht_data,in_base=dht_data,jmp_pin=dht_data) #start state machine
61 + #state machine frequency adjusted so that PIO countdown during 'readdata' ends somewhere between the
62 + #duration of a '0' and a '1' high signal
63 + sm.active(1)
64 + for i in range(5): #data should be 40 bits (5 bytes) long
65 + data.append(sm.get()) #read byte
66 +
67 + print("data: " + str(data))
68 +
69 + #check checksum (lowest 8 bits of the sum of the first 4 bytes)
70 + for i in range(4):
71 + total=total+data[i]
72 + if((total & 255) == data[4]):
73 + humidity=((data[0]<<8) + data[1])/10.0 #DHT11 provides integer humidity (no decimal part)
74 + temperature=(((data[2] &0x7f) << 8) + data[3]) /10.0 #DHT11 provides signed integer temperature (no decimal part)
75 + if (data[2] & 0x80) == 0x80:
76 + temperature = -temperature
77 + return [humidity, temperature]
78 + else:
79 + return False
1 +import tm1637
2 +from machine import Pin
3 +from utime import sleep
4 +display4 = tm1637.TM1637(clk=Pin(12), dio=Pin(13))
5 +
6 +# --------------------------------------------------- #
7 +# FUNCTIONS
8 +# --------------------------------------------------- #
9 +def work_tm1637(data:str):
10 + display4.show(data)
11 +
12 +def off_tm1637():
13 + display4.show(' ')
1 +import array, utime
2 +from machine import Pin
3 +import rp2
4 +
5 +import neopixel
6 +import dht
7 +import bluetoooth as bto
8 +import ultrasonic
9 +import reed
10 +import display4
11 +
12 +# --------------------------------------------------- #
13 +# FUNCTIONS
14 +# --------------------------------------------------- #
15 +def _collect_sensor_datas(reed_data:int) -> str:
16 + # Collect Humidity, Temperature
17 + dht_data = dht.work_dht()
18 + if dht_data == False:
19 + dht_data = [0,0]
20 + # Collect Ultrasonic distance
21 + ultrasonic_data = ultrasonic.work_sr04()
22 + # Make data string
23 + send_data_str = str(reed_data) + '/' + str(dht_data[1]) + '/' + str(dht_data[0]) + '/' + str(ultrasonic_data)
24 +
25 + return send_data_str
26 +
27 +# --------------------------------------------------- #
28 +# LOOP ENTRYPOINT
29 +# --------------------------------------------------- #
30 +def _run():
31 + # INIT REED STATE
32 + reed_data = -1
33 + display4.off_tm1637()
34 + # LOOP
35 + while True:
36 + # ------------------------------------------- #
37 + # DEFAULT LOOP
38 + # ------------------------------------------- #
39 + # Get data using BT(Standby)
40 + input_data = bto.recv_data_bt()
41 +
42 + # Get reed data from reed sensor
43 + current_reed_data = reed.work_reed()
44 +
45 + # ------------------------------------------- #
46 + # IF CONDITION MET
47 + # ------------------------------------------- #
48 + if input_data != '' or reed_data != current_reed_data:
49 + # Refine BT data
50 + input_data = input_data.strip()
51 + # Test code
52 + print('INPUT FOUND ', input_data)
53 +
54 + # IF INPUT MEANS GET MESSAGE or MEDICINE LID STATUS CHANGED
55 + if input_data == 'REQ' or reed_data != current_reed_data:
56 + # Send data using BT
57 + bto.send_data_bt(_collect_sensor_datas(reed_data))
58 + else:
59 + # Refine BT data
60 + input_data = input_data.strip()
61 + display4.work_tm1637(input_data)
62 + neopixel.work_led()
63 + display4.off_tm1637()
64 + # Send data using BT
65 + bto.send_data_bt(_collect_sensor_datas(reed_data))
66 +
67 + # Update reed state
68 + reed_data = current_reed_data
69 +
70 +
71 +
72 +if __name__ == '__main__':
73 + _run()
1 +import array, utime
2 +from machine import Pin
3 +import rp2
4 +
5 +NUM_LEDS = 8
6 +PIN_NUM = 22
7 +
8 +BLACK = (0, 0, 0)
9 +RED = (255, 0, 0)
10 +YELLOW = (255, 150, 0)
11 +GREEN = (0, 255, 0)
12 +CYAN = (0, 255, 255)
13 +BLUE = (0, 0, 255)
14 +PURPLE = (180, 0, 255)
15 +WHITE = (255, 255, 255)
16 +COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE, BLACK)
17 +
18 +@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24)
19 +def ws2812():
20 + T1 = 2
21 + T2 = 5
22 + T3 = 3
23 + wrap_target()
24 + label("bitloop")
25 + out(x, 1) .side(0) [T3 - 1]
26 + jmp(not_x, "do_zero") .side(1) [T1 - 1]
27 + jmp("bitloop") .side(1) [T2 - 1]
28 + label("do_zero")
29 + nop() .side(0) [T2 - 1]
30 + wrap()
31 +
32 +# Create the StateMachine with the ws2812 program, outputting on pin
33 +sm = rp2.StateMachine(0, ws2812, freq=8_000_000, sideset_base=Pin(PIN_NUM))
34 +# Start the StateMachine, it will wait for data on its FIFO.
35 +sm.active(1)
36 +# Display a pattern on the LEDs via an array of LED RGB values.
37 +ar = array.array("I", [0 for _ in range(NUM_LEDS)])
38 +
39 +# --------------------------------------------------- #
40 +# FUNCTIONS
41 +# --------------------------------------------------- #
42 +def _pixels_show(brightness:int = 0.2):
43 + dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)])
44 + for i,c in enumerate(ar):
45 + r = int(((c >> 8) & 0xFF) * brightness)
46 + g = int(((c >> 16) & 0xFF) * brightness)
47 + b = int((c & 0xFF) * brightness)
48 + dimmer_ar[i] = (g<<16) + (r<<8) + b
49 + sm.put(dimmer_ar, 8)
50 + utime.sleep_ms(10)
51 +
52 +def _pixels_set(i, color):
53 + ar[i] = (color[1]<<16) + (color[0]<<8) + color[2]
54 +
55 +def _pixels_fill(color):
56 + for i in range(len(ar)):
57 + _pixels_set(i, color)
58 +
59 +
60 +# --------------------------------------------------- #
61 +# ENTRYPOINT
62 +# --------------------------------------------------- #
63 +def work_led(brightness:int = 0.2):
64 + print("WS2812B WORKING")
65 + for color in COLORS:
66 + _pixels_fill(color)
67 + _pixels_show(brightness)
68 + utime.sleep(0.4)
69 +
1 +from machine import Pin, Signal
2 +
3 +data_pin = Pin(16, Pin.IN)
4 +
5 +# --------------------------------------------------- #
6 +# FUNCTIONS
7 +# --------------------------------------------------- #
8 +def work_reed() -> int:
9 + # 1 = Lid opened, 0 = Lid closed
10 + return data_pin.value()
11 +
1 +"""
2 +MicroPython TM1637 quad 7-segment LED display driver
3 +https://github.com/mcauser/micropython-tm1637
4 +MIT License
5 +Copyright (c) 2016 Mike Causer
6 +Permission is hereby granted, free of charge, to any person obtaining a copy
7 +of this software and associated documentation files (the "Software"), to deal
8 +in the Software without restriction, including without limitation the rights
9 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 +copies of the Software, and to permit persons to whom the Software is
11 +furnished to do so, subject to the following conditions:
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 +SOFTWARE.
21 +"""
22 +
23 +from micropython import const
24 +from machine import Pin
25 +from time import sleep_us, sleep_ms
26 +
27 +TM1637_CMD1 = const(64) # 0x40 data command
28 +TM1637_CMD2 = const(192) # 0xC0 address command
29 +TM1637_CMD3 = const(128) # 0x80 display control command
30 +TM1637_DSP_ON = const(8) # 0x08 display on
31 +TM1637_DELAY = const(10) # 10us delay between clk/dio pulses
32 +TM1637_MSB = const(128) # msb is the decimal point or the colon depending on your display
33 +
34 +# 0-9, a-z, blank, dash, star
35 +_SEGMENTS = bytearray(b'\x3F\x06\x5B\x4F\x66\x6D\x7D\x07\x7F\x6F\x77\x7C\x39\x5E\x79\x71\x3D\x76\x06\x1E\x76\x38\x55\x54\x3F\x73\x67\x50\x6D\x78\x3E\x1C\x2A\x76\x6E\x5B\x00\x40\x63')
36 +
37 +class TM1637(object):
38 + """Library for quad 7-segment LED modules based on the TM1637 LED driver."""
39 + def __init__(self, clk, dio, brightness=7):
40 + self.clk = clk
41 + self.dio = dio
42 +
43 + if not 0 <= brightness <= 7:
44 + raise ValueError("Brightness out of range")
45 + self._brightness = brightness
46 +
47 + self.clk.init(Pin.OUT, value=0)
48 + self.dio.init(Pin.OUT, value=0)
49 + sleep_us(TM1637_DELAY)
50 +
51 + self._write_data_cmd()
52 + self._write_dsp_ctrl()
53 +
54 + def _start(self):
55 + self.dio(0)
56 + sleep_us(TM1637_DELAY)
57 + self.clk(0)
58 + sleep_us(TM1637_DELAY)
59 +
60 + def _stop(self):
61 + self.dio(0)
62 + sleep_us(TM1637_DELAY)
63 + self.clk(1)
64 + sleep_us(TM1637_DELAY)
65 + self.dio(1)
66 +
67 + def _write_data_cmd(self):
68 + # automatic address increment, normal mode
69 + self._start()
70 + self._write_byte(TM1637_CMD1)
71 + self._stop()
72 +
73 + def _write_dsp_ctrl(self):
74 + # display on, set brightness
75 + self._start()
76 + self._write_byte(TM1637_CMD3 | TM1637_DSP_ON | self._brightness)
77 + self._stop()
78 +
79 + def _write_byte(self, b):
80 + for i in range(8):
81 + self.dio((b >> i) & 1)
82 + sleep_us(TM1637_DELAY)
83 + self.clk(1)
84 + sleep_us(TM1637_DELAY)
85 + self.clk(0)
86 + sleep_us(TM1637_DELAY)
87 + self.clk(0)
88 + sleep_us(TM1637_DELAY)
89 + self.clk(1)
90 + sleep_us(TM1637_DELAY)
91 + self.clk(0)
92 + sleep_us(TM1637_DELAY)
93 +
94 + def brightness(self, val=None):
95 + """Set the display brightness 0-7."""
96 + # brightness 0 = 1/16th pulse width
97 + # brightness 7 = 14/16th pulse width
98 + if val is None:
99 + return self._brightness
100 + if not 0 <= val <= 7:
101 + raise ValueError("Brightness out of range")
102 +
103 + self._brightness = val
104 + self._write_data_cmd()
105 + self._write_dsp_ctrl()
106 +
107 + def write(self, segments, pos=0):
108 + """Display up to 6 segments moving right from a given position.
109 + The MSB in the 2nd segment controls the colon between the 2nd
110 + and 3rd segments."""
111 + if not 0 <= pos <= 5:
112 + raise ValueError("Position out of range")
113 + self._write_data_cmd()
114 + self._start()
115 +
116 + self._write_byte(TM1637_CMD2 | pos)
117 + for seg in segments:
118 + self._write_byte(seg)
119 + self._stop()
120 + self._write_dsp_ctrl()
121 +
122 + def encode_digit(self, digit):
123 + """Convert a character 0-9, a-f to a segment."""
124 + return _SEGMENTS[digit & 0x0f]
125 +
126 + def encode_string(self, string):
127 + """Convert an up to 4 character length string containing 0-9, a-z,
128 + space, dash, star to an array of segments, matching the length of the
129 + source string."""
130 + segments = bytearray(len(string))
131 + for i in range(len(string)):
132 + segments[i] = self.encode_char(string[i])
133 + return segments
134 +
135 + def encode_char(self, char):
136 + """Convert a character 0-9, a-z, space, dash or star to a segment."""
137 + o = ord(char)
138 + if o == 32:
139 + return _SEGMENTS[36] # space
140 + if o == 42:
141 + return _SEGMENTS[38] # star/degrees
142 + if o == 45:
143 + return _SEGMENTS[37] # dash
144 + if o >= 65 and o <= 90:
145 + return _SEGMENTS[o-55] # uppercase A-Z
146 + if o >= 97 and o <= 122:
147 + return _SEGMENTS[o-87] # lowercase a-z
148 + if o >= 48 and o <= 57:
149 + return _SEGMENTS[o-48] # 0-9
150 + raise ValueError("Character out of range: {:d} '{:s}'".format(o, chr(o)))
151 +
152 + def hex(self, val):
153 + """Display a hex value 0x0000 through 0xffff, right aligned."""
154 + string = '{:04x}'.format(val & 0xffff)
155 + self.write(self.encode_string(string))
156 +
157 + def number(self, num):
158 + """Display a numeric value -999 through 9999, right aligned."""
159 + # limit to range -999 to 9999
160 + num = max(-999, min(num, 9999))
161 + string = '{0: >4d}'.format(num)
162 + self.write(self.encode_string(string))
163 +
164 + def numbers(self, num1, num2, colon=True):
165 + """Display two numeric values -9 through 99, with leading zeros
166 + and separated by a colon."""
167 + num1 = max(-9, min(num1, 99))
168 + num2 = max(-9, min(num2, 99))
169 + segments = self.encode_string('{0:0>2d}{1:0>2d}'.format(num1, num2))
170 + if colon:
171 + segments[1] |= 0x80 # colon on
172 + self.write(segments)
173 +
174 + def temperature(self, num):
175 + if num < -9:
176 + self.show('lo') # low
177 + elif num > 99:
178 + self.show('hi') # high
179 + else:
180 + string = '{0: >2d}'.format(num)
181 + self.write(self.encode_string(string))
182 + self.write([_SEGMENTS[38], _SEGMENTS[12]], 2) # degrees C
183 +
184 + def show(self, string, colon=False):
185 + segments = self.encode_string(string)
186 + if len(segments) > 1 and colon:
187 + segments[1] |= 128
188 + self.write(segments[:4])
189 +
190 + def scroll(self, string, delay=250):
191 + segments = string if isinstance(string, list) else self.encode_string(string)
192 + data = [0] * 8
193 + data[4:0] = list(segments)
194 + for i in range(len(segments) + 5):
195 + self.write(data[0+i:4+i])
196 + sleep_ms(delay)
197 +
198 +
199 +class TM1637Decimal(TM1637):
200 + """Library for quad 7-segment LED modules based on the TM1637 LED driver.
201 + This class is meant to be used with decimal display modules (modules
202 + that have a decimal point after each 7-segment LED).
203 + """
204 +
205 + def encode_string(self, string):
206 + """Convert a string to LED segments.
207 + Convert an up to 4 character length string containing 0-9, a-z,
208 + space, dash, star and '.' to an array of segments, matching the length of
209 + the source string."""
210 + segments = bytearray(len(string.replace('.','')))
211 + j = 0
212 + for i in range(len(string)):
213 + if string[i] == '.' and j > 0:
214 + segments[j-1] |= TM1637_MSB
215 + continue
216 + segments[j] = self.encode_char(string[i])
217 + j += 1
218 + return segments
219 +
220 +
1 +''' Original code from https://www.iottrends.tech/blog/how-to-use-ultrasonic-sensor-with-raspberry-pi-pico/
2 +'''
3 +from machine import Pin
4 +import utime
5 +trigger = Pin(26, Pin.OUT)
6 +echo = Pin(27, Pin.IN)
7 +
8 +# --------------------------------------------------- #
9 +# FUNCTIONS
10 +# --------------------------------------------------- #
11 +def work_sr04():
12 + trigger.low()
13 + utime.sleep_us(2)
14 + trigger.high()
15 + utime.sleep_us(5)
16 + trigger.low()
17 + while echo.value() == 0:
18 + signaloff = utime.ticks_us()
19 + while echo.value() == 1:
20 + signalon = utime.ticks_us()
21 + timepassed = signalon - signaloff
22 + distance = (timepassed * 0.0330) / 2
23 +
24 + return distance
25 +
1 +
2 +#include <SoftwareSerial.h>
3 +#include <DHT.h>
4 +#include <TM1637Display.h>
5 +#include <Adafruit_NeoPixel.h>
6 +#include <string.h>
7 +
8 +//-------------Bluetooth--------------//
9 +#define BLUETXPIN 2
10 +#define BLUERXPIN 3
11 +
12 +const byte numChars = 15;
13 +char inputdata[numChars]; // an array to store the received data
14 +
15 +boolean newData = false;
16 +
17 +//--------Temperature, Humidity--------//
18 +#define DHTPIN A2
19 +#define DHTTYPE DHT22
20 +
21 +DHT dht(DHTPIN, DHTTYPE);
22 +
23 +//-------------Ultrasonic-------------//
24 +#define USTRIGPIN A0
25 +#define USECHOPIN A1
26 +
27 +long duration;
28 +long distance;
29 +
30 +//--------------Magnetic--------------//
31 +#define MAGPIN 13
32 +int mag_value = 0;
33 +
34 +SoftwareSerial wirelessSerial(BLUETXPIN, BLUERXPIN);
35 +
36 +//--------------7Segment--------------//
37 +#define TM1637CLKPIN 5
38 +#define TM1637DIOPIN 4
39 +
40 +TM1637Display display = TM1637Display(TM1637CLKPIN, TM1637DIOPIN);
41 +
42 +// All segments on:
43 +const uint8_t data[] = {0xff, 0xff, 0xff, 0xff};
44 +// All segments off:
45 +const uint8_t blank[] = {0x00, 0x00, 0x00, 0x00};
46 +
47 +//--------------NeoPixel--------------//
48 +#define NEOPIXELPIN 6
49 +#define NUMLED 8
50 +Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMLED, NEOPIXELPIN, NEO_GRB + NEO_KHZ800);
51 +
52 +//------------Entrypoint--------------//
53 +void setup() {
54 + // Temp, Hum
55 + dht.begin();
56 +
57 + // Ultrasonic
58 + pinMode(USTRIGPIN, OUTPUT);
59 + pinMode(USECHOPIN, INPUT);
60 +
61 + // Magnetic
62 + pinMode(MAGPIN, INPUT);
63 +
64 + // Bluetooth
65 + wirelessSerial.begin(9600);
66 +
67 + // 7Segment
68 + display.clear();
69 + display.setBrightness(7);
70 +
71 + // NeoPixel
72 + strip.begin();
73 + strip.show();
74 +
75 + // Test
76 + Serial.begin(9600);
77 +}
78 +
79 +//------------Functions-------------//
80 +void recvWithEndMarker() {
81 + static byte ndx = 0;
82 + char endMarker = '\n';
83 + char rc;
84 +
85 + while (wirelessSerial.available() > 0 && newData == false) {
86 + rc = wirelessSerial.read();
87 +
88 + if (rc != endMarker) {
89 + inputdata[ndx] = rc;
90 + ndx++;
91 + if (ndx >= numChars) {
92 + ndx = numChars - 1;
93 + }
94 + }
95 + else {
96 + inputdata[ndx] = '\0'; // terminate the string
97 + ndx = 0;
98 + newData = true;
99 + }
100 + }
101 + if (newData == true) {
102 + Serial.print("TESTTSETESTST ...... ");
103 + Serial.println(inputdata);
104 + Serial.println(strlen(inputdata));
105 +
106 + int inputdata_len = strlen(inputdata) - 10;
107 + Serial.print("INPUTDATALEN: ");
108 + Serial.println(inputdata_len);
109 + inputdata[inputdata_len] = '\0';
110 +
111 + Serial.println(inputdata);
112 + Serial.println(strlen(inputdata));
113 + }
114 +}
115 +
116 +void showNewData() {
117 + Serial.print("This just in ... ");
118 + Serial.println(inputdata);
119 + Serial.println(strlen(inputdata));
120 +}
121 +
122 +void ultrasonicSensor() {
123 + // Send signal
124 + digitalWrite(USTRIGPIN, LOW);
125 + delayMicroseconds(2);
126 + digitalWrite(USTRIGPIN, HIGH);
127 + delayMicroseconds(10);
128 + digitalWrite(USTRIGPIN, LOW);
129 +
130 + // Save duration(Oneway x 2)
131 + duration = pulseIn(USECHOPIN, HIGH);
132 +
133 + // Calculate distance
134 + Serial.print("Duration: ");
135 + Serial.println(duration);
136 + distance = (duration * 17) / 1000 ;
137 +
138 + // Test
139 + Serial.print("Distance: ");
140 + Serial.print(distance);
141 + Serial.println("cm");
142 +
143 + // Send thw BLE
144 + wirelessSerial.write(distance);
145 +}
146 +
147 +void temphumSensor() {
148 + // Get humidity and temperature
149 + float h = dht.readHumidity();
150 + float t = dht.readTemperature();
151 +
152 + // Test
153 + Serial.print("Humidity: ");
154 + Serial.print(h);
155 + Serial.print(" %\t");
156 + Serial.print("Temperature: ");
157 + Serial.print(t);
158 + Serial.println(" *C");
159 +
160 + // Send thw BLE
161 + wirelessSerial.write(h);
162 + wirelessSerial.write(t);
163 +}
164 +
165 +void magneticSensor() {
166 + // Get mag value
167 + mag_value = digitalRead(MAGPIN);
168 +
169 + // Test
170 + Serial.print("Magnetic: ");
171 + Serial.println(mag_value);
172 +
173 + // Send thw BLE
174 + wirelessSerial.write(mag_value);
175 +}
176 +
177 +void cycleNeoPixel() {
178 + for (int i = 0; i < NUMLED; i++) {
179 + strip.setPixelColor(i % NUMLED, 0, 0, 0);
180 + strip.setPixelColor((i + 1) % NUMLED, 0, 1, 2);
181 + strip.setPixelColor((i + 2) % NUMLED, 0, 4, 3);
182 + strip.setPixelColor((i + 3) % NUMLED, 0, 16, 9);
183 + strip.setPixelColor((i + 4) % NUMLED, 0, 30, 16);
184 + strip.setPixelColor((i + 5) % NUMLED, 0, 60, 31);
185 + strip.setPixelColor((i + 6) % NUMLED, 0, 0, 0);
186 + strip.setPixelColor((i + 7) % NUMLED, 1, 2, 0);
187 +
188 + strip.show();
189 + delay(80);
190 + }
191 +}
192 +
193 +void offNeoPixel() {
194 + for (int i = 0; i < NUMLED; i++) {
195 + strip.setPixelColor(i, 0, 0, 0);
196 + }
197 + strip.show();
198 +}
199 +
200 +void doseDisplay() {
201 + Serial.print("Dose: ");
202 + Serial.println(inputdata);
203 + Serial.println(int(inputdata[0] - '0'));
204 + for (int i = 0; i < 10; i++) {
205 + cycleNeoPixel();
206 + display.showNumberDec(int(inputdata[0] - '0'), false, 1, 3);
207 + }
208 + display.clear();
209 + offNeoPixel();
210 +}
211 +
212 +void dateDisplay() {
213 + Serial.print("Last time: ");
214 + Serial.print(inputdata[0]);
215 + Serial.print(inputdata[1]);
216 + Serial.print(inputdata[2]);
217 + Serial.println(inputdata[3]);
218 +
219 + display.showNumberDec(int(inputdata[0] - '0'), false, 1, 0);
220 + display.showNumberDec(int(inputdata[1] - '0'), false, 1, 1);
221 + display.showNumberDec(int(inputdata[2] - '0'), false, 1, 2);
222 + display.showNumberDec(int(inputdata[3] - '0'), false, 1, 3);
223 + delay(5000);
224 + display.clear();
225 +}
226 +
227 +
228 +//---------------Main----------------//
229 +void loop() {
230 + // Data
231 + if (newData == false) {
232 + recvWithEndMarker();
233 + }
234 +
235 + // Call Functions
236 + if (newData == true) {
237 + showNewData();
238 + // Menu
239 + if (inputdata[0] == 'A') {
240 + ultrasonicSensor();
241 + }
242 + else if (inputdata[0] == 'B') {
243 + temphumSensor();
244 + }
245 + else if (inputdata[0] == 'C') {
246 + magneticSensor();
247 + }
248 + else if (strlen(inputdata) < 4) {
249 + doseDisplay();
250 + } else {
251 + dateDisplay();
252 + }
253 + newData = false;
254 + }
255 +}
...\ No newline at end of file ...\ No newline at end of file