将 Raspberry Pi 连接到 Azure IoT 中心 (Node.js)Connect Raspberry Pi to Azure IoT Hub (Node.js)

在本教程中,首先学习有关使用运行 Raspbian 的 Raspberry Pi 的基础知识。In this tutorial, you begin by learning the basics of working with Raspberry Pi that's running Raspbian. 然后学习如何使用 Azure IoT 中心将设备无缝连接到云。You then learn how to seamlessly connect your devices to the cloud by using Azure IoT Hub. 有关 Windows 10 IoT Core 的示例,请访问 Windows 开发人员中心For Windows 10 IoT Core samples, go to the Windows Dev Center.

还没有工具包?Don't have a kit yet? 试用 Raspberry Pi 联机模拟器Try Raspberry Pi online simulator. 或在此处购买新工具包。Or buy a new kit here.

准备工作What you do

  • 创建 IoT 中心。Create an IoT hub.
  • 在 IoT 中心内为 Pi 注册设备。Register a device for Pi in your IoT hub.
  • 设置 Raspberry Pi。Set up Raspberry Pi.
  • 在 Pi 上运行示例应用程序,将传感器数据发送到 IoT 中心。Run a sample application on Pi to send sensor data to your IoT hub.

学习内容What you learn

  • 如何创建 Azure IoT 中心以及如何获取新的设备连接字符串。How to create an Azure IoT hub and get your new device connection string.
  • 如何通过 BME280 传感器连接 Pi。How to connect Pi with a BME280 sensor.
  • 如何通过在 Pi 上运行示例应用程序来收集传感器数据。How to collect sensor data by running a sample application on Pi.
  • 如何将传感器数据发送到 IoT 中心。How to send sensor data to your IoT hub.

需要什么What you need


  • 一个 Raspberry Pi 2 或 Raspberry Pi 3 电路板。A Raspberry Pi 2 or Raspberry Pi 3 board.
  • Azure 订阅。An Azure subscription. 如果没有 Azure 订阅,可在开始前创建一个试用订阅If you don't have an Azure subscription, create a trial subscription before you begin.
  • 连接到 Pi 的监视器、USB 键盘和鼠标。A monitor, a USB keyboard, and mouse that connects to Pi.
  • 运行 Windows 或 Linux 的 Mac 或电脑。A Mac or PC that is running Windows or Linux.
  • Internet 连接。An internet connection.
  • 16 GB 或更大容量的 microSD 卡。A 16 GB or above microSD card.
  • USB-SD 适配器或 microSD 卡,用于将操作系统映像刻录到 microSD 卡中。A USB-SD adapter or microSD card to burn the operating system image onto the microSD card.
  • 带有 6 英尺微型 USB 电缆的 5 伏 2 安电源。A 5-volt 2-amp power supply with the 6-foot micro USB cable.

以下项可选:The following items are optional:

  • 已装配的 Adafruit BME280 温度、压力和湿度传感器。An assembled Adafruit BME280 temperature, pressure, and humidity sensor.
  • 试验板。A breadboard.
  • 6 根 F/M 跳线。6 F/M jumper wires.
  • 散射的 10 毫米 LED 灯。A diffused 10-mm LED.


如果没有可选项,可以使用模拟的传感器数据。If you don't have the optional items, you can use simulated sensor data.

创建 IoT 中心Create an IoT hub

