简体   繁体   中英

Bare metal programming in C for Raspberry pi

I am currently programming raspberry pi.

I wanted to get clear out some doubts, please can anybody help.

Here is the code snippet.

#define GPIO_BASE 0x20200000UL

gpio = (unsigned int*)GPIO_BASE; gpio[GPIO_GPFSEL1] |= (1 << 18);

This code is from http://www.valvers.com/embedded-linux/raspberry-pi/step01-bare-metal-programming-in-cpt1

I do understand the functionality of the code to switch on and switch off the LED .

I have problem understand the these statements

gpio = (unsigned int*)GPIO_BASE; gpio[GPIO_GPFSEL1] |= (1 << 18);

First you have some address in memory.

define GPIO_BASE 0x20200000UL

Under this address exists a control structure for GPIO. In your case it's just an array of ints. Writing a value to a certain field of that structure makes GPIO set its pins.

gpio = (unsigned int*)GPIO_BASE;

You select some register in your structure (the address (unsigned int*)GPIO_BASE + GPIO_GPFSEL1) and you set the 18th bit on.

gpio[GPIO_GPFSEL1] |= (1 < < 18);

The GPIO will likely respond with setting one of its pins to high state. The LED attached to that pin will start glowing.

Well ...

The first statement:

gpio = (unsigned int*)GPIO_BASE;

sets the pointer variable gpio equal to the value of GPIO_BASE , and also casts the latter to a pointer type.

The second

gpio[GPIO_GPFSEL1] |= (1 << 18);

does a bitwise OR of the value in gpio[GPIO_GPFSEL1] with the constant value 1 << 18 . This "turns on" bit 18 (counting from 0) in the register GPIO_GPFSEL1 .

Remember that in C, array indexing a[b] is the same as *(a + b) , ie it's a pointer addition and dereferencing.

After

gpio = (unsigned int*)GPIO_BASE;

gpio points to 0x20200000 memory address. This is "The base address of the GPIO peripheral (ARM Physical Address)".

Article that you've linked says that:

Back to the processor manual and we see that the first thing we need to do is set the GPIO pin to an output. This is done by setting the function of GPIO16 to an output. Bits 18 to 20 in the 'GPIO Function Select 1′ register control the GPIO16 pin.

Statement

#define GPIO_GPFSEL1    1
gpio[GPIO_GPFSEL1] |= (1 << 18);

breaks down to:

gpio[1] = gpio[1] | (1 << 18);

So, address (0x20200000 + sizeof(unsigned int)) is dereferenced and OR operator sets the bit 18 to 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM