Code android e arduino

Hello,

Please format your code:
https://discourse.processing.org/faq#format-your-code

You formatted it so I can work with it now… :)

This was a very quick exploration using Processing on PC and Arduino MEGA 2560 R3 connected with a USB cable.

Arduino
int incomingData;
char data = 0;
const byte LED9 = 9;
const byte LED11 = 11; //BACK
const byte LED12 = 12; //STOP
const byte LED13 = 13; //FWD
void setup()
{

pinMode(LED9, OUTPUT);   //set pin4 as output 
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
Serial.begin(9600);

}

void loop()
{
//if(Serial.available())
if (Serial.available() > 0) 
  {
  analogWrite(9, incomingData);
    
  data = Serial.read();
  //Serial.print("\n");
  //Serial.print(data); //Print Value of data in Serial monitor 
  //Serial.print(" : ");  
  incomingData = Serial.read();
  Serial.println(data);

  if (data == '!')
    //stop_();
    digitalWrite(LED13, HIGH);
    
  else if (data == '~')
  digitalWrite(LED13, LOW);
  
    //forward_();

//  else if (data == 'b')
//    backward_();
  }
}

void stop_() 
  {
  Serial.println("STOP");
  digitalWrite(LED12, HIGH);
  digitalWrite(LED11, LOW);
  digitalWrite(LED13, LOW);
  }

void forward_() 
  {
  Serial.println("FORWARD");
  digitalWrite(LED13, HIGH);
  digitalWrite(LED12, LOW);  
  digitalWrite(LED11, LOW);
  }

void backward_() 
  {
  Serial.println("BACKWARD");
  digitalWrite(LED11, HIGH);
  digitalWrite(LED12, LOW);
  digitalWrite(LED13, LOW);
  }
Processing
import processing.serial.*;

Serial myPort;  // Create object from Serial class
int val;        // Data received from the serial port

int count;

void setup() 
  {
  size(200, 200);
  // List all the available serial ports
  printArray(Serial.list());
  
  String portName = Serial.list()[2];
  myPort = new Serial(this, portName, 9600);
  delay(1000);
  }

void draw() 
  {
  count++;
  byte data = byte(count);
  myPort.write(data);              // send an H to indicate mouse is over square
  println(char(data));
  
  if(data == '!')
  background(255, 255, 0);
  else if (data == '~')
  background(0);
  }

This works!

I did not have a bank of LEDs so just using LED13 on Arduino and turned it ON and OFF and also changed Processing background.
I used an integer counter converted to a byte to send data from Processing and looked for the equivalent ASCII value (character) received on Arduino.

The important thing is I added a delay() in setup():
delay(1000)

The Arduino will reboot when you make an initial serial connection and you should wait until it is ready to receive serial data first otherwise you will flood the buffers.

I have a topic about this in the forum.
You can look for it.

:)