I want to control a LED and also print control value to serial, but if I close the serial monitor there's a lagging. I tried with if (serial), but it didn't work. Any suggestions?
I followed your complier setup and got no errors anyway. The compiler says OK. When I run the program everything is fine and the LED brightness is controlled smoothly, also when i open the serial monitor. The lagging starts when close the monitor. If I open the monitor again, everything's fine.
int sensorPin = A0;
int fadeValue = 0 ;
int ledValue = 0 ;
void setup() {
// put your setup code here, to run once:
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly: fadeValue = analogRead(sensorPin);
fadeValue= analogRead(sensorPin);
ledValue=map(fadeValue,0,1023,0,255);
analogWrite(ledPin,ledValue );
if (Serial) {
Serial.print("Värde: ");
Serial.print(ledValue);
Serial.print(" ");
Serial.println(fadeValue);
}
delay (50);```
}
The Arduino Micro uses a ATMega32U4 processor which has a native USB interface. In contrast to e.g. a UNO the processor recognizes, when the USB connection gets broken ( closing the serial monitor ) and gets stuck with a timeout.
if(Serial) and the variations only check if a connection has been established, not if the connection disappears. It's mostly important if you don't want to 'loose' the first print statements. To my knowledge, printing / writing is basically ignored if the connection was not yet established; the problem comes when it disappears.
I suspect that you actually have to test for the size that you want to send; if you want to send e.g. 10 characters but there is only place for 1, you might still run into the problem.