I recently got an Arduino uno and are staring with the basics. I want to control the blinking rate of a led using serial monitor.
it works between 1 and 9 but not anything higher. what am i doing wrong
const int led = 13;
int ledSpeed = 0;
void setup() {
pinMode(led, OUTPUT);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
ledSpeed = Serial.read();
}
digitalWrite(led, HIGH);
delay(ledSpeed);
digitalWrite(led, LOW);
delay(ledSpeed);
}
If you want, but I don't see how that will make a difference. The flaw in that you are under the impression that sending a value of say "1000" through the serial monitor will be received as 1000 on the other end. In actuality, your Arduino will receive '1', '0', '0', and '0'. So with your code, it will receive '1', and blink the LED with a delay of 49 mS (the decimal value of ASCII '1'). It will then repeat the process 3 more times using 48 (the decimal value of ASCII '0'). If you have any line ending selected, it will do it for those values.
What you are looking for is a state machine that will accept the individual characters and put them into an array. If you receive the stop byte, such as a new line, then feed the null-terminated array into atoi() to get the decimal value and use that in your delay Here is a simple example:
const char stopByte = '\n';
// Maximum characters in an int + null terminated character
const byte maxBuffer = 6;
void setup() {
Serial.begin(115200);
Serial.println("[Serial2Int]");
}
void loop() {
// Stores the characters between the start and stop bytes
static char buffer[maxBuffer];
// Keeps track of spot in buffer
static byte index=0;
if (Serial.available() > 0 ) {
char inChar = Serial.read();
if (inChar==stopByte) // If stop byte is received
{
processData(buffer); // process the data
index=0; // reset the array
buffer[0] = '\0';
}
else
{
buffer[index] = inChar; // put the character into our array
index++; // and move to the next key in the array
buffer[index] = '\0'; // then null terminate
}
}
}
void processData(char buffer[]) {
unsigned int value = atoi(buffer); // convert string to int
Serial.print("Value: ");
Serial.println(value);
}