此部分介绍如何使用 Azure 门户创建 IoT 中心。This section describes how to create an IoT hub using the Azure portal.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 从 Azure 主页中选择“+ 创建资源”按钮,然后在“搜索市场”字段中输入“IoT 中心”。 From the Azure homepage, select the + Create a resource button, and then enter IoT Hub in the Search the Marketplace field.

  3. 在搜索结果中选择“IoT 中心”,然后选择“创建” 。Select IoT Hub from the search results, and then select Create.

  4. 在“基本信息”选项卡上,按如下所示填写字段: On the Basics tab, complete the fields as follows:

    • 订阅:选择要用于中心的订阅。Subscription: Select the subscription to use for your hub.

    • 资源组:选择一个资源组或新建一个资源组。Resource Group: Select a resource group or create a new one. 若要新建资源组,请选择“新建”并填写要使用的名称。 To create a new one, select Create new and fill in the name you want to use. 若要使用现有的资源组,请选择它。To use an existing resource group, select that resource group. 有关详细信息,请参阅管理 Azure 资源管理器资源组For more information, see Manage Azure Resource Manager resource groups.

    • 区域:选择中心所在的区域。Region: Select the region in which you want your hub to be located. 选择最靠近你的位置。Select the location closest to you.

    • IoT 中心名称:输入中心的名称。IoT Hub Name: Enter a name for your hub. 此名称必须全局唯一。This name must be globally unique. 如果输入的名称可用,会显示一个绿色复选标记。If the name you enter is available, a green check mark appears.


    IoT 中心将公开为 DNS 终结点,因此,命名时请务必避免包含任何敏感信息。The IoT hub will be publicly discoverable as a DNS endpoint, so make sure to avoid any sensitive information while naming it.

    在 Azure 门户中创建中心

  5. 在完成时选择“下一步: 大小和规模”,以继续创建中心。Select Next: Size and scale to continue creating your hub.

    使用 Azure 门户为新的中心设置大小和规模

    可在此处接受默认设置。You can accept the default settings here. 如果需要,可以修改以下任何字段:If desired, you can modify any of the following fields:

    • 定价和缩放层:选择的层。Pricing and scale tier: Your selected tier. 可以根据你需要的功能数以及每天通过解决方案发送的消息数从多个层级中进行选择。You can choose from several tiers, depending on how many features you want and how many messages you send through your solution per day. 免费层适用于测试和评估。The free tier is intended for testing and evaluation. 允许 500 台设备连接到中心,每天最多可传输 8,000 条消息。It allows 500 devices to be connected to the hub and up to 8,000 messages per day. 每个 Azure 订阅可以在免费层中创建一个 IoT 中心。Each Azure subscription can create one IoT hub in the free tier.

      如果正在完成 IoT 中心设备流的快速入门,请选择免费层。If you are working through a Quickstart for IoT Hub device streams, select the free tier.

    • IoT 中心单元:每个单位每日允许的消息数取决于中心的定价层。IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. 例如,如果希望中心支持 700,000 条消息引入,请选择两个 S1 层单位。For example, if you want the hub to support ingress of 700,000 messages, you choose two S1 tier units. 有关其他层选项的详细信息,请参阅选择合适的 IoT 中心层For details about the other tier options, see Choosing the right IoT Hub tier.

    • 高级设置 > 设备到云的分区:此属性将设备到云消息与这些消息的同步读取器数目相关联。Advanced Settings > Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. 大多数中心只需要 4 个分区。Most hubs need only four partitions.

  6. 在完成时选择“下一步: 标记”继续到下一屏幕。Select Next: Tags to continue to the next screen.

    标记是名称/值对。Tags are name/value pairs. 可以为多个资源和资源组分配相同的标记,以便对资源进行分类并合并计费。You can assign the same tag to multiple resources and resource groups to categorize resources and consolidate billing. 有关详细信息,请参阅使用标记来组织 Azure 资源for more information, see Use tags to organize your Azure resources.

    使用 Azure 门户为新的中心设置大小和规模

  7. 在完成时选择“下一步: 查看+创建”可查看选择。Select Next: Review + create to review your choices. 你会看到类似于此屏幕的内容,但其中包含创建中心时选择的值。You see something similar to this screen, but with the values you selected when creating the hub.


  8. 选择“创建”以创建新的中心 。Select Create to create your new hub. 创建中心需要几分钟时间。Creating the hub takes a few minutes.

在 IoT 中心内注册新设备Register a new device in the IoT hub

