I am doing a project for an axam. My program needs to read from serial.
What the program needs to read is things thay i write to the serial.
The code i am executing when this problem happens is:
int bogstav = 0;
int ch = 0;
Serial.print(ch);
while (1) {
Serial.print("For");
if (Serial.available()) {
Serial.print("efter");
ch = Serial.read();
Serial.print(ch);
if (ch == 32) {
break;
}
if (ch == 10) {
break;
}
if ( bogstav == 9) {
break;
}
bogstav++;
}
}
}
and what i get in the terminal is:
0ForForForForForForForefter10
This means that i get nothing through the serial, and suddenly i get 10 through the serial.
Can this be a fragment from early in the code, and if that is the case, why will it suddenly appear?
Not sure what your code is supposed to do. Simple serial capture/compare code.
// zoomkat 8-6-10 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later
int ledPin = 13;
String readString;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
Serial.println("serial on/off test 0021"); // so I can keep track
}
void loop() {
while (Serial.available()) {
delay(3);
char c = Serial.read();
readString += c;
}
if (readString.length() >0) {
Serial.println(readString);
if (readString == "on")
{
digitalWrite(ledPin, HIGH);
Serial.println("LED ON");
}
if (readString == "off")
{
digitalWrite(ledPin, LOW);
Serial.println("LED OFF");
}
readString="";
}
}
The examples in Serial Input Basics are simple reliable ways to receive data. And they don't need any delay() nor do they block the Arduino from doing other stuff.
This means that i get nothing through the serial, and suddenly i get 10 through the serial.
That is likely to be because the Arduino works very much faster than serial data arrives.
Also, the String (capital S) class can cause trouble in the small memory of the Arduino. It is better not to use it. Just use strings (small s) which are arrays of char terminated with a 0.
Robin2:
Also, the String (capital S) class can cause trouble in the small memory of the Arduino. It is better not to use it. Just use strings (small s) which are arrays of char terminated with a 0.