Hi there,
I am using a simple code to turn on my LED when a button is pushed and when the sharp sensor detects something close. Below is my code to do this:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 5; // the number of the LED pin
#define SHARP_PIN A1 // Sharp pin number
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
float distSharp = analogRead(SHARP_PIN);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == LOW) {
// turn LED on:
digitalWrite(ledPin, LOW);
Serial.println(buttonState);
} else {
// turn LED off:
digitalWrite(ledPin, HIGH);
Serial.println(buttonState);
Serial.println(distSharp);
delay(1000);
// Serial.println(distSharp);
}
if( distSharp > 250 ){ // I
digitalWrite( ledPin, HIGH ); // Turn on the power to the LED pin
Serial.println(distSharp);
// delay(2000);
}
else {
digitalWrite( ledPin, LOW ); // Turn off the power to the LED pin
Serial.println(distSharp);
// delay(1000);
}
}
The code seems to work fine when I connect the Arduino MKR WAN1300 via USB to my computer. However, when I connect it with a battery, the LED just turns ON all the time. I would like the LED to work the same way when its connected to the PC.
Please help