raspberry pi_如何使用Node,Raspberry Pi和LCD屏幕监控天气

raspberry pi

Over the last few years, smart home devices have gone from less than 300,000 back in 2015 up to almost 1.2 billion in 2020. And they’re expected to grow to 1.5 billion by 2021.

在过去的几年中,智能家居设备已经从2015年的不到30万台增长到2020年的近12亿台。预计到2021年,它们将增长到15亿台

So it's likely you have at least some smart devices in your home, given that the average will reach 8.7 smart devices per home by 2021.

因此,鉴于到2021年每个家庭的平均智能设备数量将达到8.7个,因此您的家庭中至少可能有一些智能设备。

As developers, we have some advantage in this domain, since we can build our own smart home devices.

作为开发人员,由于我们可以构建自己的智能家居设备,因此我们在这一领域具有一定优势。

It’s not only the devices that have experienced rapid development. The development boards used for them have started to become more and more commercial and accessible.

不仅设备经历了飞速的发展。 用于它们的开发板已开始变得越来越商业化和易于使用。

In this article, we will see how we can use a Raspberry Pi, an LCD screen, and a few lines of code to monitor the weather outside or for a specific location.

在本文中,我们将看到如何使用Raspberry Pi,LCD屏幕和几行代码来监视外部或特定位置的天气。

Because this is a Do It Yourself (DIY) project, there are some prerequisites that we need for this device.

因为这是一个自己动手(DIY)项目,所以此设备需要一些先决条件。

先决条件 (Prerequisites)

  • Raspberry Pi 3 (or higher)

    Raspberry Pi 3(或更高版本)
  • LCD Screen

    液晶屏
  • Connection Wires

    连接线
  • Potentiometer (Optional)

    电位计(可选)
  • Breadboard (Optional)

    面包板(可选)

如何建造 (How to Build It)

As soon as we have everything we need we can start. Let's take it step by step.

一旦我们拥有了所需的一切,我们就可以开始。 让我们逐步进行。

步骤一-基本配置 (Step I - Base Configuration)

The first step consists of the basic setup and a verification of all the components.

第一步包括基本设置和所有组件的验证。

For this demo, we will use ClimaCell Weather API as a weather data provider, as they have a large number of indicators, including air quality indicators, for us to use.

在此演示中,我们将使用ClimaCell Weather API作为天气数据提供者,因为它们具有大量指标,包括空气质量指标,可供我们使用。

To use their API we must open an account on their platform and get an API key, which we’ll use to sign our requests.

要使用他们的API,我们必须在他们的平台上开设一个帐户并获取一个API密钥,我们将使用它来签署请求。

The account is free to open and it comes with a 100-hour limit of API calls, which is more than enough for our project.

该帐户是免费开放的,并且具有100小时的API调用限制,这对于我们的项目来说已经绰绰有余。

As soon as we have this API key, we can move to the hardware configuration and connect the LCD screen to our Raspberry Pi. You should turn the Raspberry Pi off while you make the wire connection.

一旦有了此API密钥,我们就可以转到硬件配置并将LCD屏幕连接到我们的Raspberry Pi。 进行有线连接时,应关闭Raspberry Pi。

The pin layout for Raspberry Pi 3 can be seen in the next image.

下图显示了Raspberry Pi 3的引脚布局。

The wire connection between the LCD and the development board is the following:

LCD和开发板之间的电线连接如下:

This hardware connection will make the LCD screen be on full brightness and full contrast. The brightness level is not a problem, but contrast is because we won’t be able to see the characters on the screen.

这种硬件连接将使LCD屏幕处于全亮度和全对比度状态。 亮度级别不是问题,但是对比度是因为我们将无法在屏幕上看到字符。

That’s why we need to introduce at least one potentiometer with which to set the contrast level.

这就是为什么我们需要引入至少一个电位器来设置对比度级别的原因。

At this point, we can turn on our Raspberry Pi and we should see the LCD screen alive. With the help of variable resistance we should be able to control the contrast.

此时,我们可以打开Raspberry Pi,我们应该可以看到LCD屏幕还活着。 在可变电阻的帮助下,我们应该能够控制对比度。

第二步-项目配置 (Step II - Project Configuration)

As a programming language, we’ll use NodeJS to write the code. If you don’t already have NodeJS installed on your Raspberry then you can follow these simple instructions.

作为一种编程语言,我们将使用NodeJS编写代码。 如果您尚未在Raspberry上安装NodeJS,则可以按照以下简单说明进行操作

In a new folder, run the command npm init -y to set up a new npm package, followed by the command npm install lcd node-fetch to install these 2 necessary dependencies.

在新文件夹中,运行命令npm init -y设置新的npm软件包,然后npm install lcd node-fetch命令npm install lcd node-fetch来安装这两个必需的依赖项。

  • lcd will be used to communicate with the LCD Screen

    lcd将用于与LCD屏幕通信

  • node-fetch  will be used to make HTTP requests to ClimaCell API.

    node-fetch将用于向ClimaCell API发出HTTP请求。

