Page 1 of 1

Purpose of GPIO_OUT_W1TS_REG

Posted: Sun May 28, 2017 6:03 pm
by kolban
Reading the tech reference, we have two registers called GPIO_OUT_W1TS_REG and GPIO_OUT_W1TC_REG which apparently are Write One To Set and Write One To Clear. If I understand these correctly, Writing a 1 in BITx of GPIO_OUT_W1TS_REG is the equivalent of setting the corresponding bit in GPIO_OUT_REG.

My question is why do we have this? Can we not read the value of GPIO_OUT_REG and then write it back with the desired changed bit either on or off?

Re: Purpose of GPIO_OUT_W1TS_REG

Posted: Sun May 28, 2017 8:44 pm
by WiFive
Yes but why would you want to do that when you can do it in one operation? It's a convenience function.

Re: Purpose of GPIO_OUT_W1TS_REG

Posted: Mon May 29, 2017 5:13 am
by ESP_Sprite
Also, these registers make atomic operations possible in a multitasked environment. Setting a bit in a register normally means reading the register, OR'ing the value with the bit you want to set, then writing back the register. (This even happens when you write it in one operation in C, like GPIO_OUT_REG|=2) Say we have two tasks that do this: task A sets bit 1 and task B sets bit 2.
  • Task A reads the reg value
    Task A or's the value with 2
    ***CONTEXT SWITCH***
    Task B reads the reg value
    Task B ors the reg value with 4
    Task B writes the value back
    ***CONTEXT SWITCH***
    Task A writes the reg value back
In this case, the value that is written back in task A is the value it read earlier, OR 2. In other words: it overwrites the value task B wrote in the mean time! (Fyi, this type of thing can also happen with memory values and are the reason you should put locks around shared values unless you have a good reason not to.)

Normally, you would have to work around this with locking, but for the GPIOs, you can also use the W1TS and W1TC registers. Because writing a value there is atomic, there's no way a context switch can mess it up, and hence no need to use locks.There are a few more registers like this; in particular the interrupt clear registers come to mind.