CSCI373 - Week - 08 - Read From Serial Monitor
CSCI373 - Week - 08 - Read From Serial Monitor
Week 08
Read from Serial Monitor
Read from Serial Monitor
To send data from the Serial Monitor to the Arduino, we need the
Arduino to listen to the serial buffer - the part of the Arduino that
receives data from the outside world via the serial pins (digital 0 and 1)
that are also connected to the USB circuit and cable to your computer.
The serial buffer holds incoming data from the Serial Monitor’s input
window.
int a, s = 0;
void loop(){
if (Serial.available() > 0) {
a = Serial.parseInt();
Serial.print("You entered: ");
Serial.println(a);
s += a;
Serial.print("Sum= ");
Serial.println(s);
}
}
Practice Exercise1
• The Arduino reads a character between 'a' and 'c' from the serial
monitor:
• the piezo (pin 9) plays a sound corresponding for each letter,
• and an error sound for other letters.
7
The Arduino reads a character between 'a' and 'c' from the serial monitor then the piezo
(pin 8) plays a sound corresponding for each letter, and an error sound for other letters.
char x;
void setup() {
Serial.begin(9600);
if (Serial.available() == 0) { }
}
void loop() {
if (Serial.available() > 0) {
x = Serial.read();
if (x != '\n') //The Enter key
Serial.println(x);
switch (x) {
case 'a': tone(8, 262, 100); break;
case 'b': tone(8, 31, 100); break;
case 'c': tone(8, 262, 100);
case '\n':break; //The Enter key
default: tone(8, 196, 50); delay(100); //noTone(8);
tone(8, 196, 50);
Serial.println("Else");
}
}
}
Practice Exercise
When the arduino starts, the piezo plays a sound for one
time, the serial monitor displays "Enter a number" then
keeps displaying a dot until the user enter a number N, the
arduino uses N to set the brightness of the LED.
Each time you push the button the brightness of the LED
should be increased by a value of + 50. If the increment
will make the brightness > 255 then set it to 0.
Practice ex2 if (Serial.available() > 0) {
number = Serial.parseInt();
Serial.println(number);
#define LED 5
analogWrite(LED, number);
#define BUTTON 7
}
int x = 0;
if (digitalRead(BUTTON) == HIGH ) {
int number;
x += 50;
void setup() {
if (number + x < 255)
Serial.begin(9600);
analogWrite(LED, number + x);
tone(3, 33, 100);
else {
while (Serial.available() == 0) {
analogWrite(LED, 0);
Serial.print(".");
x = 0;
delay(100);
}}
}
delay(100);
}
} 10
void loop() {
Practice Exercise-2
Write an Arduino program that uses the serial monitor to read
commands from the user and control the state of three LEDs
based on the commands.
There are two push buttons connected to the Arduino board,
and each button should have a different effect on the LED
states.