×

使用boltiot预测温度

消耗积分:0 | 格式:zip | 大小:6.45 MB | 2022-11-24

笑尽往事

分享资料个

描述

温度预测

温度预测

所需硬件

  • Bolt Wifi 模块
  • 3 母对公线
  • 温度传感器:LM35传感器

连接

将 LM35 传感器连接到螺栓

第 1 步:握住传感器,以便您可以读取上面写的 LM35。

第 2 步:在此位置,将传感器的引脚从左到右识别为 VCC、输出和接地。

在上图中,VCC 连接到红色线,输出连接到橙色线,Gnd 连接到棕色线。步骤 3:使用公对母线将 LM35 的 3 个引脚连接到 Bolt Wifi 模块,如下所示如下:

  • LM35 的 VCC 引脚连接到 Bolt Wifi 模块的 5v。
  • LM35 的输出引脚连接到 Bolt Wifi 模块的 A0(模拟输入引脚)。
  • LM35 的 Gnd 引脚连接到 Gnd。

最终威廉希尔官方网站 应如下图所示:

既然您知道多项式回归是什么,我们将使用它与 Bolt Cloud 来预测您房间的温度。

第 1 步:在“云、API 和警报”模块的“通过 VPS 连接传感器”主题中进行与“温度监视器的硬件连接”屏幕相同的连接。

Step 2: Power up the circuit and let it connect to the Bolt Cloud. (The Green LED of the Bolt should be on)

Step 3: Go to cloud.boltiot.com and create a new product. While creating the product, choose product type as Input Device and interface type as GPIO. After creating the product, select the recently created product and then click on configure icon.

Step 4: In the hardware tab, select the radio button next to the A0 pin. Give the pin the name 'temp' and save the configuration using the 'Save' icon.

Step 5: Move to the code tab, give the product code the name 'predict', and select the code type as js.

Step 6: Write the following code to plot the temperature data and run the polynomial regression algorithm on the data, and save the product configurations.

setChartLibrary('google-chart');

setChartTitle('Polynomial Regression');

setChartType('predictionGraph');

setAxisName('time_stamp', 'temp');

mul(0.0977);

plotChart('time_stamp', 'temp');

Step 7: In the products tab, select the product created and then click on the link icon. Select your Bolt device in the popup and then click the 'Done' button.

Step 8: Click on 'deploy configuration' button and then the 'view this device' icon to view the page that you have designed. Below is the screenshot of the final output.

Step 1: Connect the temperature monitoring circuit as we have done in the previous lesson -Hardware connections for temperature monitor.

Step 2: Login into the putty by entering the IP address of your digital ocean droplet.

Step 3: After successful login, create a file named conf.py which will store all the credentials related to Twilio. To create a new file type sudo nano conf.py in the terminal. After that write below code to save all the credentials in a single file.

SID = 'You can find SID in your Twilio Dashboard'

AUTH_TOKEN = 'You can find on your Twilio Dashboard'

FROM_NUMBER = 'This is the no. generated by Twilio. You can find this on your Twilio Dashboard'

TO_NUMBER = 'This is your number. Make sure you are adding +91 in beginning'

API_KEY = 'This is your Bolt Cloud accout API key'

DEVICE_ID = 'This is the ID of your Bolt device'

Note: You have to replace all the above value with your credentials. You can find the first four value in Twilio dashboard and the last two in Bolt Cloud dashboard.

We store all the credentials in a separate file since it is sensitive data which should not be shared with anyone. Hence it is a good practice to avoid using credentials in code directly. After replacing all the values, save the file using CTRL+X.

Step 4: Now create one more file named temp_sms.py. To do so you have to type sudo nano temp_sms.py in the terminal. Now we will write main code to collect the data from the Bolt and send SMS if it crosses the threshold.

The algorithm for the code can be broken down into the following steps -

Fetch the latest sensor value from the Bolt device.

Check if the sensor value is in the range specified in our min and max values.

If it is not in range, send the SMS.

Wait for 10 seconds.

Repeat from step 1.

Now we will initialize two variables which will store minimum and maximum threshold value. You can initialize any minimum and maximum integer limits to them.

  • This would send an alert if the temperature reading goes below the minimum limit or goes above the maximum limit similar to the alerts on a Pharmaceutical company's manufacturing line.

minimum_limit = 300

maximum_limit = 600

  • Now to fetch the data from Bolt Cloud, we will create an object called 'mybolt' using which you can access the data on your Bolt.
  • For the Bolt Cloud to identify your device, you will need to provide the API key and the Device ID when creating the mybolt object. Since the conf file holds the API key and Device ID variables, you can use them as follows,

