I am trying to make a system that takes a numeric user input in the console and then spins a motor that many times
(I want to have 2 inputs and 2 motors but I want to start smaller and build up, I also in the future want it to be able to read the inputs from a text file)
I have been looking at a lot of documentation that is out there relating to BufferedSerial but nothing I have tried seems to work.
Does anyone have any suggestions???
Hello,
BufferedSerial sometimes can only read a part of the whole string (It is not affected by size of the buffer but probably by a processor speed/load), so you must collect all the parts and then process them.
For code example click here
#include "mbed.h"
#include <string>
#define MAXIMUM_BUFFER_SIZE 10
#define FORMAT "1-100"
DigitalOut led(LED1);
static BufferedSerial serial_port(USBTX, USBRX);
int main(){
printf("Example start\nPlease enter motor ID and number of steps of that motor.\n");
printf("ID-Steps \nFormat: %s\n", FORMAT);
char buf[MAXIMUM_BUFFER_SIZE];
string myString;
int counter = 0;
while (1) {
if (uint32_t num = serial_port.read(buf, sizeof(buf))) {
// convert to string
for (int i = 0; i < num; i++) {
// only string without new line and carriage return
if('\r' != buf[i] && '\n' != buf[i]){
myString += buf[i];
counter++;
}
}
// is complete
if (counter >= sizeof(FORMAT)-1){
int motorID = stoi(&myString[0]);
int motorSteps = stoi(&myString[2]);
// your motor magic here
printf("Motor %d will run for %d steps\n", motorID, motorSteps);
myString = "";
counter = 0;
}
led = !led;
}
}
}
It has been tested with this setup:
- MbedOS 6.7,
- MbedStudio 1.3.1
- Boards - Nucleo-F429ZI, F446RE, F303RE
- Serial terminals - Termite, Hercules, Putty and also Serial Monitor of the MbedStudio.
BR, Jan
Hello, Thank you for the help so far, I ran the code to ensure it would work and the output is looking like this
do you know what this might be, is it related to the buffer size?
Hmm, I don’t know.
Just try to commented out the first printf, that string is not necessary it is only for info how to use the rest.
BR, Jan