How can you set and read the GPIO pins using the C SDK?

Hey all,

I’ve been trying to figure out how to set and read the GPIO pins using the C SDK. So far, I haven’t been able to get any of them to show any output when I attach a voltimeter. Can anyone tell me what I’m doing wrong? Here’s what I’ve written so far:

/*
  Build by running the following commands:

  PICO_SDK_PATH=/home/larry/Projects/pico-sdk/ cmake -S . -B build -DPICO_BOARD=pico
  cmake --build build --target hello_world
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/clocks.h"
#include "i2ckbd.h"
#include "lcdspi.h"
#include "psram_spi.h"
#include "pwm_sound.h"

int main() {
  set_sys_clock_khz(133000, true);
  stdio_init_all();
  init_i2c_kbd();
  lcd_init();
  lcd_clear();
  lcd_print_string("Testing GPIO pins\n");

  uint gpio = 1;
  bool value = 1;
  char* message = malloc (100 * sizeof (char));

  gpio_set_dir (1, GPIO_OUT);
  gpio_set_dir (2, GPIO_OUT);
  gpio_set_dir (3, GPIO_OUT);
  gpio_set_dir (4, GPIO_OUT);
  while (1) {
    sleep_ms(2000);
    sprintf (message, "Testing GPIO pins sending value out %u\n", (uint) value);
    lcd_print_string(message);
    gpio_put (1, value);
    gpio_put (2, value);
    gpio_put (3, value);
    gpio_put (4, value);
    value = !value; 
  }
  return 0;
}

The program displays the Testing message and appears to toggle between sending a 1 and a 0 signal to the various IO pins once every two seconds, but my voltimeter does not display any output.

The rest of the program (the build environment etc can be found in my demo repo in Codeberg - llee454/picocalc-test: A demonstration project showing how to compile, build, and flash C programs for the PicoCalc. - Codeberg.org.

Thanks!

  • L

The pins that go to the outside connector are not “1,2,3,4”.

Now that I’m actually awake and could check, the external pins are 2,3,4,5,21,28. So at least a couple of them should toggle.

But you’re missing calls to gpio_init(<pin>) for each pin you’re using as gpio. Every pin has a mux that selects the peripheral it’s connected to, and unless you explicitly select it for gpio (which gpio_init does), chances are high that it’s actually defaulting to some other peripheral.

Yup, the pins all default to disconnected (function NULL) on reset.

@pelrun - you are awesome! Thanks for the quick reply. I will fix this and test immediately!

I added the gpio_init function calls to my code and successfully observed the pins toggling ± 3V on the selected pins! Success. I’m going to try reading values from these pins next. Please let me know if there’s anything I should do to read values.

Also, It appears that these pins can be used to drive various other protocols. Can anyone drop in a description about how we can uses these other protocols through the C SDK?

I’ll keep posting my demo/test code here: Making sure you're not a bot!

Cheers!