Presentation is loading. Please wait.

Presentation is loading. Please wait.

Hands on Beaglebone Introduction on beaglebone Using it’s IO and interface Work as web server.

Similar presentations


Presentation on theme: "Hands on Beaglebone Introduction on beaglebone Using it’s IO and interface Work as web server."— Presentation transcript:

1 Hands on Beaglebone Introduction on beaglebone Using it’s IO and interface Work as web server

2 A.Hardware introduction a)CPU spec b)What’s on beaglebone: Interfaces B.Software came with the board and others a)SW has been developped on beaglebone b)Make a original SD card C.PC environment set up D.Fist program on beagle E.How beaglebone IO is organized a)Pins muxing b)Mmap and Files F.Using Script languages G.Using Python on beaglebone. a)Python libraries on beaglebone b)Enviroment set up c)Install PyBBIO d)Edit through WinSCP e)digital pins f)Read ADC g)Using UART port h)PWM i)Web server H.Reference

3 Main feature on the CPU itself: a)The CPU on beaglebone is a truly powerful 720Mhz processor based on the ARM cortex-A8 b)Strong graphic support with SGX530 Graphics Engine support OPENGL ES 2.0 c)Integrated LCD controller d)Real-Time Clock (RTC) e)Up to Two USB 2.0 High-Speed OTG Ports with Integrated PHY f)10/100/1000 Ethernet Switch Supporting Up to Two Ports g)Two Controller Area Network Ports (CAN) h)Six UARTs, Two McASPs, Two McSPI, and Three I2C Ports i)Up to Three Enhanced High-Resolution PWM Modules (eHRPWM) j)Up to Four Banks of General-Purpose IO (GPIO), 32 GPIOs per Bank (Multiplexed with Other Functional Pins) k)Crypto Hardware Accelerators (AES, SHA, PKA, RNG) A. Hardware introduction

4 On beaglebone: Peripherial chips are added to make the board more handy to use. a)256MB DDR2 @ 400MHz b)TPS65217 power management IC c)USB hub d)Ethernet phy e)Micro SD slot f)Four Green LEDs that can be controlled via the SW by setting GPIO ports g)2 46 pins expansions header (2.54): LCD ‚GPMC bus(memory controller) ƒMMC1 „SPI x2 …IIC x2 †UART x4 ‡ADC(1.8V max) ˆGPIO x 66 ‰CAN Bus x2 ŠTimer output x4 PWM x 8 All IO are 3.3V except ADC is 1.8V

5 Summary Beaglebone is powerful for even android 4.0 system. Beaglebone have necessary interface for embedded applications, covering most interfaces of common MCU. 3.3V interface make it easy to connect with most sensors. Full Ethernet capability make your system on line. USB host provides wider interfaces( mouse/keyboard/USB web cam) By the power of CPU, visual analysis is easy on beaglebone. USB debug interface: no need for special tool. If powered by USB only, cpu runs at 500Mhz

6 B. Software came with the board and some others a)Beaglebone is an open sourced hardware, widly supported by several open source organization, serverail OS is ported on beaglebone. b)On the micro SD card comes with beaglebone, there is a Angstrom distribition linux. http://www.angstrom-distribution.org/ Angstrom linux distribution is specilized for embedded device, beaglebone releated release: http://downloads.angstrom- distribution.org/demo/beaglebone/ http://www.angstrom-distribution.org/http://downloads.angstrom- distribution.org/demo/beaglebone/ c)TI also support an linux on beaglebone: Sitara Linux Software (http://processors.wiki.ti.com/index.php/Sitara_Linux_Software_Developer%E2%80% 99s_Guide)http://processors.wiki.ti.com/index.php/Sitara_Linux_Software_Developer%E2%80% 99s_Guide d)TI also support Android on it’s A8 process, including beaglebone. Currently upto 4.0.3 http://software- dl.ti.com/dsps/dsps_public_sw/sdo_tii/TI_Android_DevKit/TI_Android_ICS_4_0_3_De vKit_3_0_1/index_FDS.html http://software- dl.ti.com/dsps/dsps_public_sw/sdo_tii/TI_Android_DevKit/TI_Android_ICS_4_0_3_De vKit_3_0_1/index_FDS.html e) Rowboat is an organization supports android on TI AM335x, AM35x, AM37x process, which included beaglebone, currently upto 4.11 http://code.google.com/p/rowboat/http://code.google.com/p/rowboat/ f)Win CE has also been ported to beaglebone.

7 Make a original micro SD card before starting: 1.This is normally done in ubuntu PC, like angstrom stated in the page: : http://downloads.angstrom-distribution.org/demo/beaglebone/ http://downloads.angstrom-distribution.org/demo/beaglebone/ 2.But it’s also possible to work this out in windows: 1)Prepare a micro SD or SD card reader, and install the driver correctly under windows.(Please choose a reliable card reader, some cheap card reader can cause error while writing to micro SD card) 2)Prepare a micro SD card at least 4GB, we recommand Sandisk class 4 or class 6. (same reason as selecting SD card, and class 10 won’t be better than class 4 or 6) 3)Since files are mostly zipped, 7-zip is recommanded.7-zip 4)Download Win32 DiskImager (also known as the win32-image-writer)Win32 DiskImager 5)If you are using an old SD card, you will need tool to erase the SD card, “HP Formatting tool” is recommanded and can be down loaded from these loations: HP Format Tool Ver 2.18 http://www.pcworld.com/downloads/file/fid,64963-page,1/description.htmlhttp://www.pcworld.com/downloads/file/fid,64963-page,1/description.html HP Format Tool Ver 2.18 http://files.extremeoverclocking.com/file.php?f=197http://files.extremeoverclocking.com/file.php?f=197 HP Format Tool Ver 2.18 http://hp-usb-disk-storage-format-tool.software.informer.com/http://hp-usb-disk-storage-format-tool.software.informer.com/ HP Format Tool Ver 2.0.6 http://www.4shared.com/rar/9mNWV4Vl/HP_USB_Disk_Storage_Format_Too.htmlhttp://www.4shared.com/rar/9mNWV4Vl/HP_USB_Disk_Storage_Format_Too.html 5)Down load the image of original one:From 12/18/2012 onward BeagleBone boards revision A6A are shipped with 11-22-12 release, can be found here: http://circuitco.com/support/files/BeagleBone- A6A/BeagleBone_Rev_A6A_Production_11_22_2012.7z

8 6)Unzip the compressed image file with 7-zip. 7)Run the HP formatter tool and format the SD card for FAT or FAT32 in order to remove partition from the card.(in windows 7 run this in adminstrator mode) 8)After formated the SD card, close the formatter tools and start the Win32DiskImager. 9)Select the decompressed image file and correct SD card location. MAKE SURE YOU SELECT THE CORRECT LOCATION OF THE SD CARD. 10)Click on 'Write'. 11)After the image writing is done, eject the SD card, now we can put the card into beaglebone to see if every thing works.

