Skip to content

Instantly share code, notes, and snippets.

@MB901
Created March 9, 2022 20:22
Show Gist options
  • Select an option

  • Save MB901/8e3991fdd8201f422cf1212073d15f66 to your computer and use it in GitHub Desktop.

Select an option

Save MB901/8e3991fdd8201f422cf1212073d15f66 to your computer and use it in GitHub Desktop.
#pragma once
#include "esphome.h"
//define differents pins of X9CXXX board
#define CSPIN 16
#define INCPIN 17
#define UDPIN 18
class DigitalPotentiometer : public Component
{
public:
bool enable = false; //sending data to X9CXXX or not
int current_step = 0; //current value between 0 and 100
int new_step = 0; //value to be setted between 0 and 100
DigitalPotentiometer(esphome::template_::TemplateSwitch *&_enable, esphome::template_::TemplateNumber *&_step)
{
_enable->add_on_state_callback([this](bool newState)
{ enable = newState; });
_step->add_on_state_callback([this](int newStep)
{ new_step = newStep; });
}
void setup() override
{
pinMode(CSPIN,OUTPUT);
pinMode(INCPIN,OUTPUT);
pinMode(UDPIN,OUTPUT);
reset();
}
void loop() override //only active when send_data_x9c qwitch is on
{
if (enable)
{
go_to_step();
}
}
void reset() //reset X9CXXX to a known value
{
digitalWrite(CSPIN, LOW);
digitalWrite(UDPIN, LOW);
for (uint8_t i = 0; i < 100; i++)
{
digitalWrite(INCPIN, LOW);
delayMicroseconds(100);
digitalWrite(INCPIN, HIGH);
delayMicroseconds(100);
}
digitalWrite(UDPIN, HIGH);
digitalWrite(CSPIN, HIGH);
current_step = 0;
}
void go_to_step()
{
digitalWrite(CSPIN, LOW);
while (current_step != new_step)
{
if (current_step > new_step)
{
digitalWrite(UDPIN, LOW);
digitalWrite(INCPIN, LOW);
delayMicroseconds(100);
digitalWrite(INCPIN, HIGH);
delayMicroseconds(100);
if (current_step > 0) current_step--;
}
else
{
digitalWrite(UDPIN, HIGH);
digitalWrite(INCPIN, LOW);
delayMicroseconds(100);
digitalWrite(INCPIN, HIGH);
delayMicroseconds(100);
if (current_step < 100) current_step++;
}
}
digitalWrite(CSPIN, HIGH);
}
}; //class
esphome:
# ... [Other options]...
includes:
- custom_componenent/digital_potentiometer.h
#wifi...
#... your personnal code...
number: #value to be setted on X9CXXX between 0 and 100
- platform: template
name: "X9C Position"
id: x9c_position
optimistic: true
min_value: 1
max_value: 100
step: 1
switch: #//sending data to X9CXXX or not
- platform: template
name: "Send Data to X9C"
id: send_data_x9c
optimistic: true
custom_component:
- lambda: |-
auto myComponent = new DigitalPotentiometer(id(send_data_x9c), id(x9c_position));
return {myComponent};
@MB901
Copy link
Author

MB901 commented Mar 9, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment