# Get Started with the Raspberry Pi

This tutorial will help you use a KORE Programmable Wireless SIM to build and run your first IoT application. The device you'll build uses a [Waveshare SIM7600G-H 4G Hat](https://www.waveshare.com/wiki/SIM7600G-H_4G_HAT), a development board which equips a low-cost Raspberry Pi computer with a Simcom 7600G-H cellular modem.

<figure><img src="https://3566848590-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F9p1Cs774U7DhQF5Pc3aj%2Fuploads%2FSAX28QkF8zHNrvRaSmra%2FRaspberry.webp?alt=media&#x26;token=74b5ac38-c706-4b6a-9a1b-a32ab413868c" alt=""><figcaption></figcaption></figure>

***

## The hardware

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

* A Waveshare [SIM7600G-H 4G HAT](https://www.waveshare.com/wiki/SIM7600G-H_4G_HAT) . This is the global version; there are [variants](https://www.waveshare.com/wiki/Main_Page#Wireless_Communication) that target specific territories.
* A [Raspberry Pi](https://www.raspberrypi.org/products/raspberry-pi-4-model-b/). This guide was written using the Pi 4 Model B, but there are other versions of the Pi available — it should work with any of them, but we've only tested the 4. The SIM7600G-H 4G Hat works with all but the very first Pi. To use the Pi, you will also need:
  * A Micro SD card of 8GB or above.
  * A monitor and an HDMI-to-micro-HDMI cable.
  * A keyboard and a mouse
  * A 5V, 2A (10W) USB-C AC adaptor.
* An [MCP9808 temperature sensor on a breakout board](https://www.adafruit.com/product/1782).
  * You'll need to solder the supplied header pins to the breakout board.
* Four female-to-female jumper wires.

### Hardware setup: the Raspberry Pi

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](https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up) 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.

<figure><img src="https://3566848590-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F9p1Cs774U7DhQF5Pc3aj%2Fuploads%2FemSsMUg1jPPzO8J2tBhq%2FRaspberry_2.webp?alt=media&#x26;token=503fca96-5c45-4f64-af27-2153928c6e34" alt=""><figcaption></figcaption></figure>

{% hint style="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.
{% endhint %}

### Hardware setup: the SIM7600G-H 4G Hat

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 KORE 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:

   <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2Fe795d6adc657cc49ef7e25df824b478d51a64c0e69722ae9e1d029534446de40.jpg&#x26;w=3840&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>

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

   <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F414c7e809e68aced7328cf5b30a2815f46c46154b78b228a01dcf87f81d608a6.jpg&#x26;w=3840&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>
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**&#x20;
   * 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:

   <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F7a101677d15ee85d8a05ed5c108ed9649e19119e5773f6637cee96e1341773c0.jpg&#x26;w=3840&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>
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:

   <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F32c2e50f47f43b4f694cb65c0dc779f55a8c6bd2cd492b2da922a687e4ebe00f.jpg&#x26;w=3840&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>
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:

   Here's a close-up:

   <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F84435001bc31d9c3cb576db6f0c0929134e762a30c5ed836cc1dcaa60f35749d.jpg&#x26;w=3840&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>

   <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F808cdef879185fb3ba1a4616cbd7cfb6f26131a167e7737b5c653b1eb0aa7e0c.jpg&#x26;w=3840&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>
6. Finally, power up the Pi by re-inserting the power cable.

***

## Software setup

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 <a href="#id-1-configure-pi-serial-port-access" id="id-1-configure-pi-serial-port-access"></a>

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**:

   <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F72c7eae812a8bcd73e912a2d197518c22c28c7e9f6b862681ef33cb7385842f9.png&#x26;w=1920&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>
4. Now highlight **Serial Port** and hit **Enter**:

   <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F114e1bf1befbb113072d31c1e561f522b4f27aeb7819242c6546775084e7bcb6.png&#x26;w=1920&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>
5. When you are asked **Would you like a login shell to be accessible over serial?** select **No** and hit **Enter**:

   <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F35db88793d0a47e223e1bc8bbeb027a941f17e84a7fd8e5243b464fc5ef64eaf.png&#x26;w=1920&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>
6. When you are asked **Would you like the serial port hardware to be enabled?** select **Yes** and hit **Enter**:

   <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F160a9386c8f9c2b09c3bed46cb874c8a620bca4610c5efab2adc09552d7fc6da.png&#x26;w=1920&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>
7. Select **Finish** .
8. The `raspi-config` utility will offer to restart the Pi — accept its suggestion.

#### 2. Power up the Hat <a href="#id-2-power-up-the-hat" id="id-2-power-up-the-hat"></a>

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:

```bash
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 <a href="#id-3-connect-to-the-internet" id="id-3-connect-to-the-internet"></a>

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:

```bash
sudo apt install ppp -y
sudo cp /etc/ppp/peers/provider /etc/ppp/peers/provider.bak
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:

```bash
nocrtscts
debug
nodetach
ipcp-accept-local
ipcp-accept-remote
```

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

```bash
connect '/usr/sbin/chat -s -v -f /etc/chatscripts/gprs -T programmable-wireless.api.korewireless.com'
```

```bash
/dev/ttyUSB2
```

The last line comes from [the value you determined earlier](#id-2-power-up-the-hat).

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

```bash
sudo pon
```

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

Open a fresh terminal and enter:

```bash
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`:

  <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F5ede1a43a0df4c21b6eb170ad7038cbe2d42c100272a712ee01a4892bfe6b2be.png&#x26;w=1920&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>
* Open up a browser and navigate to **korewireless.com**:

  <figure><img src="https://3566848590-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F9p1Cs774U7DhQF5Pc3aj%2Fuploads%2Fb3hBsA0lDIbOtgyGQ7GY%2Fimage.png?alt=media&#x26;token=93e6da65-092a-4a82-9415-b14ce708d861" alt=""><figcaption></figcaption></figure>

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.

***

### Build an MQTT app <a href="#build-an-mqtt-app" id="build-an-mqtt-app"></a>

With the hardware working, you're ready to build your first IoT application. You'll be using a technology called [MQTT](https://en.wikipedia.org/wiki/MQTT) 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 <a href="#id-1-set-up-an-mqtt-broker" id="id-1-set-up-an-mqtt-broker"></a>

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](https://github.com/mqtt/mqtt.github.io/wiki/public_brokers).

{% hint style="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.
{% endhint %}

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](http://www.hivemq.com/demos/websocket-client/) .
2. Click the **Connect** button:

   <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F611ad335e78d63eb5e3dd585b6e595528751e9189a08284f4df85488282644ee.png&#x26;w=1920&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>
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:

   <figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F458c9543611d8e505d6137e6f42e0c3d51894a93927913141271e25ffa8a4f38.png&#x26;w=1200&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>
5. Click **Subscribe** .

#### 2. Prepare the Raspberry Pi <a href="#id-2-prepare-the-raspberry-pi" id="id-2-prepare-the-raspberry-pi"></a>

1. On the Raspberry Pi, run the following command in a Terminal window or at the command line:

   ```bash
   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:   &#x20;

   <pre class="language-python" data-full-width="true"><code class="lang-python">##############################################
   # KORE MQTT Demo for Programmable Wireless #
   ##############################################
   from time import sleep
   from sys import exit
   from smbus import SMBus
   import json
   import paho.mqtt.client as mqtt

   ##############################################
   # Global variables                           #
   ##############################################
   # EDIT THESE
   MQTT_CLIENT_ID = "SOME_RANDOM_STRING"
   MQTT_PUBLISH_TOPIC = "SOME_RANDOM_STRING/info"
   MQTT_ADDRESS = "broker.hivemq.com"
   MQTT_BROKER_PORT = 1883
   MQTT_USERNAME = "YOUR_USERNAME"
   MQTT_PASSWORD = "YOUR_PASSWORD"

   ##############################################
   # MCP9808 driver                             #
   ##############################################
   MCP9808_I2CADDR_DEFAULT = 0x18
   MCP9808_REG_CONFIG = 0x01
   MCP9808_REG_AMBIENT_TEMP = 0x05
   MCP9808_REG_MANUF_ID = 0x06
   MCP9808_REG_DEVICE_ID = 0x07

   class MCP9808(object):
       def __init__(self, address=MCP9808_I2CADDR_DEFAULT, bus=None):
           self.address = address
           if bus: self.bus = SMBus(bus)

       def check(self):
           # Check we can read correct Manufacturer ID and Device ID values
           try:
               mid_data = self.bus.read_i2c_block_data(self.address, MCP9808_REG_MANUF_ID, 2)
               did_data = self.bus.read_i2c_block_data(self.address, MCP9808_REG_DEVICE_ID, 2)
               mid_value = (mid_data[0] &#x3C;&#x3C; 8) | mid_data[1]
               did_value = (did_data[0] &#x3C;&#x3C; 8) | did_data[1]
               return (mid_value == 0x0054 and did_value == 0x0400)
           except:
               return False

       def read(self):
           # Get the ambient temperature
           temp_data = self.bus.read_i2c_block_data(self.address, MCP9808_REG_AMBIENT_TEMP, 2)

           # Scale and convert to signed Celsius value.
           temp_raw = (temp_data[0] &#x3C;&#x3C; 8) | temp_data[1]
           temp_cel = (temp_raw &#x26; 0x0FFF) / 16.0
           if temp_raw &#x26; 0x1000: temp_cel -= 256.0
           return temp_cel

   ##############################################
   # The main application code                  #
   ##############################################
   def app_loop():
       tx_count = 1
       try:
           # Setup the temperature sensor
           sensor = MCP9808(bus=1)
           sensor_state = sensor.check()
           if sensor_state is False:
               print("[ERROR] No MCP9808 attached")
               exit(1)

           #  Main application loop
           while True:
               temp = sensor.read()
               print("{}. Ambient temperature is {:.02f} celsius".format(tx_count, temp))
               tx_count +=1

               # Craft a message to the cloud
               msg_formatted = json.dumps({
                   'device_id': MQTT_CLIENT_ID + "-device",
                   'temperature': temp,
                   'units': 'celsius',
                   'shenanigans': "none"
               })

               # Publish the message by MQTT
               client.publish(MQTT_PUBLISH_TOPIC, msg_formatted)

               # Loop every minute
               sleep(60)
       except KeyboardInterrupt:
           print(" MQTT Demo 1for Programmable Wireless stopped")
       except OSError:
           print("[ERROR] Cannot read sensor, check connection")

   ##############################################
   # Called from the command line               #
   ##############################################
   if __name__ == '__main__':
       print ("Starting MQTT Demo 1 for Programmable Wireless")

       # Setup MQTT
       client = mqtt.Client("KORE DEMO 1")
       client.username_pw_set(MQTT_USERNAME, password=MQTT_PASSWORD)
       client.connect(MQTT_ADDRESS, MQTT_BROKER_PORT, 60)
       client.loop_start()

       # Run the main loop
       app_loop()

   </code></pre>

   &#x20;                                     &#x20;
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 <a href="#id-3-fit-the-mcp9808-temperature-sensor" id="id-3-fit-the-mcp9808-temperature-sensor"></a>

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 Pin | Pi Pin         |
| ----------- | -------------- |
| VDD         | Pin 1: 3V3     |
| GND         | Any GND        |
| SCL         | Pin 5: I2C SCL |
| SDA         | Pin 3: I2C SDA |

<figure><img src="https://www.twilio.com/_next/image?url=https%3A%2F%2Fdocs-assets.prod.twilio.com%2F9b0837b2e76d869266c5d85ccbe50868d0427b823518b33404291391053538d7.png&#x26;w=1920&#x26;q=75&#x26;dpl=dpl_AuqPDm9XSGrvUpZmSvuw94WG442g" alt=""><figcaption></figcaption></figure>

#### 4. Begin sending data <a href="#id-4-begin-sending-data" id="id-4-begin-sending-data"></a>

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](http://www.hivemq.com/demos/websocket-client/)

***

### Next steps <a href="#next-steps" id="next-steps"></a>

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](https://github.com/korewireless/prog-wireless-raspberry-pi-demos/blob/main/mqtt/mqtt_subscribe.py) .
  * 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.
