How to Read Serial Data in Arduino

Ah, Arduino, I remember when you were just crawling around and blinking LEDs. Now you're ready to learn how to speak! In this lesson we'll learn how to use the Series Library to communicate from the Arduino board dorsum to the computer over the USB port. Then nosotros'll learn how to dispense numbers and data.

For this lesson we won't be using the shield, so only remove it (keeping the mood light LEDs on it you'd like). The shield doesn't comprise any programs or data, information technology is just our fashion of connecing up the LEDs and resistors. We'll use the shield once again but for now, we tin examine the RX and TX LEDs on the main Arduino board which will help y'all with debugging

Libraries are not bad places, and not still illegal in the U.s.a.! If you ever demand to learn how to do something, like say prepare a motorcycle, you lot can become to your local library and take out a book. Sure yous could purchase the volume but the library is nice because equally a resource yous tin get the book whenever you demand information technology, keeping your house uncluttered.

Software Libraries are very similar. We already studied what a process is, in lesson 3: a procedure is a listing of things to do. A library is a large collection of procedures, where all the procedures are related! If you, say, desire to command a motor, you may desire to find a Motor Control Library: a drove of procedures that have already been written for you lot that y'all can use without having to exercise the dirty work of learning the nuances of motors.

The library nosotros will be using is the Serial Library, which allows the Arduino to send data back to the computer:

Serial may audio like a tasty breakfast food, but its actually quite unlike. The discussion serial means "one after the other." For instance, a serial killer doesn't stop with one murder, but stabs many people one after the other. Serial data transfer is when we transfer data one chip at a time, i correct after the other.

Information is passed back & forth betwixt the computer and Arduino by, substantially, setting a pin high or depression. Simply like nosotros used that technique to turn an LED on and off, nosotros tin can also ship data. One side sets the pin and the other reads it. Information technology's a trivial like Morse code, where you can utilize dits and dahs to send messages by telegram. In this case, instead of a long cablevision, its only a few anxiety.


This is as proficient equally Microsoft Visio can do, yay!

