Mission10_Humiture_Sensor
In the previous mission, you learn about the LCD. Now you're going to know more about it. The LCD will be used to show the temperature in your room.
What you need​
The parts you will use are all included in the Maker kit.
- SwiftIO board
- Shield
- Humiture sensor
- 16x2 LCD
- 4-pin cable
Circuit​
Place the shield on top of the SwiftIO board.
Connect the humiture sensor and the LCD to the I2C0. There are three available pins, you could choose any two.

Example code​
// Import the SwiftIO library to use everything in it.
import SwiftIO
// Import the board library to use the Id of the specific board.
import MadBoard
// Initialize the LCD and sensor to use the I2C communication.
let i2c = I2C(Id.I2C0)
let lcd = LCD1602(i2c)
let sht = SHT3x(i2c)
while true{
// Read and display the temperature on the LCD and update the value every second.
let temp = sht.readCelsius()
lcd.write(x:0, y:0, "Temperature:")
lcd.write(x: 0, y: 1, temp)
lcd.write(x:4, y:1, " ")
lcd.write(x:5, y:1, "C")
sleep(ms: 1000)
}
Background​
Humiture sensor​
The humiture sensor can sense the temperature and humidity at the same time. This one uses the I2C protocol to communicate with the SwiftIO board. You can find a file SHT3x.swift
in this mission that you can use to read the values.
Code analysis​
In this project, there is the file LCD1602.swift
for the LCD and the file SHT3x.swift
for the sensor. You can directly use them to simplify your code and don't need to configure them according to their datasheet.
So let's come to the file main.swift
.
import SwiftIO
import MadBoard
Import the necessary libraries: SwiftIO and SwiftIOBoard. SwiftIO is used to control the input and output of the SwiftIO board. SwiftIOBoard defines the pin name of the board.
let i2c = I2C(Id.I2C0)
let lcd = LCD1602(i2c)
let sht = SHT3x(i2c)
Initialize the I2C interface I2C0. Then initialize the LCD and the sensor. Both of them need the I2C interface as their parameter.
let temp = sht.readCelsius()
To get the temperature, you need the method readCelsius()
in the file SHT3x.swift
. It will calculate the temperature into Celsius.
lcd.write(x:0, y:0, "Temperature:")
lcd.write(x: 0, y: 1, temp)
lcd.write(x:4, y:1, " ")
lcd.write(x:5, y:1, "C")
As you get the value, you can display it on the LCD. The four statements are all about the content to be displayed:
- The first row of the LCD will display the text "Temperature:". It starts from the origin.
- The temperature displays on the second row from the first column. They will take up four characters.
- The fifth is blank to separate the value from the unit.
- The sixth is the unit.

sleep(ms: 1000)
The sensor will read value every 1s, so the value on the LCD will refresh per second.
Reference​
I2C - use I2C protocol to communicate with other devices.
SwiftIOBoard - find the corresponding pin id of SwiftIO board.