A simple sketch in Simon Monk book sets out the code below where you simply enter a number of between 0 and 255 eg to get corresponding reading on a multimeter (positive lead attached to digital pin 6 and negative to gnd etc,
Anyway, no matter what number i insert in serial monitor the voltage does not go beyond, say 0.7 volts DC. In other words, there is indeed a jump in DCv but it does not reflect the range 0-5v analog for 0-255 digital input.
When you send something via the Serial Monitor, there migth be a CarriageReturn or LineFeed or both after the text. The Serial.parseInt() does not read that, so the next time the loop() runs, the Serial.parseInt() sees those CarriageReturn and LineFeed, but it can not make a number of it, so it returns zero.
Solution: Get rid of those CarriageReturn and LineFeed.
void setup()
{
pinMode(6, OUTPUT);
Serial.begin(9600);
Serial.println("Type a number");
}
void loop()
{
if (Serial.available() > 0)
{
int dutyCycle = Serial.parseInt();
analogWrite(6, dutyCycle);
// Remove any CarriageReturn or LineFeed
while (Serial.available() > 0)
{
Serial.read();
}
}
}
Thanks Koepel, that worked. You’re a genius! Really appreciated!
Tim
Tim Flahvin | Partner
Thomson Geer
T +61 2 8248 5850 | M 0408 416 058
Level 14, 60 Martin Place, Sydney NSW 2000 Australia tflahvin@tglaw.com.au | tglaw.com.au
What if a serial terminal program has a bug and has switched them and sends "\n\r" at the end ?
What if someone types numbers with a total length of 90 ?
What if someone types "100000" ?
@tflahvin The return value of Serial.parseInt() is 'long', see the reference: Serial.parseInt() - Arduino Reference
If someone types "100000" with the Serial.parseInt() and then convert it to a 'int', then you get a negative number.
This is a little better:
long dutyCycle = Serial.parseInt(); // it returns a long
if( dutyCycle < 0)
dutyCycle = 0;
if( dutyCycle > 255)
dutyCycle = 255;
analogWrite(6, (int) dutyCycle);