本部分在 IoT 中心的标识注册表中创建设备标识。In this section, you create a device identity in the identity registry in your IoT hub. 除非设备在标识注册表中具有条目,否则设备无法连接到中心。A device cannot connect to a hub unless it has an entry in the identity registry. 有关详细信息,请参阅 IoT 中心开发人员指南For more information, see the IoT Hub developer guide.

  1. 在 IoT 中心导航菜单中,打开“IoT 设备” ,然后选择“新建” 以在 IoT 中心中添加设备。In your IoT hub navigation menu, open IoT Devices, then select New to add a device in your IoT hub.


  2. 在“创建设备” 中,为新设备提供名称(例如 myDeviceId),然后选择“保存” 。In Create a device, provide a name for your new device, such as myDeviceId, and select Save. 此操作会为 IoT 中心创建设备标识。This action creates a device identity for your IoT hub.



    收集的日志中可能会显示设备 ID 用于客户支持和故障排除,因此,在为日志命名时,请务必避免包含任何敏感信息。The device ID may be visible in the logs collected for customer support and troubleshooting, so make sure to avoid any sensitive information while naming it.

  3. 创建设备后,在“IoT 设备”窗格的列表中打开该设备 。After the device is created, open the device from the list in the IoT devices pane. 复制主连接字符串以便稍后使用。Copy the Primary Connection String to use later.



IoT 中心标识注册表只存储设备标识,以启用对 IoT 中心的安全访问。The IoT Hub identity registry only stores device identities to enable secure access to the IoT hub. 它存储设备 ID 和密钥用作安全凭据,以及可用于禁用单个设备访问的启用/禁用标志。It stores device IDs and keys to use as security credentials, and an enabled/disabled flag that you can use to disable access for an individual device. 如果应用程序需要存储其他特定于设备的元数据,则应使用特定于应用程序的存储。If your application needs to store other device-specific metadata, it should use an application-specific store. 有关详细信息,请参阅 IoT 中心开发人员指南For more information, see IoT Hub developer guide.

设置 Raspberry PiSetup Raspberry Pi

为 Pi 安装 Raspbian 操作系统Install the Raspbian operating system for Pi

准备用于安装 Raspbian 映像的 microSD 卡。Prepare the microSD card for installation of the Raspbian image.

  1. 下载 Raspbian。Download Raspbian.

    a.a. Raspbian Buster with desktop(.zip 文件)。Raspbian Buster with desktop (the .zip file).

    b.b. 将 Raspbian 映像解压缩到计算机的某个文件夹中。Extract the Raspbian image to a folder on your computer.

  2. 将 Raspbian 安装到 microSD 卡。Install Raspbian to the microSD card.

    a.a. 下载并安装 Etcher SD 卡刻录机实用工具Download and install the Etcher SD card burner utility.

    b.b. 运行 Etcher 并选择已在步骤 1 中解压缩的 Raspbian 映像。Run Etcher and select the Raspbian image that you extracted in step 1.

    c.c. 选择 microSD 卡驱动器。Select the microSD card drive. Etcher 可能已选择了正确的驱动器。Etcher may have already selected the correct drive.

    d.d. 单击“刷机”,将 Raspbian 安装到 microSD 卡。Click Flash to install Raspbian to the microSD card.

    e.e. 在安装完成后,从计算机中移除 microSD 卡。Remove the microSD card from your computer when installation is complete. 可以安全地直接取出 microSD 卡,因为 Etcher 会在完成后自动弹出或卸载 microSD 卡。It's safe to remove the microSD card directly because Etcher automatically ejects or unmounts the microSD card upon completion.

    f.f. 将 microSD 卡插入 Pi。Insert the microSD card into Pi.

启用 SSH 和 I2CEnable SSH and I2C

  1. 将 Pi 连接到监视器、键盘和鼠标。Connect Pi to the monitor, keyboard, and mouse.

  2. 启动 Pi,然后使用 pi 作为用户名并使用 raspberry 作为密码来登录 Raspbian。Start Pi and then sign into Raspbian by using pi as the user name and raspberry as the password.

  3. 依次单击 Raspberry 图标 >“首选项” > “Raspberry Pi 配置”。 Click the Raspberry icon > Preferences > Raspberry Pi Configuration.

    Raspbian 首选项菜单

  4. 在“接口” 选项卡上,将“I2C” 和“SSH” 设置为“启用” ,然后单击“确定” 。On the Interfaces tab, set I2C and SSH to Enable, and then click OK. 如果没有物理传感器并且想要使用模拟的传感器数据,则此步骤是可选的。If you don't have physical sensors and want to use simulated sensor data, this step is optional.

    在 Raspberry Pi 上启用 I2C 和 SSH


