serial communication problem when retrieving data

good night
I did a serial communication program with the arduino, but I have a problem when retrieving data.

the first since the arduino and the value we receive is always to be processed and shipped. he is to keep in memory and when sending a print because it always the same.

the code I used was the following:

#include <ctype.h>

int recebido;
char dados[4];
int i=0;

void setup() {
	Serial.begin(9600);	// opens serial port, sets data rate to 9600 bps
        pinMode(9, OUTPUT);     
}

void loop() {
 
      
      // send data only when you receive data:
      if (Serial.available()>4) {

      while(isdigit((dados[i++] = Serial.read())));
      
      recebido = atoi(dados);
     
      analogWrite(9,recebido);
      Serial.print("dir: ");
      Serial.println(recebido);
      delay(500);
     
    }
    
    else 
   {
     analogWrite (9, 0);
   }
   
}

in the image below you can see the k say.

on the console when you press a key, it sends a given, since this under the key you pressed. but as a first key that was loaded and that the four key corresponds to a PWM 100 sends always 100.

How do I go for it by reading the values ??automatically? I think the code is correct.

he should of always updating the string data when the iteration ends, but he is to stick to the 1st stored value sent, and afterwards he did not read any further.

below is also the code in c + + I'm using to communicate, and this is sending the correct data, as already seen in Experiment hyperterminal windows and the value submitted is correct

#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */

int vel;
int dir;
char envio[2] = { ' ' } ;
char* status = 0;
int count = 0;
int flags = 0;
int fd, j;
int enviodados; 

// abrir porta serie
int abrir_porta_serie(char *port) {
  struct termios options;
  fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd == -1) {
    printf("impossivel a comunicaçao \nligar a porta serial \n", port);
    }
    else {
    tcgetattr(fd, &options); // Get the current options for the port...
    cfsetispeed(&options, B9600 ); // Set the baud rates
    cfsetospeed(&options, B9600);
    options.c_cflag |= (CLOCAL | CREAD); // Enable the receiver and set local mode...
    tcsetattr(fd, TCSANOW, &options); // Set the new options for the port...
    }
  return(fd);
}


// envio de dados
int envio_de_dados(int fd) {
  int count;
 count = write(fd, envio , strlen(envio));
 return(count);
}

int main() {


    /* Abrir a porta de dados*/
    char port[50] = "/dev/ttyUSB0";
    fd = abrir_porta_serie(port);
    float opcao;
        int weight;
    for(;;){
    printf("intruduza uma tecla: " );
    scanf("%f", &opcao);

    if(opcao== 1){
        enviodados = 0;
    }
    else if (opcao == 2){
        enviodados = 25;
    }
    else if (opcao == 3){
        enviodados = 50;
    }
    else if (opcao == 4){
        enviodados = 100;
    }
    else if (opcao == 5){
        enviodados = 175;
    }
    else if (opcao == 6){
        enviodados = 225;
    }

    sprintf( envio, "%d ",  enviodados );
    printf("dados enviados %s \n ", envio);
       //sprintf( direcao, "%dS ", dir );


/*_________________________________________________________________________________________*/
   /*inicio dos dados a serem transmitidos*/
 
  envio_de_dados(fd);
  weight = envio_de_dados(fd);
      }
  close(fd);
  return 0;
}

if I can help thank you.

thanks

greetings paulo lopes

You forgot to set 'i' back to 0 after you process the input.
You should also put a null terminator on the string before you convert to a number.
You should also allow for values less than four characters.

Something like this should work (not tested):

void loop() {
      // send data only when you receive data:
      if (Serial.available()) 
          {
          dados[i] =  Serial.read();
          if (isdigit(dados[i]))
               i++;
          else
          if (i > 0) // Make sure we have some digits
              {
              dados[i] = '\0';  //  Add null terminator
              recebido = atoi(dados);
              i = 0;
     
              analogWrite(9,recebido);
              Serial.print("dir: ");
              Serial.println(recebido);
             delay(500);     
             }
        else 
             {
            analogWrite (9, 0);
             }
       }
}

works perfectly :slight_smile: :slight_smile: :slight_smile: :slight_smile: :slight_smile:

thanks for the help :smiley:

greetings angel3love