agrobot_base/Firmware/Modulos/Pinout.h

125 lines
4.3 KiB
C++

#include "Enuns.h"
#include "SerialService.h"
#include "I2CService.h"
#ifndef Pinout
#define Pinout
#define PINO_INVALIDO 0xFF
class PinoModel {
public:
int num;
TiposBarramentos barramento;
TiposPinos tipo;
TiposLeituras leitura;
PinoModel(int numero = PINO_INVALIDO, TiposBarramentos barr = CONTROLADOR, TiposPinos tp = _INPUT, TiposLeituras lt = DIGITAL) : num(numero), barramento(barr), tipo(tp), leitura(lt) {
}
bool Definido() {
return num != PINO_INVALIDO;
}
void Conectar(bool statusInicial = false) {
if (Definido()) {
if (barramento == CONTROLADOR) {
if (tipo == _INPUT) {
pinMode(num, INPUT);
} else if (tipo == _OUTPUT) {
pinMode(num, OUTPUT);
set(statusInicial);
}
}
else if (barramento == EXPANSOR_GPIO) {
if (I2CService::McpIniciado) {
I2CService::SolicitarAcessoI2C();
if (tipo == _INPUT) {
I2CService::mcp.pinMode(num, INPUT);
} else if (tipo == _OUTPUT) {
I2CService::mcp.pinMode(num, OUTPUT);
set(statusInicial);
}
I2CService::LiberarAcessoI2C();
}
}
}
}
void Desconectar() {
if (Definido()) {
if (barramento == CONTROLADOR) {
if (tipo == _PWM) {
ledcDetachPin(num);
}
pinMode(num, INPUT);
}
else if (barramento == EXPANSOR_GPIO) {
if (I2CService::McpIniciado) {
I2CService::SolicitarAcessoI2C();
I2CService::mcp.pinMode(num, INPUT);
I2CService::LiberarAcessoI2C();
}
}
}
}
int get(int leituras = 1) {
if (Definido()) {
if (barramento == CONTROLADOR) {
if (leitura == DIGITAL) {
return digitalRead(num);
}
else if (leitura == ANALOGICO) {
double l = 0;
for (int i = 0; i < leituras; i++) {
l += analogRead(num);
delay(1);
}
return l / leituras;
}
}
else if (barramento == EXPANSOR_GPIO) {
if (I2CService::McpIniciado) {
I2CService::SolicitarAcessoI2C();
int leitura = I2CService::mcp.digitalRead(num);
I2CService::LiberarAcessoI2C();
return leitura;
}
}
else if (barramento == EXPANSOR_ADS) {
if (I2CService::AdsIniciado) {
I2CService::SolicitarAcessoI2C();
uint16_t l = 0;
for (int i = 0; i < leituras; i++) {
int leituraADC = (int)(I2CService::ads.readADC_SingleEnded(num));
int leitura12bits = map(leituraADC, 0, 32767, 0, 4095);
l += leitura12bits;
delay(1);
}
I2CService::LiberarAcessoI2C();
return (int)(l / leituras);
}
}
}
return -1;
}
void set(bool status) {
if (Definido()) {
if (barramento == CONTROLADOR) {
digitalWrite(num, status ? HIGH : LOW);
}
else if (barramento == EXPANSOR_GPIO) {
if (I2CService::McpIniciado) {
I2CService::SolicitarAcessoI2C();
I2CService::mcp.digitalWrite(num, status ? HIGH : LOW);
I2CService::LiberarAcessoI2C();
}
}
}
}
};
#endif