将上一章节的大气压强+温度信息上传至服务器

首先,在服务器运行网络调试助手

有很多免费的网络调试助手可用

 

将如下代码记录为xxx.py文件

 

#!/usr/bin/python

#-*-coding:utf-8-*-

 

import socket

import time

from BMP180 import BMP180

# Initialise the BMP085 and use STANDARD mode (default value)

# bmp = BMP085(0x77, debug=True)

bmp = BMP180()

# To specify a different operating mode, uncomment one of the following:

# bmp = BMP085(0x77, 0)  # ULTRALOWPOWER Mode

# bmp = BMP085(0x77, 1)  # STANDARD Mode

# bmp = BMP085(0x77, 2)  # HIRES Mode

# bmp = BMP085(0x77, 3)  # ULTRAHIRES Mode

 

HOST = '121.40.69.30'

PORT = 4000

Flag = True

 

while True:

 

    try:

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 定义socket类型,网络通信,TCP

        s.connect((HOST, PORT))  # 要连接的IP与端口

        # s.connect(('127.0.0.1', 6666))  #服务器和客户端都在一个系统下时使用的ip和端口

 

        Flag = True

    except socket.error as msg:

        print(msg)

        s.close()  # 关闭连接

        Flag = False

    while Flag:

        try:   

            temp = bmp.read_temperature()

            # Read the current barometric pressure level

            pressure = bmp.read_pressure()

            # To calculate altitude based on an estimated mean sea level pressure

            # (1013.25 hPa) call the function as follows, but this won't be very accurate

            altitude = bmp.read_altitude()

            # To specify a more accurate altitude, enter the correct mean sea level

            # pressure level.  For example, if the current pressure level is 1023.50 hPa

            # enter 102350 since we include two decimal places in the integer value

            # altitude = bmp.readAltitude(102350)

            print "Temperature: %.2f C" % temp

            print "Pressure:    %.2f hPa" % (pressure / 100.0)

            #print "Altitude:    %.2f\n" % altitude

 

            s.sendall("Temperature: %.2f C\r\n" % temp )      # 发送数据

            time.sleep(1)  # 休眠3秒

            s.sendall("Pressure: %.2f hPa\r\n" % (pressure / 100.0))    # 发送数据

            time.sleep(1)  # 休眠3秒

 

        except socket.error as msg:

            print(msg)

            s.close()  # 关闭连接

            Flag = False

 

 

直接运行该文件即可 在本地打印出温度和大气压强相关的信息 同时将采集到的数据上传到相应的IP

本地运行:

pi@raspberrypi:~/Desktop $ python BMP180_test.py 

Temperature: 19.00 C

Pressure:    1027.91 hPa

Temperature: 19.00 C

Pressure:    1027.88 hPa

Temperature: 19.00 C

Pressure:    1027.98 hPa

 

服务器接受数据如下:

 

按照如上操作 即可实现简单的数据上传功能

但是实际的项目应用肯定是考虑的更加全面 功能也不仅如此 后续看看能不能将采集的数据进行本地存储

如果想添加开机自启动 参考

树莓派 添加一个开机自启动的程序 (7)

http://www.muwenyidao.com/default.aspx?type=post&name=55