понедељак, 20. фебруар 2012.

Matrix led display controlled by Arduino and Android - the coding part

HI guys,

  hope you have enjoyed reading our last post about matrix led display. As we mentioned earlier, this post is going to be about coding Arduino and Android so we could use it to control our system...

 We can start with Arduino code. So, what is actually needed? Of course, because we use MAX7219 martix led drivers you guess we will use some code and libraries that are (closely) connected with this drivers. Very usefull page about that and our initial guide to get more information about Arduino coding was http://www.pjrc.com/teensy/td_libs_Matrix.html, so thanks to people who made this page. First, readers can get some basic info about hw parts and more important and more usefull they can find some basic about used libraries. Those are Matrix.h and Sprite.h.  About them, you can find more at http://wiring.org.co/reference/libraries/Matrix/index.html  and 
http://wiring.org.co/reference/libraries/Sprite/index.html . So, if you write any code based on those two libraries, it is good to start with this because some elementary code about almost every command is present on those links. So, let's see onde again picture of our system.


Now we will try to explaine most important parts of our Arduino code, and if anyone needs more explination, try to contact us via mail or better, write comment, and we will send our code. Get in mind that for  first couple lines of code - it is connected with bluetooth configuration and more about that you can find in our post about Bluetooth - http://arduinoandroid.blogspot.com/2011/11/post-number-2-work-version.html


ArduinoSolution
#include <NewSoftSerial.h> // Bluetooth library
#include <Sprite.h>  // Sprite before Matrix
#include <Matrix.h>
// instance of Matrix class with Arduino digital pins we use for DIN, CLOCK and //LOAD, respectively
//                     DIN, CLK, LOAD, #chips
Matrix myLeds = Matrix(12, 11, 10, 3);
byte byteNiz[200]; //  Array for readed characters
int pokByte =0; // pointer for the currently read character

int i=23; // column value from where characters are started moving on display
byte proc;  //  character currently being worked with
int maks=0; // total length of text that will rotate on display
int razlika = 0; // this is actually maks - length of display(23, because 3 matrix //8x8)
int citao = 0; // for 0, character is being read, for 1 just shown rotating on display
int krajnjaPozicija = 23; // max column value of display (depends of number of led matrices)

int bluetoothTx = 2;  // TX-O pin for bluetooth mate, Arduino D2
int bluetoothRx = 3;  // RX-I pin for bluetooth mate, Arduino D3
NewSoftSerial bluetooth(bluetoothTx, bluetoothRx); // instances of bluetooth, //will be used for receiving characters from android app
...                         
... // for every letter (or better), for every sing you want to see on display, define //instances of Sprite, set height and witdh...with red colour, we wanted to show //you what sign is specified...define this for every letter you need
Sprite letter_A = Sprite(5, 7,
  B01110,
  B10001,
  B10001,
  B11111,
  B10001,
  B10001,
  B10001
);

Sprite letter_B = Sprite(5, 7,
  B11110,
  B10001,
  B10001,
  B11110,
  B10001,
  B10001,
  B11110
);
... // // Setup function - being executed only once, when program is being //started
void setup()
{
  Serial.begin(9600);  // Serial communication at 9600bps
  bluetooth.begin(115200);  // BaudRate for Bluetooth module is 115200bps  bluetooth.print("$$$");  // Get into Bluetooth mode command mode
  delay(100);  // Short delay, so Bluetooth can answer with CMD  bluetooth.println("U,9600,N");  // get back to 9600, because 115200 can be to fast for NewSoftSerial  
  bluetooth.begin(9600);  // baudrate for bluetooth modul now is 9600     bluetooth.print("$$$");
  delay(100);
  bluetooth.println("w");
  delay(1000);
  bluetooth.println("---");/ exit from command mode
  // Finished configuration od BT mate
 
  myLeds.clear();// clear led display 
  myLeds.setBrightness(15); // set value for Led brightness        Serial.begin(9600);
  // niz u koji se smestaju karakteri se popuni nulama
  for( int brojac=0; brojac<200; brojac++ )
    byteNiz[brojac] = 0;
    pokByte = 0; 
}

// loop function, repeats all the time while the program is running
void loop()
{
  myLeds.clear();// to refresh the display     
  readLetter();//  function used for character reading   
if( citao == 1 )
       drawLetter(); // function for showing text on led display
}

