USB Serial Input on the Pico

C File

#include <stdio.h>
#include "pico/stdlib.h"

int main(){
    //Initialise I/O
    stdio_init_all(); 

    // Initialise GPIO (Green LED connected to pin 25)
    gpio_init(25);
    gpio_set_dir(25, GPIO_OUT);

    char userInput;

    //Main Loop 
    while(1){
        //Get User Input
        printf("Command (1 = on or 0 = off):\n");
        userInput = getchar();

        if(userInput == '1'){
            // Turn On LED
            gpio_put(25, 1); // Set pin 25 to high
            printf("LED switched on!\n");
        }
        else if(userInput == '0'){
            // Turn Off LED
            gpio_put(25, 0); // Set pin 25 to high.
            printf("LED switched off!\n");
        }
        else{
            printf("Invalid Input!\n");
        }
    }
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.12)

include(pico_sdk_import.cmake)

project(pico-projects)

pico_sdk_init()

add_executable(blink_led
    blink_led.c
)

target_link_libraries(blink_led pico_stdlib)

pico_enable_stdio_usb(blink_led 1)
pico_enable_stdio_uart(blink_led 0)

pico_add_extra_outputs(blink_led)

3 comments

  1. For me this is not working. In the moment I want to use some kind of read command `scanf` or `getchar` I can’t open the port anymore. Serial connect is not found by the pc.

  2. I love your tutorials, thank you for preparing them. Regarding this tutorial, I couldn’t make it run. I can compile and get uf2 file without any errors but after uploading to Pico, i cant access to serial port of pico. Permission denied.
    If I remove getchar() command, then I can access the serial port. I have no idea what is causing this.
    Also tried scanf() and have same effect.

Leave a comment

Your email address will not be published. Required fields are marked *