H i Guy! Sorry for my English But i'm Italian!
I've got a problem!
I want set 3 led intensity from a serial string.
This is the code:
Code:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);
char ricevi[4];
int n = 0, Ciclo;
int led6= 6;
void setup()
{
mySerial.begin(9600);
}
void loop()
{
if (mySerial.available() > 0)
{
delay(5);
while(n <= 4)
{
ricevi[n] = mySerial.read();
n++;
}
n = 0;
Ciclo = atoi(ricevi);
analogWrite(6, Ciclo);
}
}
This code Read a multicharacter string from serial.
I want turn on led1 with 50% offerte Power with This string (a50) The led2 with (b50) etc....
Can i do This? what code should I use?
If there is one character available, the if statement will be true. You can NOT take that as permission to read 4 characters, no matter what zoomkat says.
I tried and I assure you it's working! if I type 0 the led light goes off if I type 120 is on the 50%, and if I type 255 is on 100%
I can not enter a Switch case with a50 b40 c60 etc…
I can not enter a Switch case with a50 b40 c60 etc…
The relevance of this statement escapes me. You are free to split the string into multiple parts, like a and 50, b and 40, etc., and deal with each part separately.
dxcoco2:
This code Read a multicharacter string from serial.
I want turn on led1 with 50% offerte Power with This string (a50) The led2 with (b50) etc....
Can i do This? what code should I use?
As was pointed out to you, it does not read a multicharacter string from mySerial. It happens to read them in this case, because you are wasting time with a delay(5), allowing some number of bytes to arrive. This is extremely bad practice, and if you get into that habit, it will come back to haunt you.
In this code, if you always want to read only 3 bytes, you should use if mySerial.available == 3 or if you want an unknown number of bytes, read them one at a time, or read as many as are available, collecting them until you receive a delimiting character, and THEN work on the received data.
You are reading into a 4 byte array, and then performing an atoi() on it. The problem is that you are not terminating the array of char. After you read in three bytes, you should terminate the string with a 0. Otherwise, you'll be looking at some other variable, and if it happens to contain a numeric ASCII character, you'll get a wrong answer.You are also reading 5 bytes in to a 4 byte array, because your while loop does not terminate until n > 4. Again, this will cause problems if you happen to overwrite another variable.
check the reference section, Serial.read() return -1 if there is no char available, in addition you have the Monitor set to sent cr/lf or nl when you press send. Try echoing the chars as you read them and see. As I said what you are getting is "random"!.
void loop()
{
if (mySerial.available() > 0)
{
delay(5);
while(n <= 4)
{
ricevi[n] = mySerial.read();
mySerial.print(ricev[n],DEC);// echo and print in decimal
n++;
}
n = 0;
Ciclo = atoi(ricevi);
analogWrite(6, Ciclo);
}
}