summaryrefslogtreecommitdiff
path: root/src/drivers/digital_pot.cpp
blob: b20d982d663aacef9d714f8922d9029ecd3bd500 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
 * Copyright 2023 jacqueline <me@jacqueline.id.au>
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */

#include "digital_pot.hpp"

#include <cstdint>

namespace drivers {

using GpioExpander::VOL_LEFT;
using GpioExpander::VOL_RIGHT;
using GpioExpander::VOL_UP_DOWN;
using GpioExpander::VOL_Z_CROSS;

DigitalPot::DigitalPot(GpioExpander* gpios) : gpios_(gpios) {
  gpios_->set_pin(VOL_Z_CROSS, true);  // Active-low
  gpios_->set_pin(VOL_UP_DOWN, true);
  gpios_->set_pin(VOL_LEFT, false);
  gpios_->set_pin(VOL_RIGHT, false);
  gpios_->Write();

  // Power-on reset sets attenuation to maximum anyway, but we want to be safe
  // and not blow anyone's ears out.
  for (int i = 0; i < 32; i++) {
    gpios_->set_pin(VOL_LEFT, true);
    gpios_->set_pin(VOL_RIGHT, true);
    gpios_->Write();
    gpios_->set_pin(VOL_LEFT, false);
    gpios_->set_pin(VOL_RIGHT, false);
    gpios_->Write();
  }
}

auto DigitalPot::SetRelative(int_fast8_t change) -> void {
  if (change == 0) {
    return;
  }

  gpios_->set_pin(VOL_UP_DOWN, change > 0);
  gpios_->Write();

  for (int i = 0; i < std::abs(change); i++) {
    gpios_->set_pin(VOL_LEFT, true);
    gpios_->set_pin(VOL_RIGHT, true);
    gpios_->Write();
    gpios_->set_pin(VOL_LEFT, false);
    gpios_->set_pin(VOL_RIGHT, false);
    gpios_->Write();
  }
}

auto DigitalPot::SetRelative(Channel ch, int_fast8_t change) -> void {
  if (change == 0) {
    return;
  }

  GpioExpander::Pin pin = (ch == Channel::kLeft) ? VOL_LEFT : VOL_RIGHT;
  gpios_->set_pin(VOL_UP_DOWN, change > 0);
  gpios_->Write();

  for (int i = 0; i < std::abs(change); i++) {
    gpios_->set_pin(pin, true);
    gpios_->Write();
    gpios_->set_pin(pin, false);
    gpios_->Write();
  }
}

auto DigitalPot::SetZeroCrossDetect(bool enabled) -> void {
  gpios_->set_pin(VOL_Z_CROSS, !enabled);  // Active-low
  gpios_->Write();
}

auto DigitalPot::GetMaxAttenuation() -> int_fast8_t {
  return 31;
}

auto DigitalPot::GetMinAttenuation() -> int_fast8_t {
  return 0;
}

}  // namespace drivers