Advertisement
pleasedontcode

I2C example

Jul 26th, 2024
743
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 1.03 KB | Source Code | 0 0
  1. #include <Wire.h> // Include the I2C library
  2.  
  3. #define TEMP_SENSOR_ADDR 0x48 // Temperature sensor I2C address
  4. #define HUMID_SENSOR_ADDR 0x40 // Humidity sensor I2C address
  5.  
  6. void setup() {
  7.   Wire.begin(); // Join I2C bus
  8.   Serial.begin(9600); // Start serial communication
  9. }
  10.  
  11. void loop() {
  12.   // Read temperature
  13.   Wire.beginTransmission(TEMP_SENSOR_ADDR);
  14.   Wire.write(0x00); // Command to read temperature
  15.   Wire.endTransmission();
  16.   Wire.requestFrom(TEMP_SENSOR_ADDR, 2); // Request 2 bytes from temp sensor
  17.   int temp = Wire.read() << 8 | Wire.read(); // Combine bytes
  18.   Serial.print("Temperature: ");
  19.   Serial.println(temp);
  20.  
  21.   // Read humidity
  22.   Wire.beginTransmission(HUMID_SENSOR_ADDR);
  23.   Wire.write(0x00); // Command to read humidity
  24.   Wire.endTransmission();
  25.   Wire.requestFrom(HUMID_SENSOR_ADDR, 2); // Request 2 bytes from humidity sensor
  26.   int humid = Wire.read() << 8 | Wire.read(); // Combine bytes
  27.   Serial.print("Humidity: ");
  28.   Serial.println(humid);
  29.  
  30.   delay(1000); // Wait for 1 second before next reading
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement