LESSON – USER INPUT USER INPUT Usually,
user input refers to data that is entered by a computer user into a computer
application. Learning how to do deal
with user input is one of the first (and easiest) things one learns when
learning a new programming language such as Python or Java. However,
with Arduino, we do not have a normal setting. There is no keyboard or monitor on the
Arduino. So user input will have more
complexity to it. In our
situation, user input refers to information that can be typed into the serial
monitor window on a computer that is connected to the Arduino. SERIAL CONNECTION Like
when we want to display something in the serial monitor, to get input, we
also need to establish a serial connection.
We still use: Serial.begin(9600); INPUTING DATA Open the
Serial Monitor (Tools > Serial Monitor). At the
top, you will see a text field and a send button. Enter your input there and hit Send. WAITING FOR DATA We have
to make our program wait for data to be available. So we have to use a loop that keeps looping
until some data is available. The code
looks like this: while (Serial.available() == 0) { //Do
nothing } The
above code is a while loop. It loops as long as the amount of available
input data is zero. Once there is data
available, it stops looping and the program continues. Note
that the above loop can be written on a single like like this instead: while (Serial.available() == 0) {} READING THE DATA We can
read the data by using the function Serial.readString() like
this: String word = Serial.readString(); FULL EXAMPLE – GREETING PROGRAM void
setup() { Serial.begin(9600); Serial.println("Enter your
name."); while (Serial.available() == 0) { }
//waiting for data String name = Serial.readString(); //reading data Serial.println("Hello " + name); } |
TRY THIS… PRACTICE Write
the program that will ask the user for their birth year. The program then calculates their age. The program then responds with a message
based on the age. See the table below
for the message:
|