INF2004_Labs/lab_2/lab_2.c

97 lines
3.0 KiB
C

/**
* Lab 2
* This is configured with GPIO15 as a pseudo button with a pull up resistor
* Since the button is active low, the program will send '1' when the button is not pressed (high)
* and send 'A' to 'Z' when the button is pressed (low)
*/
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/uart.h"
#define UART_ID uart0
#define BAUD_RATE 115200 // Baud rate of UART
#define UART_TX_PIN 16 // GPIO for UART TX pin
#define UART_RX_PIN 17 // GPIO for UART RX pin
#define PSEUDO_BTN 15 // GPIO for pseudo button
#define SLEEP_TIME 1000 // For testing can use a smaller value
// 1000ms is based on the lab requirements
/**
* Sends a character through UART0 based on the state of GPIO15 (Pseudo button)
* @param uart_input Pointer to a character to be sent through UART0 (Space optimisation)
* @return void Prints the character in uart_receive()
*/
static void uart_transmit(char *uart_input) {
if (gpio_get(PSEUDO_BTN)) { // If GPIO15 is high
uart_putc(UART_ID, '1');
} else { // If GPIO15 is low
uart_putc(UART_ID, *uart_input);
*uart_input = (*uart_input - 'A' + 1) % 26 + 'A'; // Next character and wrap around back to A
}
}
/**
* Receives a character through UART0 and prints it out
* NOTE: Flipping bit 5 effectively converts a character to lowercase
* @param uart_output Pointer to a location to store the received character (Space optimisation)
* @return void Character is read and printed
*/
static void uart_receive(char *uart_output) {
if (uart_is_readable(UART_ID)) {
*uart_output = uart_getc(UART_ID);
if (*uart_output >= 'A' && *uart_output <= 'Z') {
*uart_output ^= (1 << 5); // XOR with 32 to convert to lowercase
// This operation flips bit 5
} else if (*uart_output == '1') {
*uart_output = '2'; // If '1' is received, print '2'
}
printf("%c\n", *uart_output);
}
}
/**
* Initializes UART0 and GPIO pins
* @return void
*/
static void pin_init() {
// UART init
uart_init(UART_ID, BAUD_RATE);
gpio_set_function(UART_TX_PIN, GPIO_FUNC_UART);
gpio_set_function(UART_RX_PIN, GPIO_FUNC_UART);
// Disable UART FIFO for data to be tx/rx immediately
uart_set_fifo_enabled(UART_ID, false);
// Pseudo button init
gpio_set_dir(PSEUDO_BTN, GPIO_IN);
// Enable pull up resistor
gpio_set_pulls(PSEUDO_BTN, true, false);
}
int main() {
stdio_init_all();
pin_init();
u_char uart_input = 'A'; // Initial value of A
u_char uart_output; // To store received character
while (true) {
uart_transmit(&uart_input); // Pass by reference to change
// value of uart_input during transmission
uart_receive(&uart_output); // Pass by reference to change
// value of uart_output during reception
sleep_ms(SLEEP_TIME); // Sleep based on SLEEP_TIME
}
}