(Now, people who are all geeked-out will probably get angry at this point because I'1000 simplifying things. Well guess what, its an Arduino tutorial, not a OSI Physical Network Architecture tutorial.)

The world isn't run by weapons anymore, or free energy, or coin. Information technology's run by little ones and zeroes, little bits of information. It's all just electrons. - Sneakers

At present is a good fourth dimension to review how data is measured. For instance, we measure out weight with "ounces" and "pounds" (or grams and kilograms) and distances with "inches," "feet," and "miles" (or centimeters, meters and kilometers). Information has its own system of measurements:

A unmarried bit is either a zero or a one.
You lot tin group bits together into viii $.25 which is i byte.
1024 bytes (8192 bits) is one Kilobyte (sometimes written KB).
1024 KB (1048576 bytes) is 1 Megabyte (MB)
1024 MB is 1 Gigabyte (GB)

An interesting thing to note is while 1000 grams is a kilogram, about all reckoner systems consider 1024 bytes to be a kilobyte. That is, a ane.0 Kilobyte file on your computer is 1024 bytes:

If your hard disk drive is 200 Gigabytes, how many bytes is that? Use a calculator with lots of digits!
Highlight the text below for the respond
200 GB * 1024 = 204800 MB
204800 MB * 1024 = 209715200 KB
209715200 KB * 1024 = 214748364800 bytes!

Hard drive makers are quite sneaky, you'll discover that they define GB equally beingness k MB, and 1 MB = thousand KB, etc. Given this fact, how many bytes tin you actually store in your 200GB bulldoze?
Highlight the text below for the answer
200 GB * k = 200000 MB
200000 MB * 1000 = 200000000 KB

How much less storage do you lot get thanks to the marketing guy who came up with this play a trick on?
Highlight the text below for the answer
About 4.6% less than yous'd expect

We've actually used the Serial communications adequacy already quite a chip...that's how nosotros transport sketches to the Arduino! When you Compile/Verify what you're really doing is turning the sketch into binary information (ones and zeros). When you Upload it to the Arduino, the $.25 are shoved out one at a time through the USB cablevision to the Arduino where they are stored in the principal chip.

Next time you upload a sketch, look carefully at the two LEDs near the USB connector, they'll blink when information is existence transmitted. I blinks when the Arduino is receiving information (RX) and 1 blinks when the Arduino is transmitting data (TX)

Enough chatting amidst ourselves, its fourth dimension to get the Arduino talking. Our offset sketch is going to exist the hullo world! program. When information technology starts upward, it will say "howdy world!"

Create a New Sketch... and salve it equally HelloWorld

Into the new sketch, copy and paste the following source lawmaking, and so save information technology

                  void                setup()                     {                Serial.begin(9600);                           Serial.println("How-do-you-do world!");   }                void                loop()                        {                                    }

OK first thing to discover is that there's nothing in the loop procedure! We've gutted it...and put some stuff into the setup process.

Even if nosotros accept naught in the setup or loop procedures, the Arduino requires them to exist in that location. That mode information technology knows you lot really mean to do nothing, every bit opposed to forgetting to include them!

The starting time line of code in the setup procedure is this 1:

Nosotros definately see that there is a Serial thing going on, and information technology looks like in that location is a procedure call as well. This is a library process phone call. The library is called Serial and inside the library is a process chosen begin.

library name

.

process proper noun

(input values)

;

Serial

.

begin

(9600)

;

If there's no library name, information technology means that the procedure is in the 'default' drove of procedures we use. For instance, filibuster() is so common, the designers of the Arduino software didn't bother putting it into a library.

So there's some mystery procedure that'southward called begin, well it's not too tough to figure out what it might do. It'due south the process that gets the Serial stuff gear up. Simply what's the 9600 near?
The annotate says 9600 bps, and just so you lot know bps stands for $.25-per-2nd (we will refer to this as the baud rate)
If you accept broadband connection, yous may remember reading somewhere that it has, say 350 kbps download charge per unit. This is how fast the connection can read and write bits on the wire. (Needless to say, your broadband connectedness can transfer data a lot faster than an Arduino!)

OK and then Serial.brainstorm sets up the Arduino with the transfer rate nosotros desire, in this case 9600 bits per 2nd.

Lets move on to the next line.

                Serial.println("Hello world!");                

This line too uses the Serial library, this fourth dimension it's calling a procedure called println which is just a shorthand for "print line". Annotation that the 6th letter of the alphabet in println is the letter L not the number 1. This time the input is a quotation, the line of text nosotros would similar it to print. We apply 2 "'s (double quotes) to indicate the offset and end of a line of text.

  • If the Arduino transfers information at 9600 bits per second and you're sending 12 bytes of data, how long does it take to send over this information?
    Highlight the text beneath for the respond
    12 bytes of information equals 12 * 8 = 96 bits of information. If we can transfer 9600 $.25 per 2d, then 96 bits takes 1/100th of a 2nd!
  • If the Arduino transfers data at 19200 $.25 per 2nd (19200 baud) and you're sending 12 bytes of data, how long does it take to ship over this information?
    Highlight the text below for the answer
    This is twice as fast as before, so it will take half the time, about 1/200th of a second.

Practiced, now compile the sketch and upload it to your Arduino....

Information technology looks similar not much is going on here. Somewhat disappointing since nosotros had then much fun with blinking colored lights before. The trick here is that while you lot can see blinking lights quite easily, seeing serial data requires a monitor, which like your display monitor will show us what data is being transfered.

Lucky for us, at that place'due south a serial monitor built into the Arduino software!

I'yard non quite sure what the icon ways, but regardless if you click that button you will replace the black Program Notification surface area with a Series Monitor.

So...click information technology!

What happens next is, sadly, quite dependent on which kind of Arduino you accept

Windows Mac OS X Linux
NG Arduino does not reset. Arduino does not reset. Arduino does not reset.
Diecimila Arduino resets, starts the sketch a few seconds later Arduino resets, starts the sketch a few seconds subsequently Arduino resets, starts the sketch a few seconds later

In the very common case of having a Diecimila Arduino, the serial monitor will automobile-reset the Arduino. The sketch will get-go up a couple of seconds subsequently

Otherwise, the Arduino does not reset itself. Either fashion, once you've switched to the serial monitor, press the reset push button. If yous take an NG Arduino you'll take to look 7 seconds for the sketch to outset.

Voila! It is our sketch!

Baud charge per unit lucifer up!

If yous ever find that you're getting a whole lot of gibberish instead of proper text, make sure that y'all have the correct baud charge per unit selected in the drop down menu of the Serial Monitor. Annotation that this advice baud rate is indepedent of the upload process, which is fixed at 19200 bps.

Next, try pressing the reset push a few times to make more How-do-you-do Worlds! appear. If you have an NG, this may exist a bit abrasive but do information technology anyways.

Each time you reset the Arduino, it performs the setup procedure, and prints out Hi again. If you expect closely at the Arduino, you lot will as well see the little TX LED glimmer merely as information technology prints out this message. That'southward your indication that data was sent.

What'due south Send do?

When yous println you are sending data from the Arduino to the computer. The Send button (and the text input adjacent to information technology) are used to send information to the Arduino. We aren't going to be using it in this lesson then don't be surprised that information technology doesn't do annihilation when you click information technology!

Our next sketch will exist a minor modification of this one. Instead of press out Hi World just in one case, we'd similar information technology to print information technology out over and over and over again.

  • What simple modification should we perform to brand the Arduino print Hello Globe over and over once more?
    Highlight the text below for the answer
    But motion the Serial.println("Hello world!"); statement from the setup procedure to the loop process.

Perform this modification and then compile and upload the new hyper-hello sketch. Then start up the series monitor. You will encounter Hello World! roll by super fast!

  • Whats going on with the TX LED?
    Highlight the text below for the answer
    It's lit, not blinking
  • Try waving the Arduino effectually in a dark room, what practise yous meet?
    Highlight the text beneath for the respond
    There are little dotted light trails
  • What's going on hither? Hint: Recall lesson 2?
    Highlight the text below for the respond
    The information is being transmitted so fast, that we tin't run into the TX LED blinking...information technology'southward sending data many times a second!

Brand the Arduino chill out a little by adding a one 2d delay to the sketch, so that it only prints out Hello World once a second.

                  void                setup()                     {                Serial.begin(9600);            }                void                loop()                        {                Serial.println("Hullo world!");                delay                (1000);                }

At present you should spend some time playing with println and making it display a message of your choice! Perhaps add some more println statements in gild to make the bulletin longer?

We've played around with printing out phrases, but it turns out we can besides impress out numbers pretty easily too.

                                    int                                a = five;                int                b = 10;                int                c = 20;                                  void                                setup()                     {                Serial.brainstorm(9600);                           Serial.println("Here is some math: ");                Serial.print("a = ");                Serial.println(a);                Series.print("b = ");                Serial.println(b);                Serial.print("c = ");                Serial.println(c);                Serial.print("a + b = ");                       Serial.println(a + b);                Serial.print("a * c = ");                       Series.println(a * c);                Serial.print("c / b = ");                       Serial.println(c / b);                Serial.impress("b - c = ");                       Serial.println(b - c); }                void                                loop()                      { }              

Try out this sketch on your Arduino

Note that we're using two procedures here, the original println and at present also print. The print procedure is just like println except it does not print out a "railroad vehicle return" at the end, starting a new line. You can experiment with changing the impress's to println'south and looking at the Series Monitor output to verify this for yourself.

Hither'south whats going on in the Arduino with this sketch. For case, lets look at this line:

We've seen that if you apply a quoted line of text equally input to println process, it will display that text. In this instance you tin can encounter that if you use a variable to println it will look up what that variable contains and print that out!

It turns out that the Arduino is smart plenty to also practise math when asked:

In this case, the Arduino looks at what the input to println is, and finds its really a calculation. It looks up what a is (v) and what b is (10) and then adds them together (+) then uses that as the value to transport to println

Note that for now, we tin can only do math using integers, which if yous recollect, are whole numbers. That ways we can't notwithstanding print out numbers like 3.14 or one.5.

I could become on and on about operators, its all very important stuff, but many people accept written proficient tutorials on this topic already then I'm going to send you off to read them in that location!

  • A C++ tutorial (this i'due south pretty squeamish, just ignore the cout stuff which is C++'s way of press out values)
  • A C tutorial on operators
  • A list of all the math operators

Let's make our beginning simple estimator, to calculate a hypoteneuse. If you lot remember from form school, if you have a right-triangle, the hypoteneuse h can be calculated from the lengths of the two legs, c1 and c2 (which we'll telephone call a & b)

