i am a new arduino user and i have a problem while using serial.read
i need to input a string of characters and read them using serial.read
the string consists of 1 character and 2 integers
the character determines which pin turns on and the first integer decides how much voltage to give on that pin. i am giving the voltage through analog.write. the 2nd integer decides for how much time to turn on that pin. if anyone can help me out that would be good. as of now i can only read the first character and first integer. cant figure out a way to read the 2nd integer. here is my code

#define numberOfDigits 11
char theNumberString[numberOfDigits + 1];
char theNumberString2[numberOfDigits];
int voltage;
//int pinA = 9;
//int pinB = 10;
int pin;
char electrode;
void voltageCheck();
int time;

void setup()
{
Serial.begin(9600);
}
void loop()
{
if (Serial.available()>0)
{
switch(electrode)
{
case ‘a’:
pin = 9;
Serial.print(“electrode = A”);
Serial.print(’\n’);
voltageCheck();
break;
case ‘b’:
pin = 10;
Serial.print(“electrode = B”);
Serial.print(’\n’);
voltageCheck();
}
}
}

void voltageCheck()
{
{
for ( int i=0; i < 1; theNumberString[i++] = Serial.read());
voltage = atoi(theNumberString);
if (voltage <=5 && voltage>=0)
{
Serial.print(“voltage”);
Serial.print(voltage);
Serial.print(’\n’);
analogWrite( pin , voltage*51);
Serial.print(“time”);
Serial.print(time);
}
else
{
Serial.print(“error”);
}
}
}

Oh man, where to start…

the character determines which pin turns on and the first integer decides how much voltage to give on that pin. i am giving the voltage through analog.write.

Analog write doesn’t output an analog voltage, it outputs a PWM signal.

``````   if (Serial.available()>0)
``````

You’re assuming that you instantly get all three characters, when in fact, your loop() function will likely run a hundred times or so between characters. So you should either change the 0 to 2, or use a state machine and a deliminator character.

``````for ( int i=0; i < 1; theNumberString[i++] = Serial.read());
``````

This is not the proper way to use a for loop

``````voltage = atoi(theNumberString);
``````

atoi() expects a null terminated array or chars. You’re not giving it one.