Friday 21 April 2017

Serial Monitor - Reading numbers

This is all about how to read data from the serial monitor.
The serial monitor, allows you to capture and enter data in real time.
It is the 'tether' between the computer and your Arduino - it lets you send and receive text messages
which is handy for debugging and also controlling the Arduino from a keyboard! 
 
The Arduino IDE serial monitor looks like this:
 

 
Below is some code on entering data into the serial monitor.

The arduino will wait till you have entered a value.

This serial monitor is in TinkerCad. 

Example 1

// variables
int myNumber;
String msg="Please Enter Your Number:";
String msg2="Your Number is: ";

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  // 3 things we do: ask wait read
  Serial.println(msg); //ask
  while (Serial.available()==0){
    // while there is no data
    //on the serial loop do nothing ..wait
   }
    //read
 
    myNumber=Serial.parseInt();
    Serial.print(msg2);

    Serial.println(myNumber);
 
  }

-----------------------------------------------------

Example 2
// we want the user to select how many times to blink the LED

// we want the user to select how many times to blink the LED

// variables
int numBlinks;
String msg="How many blinks do you want?:";
int j;
int bt=100;
int redPin=12;


void setup()
{
  Serial.begin(9600);
  pinMode(redPin,OUTPUT);
}

void loop()
{
  // 3 things we do: ask wait read
  Serial.println(msg); //ask
  while (Serial.available()==0){
    // while there is no data
    //on the serial loop do nothing ..wait
  }
    //read
    numBlinks=Serial.parseInt();
  for (j=1;j<=numBlinks;j=j+1){
    digitalWrite(redPin,HIGH);
    delay(bt);
    digitalWrite(redPin,LOW);
    delay(bt);
  }
      
   
 
}

-----------------------------------------------------------------------------------

Example 3
Not using the LED this time.

-------
// calculate the area of a circle

// variables

String msg="What is the radius of your circle ?:";
float radius;
float area;
String msg2="Your Circle Has an Area of : ";
float pi=3.14;

void setup()
{
  Serial.begin(9600);
 
}

void loop()
{
  // 3 things we do: ask wait read
  Serial.println(msg); //ask
  {
  while (Serial.available()==0);
    // while there is no data
    //on the serial loop do nothing ..wait
}
    //read
    radius=Serial.parseFloat(); // parseFloat  not parseInt
  area=pi*radius*radius;
  Serial.print(msg2);
  Serial.println(area);
 
      
   
 
}

 ----------------------------------------------

Links

 
 ---------------------------------
------------------------------------- 

No comments:

Post a Comment