#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/adc.h"
#define DEBUG 1
uint8_t ident_code = 0;
void prompt_message();
void parse_message();
void normalize_pot_readings(int adc_raw, bool percentage);
int get_pot_readings();
void send_ident_controller(uint8_t code);
void send_message(char *message);
void get_identification_code();
void sample_register();
void pulse_clock();
const uint32_t clockPin = 3;
const uint32_t dataPin = 2;
const uint32_t latchPin = 4;
const uint32_t analogPotPin = 26;
const uint adc_max = (1 << 12) - 1;
int main() {
stdio_init_all();
gpio_init(clockPin);
gpio_set_dir(clockPin, GPIO_OUT);
gpio_init(latchPin);
gpio_set_dir(latchPin, GPIO_OUT);
gpio_init(dataPin);
gpio_set_dir(dataPin, GPIO_IN);
adc_init();
adc_gpio_init(analogPotPin);
prompt_message();
while (1) {
/*
get_identification_code();
sleep_ms(500);
send_ident_controller(ident_code);
get_pot_readings();
normalize_pot_readings(get_pot_readings(),false);
*/
parse_message();
//sleep_ms(500);
}
}
void prompt_message() {
printf("Write a message please \n");
}
void parse_message() {
char c = getchar();
printf("%c", c);
}
void normalize_pot_readings(int adc_raw, bool percentage) {
float value;
if (percentage) {
value = (adc_raw / (float)adc_max);
} else {
value = (adc_raw / (float)adc_max) - .5f;
}
if (DEBUG) {
printf("raw values : %d \t normalized values %.2f \n",
adc_raw,
value);
}
}
int get_pot_readings() {
adc_select_input(0);
int adc = adc_read();
return adc;
}
void send_ident_controller(uint8_t code) {
switch(code) {
case 0xff:
send_message("Potentiometer identified");
break;
default:
send_message("Keyboard identified");
}
}
void send_message(char *message) {
printf(message);
printf("\n");
}
void get_identification_code() {
sample_register();
for (int i = 0; i <= 7; i++) {
uint8_t buf;
buf = gpio_get(dataPin);
ident_code = (ident_code << 1) + buf;
pulse_clock();
}
}
void sample_register() {
gpio_put(latchPin, 0);
gpio_put(latchPin, 1);
}
void pulse_clock() {
gpio_put(clockPin, 1); // Shift out the next bit
gpio_put(clockPin, 0);
}