89 lines
2.8 KiB
C
89 lines
2.8 KiB
C
/**
|
|
* Lab 2
|
|
* Note that this program would print out garbage for the first few characters
|
|
* received. It will work as intended after a few characters are received.
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
#include "pico/stdlib.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 GPIO_PIN 15 // GPIO for pseudo button
|
|
|
|
#define SLEEP_TIME 100 // 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()
|
|
*/
|
|
void uart_transmit(char *uart_input) {
|
|
if (gpio_get(GPIO_PIN)) { // Active low
|
|
uart_putc(UART_ID, '1');
|
|
} else { // Active high
|
|
uart_putc(UART_ID, *uart_input);
|
|
*uart_input = (*uart_input - 'A' + 1) % 26 + 'A'; // Next character
|
|
// Wrap around back to A
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Receives a character through UART0 and prints it out
|
|
* Ideally, the buffer should be cleared after each read
|
|
* 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
|
|
*/
|
|
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
|
|
*/
|
|
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);
|
|
|
|
// Pseudo button init
|
|
gpio_set_dir(GPIO_PIN, GPIO_IN);
|
|
}
|
|
|
|
int main() {
|
|
stdio_init_all();
|
|
pin_init();
|
|
|
|
char uart_input = 'A'; // Initial value of A
|
|
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
|
|
}
|
|
|
|
}
|