Serial communication between Arduino and Matlab Pong game

Hell folks,

I need your insight and help. I am working on a project to use a pot to control a movement of paddle in a pong game on my PC. Basically, this pot is connected to A0, 5v and GND of Arduino, and Arduino is USB plugged to my laptop. The voltage of pot corresponds to the location of paddle.

The rule of Pong is simple and try to use the paddle to hit the ping pong. A dialog box pops up to tell you what to do next if you lost a life. When the dialog box on, the matlab code should not take any data that comes into the serial pot. My problem lies here. I would like my matlab code to send a character or number to Arduino, which shuts down the data line that sends the data from pot to computer, everytime that dialog box is up.

The way I did it is that I use fwrite(s,10,‘int8’) in my matlab code to send the integer 10 back to my Arduino when the dialog box is on. Once Arduino receives this integer from, it will break out of the while loop that sends the pot data to Matlab. The Arduino code is listed below. My approach only works when I reduce the delay to less than 5ms, like <= delay(5). But then at the level of delay, my matlab just does not take any data from Arduino. Then if I keep the delay level around 30ms, then Arduino didnt take the integer 10 sent from Arduino. Matlab code is attached as well. The line of code for fwrite in matlab is at the Line 414. Thanks for the help in advance.

int f;
void setup() {
  // initialize serial communication at 9600 bits per second:

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  f =;
  while(f == 9){
      int sensorValue = analogRead(A0)/20;
      if (f == 10){

Thanks. (5.64 KB)

just saw my question moved to this catalog. Thanks Webster.

could anybody give me some insights? thanks.

I think you need to change the overall approach to your program.

At the moment you have a WHILE loop within loop(). There is no need to have one loop inside the other.

You need to check if there is serial data and if there is you should save the value. That means the value will stay the same even if there is no input.

Then you can change your WHILE to an IF so that the analogRead() takes place in every iteration of loop() as long as the variable has the value 9. If any other value is sent the IF will fail.

Serial input basics

Thanks a lot, Robin2. Your insight is right and I worked out the problem.