若要启用 SSH 和 I2C,可在 raspberrypi.orgAdafruit.com 中找到更多参考文档。To enable SSH and I2C, you can find more reference documents on raspberrypi.org and Adafruit.com.

将传感器连接到 PiConnect the sensor to Pi

使用试验板和跳线,将 LED 灯和 BME280 连接到 Pi,如下所示。Use the breadboard and jumper wires to connect an LED and a BME280 to Pi as follows. 如果没有该传感器,请跳过此部分If you don’t have the sensor, skip this section.

Raspberry Pi 和传感器连接

BME280 传感器可以收集温度和湿度数据。The BME280 sensor can collect temperature and humidity data. 当设备向云发送消息时,LED 将闪烁。The LED blinks when the device sends a message to the cloud.

对于传感器引脚,请使用以下接线:For sensor pins, use the following wiring:

始端(传感器和 LED 灯)Start (Sensor & LED) 结束(开发板)End (Board) 线缆颜色Cable Color
VDD(引脚 5G)VDD (Pin 5G) 3.3V 电源(引脚 1)3.3V PWR (Pin 1) 白线White cable
GND(引脚 7G)GND (Pin 7G) GND(引脚 6)GND (Pin 6) 棕色电缆Brown cable
SDI(引脚 10G)SDI (Pin 10G) I2C1 SDA(引脚 3)I2C1 SDA (Pin 3) 红线Red cable
SCK(引脚 8G)SCK (Pin 8G) I2C1 SCL(引脚 5)I2C1 SCL (Pin 5) 橙色电缆Orange cable
LED VDD(引脚 18F)LED VDD (Pin 18F) GPIO 24(引脚 18)GPIO 24 (Pin 18) 白线White cable
LED GND(引脚 17F)LED GND (Pin 17F) GND(引脚 20)GND (Pin 20) 黑线Black cable

单击以查看 Raspberry Pi 2 和 3 引脚映射以供参考。Click to view Raspberry Pi 2 & 3 pin mappings for your reference.

成功将 BME280 连接到 Raspberry Pi 后,它应如下图所示。After you've successfully connected BME280 to your Raspberry Pi, it should be like below image.

连接在一起的 Pi 和 BME280

将 Pi 连接到网络Connect Pi to the network

使用 USB 微电缆和电源开启 Pi。Turn on Pi by using the micro USB cable and the power supply. 使用以太网电缆将 Pi 连接到有线网络,或者按照 Raspberry Pi Foundation 中的说明将 Pi 连接到无线网络。Use the Ethernet cable to connect Pi to your wired network or follow the instructions from the Raspberry Pi Foundation to connect Pi to your wireless network. 将 Pi 成功连接到网络后,需要记下 Pi 的 IP 地址After your Pi has been successfully connected to the network, you need to take a note of the IP address of your Pi.



确保 Pi 与计算机连接到同一网络。Make sure that Pi is connected to the same network as your computer. 例如,如果计算机连接到无线网络,而 Pi 连接到有线网络,则可能看不到 devdisco 输出中的 IP 地址。For example, if your computer is connected to a wireless network while Pi is connected to a wired network, you might not see the IP address in the devdisco output.

在 Pi 上运行示例应用程序Run a sample application on Pi

