#include <stdio.h>
#include "driver/gpio.h"
#include "esp_adc/adc_oneshot.h"
#include "esp_rom_delay.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#define SHCP_PIN GPIO_NUM_5
#define STCP_PIN GPIO_NUM_4
#define DS_PIN GPIO_NUM_2
#define LED1_PIN GPIO_NUM_18
#define LED2_PIN GPIO_NUM_19
#define POT1_CH ADC_CHANNEL_6 // GPIO34
#define POT2_CH ADC_CHANNEL_7 // GPIO35
#define POT3_CH ADC_CHANNEL_4 // GPIO32
static const uint8_t segmentCodes[] = {
0b11000000, // 0
0b11111001, // 1
0b10100100, // 2
0b10110000, // 3
0b10011001, // 4
0b10010010, // 5
0b10000010, // 6
0b11111000, // 7
0b10000000, // 8
0b10010000, // 9
};
static void shiftOut(gpio_num_t dataPin, gpio_num_t clockPin, bool msbFirst, uint8_t val) {
for (int i = 0; i < 8; i++) {
int bit = msbFirst ? (val >> (7 - i)) & 0x01 : (val >> i) & 0x01;
gpio_set_level(dataPin, bit);
gpio_set_level(clockPin, 0);
esp_rom_delay_us(1);
gpio_set_level(clockPin, 1);
esp_rom_delay_us(1);
}
}
static void displayNumber(int number) {
number = number < 0 ? 0 : (number > 99 ? 99 : number);
uint8_t tensCode = segmentCodes[number / 10];
uint8_t onesCode = segmentCodes[number % 10];
shiftOut(DS_PIN, SHCP_PIN, true, onesCode);
shiftOut(DS_PIN, SHCP_PIN, true, tensCode);
gpio_set_level(STCP_PIN, 1);
esp_rom_delay_us(1);
gpio_set_level(STCP_PIN, 0);
}
void app_main() {
// GPIO Configuration
gpio_config_t io_conf = {
.pin_bit_mask = (1ULL << SHCP_PIN) | (1ULL << STCP_PIN) | (1ULL << DS_PIN) |
(1ULL << LED1_PIN) | (1ULL << LED2_PIN),
.mode = GPIO_MODE_OUTPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE,
};
gpio_config(&io_conf);
// ADC Configuration
adc_oneshot_unit_handle_t adc_handle;
adc_oneshot_unit_init_cfg_t adc_config = {
.unit_id = ADC_UNIT_1,
.ulp_mode = ADC_ULP_MODE_DISABLE,
};
ESP_ERROR_CHECK(adc_oneshot_new_unit(&adc_config, &adc_handle));
adc_oneshot_chan_cfg_t channel_config = {
.atten = ADC_ATTEN_DB_12,
.bitwidth = ADC_BITWIDTH_12,
};
ESP_ERROR_CHECK(adc_oneshot_config_channel(adc_handle, POT1_CH, &channel_config));
ESP_ERROR_CHECK(adc_oneshot_config_channel(adc_handle, POT2_CH, &channel_config));
ESP_ERROR_CHECK(adc_oneshot_config_channel(adc_handle, POT3_CH, &channel_config));
displayNumber(0);
while (1) {
int pot1Value, pot2Value, pot3Value;
adc_oneshot_read(adc_handle, POT1_CH, &pot1Value);
adc_oneshot_read(adc_handle, POT2_CH, &pot2Value);
adc_oneshot_read(adc_handle, POT3_CH, &pot3Value);
int displayedNumber = (pot3Value * 99) / 4095;
displayNumber(displayedNumber);
if (displayedNumber % 2 == 0) {
gpio_set_level(LED1_PIN, (pot1Value > 2047) ? 1 : 0);
gpio_set_level(LED2_PIN, 0);
} else {
gpio_set_level(LED1_PIN, 0);
gpio_set_level(LED2_PIN, (pot2Value > 2047) ? 1 : 0);
}
vTaskDelay(pdMS_TO_TICKS(100));
}
}