Hi! Greetings. I am trying to read from the piezo vibration sensor. I have connected power to 3.3v, Ground to Ground and Out to digital pin D0 and LED to D7. I am only having serial output 0.
In addition to above you are only reading once per second and thus might miss any signal coming from the sensor.
I’d go for an interrupt enabled pin (D0 & A5 are not) and use attachInterrupt()
@peekay123@ScruffR
Many thanks and always appreciate your prompt reply. I have come up with the below code, however the serial output is still 0. The ledPin D7 lights on for couple of second then goes off.
Code:
const int ledPin=D7;
volatile int state = HIGH;
int sensorState=D1;
void setup() {
Serial.begin(9600);
pinMode(sensorState, INPUT); //Piezo vibration sensor is connected
pinMode(ledPin,OUTPUT);
attachInterrupt(sensorState, vibCheck, CHANGE);
}
void loop() {
int sensorState = digitalRead(D1);
Serial.println(sensorState);
delay(5000);
if(sensorState == HIGH)
{
digitalWrite(ledPin,HIGH);
}
else
{
digitalWrite(ledPin,LOW);
}
}
void vibCheck()
{
state = !digitalRead(sensorState);
digitalWrite(ledPin, state);
}
If it is a vibration sensor its output could be wacky. Depending on the time it takes to sense, polling every 5 seconds is an eon on this micro-controller.
Take a look at this alternative approach:
const int MOTION_TIMEOUT = 5000UL; // 5 seconds of led everytime motion is detected, outside of the debounce time
const int ledPin = D7;
const int vibrationSensor = D1;
unsigned long lastVibrationTime;
void setup() {
Serial.begin(9600);
pinMode(vibrationSensor, INPUT); //Piezo vibration sensor is connected
pinMode(ledPin, OUTPUT);
attachInterrupt(vibrationSensor, vibCheck, CHANGE);
}
void loop()
{
if(millis() - lastVibrationTime < MOTION_TIMEOUT && digitalRead(ledPin) == LOW)
{
digitalWrite(ledPin, HIGH);
}
else
{
digitalWrite(ledPin, LOW);
}
}
void vibCheck()
{
// you can debounce this as well:
if(millis() - lastVibrationTime < 100) // will ignore bouncy signals inside 100ms
return;
//
lastVibrationTime = millis();
}
if you are using it to sense the presence of pressure, that’s a different animal and polling would be important, but you need to get rid of that blocking delay in loop().
I found the problem in @kazi93’s updated code (using an interrupt)!
Take a very careful close look at your code. You have two different variables with the same name.
One of them is a global variable, and the other is a local variable inside your loop.
When inside your loop, you are using the local variable. In all the rest of your code, you are using the global variable. Since you are using two different variables, your program is behaving properly according to your code. However, it is not behaving how you expect it to.
I will leave it at that so you can study the scope of variables and understand it.