#include "main.h" #include "mcp41x.h" static uint32_t pot_value[MCP41X_RES_MAX] = {10000, 50000, 100000}; static void mcp41x_transmit(mcp41x_handle_t *hpot, uint8_t *data) { HAL_GPIO_WritePin(hpot->cs_port, hpot->cs_pin, GPIO_PIN_RESET); HAL_SPI_Transmit(hpot->hspi, data, 2, HAL_MAX_DELAY); HAL_GPIO_WritePin(hpot->cs_port, hpot->cs_pin, GPIO_PIN_SET); } void mcp41x_init(mcp41x_handle_t *hpot, SPI_HandleTypeDef *hspi, GPIO_TypeDef *cs_port, uint16_t cs_pin, mcp41x_res_t res) { hpot->hspi = hspi; hpot->cs_port = cs_port; hpot->cs_pin = cs_pin; hpot->max_res = res; hpot->dir = MCP41X_ATOB; HAL_GPIO_WritePin(hpot->cs_port, hpot->cs_pin, GPIO_PIN_SET); } void mcp41x_setValue(mcp41x_handle_t *hpot, uint8_t value) { if (hpot->dir == MCP41X_BTOA) { value = 255 - value; } hpot->value = value; uint8_t data[2] = {MCP41X_WRITE0, value}; mcp41x_transmit(hpot, data); } void mcp41x_setVolume(mcp41x_handle_t *hpot, uint8_t volume) { if (volume > 100) { volume = 100; } uint32_t value = volume * 255U / 100U; mcp41x_setValue(hpot, value); } uint8_t mcp41x_getVolume(mcp41x_handle_t *hpot) { return hpot->value * 100U / 255U; } void mcp41x_setResistance(mcp41x_handle_t *hpot, uint32_t resistance) { if (resistance > pot_value[hpot->max_res]) { resistance = pot_value[hpot->max_res]; } uint32_t value = resistance * 255U / pot_value[hpot->max_res]; mcp41x_setValue(hpot, value); } uint32_t mcp41x_getResistance(mcp41x_handle_t *hpot) { return hpot->value * pot_value[hpot->max_res] / 255; } void mcp41x_setWiperDir(mcp41x_handle_t *hpot, mcp41x_dir_t dir) { hpot->dir = dir; } void mcp41x_sleep(mcp41x_handle_t *hpot) { uint8_t data[2] = {MCP41X_SLEEP, 0}; mcp41x_transmit(hpot, data); }