Skip to main content

Site Navigation

Your Account

Choose Language

Anything programming related to the Hexbright

34 Questions View all

Typo in accelerometer code?

I'm new to Arduino programming and didn't find this syntax on the Arduino page:

Is the double !! a typo here or is there some value to using the bitwise 'not' twice or is this unique to Arduino?

tapped = !!(tilt & 0x20);

shaked = !!(tilt & 0x80);

Answer this question I have this problem too

Is this a good question?

Score 0
Add a comment

2 Answers

Most Helpful Answer

Short answer

It will return a 1 if the tapped register is set or a 0 if not.

Long answer

! will perform a boolean negation. If a value is not 0, turn it to a 0. If a value is a 0, turn it to a 1.

This code first does a bitwise comparison, like so:

Bxxxxxxxxxxxxxxxx (tilt) &

B00000001000000000 (0x20)

This filters out everything but the 10th bit. The result is 0 or 0x20 (512 in decimal).

Then we not it twice:

!512->0, !0->1 or

!0->1, !1->0.

So, the double negation (!!) code converts any result to a 1 or 0.

Was this answer helpful?

Score 1
Add a comment

This is actually an infrequently used C idiom that forces the result to be true (1) or false (0). It has nothing to do with Arduino. So in the case where (tilt & 0x20) is 0x20, the result is 1. It is a lot easier to read than say..

(tilt & 0x20) >> 5

Was this answer helpful?

Score 0
Add a comment

Add your answer

Kevin Hoyt will be eternally grateful.
View Statistics:

Past 24 Hours: 0

Past 7 Days: 0

Past 30 Days: 0

All Time: 290