Simvik

A relay and a sensor's power switch, from the transistors

One transistor turns its load on with a high pin, the other with a low pin. Work out which from the schematic, and keep both off from reset. A medium…

medium · Reading datasheets and schematics · schematics · gpio · driver

PA8 switches a 12 V relay and PA9 switches the humidity sensor's supply. Working from the Datasheet excerpt below, write:

  • power_init(), which makes PA8 and PA9 outputs with the relay off and the sensor unpowered. Change no other pin.
  • relay_set(on), which energises the relay's coil when on is 1 and releases it when it is 0.
  • sensor_power(on), which powers the sensor when on is 1 and cuts its supply when it is 0.

Every change of an output pin shows up in the output as gpioa: pin 8 high.

Datasheet excerpt

Board schematic, sheet 4 (switched loads)

                         12V
                          │
               D5 (flyback, across K1)
                          │
                    K1 relay coil
                          │ collector
PA8 ──[R30 1 kΩ]──┬──── Q2 base          Q2: NPN (MMBT3904)
                  │       │ emitter
             [R31 10 kΩ] GND
                  │
                 GND

               3V3
                │ source
3V3 ─[R33 100 kΩ]─┐
                  │
PA9 ──────────────┴── Q3 gate            Q3: P-channel MOSFET (DMG2305)
                │ drain
                └── VDD_SENSOR ── U8 (humidity sensor) VDD

GPIO registers (reference manual)

OffsetRegisterPin y occupiesValues
0x00MODERbits 2y+1:2y00 input, 01 output, 10 alternate function. Resets to 0xA8000000: PA13 and PA14 are the debugger's
0x14ODRbit ythe output latch
0x18BSRRbit y sets pin y, bit y+16 clears itwrite-only

Starter code

void power_init(void) {
  GPIOA->MODER = (1u << 16) | (1u << 18);
}

void relay_set(int on) {
  GPIOA->BSRR = on ? 1u << 8 : 1u << 24;
}

void sensor_power(int on) {
  GPIOA->BSRR = on ? 1u << 9 : 1u << 25;
}

Example tests

Both loads on and off

power_init();
relay_set(1);
sensor_power(1);
relay_set(0);
sensor_power(0);

Expected output:

gpioa: pin 9 high
gpioa: pin 8 high
gpioa: pin 9 low
gpioa: pin 8 low
gpioa: pin 9 high

Learn it first

More Reading datasheets and schematics problems