ESPHome  2022.5.1
mcp3008.cpp
Go to the documentation of this file.
1 #include "mcp3008.h"
2 #include "esphome/core/log.h"
3 
4 namespace esphome {
5 namespace mcp3008 {
6 
7 static const char *const TAG = "mcp3008";
8 
10 
12  ESP_LOGCONFIG(TAG, "Setting up mcp3008");
13  this->spi_setup();
14 }
15 
17  ESP_LOGCONFIG(TAG, "MCP3008:");
18  LOG_PIN(" CS Pin:", this->cs_);
19 }
20 
21 float MCP3008::read_data(uint8_t pin) {
22  uint8_t data_msb, data_lsb = 0;
23 
24  uint8_t command = ((0x01 << 7) | // start bit
25  ((pin & 0x07) << 4)); // channel number
26 
27  this->enable();
28  this->transfer_byte(0x01);
29 
30  data_msb = this->transfer_byte(command) & 0x03;
31  data_lsb = this->transfer_byte(0x00);
32 
33  this->disable();
34 
35  int data = data_msb << 8 | data_lsb;
36 
37  return data / 1023.0f;
38 }
39 
40 MCP3008Sensor::MCP3008Sensor(MCP3008 *parent, uint8_t pin, float reference_voltage)
41  : PollingComponent(1000), parent_(parent), pin_(pin), reference_voltage_(reference_voltage) {}
42 
44 
45 void MCP3008Sensor::setup() { LOG_SENSOR("", "Setting up MCP3008 Sensor '%s'...", this); }
47  ESP_LOGCONFIG(TAG, "MCP3008Sensor:");
48  ESP_LOGCONFIG(TAG, " Pin: %u", this->pin_);
49  ESP_LOGCONFIG(TAG, " Reference Voltage: %.2fV", this->reference_voltage_);
50 }
52  float value_v = this->parent_->read_data(pin_);
53  value_v = (value_v * this->reference_voltage_);
54  return value_v;
55 }
56 void MCP3008Sensor::update() { this->publish_state(this->sample()); }
57 
58 } // namespace mcp3008
59 } // namespace esphome
void dump_config() override
Definition: mcp3008.cpp:16
float get_setup_priority() const override
Definition: mcp3008.cpp:9
const float DATA
For components that import data from directly connected sensors like DHT.
Definition: component.cpp:18
float get_setup_priority() const override
Definition: mcp3008.cpp:43
This class simplifies creating components that periodically check a state.
Definition: component.h:266
void dump_config() override
Definition: mcp3008.cpp:46
void setup() override
Definition: mcp3008.cpp:11
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:70
float read_data(uint8_t pin)
Definition: mcp3008.cpp:21
const float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition: component.cpp:17
Definition: a4988.cpp:4
MCP3008Sensor(MCP3008 *parent, uint8_t pin, float reference_voltage)
Definition: mcp3008.cpp:40