Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5381

SDK • 4 bit binary LED counter using mask functions from SDK

$
0
0
Hello RPi Pico!

I just got my first batch of Pico boards 2 days ago, and I think they're great and I like the C sdk and docs, very helpful! I played with some examples, then set off to make my favorite hello world, an LED binary counter!

I'm not a very experienced C programmer, so it took me a few days to refine this program. Also, I'm rusty, I have not played with uC lately.
I asked chatGPT 3.5 for the tip about how to create a gpio bit mask value i.e. (1 << 2) | (1<<3) etc. but I didn't want to have it answer about using the cool mask functions to create a binary counter. I wanted to figure that out myself! Using an old example of a binary counter from an Arduino sketch that used the modulus function, I modified it to create a bit mask for each LED frame from 0000-1111 using gpio_put_masked()

This circuit connects GP2-GP5 (pins 4-7) to 4 LEDs (and resistors).
I used my RPi USB console cable connected to pins 1-3 with minicom online from a Slackware 15.0 PC for serial output viewing.

Optionally you can make some constants for the LED pins for easy modification of pin location.

Here is my code, I hope you like it.

Code:

// 4 bit LED binary counter on Rpi Pico using the GPIO mask functions// this example is in the public domain// Wire LSB to GP2, read right to left#include <stdio.h>#include "pico/stdlib.h"int main(){// setup stdio for serial UARTstdio_init_all();// Define GPIO pins GP2-GP5 (mask 0x3C)uint gpio_mask = (1 << 2) | (1 << 3) | (1 << 4) | (1 << 5);// init and set GPIO pins as outputs / void gpio_init_mask (uint gpio_mask)gpio_init_mask(gpio_mask);gpio_set_dir_out_masked(gpio_mask);// loop 4 bit binary counter foreverwhile(1){// serial line header for each roundprintf("DEC\n");// declare variable for counter and GPIO put maskint k;uint gpio_put_mask;// loop the LEDs using modulus for base 2for(k=0;k<16;k++){    // print decimal value to serial    printf("%2d\t",k);    // Drive GPIO high/low depending on parameters / static void gpio_put_masked (uint32_t mask, uint32_t value)    gpio_put_mask = (((k >> 0) % 2) << 2) | (((k >> 1) % 2) << 3) | (((k >> 2) % 2) << 4) | (((k >> 3) % 2) << 5);    // show GPIO put mask for each frame    printf("gpio_put_mask %X\t\n",gpio_put_mask);    // display k in binary using LEDs    gpio_put_masked(gpio_mask,gpio_put_mask);    sleep_ms(500);    }}}

Statistics: Posted by breaker — Mon Dec 11, 2023 4:30 am



Viewing all articles
Browse latest Browse all 5381

Trending Articles