Getting Started with Arduino Wiring for Windows 10 IoT …pdf.ebook777.com/035/B01B0NSI5E.pdf ·...
Transcript of Getting Started with Arduino Wiring for Windows 10 IoT …pdf.ebook777.com/035/B01B0NSI5E.pdf ·...
Copyright
GettingStartedwithArduinoWiringforWindows10IoTCore
AgusKurniawan
1stEdition,2016
Copyright©2016AgusKurniawan
**Windows10IoTCore,VisualStudioandLogoaretrademarkandcopyrightfromMicrosoft
**RaspberryPiistrademarkandcopyrightfromRaspberryPi,www.raspberrypi.org
TableofContentsCopyright
Preface
1.SettingUpDevelopmentEnvironment
1.1RaspberryPi2
1.2GettingHardware
1.3Windows10forRaspberryPi
1.4DevelopmentTools
1.5ConfiguringWindows10IoTCoreforRaspberryPi2
2.DigitalI/O
2.1GettingStarted
2.2Demo1:HelloWorld:BlinkingLED
2.2.1Wiring
2.2.2WritingProgram
2.2.2.1CreatingaProject
2.2.2.2WritingCodes
2.2.3ConfiguringRemoteMachine
2.2.4Testing
2.2.5Debugging
2.3Demo2:LEDandPushbutton
2.3.1Wiring
2.3.2WritingProgram
2.3.3ConfiguringRemoteRaspberryPi
2.3.4Testing
3.SerialCommunication
3.1SerialPortonWindows10IoTCore
3.2DemoSerialCommunication
4.AnalogI/O
4.1GettingStarted
5.WorkingwithI2C/TWIProtocol
5.1GettingStarted
5.2Demo:SensorDeviceBasedI2C
5.2.1SensorDeviceBaseI2C
5.2.2WritingProgram
5.2.2.1CreatingaProject
5.2.2.2WritingCodes
5.2.2.3ConfiguringRemoteMachine
5.2.3Testing
6.WorkingwithSPIProtocol
6.1GettingStarted
6.2Demo:HelloSPI
6.2.1HardwareConfiguration
6.2.2WritingProgram
6.2.3Testing
SourceCode
Preface
IfyouhaveexperiencesinArduinodevelopmentusingSketchprogram,nowyoucandoportingyourArduinocodetoRaspberryPi2withWindows10IoTCore.ThisbookwaswrittentohelpanyonewhowantstogetstartedwithArduinoWiringwhichistargetedtoWindows10coreforRaspberryPi2.ItdescribesallthebasicelementsoftheArduinoWiringwithstep-by-stepapproach.
AgusKurniawan
MicrosoftMVP,2004-2015
Depok,January2016
1.1RaspberryPi2
TheRaspberryPiisalowcost,credit-cardsizedcomputerthatplugsintoacomputermonitororTV,andusesastandardkeyboardandmouse(source:https://www.raspberrypi.org/help/what-is-a-raspberry-pi/).
TheRaspberryPi2comeswithamuchmorepowerfulprocessor(fourCortex-A7coreswithupto900MHz)andmorememory(1GBRAM).ThefollowingistechnicalspecificationofRaspberryPi2device:
ARM7QuadCoreCPU1GBRAM900MHzBoardClockSpeed40GPIOPins4xUSBPorts4PoleStereoOutput1xHDMIPort1x0/100Ethernet1xMicroSDCardslot
YoucanseeRaspberryPi2devicewithmodelBontheFigurebelow.
1.2GettingHardware
HowtogetRaspberryPi2device?
Officiallyyoucanbuyitfromtheofficialdistributor
RS,http://uk.rs-online.com/web/generalDisplay.html?id=raspberrypiElement14,http://www.element14.com/raspberrypi
YoualsobuyRaspberryPiperipheraldevicesforinstance,keyboard,mouse,HDMIcable,SDcard,USBhub,etc.
ItriedtolookforbuyingRaspberryPi2deviceandfoundthatthereareanotheroptionstobuy
ThePiHut,http://thepihut.comSparkfun,https://www.sparkfun.com/EXP-Tech,http://www.exp-tech.de/Cooking-hack,http://www.cooking-hacks.com/Amazon,http://www.amazon.comEbay,http://www.ebay.com
Youalsocanbuythisboardatyourlocalelectronicsstores.
1.3Windows10forRaspberryPi
MicrosofthasannouncedthattheyreleaseWindows10forRaspberryPi2,http://blogs.windows.com/buildingapps/2015/02/02/windows-10-coming-to-raspberry-pi-2/.NowMicrosoftalreadyreleasedWindows10previewforRaspberryPi2,http://blogs.windows.com/buildingapps/2015/04/29/microsoft-brings-windows-10-to-makers/.
Inthisbook,welearnhowtogetstartedwithWindows10IoTCoreforRaspberryPi2board.Inthisbook,IsupposeyouhaveknowledgeaboutWindows10IoTCore.Ihavewrittene-book,GettingStartedwithWindows10forRaspberryPi2,http://blog.aguskurniawan.net/post/Getting-Started-with-Windows-10-for-Raspberry-2.aspx.
MakesureyouhavedeployedWindows10IoTCorebuild10586orlatertoworkwithArduinoWiringdevelopment.
1.5ConfiguringWindows10IoTCoreforRaspberryPi2
TowriteaprogramforArduinoWiringonRaspberryPi2withWindows10IoTCore,youshouldconfigureyourWindows10IoTCoreinDirectMemoryMappedDriver.
Toconfigurethatmode,openabrowserandnavigatetohttp://windows10iotcore_ipaddress:8080.Thedefaultauthenticationisusername:Administratorandpassword:p@ssw0rd.
SelectDevices.YoushouldseeControllerDriverconfiguration.
2.1GettingStarted
Inthischapter,weworkwithDigitalI/O.Ingeneral,digitalRead()anddigitalWrite()workwithRaspberryPi.
Let’sstarttocreateprojects.
2.2Demo1:HelloWorld:BlinkingLED
Inthissection,welearnhowtogetstartedwithRaspberryPiprogrammingonWindows10IoTCore.WebuildLEDblinkingapplication.Weuse3LEDstoillustrateourcase.
2.2.1Wiring
Inthissection,welearnhowtowritedatausingGPIOonRaspberryPi.Wecanuse3LEDstoillustrateourcase.
OurLEDsareconnectedtoGPIOpins:GPIO13,GPIO6,andGPIO5.LEDgroundpinisconnectedtoGPIOGND.
Thefollowingisourdemowiring.
2.2.2WritingProgram
Inthissection,wedevelopprogramtoaccessRaspberryPiGPIOusingVisualStudio2015.
2.2.2.1CreatingaProject
Firstly,wecreateaproject.OpenVisualStudio2015.Then,youcancreateanewproject.SelectVisualC++->Windows>WindowsIoTCore.ChooseArduinoWiringApplicationforWindowsIoTCoretemplate.
FillLedBlinkingonprojectname.Ifdone,clickOKbutton.
Ifyoudon’tseethistemplate,youcandownloadandinstallitonhttps://visualstudiogallery.msdn.microsoft.com/55b357e1-a533-43ad-82a5-a88ac4b01dec.
Then,youcanseeSketchprogramonVisualStudio2015codeeditor.
2.2.2.2WritingCodes
NowwecanmodifyourcodeonBlinking.inofile.Pleaseopenthatfileandwritethiscode.
voidsetup()
{
pinMode(GPIO13,OUTPUT);
pinMode(GPIO6,OUTPUT);
pinMode(GPIO5,OUTPUT);
}
voidloop()
{
digitalWrite(GPIO13,HIGH);
digitalWrite(GPIO6,LOW);
digitalWrite(GPIO5,LOW);
delay(500);
digitalWrite(GPIO13,LOW);
digitalWrite(GPIO6,HIGH);
digitalWrite(GPIO5,LOW);
delay(500);
digitalWrite(GPIO13,LOW);
digitalWrite(GPIO6,LOW);
digitalWrite(GPIO5,HIGH);
delay(500);
}
Savethiscode.
2.2.3ConfiguringRemoteMachine
YoushouldchangetargetisARMandRemoteMachine.
Then,openprojectproperties.SelectDebugging.FillRaspberryPi2hostname,suchasminwinpc.Then,selectUniversal(UnencryptedProtocol)onAuthenticationType.
Savetheconfiguration.
Nowyoucompiletheprogram.Makesureyoudon’tgetanyerroroncompiling.
2.2.4Testing
Ifyourprogramdoesn’tgeterrorsoncompiling,thenyoucanrunthisprogram.ClickRemoteMachineonDebugmenu,seetheFigurebelow.
Ifsuccess,youshouldseeLEDsareblinking.
2.2.5Debugging
Wecandebugourprogram.Justsetbreakpointsonyourcode.
2.3Demo2:LEDandPushbutton
WebuildasimpledemotoillustrateI/OonRaspberryPiGPIO.WneedapushbuttonandLED.Ifyoupresspushbutton,LEDwilllighting.Otherwise,itwilloff.
2.3.1Wiring
ConnectyourLEDintoGPIO13andpushbuttononGPIO6.Thefollowingisourwiring.
2.3.2WritingProgram
Createaproject,callPushLed,onVisualStudio2015.Pleasefollowinstructionsonsection2.2.2.1.
WritethiscodeforPushLed.ino.voidsetup()
{
pinMode(GPIO13,OUTPUT);
pinMode(GPIO6,INPUT);
}
voidloop()
{
intstate=digitalRead(GPIO6);
digitalWrite(GPIO13,state);
delay(500);
}
2.3.3ConfiguringRemoteRaspberryPi
WemustconfigureourremoteRaspberryPiandproject.Pleasefollowinstructionsonsection2.2.3.
2.3.4Testing
NowyoucandeployandexecuteprogramintoWindows10IoTCoreonRaspberryPi2board.
Presspushbuttontogetaresponsefromtheprogram.
Afterpressed,youshouldseethelightingLED.
3.1SerialPortonWindows10IoTCore
MicrosoftremoveSerialobjectsowecan’tuseSerialinourprogramnow.Pleasecheckitonhttps://ms-iot.github.io/content/en-US/win10/ArduinoWiringPortingGuide.htm#port_serial.Tosenddatatotheprogramoutput,MicrosoftprovideLog().WecanseethemessageonOutputwindowofVisualStudio2015.
3.2DemoSerialCommunication
Fordemo,Iuseaprogramfromsection2.2.WeaddmessagesusingLog()sowecanmonitorthesemessageonOutputwindow.
CreateArduinoWiringproject,calledSerialDemo.Seesection2.2.2.1.Then,writethiscodeonSerialDemo.ino.
voidsetup()
{
pinMode(GPIO13,OUTPUT);
pinMode(GPIO6,OUTPUT);
pinMode(GPIO5,OUTPUT);
}
voidloop()
{
Log(L"LED1ON\n");
digitalWrite(GPIO13,HIGH);
digitalWrite(GPIO6,LOW);
digitalWrite(GPIO5,LOW);
delay(500);
Log(L"LED2ON\n");
digitalWrite(GPIO13,LOW);
digitalWrite(GPIO6,HIGH);
digitalWrite(GPIO5,LOW);
delay(500);
Log(L"LED3ON\n");
digitalWrite(GPIO13,LOW);
digitalWrite(GPIO6,LOW);
digitalWrite(GPIO5,HIGH);
delay(500);
}
ConfigureyourprojecttoRemotemachineforRaspberryPi.Seesection2.2.3.
Afterrunning,youcanseemessageonOutputwindowfromVisualStudio.
4.1GettingStarted
Unfortunately,RaspberryPi2doesn’thaveanalogI/Osotechnicallywecan’tuseanalogRead()andanalogWrite()inourprogram.Alternatively,wecanaccessAnalogsensorsviaSPIandI2C.YoucanalsouseICssuchasMCP3008,whichsupportforconvertingfromanalogtoSPIorI2C.
Asampleofsensormodule-basedI2Ccanbereadonchapter5.
5.WorkingwithI2C/TWIProtocol
ThischapterexplainshowtoworkwithI2ConRaspberryPi2boardandwriteprogramtoaccessI2C.
5.1GettingStarted
TheI2C(Inter-IntegratedCircuit)buswasdesignedbyPhilipsintheearly’80stoalloweasycommunicationbetweencomponentswhichresideonthesamecircuitboard.TWIstandsforTwoWireInterfaceandformostmartsthisbusisidenticaltoI²C.ThenameTWIwasintroducedbyAtmelandothercompaniestoavoidconflictswithtrademarkissuesrelatedtoI²C.
I2Cbusconsistsoftwowires,SDA(SerialDataLine)andSCL(SerialClockLine).ThefollowingisI2CbusonRaspberryPi2board.
ToconnectdeviceviaI2C,youcandothefollowingconnection.
Youshoulddefinewhichtobemasterandslave.
Wealsocandefine1masterandtwoslavedevices.
TherearemanydeviceswhichuseI2Ctocommunicatetoother.ThefollowingisalistofsampledevicewithI2Cenabled:
EEPROMICwithI2CsupportADC/DACwithI2Csupport,forinstance,http://www.adafruit.com/product/935RealTimeClock(RTC),http://www.adafruit.com/products/264LCD+KeypadmodulewithI2Csupport,forinstance,http://www.adafruit.com/product/1109
Fortesting,IusedPCF8591AD/DAConvertermodulewithsensorandactuatordevices.Youcanfinditonthefollowingonlinestore:
Amazon,http://www.amazon.com/PCF8591-Converter-Module-Digital-Conversion/dp/B00BXX4UWC/eBay,http://www.ebay.comDealextreme,http://www.dx.com/p/pcf8591-ad-da-analog-to-digital-digital-to-analog-converter-module-w-dupont-cable-deep-blue-336384Aliexpress,http://www.aliexpress.com/
Inaddition,youcanfindthisdeviceonyourlocalelectronicsstore/onlinestore.
Thismodulehasminiformmodeltoo,forinstance,youcanfinditonAmazon,http://www.amazon.com/WaveShare-PCF8591T-Converter-Evaluation-Development/dp/B00KM6X2OI/.
ThismoduleusePCF8591ICandyoucanreadthedatasheetonthefollowingURLs.
http://www.electrodragon.com/w/images/e/ed/PCF8591.pdfhttp://www.nxp.com/documents/data_sheet/PCF8591.pdf
OnWindows10IoTCoreforRaspberryPi2,wecanaccessI2CviaArduinoWiring
5.2Demo:SensorDeviceBasedI2C
TheobjectiveofthissectionistoillustratehowtoreaddataonI2Cbus.WeusePCF8591AD/DAconverterwithsensordevicesasI2Cexternalsource.Youcanreadthismoduleonthislink,http://www.electrodragon.com/w/images/8/89/PCF8591_ADC_DAC_ADDA_Analog_Digital_Converter_Module_schematic_.pdf.Inourscenario,wewillreadthreesensordevicesinPCF8591AD/DAmodulesviaI2C.
Let’sstart!.
5.2.1SensorDeviceBaseI2C
NowyoucanconnectyourPCF8591AD/DAtoRaspberryPi2board.Thefollowingisdemowiring:
ModuleSCL—>RaspberryPi2boardSCLModuleSDA—>RaspberryPi2boardSDAModuleVCC–>RaspberryPi2board+3.3VModuleGND–>RaspberryPi2boardGND
Thefollowingisasampleofhardwareimplementation.
5.2.2WritingProgram
Inthissection,webuildaprogramtoaccesssensorviaI2Cport.
5.2.2.1CreatingaProject
CreateanewprojectonVisualStudio2015,calledSensorI2cDemo.Followtheinstructionsonsection2.2.2.1
5.2.2.2WritingCodes
NowwemodifyourcodeonSensorI2CDemo.inofile.Pleaseopenthatfileandwritethiscode.
#include<Wire.h>
#definePCF8591(0x90>>1)//I2Cbusaddress
#definePCF8591_ADC_CH00x00//thermistor
#definePCF8591_ADC_CH10x01//photo-voltaiccell
#definePCF8591_ADC_CH20x02
#definePCF8591_ADC_CH30x03//potentiometer
ULONGADC1,ADC2,ADC3;
voidsetup()
{
//putyoursetupcodehere,torunonce:
Wire.begin();
}
voidloop()
{
//readthermistor
Wire.beginTransmission(PCF8591);
Wire.write((byte)PCF8591_ADC_CH0);
Wire.endTransmission();
delay(500);
Wire.requestFrom(PCF8591,2);
ADC1=Wire.read();
ADC1=Wire.read();
Log(L"Thermistor=%d\n",ADC1);
//readphoto-voltaiccell
Wire.beginTransmission(PCF8591);
Wire.write(PCF8591_ADC_CH1);
Wire.endTransmission();
delay(500);
Wire.requestFrom(PCF8591,2);
ADC2=Wire.read();
ADC2=Wire.read();
Log(L"Photo-voltaiccell=%d\n",ADC2);
//potentiometer
Wire.beginTransmission(PCF8591);
Wire.write(PCF8591_ADC_CH3);
Wire.endTransmission();
delay(500);
Wire.requestFrom(PCF8591,2);
ADC3=Wire.read();
ADC3=Wire.read();
Log(L"potentiometer=%d\n",ADC3);
delay(1000);
}
Youcanseethatweobtainsensordatafromthesecondbytefromsensordevice.
Savethiscode.
5.2.2.3ConfiguringRemoteMachine
Pleaseconfigureyourremotemachineandprojectbasedoninstructionfromsection2.2.3
5.2.3Testing
Nowyoucancompileanduploadtheprogramtotheboardindebuggingmode.
Thefollowingisasampleoutputondebugoutput
6.WorkingwithSPIProtocol
ThischapterexplainshowtoworkSPIonRaspberryPi2boardandhowtoaccessSPIusingArduinoWiring.
6.1GettingStarted
TheSerialPeripheralInterface(SPI)isacommunicationbusthatisusedtointerfaceoneormoreslaveperipheralintegratedcircuits(ICs)toasinglemasterSPIdevice;usuallyamicrocontrollerormicroprocessorofsomesort.RaspberryPi2hastwoSPIports.
SPIinRaspberrycanbedefinedonthefollowingpins:
SPI0:
MOSI(GPIO19)MISO(GPIO21)SCLK(GPIO23)CS0(GPIO24)CS1(GPIO26)
SPI1:
MOSI(GPIO38)MISO(GPIO35)SCLK(GPIO40)CS0(GPIO11)
YoucanseethesepinsontheRaspberryPiGPIOpins,showninFigurebelow.
RaspberryPiworksasSPIMaster.IfyouwanttoconnecttoSPISlaveDevices,youcanconnectwiththefollowingconfiguration.
(imagesource:http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus)
6.2Demo:HelloSPI
TheobjectiveofthedemoistogetstartedhowtoworkwithSPIonRaspberryPi2boardusingArduinoWiring.Inthisscenario,weapplySPIloopback.
Thefollowingisourscenario:
SendonebytedatatoSPI0ReceiveonebytefromSPI0
BecausewebuildSPIloopback,wewillreceivewhatwesent.
Let’sstart.
6.2.1HardwareConfiguration
Hardwareconfigurationiseasy.YoujustconnectMOSIandMISOpinswitheachother.Inthisdemo,IusedSPI0onRaspberryPi2boardsoIconnectMOSI(GPIO19)pintoMISO(GPIO21)pinthroughajumpercable.
Thefollowingisasampleofhardwareconfiguration.
6.2.2WritingProgram
CreateanewprojectusingVisualStudio2015,calledSPILoopback.Pleasereadsection2.2.2.
Then,modify*.inofilewiththefollowingcode.#include<SPI.h>
ULONGsendData,recvData;
//source:
//http://forum.arduino.cc/index.php?topic=197633.0
ULONGrandomDigit(){
unsignedlongt=micros();
byter=(t%10)+1;
for(bytei=1;i<=4;i++){
t/=10;
r*=((t%10)+1);
r%=11;
}
return(r-1);
}
voidsetup()
{
SPI.begin();
}
voidloop()
{
sendData=randomDigit();
recvData=SPI.transfer(sendData);
Log(L"Send=%d\n",sendData);
Log(L"Recv=%d\n",recvData);
delay(800);
}
Savethiscode.
Trytoconfigureyourprojectandremotemachinebasedonsection2.2.3.
6.2.3Testing
CompileanduploadyourprogramtoremoteRaspberryPi2board.YoushouldseesentandreceiveddataonOutputconsole.
AsampleoutputcanbeseeninFigurebelow.
SourceCode
Sourcecodecanbedownloadedonhttp://www.aguskurniawan.net/book/codes_arwir.zip.
Contact
Ifyouhavequestionrelatedtothisbook,[email protected]:http://blog.aguskurniawan.net.