Arduino and Processing: Change speed of DC Motor and read Newping sensor Serial

Hello! I am almost totally new in programming, and I want to finish a project that does the following:

When initializing, choose a button (in Processing/arduino serial monitor) that sends a character (a/b, or anything else) by serial to Arduino:

-when choosing a, then use sensor reading function
-when choosing b, then enter speed control function

The problem is when I choose a, only one value of sensor reading is being shown while also, being a wrong reading... I have to press a repeatedly to get wrong values of the sensor. - I want this being done automatically so that every value collected at 50ms to be shown in a box in Processing window.

The problem when I'm choosing b, motor sets PWM speed at 'b' ASCII value, (at least, that's what I'm thinking) and then I can't change PWM value anyway in 0-255 value... in processing there will be a controlP5 slider.

What I'm thinking is that the serial has to be flushed before entering one of the cases... Also, how do I return to the state where I can choose a/b after I did that already?

I attached the program, I'm new here so please don't hate! Thank you in advance! :slight_smile:

Arduino_2.ino (827 Bytes)

You need a more sophisticated program - especially the part that receives the data. For one activity you only need to send a single character but for the other activity (the motor speed) you also need to send the speed. Your program is not properly designed for that.

Have a look at the 3rd example in Serial Input Basics and design your Processing program to send data compatible with it.

It will make things much simpler if the Processing program always sends two pieces of data - for example <a,0> when the sensor reading are required and <b,123> when the speed needs to change (123 is an example of the new speed value). In that link the parse example illustrates how to convert the characters "123" into an int that can be used with analogWrite(). When the command 'a' is received your code can just ignore the number that accompanies it.

For the continuous operation of the sensor when you send an 'a' the Arduino program needs to set a variable (let's call it sensortRun sensorRun) to true and your function should be like this

int sensorRead()
{
  if (sensorRun == true) {
     delay(50);
     Serial.print("distance: ");
     Serial.print(sonar.convert_cm(uS));
     Serial.println("cm");
  }
}

AND that function should be called directly from loop()

You have not said what command will stop the sensor from sending (i.e. when should sensorRun be set to false) so I have not dealt with that.

...R

Thank you very much for your answer. I already have read the serial input basics post, but I didn't think it would help me in any way. I am researching right now, and will try to fix this.