Hi all, I am using the serial port to control my arduino. I am using the serial port to control and I want to send a control like g1234. The arduino would then use the motor shield to move a motor to position 1234 which is based on a potentiometer output. I am having a hard time figuring out how to get the 1234 value as an integer. Basically I have used the following code, but I am kinda lost at this point.
char bytes[6];
int bytesToRead = 0; // number of bytes available to read
bytesToRead = Serial.available();
if(bytesToRead > 0)
{
for(int i = 0; i < bytesToRead; i++)
{
bytes[i] = Serial.read();
}
Serial.println(atoi(bytes));
ch = bytes[0];
}
If the control strings are all in the form cnnnn, where c is a single letter, and n is a single digit, you don't need to store the input in an array at all.
int bytesToRead = 0; // number of bytes available to read
void loop()
{
char cmd;
int nnnn = 0;
if(bytesToRead > 0)
{
cmd = Serial.read();
if(cmd >= 'a' && cmd <= 'z')
{
for(int i = 0; i < bytesToRead; i++)
{
nnnn *= 10;
nnnn += Serial.read() - '0';
}
}
}
// Create a switch statement using cmd
switch(cmd)
{
case 'g':
// Use nnnn to do something
break;
// Other cases for other commands
break; // After each case
}
}
There have been several threads lately, involving Serial.read without a delay. It works for some people, but not for others. You might try adding a small delay after each Serial.read statement (something like 10 milliseconds seems to work).
A delay should not be required if just reading a single character after testing if Serial.available() is true. If it's true the complete character has already been read in and is in a buffer location ready to be read in a single instruction. If however you try and read more then a single character without checking how many characters have been received and buffered or don't do a Serial.available() check before each character is read in you might have a problem that appears to be solved by adding a delay. Delay in this case is masking the real problem most likely, in handling of the serial data stream.