0
votes

I am trying to send a message from my arduino via bluetooth to my android app that I wrote. Here is my sketch:

int ledPin = 13;
int buttonPin = 8;
byte leds = 0;

void setup() 
{ 
  Serial.begin(9600); //note this may need to be changed to match your module 
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
} 

void loop() 
{ 
  if (digitalRead(buttonPin) == LOW)
  {
    Serial.println("BUTTON PUSHED");
    digitalWrite(ledPin, HIGH);
  }
  if (digitalRead(buttonPin) == HIGH)
  {
    Serial.println("NO BUTTON");
    digitalWrite(ledPin, LOW);
  }

} 

When I load my android app, it finds my arduino and asks me to pair it. I can see the 'no button' text on the phone, but when I push the button nothing happens. I don't receive anything. I am thinking it has to do something with the arduino sketch.

1

1 Answers

0
votes

The loop() code runs at full speed. At 9600 baud, the code as shown will be transmitting "NO BUTTON" about 100 times per second. The input buffer on the Android side is flooded with the NO BUTTON message. By the time you get to press the button, it is too late.

First test: hold or lock the button down while you reset the Arduino. You should see "BUTTON PUSHED"

Options for fix are

  1. Rate limit (low tech)

    void loop {
      ... existing poll and send code ...
      delay(2000);
    }
    
  2. Send only when state changes (likely what you intend)

    int laststate = 2;
    
    void loop() {
      int state = digitalRead(buttonPin);
      if( state != laststate ) {
        if( state == HIGH ) {
          // ... send message ...
        else if( state == LOW ) {
          //... send message ...
        }
        laststate = state;
      }
    }