Purpose of GPIO_OUT_W1TS_REG

User avatar
kolban
Posts: 1683
Joined: Mon Nov 16, 2015 4:43 pm
Location: Texas, USA

Purpose of GPIO_OUT_W1TS_REG

Postby kolban » Sun May 28, 2017 6:03 pm

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?
Free book on ESP32 available here: https://leanpub.com/kolban-ESP32

WiFive
Posts: 3529
Joined: Tue Dec 01, 2015 7:35 am

Re: Purpose of GPIO_OUT_W1TS_REG

Postby WiFive » Sun May 28, 2017 8:44 pm

Yes but why would you want to do that when you can do it in one operation? It's a convenience function.

ESP_Sprite
Posts: 8926
Joined: Thu Nov 26, 2015 4:08 am

Re: Purpose of GPIO_OUT_W1TS_REG

Postby ESP_Sprite » Mon May 29, 2017 5:13 am

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.

Who is online

Users browsing this forum: koushik and 58 guests