克隆示例应用程序,并安装必备组件包Clone sample application and install the prerequisite packages

  1. 从主计算机使用下列 SSH 客户端之一连接到 Raspberry Pi:Connect to your Raspberry Pi with one of the following SSH clients from your host computer:

    Windows 用户Windows Users

    a.a. 下载并安装 PuTTY for Windows。Download and install PuTTY for Windows.

    b.b. 将 Pi 的 IP 地址复制到主机名(或 IP 地址)部分,并选择 SSH 作为连接类型。Copy the IP address of your Pi into the Host name (or IP address) section and select SSH as the connection type.


    Mac 和 Ubuntu 用户Mac and Ubuntu Users

    使用 Ubuntu 或 macOS 上的内置 SSH 客户端。Use the built-in SSH client on Ubuntu or macOS. 可能需要运行 ssh pi@<ip address of pi>,以通过 SSH 连接 Pi。You might need to run ssh pi@<ip address of pi> to connect Pi via SSH.


    默认用户名是 pi,密码是 raspberryThe default username is pi and the password is raspberry.

  2. 将 Node.js 和 NPM 安装到 Pi。Install Node.js and NPM to your Pi.

    首先检查 Node.js 版本。First check your Node.js version.

    node -v

    如果版本低于 10.x,或者 Pi 上没有 Node.js,请安装最新版本。If the version is lower than 10.x, or if there is no Node.js on your Pi, install the latest version.

    curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash
    sudo apt-get -y install nodejs
  3. 克隆示例应用程序。Clone the sample application.

    git clone https://github.com/Azure-Samples/azure-iot-samples-node.git
  4. 安装示例的所有程序包。Install all packages for the sample. 安装包括 Azure IoT 设备 SDK、BME280 传感器库和接线 Pi 库。The installation includes Azure IoT device SDK, BME280 Sensor library, and Wiring Pi library.

    cd azure-iot-samples-node/iot-hub/Tutorials/RaspberryPiApp
    npm install


    完成此安装过程可能需要几分钟,具体取决于网络连接情况。It might take several minutes to finish this installation process depending on your network connection.

配置示例应用程序Configure the sample application

  1. 通过运行以下命令,打开配置文件:Open the config file by running the following commands:

    nano config.json


    此文件中有两个可以配置的项。There are two items in this file you can configure. 第一个是 interval,它定义发送到云的消息之间的时间间隔(以毫秒为单位)。The first one is interval, which defines the time interval (in milliseconds) between messages sent to the cloud. 第二个是 simulatedData,它是一个布尔值,指示是否使用模拟的传感器数据。The second one is simulatedData, which is a Boolean value for whether to use simulated sensor data or not.

    如果没有传感器,请将 simulatedData 值设置为 true,使示例应用程序创建和使用模拟的传感器数据。If you don't have the sensor, set the simulatedData value to true to make the sample application create and use simulated sensor data.

    注意:默认情况下,本教程中使用的 i2c 地址为 0x77。根据配置,它也可能是 0x76:如果遇到 i2c 错误,请尝试将该值更改为 118,然后看看效果是否更好。若要查看传感器使用的地址,请在 raspberry pi 上的 shell 中运行 sudo i2cdetect -y 1Note: The i2c address used in this tutorial is 0x77 by default. Depending on your configuration it might also be 0x76: if you encounter an i2c error, try to change the value to 118 and see if that works better. To see what address is used by your sensor, run sudo i2cdetect -y 1 in a shell on the raspberry pi

  2. 通过按“Ctrl-O”>“Enter”>“Ctrl-X”保存并退出。Save and exit by typing Control-O > Enter > Control-X.

运行示例应用程序Run the sample application

通过运行以下命令,生成示例应用程序:Run the sample application by running the following command:



确保将设备连接字符串复制并粘贴到单引号中。Make sure you copy-paste the device connection string into the single quotes.

应看到以下输出,其中显示传感器数据以及发送至 IoT 中心的消息。You should see the following output that shows the sensor data and the messages that are sent to your IoT hub.

输出 - 从 Raspberry Pi 发送到 IoT 中心的传感器数据

读取 IoT 中心收到的消息Read the messages received by your hub

若要监视 IoT 中心从设备收到的消息,一种方法是使用适用于 Visual Studio Code 的 Azure IoT Tools。One way to monitor messages received by your IoT hub from your device is to use the Azure IoT Tools for Visual Studio Code. 若要了解详细信息,请参阅使用适用于 Visual Studio Code 的 Azure IoT Tools 在设备和 IoT 中心之间发送和接收消息To learn more, see Use Azure IoT Tools for Visual Studio Code to send and receive messages between your device and IoT Hub.

若要了解如何通过更多方式来处理设备发送的数据,请转到下一部分。For more ways to process data sent by your device, continue on to the next section.

后续步骤Next steps

此时已运行示例应用程序,收集传感器数据并将其发送到 IoT 中心。You’ve run a sample application to collect sensor data and send it to your IoT hub.

若要继续了解 Azure IoT 中心入门知识并浏览所有扩展的 IoT 方案,请参阅:To continue to get started with Azure IoT Hub and to explore all extended IoT scenarios, see the following: