Connecting Raspberry Pi with Grove Base Hat to ThingsBoard


ThingsBoard Community Edition is an open-source server-side platform that allows you to monitor and control IoT devices. It is free for both personal and commercial usage and you can deploy it anywhere. If you are not familiar with the platform yet, we recommend to review what is thingsboard page and getting started guide at first and then proceed with this tutorial. Within this guide we use

This sample application will allow you to collect information from sensors and control Servo, Led of your Raspberry Pi device with Grove Base Hat PCB using ThingsBoard web UI. The purpose of this application is to demonstrate ThingsBoard and Grove Base Hat PCB integrations.

Raspberry Pi will use simple application written in Python for connecting to ThingsBoard server via MQTT, sending information from sensors and listening to RPC commands. ThingsBoard built-in dashboards will be used for data visualizing and controlling Servo and Led as well.

At the end we will get the following result:


For the purpose of this tutorial you need ThingsBoard server up and running. Within this guide we use

Hardware and pinouts:

Raspberry Pi 3 model B (You can also use Raspberry Pi 4)

Grove Base Hat

In our case we connect following modules:


Wiring scheme

We use following wiring scheme:

Module                              Pinouts on Grove Base Hat
Analog Servo                        PWM(12)
Mini PIR Motion Sensor v1.0         D5
Ultrasonic ranger v2.0              D16
RED Led Button v1.0                 D18
Moisture Sensor v1.4                A0
Light sensor v1.2                   A2
Temperature&Humidity Sensor v1.2    D22

Programming the Raspberry Pi

By first we need to configure the Raspberry Pi. Please follow this article.

After the configuration we need to install libraries used in the script to the Raspberry Pi.

The following command will install thingsboard python client sdk, it is used for communication with ThingsBoard server:

pip3 install tb-mqtt-client

Also we need to install Seeed-Studio library to be able to connect our modules:

git clone
pip3 install ./

At last if you use Temperature and Humidity sensor (DHTXX), you also need to install the Library for Temperature and Humidity Sensor:

git clone
sudo python3 ./Seeed_Python_DHT/ install

Application source code

Our application consists of a single python script that is well documented. You will need to modify THINGSBOARD_HOST constant to match your ThingsBoard server installation IP address or hostname.

Also we need say to ThingsBoard that we want to connect this device and get the device ACCESS_TOKEN, which will be used in the script. Log in to your environmentDevice groupsAdd device groupAdd new device (e.g. Device 1 with type grove) — Open device detailsCopy access token.


After this you need to replace the THINGSBOARD_HOST and ACCESS_TOKEN in the script below, with your values. In case you use Live demo, populate as THINGSBOARD_HOST

import logging
import time
from tb_device_mqtt import TBDeviceMqttClient, TBPublishInfo
from grove.grove_mini_pir_motion_sensor import GroveMiniPIRMotionSensor
from grove.grove_ultrasonic_ranger import GroveUltrasonicRanger
from Seeed_Python_DHT.seeed_dht import DHT
from grove.grove_moisture_sensor import GroveMoistureSensor
from grove.button import Button
from grove.grove_ryb_led_button import GroveLedButton
from grove.grove_light_sensor_v1_2 import GroveLightSensor
from grove.grove_servo import GroveServo

# Configuration of logger, in this case it will send messages to console
                    format='%(asctime)s - %(levelname)s - %(module)s - %(lineno)d - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

log = logging.getLogger(__name__)

thingsboard_server = 'THINGSBOARD_HOST'
access_token = 'ACCESS_TOKEN'

