the question is where to add the gy39.h file?
includes:
- gy39.h
name: my_gy39
platform: ESP8266
board: nodemcu
wifi:
networks:
ssid: "gy" #改成你的wifi名称
password: "12345678" #改成你的wifi密码
logger:
# Enable Home Assistant API
api:
password: 'gy39_esphome'
ota:
password: 'gy39_esphome'
i2c:
sda: D2
scl: D1
frequency: 20000
sensor:
- platform: custom
lambda: |-
auto my_sensor = new MyCustomSensor();
App.register_component(my_sensor);
return {my_sensor->temperature_sensor, my_sensor->pressure_sensor,my_sensor->alt_sensor, my_sensor->hum_sensor,my_sensor->lux_sensor};
sensors:
- name: "gy39_Temperature"
unit_of_measurement: °C
accuracy_decimals: 1
- name: "gy39_Pressure"
unit_of_measurement: hPa
accuracy_decimals: 2
- name: "gy39_alt"
unit_of_measurement: m
accuracy_decimals: 0
- name: "gy39_hum"
unit_of_measurement: '%'
accuracy_decimals: 2
- name: "gy39_lux"
unit_of_measurement: lux
accuracy_decimals: 2
and gy39.h file
#include "esphome.h"
class MyCustomSensor : public PollingComponent {
//class MyCustomSensor : public Component,public Sensor {
public:
// constructor
Sensor *temperature_sensor = new Sensor();
Sensor *pressure_sensor = new Sensor();
Sensor *alt_sensor = new Sensor();
Sensor *hum_sensor = new Sensor();
Sensor *lux_sensor = new Sensor();
MyCustomSensor() : PollingComponent(5000) {}
void setup() override {
// Initialize the device here. Usually Wire.begin() will be called in here,
// though that call is unnecessary if you have an 'i2c:' entry in your config
Wire.begin();
}
void update() override {
// Example: write the value 0x42 to register 0x78 of device with address 0x21
uint8_t raw_data[14];
iic_read(0xb6,0x04,raw_data,10);
int16_t Temp=((int16_t)raw_data[0]<<8)|raw_data[1];
int32_t P=raw_data[2]*16777216+raw_data[3]*65536+raw_data[4]*256+raw_data[5];
int16_t Hum=((int16_t)raw_data[6]<<8)|raw_data[7];
int16_t Alt=((int16_t)raw_data[8]<<8)|raw_data[9];
delay(1);
iic_read(0xb6,00,raw_data,4);
int32_t Lux=raw_data[0]*65536+raw_data[1]*256+raw_data[2];
temperature_sensor->publish_state(Temp/100.0f);
pressure_sensor->publish_state(P/100.0f);
alt_sensor->publish_state(Alt);
hum_sensor->publish_state(Hum/100.0f);
lux_sensor->publish_state(Lux);
}
void iic_read(unsigned char iic_add ,unsigned char reg,unsigned char *data,unsigned char len)
{
Wire.beginTransmission(iic_add>>1);//i2c_start_wait(iic_add);
Wire.write(reg); //i2c_write(add);
Wire.endTransmission();
Wire.requestFrom(iic_add>>1, len);
while(len--)
{
*data++ = Wire.read();
}
}
};