7 Aug 2012

First Android App controls android via bluetooth LEDs

A fairly simple one. I will only describe how the seek bar works, and part of how commands are recognized by arduino (arduino code). I will do another one about bluetooth another day.






Full Arduino Code:


byte packet[2];
int pIndex;

int rPin = 9;
int yPin = 10;
int gPin = 11;

byte rValue = 0;
byte yValue = 0;
byte gValue = 0;

void setup() {
        Serial.begin(9600);
}

void loop() {

       
       
        // see if there's incoming serial data:
        if (Serial.available() > 0) {
                packet[pIndex++] = Serial.read();
        }
       
        if(pIndex >= 2){
       
                switch(packet[0]){
                        case 'r':
                                rValue = packet[1];
                                break;
                        case 'y':
                                yValue = packet[1];
                                break;
                        case 'g':
                                gValue = packet[1];
                                break;
                        default:
                                ;
                }
               
                analogWrite(rPin, rValue);   // 0 - 255
                analogWrite(yPin, yValue);  
                analogWrite(gPin, gValue);  
               
                Serial.print(packet[0],);
                Serial.print("  ");
                Serial.println(packet[1]);
               
                pIndex = 0;
               
        }
       
        delay(100);
}


Android Code (java):

I am not going to post all the source code because i have a lot of unneeded controls in the code, and I have no time to tidy it up, so I will only post the relevant snippets.
if you have any error, it's probably want you to import the library :)

Create SeekBars, and it's value (using byte because of the bluetooth nature)

SeekBar sr;
SeekBar sy;
SeekBar sg;
byte srValue;
byte syValue;
byte sgValue;


Set seekbar maximum value to 255, as the max of a byte is 255.

        sr.setMax(255);
        sy.setMax(255);
        sg.setMax(255);


And lastly, setup the event listener for the seekbar, we put the progress value in memory, and only send it to target device when we finish dragging it to reduce data traffic, i will only show one of the seekbar listener.

        sr.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
tv1.setText("Red " + progress);
srValue = (byte) progress;
}

public void onStopTrackingTouch(SeekBar seekBar) {
String temp = "r";
byte bytes[] = temp.getBytes();
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.write(srValue);
} catch (IOException e) {
e.printStackTrace();
}
}
       
       
           });

No comments:

Post a Comment

Note: only a member of this blog may post a comment.