Skip to content

Commit

Permalink
Add bit packing GPIO implementation for stm32f1 as well.
Browse files Browse the repository at this point in the history
Signed-off-by: Terraneo Federico <[email protected]>
  • Loading branch information
danielecattaneo authored and fedetft committed Jan 16, 2025
1 parent ce54486 commit 463dd1c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
10 changes: 6 additions & 4 deletions miosix/arch/common/drivers/stm32f1_gpio.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ namespace miosix {

void GpioPin::mode(Mode m)
{
unsigned char n=getNumber();
GPIO_TypeDef *d=getPortDevice();
if(n<8)
{
p->CRL &= ~(0xf<<(n*4));
p->CRL |= toUint(m)<<(n*4);
d->CRL &= ~(0xf<<(n*4));
d->CRL |= toUint(m)<<(n*4);
} else {
p->CRH &= ~(0xf<<((n-8)*4));
p->CRH |= toUint(m)<<((n-8)*4);
d->CRH &= ~(0xf<<((n-8)*4));
d->CRH |= toUint(m)<<((n-8)*4);
}
}

Expand Down
30 changes: 22 additions & 8 deletions miosix/arch/common/drivers/stm32f1_gpio.h
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ class GpioPin
* \param n which pin (0 to 15)
*/
GpioPin(unsigned int p, unsigned char n)
: p(reinterpret_cast<GPIO_TypeDef*>(p)), n(n) {}
: p(pack(p, n)) {}

/**
* Set the GPIO to the desired mode (INPUT, OUTPUT, ...)
Expand All @@ -105,15 +105,15 @@ class GpioPin
*/
void high()
{
p->BSRR= 1<<n;
getPortDevice()->BSRR= 1<<getNumber();
}

/**
* Set the pin to 0, if it is an output
*/
void low()
{
p->BRR= 1<<n;
getPortDevice()->BRR= 1<<getNumber();
}

/**
Expand All @@ -122,7 +122,7 @@ class GpioPin
*/
int value()
{
return (p->IDR & 1<<n) ? 1 : 0;
return (getPortDevice()->IDR & (1<<getNumber())) ? 1 : 0;
}

/**
Expand All @@ -144,16 +144,30 @@ class GpioPin
/**
* \return the pin port. One of the constants PORTA_BASE, PORTB_BASE, ...
*/
unsigned int getPort() const { return reinterpret_cast<unsigned int>(p); }
unsigned int getPort() const { return p & ~0xF; }

/**
* \return the pin number, from 0 to 15
*/
unsigned char getNumber() const { return n; }
unsigned char getNumber() const
{
return static_cast<unsigned char>(p & 0xF);
}

private:
GPIO_TypeDef *p; //Pointer to the port
unsigned char n; //Number of the GPIO within the port
inline GPIO_TypeDef *getPortDevice() const
{
return reinterpret_cast<GPIO_TypeDef *>(getPort());
}

static inline unsigned long pack(unsigned long p, unsigned long n)
{
//We use the fact that GPIO device pointers are always 16-byte aligned
//to binpack the port number together with the pointer
return p | n;
}

unsigned long p;
};

/**
Expand Down

0 comments on commit 463dd1c

Please sign in to comment.