Knock sensor tutorial Questions

I was reading the following tutorial:

created 25 Mar 2007
by David Cuartielles http://www.0j0.org
modified 30 Jun 2009
by Tom Igoe

*/

// these constants won’t change:
const int ledPin = 13; // led connected to digital pin 13
const int knockSensor = 0; // the piezo is connected to analog pin 0
const int threshold = 100; // threshold value to decide when the detected sound is a knock or not

// these variables will change:
int sensorReading = 0; // variable to store the value read from the sensor pin
int ledState = LOW; // variable used to store the last LED status, to toggle the light

void setup() {
pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
Serial.begin(9600); // use the serial port
}

void loop() {
// read the sensor and store it in the variable sensorReading:
sensorReading = analogRead(knockSensor);

// if the sensor reading is greater than the threshold:
if (sensorReading >= threshold) {
// toggle the status of the ledPin:
ledState = !ledState;
// update the LED pin itself:
digitalWrite(ledPin, ledState);
// send the string “Knock!” back to the computer, followed by newline
Serial.println(“Knock!”);
}
delay(100); // delay to avoid overloading the serial port buffer
}

I have a few questions…

It does say pinMode(ledPin, OUTPUT), but where is the pinMode of the knocksensor?
Doesn’t that have to change to an INPUT?

Also, it says:
if (sensorReading >= threshold) {

ledState = !ledState;

Is this possible with just ints? I thought you needed booleans for functions like this…

but where is the pinMode of the knocksensor?

All pins default to inputs so there is no need to declare it although for best practice you should.

Is this possible with just ints?

Yes with ints the ! operation inverts each it of the number. You can even do it with values.

Does that mean that 1 becomes -1 and vice versa?
Thanks for the reply btw!

Well not quite. If you think of the number in terms of bits, 0 is all the bits set to a logic 0. Whereas if all the bits in an int were set to logic one you would have a value of -1.

These are also the vlaues of true and false. a +1 would be all zeros but the least significant bit and the inverse would be -2. Look up the terms ones complement and twos complement. The arduino uses twos complement numbers.

Pins default to input on the ATmegas, but I think it’s best to include the pinMode calls for all pins used in the sketch.
For future compatibility, and for clarity.

As for the ! operator, see this:

void setup(){
Serial.begin(9600);

boolean b = false;
Serial.println(!b,DEC); //1
byte x = 10;
Serial.println(!x,DEC); //0
int i = -345;
Serial.println(!i,DEC); //0
byte surprise = 0;
Serial.println(!surprise,DEC); //1

}
void loop(){}

:slight_smile:

Well I know booleans can be true or false, I thought that’s what they were for. for toggling.

But I didn’t know it coult be done with a regular int