def main():

    # Grove - Servo connected to PWM port
    servo = GroveServo(12)
    servo_angle = 90
    # Grove - mini PIR motion pir_sensor connected to port D5
    pir_sensor = GroveMiniPIRMotionSensor(5)

    # Grove - Ultrasonic Ranger connected to port D16
    ultrasonic_sensor = GroveUltrasonicRanger(16)

    # Grove - LED Button connected to port D18
    button = GroveLedButton(18)

    # Grove - Moisture Sensor connected to port A0
    moisture_sensor = GroveMoistureSensor(0)

    # Grove - Light Sensor connected to port A2
    light_sensor = GroveLightSensor(2)
    light_state = False

    # Grove - Temperature&Humidity Sensor connected to port D22
    dht_sensor = DHT('11', 22)

    # Callback for server RPC requests (Used for control servo and led blink)
    def on_server_side_rpc_request(request_id, request_body):'received rpc: {}, {}'.format(request_id, request_body))
        if request_body['method'] == 'getLedState':
            client.send_rpc_reply(request_id, light_state)
        elif request_body['method'] == 'setLedState':
            light_state = request_body['params']
        elif request_body['method'] == 'setServoAngle':
            servo_angle = float(request_body['params'])
        elif request_body['method'] == 'getServoAngle':
            client.send_rpc_reply(request_id, servo_angle)

    # Connecting to ThingsBoard
    client = TBDeviceMqttClient(thingsboard_server, access_token)

    # Callback on detect the motion from motion sensor
    def on_detect():'motion detected')
        telemetry = {"motion": True}
        # Deactivating the motion in Dashboard
        client.send_telemetry({"motion": False})"Motion alert deactivated")

    # Callback from button if it was pressed or unpressed
    def on_event(index, event, tm):
        if button._GroveLedButton__btn.is_pressed():
            log.debug('button: single click')
            telemetry = {"button_press": True}
            log.debug('button: single click')
            telemetry = {"button_press": False}
        if event & Button.EV_SINGLE_CLICK:
        elif event & Button.EV_DOUBLE_CLICK:
        elif event & Button.EV_LONG_PRESS:

    # Adding the callback to the motion sensor
    pir_sensor.on_detect = on_detect
    # Adding the callback to the button
    button.on_event = on_event
        while True:
            distance = ultrasonic_sensor.get_distance()
            log.debug('distance: {} cm'.format(distance))

            humidity, temperature =
            log.debug('temperature: {}C, humidity: {}%'.format(temperature, humidity))

            moisture = moisture_sensor.moisture
            log.debug('moisture: {}'.format(moisture))

            log.debug('light: {}'.format(light_sensor.light))

            # Formatting the data for sending to ThingsBoard
            telemetry = {'distance': distance,
                         'temperature': temperature,
                         'humidity': humidity,
                         'moisture': moisture,
                         'light': light_sensor.light}

            # Sending the data

    except Exception as e:
        raise e

if __name__ == '__main__':

Data Visualization and Control

To configure dashboard you should login into ThingsBoard environment.

To proceed with this step, please download a grove_seeed_studio.json file, which contains preconfigured dashboard for this script. Once logged in, open Dashboards, click on the plus button in the bottom right corner of the screen and select the “Import dashboard” icon. Select recently downloaded file of dashboard configuration. Now you must edit the alias of Grove widget you should do this by pressing on the pen icon. Select the Filter type parameter as “Single entity”, set Type as “Device” and from the list of devices - select your GROVE device.

Running the application

This simple command will launch the application:


The results of script running - you can see on the dashboard.


Also from dashboard you can control the servo (by rotating the knob control with name “Servo”) or the led (by pressing the trigger “Button Led”).

See Also

Browse other samples or explore guides related to main ThingsBoard features:

Your feedback

Don’t hesitate to star ThingsBoard on github to help us spread the word. If you have any questions about this sample - post it on the issues.

Next steps

  • 入门指南 - 这些指南提供了ThingsBoard主要功能的快速概述。

  • 安装指南 - 了解如何在各种操作系统上安装ThingsBoard。

  • 设备连接 - 了解如何根据您的连接方式或解决方案连接设备。

  • 数据看板 - 这些指南包含有关如何配置复杂的ThingsBoard仪表板的说明。

  • 数据处理 - 了解如何使用ThingsBoard规则引擎。

  • 数据分析 - 了解如何使用规则引擎执行基本的分析任务。

  • 高级功能 - 了解高级ThingsBoard功能。

  • 开发指南 - 了解ThingsBoard中的贡献和开发。