a2 + b 2 = h 2
h = (a2 + b2 )

                  #include                "math.h"                                                int                a = three;                int                b = iv;                int                h;                void                setup()                     {                Serial.begin(9600);                           Serial.println("Lets calculate a hypoteneuse");                Serial.print("a = ");                Serial.println(a);                Series.print("b = ");                Series.println(b);      h =                sqrt( a*a + b*b );                Series.impress("h = ");                Series.println(h); }                void                                loop()                 { }              

The first thing that'south new here is this line at the very offset of the sketch:

Which basically says "We'd like to use the math procedures, which are in a library that requires us to include the file math.h where the sqrt procedure lives". Merely ignore information technology for at present, it'southward not important.

The second thing that's different here is that when we create the variable h we don't assign it a value.

It turns out that this is totally OK, it merely means that we don't know what h is going to store withal, because nosotros're going to calculate it later. Since information technology's not assigned to a value upon creation, the Arduino just creates the box, the stuff inside is whatever was in left over in memory.

Default values

If y'all don't assign a value to a variable, information technology could be any value. Brand sure you lot don't endeavor to use the variable before y'all assign it a value!

Later on on in the sketch, we assign information technology the value.

In this line, we square a and b and then add them together, then we call the sqrt() procedure (which does exactly what yous may think), to have the square root. So we assign that to the variable h.

