Skip to contentSkip to navigationSkip to topbar
On this page

Get Started with Programmable Wireless, the Raspberry Pi 4 and the Waveshare 4G Hat


This tutorial will help you use a Twilio Programmable Wireless SIM to build and run your first IoT application. The device you'll build uses a Waveshare SIM7600G-H 4G Hat(link takes you to an external page), a development board which equips a low-cost Raspberry Pi computer with a Simcom 7600G-H cellular modem.

The Waveshare SIM7600G-H 4G Hat.

The hardware

the-hardware page anchor

In addition to your configured Programmable Wireless SIM, you will need the following hardware to proceed with this guide:

Hardware setup: the Raspberry Pi

hardware-setup-the-raspberry-pi page anchor

The Raspberry Pi has its own setup procedure which involves downloading and installing its Linux operating system, called Raspberry Pi OS, onto the Micro SD card. The Raspberry Pi Foundation has a very good walkthrough(link takes you to an external page) of its own that covers this process — you should use this to get your Pi ready before proceeding to the next stage of this guide.

(information)

Info

During setup you should connect your Pi 4 to your WiFi network as you will need to download extra software later. We'll disable WiFi in due course to demonstrate data access over cellular.

Hardware setup: the SIM7600G-H 4G Hat

hardware-setup-the-sim7600g-h-4g-hat page anchor

The SIM7600G-H 4G Hat ships with all you need to fit it onto the Pi. Just follow these steps to set everything up:

  1. Fit your Twilio SIM into the SIM7600G-H 4G Hat's SIM retainer. This takes a full-size SIM, so take care removing your SIM from its mount, or use an adapter if you have already removed the SIM as a Micro or Nano SIM:

    Open the Hat's SIM retainer to add your SIM.

    Lock the SIM retainer in place to keep the Twilio SIM secure:

    Lock the SIM retainer in place to keep the Twilio SIM secure.
  2. If it's powered up, turn off the Pi.

    • If you're at the command line, enter sudo shutdown -h now.
    • If you're at the desktop, select Shutdown… from the Raspberry menu and then click Shutdown .
    • Remove the power cable when the Pi's activity LED has flashed ten times.
  3. Slot the SIM7600G-H 4G Hat onto the Pi's GPIO header:

    Fit the Hat onto the Pi GPIO pins.
  4. Connect the supplied USB cable to the micro USB port marked just USB on the SIM7600G-H 4G Hat and a USB port on the Pi:

    Connect the USB cable.
  5. Assemble the bundled cellular antenna and connect it to the SIM7600G-H 4G Hat. Fit it to the LTE connector marked MAIN on the board:

    Connect the antenna to the Hat.

    Here's a close-up:

    Use the connector marked main.
  6. Finally, power up the Pi by re-inserting the power cable.

We now need to run through a few steps to get the Pi ready to talk to the SIM7600G-H 4G Hat. Some of these will require you to restart the Pi.

1. Configure Pi serial port access

1-configure-pi-serial-port-access page anchor
  1. If you're at the Raspberry Pi desktop, select Accessories > Terminal from the Raspberry menu.
  2. Run sudo raspi-config .
  3. Use the cursor keys to highlight Interfacing Options, then hit Enter:

  4. Now highlight Serial Port and hit Enter:

  5. When you are asked Would you like a login shell to be accessible over serial? select No and hit Enter:

  6. When you are asked Would you like the serial port hardware to be enabled? select Yes and hit Enter:

  7. Select Finish .
  8. The raspi-config utility will offer to restart the Pi — accept its suggestion.

When the Pi is back up, you should see that the SIM7600G-H 4G Hat's PWR LED is lit. Now press the PWRKEY button on the board — after a brief moment, the NET LED should light up.

At the command line or in a desktop Terminal run:

ls /dev/ttyUSB*

You should see a list of items all beginning with ttyUSB and including ttyUSB2, which is the device you'll use in subsequent steps. If you don't see a list of TTYs, first check that the SIM7600G-H 4G Hat's PWR and NET LEDs are lit. Make sure your USB cable is not connected to USB TO UART on the Hat.

3. Connect to the Internet

3-connect-to-the-internet page anchor

Now you can connect to the Internet. You need to install the PPP (Point-to-Point Protocol) software the Pi will use to establish the connection, and to configure it. First run the following commands at the command line:

1
sudo apt install ppp -y
2
sudo cp /etc/ppp/peers/provider /etc/ppp/peers/provider.bak
3
sudo nano /etc/ppp/peers/provider

The last of these commands opens the primary configuration file in a text editor so you can make the required changes. Make sure the file contains the following lines. Some may be missing, others may be present depending on the version of ppp you've installed:

1
nocrtscts
2
debug
3
nodetach
4
ipcp-accept-local
5
ipcp-accept-remote

In the same file, look for lines very like these and update them so they match what's shown here:

