IoT Tutorial: Room Temperature Sensors From A Raspberry Pi, Using Go
@jeremymorganjeremymorgan Tech blogger, author, overall geek. Love tech and love writing about it. In this tutorial, I’ll show you how to grab temperature from a Raspberry Pi and build an endpoint to store the data, with Go. You will learn: How to retrieve the temperature from a sensor How to send that data in JSON Build an API endpoint to receive it Store the data in SQLite database And we’ll do it all with Go. I did a live stream of the entire process that you can watch here. What You’ll Need for This Tutorial A Raspberry Pi (any model should work) An AM2302 (Wired DHT22) sensor A Linux Host (I’m using an Amazon LightSail FreeBSD Server) I’m using Pop!_OS to develop on, but you can use anything you’d like. Why Are We Doing This? I’ve previously written a tutorial to grab room temperature from a Raspberry Pi, and it’s very similar, only using Python. This is another “hand-rolled” tutorial. Why are we doing this by hand? Why not use a cloud service? The purpose of this tutorial is to give you a deep understanding of IoT and how it works. You can easily use a cloud provider such as: AWS IoT Azure IoT Edge Google Cloud IoT Core These services are great. They’re awesome. If you’re building a real project or working on IoT professionally, this is the way to go. They provide excellent secure services and handle so many things for you. That’s great, but if you want to truly learn IoT you need to get down to the nuts and bolts. The cloud services have clients you configure, and you push the data up, and it’s visualized for you. In this tutorial, we’re going to build all that stuff ourselves and understand it. Let’s Rock and Roll! Connect the Temperature Sensor The sensor will have three wires coming out from it and will need to be connected to the GPIO of the Raspberry Pi, as shown above. There is a red power wire that goes to pin 1.The black wire is ground and goes to pin 6.The orange (sometimes yellow or white) is data and goes to Pin 11. Read the Temperature Sensor We’re going to create a Go file on the Raspberry Pi to read the temperature from the sensor. I named it readsensor.go. Next, you need to install the Go-DHT libraries from this repo. go get github.com/MichaelS11/go-dht This is a library I like to use because it’s incredibly simple and has worked reliably for me. First, let’s just verify the functionality of the sensor. Let’s build our file from the top. Add the following to the header: “github.com/MichaelS11/go-dht” This will pull in the Go-DHT package and fmt to format the output. Next, I’ll create a CONST to set the GPIO. Pin 11 is GPIO 17. You can use other GPIO pins if you like. Next, we need to do three things for the temperature sensor: Initialize the GPIO Host Create a new DHT reader Read it So in our main func, » Read More
Like to keep reading?
This article first appeared on hackernoon.com. If you'd like to keep reading, follow the white rabbit.