Whatever was in h before is lost, replaced by the new value.

You can nest procedures and functions all y'all desire, calling a procedure on the render value of some other procedure.

  • Lets say you have a variable "foo" which contains a number. Yous'd like to find the square root of the square root of this number. What line of code would print out this value?
    Highlight the text below for the answer
    Serial.println( sqrt( sqrt(foo) );
    First take the square root of foo, then take the square root of that and then utilize that value as the input to println

Now its your plough to create a calculator.
You'll create a Ohm'south law figurer. Ohm'south law says that Voltage = Current * Resistance. (This is a pretty useful law which forms the basis of electronics, and we'll report it in depth more subsequently.) Starting with two variables, i for current and r for resistance, accept it print out the amount of voltage that tin can be measured accross the resistor.

Let'south write a program that will do that hard drive size calculation we did before. We'll start with the hard drive size in GB, and print out how many MB in that location are.

We'll beginning unproblematic, just printing out the drive size in GB

                  int                drive_gb = 5;                void                setup()                     {                Serial.begin(9600);                           Serial.print("Your Hd is ");
Serial.print(drive_gb);
Serial.println(" GB big."); } void loop() { }

Copy and paste this sketch into Arduino software and name the sketch DriveCalc. And then compile and upload it.

OK, lets add a department of code that will print out the number of Megabytes in the difficult drive.

                  int                drive_gb = 5;                int                drive_mb;                  void                setup()                     {                Serial.begin(9600);                           Serial.print("Your HD is ");
Serial.impress(drive_gb);
Serial.println(" GB large."); drive_mb = 1024 * drive_gb; Serial.print("Information technology can store ");
Series.print(drive_mb);
Serial.println(" Megabytes!"); } void loop() { }

This time if you compile and upload it you should go

Which is correct, yay! Now try a few different whole numbers for the drive size, from 1 GB to 100 GB.

You may detect that if you lot put in a 100GB drive size, something very, very strange happens:

A 100GB drive should have 102400MB in it, not some negative number. What's going on here?

What's happening is that we take an overflow trouble. Think about your car odometer. The odometer has only four digits, it can display 0 miles to 9999 miles travelled. If yous travel 10000 miles, the odometer will "gyre over" to 0 over again, and from then on it volition brandish an incorrect value.

