控制Arduino IO口和LCD1602显示当前时间、温度、CPU负载的树莓派

目的

用树莓派接入云平台,在本地显示时间、本地显示温度、温度通过tcp长连接传入贝壳物联平台

查看树莓派的引脚

输入

1
gpio readall

显示板子的插座、或者BCM引脚定位、或者WPi的引脚定位。

LM35

LM35需要5v供电..
由于树莓派没有模拟输入口..
所以我用Arduino做下位机

LM35接线

LCD1602

LCD1602同样也是5v供电。

LCD1602接线

这里采用4线接入(BROAD编号)

然后我卡住了一个小时..
我是准备用python写LCD1602的..
想想还是算了..
我还是用库吧…

安装驱动库

1
2
$ gitclone https://github.com/lyq1996/LCD1602.git
$ cd LCD1602

这个时候就可以用了..使用前修改一下RS,EN,Data的引脚

1
2
3
4
5
6
self.LCD_RS = 27
self.LCD_E = 22
self.LCD_D4 = 23
self.LCD_D5 = 24
self.LCD_D6 = 25
self.LCD_D7 = 26

修改OK之后的runit.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from lcd1602 import LCD1602
from time import sleep
import time,socket,struct,fcntl
lcd = LCD1602()
t = 1
while(1):
#time1 = str(t)
#print time.time()
#lcd.lcd_clear()
t = str(time.strftime("%Y-%m-%d %H:%M", time.localtime()))
lcd.lcd_string("Hello World",lcd.LCD_LINE_1)
lcd.lcd_string(t,lcd.LCD_LINE_2)
time.sleep(5)
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s','eth0'[:15]))[20:24])
lcd.lcd_string("Your Ip:",lcd.LCD_LINE_1)
lcd.lcd_string(ip,lcd.LCD_LINE_2)
time.sleep(5)
lcd.cleanup()

运行

1
python runit.py

效果如下

Arduino

Arduino串口上传程序

(监听串口的输入,如果为”temp”则发送LM35的温度数值,如果为”play”则亮LED)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const int LED = 7;
const int LM35d0 = 0;
const int LM35d1 = 1;
//unsigned long lastCheckInTime = 0;
unsigned long lastUpdateTime = 0;
//const unsigned long postingInterval = 40000;
const unsigned long updateInterval = 5000;
String inputString = "";
boolean stringComplete = false;
void setup() {
pinMode(LED,OUTPUT);
Serial.begin(9600);
// put your setup code here, to run once:
}
void loop() {
serialprocess();
if (stringComplete){
inputString.trim();
processMessage(inputString);
inputString = "";
stringComplete = false;
}}
void serialinput(){
float data,data1,data2;
int s,s1;
// put your main code here, to run repeatedly:
s = analogRead(LM35d0);
s1 = analogRead(LM35d1);
data1 = s*(5.0/1023.0*100);
data2 = s1*(5.0/1023.0*100);
data = (data1+data2)/2;
Serial.println(data);
//Serial.println('\n');
lastUpdateTime = millis();
}
void serialprocess(){
while (Serial.available()) {
char inChar = (char)Serial.read();
inputString += inChar;
if (inChar == '\n')
{
stringComplete = true;
}
}
}
void processMessage(String msg){
if(msg=="play"){
digitalWrite(LED, HIGH);
}
if(msg == "stop"){
digitalWrite(LED, LOW);}
if(msg == "temp"){
serialinput(); }
}

树莓派和Arduino串口连接详情

这里

树莓派

程序

