You are on page 1of 58

Beginners Guide to

C#
and the
.NET Micro Framework
January 20
th
202
!e" 2.0
Co#yright $ 202 G%& E'ectronics( ))C
www.G%&E'ectronics.com
Community* www.TinyC)!.com
Gus &ssa
Licensed under Creative Commons Share Alike 3.0
Beginners guide to C# and NETM
Table of Contents
!.A"out the Book..........................................................3
!.!.#ntended Audience............................................3
!.$.%isclaimer..........................................................3
$.#ntroduction................................................................&
$.!.Advantages.......................................................&
3..NET 'adgeteer........................................................(
&.'etting Started..........................................................)
&.!.S*stem Setu+....................................................)
&.$.The Emulator.....................................................)
Create a ,ro-ect.................................................)
Selecting Trans+ort.............................................
E/ecuting...........................................................0
Break+oints......................................................!0
&.3.1unning on 2ard3are......................................!!
M%e+lo* can ,ing4.........................................!!
%e+lo*ing to 2ard3are.....................................!$
(.C# Level !...............................................................!3
(.!.5hat is .NET6.................................................!3
(.$.5hat is C#6.....................................................!3
7Main8 is the Starting ,oint...............................!3
Comments........................................................!&
3hile9loo+.........................................................!(
:aria"les..........................................................!)
Assem"lies.......................................................!.
5hat Assem"lies to Add6................................$!
Threading.........................................................$$
).%igital #n+ut ; <ut+ut..............................................$(
).!.%igital <ut+uts.................................................$(
Blink an LE%.....................................................$=
).$.%igital #n+uts....................................................$.
).3.#nterru+t ,ort...................................................30
).&.Tristate ,ort.....................................................3!
=.C# Level $...............................................................33
=.!.Boolean :aria"les...........................................33
=.$.i>9statement......................................................3(
=.3.i>9else9statements............................................3)
=.&.Methods and Arguments.................................3.
=.(.Classes............................................................30
=.).,u"lic vs. ,rivate.............................................&0
=.=.Static vs. non9static.........................................&0
=...Constants........................................................&!
=.0.Enumeration....................................................&!
..Assem"l*?irm3are Matching.................................&&
Boot9u+ Messages...........................................&&
0.'ar"age Collector...................................................&)
0.!.Losing 1esources............................................&=
0.$.%is+ose...........................................................&.
0.3.'C <ut+ut Messages......................................&0
!0.C# Level 3.............................................................(0
!0.!.B*te...............................................................(0
!0.$.Char...............................................................(0
!0.3.Arra*..............................................................(!
!0.&.String.............................................................($
!0.(.or9Loo+........................................................(3
!0.).S3itch Statement...........................................((
!!.Additional 1esources.............................................(.
Tutorials and %o3nloads..................................(.
Codeshare........................................................(.
eBooks.............................................................(.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age $?(.
Beginners guide to C# and NETM !.A"out the Book
1. About the Book
1.1. Intended Audience
This "ook is >or "eginners 3anting to get started on .NET Micro rame3ork. No +rior
kno3ledge is necessar*. The "ook covers the "asics o> .NET Micro rame3orkA :isual Studio
and even C#4
#> *ouBre a ho""*ist or an engineerA *ou 3ill >ind a good deal o> in>o in this "ook. This "ook
makes no assum+tion a"out 3hat *ouA the readerA kno3s so ever*thing is e/+lained
e/tensivel*.
1.2. Disclaimer
This is a >ree "ook use it >or *our o3n kno3ledge and at *our o3n risk. Neither the 3riter nor
'2# Electronics is res+onsi"le >or an* damage or loss caused "* this >ree eBook or "* an*
in>ormation su++lied "* it. There is no guarantee an* in>ormation in this "ook is valid.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age 3?(.
Beginners guide to C# and NETM $.#ntroduction
2. Introduction
2ave *ou ever thought o> some great idea >or a +roduct "ut *ou couldnBt "ring it to li>e
"ecause technolog* 3asnBt on *our side6 <r ma*"e thoughtA 7thereBs got to "e an easier
3a*48 Ma*"e *ou are a +rogrammer that 3anted to make a securit* s*stem "ut then thought
using a ,C is too e/+ensive to run a sim+le s*stem6 The ans3er is Microso>tBs .NET Micro
rame3ork4
2ere is a scenarioA *ou 3ant to make a +ocket9',S9data9logger that saves +ositionsA
accelerationA and tem+eratures on a memor* card and dis+la*s them on a small dis+la*.
',S devices can send +osition data over a serial +ortA so *ou can easil* 3rite some code on
a ,C to read the ',S data and save it on a >ile. But a ,C 3onBt >it in *our +ocket4 Another
+ro"lem is ho3 3ould *ou measure tem+erature and acceleration on a ,C6 #> *ou make this
+ro-ect using classic microcontrollersA like A:1A or ,#C microA all this can "e done "ut then
*ou need a com+iler >or the microcontroller *ou chose C3hich +ro"a"l* ver* e/+ensiveDA a
3eek to learn the +rocessorA a 3eek to 3rite a serial driverA a month or more to >igure out the
AT >ile s*stem and more time >or memor* cards...etc. Basicall*A it can "e done in >e3 3eeks
or months o> 3ork.
2.1. Advantages
#> *ou are using .NET Micro rame3ork then there are man* advantagesE
!. #t runs on Microso>tBs :isual C# E/+ressA >ree and and high9end #%E.
$. .NET Micro rame3ork is o+en9source and >ree.
3. Four same code 3ill run an* NETM device 3ith almost no changes.
&. ull de"ugging ca+a"ilities. CBreak+ointsA ste++ing in codeA varia"les...etc.D
(. 2as "een tested in man* commercial +roductsA 3ith assured Gualit*.
). #ncludes man* "us drivers.CS,#A HA1T A #$C...etc.D
=. Eliminates the need to use com+licated and long +rocessorsB datasheets.
.. #> *ou are alread* a ,C C# +rogrammer then *ou are kno3 NETM.
Throughout this document, I may refer to .!T "icro #rame$ork as !T"#.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age &?(.
Beginners guide to C# and NETM 3..NET 'adgeteer
%. .!T &adgeteer
.NET 'adgeteer +lat>orm de>initions take NETMBs >le/i"ilit* to the ne/t level. #t is a set o>
rules on ho3 hard3are modules can interact 3ith a main"oard. The com+lete s+eci>ications
and so>t3are are o+en9source. '2# Electronics is +roud to the >irst to o>>er a .NET 'adgeteer
+lat>orm.
'2# Electronics strongl* "elieves in .NET 'adgeteer and is strongl* investing in e/+anding
the gadgetr*9com+ati"le o>>ers. Current o>>ers are >ound at
htt+E??333.ghielectronics.com?catalog?categor*?$)(?
This "ook is not meant to "e used >or gadgeteer devices "ut it can "e a great tool to
understanding the NETMA 3hich is 'adgeteerBs core engine.
7.NET 'adgeteer Hltimate 'uide8 is another >ree e"ook that targets .NET 'adgeteer.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age (?(.
Beginners guide to C# and NETM &.'etting Started
'. &etting (tarted
Im)ortant note* #> *ou have -ust received *our hard3are or *ou are not sure 3hat >irm3are is
loaded on itA *ou MHST u+date the >irm3are. Four deviceBs manual 3ill have more in>o on
ho3 to do so. AlsoA make sure *ou read the 7>irm3are?assem"l* matching8 section in this
"ook.
'.1. (ystem (etu)
Be>ore 3e tr* an*thingA 3e 3ant to make sure the ,C is setu+ 3ith needed so>t3are. irst
do3nload and install +isual C, e-)ress 2.1. C:S$00. or older 3ill not 3orkD
htt+E??333.microso>t.com?e/+ress?vcshar+?
No3A do3nload and install .NET Micro rame3ork &.! S%I Cnot the +orting kitD and the '2#
+ackage installer. Both are >ound on this +age
htt+E??333.tin*clr.com?su++ort?
B* the 3a*A *ou ma* 3ant to "ookmark this +age as it has a"out ever*thing *ou need to use
NETM.
'.2. The !mulator
NETM includes an emulator that allo3s *ou to run NETM a++lications right on *our ,C. or
our >irst +ro-ectA 3e 3ill use the emulator to run a ver* sim+le a++lication.
Create a /ro0ect
<+en :isual C# E/+ress andA >rom the menuA select file 12 e$ /ro0ect. The 3iJard should
no3 have the 7Micro rame3ork8 o+tion in the le>t menu. Click on itA and >rom the tem+latesA
select 7Console A++lication8.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age )?(.
Beginners guide to C# and NETM &.'etting Started
Click the 7<I8 "utton and *ou 3ill have a ne3 +ro-ect that is read* to run. The +ro-ect onl*
has one C# >ileA called ,rogram.csA 3hich contains ver* >e3 lines o> code. The >ile is sho3n
in 7Solution E/+lorer8 3indo3. #> this 3indo3 is not sho3ing then *ou can o+en it "* clicking
7:ie39KSolution E/+lorer8 >rom the menu.
using System;
using Microsoft.SPOT;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
#ebug.Print!
$esources.%etString!$esources.String$esources.String1"";
&
&
&
Co+*right @ $0!$ '2# ElectronicsA LLC ,age =?(.
Beginners guide to C# and NETM &.'etting Started
or sim+licit* change the code to look like the listing "elo3
using System;
using Microsoft.SPOT;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
#ebug.Print!'Ama(ing)'";
&
&
&
Selecting Trans+ort
%onBt 3orr* i> *ou do not understand the code. # 3ill e/+lain it later. or no3A 3e 3ant to run it
on the emulator. LetBs make sure *ou have ever*thing setu+ +ro+erl*. Click on 7,ro-ect9
K,ro+erties8 >rom the menu. #n the ne3 sho3ing 3indo3A 3e 3ant to make sure 3e select the
emulator. <n the le>t side ta"sA select 7.NET Micro rame3ork8 and make sure the 3indo3
looks like the image "elo3.
Trans+ortE Emulator
Co+*right @ $0!$ '2# ElectronicsA LLC ,age .?(.
Beginners guide to C# and NETM &.'etting Started
%eviceE Microso>t Emulator
Make sure the out+ut 3indo3 is visi"leA click on 7:ie39K<ut+ut8
!-ecuting
inall*A 3e are read* to run our >irst a++lication. ,ress ( ke* on the com+uter. This is a ver*
use>ul shortcut and *ou 3ill "e using it a lot to run *our a++lications. A>ter *ou +ress (A the
a++lication 3ill "e com+iled and loaded on the emulator and in cou+le seconds ever*thing 3ill
sto+4 That is "ecause our +rogram had >inished e/ecution so >ast that 3e didnBt see much.
5e 3ant to 7de"ug8 the code no3. %e"ugging means that *ou are a"le to ste+ in the code
and see 3hat it is doing. This is one o> the greatest values o> NETM.
This time use !! instead o> (A this 3ill 7ste+8 in the a++lication instead o> -ust running it.
This 3ill de+lo* the a++lication on the emulator and sto+ at the ver* >irst line o> code. This is
indicated "* the *ello3 arro3.
C# a++lications al3a*s start >rom a method called Main and this is 3here the arro3 sto++ed.
,ress !! again and the de"ugger 3ill run the ne/t line o> codeA 3hich is the line *ou
changed "e>ore. Fou +ro"a"l* have guessed it rightA this line 3ill +rint 7AmaJing48 to the
de"ug 3indo3. The de"ug 3indo3 is the out+ut 3indo3 on :isual C# E/+ress. Make sure
<ut+ut 3indo3 is visi"le like e/+lained earlier and +ress !! one more time. <nce *ou ste+
on that lineA *ou 3ill see the 3ord 7AmaJing48A sho3ing in the out+ut 3indo3.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age 0?(.
Beginners guide to C# and NETM &.'etting Started
#> *ou no3 +ress !! againA the +rogram 3ill end and the emulator 3ill e/it.
Break)oints
Break+oints are another use>ul >eature 3hen de"ugging code. 5hile the a++lication is
runningA the de"ugger checks i> e/ecution has reached a "reak+oint. #> soA the e/ecution 3ill
+ause. Click the "ar to the le>t o> the line that +rints 7AmaJing48 This 3ill sho3 a red dot 3hich
indicates a "reak+oint.
No3 +ress ( to run the so>t3are and 3hen the a++lication reaches the "reak+ointA the
de"ugger 3ill +auseA as sho3n in the image "elo3
No3A *ou can ste+ in the code using !! or continue e/ecution using (.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age !0?(.
Beginners guide to C# and NETM &.'etting Started
'.%. 3unning on 4ard$are
1unning NETM a++lications on hard3are is ver* sim+le. #nstructions can "e slightl* di>>erent
on di>>erent hard3are. This "ook uses EL >or demonstration +ur+oses "ut an* other
hard3are 3ill 3ork similarl*.
"#De)loy can /ing5
Be>ore 3e use the hard3areA let us make sure it is +ro+erl* connected. The NETM S%I
comes 3ith so>t3are >rom Microso>t called M%e+lo*. There are man* good uses >or
M%e+lo* "ut >or no3 3e onl* need it to 7+ing8 the device. Basicall*A 7+ing8 means that
M%e+lo* 3ill sa* 72i8 to the device and then checks i> the device 3ill res+ond 3ith 72i8 "ack.
This is good to make sure the device is connected +ro+erl* and trans+ort 3ith it has no
issues.
<+en M%e+lo* and connect EL using the included HSB ca"le to *our ,C. #> this is the >irst
time *ou +lugged in ELA 5indo3s 3ill look >or the drivers and automaticall* >ind them. #> notA
su++l* the driver >rom the S%I >older and 3ait till 3indo3s is >inished.
#n the dro+9do3n menuA select HSB. Fou should see *our device sho3ing in the device list.
#n m* e/am+leA # see HSBiJi. Select *our device and click the 7,ing8 "utton. Fou should no3
see Tin*CL1.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age !!?(.
Beginners guide to C# and NETM &.'etting Started
De)loying to 4ard$are
No3 that 3e checked that the hard3are is connected using M%e+lo*A 3e need to go "ack to
:isual Studio. rom the +ro-ect +ro+ertiesA select HSB >or trans+ort and then *our device
Cmine is HSBiJiD. Make sure *our setu+ looks similar to the image "elo3.
,ressing ( 3ill no3 send our sim+le a++lication to EL and it 3ill run right inside the real
hard3are. S3itching >rom emulator to real hard3are is that sim+le4
Tr* the ste+s 3e did 3ith the emulatorA like setting "reak+oints and using !! to ste+ in the
code. Note that 7%e"ug.,rint8 3ill still >or3ard the de"ug messages >rom the hard3are "ack to
the out+ut 3indo3 on :isual Studio.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age !$?(.
Beginners guide to C# and NETM (.C# Level !
6. C, 7evel 1
This "ook is not meant to cover C# in details "ut # 3ill cover most o> "asics to hel+ *ou get
started.
6.1. 8hat is .!T9
.NET rame3ork 3as develo+ed to standardiJe +rogramming. CNote ho3 # am talking a"out
the >ull .NET rame3ork and not the "icro rame3ork.D <nce *ou +rogram in .NETA *ou are
no longer concerned o> the underl*ing o+erating s*stem. #t o>>ers a set o> li"raries that
develo+ers can use >rom man* +rogramming languages.
The .NET rame3ork runs on ,Cs and not on smaller devicesA "ecause it is a ver* large
>rame3ork. AlsoA the >ull >rame3ork has man* things CmethodsD that 3ouldnBt "e ver* use>ul
on smaller devices. This is ho3 .NET Com+act rame3ork 3as "orn. The com+act
>rame3ork removed unneeded li"raries to shrink do3n the siJe o> the >rame3ork. This smaller
version runs on 5indo3s CE and smart +hones. The com+act >rame3ork is smaller than the
>ull >rame3ork "ut it is still too large >or mini devices "ecause o> its siJe and "ecause it
reGuires an o+erating s*stem to run.
.NET Micro rame3ork is the smallest version o> those >rame3orks. #t removed more li"raries
and it "ecame <S inde+endent. Because o> the similarit* among these three >rame3orksA
almost the same code can no3 run on ,Cs and small devicesA 3ith little or no modi>ications.
or e/am+leA using the serial +ort on a ,CA 5inCE device or EL 3orks the same 3a*A 3hen
using .NET.
6.2. 8hat is C,9
C and CMM are the most +o+ular +rogramming languages. C# is an u+dated and moderniJed
version o> C and CMM. #t includes ever*thing *ou 3ould e/+ect >rom a modern languageA like
gar"age collector and run9time validation. #t is also o"-ect9oriented 3hich makes +rograms
more +orta"le and easier to de"ug and +ort. Although C# +uts a lot o> rules on +rogramming
to shrink do3n the "ug9+ossi"ilitiesA it still o>>ers most o> the +o3er>ul >eatures C?CMM have.
:"ain; is the (tarting /oint
Like 3e seen "e>oreA +rograms al3a*s start at a method called Main. A method is a little
chunk o> code that does a certain task. Methods start and >inish 3ith o+en?close curl*
"rackets. #n our >irst +rogramA 3e onl* had one line o> code "et3een our curl* "rackets.
The line 3as %e"ug.,rintCNAmaJing4NDO
Co+*right @ $0!$ '2# ElectronicsA LLC ,age !3?(.
Beginners guide to C# and NETM (.C# Level !
Fou can see ho3 the line ends 3ith a semicolon. All lines must end the same 3a*.
This line calls the ,rint method that e/ists in the %e"ug o"-ect. #t calls it 3hile +assing the
string 7AmaJing48
Con>used6 LetBs tr* to clear it out a "it. LetBs sa* *ou are an o"-ect. Fou also have multi+le
methods to control *ouA the o"-ect. <ne method can "e 7Sit8 and another can "e 71un8. No3
3hat i> # 3ant *ou to 7Sa*8 amaJing6 # 3ill "e calling *our s+eak method 3ith the sentence
CstringD 7AmaJing48. So the code 3ill look likeE
Fou.Sa*C7AmaJing48DO
No3A 3h* do 3e need the Guotes "e>ore and a>ter the 3ord AmaJing6 That is "ecause C#
doesnBt kno3 i> the te/t *ou are 3riting is actuall* a command or it is actuall* te/t CstringsD.
Fou can see ho3 it is colored in red 3hen *ou add GuotesA 3hich makes reading code easier
>or usA humans.
Comments
5hat i> *ou 3ant to add comments?notes?3arnings in *our code6 Those comments 3ill hel+
*ou and others understand 3hat the code means. C# com+letel* ignores these comments.
There are $ 3a*s to create commentsA line comments and "lock comments. Comments
C#gnored te/tD are sho3n in green.
To comment a lineA or +art o> a lineA add ?? "e>ore the comment te/t. The color o> the te/t 3ill
change to green indicating that the te/t is no3 comment and is ignored "* C#.
using System;
using Microsoft.SPOT;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
** T+is is a comment
#ebug.Print!'Ama(ing)'";**t+is is a comment too)
&
&
&
Co+*right @ $0!$ '2# ElectronicsA LLC ,age !&?(.
Beginners guide to C# and NETM (.C# Level !
Fou can also comment a 3hole "lock. Start the comment 3ith ?P and then end it 3ith P?
s*m"ols
using System;
using Microsoft.SPOT;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
*, T+is is a comment
it-s still a comment
t+e bloc. /ill en no/ ,*
#ebug.Print!'Ama(ing)'";
&
&
&
$hile1loo)
#t is time >or our >irst ke*3ordA 73hile8. The 3hile9loo+ starts and ends 3ith curl* "rackets to
contain some code. Ever*thing inside 3ill continuousl* run 3hile a statement is true. or
e/am+leA # can ask *ou to kee+ reading this "ook 73hile8 *ou are a3ake4
SoA letBs make a +rogram that continuousl* +rints 7AmaJing48 endlessl*. This endless loo+ has
no ending so it 3ill al3a*s "e 7true8.
using System;
using Microsoft.SPOT;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
/+ile!true"
{
#ebug.Print!'Ama(ing)'";
&
&
&
&
Co+*right @ $0!$ '2# ElectronicsA LLC ,age !(?(.
Beginners guide to C# and NETM (.C# Level !
#n the code a"oveA e/ecution 3ill start at the 7Main8 method as usual and then it 3ill go to the
ne/t lineA 3hich is the 3hile9loo+. The 3hile9loo+ is telling the run time to e/ecute the code
inside its "rackets 3hile the statement is 7true8. Actuall*A 3e do not have a statement thereA
"ut 3e have 7true8 instead 3hich means this loo+ 3ill al3a*s run.
%o not hit ( to run the +rogram or *ou 3ill >lood the out+ut 3indo3 3ith the 3ord 7AmaJing48.
#nsteadA hit !! and ste+ in the code to understand ho3 the loo+ 3orks. Note that this
+rogram 3ill never end so *ou 3ill need to >orce sto+ using shi>tM(.
NoteE Fou can reach all these de"ug shortcuts >rom the menu under %e"ug.
+ariables
:aria"les are +laces in memor* reserved >or *our use. The amount o> memor* reserved >or
*ou de+ends on the t*+e o> the varia"le. # 3ill not cover ever* single t*+e here "ut an* C#
"ook 3ill e/+lain this in details.
5e 3ill "e using an int varia"le. This t*+e o> varia"le is used to hold integer num"ers.
Sim+l* sa*ingE
int M*:arO
3ill tell the s*stem that *ou 3ant some memor* reserved >or *ou. This memor* 3ill "e
re>erenced to as M*:ar. Fou can give it an* name *ouBd likeA as long as the name doesnBt
contain s+aces. No3A *ou can +ut an* integer num"er into this memor*?varia"le.
M*:ar Q !$3&O
Fou can also use mathematical o+erations to calculate num"ersE
M*:ar Q !$3 M &()O
or *ou can increment the num"er "* oneE
M*:arMMO
or decrement it "* oneE
M*:ar9 9O
5ith all thatA can 3e make a +rogram that +rints the 3ord BAmaJing4B three times. 2ere is the
code
using System;
using Microsoft.SPOT;
namespace MFConsoleApplication1
{
public class Program
{
Co+*right @ $0!$ '2# ElectronicsA LLC ,age !)?(.
Beginners guide to C# and NETM (.C# Level !
public static voi Main!"
{
int My0ar;
My0ar 1 2;
/+ile!My0ar34"
{
My0ar55;
#ebug.Print!'Ama(ing)'";
&
&
&
&
Notice ho3 the 3hile9loo+ statement is not 7true8 an*moreA "ut it is M*:arK0. This means
kee+ loo+ing as long as M*:arBs value is greater than 0.
#n the ver* >irst loo+ M*:ar is 3. #nside ever* loo+A 3e decrement M*:ar "* one. This 3ill
result in the loo+ running e/actl* three times and there>ore +rinting 7AmaJing48 three times.
LetBs make things more interesting. # 3ant to +rint the num"ers ! through !0. <IA 3e kno3
ho3 to make a varia"le and 3e kno3 ho3 to increment it "ut ho3 do 3e +rint a num"er to the
de"ug out+ut 3indo36 Sim+l* giving M*:ar to %e"ug.,rint 3ill give *ou an error and it 3onBt
3ork. This is "ecause %e"ug.,rint 3ill onl* acce+t stringsA not integers. 2o3 do 3e convert
an integer varia"le 7ToString86 #t is ver* sim+leA call M*:ar.ToStringCD. That 3as eas*4
using System;
using Microsoft.SPOT;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
int My0ar;
My0ar 1 4;
/+ile!My0ar614"
{
My0ar77;
#ebug.Print!My0ar.ToString!"";
&
&
&
&
Last thing to add is that 3e 3ant to make the +rogram +rint
Co+*right @ $0!$ '2# ElectronicsA LLC ,age !=?(.
Beginners guide to C# and NETM (.C# Level !
CountE !
CountE $
...
...
CountE 0
CountE!0
This can "e easil* done "* adding strings. Strings are added using the M s*m"ol -ust like ho3
*ou 3ould add an* num"ers.
Tr* the >ollo3ing code
using System;
using Microsoft.SPOT;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
int My0ar;
My0ar 1 4;
/+ile!My0ar614"
{
My0ar77;
#ebug.Print!'Count8 ' 7 My0ar.ToString!"";
&
&
&
&
Assemblies
Assem"lies are >iles containing com+iled Cassem"ledD code. This allo3s develo+ers to use
the code "ut the* donBt have access to the assem"lies source code. 5e have alread* used
%e"ug.,rint. 5ho made the %e"ug class?o"-ect and 3ho made the ,rint method that is in it6
Those are made "* the NETM team at Microso>t. The* com+ile the code and give *ou an
assem"l* to use it. This 3a*A users are not messing 3ith the internal code "ut the* can still
use it.
At the to+ o> the code used "e>oreA 3e see using Microso>t.S,<TO
This tells C# that *ou 3ant to use the 7names+ace8 Microso>t.S,<T. <ka*A "ut 3hat is a
Co+*right @ $0!$ '2# ElectronicsA LLC ,age !.?(.
Beginners guide to C# and NETM (.C# Level !
names+ace6 ,rograms are s+lit into regions or 7s+aces8. This is ver* im+ortant 3hen
+rograms are ver* large. Ever* chunk o> code or li"rar* is assigned a 7name8 >or its 7s+ace8.
,rograms 3ith the same 7names+ace8 see each other "ut i> the name s+ace is di>>erent then
3e can o+tionall* tell C# to 7use8 the other name s+ace.
The 7name8 >or our +rogramBs 7s+ace8 is names+ace MConsoleA++lication!
To 7use8 another name s+ace like NMicros+>t.S,<TN *ou need to add using Microso>t.S,<TO
5hat is S,<T an*3a*s6 2ere is a short stor*4 A >e3 *ears agoA Microso>t +rivatel* started a
+ro-ect called S,<T. The* realiJed that this +ro-ect 3as a good idea and 3anted to o>>er it to
develo+ers. The* decided to change the +roduct name to .NET Micro rame3ork "ut the*
ke+t the code the same 3a* >or "ack3ards com+ati"ilit*. #n shortA S,<T is NETM4
Back to codingA no3 tr* to remove or comment out using Microso>t.S,<TO and *our code 3ill
not 3ork an*more.
2ere is the error message sho3n a>ter # commented out using Microso>t.S,<TO
5e used the assem"lies "ut 3here are the* added6
Hncomment the code and make sure it still 3orks. No3 take a look at the 7Solution E/+lorer8
3indo3. Click the little M sign "* the 3ord 71e>erences8 and *ou should see t3o assem"lies.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age !0?(.
Beginners guide to C# and NETM (.C# Level !
No3A right9click on 7Microso>t.S,<T.Native8 then click 71emove8
<ur +rogram 3ill still "e e/actl* the same as "e>oreA "ut no3 itBs missing a ver* im+ortant
assem"l*. Tr* to run it and *ou 3ill see something like this
Co+*right @ $0!$ '2# ElectronicsA LLC ,age $0?(.
Beginners guide to C# and NETM (.C# Level !
LetBs add it "ack and make sure our +rogram still runs. 1ight click on the 71e>erences8 >older
and select 7Add 1e>erence...8
#n the ne3 3indo3A select 7.NET8 ta" and then select 7Microso>t.S,<T.Native8 and click <I.
1un the +rogram to make sure itBs 3orking again. #> *ou have an* errorsA +lease go "ack and
re+eat the ste+s to >i/ it "e>ore moving on.
8hat Assemblies to Add9
Throughout this "ookA # +rovide man* e/am+les "ut # do not tell *ou 3hat assem"lies # am
using. This is reall* eas* to >igure out >rom the documentation "ut *ou ma* >ind it di>>icult
sometimes. 5h* not -ust add them all6 As a "eginnerA *our a++lications are still ver* small so
Co+*right @ $0!$ '2# ElectronicsA LLC ,age $!?(.
Beginners guide to C# and NETM (.C# Level !
*ou 3ill have a lot o> memor* even i> *ou add all o> the assem"liesA even i> *ou are not using
them.
The assem"lies "elo3 are most commonl* used. Add them >or all o> *our +ro-ects >or no3.
<nce *ou kno3 3here ever*thing "elongsA *ou can start removing the ones *ou donBt need.
These assem"lies do not include the ones needed >ro net3orking or gra+hics.
'2#Electronics.NETM.2ard3are
'2#Electronics.NETM.#<
'2#Electronics.NETM.S*stem
Microso>t.S,<T.2ard3are
Microso>t.S,<T.Native
Microso>t.S,<T.2ard3are.Serial,ort
Microso>t.S,<T.#<
mscorli"
S*stem
S*stem.#<
Threading
This can "e a ver* advanced to+ic. Note that onl* ver* "asic in>ormation is covered here.
,rocessors?+rograms onl* run one instruction at a time. 1emem"er ho3 3e ste++ed in the
code6 <nl* one instruction got e/ecuted and then the >lo3 3ent on to the ne/t instruction.
Then ho3 is it +ossi"le that *our ,C can run multi+le +rograms at the same time6 Actuall*A
*our ,C is never running them a once4 5hat it is doing is running ever* +rogram >or a short
timeA sto+s it and goes on to run the ne/t +rogram.
'enerall*A threading is not recommended >or "eginners "ut there are things that can "e done
much easier using threads. or e/am+leA *ou 3ant to "link an LE%. #t 3ould "e nice to "link
an LE% in a se+arate thread and never have to 3orr* a"out it in the main +rogram.
AlsoA adding dela*s in the code reGuire the threading names+ace. Fou 3ill understand this
"etter in u+coming e/am+les.
B* the 3a*A LE% stands >or Light Emitting %iodes. Fou see LE%s ever*3here around *ou.
Take a look at an* T:A %:% or electronic device and *ou 3ill see a little 1ed or other color
light "ul". These are LE%s.
Add 7using S*stem.Threading8 to *our +rogram.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age $$?(.
Beginners guide to C# and NETM (.C# Level !
That is all 3e need to use threads4 #t is im+ortant to kno3 that our +rogram itsel> is a thread.
<n s*stem e/ecution start9u+A C# 3ill look >or 7Main8 and run it in a thread. 5e 3ant to add a
dela* in our thread Cour +rogramDA so it 3ill +rint the 3ord BAmaJing4B once ever* second. To
dela* a 7thread8A 3e +ut it to 7Slee+8. Note that this 7Slee+8 is not >or the 3hole s*stem. #t 3ill
onl* 7Slee+8 the 7thread8.
AddE
Thread.Slee+C!000DO
To our 5hile9loo+.
The 7Slee+8 method takes time in milliseconds. SoA >or ! second 3e 3ill need !000
milliseconds.
using System;
using Microsoft.SPOT;
using System.T+reaing;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
/+ile !true"
{
#ebug.Print!'Ama(ing)'";
T+rea.Sleep!1444";
&
&
&
&
Tr* to run the +rogram and look at the out+ut 3indo3. #> *ouBve tried it on the emulator and it
3asnBt e/actl* ! secondA donBt 3orr* a"out it. Tr* it on real hard3are CELD and it 3ill "e ver*
close to ! second.
LetBs create a second thread Cour >irst 3as automaticall* createdA remem"er6D 5e 3ill need to
create a ne3 thread o"-ect handler Cre>erenceD and name it something use>ulA like
M*Thread2andler. And create a ne3 local method and name it M*Thread. ThenA run the ne3
thread.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age $3?(.
Beginners guide to C# and NETM (.C# Level !
5e are not using the 7Main8 thread an*more so # 3ill +ut it in an endless slee+.
2ere is the code listing. #> *ou donBt understand it then donBt 3orr* a"out it. All that is needed
at this +oint is that *ou kno3 ho3 to 7Slee+8 a thread.
using System;
using Microsoft.SPOT;
using System.T+reaing;
namespace MFConsoleApplication1
{
public class Program
{
public static voi MyT+rea!"
{
/+ile !true"
{
#ebug.Print!'Ama(ing)'";
**sleep t+is t+rea for 1 secon
T+rea.Sleep!1444";
&
&
public static voi Main!"
{
** create a t+rea +anler
T+rea MyT+rea9anler;
** create a ne/ t+rea ob:ect
**an assign to my +anler
MyT+rea9anler 1 ne/ T+rea!MyT+rea";
** start my ne/ t+rea
MyT+rea9anler.Start!";
*********************************
** #o anyt+ing else you li.e to o +ere
T+rea.Sleep!Timeout.;nfinite";
&
&
&

Co+*right @ $0!$ '2# ElectronicsA LLC ,age $&?(.
Beginners guide to C# and NETM ).%igital #n+ut ; <ut+ut
<. Digital In)ut = >ut)ut
<n +rocessorsA there are man* 7digital8 +ins that can "e used as in+uts or out+uts. "* 7digital8
+ins 3e mean the +in can "e 7one8 or 7Jero8.
Im)ortant note* Static discharge >rom an*thing including the human "od* 3ill damage the
+rocessor. Fou kno3 ho3 sometimes *ou touch someone or something and *ou >eel a little
electronic discharge6 This little discharge is high enough to kill electronic circuits.
,ro>essionals use eGui+ment and take +recautions handling the static charges in their "od*.
Fou ma* not have such eGui+ment so -ust tr* to sta* a3a* >rom touching the circuit i> *ou
donBt have to. Fou ma* also use an Anti9static 3rist "and.
NETM su++orts digital in+ut and out+ut +ins through the 7Microso>t.S,<T.2ard3are8
assem"l* and name s+ace.
'o ahead and add the assem"l* and names+ace like 3e learned "e>ore.
5e are no3 read* to use the digital +ins.
<.1. Digital >ut)uts
5e kno3 that a digital out+ut +in can "e set to Jero or one. Note that one doesnBt mean it is !
volt "ut it means that the +in is su++l*ing voltage. #> the +rocessor is +o3ered o>> o> 3.3: then
state ! on a +in means that there is 3.3: on the out+ut +in. #t is not going to "e e/actl* 3.3:
"ut ver* close. 5hen the +in is set to Jero then itBs voltage is ver* close to Jero volts.
Those digital +ins are ver* 3eak4 The* canBt "e used to drive devices that reGuire a lot o>
+o3er. or e/am+leA a motor ma* run on 3.3: "ut *ou can N<T connect it directl* to the
+rocessorBs digital +in. That is "ecause the +rocessorBs out+ut is 3.3: "ut 3ith ver* little
+o3er. The "est *ou can do is drive a small LE% or 7signal8 ! or 0 to another in+ut +in.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age $(?(.
Beginners guide to C# and NETM ).%igital #n+ut ; <ut+ut
All EL "oards have a LE% connected to a digital +in. 5e 3ant to "link this led.
%igital out+ut +ins are controlled through an <ut+ut,ort o"-ect. 5e >irst create the o"-ect
handler Cre>erenceDA and then 3e make a ne3 <ut+ut,ort o"-ect and assign it to our handler.
5hen creating a ne3 <ut+ut,ort o"-ectA *ou must s+eci>* the initial state o> the +inA ! or 0.
The one and Jero can "e re>erred to high or lo3 and also can "e true for high and false for
lo$. 5e 3ill make the +in true ChighD in this e/am+le to turn on our LE% "* de>ault.
2ere is the code using +in num"er &A the EL %omino on9"oard LE%.
using System;
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
OutputPort <=#;
<=# 1 ne/ OutputPort!!Cpu.Pin">? true";
T+rea.Sleep!Timeout.;nfinite";
&
&
&
The '2# S%I shi+s 3ith s+ecial assem"lies containing the +in ma++ing o> *our device. or
e/am+leA 7ELMiniR'2#Electronics.NETM.EL8 is needed >or EL Mini.
No3A modi>* the code "* adding 7using '2#Electronics.NETM.EL8 at the to+ o> *our
+rogram. Four device ma* have a di>>erent %LL.
2ere is the codeA this time using the EL +in enumeration class.
using System;
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
using %9;=lectronics.@=TMF.F=A;
namespace MFConsoleApplication1
{
public class Program
{
Co+*right @ $0!$ '2# ElectronicsA LLC ,age $)?(.
Beginners guide to C# and NETM ).%igital #n+ut ; <ut+ut
public static voi Main!"
{
OutputPort <=#;
<=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
T+rea.Sleep!Timeout.;nfinite";
&
&
&
See ho3 much easier that is6 5e reall* do not need to kno3 3here the LE% is connected.
1un the +rogram and o"serve the LE%. #t should "e lit no3. Things are getting more e/citing4
Blink an 7!D
To "link an LE%A 3e need to set the +in high and dela* >or some time then 3e need to set it
lo3 and dela* gain. #ts im+ortant to remem"er to dela* t3ice. 5h*6 #tBs "ecause our e*es are
too slo3 >or com+uter s*stems. #> the LE% comes on and then it turns "ack o>> ver* >astA *our
e*es 3ill not see that it 3as o>> >or a ver* short time.
5hat do 3e need to "link a LE%6 ... 5e learned ho3 to make a 3hile9loo+A 3e kno3 ho3 to
dela*A and 3e need to kno3 ho3 to set the +in high or lo3. This is done "* calling the 5rite
method on the <ut+ut,ort o"-ect. Note that *ou canBt use 7<ut+ut,ort.5rite8 This is ver*
3rong "ecause 3hat out+ut +orts are *ou re>erring to6 #nsteadA use 7LE%.5rite8 3hich makes
com+lete sense.
2ere is the code to "link the on9"oard LE% on EL %omino?Mini
using System;
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
using %9;=lectronics.@=TMF.F=A;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
OutputPort <=#;
<=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
/+ile !true"
{
<=#.Crite!)<=#.$ea!"";
T+rea.Sleep!D44";
Co+*right @ $0!$ '2# ElectronicsA LLC ,age $=?(.
Beginners guide to C# and NETM ).%igital #n+ut ; <ut+ut
&
&
&
&
This is another 3a*A a sim+ler 3a*A to "link a LE%.
using System;
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
using %9;=lectronics.@=TMF.F=A;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
OutputPort <=#;
<=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
/+ile !true"
{
<=#.Crite!true";
T+rea.Sleep!D44";
<=#.Crite!false";
T+rea.Sleep!D44";
&
&
&
&
LetBs see i> *ou can change the slee+ time to make the LE% "link >aster or slo3er. AlsoA tr*
to use a di>>erent value >or its state so it is on >or a long time and then it is o>> >or a short
time.
Im)ortant note* Never connect t3o out+ut +ins together. #> the* are connected and one is
set to high and the other is set to lo3A *ou 3ill damage the +rocessor. Al3a*s connect an
out+ut +in to an in+utA driving circuit or a sim+le load like a LE%.
<.2. Digital In)uts
%igital in+uts sense i> the state o> its +in is high or lo3. There is a limitation on these in+ut
+ins. or e/am+leA the minimum voltage on the +in is 0 volts. A negative voltage ma* damage
the +in or the +rocessor. AlsoA the ma/imum *ou can su++l* to a +inA must "e less than the
Co+*right @ $0!$ '2# ElectronicsA LLC ,age $.?(.
Beginners guide to C# and NETM ).%igital #n+ut ; <ut+ut
+rocessorBs +o3er source voltage. All '2# Electronics "oards use +rocessors that run on 3.3:
so the highest voltage the +in should ever see is 3.3:. This is true >or Chi+3orkS and EL
2*dra "ut not >or EMS. EMS is (:9tolerant. This means that even though the +rocessor runs
on 3.3:A it is ca+a"le o> tolerating u+ to (: on its in+uts. Most digital chi+s that *ou 3ould "e
inter>acing 3ith are (:. Being (: tolerant allo3s us to use an* o> those digital circuits 3ith our
+rocessor.
Im)ortant note* (:9tolerant doesnBt mean the +rocessor can "e +o3ered o>> o> (:. Al3a*s
+o3er it 3ith 3.3:. <nl* the in+ut +ins can tolerate (: on them.
The #n+ut,ort o"-ect is used to handle digital in+ut +ins. An* +in on the +rocessorBs '2# use
can "e an in+ut or an out+utA "ut o> courseA not "oth4 Hnconnected in+ut +ins are called
>loating. Fou 3ould think that unconnected in+ut +ins are lo3 "ut this is not true. 5hen a +in
is an in+ut and is not connectedA it is o+en >or an* surrounding noise 3hich can make the +in
high or lo3. To take care o> this issueA modern +rocessors include an internal 3eak +ull9do3n
or +ull9u+ resistorA that are usuall* controlled "* so>t3are. Ena"ling the +ull9u+ resistor 3ill +ull
the +in high. Note that the +ull9u+ resistor doesnBt make a +in high "ut it +ulls it high. #> nothing
is connected then the +in is high "* de>ault.
There are man* uses >or in+ut +orts "ut the most common is to connect it to a "utton or a
s3itch. Man* EL "oards alread* includes an on9"oard "utton connected to the loader +in.
The loader +in is used on +o3er u+ to enter the "oot loader "ut 3e can still use this +in at
run9time. The "utton is enumerated as 7L%18 or 7Loader8.
The "utton 3ill connect "et3een ground and the in+ut +in. 5e 3ill also ena"le the +ull9u+
resistor. This means that the +in 3ill "e high C+ull9u+D 3hen the "utton is not +ressed and lo3
Cconnected to groundD 3hen the "utton is +ressed.
5e 3ill read the status o> the "utton and +ass its state to the LE%. Note that the +in is high
3hen the "utton is not +ressed C+ulled9highD and it is lo3 3hen the "utton is +ressed. This
means the LE% 3ill turn o>> 3hen the "utton is +ressed.
The codeE
using System;
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
using %9;=lectronics.@=TMF.F=A;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
OutputPort <=#;
;nputPort Eutton;
<=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
Eutton 1 ne/ ;nputPort!!Cpu.Pin"F=ABPin.#igital.<#$? false?
Co+*right @ $0!$ '2# ElectronicsA LLC ,age $0?(.
Beginners guide to C# and NETM ).%igital #n+ut ; <ut+ut
Port.$esistorMoe.PullFp";
/+ile !true"
{
<=#.Crite!Eutton.$ea!"";
T+rea.Sleep!14";
&
&
&
&
<.%. Interru)t /ort
#> 3e 3ant to check the status o> a +inA 3e 3ill al3a*s have to check its state +eriodicall*. This
3astes the +rocessorBs time on something not im+ortant. Fou 3ill "e checking the +inA ma*"eA
a million times "e>ore it is +ressed4 #nterru+t +orts allo3s us to set a method that 3ill "e
e/ecuted 3hen the "utton is +ressed C3hen +in is lo3 >or e/am+leD.
5e can set the interru+t to >ire on man* state changes on the +inA 3hen the +in is lo3 or
ma*"e 3hen it is high. The most common use is the 7on change8. The change >rom lo3 to
high or high to lo3 creates a signal edge. The high edge occurs 3hen the signal rises >rom
lo3 to high. The lo3 edge ha++en 3hen the signal >alls >rom high to lo3.
#n the e/am+le "elo3A # am using "oth edges so our method 7#ntButtonR<n#nterru+t8 3ill
automaticall* run 3henever the state o> our +in changes.
using System;
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
using %9;=lectronics.@=TMF.F=A;
namespace MFConsoleApplication1
{
public class Program
{
** t+is move out +ere so it can be use by ot+er met+os
static OutputPort <=#;

public static voi Main!"
{
<=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
** t+e pin /ill generate interrupt on +ig+ an lo/ eges
;nterruptPort ;ntEutton 1
ne/ ;nterruptPort!!Cpu.Pin"F=ABPin.;nterrupt.<#$? true?
Port.$esistorMoe.PullFp?
Port.;nterruptMoe.;nterrupt=geEot+";
** a an interrupt +anler to t+e pin
;ntEutton.On;nterrupt 71
Co+*right @ $0!$ '2# ElectronicsA LLC ,age 30?(.
Beginners guide to C# and NETM ).%igital #n+ut ; <ut+ut
ne/ @ative=vent9anler!;ntEuttonBOn;nterrupt";
**o anyt+ing you li.e +ere
T+rea.Sleep!Timeout.;nfinite";
&
static voi ;ntEuttonBOn;nterrupt!uint port? uint state?
#ateTime time"
{
** set <=# to t+e s/itc+ state
<=#.Crite!state 11 4";
&
&
&
NoteE Most "ut not all +ins on the +rocessor su++ort interru+ts.
<.'. Tristate /ort
#> 3e 3ant a +in to "e an in+ut and out+utA 3hat can 3e do6 A +in can never "e in and out
simultaneousl* "ut 3e can make it out+ut to set something and then make it in+ut to read a
res+onse "ack. <ne 3a* is to 7%is+ose8 the +in. 5e make an out+ut +ortA use it and then
dis+ose it. Then 3e can make the +in an in+ut and read it.
NETM su++orts "etter o+tions >or thisA through a Tristate +ort. Tristate means three statesO
that is in+utA out+ut lo3 and out+ut high. <ne minor issue a"out tristate +ins isO i> a +in is set
to out+ut and then *ou set it to out+ut againA 3e 3ill receive an e/ce+tion. <ne 3a* to get
around this is "* checking the direction o> the +in "e>ore changing it. The direction o> the +in
is its 7Active8 +ro+ert* 3here >alse means in+ut and true is out+ut. # +ersonall* do not
recommend the use o> Tristate +orts unless a"solutel* necessar*.
using System;
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
using %9;=lectronics.@=TMF.F=A;
namespace MFConsoleApplication1
{
public class Program
{
static voi Ma.ePinOutput!TristatePort port"
{
if !port.Active 11 false"
port.Active 1 true;
&
static voi Ma.ePin;nput!TristatePort port"
{
Co+*right @ $0!$ '2# ElectronicsA LLC ,age 3!?(.
Beginners guide to C# and NETM ).%igital #n+ut ; <ut+ut
if !port.Active 11 true"
port.Active 1 false;
&
public static voi Main!"
{
TristatePort TriPin 1
ne/ TristatePort!!Cpu.Pin"F=ABPin.;nterrupt.<#$? false?
false? Port.$esistorMoe.PullFp";
Ma.ePinOutput!TriPin";** ma.e pin output
TriPin.Crite!true";
Ma.ePin;nput!TriPin";** ma.e pin input
#ebug.Print!TriPin.$ea!".ToString!"";
&
&
&
NoteE %ue to internal designA Tristate,ort 3ill onl* 3ork 3ith interru+t ca+a"le digital +ins.
#m+ortant NoteE Be care>ul not to have the +in connected to a s3itch and then set the +in to
out+ut and high. This 3ill damage the +rocessor. # 3ould sa*A >or "eginner a++lications *ou do
not need a tristate +ort so do not use it until *ou are com>orta"le 3ith digital circuits.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age 3$?(.
Beginners guide to C# and NETM =.C# Level $
?. C, 7evel 2
?.1. Boolean +ariables
5e learned ho3 integer varia"les hold num"ers. #n contrastA Boolean varia"les can onl* "e
true or >alse. A light can onl* "e on or o>>A re+resenting this using an integer doesnBt make a
lot o> sense "ut using BooleanA it is true >or on9state and >alse >or o>>9state. 5e have alread*
used those varia"les to set digital +ins high and lo3A LE%.5riteCtrueDO
To store the value o> a "utton in a varia"le 3e use
bool buttonBstate;
buttonBstate 1 Eutton.$ea!";
5e also used 3hile9loo+s and 3e asked it to loo+ >oreverA 3hen 3e used true >or the
statement
/+ile !true"
{
**coe +ere
&
Take the last code 3e did and modi>* it to use a "ooleanA so it is easier to read. #nstead o>
+assing the Button state directl* to the LE% stateA 3e read the "utton state into "uttonRstate
"oolean then 3e +ass the "uttonRstate to set the LE% accordingl*.
using System;
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
using %9;=lectronics.@=TMF.F=A;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
OutputPort <=#;
;nputPort Eutton;
bool buttonBstate;
<=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
Co+*right @ $0!$ '2# ElectronicsA LLC ,age 33?(.
Beginners guide to C# and NETM =.C# Level $
Eutton 1 ne/ ;nputPort!!Cpu.Pin"F=ABPin.#igital.<#$? false?
Port.$esistorMoe.PullFp";
/+ile !true"
{
buttonBstate 1 Eutton.$ea!";
<=#.Crite!buttonBstate";
T+rea.Sleep!14";
&
&
&
&
Can *ou make an LE% "link as long as the "utton is +ressed6
using System;
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
using %9;=lectronics.@=TMF.F=A;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
OutputPort <=#;
;nputPort Eutton;

<=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
Eutton 1 ne/ ;nputPort!!Cpu.Pin"F=ABPin.#igital.<#$? false?
Port.$esistorMoe.PullFp";
/+ile !true"
{
/+ile !Eutton.$ea!" 11 false"**Eutton is false /+en presse
{
<=#.Crite!true";
T+rea.Sleep!244";
<=#.Crite!false";
T+rea.Sleep!244";
&
&
&
&
&
Im)ortant note* The QQ is used to check >or eGalit* in C#. This is di>>erent >rom Q 3hich is
used to assign values.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age 3&?(.
Beginners guide to C# and NETM =.C# Level $
?.2. if1statement
An im+ortant +art o> +rogramming is checking some state and taking action accordingl*. or
e/am+leA 7i>8 the tem+erature is over .0A turn on the >an.
To tr* the i>9statement 3ith our sim+le setu+A 3e 3ant to turn on the LE% 7i>8 the "utton is
+ressed. Note this is the o++osite >rom 3hat 3e had "e>ore since in our setu+A the "utton is
lo3 3hen it is +ressed. SoA to achieve this 3e 3ant to invert the state o> the LE% >rom the
state o> the "utton. #> the "utton is +ressed Clo3D then 3e 3ant to turn the LE% on ChighD. The
LE% needs to "e checked re+eatedl* so 3e 3ill do it once ever* !0ms.
using System;
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
using %9;=lectronics.@=TMF.F=A;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
OutputPort <=#;
;nputPort Eutton;
bool buttonBstate;
<=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
Eutton 1 ne/ ;nputPort!!Cpu.Pin"F=ABPin.#igital.<#$? false?
Port.$esistorMoe.PullFp";
/+ile !true"
{
buttonBstate 1 Eutton.$ea!";
if !buttonBstate 11 true"
{
<=#.Crite!false";
&
if !buttonBstate 11 false"
{
<=#.Crite!true";
&
T+rea.Sleep!14";
&
&
&
&
Co+*right @ $0!$ '2# ElectronicsA LLC ,age 3(?(.
Beginners guide to C# and NETM =.C# Level $
?.%. if1else1statements
5e learned ho3 i>9statements 3ork. No3A 3e 3ant to use the else9statement. Basicall*A 7i>8 a
statement is trueA the code inside the i>9statement runs or 7else8 the code inside the else9
statement 3ill run. 5ith this ne3 statementA 3e can o+timiJe the code a"ove to "e like this
using System;
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
using %9;=lectronics.@=TMF.F=A;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
OutputPort <=#;
;nputPort Eutton;
bool buttonBstate;
<=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
Eutton 1 ne/ ;nputPort!!Cpu.Pin"F=ABPin.#igital.<#$? false?
Port.$esistorMoe.PullFp";
/+ile !true"
{
buttonBstate 1 Eutton.$ea!";
if !buttonBstate 11 true"
{
<=#.Crite!false";
&
else
{
<=#.Crite!true";
&
T+rea.Sleep!14";
&
&
&
&
# 3ill let *ou in on a secret4 5e onl* used the i>9statement and the else9statement in this
e/am+le as a demonstration +ur+ose. 5e can 3rite the code this 3a*.
using System;
Co+*right @ $0!$ '2# ElectronicsA LLC ,age 3)?(.
Beginners guide to C# and NETM =.C# Level $
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
using %9;=lectronics.@=TMF.F=A;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
OutputPort <=#;
;nputPort Eutton;

<=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
Eutton 1 ne/ ;nputPort!!Cpu.Pin"F=ABPin.#igital.<#$? false?
Port.$esistorMoe.PullFp";
/+ile !true"
{
<=#.Crite!Eutton.$ea!" 11 false";
T+rea.Sleep!14";
&
&
&
&
<r even this 3a*4
using System;
using Microsoft.SPOT;
using System.T+reaing;
using Microsoft.SPOT.9ar/are;
using %9;=lectronics.@=TMF.F=A;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
OutputPort <=#;
;nputPort Eutton;

<=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
Eutton 1 ne/ ;nputPort!!Cpu.Pin"F=ABPin.#igital.<#$? false?
Port.$esistorMoe.PullFp";
/+ile !true"
{
<=#.Crite!)Eutton.$ea!"";
T+rea.Sleep!14";
&
Co+*right @ $0!$ '2# ElectronicsA LLC ,age 3=?(.
Beginners guide to C# and NETM =.C# Level $
&
&
&
Hsuall*A there are man* 3a* to 3rite the code. Hse 3hat makes *ou com>orta"le and 3ith
more e/+erienceA *ou 3ill learn ho3 to o+timiJe the code.
?.'. "ethods and Arguments
Methods are actions taken "* an o"-ect. #t can also "e called a >unction o> an o"-ect. 5e have
alread* seen methods and have used them. %o *ou remem"er the o"-ect %e"ug 3hich has a
,rint method6 5e have alread* used %e"ug.,rint man* times "e>oreA 3here 3e gave it a
7string8 to dis+la* in the out+ut 3indo3. The 7string8 3e +assed is called an argument.
Methods can take one or more o+tional arguments "ut it can onl* return one o+tional value.
The ,rint method in the %e"ug o"-ect onl* takes one string argument. <ther methods ma* not
reGuire an* arguments or ma* reGuire more than one argument. or e/am+leA a method to
dra3 a circle can take >our argumentsA %ra3CircleC+os/A +os*A diamA colorD. An e/am+le >or
returning values can "e a method that returns the tem+erature.
So >arA 3e have learned o> three varia"le t*+esA intA string and "ool. 5e 3ill cover other t*+es
later "ut remem"er that ever*thing 3e talk a"out here a++lies to other varia"le t*+es.
The returned value can "e an o+tional varia"le t*+e. #> there is no returned value then 3e
re+lace the varia"le t*+e 3ith 7void8. The 7return8 ke*3ord is used to return values at the end
o> a method.
2ere is a ver* sim+le method that 7returns8 the sum o> t3o integers.
int A!int var1? int varD"
{
int var2;
var2 1 var1 7 varD;
return var2;
&
5e started the method 3ith the return value t*+eA 7int8 >ollo3ed "* the method name. Then
3e have the argument list. Arguments are al3a*s grou+ed "* +arenthesis and se+arated "*
commas.
#nside the Add methodA a local integer varia"le has "een declaredA var3. Local varia"les are
created inside a method and die once 3e e/it the method. No3A 3e add our t3o varia"les and
>inall* return the result.
5hat i> 3e 3ant to return a string re+resenting the sum o> t3o num"ers6 1emem"er that a
Co+*right @ $0!$ '2# ElectronicsA LLC ,age 3.?(.
Beginners guide to C# and NETM =.C# Level $
string containing the num"er !$3 is not the same as an integer containing !$3. An integer is a
num"er "ut a string is an arra* or characters that re+resent te/t or num"ers. To humans
these are the same thingA "ut in the com+uter 3orldA this is totall* di>>erent.
2ere is the code to return a string.
string A!int var1? int varD"
{
int var2;
var2 1 var1 7 varD;

string MyString;
MyString 1 var2.ToString!";

return MyString;
&
Fou can see ho3 the returned t*+e 3as changed to a string. 5e couldnBt return var3 "ecause
it is an integer varia"leA so 3e had to convert it to a string. To do thatA 3e create a ne3
varia"le o"-ect named M*String. Then convert var3 NToStringN and +lace the ne3 string in
M*String.
The Guestion no3 is 3h* 3e called a NToStringN method on a varia"le o> t*+e integer6 #n
realit*A ever*thing in C# is an o"-ectA even the "uilt in varia"le t*+es. This "ook is not going
into these details as it is onl* meant to get *ou started.
This is all done in multi+le ste+s to sho3 *ou ho3 it is done "ut 3e can com+act ever*thing
and results 3ill "e e/actl* the same.
string A!int var1? int varD"
{
return !var17varD".ToString!";
&
# recommend *ou do not 3rite code that is e/tremel* com+actA like the e/am+le a"oveA until
*ou are ver* >amiliar 3ith the +rogramming language. Even thenA there should "e limits on
ho3 much *ou com+act the code. Fou still 3ant to "e a"le to maintain the code a>ter
sometime and someone else ma* need to read and understand *our code.
?.6. Classes
All o"-ects 3e talked a"out so >ar are actuall* 7classes8 in C#. #n modern o"-ect oriented
+rogramming languagesA ever*thing is an o"-ect and methods al3a*s "elong to one o"-ect.
This allo3s >or having methods o> the same name "ut the* can "e >or com+letel* di>>erent
Co+*right @ $0!$ '2# ElectronicsA LLC ,age 30?(.
Beginners guide to C# and NETM =.C# Level $
o"-ects. A 7human8 can 73alk8 and a 7cat8 can also 73alk8 "ut do the* 3alk the same 3a*6
5hen *ou call the 73alk8 method in C# it is not clear i> the cat or the human 3ill 3alk "ut using
human.3alk or cat.3alk makes it more clear.
Creating classes is "e*ond the sco+e o> this "ook. 2ere is a ver* sim+le class to get *ou
started
class MyClass
{
int A!int a? int b"
{
return a 7 b;
&
&
?.<. /ublic vs. /rivate
Methods can "e +rivate to a class or +u"licl* accessi"le. This is onl* use>ul to make the
o"-ects more ro"ust >rom +rogrammer misuse. #> *ou create an o"-ect CclassD and this o"-ect
has methods that *ou do not 3ant an*one to use e/ternall* then add the ke*3ord 7+rivate8
"e>ore the method return t*+eO other3iseA add the 7+u"lic8 ke*3ord.
2ere is a Guick e/am+le
class MyClass
{
public int A!int a? int b"
{
** t+e ob:ect can use private met+os
** insie t+e class only
#oSomet+ing!";
return a 7 b;
&
private voi #oSomet+ing!"
{
&
&
?.?. (tatic vs. non1static
Some o"-ects in li>e have multi+le instances "ut others onl* e/ist once. The o"-ects 3ith
multi+le instances are non9static. or e/am+leA an o"-ect re+resenting a human doesnBt mean
Co+*right @ $0!$ '2# ElectronicsA LLC ,age &0?(.
Beginners guide to C# and NETM =.C# Level $
much. Fou 3ill need an 7instance8 o> this o"-ect to re+resent one human. So this 3ill "e
something like
human MikeO
5e no3 have a 7re>erence8 called Mike o> t*+e human. #t is im+ortant to note this re>erence at
this +oint is not re>erencing an* o"-ect Cno instance assignedD -ust *etA so it is re>erencing
NHLL.
To create the 7ne38 o"-ect instance and re>erence it >rom Mike
Mike Q ne3 humanCDO
5e no3 can use an* o> the human methods on our 7instance8 o> Mike
Mike.1unCdistanceDO
Mike.EatCDO
"ool hungr* Q Mike.#s2ungr*CDO
5e have used those non9static methods alread* 3hen 3e controlled in+ut and out+ut +ins.
5hen creating a ne3 non9static o"-ectA the 7ne38 ke*3ord is used 3ith the 7constructor8 o> the
o"-ect. The constructor is a s+ecial t*+e o> method that returns no value and is onl* used
3hen creating CconstructionD ne3 o"-ects.
Static methods are easier to handle "ecause there is onl* one o"-ect that is used directl*
3ithout creating instances. The easiest e/am+le is our %e"ug o"-ect. There is onl* one de"ug
o"-ect in the NETM s*stem so using its methodsA like ,rintA is used directl*.
%e"ug.,rintC7string8DO
# ma* not have used the e/act de>initions o> static and instances "ut # 3anted to descri"e it in
the sim+lest 3a*.
?.@. Constants
Some varia"les ma* have >i/ed values that never change. 5hat i> *ou accidentall* change
the value o> this varia"le in *our code6 To +rotect it >rom changingA add the 7const8 ke*3ord
"e>ore the varia"le declaration.
const int +oursBinBoneBay 1 D>;
?.A. !numeration
An Enumeration is ver* similar to a constant. LetBs sa* 3e have a device that acce+ts >our
Co+*right @ $0!$ '2# ElectronicsA LLC ,age &!?(.
Beginners guide to C# and NETM =.C# Level $
commandsA those are M<:EA ST<,A LETA 1#'2T. This device is not a humanA so these
commands are actuall* num"ers. 5e can create constants Cvaria"lesD >or those >our
commands like the >ollo3ingE
const int MO0= 1 1;
const int STOP 1 D;
const int $;%9T 1 2;
const int <=FT 1 >;
**no/ /e can sen a comman...
SenComman!MO0=";
SenComman!STOP";
The names are all u++er case "ecause this is ho3 +rogrammers usuall* name constants. An*
other +rogrammer seeing an u++er case varia"le 3ould kno3 that this is a constant.
The code a"ove is oka* and 3ill 3ork "ut it 3ill "e nicer i> 3e can grou+ those commands
enum Comman
{
MO0= 1 1?
STOP 1 D?
$;%9T 1 2?
<=FT 1 >?
&
**no/ /e can sen a comman...
SenComman!Comman.<=FT";
SenComman!Comman.STOP";
5ith this ne3 a++roachA there is no need to remem"er 3hat commands e/ist and 3hat the
command num"ers are. <nce the 3ord 7Command8 is t*+ed inA :isual Studio 3ill give *ou a
list o> availa"le commands.
C# is also smart enough to increment the num"ers >or enumerations so the code can "e like
this listing and 3ill 3ork e/actl* the same 3a*
enum Comman
{
MO0= 1 1?
STOP ?
$;%9T?
<=FT ?
&
**no/ /e can sen a comman...
SenComman!Comman.<=FT";
Co+*right @ $0!$ '2# ElectronicsA LLC ,age &$?(.
Beginners guide to C# and NETM =.C# Level $
SenComman!Comman.STOP";
Co+*right @ $0!$ '2# ElectronicsA LLC ,age &3?(.
Beginners guide to C# and NETM ..Assem"l*?irm3are Matching
@. AssemblyB#irm$are "atching
NETM devices usuall* include e/tended >eatures. Those e/tended >eatures reGuire an e/tra
assem"l*?li"rar* to "e added to the C# +ro-ects so a user can make use o> the ne3 >eatures.
or e/am+leA NETM doesnBt su++ort Analog +ins "ut devices >rom '2# does su++ort analog
+ins. To use the analog +insA *ou need to add an assem"l*?li"rar* +rovided "* '2# then *ou
have ne3 classes?o"-ects that can "e used to access those ne3 >eatures.
The firm$are $ill fail to run if the version of the assemblyBlibrary that used in the
)ro0ect does not match the version of the firm$are.
This is a ver* common issue that users run into 3hen u+dating the >irm3are 3here the
a++lication -ust sto+s 3orking and de"ugging seems to >ail. Fou ma* see 7checksum
mismatch8 in the out+ut 3indo3.
2ere is 3hat ha++ensE
Scenario #!E A develo+er has received a ne3 device. This device ha++ens to have >irm3are
version !.0 on it. Then the develo+er 3ent to the 3e"site and do3nloaded the latest S%I.
The S%I has >irm3are version !.! in it. 5hen tr*ing to u+load a +ro-ectA :S$0!0 3ill >ail to
attach to the device 3ith no indication 3h*4 The develo+er 3ill no3 think the ne3 device is not
>unctioningA "ut actuall*A the device is -ust >ine. #n this e/am+leA the >irm3are is version !.0
and the assem"l* is version !.! so the s*stem 3ill re>use to run. To >i/ the issueA u+date the
>irm3are on the device to match the >irm3are in the S%I.
Scenario #$E A develo+er has a +er>ectl* 3orking s*stem thatA >or e/am+leA uses >irm3are
version $.!. Then a ne3 S%I comes out 3ith >irm3are version $.$A so the develo+er installs
the ne3 S%I on the ,C then u+loads the ne3 >irm3are to the device CELD. 5hen re"ooting
the deviceA it sto+s 3orking "ecause the ne3 loaded >irm3are is version $.$ "ut the user
a++lication is still using assem"l* version $.!. To fi- this issue, o)en the )ro0ect that has
the user a))lication and remove any device1s)ecific assemblies. After they are
removed, go back and add them back. 8ith this move the ne$ files $ill be fetched from
the ne$ (DC.
Boot1u) "essages
5e can easil* see 3h* the s*stem is not running using M%e+lo*. NETM out+uts man*
use>ul messages on +o3er u+. Should the s*stem "ecome unres+onsiveA >ails to run or >or
an* other de"ug +ur+osesA 3e can use M%e+lo* to dis+la* these "oot u+ messages. AlsoA
all 7%e"ug.,rint8 messages that 3e usuall* see on the out+ut 3indo3 are visi"le on
M%e+lo*.
To dis+la* the "oot u+ messagesA click on 7Target9KConnect8 >rom the menu then reset the
device. 1ight a>ter *ou reset the device in one secondA click on :)ing;. M%e+lo* 3ill >reeJe
>or a second then dis+la* a long list o> messages.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age &&?(.
Beginners guide to C# and NETM ..Assem"l*?irm3are Matching
Co+*right @ $0!$ '2# ElectronicsA LLC ,age &(?(.
Beginners guide to C# and NETM 0.'ar"age Collector
A. &arbage Collector
5hen +rogramming in older languages like C or CMMA +rogrammers had to kee+ track o>
o"-ects and release them 3hen necessar*. #> an o"-ect is created and not released then this
o"-ect is using resources >rom the s*stem that 3ill never "e >reed. The most common
s*m+tom is memor* leaks. A +rogram that is leaking memor* 3ill contentiousl* use more
memor* till the s*stem runs out o> memor* and +ro"a"l* crashes. Those "ugs are usuall*
ver* di>>icult to >ind in code.
Modern languages have gar"age collectorBs that kee+s track o> used o"-ects. 5hen the
s*stem runs lo3 on memor* resourcesA the gar"age collector -um+s in and searches through
all o"-ects and >rees the ones 3ith no 7re>erences8. %o *ou remem"er ho3 3e created o"-ects
"e>ore using the 7ne38 ke*3ord and then 3e assigned the o"-ect to a 7re>erence86 An o"-ect
can have multi+le re>erences and the gar"age collector 3ill not remove the o"-ect till it has
Jero re>erences.
** ne/ ob:ect
OutputPort $ef1 1 ne/ OutputPort!F=ABPin.#igital.<=#? true";
** secon reference for same ob:ect
OutputPort $efD 1 $ef1;
** lose t+e first reference
$ef1 1 null;
** Our ob:ect is still reference
** it /ill not be remove yet
** no/ remove t+e secon reference
$efD 1 null;
** from t+is point on? t+e ob:ect is reay to be
** remove by t+e garbage collector
Note that the o"-ect is not removed immediatel*. 5hen neededA the 'ar"age collector 3ill run
and remove the o"-ect. This can "e an issue in some rare cases "ecause the gar"age
collector needs some time to search and remove o"-ects. #t 3ill onl* "e >e3 milliseconds "ut
3hat i> *our a++lication canBt a>>ord that6 #> soA the gar"age collector can "e >orced to run at a
desired an*time.
**force t+e garbage collector
#ebug.%C!true";
Co+*right @ $0!$ '2# ElectronicsA LLC ,age &)?(.
Beginners guide to C# and NETM 0.'ar"age Collector
A.1. 7osing 3esources
The gar"age collector easeBs o"-ect allocation "ut it can also cause +ro"lems i> 3e are not
care>ul. A good e/am+le 3ould "e on using digital out+ut +ins. Lets sa* 3e need a +in to "e
high. 5e create an <ut+ut,ort o"-ect and set the +in high. Later on 3e lose the 7re>erence8
>or that o"-ect >or some reason. The +in 3ill still "e high 3hen the re>erence is lost so all is
good so >ar. A>ter a >e3 minutesA the gar"age collector kicks in and it >inds this unre>erenced
o"-ectA so it 3ill "e removed. reeing an <ut+ut,ort 3ill cause the +in to change its state to
in+ut. No3A the +in is not high an*more4
** Turn t+e <=# on
OutputPort <=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
<=# 1 null;
** /e +ave lost t+e reference but t+e <=# is still lit
**force t+e garbage collector
#ebug.%C!true";
** T+e <=# is no/ off)
An im+ortant thing to note is that i> 3e make a re>erence >or an o"-ect inside a method and the
method returns then 3e have alread* lost the re>erence. 2ere is an e/am+le
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.9ar/are;
namespace Test
{
public class Program
{
static voi Turn<=#On!"
{
** Turn t+e <=# on
OutputPort <=# 1
ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
&
public static voi Main!"
{
Turn<=#On!";
** /e t+in. t+at everyt+ign is o.ay but it is not
** run t+e %C
#ebug.%C!true";
** is <=# still onG
&
&
&
Co+*right @ $0!$ '2# ElectronicsA LLC ,age &=?(.
Beginners guide to C# and NETM 0.'ar"age Collector
To solve thisA 3e need a re>erence that is al3a*s availa"le. 2ere is the correct code
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.9ar/are;
namespace Test
{
public class Program
{
static OutputPort <=#;
static voi Turn<=#On!"
{
** Turn t+e <=# on
<=# 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.<=#? true";
&
public static voi Main!"
{
Turn<=#On!";
** run t+e %C
#ebug.%C!true";
** is t+e <=# onG
&
&
&
Another good e/am+le is using timers. NETM +rovides a 3a* to create timers that handle
3ork a>ter a determined time. #> the re>erence >or the timer is lost and the gar"age collector
runsA the timer is no3 lost and it 3ill not run as e/+ected.
Im)ortant note* #> *ou have a +rogram that is 3orking >ine "ut then right a>ter *ou see the 'C
running in the 7<ut+ut 5indo38A and the +rogram sto+s 3orking or raises an e/ce+tionA then
this is "ecause the 'C has removed an o"-ect that *ou need. AgainA that is "ecause *ou
didnBt kee+ re>erences to the o"-ect *ou 3anted to kee+ alive.
A.2. Dis)ose
The gar"age collector 3ill >ree o"-ects at some +oint "ut 3hat i> 3e need to >ree one +articular
o"-ect immediatel*6 Most o"-ects have a %is+ose method. #> an o"-ect needs to "e >reed at
an*timeA 3e can 7dis+ose8 o> it.
%is+osing an o"-ect is ver* im+ortant in NETM. 5hen 3e create a ne3 #n+ut,ort o"-ectA the
assigned +in is reserved. 5hat i> 3e 3ant to use the same +in as an out+ut6 <r even use the
same +in as an analog in+ut6 5e 3ill >irst need to >ree the +in and then create the ne3 o"-ect.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age &.?(.
Beginners guide to C# and NETM 0.'ar"age Collector
OutputPort OutPin 1 ne/ OutputPort!!Cpu.Pin"F=ABPin.#igital.#iH? true";
OutPin.#ispose!";
;nputPort ;nPort 1 ne/ ;nputPort!!Cpu.Pin"F=ABPin.#igital.#iH? true?
Port.$esistorMoe.PullFp";
A.%. &C >ut)ut "essages
5hen the gar"age collector runsA it out+uts a lot o> use>ul in>ormation to the out+ut 3indo3.
These messages give *ou an idea o> 3hat is using resources in the s*stem. Although not
recommendedA *ou ma* 3ant to disa"le those messages to >ree u+ the out+ut 3indo3 >or
*our o3n usage. This is easil* achieva"le using this line o> code.
#ebug.=nable%CMessages!false";
Co+*right @ $0!$ '2# ElectronicsA LLC ,age &0?(.
Beginners guide to C# and NETM !0.C# Level 3
1.. C, 7evel %
This section 3ill cover all the C# materials 3e 3anted to include in this "ook. A good and >ree
eBook to continue learning a"out C# is availa"le at
htt+E??333.+rogrammersheaven.com?$?CShar+Book
1..1. Byte
5e learned ho3 int is use>ul to store num"ers. The* can store ver* large num"ers "ut ever*
int consumes >our "*tes o> memor*. Fou can think o> a "*te as a single memor* cell. A "*te
can hold an* value >rom 0 to $((. #t doesnBt sound like much "ut this is enough >or a lot o>
things. #n C# "*tes are declared using 7"*te8 -ust like ho3 3e use 7int8.
byte b 1 14;
byte bb 1 1444;** t+is /ill not /or.)
The ma/imum num"er that a "*te can hold is $() T0..$((UA 5hatVs going to ha++en i> 3e
increment it over $((6 #ncrementing $(( "* one 3ould overla+ the value "ack to Jero.
Fou 3ill +ro"a"l* 3ant to use int >or most o> *our varia"les "ut 3e 3ill learn later 3here "*tes
are ver* im+ortant 3hen 3e start using arra*s.
1..2. Char
To re+resent a language like EnglishA 3e need $) values >or lo3er case and $) >or u++er
case then !0 >or num"ers and ma*"e another !0 >or s*m"ols. Adding all these u+ 3ill give us
a num"er that is 3ell less than $((. So a "*te 3ill 3ork >or us. #> 3e create a ta"le o> lettersA
num"ers and s*m"olsA 3e can re+resent ever*thing 3ith a numerical value. Actuall*A this
ta"le alread* e/ists and is called the ASC## ta"le.
So >ar a "*te is su>>icient to store all 7characters8 3e have in English. Modern com+uter
s*stems have e/+anded to include other languagesA some use ver* com+le/ non9Latin
characters. The ne3 characters are called Hnicode characters. Those ne3 Hnicode
characters can "e more than $(( and so a "*te is not su>>icient and an integer C>our "*tesD is
too much. 5e need a t*+e that uses $9"*tes o> memor*. $9"*tes is good to store num"ers
>rom 0 to over )&A000. This $9"*te t*+e is called 7short8A 3hich 3e are not using in this "ook.
S*stems can re+resent characters using !9"*te or using $9"*tes. ,rogrammers decided to
create a ne3 t*+e called char 3here char can "e !9"*te or $9"*tesA de+ending on the s*stem.
Since NETM is made >or smaller s*stemsA its char is actuall* a "*te4 This is not the case on
Co+*right @ $0!$ '2# ElectronicsA LLC ,age (0?(.
Beginners guide to C# and NETM !0.C# Level 3
a ,C 3here a char is a $9"*te varia"le4
%o not 3orr* a"out all this messA do not use char i> *ou do not have to and i> *ou use itA
remem"er that it is !9"*te on NETM.
1..%. Array
#> 3e are reading an analog in+ut !00 times and 3e 3ant to +ass the values to a methodA it is
not +ractical to +ass !00 varia"les in !00 arguments. #nsteadA 3e create an 7arra*8 o> our
varia"le t*+e. Fou can create an arra* o> an* o"-ect. 5e 3ill mainl* "e using "*te arra*s.
5hen *ou start inter>acing to devices or accessing >ilesA *ou 3ill al3a*s "e using "*te arra*s.
Arra*s are declared similar to o"-ects.
byteIJ MyArray;
The code a"ove creates a 7re>erence8 o> an o"-ect o> t*+e 7"*te arra*8. This is a re>erence "ut
it doesnBt have an o"-ect *etA it is null. #> *ou >orgot 3hat is a re>erence then go "ack and read
more in the C# Level $ cha+ter.
To create the o"-ect 3e use the 7ne38 ke*3ord and then 3e need to tell it the siJe o> our
arra*. This siJe is the count o> ho3 man* elements o> the t*+e 3e 3ill have in an arra*. <ur
t*+e is a "*teA so the num"er is ho3 man* "*tes 3e are allocating in memor*.
byteIJ MyArray;
MyArray 1 ne/ byteI14J;
5e have created a "*te arra* 3ith !0 elements in it. The arra* o"-ect is re>erenced >rom
7M*Arra*8.
5e no3 can store?read an* o> the !0 values in the arra* "* indicating 3hich 7inde/7 3e 3ant
to access.
byteIJ MyArray;
MyArray 1 ne/ byteI14J;
MyArrayI4J 1 1D2;** first ineK
MyArrayILJ 1 LL;** last ineK
MyArrayI14J 1 1;** T+is is EA#...=$$O$))
A ver* im+ortant note here is that inde/es start >rom Jero. SoA i> 3e have an arra* o> siJe !0A
then 3e have inde/es >rom 0 to 0. Accessing inde/ !0 3ill N<T 3ork and 3ill raise an
e/ce+tion.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age (!?(.
Beginners guide to C# and NETM !0.C# Level 3
5e can assign values to elements in an arra* at the time o> initialiJation. This e/am+le 3ill
store the num"ers ! to !0 in inde/es 0 to 0.
byteIJ MyArray 1 ne/ byteI14J { 1? D? 2? >? H? M? N? O? L? 14 &;
To co+* an arra*A use the Arra* class as >ollo3s
byteIJ MyArray1 1 ne/ byteI14J { 1? D? 2? >? H? M? N? O? L? 14 &;
byteIJ MyArrayD 1 ne/ byteI14J;
Array.Copy!MyArray1? MyArrayD? H";**copy H elements only
<ne im+ortant and use>ul +ro+ert* o> an arra* is the Length +ro+ert*. 5e can use it to
determine the length o> an arra*.
byteIJ MyArray1 1 ne/ byteI14J { 1? D? 2? >? H? M? N? O? L? 14 &;
byteIJ MyArrayD 1 ne/ byteI14J;
Array.Copy!MyArray1? MyArrayD? MyArray1.<engt+";**copy t+e /+ole array
1..'. (tring
5e have alread* used strings in man* +laces. 5e 3ill revie3 3hat 3e have learned and add
more details.
,rograms usuall* need to construct messages. Those messages can "e human reada"le
te/t. Because this is use>ul and a commonl* used >eature in +rogramsA C# su++orts strings
nativel*. C# kno3s i> the te/t in a +rogram is a string i> it is enclosed "* dou"le9Guotes.
This is a string e/am+le.
string MyString 1 'Some string';
string =KampleString 1 'string =KampleString';
5hatever is inside the dou"le Guotes is colored in red and considered to "e a string. Note
ho3 in the second line # +ur+osel* used the same te/t in the string to match 3hat # used to
assign the string. C# doesnBt com+ile an*thing in Guotes Cred te/tD "ut onl* takes it as it isO a
string.
Fou ma* still have con>usion on 3hat the di>>erence "et3een an integer varia"le that has ( in
it and a string that has ( in it is. 2ere is e/am+le code
Co+*right @ $0!$ '2# ElectronicsA LLC ,age ($?(.
Beginners guide to C# and NETM !0.C# Level 3
string MyString 1 'H' 7 'H';
int My;nteger 1 H 7 H;
5hat do *ou think the actual value o> the varia"les no36 or integerA it is !0 as (M(Q!0. But
>or string this is not true. Strings do not kno3 an*thing a"out 3hat is in itA te/t or num"ers
make no di>>erence. 5hen adding t3o strings togetherA a ne3 string is constructed to com"ine
"oth. And so 7(8M8(8Q8((8 and not !0 like integers.
Almost all o"-ects have a ToString method that converts the o"-ect in>ormation to a +rinta"le
te/t. This demonstration sho3s ho3 ToString 3orks
int My;nteger 1 H 7 H;
string MyString 1 'T+e value of My;nteger is8 ' 7 My;nteger.ToString!";
#ebug.Print!MyString";
1unning the a"ove code 3ill +rintE
The value o> M*#nteger isE !0
Strings can "e converted to "*te arra*s i> desired. This is im+ortant i> 3e 3ant to use a
method that onl* acce+ts "*tes and 3e 3ant to +ass our string to it. #> 3e do thatA ever*
character in the string 3ill "e converted to its eGuivalent "*te value and stored in the arra*
using System.TeKt;
.....
.....
byteIJ buffer 1 =ncoing.FTFO.%etEytes!'=Kample String'";
1..6. #or17oo)
Hsing the 3hile9loo+ is enough to serve all our loo+ needs "ut >or9loo+ can "e easier to use in
some cases. The sim+lest e/am+le is to 3rite a +rogram that counts >rom ! to !0. Similarl*A
3e can "link an LE% !0 times as 3ell. The >or9loo+ takes three arguments on a varia"le. #t
needs the initial valueA ho3 to end the loo+ and 3hat to do in ever* loo+
int i;
for !i 1 4; i 6 14; i77"
{
**o somet+ing
&
Co+*right @ $0!$ '2# ElectronicsA LLC ,age (3?(.
Beginners guide to C# and NETM !0.C# Level 3
5e >irst need to declare a varia"le to use. Then in the >or9loo+A 3e need to give it three
arguments CinitialA ruleA actionD. #n the ver* >irst loo+A 3e asked it to set varia"le 7i8 to Jero.
Then the loo+ 3ill kee+ running as long as the varia"le 7i8 is less then !0. inall*A the >or9loo+
3ill increment varia"le i in ever* loo+. Let us make a >ull +rogram and test it.
using System.T+reaing;
using Microsoft.SPOT;
using System;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
int i;
for !i 1 4; i 6 14; i77"
{
#ebug.Print!'i1 ' 7 i.ToString!"";
&
&

&
&
#> 3e run the +rogram a"oveA 3e 3ill see that it is +rinting i >rom 0 to 0 "ut not !0. ButA 3e
3anted it to run >rom ! to !0 and not 0 to 04 To start >rom ! and not 0A 3e need to set i to ! in
the initial loo+. AlsoA to run to !0A 3e need to tell the >or9loo+ to turn all the 3a* to !0 and not
less than !0 so 3e 3ill change the less than C7W8D 3ith less than or eGual C7WQ8D
using System.T+reaing;
using Microsoft.SPOT;
using System;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
int i;
for !i 1 1; i 61 14; i77"
{
#ebug.Print!'i1 ' 7 i.ToString!"";
&
Co+*right @ $0!$ '2# ElectronicsA LLC ,age (&?(.
Beginners guide to C# and NETM !0.C# Level 3
&

&
&
Can 3e make the B>orB loo+ count onl* even num"ers Cincrement "* t3oD6
using System.T+reaing;
using Microsoft.SPOT;
using System;
namespace MFConsoleApplication1
{
public class Program
{
public static voi Main!"
{
int i;
for !i 1 D; i 61 14; i 1 i 7 D"
{
#ebug.Print!'i1 ' 7 i.ToString!"";
&
&
&
&
The "est 3a* to understand >or9loo+s is "* ste++ing in code and seeing ho3 C# 3ill e/ecute
it.
1..<. ($itch (tatement
Fou +ro"a"l* 3onBt use the s3itch statement >or "eginner a++lications "ut *ou 3ill >ind it ver*
use>ul 3hen making large +rogramsA es+eciall* 3hen handling state9machines. The s3itch9
statement 3ill com+are a varia"le to a list o> constants Conl* constantsD and make an
a++ro+riate -um+ accordingl*. #n this e/am+leA 3e 3ill read the current 7%a*<>5eek8 value
and then >rom its value 3e 3ill +rint the da* as a string. 5e can do all this using i>9statement
"ut *ou can see ho3 much easier s3itch9statement isA in this case.
using System.T+reaing;
using Microsoft.SPOT;
using System;
namespace MFConsoleApplication1
{
Co+*right @ $0!$ '2# ElectronicsA LLC ,age ((?(.
Beginners guide to C# and NETM !0.C# Level 3
public class Program
{
public static voi Main!"
{
#ateTime currentTime 1 #ateTime.@o/;
int ay 1 !int"currentTime.#ayOfCee.;
s/itc+ !ay"
{
case 48
#ebug.Print!'Sunay'";
brea.;
case 18
#ebug.Print!'Monay'";
brea.;
case D8
#ebug.Print!'Tuesay'";
brea.;
case 28
#ebug.Print!'Censay'";
brea.;
case >8
#ebug.Print!'T+ursay'";
brea.;
case H8
#ebug.Print!'Friay'";
brea.;
case M8
#ebug.Print!'Saturay'";
brea.;
efault8
#ebug.Print!'Ce s+oul never see t+is'";
brea.;
&
&
&
&
<ne im+ortant note a"out s3itch9statements is that it com+ares a varia"le to a list o>
constants. A>ter ever* 7case8 3e must have a constant and not a varia"le.
5e can also change the code to s3itch on the enumeration o> da*s as the >ollo3ing sho3sE
using System.T+reaing;
using Microsoft.SPOT;
using System;
namespace MFConsoleApplication1
{
public class Program
{
Co+*right @ $0!$ '2# ElectronicsA LLC ,age ()?(.
Beginners guide to C# and NETM !0.C# Level 3
public static voi Main!"
{
#ateTime currentTime 1 #ateTime.@o/;
s/itc+ !currentTime.#ayOfCee."
{
case #ayOfCee..Sunay8
#ebug.Print!'Sunay'";
brea.;
case #ayOfCee..Monay8
#ebug.Print!'Monay'";
brea.;
case #ayOfCee..Tuesay8
#ebug.Print!'Tuesay'";
brea.;
case #ayOfCee..Cenesay8
#ebug.Print!'Censay'";
brea.;
case #ayOfCee..T+ursay8
#ebug.Print!'T+ursay'";
brea.;
case #ayOfCee..Friay8
#ebug.Print!'Friay'";
brea.;
case #ayOfCee..Saturay8
#ebug.Print!'Saturay'";
brea.;
efault8
#ebug.Print!'Ce s+oul never see t+is'";
brea.;
&
&
&
&
Tr* to ste+ in the code to see ho3 s3itch is handled in details.
Co+*right @ $0!$ '2# ElectronicsA LLC ,age (=?(.
Beginners guide to C# and NETM !!.Additional 1esources
11. Additional 3esources
'2# Electronics +rovides man* additionalA and >reeA resources.
Tutorials and Do$nloads
This +age includes +lent* o> tutorials covering a"out ever*thing NETM. #t also includes all
needed links >or do3nloadsA re>erences and an* other links needed "* NETM users. Fou
ma* 3ant to "ookmark this +age.
htt+E??333.tin*clr.com?su++ort?
Codeshare
This 3e"site includes hundreds o> code sni++ets and com+lete +ro-ects +rovided "* the
communit*. The source o> the >iles is visi"le right on the 3e"site >or those 3anting to look >or
a 7cheat sheet8 or *ou can do3nload the com+lete >iles as 3ell. 5e look >or3ard to see *our
o3n contri"utions on codeshare
htt+E??code.tin*clr.com
eBooks
BeginnersB NETM 'uideE
htt+E??333.ghielectronics.com?do3nloads?EL?BeginnersX$0guideX$0toX$0NETM.+d>
BeginnersB NETM ,orting 'uideE
htt+E??333.ghielectronics.com?do3nloads?EL?BeginnersX$0'uideX$0toX$0,ortingX$0NETM.+d>
#nternet o> thingsE
htt+E??333.ghielectronics.com?do3nloads?EL?ELR#nternetRo>RThingsRBook.+d>
.NET 'adgeteer Hltimate 'uideE
htt+E??333.ghielectronics.com?do3nloads?'adgeteer?.NETX$0'adgeteerX$0HltimateX$0'uide.+d>
Co+*right @ $0!$ '2# ElectronicsA LLC ,age (.?(.

You might also like