Keeping that in mind, remember in lesson 2 we said that when we define a variable we too define the box-type of the variable? The box is where we shop the data, in this case the type is int. It turns out that an int type can store merely 2 bytes.


How many $.25 are in 2 bytes?
Highlight the text beneath for the answer
There are 8 $.25 in 1 byte then 2 bytes is xvi $.25

To effigy out how big a number we can store in a 2 byte-sized box employ a calculator and take two to the power of the number of $.25 (since each bit can store two values, 0 or i). Then we subtract 1 because similar in the machine odometer, you can't actually brandish the final value, 10000. So, in this instance the largest number is two16 - ane = 65535. Since the number we're trying to store (102400) is larger than that, nosotros see that "rollover."

OK let'south set up it! All we demand to exercise is change the variable blazon and so that it can store more than ii bytes of information. Hither is a short list of types we tin can use.

Type Size (bits) Size (bytes)
byte

eight

one

int

xvi

ii

long

32

4

It looks like we want to employ the long type. So lets brand that alter

                  int                drive_gb = 100;                long                drive_mb;                                  void                setup()                     {                Series.begin(9600);                           Series.impress("Your HD is ");
Serial.impress(drive_gb);
Serial.println(" GB large."); drive_mb = 1024 * drive_gb; Serial.print("It tin can store ");
Series.print(drive_mb);
Serial.println(" Megabytes!"); } void loop() { }

Compile and upload this sketch....then run the Serial Monitor....

Uh oh, we didn't actually ready the problem!

How frustrating, we did the right thing and it even so didn't piece of work. The problem we have now is although the boxes are the right size, we're not handling them well.

                drive_mb = 1024 * drive_gb;

If you look at this line, what'due south happening here is that the Arduino looks up the value of the variable drive_gb to go 100. Then we multiply 100 by 1024 to become 102400 and put that in the drive_mb box. Except the way that the Arduino software does this is that it creates a temporary variable the same size as drive_gb to shop that calculation result before it sticks it into drive_mb. Then basically we are still getting an overflow, except now its happening as we practice the calculation.

Here is ane way to fix this insiduous bug:

                  int                drive_gb = 100;                long                drive_mb;                                  void                setup()                     {                Serial.brainstorm(9600);                           Series.print("Your Hard disk drive is ");
Serial.print(drive_gb);
Serial.println(" GB large."); drive_mb = drive_gb; drive_mb = drive_mb * 1024; Serial.print("It can store ");
Serial.print(drive_mb);
Serial.println(" Megabytes!"); } void loop() { }

Now when we do the calculation, the temporary result is stored in a box the aforementioned size every bit drive_mb (a long) instead of an int.

Compile and upload this sketch to try it out

There you go, at present its working!

Information technology turns out that I wasn't completely honest in the previous department when I described all the different types. There's another of import fact to know, and that has to practice with storing negative numbers.

We know that a variable that is 2 bytes big (16 $.25) can store 216 different values. We assumed earlier that these values were 0 - 65535 inclusive. But and then how exercise we store negative numbers? Information technology turns out that at that place are two kinds of variables, signed and unsigned.
Signed variables can take a positive or negative value, and so you can shop negative numbers.
Unsigned
variables can just store positive numbers.

By default, variables are signed.

Type Size ($.25) Size (bytes) Minimum Value Maximum Value

unsigned byte

eight

1

0

255

byte

eight

1

-128

127

unsigned int

16

ii

0

65535

int

xvi

two

-32768

32767

unsigned long

32

4

0

4294967295

long

32

4

-2147483648

2147483647

  • Lets say you lot accept a program that stores the age of a human in years (which so far is no more than 122), whats a skilful information type to use?
    Highlight the text below for the answer
    You lot probably want to use a byte blazon
  • Lets say you desire to store the age of a man in seconds, what is an appropriate data type now?
    Highlight the text below for the respond
    110 years = 3468960000 seconds. You'll need to store this in an unsigned long variable.

Why Types?