mybolt = Bolt(conf.API_KEY, conf.DEVICE_ID)

  • The above code will automatically fetch your API key and Device ID that you have initialized in conf.py file.
  • Now to send an SMS, we will create an object of the same.

sms = Sms(conf.SID, conf.AUTH_TOKEN, conf.TO_NUMBER, conf.FROM_NUMBER)

  • The above code will automatically fetch your SID, AUTH_TOKEN, TO_NUMBER and FROM_NUMBER that you have initialized in conf.py file. Make sure you have given correct value in conf.py file.
  • Since we want to continuously monitor the temperature reading, we will enclose our logic to fetch, compare and send the SMS inside an infinite loop using the `while True:` statement. An infinite loop is a special loop which executes its code continuously since its exit condition is never going to be valid. To exit the loop, we will need to forcibly exit the code by holding CTRL + C.

while True:

print ("Reading sensor value")

response = mybolt.analogRead('A0')

data = json.loads(response)

print("Sensor value is: " + str(data['value']))

try:

sensor_value = int(data['value'])

if sensor_value > maximum_limit or sensor_value < minimum_limit:

print("Making request to Twilio to send a SMS")

response = sms.send_sms("The Current temperature sensor value is " +str(sensor_value))

print("Response received from Twilio is: " + str(response))

print("Status of SMS at Twilio is :" + str(response.status))

except Exception as e:

print ("Error occured: Below are the details")

print (e)

time.sleep(10)

  • The code continuously fetches the temperature value using `analogRead` function. Since the sensor is connected to A0 pin of the Bolt, we will execute the analogRead() function on the pin A0.
  • The response from the Bolt Cloud using the analogRead() function is in a JSON format, so we will need to load the JSON data sent by the cloud using Python's json library.
  • The temperature value is inside a field labelled as "value" in the response. We can access the JSON values using the statement `sensor_value = int(data['value'])`. This line also converts the sensor reading to integer data type for comparing the temperature range.
  • This is enclosed inside a try-except block to handle any error that may occur in the code. More explanation of try-except code block is given here.
  • The next line of code checks if the temperature reading is above the maximum limit or below the minimum limit. If it exceeds, then the SMS will be sent.
  • The SMS to be sent will contain the text "The Current temperature sensor value is" followed by the temperature value.
  • The response from Twilio will be stored inside the `response` variable.
  • Once the temperature reading has been sent, we will need to wait for 10 seconds to get the next reading. For this, we will put the program to sleep once every loop iteration.
  • The statement `time.sleep(10)` puts the program execution on hold for 10 seconds. This means that the program would not execute for a period of 10 seconds.

In the above code, we are fetching the data every 10sec. You can change the value but ideally, it should be good if the time interval between 2 data points is more than 10sec.

Below is the complete code:

import conf

from boltiot import Sms, Bolt

import json, time

minimum_limit = 300

maximum_limit = 600

mybolt = Bolt(conf.API_KEY, conf.DEVICE_ID)

sms = Sms(conf.SID, conf.AUTH_TOKEN, conf.TO_NUMBER, conf.FROM_NUMBER)

while True:

print ("Reading sensor value")

response = mybolt.analogRead('A0')

data = json.loads(response)

print("Sensor value is: " + str(data['value']))

try:

sensor_value = int(data['value'])

if sensor_value > maximum_limit or sensor_value < minimum_limit:

print("Making request to Twilio to send a SMS")

response = sms.send_sms("The Current temperature sensor value is " +str(sensor_value))

print("Response received from Twilio is: " + str(response))

print("Status of SMS at Twilio is :" + str(response.status))

except Exception as e:

print ("Error occured: Below are the details")

print (e)

time.sleep(10)

Note: The above "sensor_value" is the raw temperature reading, obtained from the LM35 sensor. In case you want to convert this value to the temperature in degree Celsius, use the formula:

  • Temperature=(100*sensor_value)/1024

Where sensor_value is the variable in which data obtained from the LM35 sensor is stored.

  • Save the file. Time to run the code. To do so type `sudo python3 temp_sms.py` in terminal

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

评论(0)
发评论

下载排行榜

全部0条评论

快来发表一下你的评论吧 !

'+ '

'+ '