9 Summary Beaglebone cames with Angustrom linux, which was made for embedded system. You may also run Ubuntu,Android or WIN CE. Amgustrom release including lot of tools such as GCC compliers, Vim editor and some other tools we used in a common linux system. Opkg is used to manage the update and upgrade tools. It also comes with support to script languages, such as Python and bone script, Java script. Cloud9 IDE is also installed as a online programming tool.

10 C. PC enviroment set up The enviroment on PC for developing beaglebone is not necessary to be Linux(Ubuntu..etc), Mac and windows are also good for developping applications on beaglebone. Here after we will use Windows as example. 2 programs is recommand to be installed: 1)A terminal, since windows has no longer hyper terminal with it, we recommand using PuTTY, it’s free and open sourced, easy to use. Can be down load here: http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html it’s a exe file, no need to run installation, just click on it to run. http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html 2)File transfer tool: WinSCP, This is a graphic interface file transfer client(yes, there is a server on beaglebone) for windows support various protocols through ethernet. Can be down load here: http://winscp.net/eng/download.phphttp://winscp.net/eng/download.php Unless you wish to make a custom linux on beaglebone, other wise, above tools is enough for developping applications on beaglebone. USB connection and ethernet connection will be used in following pages. So you will need a router to connect beaglebone and PC.

11 Summary There are several ways of programming on beaglebone, you can use the on board IDE cloud 9. Using Vi or Vim editors and use gcc complier to comple and run program directly on beaglebone. In this case, you only need a terminal to login beaglebone’s angstrom linux to do above things. How ever, windows interface will be easier for us to work, WinSCP will take care of transfering file between PC and beaglebone, you can also install a prefered editor as you prefered.

12 Fist program on beagle 1.Connecting beaglebone on USB make sure the micro SD card is correctly inserted. Use the provided USB cable to plug BeagleBone into your computer. This will both power the board and provide a development interface. BeagleBone will boot Linux from the provided microSD card and operates as a flash drive. This provides you with a local copy of the documentation and drivers. 2. You'll see the PWR LED lit steadily. Within 10 seconds, you should see the USR0 LED blinking in a heartbeat pattern. During accesses to the SD card, you should see the USR1 LED turning on. 3. From version A5 and later version, there is no need to install extra USB driver. The FTDI USB driver should be already included in windows. In case your does not have it, you can down load it here: http://www.ftdichip.com/FTDrivers.ht m

13 4. Windows will install the drivers, it will show up 2 USB devices, one is a flash drive, one as VCP(virtual com port) which can be seen under device manager. Note the comport Nr, we will need it later. If you don’t see the drive, check the LED status, SD card,USB cable, and press reset button.(small black one next to ethernet connector.)

14 5. Open the drive appears as “BeagleBone Getting Started. in the Doc/hardware folder, there are reference manual, schemtic, pcb files, BOM..etc. reference manual is quite helpful, you can make a copy on your PC. In the Drivers are the beaglebone drivers for different system.

15 6. Open the README.htm with browser(beaglebone web recommand something else than IE), you will see a page contains most useful info, links.

16 7. Open your PuTTY, select “Serial” in the connection type. Then typing the COM number your beaglebone appear in device management. Set speed to 115200. You can save the session, same beaglebone on same PC normally has the same COM number. Then hit the Open.

17 8. When PuTTY started, you may have black terminal, simply hit “Enter”, the login screen will appear. Type “root”, press “enter”(no password), wait a second, you are now login as root. Knowing some simple linux commands is usful: “ls” will show folders “cd” change dir “cd..” upper dir “clear” you know it

18 From here you can operate your beaglebone as a linux PC, for example, type in “Vim” and press “Enter”, you can get into the editor. You will find it’s not that friendy to use, unless you have been trainned for this kind of command type editor. We are going to take another way. Connecting beaglebone through ethernet.

19 Connecting Beaglebone to router Connect beaglebone to router which has internet access.(without internet access will not hurt at this moment.) Make sure the router has DHCP service and giving IP to beaglebone.

20 There are 2 ways to know the IP of beaglebone. 1.Logging into your router and check the DHCP table, and find the IP of beaglebone. 2.Use PuTTY to login beaglebone through USB, type “ifconfig” and press enter. You will see the eth0 got an IP from your router.

21 Open your broswer, typing the address of your beaglebone, 192.168.1.56 in the example, it will lead to a 20 slide Beagelboard 101 presentation. Which can be viewed by pressing page up and page down.

22 The beagle101 along may not be clear for beginning beaglebone, but there are some very useful pages such as expansion header state. So it’s recommanded to go through the 101 for a quick look

23 Cloud9 IDE In the broswer, open port 3000 with your beaglebone address, in our example 192.168.1.56:3000 Could 9 is running on beaglebone, and doing better by adding more examples and helps. It supports bonescrpt and node.js.bonescrptnode.js This script IDE largely simplified programming on a linux beaglebone. We will experience with blinking a LED.

24 Click on the blinkled.js and the code will display on the right. If you have been playing with Arduino, you will find the codes are so similar. This code will blink the user LED3 and pin P8_3 In page 10 of beagle 101, there is a note on how to connect a LED on P8_1 Press the “debug” on the top, wait a while, you will see the led besdie the reset button start to blink. Press “STOP” can stop the program.

25 Summary: After seeing this demo, you image how easy to program a 720Mhz ARM? Even simpler than a MCU? Well. That’s the target, bone script is not yet there to fill up all your imagnations. But you can see there is digital input, digital output, analog input and even a server examples. The idea of TI is to make beaglebone programming as simple as Arduino. In real world of embedded linux, blink a led is some how more complicate than defind pin, set pin mode and write pin high or low. We will explan on this later. But the potential of runnung script on embedded system will largely decrease the difficulty of writing a application program on embedded linux. We will see more with python. You will find out programming a 720Mhz beaglebone is not that difficult.

26 How beaglebone IO is organized We have seen the simplicity of bonscript to blink the LED. But accessing a GPIO in a embedded linux system can be relatively complicate. a)Pin muxing refereing to Beaglebone System Reference manual 6.13(page 54), here it explains on those pins on header P8, you can see some pins are marked as timer, some are UART and some are GPIOs. These are the dafult setting on the Angustrom linux. Saying default means there are some other options. Yes, like some MCUs, a pin can have various functions depends on how you set up the usage in specific registers. Here with the angustrom linux on beaglebone, there are 8 possbilities(not every pin has 8 modes), called pin muxing. Unlike the MCU, the pin muxing here is SW related, not decided by the hardware. So, different linux could have different pin muxing. The developers of the Angstrom Linux image on the SD card selected their defaults to be the most commonly used ones by hobbyists, providing a good out-of-the-box experience. It’s possible to change the mux setting, since it’s control by linux, you may find them in the U-Boot configuration and some kernel modules, which is a very complicated job. fortunately it can be done another way with today’s linux.

27 Pin muxing table are table 9 and 10 for P8 and table 12 and 13 for P9 in the beaglebone reference manual