OK and then yous're probably wondering: "This is such a hurting, why bother with different size types? Lets just have every variable be as large every bit possible and we'll never have scroll-over problems."

Well, on your desktop figurer, with gigabytes of memory (RAM), this is a reasonable thing to exercise. However, the tiny tiny computer in the Arduino has a k total of 1 Kilobyte of memory. And some of that is used for background stuff you don't run across. For minor sketches sure you lot can brand everything a long and be done with information technology, but if you have a bigger sketch, yous'll run out of memory actually fast and then you'll have major issues. Then in this case, every byte counts!

What's weird most signed numbers is that if you accomplish the cease of the positive value range y'all'll rollver into the negative values.

For case, lets say yous take a signed int. If yous accept the value 32767 in that variable, and you add one to the variable, you lot'll really rollover to -32768.

This sketch will test out this fact:

                int                test = 32767;                                  void                setup()                     {                Serial.begin(9600);                           Serial.print("Examination value is: ");
Series.println(test); test = examination + one; Serial.print("Now it is ");
Series.println(test); } void loop() { }

Compile and upload to run the examination.

  • Let's say nosotros have a variable that is byte type, information technology's signed by default. It starts out with the value 127 and we add together ane to the variable, what will the new variable value be?
    Highlight the text below for the reply
    Information technology'south a signed variable so it will roll over to -128
  • Let's say at present it is an unsigned byte type, what happens at present?
    Highlight the text below for the answer
    Since it is unsigned, it tin store much more information, so it volition be able to agree the value 128.
  • If we accept an unsigned byte and it starts out with the value 250 and we add ten, what volition the value be?
    Highlight the text below for the respond
    Even though thie variable can store a lot, it can't shop more than the number 255, so it will rollover and nosotros'll cease up with the number 4.

Now it's your turn!

Write some sketches that will assist you understand variable sizes, effort creating variables of different types and signedness and adding and subtracting.

Although this lesson part seems quite boring, and severely lacking in blinky lights, understanding this stuff now will relieve you from a lot of headaches later when y'all have data overflows and your programme is all wonky and yous're really frustrated because you can't figure out why. (Trust me on this 1!)

Now its fourth dimension for y'all to aggrandize the drive size computer. Starting with the DriveCalc sketch, modify it so that it will likewise summate how many KB are stored in the difficult drive. Exam it out with a couple dissimilar drive sizes.

One time you've got that working, alter it again so that it will too display how much space the drive actually holds thanks to the sneaky math-trick that manufacturers use. Have the sketch display how much storage space is 'missing' (in KB) as well.

Here's one possible solution:

/*  * Drive size calculator!  */   int drive_gb = 100; long drive_mb; long drive_kb; long real_drive_mb; long real_drive_kb;   void setup()                    // run one time, when the sketch starts {   Serial.begin(9600);           // gear up Serial library at 9600 bps    Serial.print("Your HD is ");   Serial.print(drive_gb);   Serial.println(" GB big.");    drive_mb = drive_gb;   drive_mb = drive_mb * 1024;   drive_kb = drive_mb * 1024;      Serial.print("In theory, it can store ");   Series.impress(drive_mb);   Serial.print(" Megabytes, ");   Serial.impress(drive_kb);     Serial.println(" Kilobytes.");    real_drive_mb = drive_gb;   real_drive_mb = real_drive_mb * 1000;   real_drive_kb = real_drive_mb * 1000;      Series.print("But it really only stores ");   Serial.print(real_drive_mb);   Series.print(" Megabytes, ");   Serial.print(real_drive_kb);     Serial.println(" Kilobytes.");      Serial.impress("You are missing ");   Series.print(drive_kb - real_drive_kb);     Serial.println(" Kilobytes!"); }  void loop()                       // run over and over again { }              

Good piece of work, you got through ane of the more boring lessons. In this lesson you learned how to print text and data to the Serial Monitor. This is essential for debugging hereafter projects! You likewise learned about data types and storage and how to use the Arduino to calculate stuff.

wunderlichwourethe.blogspot.com

Source: https://www.ladyada.net/learn/arduino/lesson4.html

0 Response to "How to Read Serial Data in Arduino"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel