Ketai Library

edited October 2016 in Android Mode

hii.. Has anyone used the bt.broadcast function for bluetooth ?

Answers

  • There is an example in ketai.org showing the usage of bt.broadcast:

    http://ketai.org/examples/bluetoothcursors/

    You need to click on the source code pde files as the example shown in the page does not match the title for reasons I don't know. Here are the direct link:

    http://ketai.org/examples/bluetoothcursors/BluetoothCursors.pde

    http://ketai.org/examples/bluetoothcursors/UI.pde

    How to test the code? You will need two android devices. Load the code in both of them and run them simultaneously so they can discover each other. This is the first step for you to get a working example of android BT. The next step is to get it working with your other platform.

    Kf

  • edited October 2016
    /*Hi kfrajer..
    well i have been working a while with processing android Mode, i do know this example and i have no Problem with Platforms and sdk manager.. Its working.. 
    
    I will get to my Goal, perhaps you could give a Tipp, i have an Arduino Sketche which let me to control the color of  RGBW Leds ( in my case its the Sk6812) from my android phone over Bluetooth, by sending the Integers of the Red, Green and Blue Pixels where my finger is on the smart phone. i am using now an Application which is availible in Google play store(Color LED Controller). My Goal is to write  something similiar on Processing and install it on my phone.because i nedd to mdify it . I dont want to make it difficult or annoying for you, i have rewritten the app on processing, i have like 98% of it. 
    Here is the Code of the app in Processing:
    
    */``
    // Proceesing code :
    
    
    import android.content.Intent;
    import android.os.Bundle;
    import ketai.net.bluetooth.*;
    import ketai.ui.*;
    import ketai.net.*;
    import oscP5.*;
    
    KetaiBluetooth bt;
    String info = "";
    KetaiList klist;
    
    ArrayList<String> devicesDiscovered = new ArrayList();
    boolean isConfiguring = true;
    PFont fontMy;
    int rectColFactor = 0;
    PImage img;
    byte red,green,blue;
    byte reddata;
    byte greendata;
    byte bluedata;
    
    //********************************************************************
    // The following code is required to enable bluetooth at startup.
    //********************************************************************
    void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      bt = new KetaiBluetooth(this);
    }
    
    void onActivityResult(int requestCode, int resultCode, Intent data) {
      bt.onActivityResult(requestCode, resultCode, data);
    }
    
    void setup()
    {   
     size(displayWidth, displayHeight);
      orientation(PORTRAIT);
      background(78, 93, 75);
      stroke(255);
      textSize(24);
    
     img = loadImage("colorwheelrgb2.png"); // this is rgb color Wheel 
      //start listening for BT connections
      bt.start();
    
    
      fontMy = createFont("SansSerif", 40);
      textFont(fontMy);
    
    }
    void draw()
    {
    
    
      if (isConfiguring) 
      { 
        //-------------------- This stuff is for us to select the intended device
        // ketai lib's UI list is used
        ArrayList names;
        //background(255, 0, 0);
        klist = new KetaiList(this, bt.getPairedDeviceNames());
        isConfiguring = false; // make the "configuring" status false as we have successfully configured
      } else
      { 
        //After configuration everything happens here
    
        //first set a new background to say we are connecetd
        //background(255, 255, 0);
        fill(0);
        noStroke();
        textAlign(LEFT);
        textSize(100);
        text(info, 100, 1500);
      }
        image(img, 0, 0);
       img.loadPixels();
    
    }
    //------ For killing the list after you've selected a device to pair 
    
    void onKetaiListSelection(KetaiList klist) {
      String selection = klist.getSelection();
      bt.connectToDeviceByName(selection);
      //dispose of list for now
      klist = null;
    }
    
    //----Call back method to manage data received
    void onBluetoothDataEvent(String who, byte[] data) {
      if (isConfiguring) {
        return;
      }
      //received // i want to recieve an Integer from arduino -- works fine 
      info = new String(data);
      rectColFactor = Integer.parseInt(info);
    
     }
    
    void mousePressed() 
    {
    
     if (mouseX <= 1440 && mouseX > 0 && mouseY < 1440 && mouseY>0){
    
    //because i need to send the pixels only when i touch color wheel, not the larger //Background 
    
    // these three lines give me the red , green , blue pixels values, work fine too!!
    // i transformed the values to byte because like i understood the bt.broadcast //only can send bytes ,, i might be wrong !
     red =byte((int(red(img.pixels[mouseX+mouseY*img.width]))));
     green = byte((int(green(img.pixels[mouseX+mouseY*img.width])))); 
     blue =byte((int(blue(img.pixels[mouseX+mouseY*img.width])))); 
    
    // here is my problem 
    // now i want to use the bt.broadcast to send them 
    // i tried this 
    
    byte []data = { (byte)red,(byte)green,(byte)blue};
    byte []a = {')'};  
    // marks the beginnig so that arduino knows where is the beginning of the Sting 
    byte[]b={'.'}; // and this for the split of the values in arduino 
    
    // now i want to send them 
    
    //i tried this for example and many other things with no success by comiling //allways error on processing consol
    bt.broadcast(a);
    bt.braodcast(data);
    bt.broadcast(b);
    
    }
    }
    
    // End of processing code--------------------------------------------
    
    // Here is the Error on the processing Console when i compile in this case
    
    The method broadcast(byte[]) in the type KetaiBluetooth is not applicable for the arguments (byte)
    
    //Note: if i use the bt.broadcast function with this 
    
    byte[] data1={(byte)0x01, (byte)0x00}; bt.broadcast(data)
    // it does compile and works 
    
    ---------------------------------------------------------------------
    
    //Arduino Sketche which works with the App from Google STore
    
    #include <Adafruit_NeoPixel.h>
    #ifdef __AVR__
      #include <avr/power.h>
    #endif
    
    #define PIN 6
    
    #define NUM_LEDS 3
    
    #define BRIGHTNESS 50
    
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRBW + NEO_KHZ800);
    
    String RGB = ""; //store RGB code from BT
    String RGB_Previous = "255.255.255)"; 
    //preserve previous RGB color for LED switch on/off, default White
    String ON = "ON"; //Check if ON command is received
    String OFF = "OFF"; //Check if OFF command is received
    boolean RGB_Completed = false;
    
    
    
    void setup() {
      Serial.begin(9600);
    
      strip.setBrightness(BRIGHTNESS);
      strip.begin();
      strip.show(); // Initialize all pixels to 'off'
    
    
    
    void loop() {
        // put your main code here, to run repeatedly: 
    
      //Read each character from Serial Port(Bluetooth)
      if(Serial.available()){
        char ReadChar = (char)Serial.read();
    
      // Right parentheses ) indicates complet of the string
        if(ReadChar == ')'){
          RGB_Completed = true;
        }else{
           RGB += ReadChar;
        }
      }
    
      //When a command code is received completely with ')' ending character
      if(RGB_Completed){
       //Print out debug info at Serial output window
          Serial.print("RGB:");
         Serial.print(RGB);
          Serial.print("     PreRGB:");
          Serial.println(RGB_Previous);
    
          if(RGB==ON){
              RGB = RGB_Previous; //We only receive 'ON', so get previous RGB color back to turn LED on
              Light_RGB_LED();          
    
          }else if(RGB==OFF){
              RGB = "0.0.0)"; //Send OFF string to turn light off
              Light_RGB_LED();
          }else{
              //Turn the color according the color code from Bluetooth Serial Port
              Light_RGB_LED();   
              RGB_Previous = RGB;     
          }
          //Reset RGB String  
    
          RGB = "";
          RGB_Completed = false;
    
    
      } //end if of check if RGB completed
    
    } // end of loop
    
    void Light_RGB_LED(){
    
      int SP1 = RGB.indexOf('.');
      int SP2 = RGB.indexOf('.', SP1+1);
      int SP3 = RGB.indexOf('.', SP2+1);
      String R = RGB.substring(0, SP1);
      String G = RGB.substring(SP1+1, SP2);
      String B = RGB.substring(SP2+1, SP3);
    
      //Print out debug info at Serial output window
      Serial.print("R=");
      Serial.println( constrain(R.toInt(),0,255));
      Serial.print("G=");
      Serial.println(constrain(G.toInt(),0,255));
      Serial.print("B=");
      Serial.println( constrain(B.toInt(),0,255));
      //Light up the LED with color code
    
    if ( constrain(R.toInt(),0,255) > 250 && constrain(G.toInt(),0,255)> 250 && constrain(B.toInt(),0,255) > 250 )
    
      {
    
        for(int i=0;i<strip.numPixels();i++){
    
        // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
           strip.setPixelColor(i, strip.Color(0,0,0,255 ) );
    
        strip.show(); // This sends the updated pixel color to the hardware.
    
        delay(1); // Delay for a period of time (in milliseconds).
    
               }
    
    
      }
    
    else {
    for(int i=0;i<strip.numPixels();i++){
    
        // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
           strip.setPixelColor(i, strip.Color(constrain(R.toInt(),0,255),constrain(G.toInt(),0,255),constrain(B.toInt(),0,255),0 ) );
    
        strip.show(); // This sends the updated pixel color to the hardware.
    
        delay(1); // Delay for a period of time (in milliseconds).
    
               }
    }
    
    
    }
    
    // End of arduino Sketch .- Does Work Perfct 
    
    //Hope you could do help !! Thank you``
    
  • edited October 2016

    code formated

  • Tip: When you format your code in a post, only select the lines you want to format (aka your code lines) Make sure there is an empty line above and below your code. On the selected text, you hit ctrl+o.

    Kf

  • @zeroo===

    what sdk are you targetting???

  • What code are you executing when you get the following command:

    The method broadcast(byte[]) in the type KetaiBluetooth is not applicable for the arguments (byte)

    I am guessing what you are doing is sending a single byte value and not a byte array as defined in the underlined function call. Unfortunately the documentation on Ketai net package doesn't seem to be available in the ketai.org website. However you can also refer to the source code in github:

    https://github.com/ketai/ketai/tree/master/src/ketai/net/bluetooth

    I modify part of your code next. NOTE: This is untested (!) The following code adds clarity and does exactly what is required for your arduino code to work. Check the P5 reference for more info:

    https://processing.org/reference/rightshift.html

    https://processing.org/reference/get_.html

    void mousePressed() 
    {
    
      if (mouseX <= 1440 && mouseX > 0 && mouseY < 1440 && mouseY>0) {
    
        color pixColor = img.get(mouseX, mouseY);
        byte redCol = (pixColor >> 16 & 0xFF);
        byte greenCol = (pixColor >> 8 & 0xFF);
        byte blueCol = (pixColor >> 0 & 0xFF);
        byte colSeparator = '.';
        byte endPackage=')';
    
        //ARDUINO code reading color data 
        //int SP1 = RGB.indexOf('.');
        //int SP2 = RGB.indexOf('.', SP1+1);
        //int SP3 = RGB.indexOf('.', SP2+1);
        //String R = RGB.substring(0, SP1);
        //String G = RGB.substring(SP1+1, SP2);
        //String B = RGB.substring(SP2+1, SP3);
    
        byte []data = { redCol, colSeparator, greenCol, colSeparator, blueCol, colSeparator, endPackage};
        bt.braodcast(data);
      }
    }
    

    I hope this helps,

    Kf

  • @kfrajer  
    just tried to comiple the code with your modified part, im getting 4 errors 
     ERROR in C:\Users\Labor1\AppData\Local\Temp\android1388187234378872705sketch\src\processing\test\recievepotiwert_sendrgbwheel\RecievePotiWert_sendRgbWheel.java (at line 166)
        byte redCol = (pixColor >> 16 & 0xFF);
                      ^^^^^^^^^^^^^^^^^^^^^^^
    Type mismatch: cannot convert from int to byte
    ----------
    9. ERROR in C:\Users\Labor1\AppData\Local\Temp\android1388187234378872705sketch\src\processing\test\recievepotiwert_sendrgbwheel\RecievePotiWert_sendRgbWheel.java (at line 167)
        byte greenCol = (pixColor >> 8 & 0xFF);
                        ^^^^^^^^^^^^^^^^^^^^^^
    Type mismatch: cannot convert from int to byte
    ----------
    10. ERROR in C:\Users\Labor1\AppData\Local\Temp\android1388187234378872705sketch\src\processing\test\recievepotiwert_sendrgbwheel\RecievePotiWert_sendRgbWheel.java (at line 168)
        byte blueCol = (pixColor >> 0 & 0xFF);
                       ^^^^^^^^^^^^^^^^^^^^^^
    Type mismatch: cannot convert from int to byte
    ----------
    11. ERROR in C:\Users\Labor1\AppData\Local\Temp\android1388187234378872705sketch\src\processing\test\recievepotiwert_sendrgbwheel\RecievePotiWert_sendRgbWheel.java (at line 181)
        bt.braodcast(data);
           ^^^^^^^^^
    The method braodcast(byte[]) is undefined for the type KetaiBluetooth
    ----------
    11 problems (4 errors, 7 warnings)
    
  • @akenton API (6.0 ) 23

  • edited October 2016

    I guess you need to cast the values:

    byte redCol = (byte)(pixColor >> 16 & 0xFF);
    

    Kf

  • if i cast the value , i am gettint only one error with the broadcast function

    The method braodcast(byte[]) is undefined for the type KetaiBluetoothunction..

    im trying to goole it

  • @zeroo

    It is untested code.... meaning there could be errors and typos. Sorry! BROADCAST was misspelled.

    Also to play safe, cast the other values:

        byte colSeparator = (byte)'.';
        byte endPackage=(byte)')';
    

    Kf

  • pff didnt see that too .. it does compile now and i can lunch the sketch .!!. But nothing happens with Lights .. if i serial print the constrain(R.toInt(),0,255) on the arduino side , the three color value are always 0

  • with an error on the processing console when i touch the color Wheel saying: Error on reading connection data.:null

  • it seems to be common problem on the net ..has something to do with buffer length ?! or smth like that

  • I will suggests working in blocks.

    First of all, ensure the data bytes you transfer from your sketch and Arduino interface works. Send a known test data set and check its value in the Arduino side. For example, send "100.150.200.)" and ensure it is the same value in the arduino receive side.

    Then work with the color variables. Something to keep in mind is that in your Arduino side, you don't need to constrain the values because the values from processing (by default unless explicitly changed) are from 0 to 255.

    Last part is to get the LEDs working.

    Kf

  •     i tried to send a known data like this :
    
        color pixColor = img.get(mouseX, mouseY);
            byte redCol = (byte)(200);//(pixColor >> 16 & 0xFF);
            byte greenCol = (byte)(100);//(pixColor >> 8 & 0xFF);
            byte blueCol = (byte)(10);//(pixColor >> 0 & 0xFF);
            byte colSeparator = (byte)(',');
            byte endPackage=(byte)(')');
    

    and on the arduino i tried to serial print the constrain Values , it prints always 0.0.0

    tried to Serial.print the Strings too, these :

    String R = RGB.substring(0, SP1); String G = RGB.substring(SP1+1, SP2); String B = RGB.substring(SP2+1, SP3);

    R, G, B .. also same value for the Three , in ASCii Zeicheni guess..

  • i think the way to get this working is doing the same as the cursors example, but i dont really understand this KetaiOSCMessage in this example

  • OscMessage might not work. I mean, you could make it work but you will need to understand what the OSCmessage does for you. In other words, you need to understand how OSC build the data packages. From my own experience, OSC has two rules: It packs data in group of four bytes. When building the package structure, it requires to have at least one ZERO byte (a byte that stores 0 as a value) to separate between the structure patterns within the package.

    These are some intricacies of the OSCmessage that I learned from managing the library and it is a little bit more complex but really is not bad at all (more at http://www.sojamo.de/libraries/oscP5/). On the other hand, your code should have worked for a simple task of sending data bytes representing color. When you wrote your arduino code, did you use an existing example or do you have a link to the reference page you are using to write your code? I would like to see if possible.

    One thing you could do is to print what is the size of bytes your arduino code is receiving. If you send 200 . 100 . 10 . ) then you should be receiving 7 bytes.

    On line 232 of your original code, what do you get for the following modified code:

    void Light_RGB_LED(){
    
      println("RGB var contains: >>"+RGB+"<<"); //In arduino you use serial.println?
    
      int SP1 = RGB.indexOf('.');
      int SP2 = RGB.indexOf('.', SP1+1);
      int SP3 = RGB.indexOf('.', SP2+1);
      String R = RGB.substring(0, SP1);
      String G = RGB.substring(SP1+1, SP2);
      String B = RGB.substring(SP2+1, SP3);
    

    Kf

  •             if i print this on the arduino without println :
    
            void Light_RGB_LED(){
    
                 Serial.println("RGB var contains: >>"+RGB+"<<"); 
    
                  int SP1 = RGB.indexOf(',');
                  int SP2 = RGB.indexOf(',', SP1+1);
                  int SP3 = RGB.indexOf(',', SP2+1);
                  String R = RGB.substring(0, SP1);
                  String G = RGB.substring(SP1+1, SP2);
                  String B = RGB.substring(SP2+1, SP3);
    
                 Serial.print("R=");
                 Serial.print( constrain(R.toInt(),0,255));
                  Serial.print("G=");
                Serial.print(constrain(G.toInt(),0,255));
                  Serial.print("B=");
             Serial.println( constrain(B.toInt(),0,255));
    
        ---------------------------------------------------------------------i get this this on the Console:
    
        RGB var contains: >>È,d,
        ,<<
        R=0G=0B=0
        -----------------------------------------------------------------
    
    with Println like this :
    
      Serial.print("R=");
                 Serial.println( constrain(R.toInt(),0,255));
                  Serial.print("G=");
                Serial.println(constrain(G.toInt(),0,255));
                  Serial.print("B=");
             Serial.printlnln( constrain(B.toInt(),0,255));
    -------------------------------------------------------------------
    
    i get this :
    RGB var contains: >>È,d,
    ,<<
    R=0
    G=0
    B=0
    ---------------------------------------------------------------------
    
    if i print the strings R, G , B  without the Constrain ;
    
     Serial.println("RGB var contains: >>"+RGB+"<<"); 
    Serial.print(R);
    Serial.print(G);
     Serial.println(B);
    
    i get this :
    RGB var contains: >>È,d,
    ,<<
    Èd
    
    ---------------------------------------------------------------------
    this same arduino code works fine with the app..
    
    this would be the Link for the appinventor Seite , 
    
    http://stonez56.blogspot.de/2015/02/arduino-project-android-control-color.html
    

    for the arduino code :

    http://stonez56.blogspot.de/2014/09/arduino-android-led.html
    
    he is using a (.) to seperate the R,G and B ,  i tried both , same result
    
  • Ok so if you go to this website and in the decimal field input the following values

    200 46 100 46 10 46

    You will get the characters you are seeing in your output. 46 is the decimal representation of the dot character '.' in the ASCII table. I believe what is failing is the conversion from single character to integer. Maybe you should convert your R,G,B to char instead of integer. Usually integers are represented by 32 bits or 8 bytes. You are converting, for example, your single R variable (representing a single byte) into an integer. I am guessing your conversion is filling the other 7 bytes with 0xFF values. In a nutshell, your conversion is returning negative values which would explain why constrain returns 0. Here are some ideas:

    What do you get for this next:

                 Serial.print("R=");
                 Serial.print( R.toInt());
                 Serial.print("G=");
                 Serial.print(G.toInt());
                 Serial.print("B=");
                 Serial.println( B.toInt());
    

    Would next solve your problem:

              Serial.print("R=");
              Serial.print( constrain(R.toInt() & 0xff ,0,255));
              Serial.print("G=");
              Serial.print(constrain(G.toInt() & 0xff,0,255));
              Serial.print("B=");
              Serial.println( constrain(B.toInt() & 0xff,0,255));
    

    Kf

  • when i print this 
    
    Serial.print("R=");
    Serial.print( R.toInt());
    Serial.print("G=");
    Serial.print(G.toInt());
    Serial.print("B=");
    Serial.println( B.toInt());
    
    i get :
    R=0G=0B=0
    ---------------------------------------------------------------------and with :
    
    Serial.print("R=");
    Serial.print( constrain(R.toInt() & 0xff ,0,255));
    Serial.print("G=");
    Serial.print(constrain(G.toInt() & 0xff,0,255));
    Serial.print("B=");
    Serial.println( constrain(B.toInt() & 0xff,0,255));
    
    
    i get :
    
    RGB var contains: >>È.d.
    .<<
    R=0G=0B=0
    
  • always 0.0.0
    i dont get it why ---

  • As suspected, the toInt() function is not working as expected. Arduino reference describes exactly what the function expects:

    https://www.arduino.cc/en/Reference/StringToInt

    Here is an example: https://www.arduino.cc/en/Tutorial/StringToIntExample

    So, if your string variable does not contain numbers, it will return zero. In other words, you cannot use this to convert your string to integer. I won't be able to test the solution, but I will probably suggest running a simple code in your arduino side to make sure your conversion is working:

    String myRGB= "a.b.c.)";  //Init a string simulating incoming data
      // 'a' is 97, 'b' is 98, etc.
    
    int charsCounter=0;                         //Keep track of how many chars read so far
    boolean doneIncomingData=false;   //When three chars have been red aka R, G, B
    int[3] myRGB;  //Array storing data
    
    void setup() {
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
    }
    
    void loop(){
        if (Serial.available() && !doneIncomingData ) {
          char readChar = (char)Serial.read();
    
          if(readChar==')')
            doneIncomingData=true;
    
          else if(readChar=='.')
            charsCounter++;
    
          else if(charsCounter<3) //We are expecting three chars
            myRGB[charsCounter] = (int)readChar;
        }
    
      if(doneIncomingData ==true){
    
         //Print out debug info at Serial output window
        Serial.print("R=");
        Serial.println(myRGB[0]);
        Serial.print("G=");
        Serial.println(myRGB[1]);
        Serial.print("B=");
        Serial.println(myRGB[2]);
        //doneIncomingData =false;  //This line gets this program ready to receive the next transmission
      }
    }
    

    Now, before you set into the quest of getting bluetooth working with your arduino code, I would strongly encourage for you to send data from a proceessing sketch first. In this way you can get a proper basic code working. Your first code should ensure you are sending data from a processing sketch and receiving the data in your arduino code correctly. Only then you should try getting bluetooth working for Android. You need to make sure you have a working code. For example, line 170 in your first post containing your code:

    String RGB_Previous = "255.255.255)"

    This line doesn't agree with your strategy of decomposing the incoming data as described in your code:

    int SP1 = RGB.indexOf(',');
    int SP2 = RGB.indexOf(',', SP1+1);
    int SP3 = RGB.indexOf(',', SP2+1);
    String R = RGB.substring(0, SP1);
    String G = RGB.substring(SP1+1, SP2);
    String B = RGB.substring(SP2+1, SP3);
    

    This code will only work properly if your incoming data were:

    String RGB_Previous = "255.255.255.)"

    aka. Having three dots '.' in your received data.

    Kf

  • edited October 2016

    hey.. there are couple errors in this arduino sketch.

    int[3] myRGB;  //Array storing data

    this doesnt work , it should be like that :: int myRGB [3];
    and even when you will get the error :.conflicting declaration 'int myRGB [3]' because the same is declared as string above ..

    in the first code i posted,this Line :: String RGB_Previous = "255.255.255.)"

    is never ment to be decomposed if i am correctly thinking, it just takes the same Value of the RGB String : // RGB = RGB_Previous
    when you swutch on and off

  • no actually your right it must be demoposed otherwise i wont be able to get the three values.. But still if it deosnt agree with the strategy , so how is it working ? It should work with the first arduino code if the data from prcessing are send in this form .. i dont get it

  • edited October 2016

    I´m getting some progress here..

    from the processing android im sending the usual


        color pixColor = img.get(mouseX, mouseY);
        byte redCol = (byte)(pixColor >> 16 & 0xFF); 
        byte blueCol = (byte)(pixColor >> 0 & 0xFF);
        byte colSeparator = (byte)(('.'));
        byte endPackage=(byte)((')'));
    
        byte data[] = { redCol, colSeparator, greenCol, colSeparator, blueCol,endPackage};
    
     bt.broadcast(data);
    

    and on the arduino im just trying a simple code :

            String RGB ="";
    
            void setup() {
              Serial.begin(9600);
            }
    
            void loop() {
    
    
              if(Serial.available()){
             RGB = Serial.read();
    
                 Serial.println(RGB);
            }
    

    }

    in the arduino console im getting correct Values , like if i touch a white Color im getting :


    255 // for R
    46 // for colSeparator
    255 // G
    46 // colSeparato
    255//B
    

    41// colSeparator

    but i am not able to split them

  • edited October 2016

    the problem is that the String RGB is overwriting itself , not sure how to split the values

  • edited October 2016 Answer ✓

    this doesnt work , it should be like that :: int myRGB [3];

    You are correct. My bad, I was writing java code. I cannot differentiate btw java and C (arduino) since I don't have any arduino units with me. Good that you knew how to properly resolve that problem.

    conflicting declaration 'int myRGB [3]' because the same is declared as string above ...

    My bad again. You should remove the String declaration. The code I provide was to processed receive bytes from a processing sketch. The received data would expect a format "#.#.#.)"

    in the first code i posted,this Line :: String RGB_Previous = "255.255.255.)"

    This does not agree with line 170 of your original post. This is extremely important: you need consistency. Even if you think it does not get executed, you have to stick to one package structure. MessageOSC has its own package structure. You are very welcome to use it in processing. The challenge is to decompose it on the Arduino side. I am not sure if you can find the OscP5 lib in C version and available to be compiled for ARM architecture.

    the problem is that the String RGB is overwriting itself , not sure how to split the values

    There are different strategies. A possible option

    http://stackoverflow.com/questions/9210528/split-string-with-delimiters-in-c

    You have to remember you are transmitting bytes so if you are using string variable to store your receive packages, use them with caution. Looking at this reference: https://www.arduino.cc/en/Serial/Read I believe this could do what you want (with a slight modification):

    //NEXT: Index 0: red, index 1:green, index 2: blue
    int incomingRGB[3];   // for storing RGB data
    int incomingByte;        // for incoming serial data
    int charNumberRead=0;
    
    void setup() {
            Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
    }
    void loop() {
    
            // send data only when you receive data:
            if (Serial.available() > 0) {
                    // read the incoming byte:
                    incomingByte = Serial.read();
    
                    // say what you got:
                    Serial.print("I received: ");
                    Serial.println(incomingByte, DEC);
    
                    //next if it is a '.' separating R G B values
                    if(incomingByte ==46){
                      charNumberRead++;
                    }
                    else if(incomingByte ==41){  //41 refers to ')' from ASCII tables
                     //Reached end of package: Reset counter for next data set
                      charNumberRead=0;  
    
                      //Print results
                      serial.println("Summary of received data:");
                      serial.print("Red: ");
                      serial.print(incomingRGB[0]);
                      serial.print("Green: ");
                      serial.print(incomingRGB[1]);
                      serial.print("Blue: ");
                      serial.print(incomingRGB[2]);   
                      serial.println();
                      delay(500);                
                    }
                    else{
                       //Process incoming color data
                       //You might need to "and" your data with 0xff since integer
                       //fields are 4 bytes and byte fields are only one byte. 
                       //0xff ensures all the other 3 bytes from the integer fields 
                       //are set to ZERO
                       incomingRGB[charNumberRead]=incomingByte  & 0xff;
                    }
            }
    }
    

    --------------------------EDITED:Code changed!

    Let me know if it works for you.

    Kf

  • hii.. this code didnt compile error: //*************************************

    C:\Users\Labor1\Desktop\Nina2AppSketch\Nina2AppSketch.ino: In function 'void loop()':

    Nina2AppSketch:12: error: incompatible types in assignment of 'int' to 'int [3]'

                 incomingByte =  Serial.read();
    
                              ^
    

    Nina2AppSketch:16: error: call of overloaded 'println(int [3], int)' is ambiguous

                 Serial.println(incomingByte, DEC);
    
                                                 ^
    

    C:\Users\Labor1\Desktop\Nina2AppSketch\Nina2AppSketch.ino:16:49: note: candidates are:

    In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Stream.h:26:0,

                 from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:29,
    
                 from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:224,
    
                 from sketch\Nina2AppSketch.ino.cpp:1:
    

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:74:12: note: size_t Print::println(unsigned char, int)

     size_t println(unsigned char, int = DEC);
    
            ^
    

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:74:12: note: no known conversion for argument 1 from 'int [3]' to 'unsigned char'

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:75:12: note: size_t Print::println(int, int)

     size_t println(int, int = DEC);
    
            ^
    

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:75:12: note: no known conversion for argument 1 from 'int [3]' to 'int'

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:76:12: note: size_t Print::println(unsigned int, int)

     size_t println(unsigned int, int = DEC);
    
            ^
    

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:76:12: note: no known conversion for argument 1 from 'int [3]' to 'unsigned int'

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:77:12: note: size_t Print::println(long int, int)

     size_t println(long, int = DEC);
    
            ^
    

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:77:12: note: no known conversion for argument 1 from 'int [3]' to 'long int'

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:78:12: note: size_t Print::println(long unsigned int, int)

     size_t println(unsigned long, int = DEC);
    
            ^
    

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:78:12: note: no known conversion for argument 1 from 'int [3]' to 'long unsigned int'

    Nina2AppSketch:19: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]

                 if(incomingByte ==46){
    
                                   ^
    

    Nina2AppSketch:22: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]

                 else if(incomingByte ==41){
    
                                        ^
    

    Nina2AppSketch:27: error: 'serial' was not declared in this scope

                   serial.println("Summary of received data:");
    
                   ^
    

    Nina2AppSketch:39: error: invalid operands of types 'int [3]' and 'int' to binary 'operator&'

                    incomingByte[charNumberRead]=incomingByte  & 0xff;
    
                                                                 ^
    

    exit status 1 incompatible types in assignment of 'int' to 'int [3]'

  • it could only need a slight Notifaication .. i will try with some codes from the links you send to me

  • what does the +RGB+ mean in the code you send me yesterday.. because i never used these +---+ whith Serial.print

    Serial.println("RGB var contains: >>"+RGB+"<<");

    and i get different symbols when i move from color to color, so you are right im getting the data but the int conversion isnt working

  • Answer ✓

    Ok, I am trying to help but I am mixing my java and C (The C code are from examples on the net).Go back to the previous post to check the changes and corrections I made to the code.

    Regarding your question:

    Serial.println("RGB var contains: >>"+RGB+"<<");

    That is a way you can print data in processing (java) and it might no work at all in Arduino.

    Kf

  • It works perfect!!!

    YOU ARE THE MAN... Thank you very much for your help, u made my day.

  • but i am wondering now what if the value of one the colors is 41 or 46 , this could cause a problem

  • yes the LEDS do work normal till i think they get a 41 or 46 as R, G or B ,, and start flshing unnormal..

  • Well my friend i do realize something now, what im actually doing beside the RGB color Wheel, is sending 6 touch-button Status from the tablet to make arduino do other funtions, and they are working perfectly, because in processing im just initializing or declaring if this button is touched , send this Charakter(for example like this, a--> button 1, b ---> button2 and so on ,,, and in the arduino side its pretty simple to catch that and make hin does what ever you want,

    For the RGB values im sending also a start Charakter to get him know what he should check , and im becoming the charakter on the arduino side to let him know he should now check the RGB-- And because if i dont send StartCharakters he will get lost in other words he wont be able to know which bluetooth sendPacket to which function belongs.. now i have 2 problems :

    First problem: when i slide on the color Wheel, i will definetly get soon a value of one of the three colors which is equivalent to one of the StartCaharakters of the Buttons , so when u slide , and get a match charakter of the other function , he will just jump and do the other Funcion..

    I did solve this Problem by mapping the RGB values on the Processing Side before sending them, and so leaving some free Charakters which would never be equivalent to any of the color values.. I need sure to remap the RGB values when i catch them on the arduino side ..

    Second problem: your rgb code isnt working properly when i put everything together....

  • edited October 2016
            //*************************************************************************************
      void loop() {
    
    
    
        while (Serial.available() > 0)
           {
            // get incoming byte:
              char chByte = Serial.read();
               if (chByte == '!'){checkRGB();Serial.println("CheckRGRB");} 
     //i added a startIndicator in procressing fto know we are targeting RGB              
    
               else if (chByte == '$'){turnLedOn();Serial.println("turnLedOn");}
    
                  else if (chByte == '%'){turnLedOff();Serial.println("turnLedOff");}
    
                     else if (chByte == '&') {turnWarmWeiss();Serial.println("turnWarmWeiss");}
    
                       else if (chByte == '(') {turnKaltWeiss();Serial.println("turnKaltweiss");}
                }
    
            }
    
    
            //************************************************************************************
            void checkRGB(){
    
    
    
         while (Serial.available() > 0) { // if i remove this line i get incomingBYyte,DEC //printed always = -1
         // read the incoming byte:
           incomingByte = Serial.read();
    
            // say what you got:
              Serial.print("I received: ");
             Serial.println(incomingByte, DEC);
    
           //next if it is a '.' separating R G B values// i changed the (".") to
              // (" " ") because of the Map issue
    
                            if(incomingByte ==34){
                              charNumberRead++;
                            }
                            else if(incomingByte ==35){  //41 refers to ')' from ASCII                                //tables//changed to #
    //Reached end of package: Reset counter for next data set
    
     charNumberRead=0;  
    
                              //Print results
                             // Serial.println("Summary of received data:");
                              Serial.print("Red: ");
                              Serial.print(incomingRGB[0]);
                              Serial.print("Green: ");
                              Serial.print(incomingRGB[1]);
                              Serial.print("Blue: ");
                              Serial.print(incomingRGB[2]);   
                              Serial.println();
                              //delay(500);    
    
                            }
                            else{
                               //Process incoming color data
                               //You might need to "and" your data with 0xff since integer
                               //fields are 4 bytes and byte fields are only one byte. 
                               //0xff ensures all the other 3 bytes from the integer fields 
                               //are set to ZERO
                               incomingRGB[charNumberRead]=incomingByte  & 0xff;
                            }
             }
    
            } 
            //*********************************************************************************************
    
  • edited October 2016

    the other functions are working proparly.. And what i am sending from the Processing for the RGB ist this :

     byte data[] = {startPackage,redCol, colSeparator, greenCol, colSeparator, blueCol, endPackage};
         bt.broadcast(data);
    
Sign In or Register to comment.