28 b)Mmap and files The Mmap stands for memory mapping, which is a technic used by linux, http://linux.die.net/man/4/memhttp://linux.die.net/man/4/mem it makes a mapping of entire physcial memory as files under /dev/mem The BeagleBone is built around the TI AM3359 ARM Cortex-A8 microprocessor, and breaks out many of its I/O pins to two 2×23 pin female headers, including 4 UART ports, 7 ADC inputs, 4 PWM outputs, a whole bunch of GPIO pins and more. The use of these peripherals is very well documented in the AM335x Technical Reference Manual. The use of each module is done through reading and writing to different 16- and 32-bit memory registers, whose addresses are given in the manual.AM335x Technical Reference Manual A Unix mmap can be used to create a memory map of the /dev/mem file, which allows read and write access to it through byte addressing. This way the module registers may be accessed by their addresses in section 2.1 of the AM335x reference manual. The most basic module to use is the GPIO module. Other modules get more complicated, but they are all very well documented in the Technical Reference Manual. The biggest difference is that many of the other modules have clocks which must be enabled before they can be used. This is done using the clock module registers, and is described in detail in chapter 8. Config of pins can be done through writing a file, changing a pin status or getting data from pins can also be done through reading specific file.

29 Knowing the principal, let’s take a look on how bonescript handle these blinking LEDs. Maybe you are not familiar with linux file commands, it doesn’t matter, here we wish you know the basic. Go back to the cloud9 and open the file in bonescript/node_modules/index.js

30 This table contains 3 important pieces of information: the label that bonescript uses to identify the pins (P8_1, P8_2, etc) the GPIO pin number (P8_3 is gpio1+6, or 38) the mux label (P8_3 is gpmc_ad6) The GPIO pin number tells you the directory name you will use to read from or write to the pin. The mux label tells you the filename you will use to read or write the mux setting. Also open the file index.js, where the libraries of bonescript are: At the line 145(this could be different in different version, with the angustrom of beaglebone A6A version it’s lin 145, you may reach by seraching pinMode), here pinMode function take care of pinmuxing, line 150 and 151 shows you the files this function is writing to or reading from: var muxFile = '/sys/kernel/debug/omap_mux/' + pin.mux; var gpioFile = '/sys/class/gpio/gpio' + pin.gpio + '/value'; Line 179 you see it wirte a 0x07 to the file of pin mux: pinData |= (mux & 0x07); try { var fd = fs.openSync(muxFile, 'w'); fs.writeSync(fd, pinData.toString(16), null); }

31 Some where lower in the line 236 you can find the digitalWrite, which bonescript used to write GPIO: digitalWrite = exports.digitalWrite = function(pin, value, callback) { var gpioFile = '/sys/class/gpio/gpio' + pin.gpio + '/value'; if(pin.led) { gpioFile = '/sys/class/leds/beaglebone::' + pin.led + '/brightness'; } if(callback) { fs.writeFile(gpioFile, '' + value, null, callback); } else { fs.writeFileSync(gpioFile, '' + value, null); } return(true); } Notice that the user led is a seperated file, as we explained, pins are SW related and can be arranged.

32 You can see it’s actually writing a value in to the gpioFile, but which one? The code to set that “path” property also in index.js, just below where the pin mux setting was done lin 207. The first thing it does is try to write to a file named “export”, specifically, “/sys/class/gpio/export”. The value written is the GPIO pin number, which you’ll recall was specified in the table earlier in index.js. For Port 8 Pin 3, it was defined as gpio1+6, or 38. The export file is a funky weird file: when you write a pin number to it, it (well, the kernel process which monitors that file) creates a directory and a bunch of files that provide interfaces for accessing the pin. The directory is created at/sys/class/gpio/export/gpioNN. In the case of Port 8 Pin 3, that’s/sys/class/gpio/export/gpio38. For the purpose of using a GPIO pin, the two most important files in the gpioNN directory are named direction and value.

33 The direction file determines whether the pin is going to be used for reading or writing. As mentioned earlier, you can’t use a pin for reading without setting flipping a bit in the mux mode setting, so our only choice at this point is output. The bonescript code writes the value “out” to the direction file (i.e. to /sys/class/gpio/export/gpio38/direction). The code then saves the path to the value file (i.e. /sys/class/gpio/export/gpio38/) in the pin’s path property. This is what this line does: fs.writeFile(gpioFile, '' + value, null, callback); It writes a 1 to the value file (i.e. /sys/class/gpio/export/gpio38/value) to set the pin high (and the turn the LED on) and a 0 to set it low (and the LED off). Beside these, bonescript also handle errors. That is what we saw below the catch(ex)

34 Summary We have saw the basic structure of beaglebone’s IO, and how it’s operated under linux using the technic of memory mapping. To make a interface function as we used to use in MCU, it required more understanding on how linux is operating, which still make the process relatively complicate. Fortunately these days script languages developped at speed of rocket. Using script language can largely reduce the effort, and leave developper to focus on their creation.

35 Using Script language Of course you can use C or C++ for programming an embedded linux, it has been done before, but required lots of works. We have demostrate how to make a pin works as GPIO without using script. And you also saw at beginning how easy it was to do the samething in bonescript. the words “script language” is something very difficult to translate into chinese, here is a descript on it: “ A high-level programming language that is interpreted by another program at runtime rather than compiled by the computer's processor as other programming languages (such as C and C++) are.” Yes, script language is running on a runtime. Program can run faster if written in C or C++, but the development and progress will take much more time than script language. Another advantage of using script language is that most of script languages have lots of libraries or functions shared between users. Which preventing from doing repeated work. And in most of case, with certain conditions, script language provide cross platform ability. For example Python program can work on windows, Mac OS, linux system even android. But hardware dependance still exists, for example, using uart on windows will have different configuration than using it on beaglebone. The angustrom linux on beaglebone has already Python 2.7 on it, and there are good libraries for using beaglebone’s IO. Here after we will start some real hands on with python on beaglebone.

36 Summary Script language has several advantages: – Faster programming – Functions and library sharing – Possibility of crossing plat form – Easy to use for web application

37 Using Python on beaglebone Before going depper on Python,let’s start with some partice on terminal, get your beaglebone linked with PC through USB and log in to beaglebone with PuTTY: Type in after # python –V and hit enter, it will reply Python 2.7.2, which is the version of python. There is Python 3.x already, but 2.7 and 3.x are some how different on some functions.

38 Key in python and hit enter, you will see a prompt as “>>>”, this is the python prompt. Under this prompt we can execute python command. Following picture shows a simple math. It seems like the old basic, but script language can do much more then is. Type in quit() will stop python. You can also use editor to make a file with extension “.py” and execute it with python xxx.py

39 It’s recommand to get a book for much better python. It’s not easy to find books talk about python in chinese, here in Taiwan. Here we list 2 translation publish, for your reference: Head First Python( 深入淺出 Python) O’REILLY 基峯資訊 Programming in Python ( 精通 Python) 基峯資訊 Although it’s good to have a book on hand, but google is also a very handy tool when learning script language. There are plenty tutorial on net, if you can’t an answer on net, it would be also hard to find a good answer in books. Remember, these days, programming most open source stuff is not about only getting reference from others, participation on discussion and share your works with others are also important. After all, this is why we can progress together and faster. Python has also a systematic way to share codes between users, PyPI. We may not be skilled enough to create a useful library now, but please bear in mind, sharing is an important factor in progressing.

40 Python libraries on beaglebone Most of script languages on beaglebone use the memory mapping (mmap) in linux system. There are serveral projects: Bonescrpt using javascript(node.js) Bonescrpt PerlBone using Perl PerlBone Rbone using Ruby Rbone Hwio usig Golang Hwio beagleboneIO and beaglebone-CLIB using C beagleboneIObeaglebone-CLIB pyBBIO, mrBBIO and beaglelib using python pyBBIOmrBBIObeaglelib Some others… All these are open sourced projects, I choose pyBBIO for my python experience on beaglebone, since the documentations are pretty clear, examples are not complicate and easy to use. Owner is intend to make the programming of beaglebone as similar as a MCU programming(arduino precisly). And most important, Owenr (Alexander Hiam ) keep on updating the library. This will make the library getting strong and complete. The library cover today from GPIO to web server, although SPI and IIC is still on the way, but you can already make amazing things with your imagination.

41 Enviroment set up we are going to do this programming in windows, the hardware connection is as following. Windows PC

42 you should have now PuTTY installed on your PC, we now need a file transfer tool which we have introduced previously WinSCP, download and install it. This tool is open source and have multi language version. For traditional chinese: http://www.azofreeware.com/2008/03/winscp-41-beta.htmlWinSCP http://www.azofreeware.com/2008/03/winscp-41-beta.html remember how to get beaglebone IP address using PuTTY to log in as root? After log in, use ifconfig. Note down the eth0 IP adress(192.168.1.56 in this example)

43 Open your WinSCP type in the IP address of your beaglebone, user is root, leave the password blank. For the first connection, windows will pop up an warning, reply yes to approve the connection.

44 winSCP will locate the server on beaglebone, and log in as root. When password window pop up, leave the pass word blank and press yes. The default pass word is blank, if you wish you can add some other users and log in as other users with password. Which is as same as linux, using command as # useradd user1 # passwd user1 Then system will ask you to input 2 times of password. You can also add password to current root. #passwd And to input 2 times of password

45 Then you will see the WinSCP window as below: on the right is the file system on beaglebone, left is the one of your PC. We will constantly use PuTTY and WinSCP these 2 windows.

46 Once setup, the last thing is to make sure that your beaglebone has access to internet. To make sure it, you can ping a website. Google.com is what I used to use. Using PuTTY and type in ping google.com Then beaglebone is keeping pinging google.com, you can use Ctrl-C to stop it.