We said that we need an API key to communicate with the weather data provider. You place your secret API key directly in the main code, or you can create a config.json file in which you can place this key and any other code-related configuration you may have.

我们说过,我们需要一个API密钥来与天气数据提供者进行通信。 您可以将您的秘密API密钥直接放置在主代码中,或者可以创建config.json文件,在其中可以放置此密钥以及您可能拥有的任何其他与代码相关的配置。

config.json

config.json

{  "cc_key": "<your_ClimaCell_API_key>"}

Lastly, let’s create the main file of our project and include all these things we talked about.

最后,让我们创建项目的主文件,并包含我们讨论的所有这些内容。

// * Dependencies
const Lcd = require("lcd");
const fs = require("fs");
const fetch = require("node-fetch");

// * Globals
const { cc_key } = JSON.parse(fs.readFileSync("./config.json"));

第三步-LCD (Step III - The LCD)

Writing on the screen is a piece of cake using the lcd module. This library acts as a layer of abstraction over how we communicate with the device. In this way we don’t need to micro-manage each command individually.

使用LCD模块在屏幕上写字是小菜一碟。 该库充当我们与设备通信方式的抽象层。 这样,我们不需要对每个命令进行微管理。

The entire code for our LCD screen is the following:

LCD屏幕的完整代码如下:

The first step was to create a new lcd object and to pass as argument the pins we’ve used.

第一步是创建一个新的lcd对象,并将我们使用的引脚作为参数传递。

The keys cols and rows represent the number of columns and rows of our LCD display. 16x2 is the one I used in this example. If your LCD has just 8 columns and 1 row, then replace 16 and 2 with your values.

colsrows键代表LCD显示屏的列数和行数。 我在此示例中使用的是16x2。 如果您的LCD只有8列和1行,则用您的值替换16和2。

To write something on the display we need to use these two methods successively:

要在显示器上写东西,我们需要依次使用以下两种方法:

  • lcd.setCursor() - selecting the position from which to start writing

    lcd.setCursor()-选择开始写入的位置
  • lcd.print()

    lcd.print()

At the same time, we wrapped these two functions in a promise to make use of async/away keywords.

同时,我们将这两个函数包装在一起,保证可以使用async/away关键字。

At this point, you can use this function and print something on your display. writeToLcd(0,0,'Hello World') should print the message Hello World on the first row starting from the first column.

此时,您可以使用此功能并在显示屏上打印一些内容。 writeToLcd(0,0,'Hello World')应该在第一行的第一行上打印消息Hello World

第四步-天气数据 (Step IV - The Weather Data)

The next step is to get the weather data and print it on the display.

下一步是获取天气数据并将其打印在显示屏上。

ClimaCell provides a lot of weather data information, but also air quality and pollen, fire and other information. The data is vast, but keep in mind that your LCD screen only has 16 columns and 2 rows – that’s just 32 characters.

ClimaCell提供了大量的天气数据信息 ,而且还提供空气质量和花粉,火灾等信息。 数据是巨大的,但是请记住,您的LCD屏幕只有16列和2行–只有32个字符。

If you want to display more types of data and this limit is too small for you, then you can use a scroll effect.

如果要显示更多类型的数据,而此限制对您来说太小,则可以使用滚动效果。

For this demo we’ll keep it simple and we’ll print on the LCD screen the following data:

对于此演示,我们将使其保持简单,并在LCD屏幕上打印以下数据:

  • current date (hour, minutes, seconds)

    当前日期(小时,分钟,秒)
  • temperature

    温度
  • precipitation intensity

    降水强度

To get data from ClimaCell for a specific location, then you need to send its geographical coordinates, latitude and longitude.

要从ClimaCell获取特定位置的数据,则需要发送其地理坐标,纬度和经度。

To find your city’s coordinates, you can use a free tool like latlong.net and then you can save them in config.json file along with your API key, or you can write them directly in the code.

要查找城市的坐标,可以使用免费的工具(例如latlong.net) ,然后可以将其与API密钥一起保存在config.json文件中,也可以直接在代码中编写。

At this point the data format returned by the API call is the following:

此时,API调用返回的数据格式如下:

{
  lat: 45.658,
  lon: 25.6012,
  temp: { value: 17.56, units: 'C' },
  precipitation: { value: 0.3478, units: 'mm/hr' },
  observation_time: { value: '2020-06-22T16:30:22.941Z' }
}

We can deconstruct this object and get the temp and the precipitation values and print them on the first and second row.

我们可以解构该对象并获得温度和降水量值,并将它们打印在第一行和第二行上。

第五步-总结 (Step V - Wrap it Up)