connect '/usr/sbin/chat -s -v -f /etc/chatscripts/gprs -T wireless.twilio.com'
/dev/ttyUSB2

The last line comes from the value you determined earlier.

To initiate an Internet connection, at the command line or in a desktop terminal run:

sudo pon

You'll see a stack of lines displayed at the command line.

Open a fresh terminal and enter:

sudo route add -net "0.0.0.0" ppp0

When the prompt is back, you're ready to try out the Internet connection:

  • If you're at the desktop, select Turn off Wireless LAN from the network menu at the top right.
  • If you're at the command line, run sudo ifconfig wlan0 down .
  • At the command line or in a desktop terminal, enter ifconfig and look for the ppp0 entry — it should have a valid IP address listed under inet:

    ifconfig in the terminal.
  • Open up a browser and navigate to twilio.com/docs/iot:

    Twilio docs website.

Well done! You now have a Raspberry Pi computer that's connected to the Internet via Programmable Wireless. You can now start experimenting with cellular Internet connectivity, or begin developing your own IoT application proof-of-concept.


With the hardware working, you're ready to build your first IoT application. You'll be using a technology called MQTT(link takes you to an external page) to transmit sensor data generated by the Raspberry Pi. Picture it as an IoT device in the field relaying data back to base. That data might be the location of a shipping container, the state of a piece of machinery, or any other useful item of information that you need to track.

1. Set up an MQTT broker

1-set-up-an-mqtt-broker page anchor

To build your IoT app, you'll need an 'MQTT broker', which is the server-side system that routes messages from sources ('publishers') to receivers ('subscribers'). We're going to use HiveMQ's free MQTT broker, but there are other public MQTT brokers that you may prefer to use instead — there is a list of them here(link takes you to an external page).

(error)

Danger

HiveMQ's broker is completely open. Anyone can subscribe or publish to your topic. In production, always use encrypted communications only, and either set up your own MQTT broker or use a private broker service.

Use HiveMQ's web UI to set up the broker. You can do this on your computer, or on the Pi: just fire up a browser from the desktop.

  1. Visit HiveMQ's MQTT web client page(link takes you to an external page) .
  2. Click the Connect button:

    The HiveMQ web UI.
  3. In the Subscriptions section, click Add New Topic Subscription .
  4. Think up a topic name, make a note of it, and enter it in the Topic field. Make sure you keep the /# to the end:

    Set up an MQTT subscription.
  5. Click Subscribe .

2. Prepare the Raspberry Pi