// FUNCTION FOR READING CHARACTERS
void readLetter()
{
 if ( bluetooth.available() > 0 )
 { // set values on initial state 
  i=23; 
  maks = i; // current length of text, it will grow
  citao = 0; // for 0 is reading , for 1 is drawLetter in loop()
  pokByte = 0; 
        // while BT recieves characters, they are recieved and ready for work
     while ( bluetooth.available() > 0 )
     {
       proc = bluetooth.read(); // recieved character is now in proc
       byteNiz[ pokByte ] = proc; // put proc in recieved characters array
       pokByte = pokByte+1; // set pointer for the new character
         // for every recieved character increase length of the text
         switch (proc)
         {
            case 'a' :
            case 'A' :
             maks = maks+6;
            break;
           
            case 'b' :
            case 'B' :
             maks = maks+6;
            break;
... // treba proveriti za svaki karakter od mogucih za ispis
...
     razlika = maks - 23; // difference between text length and display length
     citao = (citao+1)%2 ; // reading is finished and now text can be shown on display
    }
  else 
     citao = 1; // continue with showing old text if there is no new text  
}

//FUNCTION FOR SHOWING TEXT ON DISPLAY
void drawLetter()
{   
   if( i < 0-razlika+1 )  // if all text has passed on display
    i = krajnjaPozicija; //  start again with showing text
   
   int poz = i;   // temporary variable for showing text

  // ispis procitanih slova
  for( int brojac = 0; brojac <pokByte; brojac++ )
  { // conditions that serve us for showing just letters that are on visiable //part of display
   boolean uslov1 = poz >= -5 && poz < 24 ;
   boolean uslov2 = (poz >=- 4) && (poz < 24 ) ;
   boolean uslov3 = (poz >=- 2) && (poz < 24 ) ;
   boolean uslov4 = (poz >=- 3) && (poz < 24 ) ;
   
    // you get character, and depending on its value, you show adecvate //character on led display  
   switch( byteNiz[brojac] )
   { // examples for letters (A,a) and (B,b)
     case 'a' :
     case 'A' :
     if( uslov1 ) 
        myLeds.write( poz , 0 , letter_A ); // show on display
    poz = poz+6; // places needed for character + one blanco
      break;
      case 'b' : // examples for (B,b)
      case 'B' : 
       if( uslov1 )
        myLeds.write( poz , 0 , letter_B );
    poz = poz+6; // places needed for character + one blanco
...
...
...
i = i-1; move left for one position
citao = 1;  // text continues to show on display    
delay(225); // short delay that gives effect that text is moveing
}




So, after Arduino code we need to say something about Android code. Once again, we needed to create Android application in which user brings in text, and via bluetooth sends it to led display. Also, we created virtual display on our Android device, that shows virtualy how text is going on the display (we will show that in pictures just a little later). So, because of Bluetooth usage, we needed to use, i think API 2.2 or above (but i'm preety sure that it is 2.2), because form this vrsion, Bluetooth is enabled. Here is the class diagram for the Arduino code, and we will try to explain most important parts of most important classes.

Class PocetnaStrana.java is responsable for the look of application when it starts.
PocetnaStrana.java
public class PocetnaStrana extends Activity implements OnCheckedChangeListener  // implements View.OnClickListener
{
      EditText tvTextZaReklamu ; // text field where text is being input
      Button sendButton, prelaz
      RadioGroup rg; // choose text color for virtual display on ANdroid
      String boja="red"  ; // default color is red   
      Context c
      String txt;
...
...
...
// icinijalizacija promenljivih u metodi OnCreate()
protected void onCreate(Bundle savedInstanceState)
      {
            // TODO Auto-generated method stub
      super.onCreate(savedInstanceState);
      setContentView(R.layout.prvapage);
      c=this.getApplicationContext();
      tvTextZaReklamu = (EditText) findViewById( R.id.editTextPolje );
      sendButton = (Button) findViewById( R.id.buttonSendMessage );
      rg = (RadioGroup) findViewById(R.id.radioGroup1);
      prelaz = (Button)this.findViewById(R.id.bBTConn);
      rg.setOnCheckedChangeListener(this);
     
// part of method to choose color
public void onCheckedChanged(RadioGroup group, int checkedId)
      {
            switch( checkedId )
            {
              case R.id.radioRedBoja :
                    this.boja="red";
                    break;
           
              case R.id.radioGreenBoja :
                    this.boja="green";
                    break;   
...
...
// 
sendButton.setOnClickListener(new View.OnClickListener()
{
      @Override
      public void onClick(View v)
      {
        txt = tvTextZaReklamu.getText().toString();
      Bundle basket = new Bundle(); //pas the data to new activity
      basket.putString("txt", txt); // put the data                     basket.putString("boja", boja); // pass the color of the text
                       
      hand.post(tmp); //pass the data to threed which controls the Bluetooth
                       
                     
Intent a = new Intent(PocetnaStrana.this,LedDispleyCommercialActivity.class);
      a.putExtras(basket); // put all data in basket
      startActivity(a); // go to new activity
...
...
...

// code for goint to activity connected with Vluetooth part of the code
prelaz.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
   Intent i = new Intent();
   i.setClass(c, Settings.class); 
   startActivity(i);
   }

...
...
...

// Handler which controls sending to BT mate device
public Handler hand = new Handler();
    Runnable tmp = new Runnable()
     {
       public void run()
       {try
        {
          outputStream=Singleton.remote_soket.getOutputStream();             
          String send=txt;
          byte[] bytesend = new byte[1024];
          bytesend=send.getBytes();                  
          outputStream.write(bytesend);              
                 




   Here is the look of application when it starts

 If you click on button Bluetooth connection, it goes to :


When Bluetooth connection achieved, you click save and back to main menu and return to start page, so enter text and click send, and text is now sent to Arduino and starts rotating on Led display. The procudere and code for that is already described earlier in this post when we talked about Arduino code. Also, application has presentation of virtual led display where text is also rotated from left to right.

Now we will describe most important parts of code for that virtual text rotation.

LedDisplayCommercial.java
public class LedDispleyCommercialActivity extends Activity
{   // atributi klase
    private MotionRunner mRunner; // instance class MotionRunner
    private int delay = 100; // delay speed

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Bundle getBasket = getIntent().getExtras();
       
        // get the text and color from the start activity
        String s = getBasket.getString("txt"); // get text
        String boja = getBasket.getString("boja"); // get color
        // inicijalizacija instance klase MotionRunner
        mRunner = new MotionRunner(this  , s , boja );
        setContentView(mRunner);
        mRunner.startIt(delay); // start thread for drawing virtual display
}
// method for resuming activity 
protected void onResume()
{
   super.onResume();
   mRunner.startLooper(delay);
}
// method for stopping
protected void onStop()
{
  super.onStop();
  finish();
}




 Those are most important classes of Android application, so if anyone needs more information, write a comment and we will try to answer and help/solve the problem. In next posts we hope to set some videos ones who are interested may see how system actually works, and potential idea is to try to gather some other guys (and girls) from university who also worked with Arduino and try to make some video podcast about our projects.
See you soon,
  M&M team





10 коментара:

  1. hello.
    excellent project.
    I would like to know the name of the android application that I use or if I could pass the link on the bluetooth of android application I use await your response, I loved the project.

    ОдговориИзбриши
  2. Hello Leonardo,thanks for your comment about the project. I'm not sure if i understand you well. Are you asking me about the code related to connection between the android device we used and Bluetooth silver module (by the way, post about it is - http://arduinoandroid.blogspot.com/2011/11/post-number-2-work-version.html). If you need that, just say and i will try to send you that code. Are you working of some similar project, maybe you have some article or project which you can read about and send us to see it?
    Greetings

    ОдговориИзбриши
  3. Hello.
    I want is the app you are using in android, as the play google search and did not find it.
    I like your project and there I was thinking considencia do something similar, as it is for a school work and have been looking for information because what I thought equals your project and when I saw it I was struck .
    just wanted to know if you have the link to download the android bluetooth app to send text to the LED matrix.
    sorrry for how I write, because some English
    read but writing is very little

    ОдговориИзбриши
  4. hello
    I want to know is whether your app is on Google android play

    ОдговориИзбриши
  5. hello Leonardo, sorry for replying delay from my side. My app is not on the Google android play, simply because you need all the hardware so the application can work. I had biggest fear when i started my project because i didn't know how to program Bluetooth transmission. After searching and searching on the net, I've found some codes and examples, but nothing strictly precise...so i experimented. If you are interested, send me your e-mail, and I will send you my code if you think it will help.

    Greetings

    ОдговориИзбриши
  6. Hi I wonder if I could pass the code to the application that used in android

    ОдговориИзбриши
  7. hello..how about if i want use wireless application than bluetooth???what i need to do??can u help me on coding..

    ОдговориИзбриши
  8. Hello, sorry about answer delay, it's because of the holidays. Well, I think if you want to use wireless you can try first with looking for some similar solutions on Google and YouTube based on wireless communication modules. I think that for Arduino may be used some type of wireless shield (similar to Bluetooth module used in this solution).

    So, find all the hardware parts and investigate a little, and than coding part comes.

    Best regards

    ОдговориИзбриши