All we need to do now is to write the logic for our script, and update the LCD screen when new data arrives.

现在我们要做的就是编写脚本的逻辑,并在新数据到达时更新LCD屏幕。

The weather data is updated every 5 minutes. But because we have a limit of 100 API Calls / Hour imposed by ClimaCell, we can go even further and update the weather data each minute.

天气数据每5分钟更新一次。 但是由于我们限制了ClimaCell每小时进行100个API调用,因此我们可以走得更远,每分钟更新一次天气数据。

For the current date, we have two options:

对于当前日期,我们有两个选择:

  • we can use the property observation_time and display the date at which the data was received, or

    我们可以使用属性observation_time并显示接收数据的日期,或者

  • we can make a real clock and display the current time.

    我们可以制作一个真实的时钟并显示当前时间。

I chose the second option, but feel free to do it as you please.

我选择了第二个选项,但您可以随意选择。

To print the time in the upper right corner, we must first calculate the starting column so that the text fits snugly. For this we can use the next formula total columns number minus text to display length

要在右上角打印时间,我们必须首先计算起始列,以使文本紧贴文本。 为此,我们可以使用下一个公式: total columns number减去text to display length

The date has 8 characters and because he has 16 columns, we must start from column number 8.

日期有8个字符,并且由于他有16列,因此我们必须从第8列开始。

The LCD setting is asynchronous, so we must use the method lcd.on() provided by the related library, so we know when the LCD has been initialized and is ready to be used.

LCD设置是异步的,因此我们必须使用相关库提供的lcd.on()方法,这样我们才能知道LCD何时已初始化并可以使用。

Another best practice in embedded systems is to close and free the resources that you use. That’s why we use the SIGNINT event to close the LCD screen when the program is stopped. Other events like this one include:

嵌入式系统中的另一个最佳实践是关闭并释放您使用的资源。 这就是为什么我们在程序停止时使用SIGNINT事件关闭LCD屏幕的原因。 其他类似事件包括:

  • SIGUSR1 and SIGUSR2 - to catch "kill pid” like nodemon restart

    SIGUSR1SIGUSR2 -捉“杀PID”像nodemon重启

  • uncaughtException - to catch uncaught exceptions

    uncaughtException捕获未捕获的异常

第六步-永远运行 (Step VI - Run it Forever)

The script is complete and at this point we can run our program. We just have one more thing we must do before we can finish.

该脚本已完成,此时我们可以运行程序。 在完成之前,我们还有要做的一件事。

At this point you’re probably connected to your Raspberry Pi using SSH or directly with an HDMI cable and a monitor. No matter what, when you close your terminal the program will stop.

此时,您可能已使用SSH或直接通过HDMI电缆和监视器连接到Raspberry Pi。 无论如何,当您关闭终端时,程序将停止。

At the same time if you power off your device and after some time or immediately power it on again, the script will not start and you’ll have to do it manually.

同时,如果您关闭设备电源并等待一段时间或立即重新打开电源,该脚本将不会启动,您必须手动进行操作。

To solve this problem, we can use a process manager like pm2.

为了解决这个问题,我们可以使用pm2之类的流程管理器。

Here are the steps:

步骤如下:

  1. sudo npm install pm2 -g - install pm2

    sudo npm install pm2 -g安装pm2

  2. sudo pm2 startup - create a startup script for pm2 manager

    sudo pm2 startup -为pm2管理器创建启动脚本

  3. pm2 start index.js - start an application

    pm2 start index.js启动应用程序

  4. pm2 save - save your process list across server restart

    pm2 save在服务器重新启动时保存您的进程列表

Now you can reboot your board and the script will start automatically when the device is ready.

现在,您可以重新启动电路板,并且在设备准备就绪时,脚本将自动启动。

结论 (Conclusion)

From this point you can customize your new device however you want. If you find this weather data important for you (or any other data from ClimaCell, like air pollution, pollen, fire index or road risk), you can create a custom case to put the Raspberry Pi and the LCD display in it. Then after you added a battery you can place the device in your house.

此时,您可以根据需要自定义新设备。 如果您发现此天气数据对您很重要(或ClimaCell的其他任何数据,例如空气污染,花粉,火灾指数或道路风险),则可以创建一个自定义案例,将Raspberry Pi和LCD显示屏放入其中。 然后,在添加电池后,您可以将设备放在家里。

Raspberry Pi is like a personal computer, so you can do much more on it than you would normally do on a microcontroller like Arduino. Because of this, it's easy to combine it with other devices you have in your house.

Raspberry Pi就像一台个人计算机,因此您可以在其上做的工作比在像Arduino这样的微控制器上做的要多得多。 因此,很容易将其与房屋中的其他设备结合使用。

翻译自: https://www.freecodecamp.org/news/monitor-the-weather-with-node-and-raspberry-pi/

raspberry pi

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值