47 WinSCP has a built in editor, it also allow you to use you selection of editor. I’m using a GNU editor Emacs (http://www.gnu.org/software/emacs/)http://www.gnu.org/software/emacs/) To add editor in to WinSCP, first install the editor of your choise on your PC. And find out where is it’s exe program. In WinSCP, under option/preference windows, select editors on the left side. Select add. Then select external editor and give the path of the exe file of the editor. You may also set the editor with releation to extension file name.

48 Install pyBBIO Make sure your beaglebone is up and connected to internet as previous descript. Log in as root through PuTTY. pyBBIO is a library of python on beaglebone, it use the technic of memory mapping, it also use other libraries of python, such as python-distutils(distribution utilty for update), python-mmap and python-pyserial, so the 1 st step is to install these parts: Type in following command after #: # opkg update && opkg install python-distutils python-mmap python-pyserial It will start to down load from internet and install it, at the end you should see it’s configuring and back to prompt #

49 Then we will get the code from net: # cd ~ # git clone git://github.com/alexanderhiam/PyBBIO.git The whole file system will be down loaded(cloned) to your beaglebone. You can use windows copy and past on PuTTY, copy the command from other windows, move to PuTTY, right click, the command is already on, then press enter.

50 After it’s done, type in # ls which is a list command, you will see there is a PyBBIO floder. Now we are going to install it: Change to PyBBIO dir: # cd PyBBIO The ls (ls), you will see a setup.py,.py is the extension file name of python file. Type in the following, this is normally how python program installed. # python setup.py install It should be correctly install as following pic

51 Let’s use one of the examples to see if the installation is correct. Change to examples floder: # cd examples If you do #ls, you will see all the example of this pyBBIO version 0.5 As usual, we start with blink LED, command as following: # python blink.py Check the user led USR2 abd USR3, it will blink. And there is no prompt, now, to stop the blink program, use CTRL-C And # prompt should be back. Here is your first python program on beaglebone.

52 PyBBIO is a constantly updated library, the code is put on git, https://github.com/alexanderhiam/PyBBIO So we can easy use git for update PyBBIO with few lines of command: # cd ~/PyBBIO # git pull # python setup.py install

53 Current pin configuration on beaglebone under PyBBIO

54 Editor through WinSCP Let’s check out how this blink.py looks like in pyBBIO, start your WinSCP, it should now have an additional folder “PyBBIO”

55 Click on the folder as operating in windows, go to: /PyBBIO/examples, and double click on blink.py, it would pop out the editor and open the file like this. (I have modified the editor option to use emacs.)

56 As you can see, the program is composed in 4 parts. The target of PyBBIO library is to make a python library like a Java IDE “Arduino”, so it would have a very similar format and work on to get similar usage on most functions. Taking blink.py as example: 1 st part: importing library or set up some constants… (# will remark the rest of the line) # Import PyBBIO library: from bbio import * 2 nd part: define a setup(), the setup() is basically what you run once when the program started, so most pin define, or interface initial is here. (the function in python has no {}, it use colone nr to note this. So make sure you do the right indent as a good programmer should do. def setup(): # Set the two LEDs as outputs: pinMode(USR2, OUTPUT) pinMode(USR3, OUTPUT) # Start one high and one low: digitalWrite(USR2, HIGH) digitalWrite(USR3, LOW)

57 3 rd part: the loop, where you put what need to done repeatedly. # Create a main function: def loop(): # Toggle the two LEDs and sleep a few seconds: toggle(USR2) toggle(USR3) delay(500) 4 th part: tell python to start with setup once and repeat loop # Start the loop: run(setup, loop) The program looks relatively simple, but as we have explained, there are a lot of open file read/write and close files and error management. But when accessing digital pin, PyBBIO use register access for read and write the pins. If you modify or write a file, and wish to save it through winSCP, when you press save for the first time, it will pop out a window asking for password, this window has to be answered, otherwise nothing will be saved.

58 Digital pins We have saw how to use digital pin to control LED, it pretty straight in PyBBIO, first, you define the pinMode, which include pin nr and direction. The simply use digitalWrite to set HIGH or LOW on the pin to control LED. With similar way, we can also read status of a pin, to be used as button in put. Still, with WinSCP, in PyBBIO/examples, you can find digitalRead.py double click to open it.

59 You see the program is pretty much the same as blink.py in the loop you can find the use of digitalRead(GPIO1_6) to read the state and write to USR3 state = digitalRead(GPIO1_6) digitalWrite(USR3, state) OK, it seems pretty straight, but some how strange if you get used to use MCU. The state is a variable, but it was not declare, not in the loop nor in the setup nor else where. In Python, declare is not necessary, you can grape a variable and use it, no need to worry it’s data type, as long as you follow the naming rules. In consequence, there are a lot of functions in Python to convert data into the type you want. No worry if you wish to use certain data type, this python functions works both on PC and beaglebone, so you can easily test the program on PC before put it into beaglebone.(So as a lot of array/list functions)

60 Reading ADC The ADC on beaglebone is targeted to be used for touch panel, so the max voltage is set at 1.8V. There are 8 input through a multiplexer, the ADC is in 12bits (0~4095). One is used internally. So there are AIN0~AIN6 on header P9, there are is also 1.8V on Pin32 of header P9 which can be used as VDD_ADC. Pin 34 is VDD_GND. When connecting anything, it’s recommended to turn off power. Use a Variable Resistor, like shown, and connect A to VDD_ADC 1.8V, and connect B to VDD_GND, W connect to AIN0 pin 39 of header P9. Take another one connect A and B as previous ones and connect W to AIN2 pin 37 on header P9..

61 Find a example called: analog_test.py, let’s take a look on it. In this example, we have set 2 constant variable for AIN0 and AIN2 only for more readilibity. # Import PyBBIO library: from bbio import * pot1 = AIN0 # pin 39 on header P9 pot2 = AIN2 # pin 37 on header P9 If we have nothing to do in the function setup(), we give it a pass command def setup(): # Nothing to do here pass In the loop(), we do 3 things: 1. Read out ADC values, it’s a 12 bits value, ranging 0~4095 # Get the ADC values: val1 = analogRead(pot1) val2 = analogRead(pot2)

62 2. Convert ADC value to voltage, which as a relation => 1.8V in 4096 step, here we use a convenient function inVolts(), you can find the calculation in the bbio.py, try to find def inVolts. # And convert to voltages: voltage1 = inVolts(val1) voltage2 = inVolts(val2) 3.We do the print, to print out value from PuTTY terminal print " pot1 ADC value: %i - voltage: %fv" % (val1, voltage1) print " pot2 ADC value: %i - voltage: %fv\n" % (val2, voltage2)

63 Type in: (note: you type in few letters and press “Tab” linux will try to fill for you) #python analog_test.py Terminal will out put as following, it print out ADC value and voltage in float! CTRL-C can interrupt the program.

64 In real world, you will need to filter your ADC value, since the reading can oscillate some how. And the ADC here is only 1.8V, it can be incluenced by other noise easly than a 5V ADC. There are several ways of filtering ADC value, some are using averaging(get certain amout of reading and do averge), some prefer to introduce a digital low pass filter to filterout certain frequency. Hardware low pass filter is also a good choise. Some simply right shift the reading of ADC to reduce the sensitivity.

65 Using UART port There are totally 6 UART on AM3359, one is used to connect to USB for our USB ternimal access. The other 5 can be found on the 2 headers. In PyBBIO the initial make Serial1, Serial2, Serial4 and Serial5 ready to be used. PyBBIO library make the uarts to be used as simple as possible, so there is no support on flow control such as CTS/RTS. Detail of usage of UART can be found here: https://github.com/alexanderhiam/PyBBIO/wiki/serial The BeagleBone's UART modules use 3.3v logic levels; applying voltages greater than 3.3v to the UART pins can cause permanent damage! TX/RX is normally pulled high, so it’s easy to know the voltage of the signal line using meter. Pin location of UARTs: Header P9: Serial1 TX - P9.24 Serial1 RX - P9.26 Serial2 TX - P9.21 Serial2 RX - P9.22 Serial4 TX - P9.13 Serial4 RX - P9.11 Header P8: Serial5 TX - P8.37 Serial5 RX - P8.38

66 Let’s take a look on the example:serial_echo.py to see how to use the library:

67 In the setup we start the serial port 2 with command Serial2.begin(), This command is included in bbio.py, it does pin muxing, and config the baud rate, port nr, timeout..etc. In PyBBIO, we use in fact the pyserial library of python, simply make it suit for beaglebone and simplify into few useful commands. def setup(): # Start Serial2 at 9600 baud: Serial2.begin(9600) In the loop, you see first we check if any thing received in UART buffer with the command Serial2.available(), the set up a empty array called data. In python data type in array can be mixed. if (Serial2.available()): # There's incoming data data = ''

68 We can use Serial2.read() to read out all the bytes in the buffer. The 5 us delay is not absolute necessary, but it would be nice to add for operation stability. data += Serial2.read() operate array just like the number in C, which means the old array appends a new byte into it. When there is no more byte in the buffer, we print it out from terminal and use Serial2.write(data) to send data out through serial2. while(Serial2.available()): # If multiple characters are being sent we want to catch # them all, so add received byte to our data string and # delay a little to give the next byte time to arrive: data += Serial2.read() delay(5) # Print what was sent: print "Data received:\n '%s'" % data # And write it back to the serial port: Serial2.write(data)

69 In previous example, we saw few very simple usage of serial, we init the uart port with Serial2.begin(9600), and use Serial2.available() to check if there is any thing arrived. Serial2.read() to read out 1 byte at time. And Serial2.write() can be used to send a array of bytes. There are also some functions for Serial, such as: Serialx.peek(): return the next byte in the buffer, but does not remove the byte from buffer. Serial.flush(): take out the bytes in the buffer. There are 3 ways to put data out through uart, if you are sending an byte array, write() is the good one to use. Writes given data to serial port. If data is list or string each element/character is sent sequentially. If data is float it is converted to an int, if data is int it is sent as a single byte (least significant if data > 1 byte). Returns the number of bytes written.

70 Serialx.prints() is easy to use when you wish to select the data formatting. Prints string of given data to the serial port. Returns the numberof bytes written. The optional 'base' argument is used to format the data. Examples: Serialx.prints(78, BIN) gives "1001110" Serialx.prints(78, OCT) gives "116" Serialx.prints(78, DEC) gives "78" Serialx.prints(78, HEX) gives "4E" Serialx.prints (1.23456, 0) gives "1" Serialx.prints(1.23456, 2) gives "1.23" Serialx.prints(1.23456, 4) gives "1.2346“ Serialx.println() given data to the serial port. Returns the number of bytes written. The optional 'base' argument is used to format the data as previous one. To test uart, we will need another device on uart, such as a FTDI USB to Uart board, which you can connect to PC and open this uart with PuTTY. But make sure the one you have is 3.3V. And connect TX of FTDI to RX of beaglebone, RX of FTDI to TX of beaglebone. Or you can try to write a program usig 2 uart on beaglebone.

71 PWM Pulse-width modulation (PWM) is a commonly used technique for controlling power to inertial electrical devices, made practical by modern electronic power switches. Dimming LED is a very common usage, using H-bridge and 2 pwms, it’s easy to drive a DC motor.With some modification it can also control RC servos. The BeagleBone has 8 PWM outputs. These come from three EHRPWM modules (two output each) and two ECAP modules with one output each. The “EHR” part means Enhanced High Resolution(16 bit). ECAP= Enhanced Capture(32 bit). Today, PyBBIO supports 2 EHRPWM(1 and 2) module which allow us to use 4 3.3V 16-bit pwm out puts. PWM pins Header P8: P8.13 - PWM2B P8.19 - PWM2A Header P9: P9.14 - PWM1A P9.16 - PWM1B There are a variety of PWM settings exposed through the file system, as described in the PWM Driver’s Guide, but the two key ones are period_freq, which is the frequency in Hz, and duty_percent, the duty cycle setting.the PWM Driver’s Guide

72 PWM clock is init by linux kernel, PyBBIO using pwmWrite() or (analogWrite() same as pwmWrite())command to set resolution and duty cycle. pwmWrite(pwm_pin, value, resolution=RES_8BIT) Sets the duty cycle of the given PWM output using the given resolution. The resolution defaults to 8 bits, so if no resolution is given the values in the range 0- 255. Resolution may be one of the defined RES_8BIT: then the value need to be 0-255 RES_16BIT: the values is 0-65535 PERCENT: to set the duty cycle in percent, or any integer greater than 0. 'value' should be an integer. pwmFrequency(pwm_pin, freq_hz) Sets the frequency in Hertz of the given PWM pin's module. Each module can only run at a single frequency, so PWM1A and PWM1B will always be running at the same frequency, and likewise for PWM2A and PWM2B. If not called, the frequency of each module will default to 100kHz. A nice example is fade.py it dim a LED with + on PWM1A(P9.14). Please add a resistor of 100~300Ohm to limit current.

73 Let’s see the demo of fade.py 1.Prepare a LED with a 100~200Ohm resistor connect to LED serially. Longer leg of LED is positive lead, you can add the resistor to positive lead or negative lead. 2.Connect the positive lead of LED to P9 pin14, which is PWM1A, and connect the negative lead to P9 pin2(or Pin1) which is GND 3.In your terminal type in python fade.py, you will see the LED light up and fade away repeatly.

74 Servo control: RC servo is controlled mostly by a PWM signal at 50Hz, and change it’s angle depends on the signal high duration, mostly between 0.9ms to 2.2ms. But different servo could have different range for the signal high duration. PyBBIO also include a servo library to control servo motors by using PWM. Which means there are 4 pins, PWM1A, PWM1B, PWM2A or PWM2B, and PWM1A and 1B must run at same frequency. You can see an easy example in Servo_sweep.py, before set up, we import Servo: from Servo import * Then, it create a servo1, using mostly the default setting. # Create an instance of the Servo object: servo1 = Servo(PWM1A) # We could have left out the PWM pin here and used # Servo.attach(PWM1A) in setup() instead. And run servo1.write(angle) If you look in to the code of servo library, it use 50Hz as deafult frequency, 0.5ms as min position, 2.4 as max position. And map to 180 degree. Your servo may not fit this spec, you can fine tune the max_ms and min_ms to get it work with your servo.

75 Testing the servo library need a RC servo and some attention. General RC servo take 5 V power, and 5V signal. The signal level of beaglebone’s PWM is 3.3V, which is just enough for 5V logic to read as a high(5*0.6=3.0). On beaglebone P9, pin 5 and pin 6 are VDD_5V, which is connected to the 5V power jack on board. We can connect servo power line to these 2 pins, but these servos some how need big current to make it works, so you will need to plug in a 5V adapter with enough current to make sure the servo works. Nornal or small size servo without load, 5V 2A should be fine. The brown line of servo is GND connected to P9pin2, red one is 5V connected to P9pin6, orange one is singal connected to P9pin14. In terminal Type in: python Servo_sweep.py You will see the servo sweeping around.

76 Web service We have see most MCU-like function on PyBBIO, PyBBIO also contain a simple interface to make your own web service. So that you can access your beaglebone with a browser on a device in the same network. Under Python, create a web service is not very difficult, Python comes with a web server in http.server, SimpleHTTPserver library. These webserver are mostly HTTP/1.1-compliant, WSGI (web server gateway interface) or CGI (common gateway interface). Once the web server is built, we will need UI on your web, it should be done in HTML, but we are not going into that part. Once you get familiar with web service you will be able to make fancy web service with some other web service frame work on beaglebone. such as Flask, Cherry Py and some other template engine. There are plenty of them.FlaskCherry Py Let’s start with simple one in PyBBIO and see how we can access our beaglebone from an other internet device and control things connected to beaglebone IO.

77 BBIOServer library BBIOServer create webservice and provide RequestHandler to handle BBIO function calls. And the UI templete is quite simple but clear, it has a title on the top, a total pages menu on the left. Right side is where you put your contains. For the contain, there are 4 major functions to be used: you can add text to tell message, add a button to do something. Or add a monitor to show something. And of course you can also add text input.

78 Structure of BBIOServer in program: BBIOServer is acturally a parallel program running on beaglebone once it’s called. So it only need to be call once, So it would be placed in setup() not loop(). We will go through the BBIOServertest.py example, but let’s see first what has to be done. 1.1 st thing to do is to import the library, since BBIOServer is written seperately, so we need to import it. 2.Create an instance of BBIOServer class. 3.Create pages, and adding what we wish to add in the page. 4.Start the server. Let’s see how these are done in the BBIOServer_test.py: you can see we do the 1 st and the 2 nd thing by these lines: # First we must import PyBBIO: from bbio import * # Then we can import BBIOServer: from BBIOServer import * # Now we create a server instance: server = BBIOServer()

79 server = BBIOServer() create an instance of BBIOServer BBIOServer() has some options: BBIOServer(port=8000, verbose=False, blocking=True) The port argument may be used to run the server on a port other than the default of 8000. If verbose = True a log of every request will be printed. If blocking = False the server will run in non-blocking mode, meaning the main loop() routine will be executed as normal while the server runs in the background. blocking=True will not run loop(). You can of course selecting some other port Nr, but some port Nr are used for some services, and you may need to use these port for other application on your beaglebone, such port 22 is what we used for shell in winSCP. Some more interesting port Nr information can be found here: http://www.chebucto.ns.ca/~rakerman/port-table.html

80 1 st Page: Then in the file you can see we created 1 st page call home with title "PyBBIO Test"and added a text on that page # Create our first page with the title 'PyBBIO Test’ home = Page("PyBBIO Test") # Add some text to the page: home.add_text("This is a test of the BBIOServer library for PyBBIO."+\ " Follow the links at the left to test the different pages.")

81 2 nd page: A 2 nd page is created, page name is text with title ”Text Input”. As you can see the name of the page will be serve to create add_text or add something else. And the text in the Page() will be show as title on top of the page and page list on the left. # Create a new page to test the text input: text = Page("Text Input") text.add_text("Press submit to send the text in entry box:") # Create the text entry box on a new line; button will say 'Submit', # and when submitted the text in the box will be sent to print_entry(): text.add_entry(lambda text: print_entry(text), "Submit", newline=True).add_text seems pretty straight, let take a look of.add_entry in bbioserver library: def add_entry(self, function, submit_label, newline=False): Add a text entry box and a submit button with the given label to the current position in the page. When submitted, the given function will be called, passing it the text currently in the entry. The function must take take a value, e.g.: 'lambda s: print s'. If newline=True the text will be put on a new line, otherwise it will be stacked on the current line. So lambda text:print_entry(text) is the function. What lambda does is putting the text(what you type in the entry) in to the function print_enrty(). Lambda is a function of python, you can google for more detail.

82 Here is how the page 2 looks like:

83 3 rd page: 3 rd page is created with name=io and title is “I/O” at about line 55. io = Page("I/O") # Make a LED control section using a heading: io.add_heading("LED Control") io.add_text("Control the on-board LEDs", newline=True). io.add_heading("ADC Readings") Here you can see we add a heading “LED Control” and “ADC Readings”, it’s slightly different from add-text on the web.

84 On 3 rd page, we add a button to toggle LED USR2 and USR3, and add a monitor to show the status of LEDs. In the red circuit you see a button of toggle LED and current state, is infact 2 functions in the code, and only 2 lines of code. # Add a button on a new line with the label 'Toggle USR2 LED' that will # call 'toggle(USR2)' when pressed: io.add_button(lambda: toggle(USR2), "Toggle USR2 LED", newline=True) # Add a monitor which will continually call 'pinState(USR2)' and # display the return value in the form: 'current state: [value]': io.add_monitor(lambda: pinState(USR2), "current state:")

85 Let’s see how it’s done to toggle the LED: io.add_button(lambda: toggle(USR2), "Toggle USR2 LED", newline=True) add_button(function, label, newline=False) Creates a button with the given label at the current location on the page. function must be a callable object, and will be called when the button is pressed. If newline = True it will be forced to the next line, otherwise it will stack to the right of the previous object if there is room on the page. The whole explaination seems ok beside this: function lambda: toggle(USR2) seems strange. Well, lambda is a powerful tool in python to create anonymous functions (i.e. functions that are not bound to a name) at runtime. You can find toggle() in BBIO.py, but here we use it without attached to a name(anonymous functions ). What is a function attached to a name? For example, add_button() is a function in BBIOServer, and we use it as io.add_button(……). And here we wish to use the toggle() without attached to a name, so we introduce lambda as construct. To creat a function and call it at same time.

86 For knowing the LED curent status in line 66: # Add a monitor which will continually call 'pinState(USR2)' and # display the return value in the form: 'current state: [value]': io.add_monitor(lambda: pinState(USR2), "current state:") Page.add_monitor(function, label, units='', newline=False) Adds a label to the current position on the page in the form: "label value units" where value is the latest return value of the callable object function which will be repeatedly called. If newline = True it will be forced to the next line, otherwise it will stack to the right of the previous object if there is room on the page. Value is being updated about every 200ms. Again, pinState() is a function of BBIO, here we use lambda to use it. As you can see, if necessary you can also add ‘units’ at the end of it, simple put the unit(like ‘degree’,’second’) in it.

87 Once you understand how the LED control works, the ADC reading is simply adding some add_monitor(), the only thing change is the function called through lambda. io.add_monitor(lambda: analogRead(AIN1), "AIN1 value:", newline=True) io.add_monitor(lambda: voltage(AIN1), "voltage:", units="v") At the end of setup(), we will user server.start to start the webserver with the pages we created. server.start(home, text, io) We have created the server instance in blocking mode: server = BBIOServer() So, server will keep running when we use run(setup, loop) to start the program. It will stop when we use CTRL-C. At which point it will continue on to loop(), so if we want our program to stop completely we need to use the PyBBIO stop() function. Or we leave nothing in our loop() function, we need to use the pass statement to keep Python happy.

88 In pratical usage, you will run the server in non-blacking mode, and do some input reading(ADC, GPIO, UART, SPI…etc), processing some calculation, and finally do some out put(GPIO/UART/PWM…etc). As you understand now, A program in PyBBIO is composed by several programs( such as web server, setup(), loop()), it’s also important to know how to pass variables from one to another. The simple way(maybe not always the good one) is to use global variable. We will come back for this. Let’s try out the webserver we just explained.

89 I added a VR like we explained in previous section ADC, Red to P9pin32, VDD_ADC. Back to P9pin34, VDD_GND. White to P9pin39, AIN0. You can also hoop up a second on on AIN1,P9pin40.

90 Log in to your beaglebone, go to PyBBIO/examples/ Then type in: python BBIOServer_test.py Perss Enter Now, the prompt is dispeared, the server is already running. If some wrong, python will pop out the error message, then you need to check out the code.

91 Now, take a PC or tablet connected to the same router,start your borwser, IE is not recommanded, chrome,firefox and others are fine. Remember the how to get the IP address of your beaglebone? Here we put in it’s IP address and assign port 8000(where we start the webservice) In my example the address of beaglebone is 192.168.1.56, here is what I put: 192.168.1.56:8000 It would redirect you to the home page of our PyBBIO Test

92 Go to Text Input page but clicking the menu on the left. In this page we used add_entry() to create a text input area, and call lambda text: print_entry(text) to print the text to teminal when the Submit button is pressed.

93 Type in some thing, press Submit, you will find what you type in the PuTTY terminal. Now you have a templete to input data/info to your beaglebone from web, to do some thing more complicate.

94 Click to the I/O page, you can conrol the USR2 and USR3 LED with these 2 buttons. Truning the VR, we will see the AIN0 value changes.

95 The web service demo is done in 3 pages, but covered mostly basic usages. You can do your webservice with your model, view and control. There is another webservice example, which is serial_server.py It shows you how to use webservice to access UART on beaglebone. Which is very useful in the aera of automation, internet of thing. You can use the uart of beaglebone to connect to automation unit through RS485, or connect zigbee coordinator to form a IOT network. There are many good examples on internet using beaglebone for these type of application, and mostly are open source, it’s also helpful to see how others do the job. http://ninjablocks.com/http://ninjablocks.com/ is a very good example… The only limitation is your imagination.

96 Additional information: Basic function of PyBIO. these functions are written in bbio/bbio.py, we used some of them, here are some more detail. 1. GPIO: pinMode(gpio_pin, direction, pull=0) Sets the direction of the given digital pin as either INPUT or OUTPUT. The optional 'pull' argument can be used to set either a pull-up or pull- down resistor on the pin if setting it as an input: pull = -1 for a pull- down, pull = 1 for a pull-up, and the default of pull = 0 for neither. digitalWrite(gpio_pin, state) Sets the state of the given digital pin to either HIGH or LOW. The pin should already be configured as an output. toggle(gpio_pin) Sets the state of the given digital pin to the opposite of its current state. The pin should already be configured as an output. digitalRead(gpio_pin) Reads and returns the state of the given digital pin as either HIGH or LOW. The pin should already be configured as an input. pinState(digital_pin) Returns the current state of a the given digital pin if it is configured as an output, or None if it is configured as an input.

97 2. ADC functions: analogRead(analog_pin) Takes a reading of the given analog pin and returns the 12-bit value. inVolts(adc_value, bits=12, vRef=1.8) Converts the given ADC value to a voltage, according to the given number of bits and reference voltage, and returns it. The default values match the built-in ADC. 3. PWM functions: analogWrite(pwm_pin, value, resolution=RES_8BIT) Sets the duty cycle of the given PWM output using the given resolution. The resolution defaults to 8 bits, so if no resolution is given it acts like Arduino's analogWrite(), taking values in the range 0-255. Resolution may be one of the defined RES_8BIT, RES_16BIT to take advantage of the 16-bit timer (values of 0-65535), PERCENT to set the duty cycle in percent, or any integer greater than 0. 'value' should be an integer. pwmWrite(pwm_pin, value, resolution=RES_8BIT) Exactly the same as analogWrite(); for those who don't like 'analog' in the name. pwmFrequency(pwm_pin, freq_hz) Sets the frequency in Hertz of the given PWM pin's module. Each module can only run at a single frequency, so PWM1A and PWM1B will always be running at the same frequency, and likewise for PWM2A and PWM2B. If not called, the frequency of each module will default to 100kHz.

98 pwmEnable(pwm_pin) Enables the given pin for output. Called automatically by analogWrite(), so shouldn't generally need to be called. pwmDisable(pwm_pin) Disables given PWM pin. Unlike calling analogWrite(pwm_pin, 0), calling this will relinquish control of the pin, allowing it to be used by another process. 3. Serial begin(baud, timeout=1) Initializes the serial port at the given baud rate. The optional timeout argument is the number of seconds to wait when reading from the RX line before giving up if no data is present. If timeout = 0 then read() will block until data is received. This method must be called before any of the below methods will work. end() Closes the serial port. This should be called prior to reinitializing at a new baud rate. available() Returns the number of bytes available in the receiving buffer. read() Returns the next byte from the receiving buffer, or -1 if the timeout set in begin() is reached before any data is present.

99 peek() Returns the next byte from the receive buffer without removing it, or -1 if no data is available. flush() Removes all data from both the TX and RX buffers. prints(data, base=None) The equivalent of Arduino's Serial.print(), but the print symbol is reserved in Python. Prints the given data to the TX line. If the data is a string it is printed as-is. If it is an integer then it may be formatted by passing one of the formatting constants listed below as base, where the default is DEC. If it is a float then base should an integer of the number of decimal points to be printed, where the default is 2. If data is of any other type, e.g. a list or dictionary, it is converted to a string then written. println(data, base=None) This behaves the same as prints(), but the data is followed by a carriage return (**\r**) and a new line (**\n**). write(data) If data is a number it is written as the the least significant byte of its integer value. If it is a string, list or tuple, each value is written sequentially, left-to-right, following the same rule if they are numbers. Returns the number of bytes written, or 0 if given an unsupported type.

100 4. Software SPI: shiftIn(data_pin, clk_pin, bit_order, n_bits=8, edge=FALLING) Receives the given number of bits from a slave device, generating the clock signal on clk_pin and reading data from data_pin, and returns as an integer. bit_order sets the endianess of the data, and should be either MSBFIRST or LSBFIRST. edge is the edge which triggers the device to write the next bit. shiftOut(data_pin, clk_pin, bit_order, data, edge=FALLING) Sends the given data to the slave, generating the clock signal on clk_pin and reading data from data_pin. bit_order sets the endianess of the data, and should be either MSBFIRST or LSBFIRST. edge is the edge which triggers the device to write the next bit. 5. time related: millis() Returns roughly the number of milliseconds passed since run() was called. micros() Returns roughly the number of microseconds passed since run() was called. delay(ms) This pauses a program for the given number of milliseconds. delayMicroseconds(us) This pauses a program for the given number of microseconds.

101 Other library in PyBBIO PyBBIO provide some basic functions, Beside the BBIOServer and Servo libraries we demonstrated, there are coming up with some new ones, you may also develop some to contribute! ADS786x library ADS7866~ADS7868, ADS7886 are analog to digital converters of TI, SPI interface. This series of ADC has different voltage range(1.2~3.6~5.25V), and different resolutions(8- 12 bits). DACx311 library ADC5311~DAC8311 are different resolution (8-14bits) digital to analog converter. Allow you to out put a voltage out put. MAX31855 library MAX31855 is a chip used to convert thermocouples to digital temperature information.

102 2 more things are helpful when you go for real design in Python: 1.Global variable In our program, it’s composed of setup() and loop(), it’s infact 2 different program, so if we need to pass data from one to the other, we will need to process with global variable. It’s not difficult, there is an example on it: switch.py Before setup(), we set 2 global variable with initial value. LED_STATE = 0 # 0=green LED lit, 1=red LED lit. SW_STATE = 0 # =1 when switch pressed; only change LED_STATE once per press Then when using them in loop() or some where, simple declare on the first line these are global: def main(): global LED_STATE, SW_STATE # Python requires you explicitely declare all global variables # that you want to change within a code block using the global # statement; see: # http://docs.python.org/reference/simple_stmts.html#the-global-statement

103 2. multiprocessing Our beaglebone is running linux, and you are capable to run some different program at same time. You can do this in linux with job management. If you want to run different things in the same program, then Python provide a very powerful tool called multiprocessing. PyBBIO based on this, make a easier to use interface(so called wrapper). With clear explanation, it would be helpful when you need to run multiprocessing.multiprocessing SafeProcess

104 Reference: http://beagleboard.org/static/beaglebone/latest/README.htm http://beagleboard.org/static/beaglebone/latest/Docs/Hardware/BONE_SRM.pdf Design materials System Reference Manual Schematics (PDF) Schematics (Orcad) Bill of materials PCB design files PCB manufacturing files http://learn.adafruit.com/beaglebone http://circuitco.com/support/index.php?title=BeagleBone

105 Backup http://www.gigamegablog.com/tag/beaglebone/ https://github.com/alexanderhiam/PyBBIO/wiki


Download ppt "Hands on Beaglebone Introduction on beaglebone Using it’s IO and interface Work as web server."

Similar presentations


Ads by Google