## Generic read switch function based on Active High/Low configuration

7 posts / 0 new
Author
Message

Sorry, this could be a silly question in this forum. But not able to find easy method.

I would like to configure my switch input type as either active high or active low. I need a code something like below, but I know this code will not work because I when I multiply by 0 (Active Low), nothing works. One way is to write code to check ACTIVE LOW/ACTIVE_HIGH using if statement and handle. But I am sure there could be a simple method to perform logical NOT operation based on configurable bits. How to make the readSwitch() function configurable depending on switch input types? Later I may pass the parameter active high or low to readSwitch function so that read switch could be made generic.

```#define ACTIVE_LOW 0
#define ACTIVE_HIGH 1
#define SWITCH_TYPE ACTIVE_LOW

{
uint8_t state=0;
if(SWITCH_TYPE*(PINC&(1<<pinNum)))
{
_delay_ms(20);
if(SWITCH_TYPE*(PINC&(1<<pinNum)))
{
state=1;
}
}
return(state);
}```
This topic has a solution.

Last Edited: Thu. Feb 22, 2018 - 01:25 AM

Write code to convert the pin state to 0 or 1 then compare with SWITCH_TYPE

Btw your switch debounce method sucks.

This reply has been marked as the solution.

Do an xor with (-SWITCH_TYPE) .

Iluvatar is the better part of Valar.

Kartman wrote:
Write code to convert the pin state to 0 or 1
Just to note that !! can be useful for this.

`PINC & (1 << 5)`

has the value 0x00 or 0x20. The 0x00 in this is what you want, the 0x20 is not. Meanwhile:

`!(PINC & (1 << 5))`

has the value true (when 0x00) or false (when 0x20). As true/false will be represented as 1/0 then this is close but "the wrong way round". Finally another '!' inverts this:

`!!(PINC & (1 << 5))`

That is 1 when the bit is set and 0 when it is not.

Here I consolidated 3 different methods and all of them consume same code.

```        if(((PINC & (1<<PC1))^(!SWITCH_TYPE<<PC1)))
if((PINC & (1<<PC1)?1:0)==SWITCH_TYPE)
if(!!(PINC & (1<<PC1))==SWITCH_TYPE)```

Why the equality test in any of those?