Arduino与树莓派配合上传数据至onenet

树莓派python代码:

# -*- coding:utf-8 -*- File: ceshitianqi

# -*- coding:utf-8 -*-
# File: ceshitianqi

import urllib2
import json
import time
import datetime
import serial  
import random
import os

APIKEY = 'ZPd***BnQvK9jI='  #改成你的APIKEY

def read(key):
    ser=serial.Serial("/dev/ttyUSB1",9600,timeout=1)
    ser.write(key)
    print("output:"+key)
    time.sleep(1)
    response = ser.readall()
    print(response)
    print(type(response))
    return response

def http_put(key):
    val = read(key) #获取Arduino的数据
    CurTime = datetime.datetime.now()
    url='http://api.heclouds.com/devices/2666***1/datapoints'
    #values={'datastreams':[{"id":"temp","datapoints":[{"at":CurTime.isoformat(),"value":val}]}]}
    print(type(val))
    if key== "a" :
      values={'datastreams':[{"id":"humidity","datapoints":[{"at":CurTime.isoformat(),"value":val}]}]}
    if key== "b" :
      values={'datastreams':[{"id":"temperature","datapoints":[{"at":CurTime.isoformat(),"value":val}]}]}
    jdata = json.dumps(values)                  # 对数据进行JSON格式化编码
    #打印json内容
    print jdata
    request = urllib2.Request(url, jdata)
    request.add_header('api-key', APIKEY)
    request.get_method = lambda:'POST'          # 设置HTTP的访问方式
    request = urllib2.urlopen(request)
    return request.read()   

str = ("a","b")
while True:
	for i in str:     
		resp = http_put(i)
      		time.sleep(2)

arduino代码:

#include 
dht11 DHT11;
#define DHT11PIN 8
void setup(){
  Serial.begin(9600);
}

void loop(){
      int chk = DHT11.read(DHT11PIN);
    if(Serial.available()>0)
   {
    char c=Serial.read();
    Serial.println(c);
    if(c=='a')
    {
      Serial.println((float)DHT11.humidity, 2);
    }
    else if(c=='b')
    {
     Serial.println((float)DHT11.temperature, 2);
      delay(2000);
    }
}
}

接线如图:

Arduino与树莓派配合上传数据至onenet_第1张图片

你可能感兴趣的:(Arduino与树莓派配合上传数据至onenet)