2-prepare-the-raspberry-pi page anchor
  1. On the Raspberry Pi, run the following command in a Terminal window or at the command line:

    sudo pip paho-mqtt
  2. Open the Pi's text editor — it's in the Pi > Accessories menu — and copy the following code into a new document. You can click the copy icon at the top right of the code panel:

    1
    ##############################################
    2
    # Twilio MQTT Demo for Programmable Wireless #
    3
    ##############################################
    4
    from time import sleep
    5
    from sys import exit
    6
    from smbus import SMBus
    7
    import json
    8
    import paho.mqtt.client as mqtt
    9
    10
    ##############################################
    11
    # Global variables #
    12
    ##############################################
    13
    # EDIT THESE
    14
    MQTT_CLIENT_ID = "SOME_RANDOM_STRING"
    15
    MQTT_PUBLISH_TOPIC = "SOME_RANDOM_STRING/info"
    16
    MQTT_ADDRESS = "broker.hivemq.com"
    17
    MQTT_BROKER_PORT = 1883
    18
    MQTT_USERNAME = "YOUR_USERNAME"
    19
    MQTT_PASSWORD = "YOUR_PASSWORD"
    20
    21
    ##############################################
    22
    # MCP9808 driver #
    23
    ##############################################
    24
    MCP9808_I2CADDR_DEFAULT = 0x18
    25
    MCP9808_REG_CONFIG = 0x01
    26
    MCP9808_REG_AMBIENT_TEMP = 0x05
    27
    MCP9808_REG_MANUF_ID = 0x06
    28
    MCP9808_REG_DEVICE_ID = 0x07
    29
    30
    class MCP9808(object):
    31
    def __init__(self, address=MCP9808_I2CADDR_DEFAULT, bus=None):
    32
    self.address = address
    33
    if bus: self.bus = SMBus(bus)
    34
    35
    def check(self):
    36
    # Check we can read correct Manufacturer ID and Device ID values
    37
    try:
    38
    mid_data = self.bus.read_i2c_block_data(self.address, MCP9808_REG_MANUF_ID, 2)
    39
    did_data = self.bus.read_i2c_block_data(self.address, MCP9808_REG_DEVICE_ID, 2)
    40
    mid_value = (mid_data[0] << 8) | mid_data[1]
    41
    did_value = (did_data[0] << 8) | did_data[1]
    42
    return (mid_value == 0x0054 and did_value == 0x0400)
    43
    except:
    44
    return False
    45
    46
    def read(self):
    47
    # Get the ambient temperature
    48
    temp_data = self.bus.read_i2c_block_data(self.address, MCP9808_REG_AMBIENT_TEMP, 2)
    49
    50
    # Scale and convert to signed Celsius value.
    51
    temp_raw = (temp_data[0] << 8) | temp_data[1]
    52
    temp_cel = (temp_raw & 0x0FFF) / 16.0
    53
    if temp_raw & 0x1000: temp_cel -= 256.0
    54
    return temp_cel
    55
    56
    ##############################################
    57
    # The main application code #
    58
    ##############################################
    59
    def app_loop():
    60
    tx_count = 1
    61
    try:
    62
    # Setup the temperature sensor
    63
    sensor = MCP9808(bus=1)
    64
    sensor_state = sensor.check()
    65
    if sensor_state is False:
    66
    print("[ERROR] No MCP9808 attached")
    67
    exit(1)
    68
    69
    # Main application loop
    70
    while True:
    71
    temp = sensor.read()
    72
    print("{}. Ambient temperature is {:.02f} celsius".format(tx_count, temp))
    73
    tx_count +=1
    74
    75
    # Craft a message to the cloud
    76
    msg_formatted = json.dumps({
    77
    'device_id': MQTT_CLIENT_ID + "-device",
    78
    'temperature': temp,
    79
    'units': 'celsius',
    80
    'shenanigans': "none"
    81
    })
    82
    83
    # Publish the message by MQTT
    84
    client.publish(MQTT_PUBLISH_TOPIC, msg_formatted)
    85
    86
    # Loop every minute
    87
    sleep(60)
    88
    except KeyboardInterrupt:
    89
    print(" MQTT Demo 1for Programmable Wireless stopped")
    90
    except OSError:
    91
    print("[ERROR] Cannot read sensor, check connection")
    92
    93
    ##############################################
    94
    # Called from the command line #
    95
    ##############################################
    96
    if __name__ == '__main__':
    97
    print ("Starting MQTT Demo 1 for Programmable Wireless")
    98
    99
    # Setup MQTT
    100
    client = mqtt.Client("TWILIO DEMO 1")
    101
    client.username_pw_set(MQTT_USERNAME, password=MQTT_PASSWORD)
    102
    client.connect(MQTT_ADDRESS, MQTT_BROKER_PORT, 60)
    103
    client.loop_start()
    104
    105
    # Run the main loop
    106
    app_loop()
  3. Look for the section marked # EDIT THESE and change some of the items as follows:

    • MQTT_CLIENT_ID — Set this to the topic name you created above, replacing SOME_RANDOM_STRING .
    • MQTT_PUBLISH_TOPIC — Use the topic name, replacing SOME_RANDOM_STRING, followed by /info .
  4. Save the program in your home folder as mqtt_publish.py .

3. Fit the MCP9808 temperature sensor

3-fit-the-mcp9808-temperature-sensor page anchor

Before you run the program you need a source for the data you'll send. This is where the MCP9808 temperature sensor comes in. You should already have soldered header pins to the small sensor board, so you can now connect the board to the Pi according to the diagram below. The Waveshare modem has pins that extend the Pi's own IO pins, so you can just wire the sensor direct to the modem board. The outer row of pins have even numbers, the inner pins odd numbers, both starting at the end closest to the Waveshare LEDs.

MCP9808 PinPi Pin
VDDPin 1: 3V3
GNDAny GND
SCLPin 5: I2C SCL
SDAPin 3: I2C SDA
Connect the MCP9808 to the Pi via the Waveshare modem board.

On the Raspberry Pi, switch to the terminal window and run the program with python mqtt_publish.py.

Switch back to the browser window or tab showing the HiveMQ MQTT broker interface. You should see messages being logged every 60 seconds — the messages currently being sent by your Pi over the cellular network!

If you're getting errors on the Pi side, check you have correctly connected up the sensor. You should also check you have your topic names and subscription set correctly in the mqtt_publish.py file and on HiveMQ(link takes you to an external page)


Your Raspberry Pi and Waveshare SIM7600G-H 4G Hat are now able to access the cellular network, and you've built a basic IoT application using MQTT messaging on top of them. Now it's over to you: what are you going to build? We can't wait to find out.

Here are some suggestions for things to try:

  • Explore sending MQTT messages back to the Pi. The Pi can subscribe to messages published by the broker — the opposite of the process outlined above — and incorporate logic that reacts to message contents: perhaps switch the reported temperature from Celsius to Fahrenheit.
    • You can find an updated version of the code you worked with above in our GitHub repo(link takes you to an external page) .
    • In the HiveMQ MQTT broker interface, under Publish , you'll need to set the topic name with /state at the end and add a message, {"units":"fahrenheit"} , to send when you click the Publish button. Make sure mqtt_subscribe.py is running on your Pi when you do.
  • Check out our guide Introduction to AT commands and try sending to your modem some of the more useful commands it lists.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.