作用
将数据上传至贝壳物联,并控制Arduino

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
from lcd1602 import LCD1602
import RPi.GPIO as GPIO
import time,socket,serial,urllib2,re,os,threading,json,sys
def get_CPU_temp():
res = os.popen('vcgencmd measure_temp').readline()
return (res.replace("temp=","").replace("'C\n",""))
def get_CPU_use():
return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))
def get_public_ip():
try:
content = urllib2.urlopen('http://ddns.nat123.com').read()
reg =re.compile(r'\d+.\d+.\d+.\d+')
c = re.findall(reg,content)
return c[0]
except:
return '0.0.0.0'
def servial_event(ser):
try:
while True:
try:
ser.isOpen()
except:
ser.open()
ser.write('temp\n')
res = ser.readlines()
if not len(res) ==0:
res = res[0][:-2]
return res
except Exception,e:
ser.close()
print e
return '0.00'
def get_ip_ini():
f = open(r'leastip.ini')
content = f.read()
f.close()
return content
def main():
lcd = LCD1602()
lastupdateiptime = 0
updateiptime = 1200
try:
readfin = False
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
thread = Thread(ser,DEVICEID,APIKEY,INPUTID1,INPUTID2,INPUTID3)
thread.start()
while True:
#t1 =time.time()
display1Time = time.time()
cpu_useage = get_CPU_use()
localtime = str(time.strftime("%Y-%m-%d %H:%M", time.localtime()))
lcd.lcd_string(localtime,lcd.LCD_LINE_1)
lcd.lcd_string("Cpu Usage:"+cpu_useage+"%",lcd.LCD_LINE_2)
while True:
if time.time()-display1Time >15/3.0:
break
res = servial_event(ser)
#res = '10.00'
cpu_temp = get_CPU_temp()
display2Time = time.time()
lcd.lcd_string("Local Temp:"+res,lcd.LCD_LINE_2)
lcd.lcd_string("Cpu Temp:"+cpu_temp,lcd.LCD_LINE_1)
thread.upload_temp(res)
while True:
if time.time()-display2Time >15/3.0:
break
display3Time = time.time()
string_a = 'Public IP:'
thread.upload_ctemp(cpu_temp)
if lastupdateiptime ==0 or time.time()-lastupdateiptime > updateiptime:
load_ip = get_ip_ini()
current_ip = get_public_ip()
lastupdateiptime = time.time()
if not load_ip == current_ip:
try:
#---------------------must modify------------------#
url = 'http://www.bigiot.net/Dns/updateDns?id=***&ip=%s&pw=********&pt=81'%(current_ip)
#---------------------must modify------------------#
urllib2.urlopen(url)
f = file(filename,"w+")
f.writelines(current_ip)
f.close()
print 'update public ip'
except Exception,e:
print e
pass
lcd.lcd_string(string_a,lcd.LCD_LINE_1)
lcd.lcd_string(current_ip,lcd.LCD_LINE_2)
while True:
if time.time()-display3Time >15/3.0:
break
thread.upload_cuseage(cpu_useage)
#print time.time()-t1
except:
lcd.lcd_string("Something error!",lcd.LCD_LINE_1)
lcd.lcd_string("System exiting!",lcd.LCD_LINE_2)
print 'KeyboardInterrupt or Exception!'
try:
thread.stop()
sys.exit()
except:
sys.exit()
class Thread(threading.Thread):#Threads class
def __init__(self,ser,deviceid,apikey,inputid1,inputid2,inputid3):
threading.Thread.__init__(self)
self.serial = ser
self.DEVICEID = deviceid
self.APIKEY = apikey
self.INPUTID1 = inputid1
self.INPUTID2 = inputid2
self.INPUTID3 = inputid3
self.timeevent = threading.Event()
self.host = "www.bigiot.net"
self.port = 8181
self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.socket.settimeout(0)
self.checkinBytes = bytes('{\"M\":\"checkin\",\"ID\":\"'+self.DEVICEID+'\",\"K\":\"'+self.APIKEY+'\"}\n')
self.breathBytes = bytes('{\"M\":\"breath\"}\n')
self.msg = ''
self.TimeToQuit = threading.Event()
self.login()
def login(self):
try:
self.socket.connect((self.host,self.port))
recv = self.socket.recv(1024)
print repr(recv)
time.sleep(2)
except:
print "connect to bigiot..."
time.sleep(1)
self.socket.sendall(self.checkinBytes)
def say(self,id,content):
self.sayBytes=bytes('{\"M\":\"say\",\"ID\":\"'+id+'\",\"C\":\"'+content+'\"}\n')
self.socket.sendall(self.sayBytes)
def keeponline(self):
self.socket.sendall(self.breathBytes)
def ledon(self):
self.serial.write('play\n')
def ledoff(self):
self.serial.write('stop\n')
def messageprocess(self):
if not self.msg == '':
self.msg = json.loads(self.msg)
if self.msg['M'] == 'connected':
self.socket.sendall(self.checkinBytes)
if self.msg['M'] == 'login':
self.say(self.msg['ID'],'Welcome! Your public ID is '+self.msg['ID'])
if self.msg['M'] == 'say':
self.say(self.msg['ID'],'You have send to me:{'+self.msg['C']+'}')
if self.msg['C'] == "play":
self.ledon()
self.say(self.msg['ID'],'LED turns on!')
if self.msg['C'] == "stop":
self.ledoff()
self.say(self.msg['ID'],'LED turns off!')
if self.msg['C'] == 'lighton':
GPIO.output(18,True)
self.say(self.msg['ID'],'LCD1602 BK light ON!')
if self.msg['C'] == 'lightoff':
GPIO.output(18,False)
self.say(self.msg['ID'],'LCD1602 BK light OFF!')
def run(self):
#time.sleep(1)
lastbreathTime = time.time()-20
while not self.TimeToQuit.isSet():
if lastbreathTime == 0 or time.time()-lastbreathTime >40:
try:
self.keeponline()
except:
print 'Thread Stop!'
lastbreathTime = time.time()
print 'Sended KeepOnline Packet!'
while True:
try:
self.data = self.socket.recv(1)
if not self.data == "\n":
self.msg +=str(self.data)
else:
#print self.msg
break
except:
self.msg = ''
break
self.messageprocess()
self.msg = ''
def stop(self):
self.TimeToQuit.set()
self.socket.close()
def upload_temp(self,value1):
valueBytes1 = bytes('{\"M\":\"update\",\"ID\":\"'+self.DEVICEID+'\",\"V\":{\"'+self.INPUTID1+'\":\"'+value1+'\"}}\n')
self.socket.sendall(valueBytes1)
def upload_cuseage(self,value2):
valueBytes2 = bytes('{\"M\":\"update\",\"ID\":\"'+self.DEVICEID+'\",\"V\":{\"'+self.INPUTID2+'\":\"'+value2+'\"}}\n')
self.socket.sendall(valueBytes2)
def upload_ctemp(self,value3):
valueBytes3 = bytes('{\"M\":\"update\",\"ID\":\"'+self.DEVICEID+'\",\"V\":{\"'+self.INPUTID3+'\":\"'+value3+'\"}}\n')
self.socket.sendall(valueBytes3)
if __name__=='__main__':
#---------------------must modify------------------#
DEVICEID = '****'
APIKEY = '*********'
INPUTID1 = '****'
INPUTID2 = '****'
INPUTID3 = '****'
#---------------------must modify------------------#
filename = r'leastip.ini'
if os.path.exists(filename):
main()
else:
f = file(filename,"w+")
content =['127.0.0.1']
f.writelines(content)
f.close()
main()

效果

操作指令

1
2
3
play:打开Arduino 7脚的LED.
stop:关闭LED.
boom:树莓派爆炸.

唯一的问题

指令的响应时间…有点堵塞…时间由1s-2s不等..应该是bigiot那边的问题

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×