Sending a numerical variable from Processing to Arduino

edited December 2015 in Arduino

I'm new in this world, and I'd know how to send a numerial variable Processing-->Arduino (not Arduino-->Processing!!).

I've got the programme for send only a letter, but i don't know hoy to send a number (0-100).

Thanks!

Answers

  • Answer ✓

    I would just send the number as a String followed by a delimiter. Then on the arduino-side you can reconstruct the number from the characters that you receive.

    Here is an example-code for processing that sends random numbers when you click a mouse-button:

    // libraries
    import processing.serial.*;
    // serial connection
    Serial port;
    
    
    void setup() {
      // init serial-port
      port = new Serial(this, Serial.list()[2], 57600);
    }
    
    void draw() {}
    
    void mousePressed() {
      // create random number
      int number = (int) random(100);
      // debug
      println("now sending number: "+number);
      // send number
      port.write(Integer.toString(number));
      // write any charcter that marks the end of a number
      port.write('e');
    }
    
    // this part is executed, when serial-data is received
    void serialEvent(Serial p) {
      try {
        // get message till line break (ASCII > 13)
        String message = p.readStringUntil(13);
        // just if there is data
        if (message != null) {
          println("message received: "+trim(message));
        }
      }
      catch (Exception e) {
      }
    }
    

    And here is the counter-part for the arduino, that reads the incoming serial-data and writes the number back to the serial-port when a delimiter is received:

    int c;
    int v=0;
    
    void setup() {
      Serial.begin(57600);
    }
    
    void loop() {
      // read serial-data, if available
      while (Serial.available()) {
        c = Serial.read();
        // handle digits
        if ((c >= '0') && (c <= '9')) {
          v = 10 * v + c - '0';
        }
        // handle delimiter
        else if (c == 'e') {
          Serial.println(v);
          v = 0;
        }
      }
    }
    

    I hope that helps to understand the principle.

  • If you only have a single value to send, you could as well just send a single byte. Would be easier on the arduino-side. Just saw this thread with an example code: https://forum.processing.org/two/discussion/14006/example-code-controlling-electric-motors-with-a-controlp5-knob-and-adafruit-motor-shield-boards#latest

  • Thank you, you have fixed my problem!! Now I have another one, but I'll write a new discussion :D

Sign In or Register to comment.