I have a PIR sensor that triggers a DC toy motor using PWM. I want to add a cell phone vibrator that could be controlled trough PWM and would only be activated after the DC toy motor has been activated 10 times. Once it has counted that the DC motor's 10th activation, I need it to trigger the vibrator and reset itself to start counting again from zero.
Any advice is welcomed.
Can someone tell me if I'm heading in the right direction with my code:
/*
This Code Counts State Change Detection for PIR Sensor
*/
int lastPIRState = LOW; //Sate of the sensor last time I checked
int count = 0; //Variable to start counting
int motorPin = 3; //Pin 3 drives the DC motor
int pir = 2; //Pin 2 inputs data from PIR sensor
void setup() {
pinMode(pir, INPUT); // make pin 2 an input:
pinMode(motorPin, OUTPUT);
}
void loop()
{
int SensorState = digitalRead(2); // read the sensor:
if (SensorState != lastPIRState){ // check if the current sensor state is different than the last
if (SensorState == HIGH){
count++;
}
}
lastPIRState = SensorState;
if (count = 10){
if(digitalRead(pir)==HIGH)
analogWrite(motorPin, 220); //255 equals 100% duty cycle.
delay(2000); //Delay is measured in milliseconds.
(digitalRead(pir)==LOW); //Turns off after delay.
{
analogWrite(motorPin, 0);
}
}
}
This image shows the DC toy motor that I am using. I will be adding another motor (vibrator) in a similar fashion to the one shown.
Please use code tags (</> button on the toolbar) when you post code or warning/error messages. The reason is that the forum software can interpret parts of your code as markup, leading to confusion, wasted time, and a reduced chance for you to get help with your problem. This will also make it easier to read your code and to copy it to the IDE or editor. Using code tags and other important information is explained in the How to use this forum post. Please read it.
Please always do a Tools > Auto Format on your code before posting it. This will make it easier for you to spot bugs and make it easier for us to read.
Please remove unnecessary blank lines from your code before posting to the forum. One or two to separate code into sections is fine but large spaces for no reason just make for more scrolling when we're trying to read your code.
nyphot:
Not that it's part of your question, but I'm curious why are you PWM-ing a vibrator?- do you want different degrees of vibration?
If I'm not mistaking, a vibrator works under the same principle of a DC motor. So I figured PWM would be the best method. Is that not the case?
No, I don't want diffrent degrees of vibration. The vibrator also runs on 3V and I can easily adjust the PWM's duty cycle to provide the required input.