Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
titleBeispiel Processing zu Arduino
collapsetrue
import processing.serial.*;
 // Import the Processing Serial Library for communicating with arduino
Serial myPort;               // The used Serial
Port
 
void setup()
{
  background(0);
  size(500, 500);

 println(Serial.list()); // Printsprint theall listavailable ofports
serial available devices (Arduino should be on top of the list) println(Serial.list());

  // open specific serial port
  myPort = new Serial(this, "/dev/cu.usbmodem12131usbmodem14621", 9600);
// Open a new port and connect with Arduino at 9600 baud
}


void draw()
{
  // prepare values
  int firstValue = 111;
  int secondValue = 222;
  int thirdValue = 333;

  // write values
  myPort.write(str(firstValue));
  myPort.write(",");
  myPort.write(str(secondValue));
  myPort.write(",");
  myPort.write(str(thirdValue));
  myPort.write("\n");

  delay(1000);
}

Um auf der Seite des Arduino auf eingehende Nachrichten über die serielle Schnittstelle zu horchen müssen wir einige Funktionen benutzen. Diese sind:

...

Code Block
languagejava
titleBeispiel Werte in Arduino empfangen
collapsetrue
#define LED_PIN 6
#define NUM_OF_VALUES 3

String
incomingString ="";
int incomingValues[NUM_OF_VALUES];

void setup()
{
  Serial.begin(9600);
  pinMode(LED_PIN, OUTPUT);

  // open the serial port with a baudrate of 9600
  Serial.begin(9600);
}

void loop()
{
  // check if data is available
  if (Serial.available() > 0)
  {
    // read string
    incomingStringString str = Serial.readStringUntil('\n');

    // split(incomingString data and write to incomingValues
    split(str, incomingValues, NUM_OF_VALUES);
  }

  // take first value and set LED
  analogWrite(LED_PIN6, incomingValues[0]);
}

void split(String inputString, int returnData[], int numOfValues)
{
  int index = 0;
  int lastPos = 0;

  for  for(int i = 0; i<inputStringi < inputString.length(); i++)
  {
    if (inputString.charAt(i) == ',' && index < numOfValues)
    {
      String tempStr = inputString.substring(lastPos, i - 1);
      returnData[index] = tempStr.toInt();
      index++;
      lastPos = i + 1;
    }
  }
}