Go Down

Topic: MKRWAN1300 behaving differently when connected to a battery? (Read 736 times) previous topic - next topic

KingVichai

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:
Code: [Select]


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

mjunior-fitec

Hello KingVichai.
Is your whole code here?
If so, while using the PC USB, does the the Serial.println debugs works correctly also?

I miss the common Serial.begin(BAUD); and while(!Serial) lines. Remember to treat it correctly when not using the PC USB. If you need a sample code I can suggest you, just ask.

Also, how is the sharp sensor powered on the 2 scenarios?
Please give us a little more information so we can help you better.

Regards.

MITEL

Further details are needed as asked also by mjunior, however it seems strange that the code, as is, does what you want when USB powered .  Check these details:

Code: [Select]
// turn LED off:
   digitalWrite(ledPin, HIGH);


and

   
Code: [Select]
digitalWrite( ledPin, HIGH ); // Turn on the power to the LED pin

and

Code: [Select]
  if (buttonState == LOW) {
    // turn LED on:
    digitalWrite(ledPin, LOW);


Something is clearly wrong, and likely it is going ok only by chance.

Go Up