-1

I'm trying to write a script to move an object coupled to a linear axis through a stepper motor. The user must send information such as the length to be moved, the speed of movement, the direction of movement, or even if he wants to make millimetric adjustments via the serial. However, I can't read lengths from 43 mm where I send the integer 43 over serial. I tested several methods that I found on the internet. Below is the current code and some alternatives of the serial read section that failed.

void(* resetFunc) (void) = 0;

//Serial read
const int bufferSize = 30; // Tamanho máximo para o buffer de leitura
char buffer[bufferSize];   // Buffer para armazenar os dados lidos via serial

//Step motor
const int stepPin = 3;
const int senPin = 2;
const int enPin = 8;
int sen, sp, len, ad; //sen = forward or backward, sp = speed, len = length, ad = enable steps to adjustment
int REV;//motor revolutions
int time_motor; // interval of pulse (on/off)

void setup()

{
  
  pinMode(stepPin,OUTPUT); 
  pinMode(senPin,OUTPUT);
  pinMode(enPin,OUTPUT);
  digitalWrite(enPin,LOW);
  
  Serial.begin(9600);
 
  while (!Serial.available()) {
    delay(10);
  }

  int bytesRead = Serial.readBytesUntil('\n', buffer, bufferSize);

  buffer[bytesRead] = '\0';

  sscanf(buffer, "%d,%d,%d,%d", &ad, &sen, &len, &sp);

  Serial.print("ad: ");
  Serial.println(ad);
  Serial.print("sen: ");
  Serial.println(sen);
  Serial.print("len: ");
  Serial.println(len);
  Serial.print("sp: ");
  Serial.println(sp);
      
  time_motor = 100;
        
  REV = int(768 * len);
  
  if(ad == 0){   
    if (sen == 1){
      backward(REV, time_motor);
      }
  
    else {
      forward(REV, time_motor);
      }
  
      resetFunc();
  }
  else{
    if(sen == 1){backward(768, time_motor);resetFunc();}
    else{forward(768, time_motor);resetFunc();}
  }
}

void forward(int len_fact, int time_c) {
  digitalWrite(enPin, LOW);
  digitalWrite(senPin, HIGH);
  for (int x = 0; x < len_fact; x++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(time_c);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(time_c);
  }
}

void backward(int len_fact, int time_c) {
  digitalWrite(enPin, LOW);
  digitalWrite(senPin, LOW);
  for (int x = 0; x < len_fact; x++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(time_c);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(time_c);
  }
}


void loop()
{

}

An alternative below:

  while (!Serial.available()) {
    // Aguarda até que haja dados disponíveis na porta serial
  }

  delay(100); // Pequeno atraso para garantir que todos os dados tenham chegado

  int bytesRead = 0;
  while (Serial.available() && bytesRead < bufferSize - 1) {
    char c = Serial.read();
    if (c == '\n') {
      break; // Termina a leitura ao encontrar uma quebra de linha
    }
    buffer[bytesRead] = c;
    bytesRead++;
  }

  // Adiciona o caractere nulo para indicar o final da string
  buffer[bytesRead] = '\0';

  // Usa a função sscanf para extrair os números do buffer
  sscanf(buffer, "%d,%d,%d,%d", &ad, &dir, &len, &sp);

  // Imprime os valores lidos para verificá-los
  Serial.print("ad: ");
  Serial.println(ad);
  Serial.print("dir: ");
  Serial.println(dir);
  Serial.print("len: ");
  Serial.println(len);
  Serial.print("sp: ");
  Serial.println(sp);

And the other:

  while (!Serial.available()) {
    // Aguarda até que haja dados disponíveis na porta serial
  }

  // Lê os dados da porta serial e armazena no buffer até atingir o tamanho máximo
  int bytesRead = 0;
  while (bytesRead < bufferSize - 1) {
    if (Serial.available()) {
      char c = Serial.read();
      if (c == '\n') {
        break; // Termina a leitura ao encontrar uma quebra de linha
      }
      buffer[bytesRead] = c;
      bytesRead++;
    }
  }

  // Adiciona o caractere nulo para indicar o final da string
  buffer[bytesRead] = '\0';

  // Usa a função sscanf para extrair os números do buffer
  sscanf(buffer, "%d,%d,%d,%d", &ad, &dir, &len, &sp);

  // Imprime os valores lidos para verificá-los
  Serial.print("ad: ");
  Serial.println(ad);
  Serial.print("dir: ");
  Serial.println(dir);
  Serial.print("len: ");
  Serial.println(len);
  Serial.print("sp: ");
  Serial.println(sp);

Serial returns nothing or "?". How should I proceed to solve this problem? I'm using an original Arduino uno and writing in the arduino IDE. The version is 1.8.19.

4
  • 3
    maybe you set the wrong baud rate in the serial console
    – jsotola
    Aug 30, 2023 at 22:03
  • 1
    reduce your program. to minimum code that still exhibits the problem
    – jsotola
    Aug 30, 2023 at 22:57
  • 2
    You are sending 4 numbers over serial, right? Please copy and paste the exact numbers that you are sending.
    – Nick Gammon
    Aug 31, 2023 at 1:26
  • 1
    Before the sscanf I would be printing what is in that buffer.
    – Nick Gammon
    Aug 31, 2023 at 5:56

1 Answer 1

0

Well, you didn't provided that much info, but i picked up on some of your code (below) and in the serial monitor i can read all the numbers :

    const int bufferSize = 30; // Tamanho máximo para o buffer de leitura
char buffer[bufferSize];   // Buffer para armazenar os dados lidos via serial

//Step motor
const int stepPin = 3;
const int senPin = 2;
const int enPin = 8;
int dir, sp, len, ad; //sen = forward or backward, sp = speed, len = length, ad = enable steps to adjustment
int REV;//motor revolutions
int time_motor; // interval of pulse (on/off)

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
while (!Serial.available()) {
    // Aguarda até que haja dados disponíveis na porta serial
  }

  delay(100); // Pequeno atraso para garantir que todos os dados tenham chegado

  int bytesRead = 0;
  while (Serial.available() && bytesRead < bufferSize - 1) {
    char c = Serial.read();
    if (c == '\n') {
      break; // Termina a leitura ao encontrar uma quebra de linha
    }
    buffer[bytesRead] = c;
    bytesRead++;
  }

  Serial.println(buffer);

  // Adiciona o caractere nulo para indicar o final da string
  buffer[bytesRead] = '\0';

  // Usa a função sscanf para extrair os números do buffer
  sscanf(buffer, "%d,%d,%d,%d", &ad, &dir, &len, &sp);

  // Imprime os valores lidos para verificá-los
  Serial.print("ad: ");
  Serial.println(ad);
  Serial.print("dir: ");
  Serial.println(dir);
  Serial.print("len: ");
  Serial.println(len);
  Serial.print("sp: ");
  Serial.println(sp);
}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.