#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/pio.h"
#include "hardware/gpio.h"
#include "stdlib.h"
#include "unistd.h"
// Define pins
const unsigned uint8_t pins[] = {
// Rotary encoder
{ "EN_PhaseA", 10, GPIO_OUT},
{ "EN_PhaseB", 11, GPIO_OUT},
{ "EN_switch", 12, GPIO_OUT}, // SW
// Switch register
{ "SR_data", 13, GPIO_OUT}, // data pin
{ "SR_latch", 14, GPIO_OUT}, // latch pin
{ "SR_clock", 15, GPIO_OUT}, // clock pin
// Test pin
{ "T_LED", 20, GPIO_OUT},
};
const uint8_t pinCount = 24;
// Define bit strings
const char* bitString = "101010101010101010101010";
const char* prvString = "";
// Initialise pins
void init_pins() {
// Initialize GPIO pin
gpio_init(pins[3]);
// Set GPIO pin directions
gpio_set_dir(pins[3], GPIO_OUT);
}
// returns the output from the encoder
void encoder_callback(uint gpio, uint32_t events) {
uint32_t gpio_state = 0;
gpio_state = (gpio_get_all() >> 10) & 0b0111; // get all GPIO them mask out all but bits 10, 11, 12
// This will need to change to match which GPIO pins are being used.
static bool ccw_fall = 0; //bool used when falling edge is triggered
static bool cw_fall = 0;
uint8_t enc_value = 0;
enc_value = (gpio_state & 0x03);
if (gpio == pins[0]) {
if ((!cw_fall) && (enc_value == 0b10)) // cw_fall is set to TRUE when phase A interrupt is triggered
cw_fall = 1;
if ((ccw_fall) && (enc_value == 0b00)) { // if ccw_fall is already set to true from a previous B phase trigger, the ccw event will be triggered
cw_fall = 0;
ccw_fall = 0;
//do something here, for now it is just printing out CW or CCW
printf("CCW \r\n");
}
}
if (gpio == pins[1]) {
if ((!ccw_fall) && (enc_value == 0b01)) //ccw leading edge is true
ccw_fall = 1;
if ((cw_fall) && (enc_value == 0b00)) { //cw trigger
cw_fall = 0;
ccw_fall = 0;
//do something here, for now it is just printing out CW or CCW
printf("CW \r\n");
}
}
}
// Function to shift data into the 74HC595 register
void shift(const char* data) {
// Start data sending
gpio_put(pins[4], 0);
gpio_put(pins[5], 0);
gpio_put(pins[4], 1);
// Load data in reverse order
for (int i = 0; i < pinCount; i++) {
gpio_put(pins[5], 0);
gpio_put(pins[3], (data[i] == '1') ? 1 : 0);
gpio_put(pins[5], 1);
}
// Store data on register
gpio_put(pins[4], 0);
gpio_put(pins[4], 1);
}
int main() {
stdio_init_all();
// Initialize GPIO pins
init_pins();
gpio_put(pins[6], 1);
while (1) {
if(prvString != bitString) {
// Call the shift function
shift(bitString);
prvString = bitString;
sleep_ms(500);
}
}
}