336Views4Replies

Author Options:

help with arduino programming? Answered

right so i made this IR proximity detector, and having trouble with the code...

#include <MsTimer2.h>
#define irx 2

static boolean output = HIGH;

int Ledpin = 13;

void setup(){
pinMode(Ledpin, OUTPUT);
pinMode(irx, INPUT);
Serial.begin(9600);
MsTimer2::set(5, flash);
MsTimer2::start();
}

void loop(){
while(digitalRead(irx));
Serial.println("detected");
digitalWrite(Ledpin, HIGH);
}

void flash() {
digitalWrite(12, output);
output = !output;
}

i want the LED to be on when it detects something and go off when it doesnt detect anything, but after it detecs something it stays on for ever... :(

wjhat wrong here?

Discussions

0
None
NachoMahma

9 years ago

. I'm not familiar with Arduino programming, but it looks to me like you need an IF...THEN...ELSE in loop(). This is probably not valid code, but should give you the idea void loop(){ if (digitalRead(irx)); Serial.println("detected"); digitalWrite(Ledpin, HIGH); else Serial.println("gone"); digitalWrite(Ledpin, LOW); }

0
None
amando96NachoMahma

Answer 9 years ago

yea that was about the code i managed to fing after a while althought this way it takes less space void loop(){ digitalWrite(Ledpin, LOW); while(digitalRead(irx)); digitalWrite(Ledpin, HIGH); all i did was forget to turn the LED off, thats why it was always on xD

0
None
NachoMahmaamando96

Answer 9 years ago

. Nice solution. Any code that does what you want it to do is good code. ;)

0
None
Laserman595NachoMahma

Answer 8 years ago

ok Here is a super simple version, it has been compiled and works great and it only takes up 2406 bytes!  (of 30720 bytes max)


int ledPin = 8;
int PirPin = 9;
int val = 0;

void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(PirPin, INPUT);
}

void loop() {
val = digitalRead(PirPin);
if (val == LOW) {
  digitalWrite(ledPin, LOW);
  Serial.println("gone");
} else {
  digitalWrite(ledPin, HIGH); 
  Serial.println("detected");
  delay(2000); // delay to insure you see the led
}
}