Bird
0
0
Arduinoprogramming~30 mins

Reading I2C sensor data in Arduino - Mini Project: Build & Apply

Choose your learning style9 modes available
Reading I2C sensor data
📖 Scenario: You have a temperature sensor connected to your Arduino using the I2C communication protocol. You want to read the temperature data from the sensor and display it on the Serial Monitor.
🎯 Goal: Build a simple Arduino program that reads temperature data from an I2C sensor and prints the temperature value to the Serial Monitor.
📋 What You'll Learn
Use the Wire library to communicate over I2C
Initialize the I2C communication in the setup() function
Read two bytes of data from the sensor at I2C address 0x48
Combine the two bytes into a temperature value
Print the temperature value to the Serial Monitor
💡 Why This Matters
🌍 Real World
Reading sensor data over I2C is common in projects like weather stations, home automation, and robotics.
💼 Career
Understanding I2C communication and sensor data reading is essential for embedded systems and hardware programming jobs.
Progress0 / 4 steps
1
Setup I2C communication and sensor address
Include the Wire.h library and create a constant byte variable called sensorAddress with the value 0x48.
Arduino
Hint

Use #include <Wire.h> to include the I2C library. Define sensorAddress as const byte sensorAddress = 0x48;.

2
Initialize I2C and Serial communication
In the setup() function, start the I2C communication with Wire.begin() and start Serial communication at 9600 baud with Serial.begin(9600).
Arduino
Hint

Use Wire.begin() to start I2C and Serial.begin(9600) to start serial communication.

3
Read two bytes from the sensor
In the loop() function, request 2 bytes from the sensor using Wire.requestFrom(sensorAddress, 2). Then read the first byte into highByte and the second byte into lowByte using Wire.read().
Arduino
Hint

Use Wire.requestFrom(sensorAddress, 2) to ask for 2 bytes. Use Wire.read() twice to get each byte.

4
Calculate temperature and print it
Combine highByte and lowByte into an integer called temperature by shifting highByte 8 bits left and OR with lowByte. Then print "Temperature: " followed by temperature and " C" to the Serial Monitor.
Arduino
Hint

Shift highByte left by 8 bits and OR with lowByte to get temperature. Use Serial.print and Serial.println to show the temperature.