'+ ''+ '
'+ ''+ ''+ '
'+ ''+ '' ); $.get('/article/vipdownload/aid/'+webid,function(data){ if(data.code ==5){ $(pop_this).attr('href',"//m.obk20.com/www/login/index.html"); return false } if(data.code == 2){ //跳转到VIP升级页面 window.location.href="//m.obk20.com/vip/index?aid=" + webid return false } //是会员 if (data.code > 0) { $('body').append(htmlSetNormalDownload); var getWidth=$("#poplayer").width(); $("#poplayer").css("margin-left","-"+getWidth/2+"px"); $('#tips').html(data.msg) $('.download_confirm').click(function(){ $('#dialog').remove(); }) } else { var down_url = $('#vipdownload').attr('data-url'); isBindAnalysisForm(pop_this, down_url, 1) } }); }); //是否开通VIP $.get('/article/vipdownload/aid/'+webid,function(data){ if(data.code == 2 || data.code ==5){ //跳转到VIP升级页面 $('#vipdownload>span').text("开通VIP 免费下载") return false }else{ // 待续费 if(data.code == 3) { vipExpiredInfo.ifVipExpired = true vipExpiredInfo.vipExpiredDate = data.data.endoftime } $('#vipdownload .icon-vip-tips').remove() $('#vipdownload>span').text("VIP免积分下载") } }); }).on("click",".download_cancel",function(){ $('#dialog').remove(); }) var setWeixinShare={};//定义默认的微信分享信息,页面如果要自定义分享,直接更改此变量即可 if(window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger'){ var d={ title:'使用boltiot预测温度',//标题 desc:$('[name=description]').attr("content"), //描述 imgUrl:'https://'+location.host+'/static/images/ele-logo.png',// 分享图标,默认是logo link:'',//链接 type:'',// 分享类型,music、video或link,不填默认为link dataUrl:'',//如果type是music或video,则要提供数据链接,默认为空 success:'', // 用户确认分享后执行的回调函数 cancel:''// 用户取消分享后执行的回调函数 } setWeixinShare=$.extend(d,setWeixinShare); $.ajax({ url:"https://www.elecfans.com/app/wechat/index.php?s=Home/ShareConfig/index", data:"share_url="+encodeURIComponent(location.href)+"&format=jsonp&domain=m", type:'get', dataType:'jsonp', success:function(res){ if(res.status!="successed"){ return false; } $.getScript('https://res.wx.qq.com/open/js/jweixin-1.0.0.js',function(result,status){ if(status!="success"){ return false; } var getWxCfg=res.data; wx.config({ //debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId:getWxCfg.appId, // 必填,公众号的唯一标识 timestamp:getWxCfg.timestamp, // 必填,生成签名的时间戳 nonceStr:getWxCfg.nonceStr, // 必填,生成签名的随机串 signature:getWxCfg.signature,// 必填,签名,见附录1 jsApiList:['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); wx.ready(function(){ //获取“分享到朋友圈”按钮点击状态及自定义分享内容接口 wx.onMenuShareTimeline({ title: setWeixinShare.title, // 分享标题 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); //获取“分享给朋友”按钮点击状态及自定义分享内容接口 wx.onMenuShareAppMessage({ title: setWeixinShare.title, // 分享标题 desc: setWeixinShare.desc, // 分享描述 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 type: setWeixinShare.type, // 分享类型,music、video或link,不填默认为link dataUrl: setWeixinShare.dataUrl, // 如果type是music或video,则要提供数据链接,默认为空 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); //获取“分享到QQ”按钮点击状态及自定义分享内容接口 wx.onMenuShareQQ({ title: setWeixinShare.title, // 分享标题 desc: setWeixinShare.desc, // 分享描述 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); //获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口 wx.onMenuShareWeibo({ title: setWeixinShare.title, // 分享标题 desc: setWeixinShare.desc, // 分享描述 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); //获取“分享到QQ空间”按钮点击状态及自定义分享内容接口 wx.onMenuShareQZone({ title: setWeixinShare.title, // 分享标题 desc: setWeixinShare.desc, // 分享描述 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); }); }); } }); } function openX_ad(posterid, htmlid, width, height) { if ($(htmlid).length > 0) { var randomnumber = Math.random(); var now_url = encodeURIComponent(window.location.href); var ga = document.createElement('iframe'); ga.src = 'https://www1.elecfans.com/www/delivery/myafr.php?target=_blank&cb=' + randomnumber + '&zoneid=' + posterid+'&prefer='+now_url; ga.width = width; ga.height = height; ga.frameBorder = 0; ga.scrolling = 'no'; var s = $(htmlid).append(ga); } } openX_ad(828, '#berry-300', 300, 250);