Home

Ethernut Software Manual

image

Contents

1. Standard wiederherstellen Abbrechen Ubemehmen 2 Ethernut HyperTerminal Oj x Datei Bearbeiten Ansicht Anrufen bertragung Make sure that the Ethernut Board z gt DIF lt i is connected to your local network Die 613 sole Resetting your Ethernut by pressing the reset button on the board will produce some text output in the terminal emulator s window Nut OS 3 4 1 1 HTTP Daemon 192 168 192 100 ready vi RF GR ky Verbunden 00 00 59 TTY 1115200 8 N 1 The text on your system will differ depending on your network configuration If your network doesn t use DHCP you may get something like this 29 Ethernut Software Manual 30 D Ethernut HyperTerminal oj x Datei Bearbeiten Ansicht Anrufen bertragung Nut OS 3 4 1 1 HTTP Daemon EEPROM DHCP ARP config failed 192 168 192 100 ready T INF 4 erbunden 00 06 31 TTY p 15200 8 N 1 RF GROSS Start a web browser on your PC The URL to request is the IP address which has been printed on the terminal emulator If everything went well you will see the main index page of the Ethernut webserver Mozilla Build ID 2002053012 So Untitled 5 ui Welcome to Ethernut HTTP Flash demo CGI Samples Login root Password root Parameter demo Thread list Timer list Socket list Hc oF Document Done 0 109 secs Congratulations your embedded webse
2. int sscanf CONST char string CONST char fmt int ungetc int c FILE stream int vfprintf FILE stream CONST char fmt va_list ap int vfscanf FILE stream CONST char fmt va_list ap int vsprintf char buffer CONST char fmt va_list ap int vsscanf CONST char string CONST char fmt va_list ap In addition the following low level I O functions are available int _close int fd int _open CONST char name int mode int _read int fd void buffer size t count int _write int fd CONST void buffer size t count int _ioctl int fd int cmd void buffer long _filelength int fd This set of functions allows to port many existing PC applications without too much effort Nevertheless there is an important difference to standard C applications written for the PC Typical embedded systems do not pre define devices for stdin stdout and stderr Thus the well know Hello world include lt stdio h gt int main void printf Hello world n requires a few additional lines of code on Nut OS include lt stdio h gt include lt dev usartavr h gt int main void unsigned long baud 115200 Register the device we want to use NutRegisterDevice amp devUsartAvr0O O 0 Assign the device to stdout freopen uart0O w stdout Optionally set the baudrate of the serial port _ioctl _fileno stdout UART SETSPEED amp baud Nut OS 35
3. Add ETHERNUT2 to the macro definitions only if you are compiling for the Ethernut 2 0 or 2 1 board In any case you need to add __ HARVARD ARCH All Macro Defines should be separated by spaces The robi command entered for the Execute Command After Successful Build at the bottom can be used to convert a hex file to a raw binary and is not required You may use raw binary files later when replacing the JTAG or ISP adapter by the Ethernet Compiler Options a x Paths Compiler Target Contig Salvo TT Strict ANSI C Checkings lv Accept Extensions C comments binary constants int size enum for backward compatibility Macro Defines Undefinefs ETHERNUT2 MCU enhanced HA EU Output Format COFF HEX z M Optimizations AVRA Studio Version COFF Studio 3 x Studio 4 0 to 4 05 Studio 4 06 and above Trials Left Code Compression TT Global Optimizations fo Optimizations are restricted to Advanced and Professional versions 45 trials of each optimization are available for evaluation The trials can not be renewed Code Compression if applicable is available in the ADY and PRO versions and Global Optimizations if applicable is available only in the PRO version Execute Command After Successful Build c ethernut 3 9 9 nut tools win32 robi Zp hex Zp bin Cancel Set As Default Load Default Help bootloader Loading programs into the Ethernut via a bootl
4. 5 File Edit View Build Help the hardware related configuration FT YE for this board will be automatically eee set by the Configurator Then the A CET Platform E Tools main configuration window will receive the focus Architecture RTOS kernel Device drivers C runtime tool specific C runtime target specific Fi Network general PO VETERE RE PN PETE IAP gt E z 09 59 45 Nut OS Configurator Version 1 2 3 09 59 45 Linked to we Widgets 2 6 0 09 59 45 Running on Windows 2000 build 2195 Service Pack 4 10 02 27 Loading c ethernut 3 9 9 nut conf repository nut 10 02 27 Loading C ethernut 3 9 9 nut conf ethernut21 b conf 10 02 27 OK E FF EH F Select Settings from the Edit entry of the main menu 4 tf The settings notebook with four pages x named Repository Build Tools and Samples Repositoy Build Tools Samples will appear Usually the first page can be left po uncha nged The entry specifies the path to c ethemut 3 9 9 nut conf repository nut Browse the Nut OS component repository Use slashes instead of backslashes with path names The first entry on the second page specifies the path xl to the source tree The Configurator will scan this Repository Build Tools Samples directory for predefined platform settings and add Source Directory them to the Platform drop down list If this list is c7
5. Compiler Target Config Salvo pated eet fe Sethernut 3 9 9 nutbld include c ethernu Add had been added to the Include Paths c ethernut 3 9 9 nutbld include and c ethernut 3 9 9 nut include This way ICCAVR will search C header files in the Nut OS build directory first then in the original Nut OS source directory and finally in its own include directory which doesn t need to be specified In other words the files located in the build tree will override the original header files in the source tree which in turn will override the original ICC header files Asm Include Paths Add Library Paths c ethemut 3 9 9 nutbld ib Browse Output Directory Browse NOTE The compiler driver automatically adds lt install root gt include as the default include path and lt install root Nib as the default library path You do not need to add them to the respective edit boxes above You may enter multiple paths in the Include Paths and the Library Paths fields Cancel Set As Default Load Default Help The entry marked Library Path points to the directory which contains our readily build Nut OS libraries Click on the Compiler tab and verify that all options are correctly set Code size reduction is optional and only available in the professional version of the ImageCraft compiler Add MCU enhanced to the macro definitions only if you are compiling for the ATmega128 CPU
6. When started a file selection Pers nlicher Ordner KI ethernut 3 9 9 cone G i P3 Desktop dialog IS presented If not already E e EEE displayed navigate to the Mi atSlebica conf 1Gestern ethernut X Y Z nut conf directory JD charon2 conf Gestern pD ethernut103 conf Gestern i pD ethernut13f conf Gestern where the hardware configuration files are located D ethemutlag conf Gestern lal ethernut20a conf Gestern ma n zi db Hinzuf gen sao Nut OS Configuration conf Ww X Abbrechen Pa ffnen Select the configuration file for your board E ethernut13f conf for board versions 1 3 Rev F or previous E ethernut13g conf for board versions 1 3 Rev G E ethernut21b conf for board versions 2 0 Rev A or Ethernut 2 1 Rev B After pressing OK the selected file will be loaded and the hardware related configuration for this board will be automatically set by the Configurator The main configuration window will receive the focus If the component tree is empty don t worry It s simply because the Configurator couldn t find the repository file We will fix this soon Nut OS Configurator ethernut21b File Edit View Build Help x Property Value gt Tools gt 6 Architecture b gt RTOS Kernel In Device drivers gt 6 C runtime tool specific 6 C runtime target specific gt 6 Network general tf Network application layer 7 N a OA gt 12 30 20 Nut OS Co
7. they can rely on not being stopped unexpectedly However they may be interrupted by hardware interrupt signals In opposite to pre emptive multithreading cooperative multithreading simplifies resource sharing and usually results in faster and smaller code As stated earlier the main application thread is already running as a thread together with the background idle thread which is not visible to the application Creating a new thread is done by calling NutThreadCreate The code running as a thread is nothing else than another C routine To hide platform specific details applications should use the THREAD macro to declare those routines THREAD Threadl arg for NutSleep 125 int main void Nut ThreadCreate t1 Threadl 0 512 for NutSleep 125 In this example the main thread creates a new thread before entering and endless loop The new thread will run in a similar senseless loop It is important to keep the cooperative nature of Nut OS in mind NutSleep which will be explained next stops execution for a specified number of milliseconds If one of the loops would not call this or any other blocking function like reading from a device or waiting for an event then the other threads would never gain CPU control Timer Management Nut OS provides time related services allowing application to delay itself for an integral number of system clock ticks by calling NutSleep A clock tick occ
8. Configurator will create a new or update an existing directory for application development and fill in a copy of the Nut OS sample applications By default Nut OS uses DHCP to automatically setup its TCP IP configuration Even without DHCP typical applications will store these settings in the on chip EEPROM and thus will not require modifications of the source code In order not to overload this tutorial we use hard coded addresses Run your favorite editor and load the file httpd httpserv c which is located in the sample directory just created You probably have to change the IP address and may also modify the IP mask to fit your network environment Otherwise your web browser won t be able to talk to your Ethernut Board later on If unsure what to do better ask someone with IP network experience 27 Ethernut Software Manual 28 ioli Datei Bearbeiten Suchen Ansicht Projekt Ausf hren Fehlersuche nai CVS Fenster Hilfe fa httpserv c Simple multithreaded HTTP daemon af ft These values are used if there is no valid configuration in EEPROM define MYMAC 0x00 0x06 0x98 0x00 0x00 Ox00 define MYIP 192 168 192 100 define MYMASK 255 255 255 0 Compiler fh Ressourcen dih Kompilier Log NA Fehlersuche A Suchergebnisse Einf gen 607 Zeilen in Datei You may also change the MAC Address to the one which you received with your Ethernut Board For self build boards or other boards
9. Ethernut Software Manual printf Hello world n Btw a typical pitfall is to mix Nut OS and compiler libraries for standard C functions If your application hangs in stdio functions or crashes when calling them then check your linker map file to make sure that these functions are loaded from Nut OS libraries If not you may forgot to add nutcrt to the list of libraries File System Neither Nut OS nor Nut Net require a file system but Webservers are designed with a file system in mind To make things easier for the programmer Nut OS provides a very simple file system named UROM where files are located in code ROM A special tool crurom create UROM is used to convert directories into a C source file which is then compiled and linked to your application code In addition a preview release of a read only FAT file systems is available which requires additional hardware like an IDE or Compact Flash interface This part is still under heavy development Visit the project page on the Ethernut website and subscribe to the Ethernut mailing list for latest informations Device Drivers Device drivers wether written as Nut OS extensions or as part of an application can define there own interrupt routines check the compiler documentation or may register callback routines by calling NutRegisterlrqHandler In opposite to desktop computers tiny embedded systems do not provide a memory management hardware unit to protect memory ar
10. Insta ation If Check the components you want to install and uncheck the components you don t want to unsure leave Fu sel ected a nd install Click Next to continue click Next to continue sl SSA ____ oO_ 1 5 Or select the optional Nut Os components you wish to Nut Net install Manuals Development Tools Application Samples Ethernut Bootloaders Pe El FE FE AE Description Space required 23 1MB Position your mouse over a component to see its description Nullsoft Install System v2 06 lt Back Cancel Quick Start with WinAVR FS Nut 05 2 9 setup Ts Choose Install Location Yo u can Now se ect th e Choose the folder in which to install Nut OS 3 9 9 installation directory By d efa u It a fi es WI be Insta ed Setup will install Nut OS 3 9 9 in the Following Folder To install in a different folder click i nc ethernut X Y 7 an d Browse and select another folder Click Install to start the installation the source code will be installed in C ethernut X Y Z nut which is called the top source directory or the i Kaka g Browse source tree 3 9 Click Install to start the Space required 23 1MB instal lation Space available 19 6GB Nullsoft Install System v2 06 AH U ioi xl Installing Th e next d la og wi S how the Please wait while Nut OS 3 9 9 is being installed eb installation progress This will take
11. Nut705S version 3 9 9 Anyway only the AVR platform can be considered stable the system for the ARM is quite new and partly incomplete All remaining CPUs offered in the Configurator are more like placeholders What about the Linux Emulator This emulation allows you to develop and run Nut OS applications on Linux It has been created and used by the ETH Zurich to develop their Nut OS based Bluetooth Stack Initially limited to RS232 communication emulating TCP IP support has been added recently If the Configurator fails to correctly setup the environment try the configure script in the source directory What about the AT90CAN128 Henrik Maier from FOCUS Software Engineering spent a lot of time with porting Nut OS to this device Just to Lind oul that the chip Ls buggy Atmel confirmed that the AT90CAN128 fails when the stack pointer addresses external RAM Using ICCAVR V7 fails The previous version worked Nut 0S 3 9 9 had been tested with ICCAVR version 7 However V7 installations are buggy You need V7 03C with Beta2 patch or above Using GCC fails Previous versions worked There had been several changes in the compiler and avr libc which regularly broke Nut OS Unfortunately WinAVR 20050214 with GCC 3 4 3 which seemed to work nice first produces strange results with fprintf Another problem is that twi h moved to another directory To solve this Simply move this file
12. NutAppMain Other compilers won t be hurt Almost all Nut OS header files do include compiler h Thus it is required only when no other header files are used in the application code Thread Management Typically Nut OS is at its most useful where there are several concurrent tasks that need to be undertaken at the same time To support this requirement Nut OS offers some kind of light processes called threads In this context a thread is a sequence of executing software that can be considered to be logically independent from other software that is running on the same CPU All threads are executing in the same address space using the same hardware resources which significantly reduces task switching overhead Therefore it is important to stop them from causing each other problems This is particularly an issue where two or more threads need to share a resources like memory locations or peripheral devices The system works on the principle that the most urgent thread always runs One exception to this is when a CPU interrupt arrives and the interrupt has not been disabled Each thread has a priority which is used to determine how urgent it is This priority ranges from 0 to 254 with the lowest value indicating the most urgent Nut OS implements cooperative multithreading That means that threads are not bound to a fixed time slice Unless they are waiting for specific event or explicitly 31 Ethernut Software Manual yielding the CPU
13. OS Configurator from the Initial Directory c ethemut 3 9 9 T Capture Output DOS Console Mode Program only Create urom c Nut OS Confiqurator Tools menu This will start the Nut OS Configurator In this chapter we will not handle the details of this tool but concentrate on the ICCAVR specific settings When started a file Selectae sx selection dialog is Suchenin con EE presented If not already arch sa charon2 conf a stk501 conf displayed navigate to c emunix conf p8 wolf conf Verlauf cpp ak ethernut103 conf ak xnut 100 conf the nut conf di rectory H crt Sja o W h ere th e h a rd ware dev 5 ethernut13g conf a xnut 100 atmega128 0 Deskto fs a ethernut20a conf a xnut 105 conf configuration files are Li Dalai si O cate d i o Os tan ethernut30 coo Eigene Dateien Jpro sa temo Iyo Cofition le Select the configuration e arthernet1 conf a baxpontz SP ST mar tan at91eb40a conf tan MMnet02 conf file for your board and Atbeitsplate click on Open gt Dateiname _Abbrechen Netzwerkumg A Dateityp Nut 05 Configuration conf v Abbrechen E ethernut13f conf for board versions 1 3 Rev F or previous E ethernut13g conf for board version 1 3 Rev G E ethernut21b conf for board versions 2 0 Rev A or 2 1 Rev B Quick Start with ICCAVR The selected file will be loaded and Mb I 1B 2
14. a few seconds You can Extract dir_000039 htm click Show details to view the EP list of files being installed Nullsoft Install System v2 06 Bi ex Cancel 3 Nut OS 3 9 9 Setup i 0 xj When all files had been copied to the installation directory a final dialog appears Check the checkbox to Start Nut OS Configurator and click Finish to close the installation wizard Start Nut OS Configurator This will start the Configurator which will be explained in the next chapter Completing the Nut OS 3 9 9 Setup Wizard Nut OS 3 9 9 has been installed on your computer Click Finish to close this wizard The installation added a few entries to your Windows start menu one of which is titled Configure Development Environment Use this entry when you later want to start the Configurator again http www ethernut de 23 Ethernut Software Manual Configuring Nut OS When the Nut OS Configurator hasn t been started yet select Configure Development Environment from the Ethernut 3 9 6 entry in the Windows Program Start Menu In this chapter we will not go to the details of this tool but concentrate on the AVR GCC specific settings 2 xi First a file selection Suchen in Sy coni ear dialog IS presented If ja charon2 conf t88 stk501 conf p8 emunikc conf p8 wolf conf not already displayed Verlauf a ethernut103 conf ja xnut 100 conf navigate to the nut conf E a ethernut
15. are not included in your standard PATH environment The Configurator will add these entries to the PATH environment when running the compiler c fethernut 3 9 6 nut tools win32 c winayr bin c winayr utils bin 25 Ethernut Software Manual NutConf Settings x Entries on the last page of the settings notebook are Aepesitew Build Tools Samples used to create a sample application directory PERI Nut OS comes with a few samples which c ethemut 3 3 6 nutapp Browse demonstrate its capabilities This includes the HTTP server we are going to build in this chapter The configurator can create a new directory for you copying the sources from the source tree and SR force creating templates for the Makefiles Such a directory may also host your own Nut OS applications later Programmer avruisp stk500 It is quite useful to select a programmer from the drop down list because applications may be build and uploaded to the target board later in one go with make burn Press OK to save your entries Nut 0S Configurator ethernut21b DI x File Edit Build Help oe kl J Nut OS Components D ta Tools TOOL CC AVR TOOL_GCC TOOL CXX I GCC for ARM File include cfgfarch h GCC For ARM no libc Macro AVR GCC AEGCC for AVR Active True CC for AYR GCC For Linux Yes TT ImageCraft for AVR GCC Settings Make sure you have deselected all other compilers a TT Include de
16. back to avr include avr WinAVR 20030913 with GCC 3 3 1 is old but produces reliable code Problem Solution The Configurator s main window is empty There s no component tree shown Make sure to set the correct path to the repository on the first settings page Reload the configuration file or restart the Configurator Building Nut 0S for platform XYZ fails with errors Using the old method building it directly in the source tree fails too The configuration had been tested with different settings However some configurations may still fail Standard builds should be done with the Configurator specifying a separate build directory At the time of this writing standard refers to configurations that worked with Nut OS 3 9 x Samples are not running on Ethernut 1 3 Rev G Make sure you have selected the correct configuration file for the Nut OS Configurator When using ImageCraft the Other Options must include ucrtenutram o instead of ucrtnutram o The additional letter e stands for early Ethernet initialization The ftpd sample is not running on Ethertnut 1 3 The ftp server needs a file system with write access The Peanut file system used in this sample can not run on Ethernut 1 3 because this board doesn t provide banked memory TCP and UDP samples are not running on Ethernut la When creating a new sample tree the Configurator creates UserConf
17. editor You probably have to change the IP address and may also modify the IP mask to fit your network environment Otherwise your web browser won t be able to talk to your Ethernut Board later on If unsure what to do better ask someone with IP network experience You can change the MAC Address to the one which you received with your Ethernut Board For self build boards or other boards without MAC address you need at least to make sure that the address is unique in your local network When selecting Make Project from the project menu ICCAVR will compile and link the webserver code Check that no errors occurred during this process Refer to the ICCAVR manual for further details 11 Ethernut Software Manual ImageCraft IDE for ICCA R PROFESSIONAL ioj x File Edit Search View Project Studio RCS Tools Terminal Help n ou amp hels eslfel pbagelggo httpsery c Project Browser VE IC HTTPD Associate a stream with the socket so we car EG Files urom c if istream fdopenilint sock r b 0 lt p hitpserv c z Headers Documents index html form html printf 5u Creating stream device failed else jt This API call saves us a lot of work It client s HTTP request send any requeste registered file system or handle CGI a b iccavr c I include IC icc include e D la iccavr o httpd LC icc lib g ucrtatmega o bfur Device 63 full tools wi
18. executable open source software development tools for the AVR hosted on the Windows platform They are mainly based on the GCC for AVR toolchain and are quite similar to the Linux tools Detailed information is available at winavr sourceforge net Installing Nut OS The installation for Windows is packed into a self extracting executable named ethernut X Y Z exe where X Y Z has to be replaced with the version number The file contains the complete code some Nut OS tools and the API reference Installer Language if x After starting the installation you can choose the Please select a language language The selected language is used during the installation only All other parts and the Nut OS Elec O AA documentation are available in English only cm 3 Nut OS 3 9 9 Setup a 210 xi After selecting the installer language and clicking OK a welcome screen will appear Click Next to continue Welcome to the Nut OS 3 9 9 Setup Wizard This wizard will guide you through the installation of Nut os 3 9 9 It is recommended that you close all other applications before starting Setup This will make it possible to update relevant system files without having to reboot your computer Click Next to continue Cancel Nut OS 3 9 9 Setup The next dialog lists all Nut OS hoese Components Choose which features of Nut OS 3 9 9 you want to install components which are In cl u d ed In th e
19. la og li sts al N ut OS Choose which features of Nut OS 3 9 9 you want to install eb components which are S In cl u d ed In th e insta ation If Check the components you want to install and uncheck the components you don t want to unsure eave Fu se ected an d install Click Next to continue click Next to continue a EE z Or select the optional V Nutjos components you wish to 4 Nut Net install i v Manuals Development Tools H V Application Samples V Ethernut Bootloaders Description Space required 23 1MB Position your mouse over a component to see its description Nullsoft Install System v2 06 lt Back Cancel zix You can now select the Choose Install Location i Ch he folder in which to i Il OS 3 9 9 installation directory By oose the folder in which to install Nut OS 3 9 default all files will be installed Setup will install Nut OS 3 9 9 in the Following folder To install in a different folder click Inc x ethernut x Y ZzZ and Browse and select another folder Click Install to start the installation the source code will be installed in C ethernut X Y Z nut which is called the top source directory or the Destination Folder source tree c lethernut 3 9 91 Browse Click Install to start the f Space required 23 1MB installation Space available 19 6GB Nullsoft Install System v2 06 cn Nut 0S 3 9 9 Setup T
20. need to modify the call to NutNetlfConfig in the C source file named tcps c as explained above Note that your PC and the Ethernut board should use the same network mask but different IP addresses And they must reside in the same network unless you add specific routes to the Nut Net routing table However IP routing might get rather complex and is beyond the scope of this manual You might refer to a good book explaining that matter Most local networks are configured as class C which means that a maximum of 254 different IP addresses are available and the IP network mask is specified as 255 255 255 0 All hosts in this network must have equal numbers in the first three parts of their IP addresses In this case 192 168 171 1 and 192 168 171 5 belong to the same network but 192 168 171 1 and 192 168 181 5 don t After you have done the changes open a Linux console or DOS prompt with the GCC environment and enter make This will create an updated binary file named tcps hex If your local network supports DHCP you may use the precompiled binary for a first try but may later modify the default MAC address After programming your Ethernut board with this binary open a Linux console or DOS prompt window and type telnet x x x x 12345 replacing x x x x with the IP address of your Ethernut board The telnet window should display 200 Welcome to tcps Type help to get help You may now enter any of the following commands using low
21. s descriptions com x st VeR bootloading mode It does COMI Zi not support EEPROM or verify function Target Device Setting ISP Options Use Project gt Options gt Device setting Additional STK500 exe command line arguments Perform Target Signature Check EEPROM Options 7 Auto Program After Compile with Flash from project Program with project file and selected EEPROM option Preserve existing content Verify After Programming Manual select Manual Program NOW FLASH Options Manual Selection Files Program with project output files Select hex file for FLASH Browse Manual select C ethemut nut appicchttpd httpd hex Program FLASH EEPROM Verity FLASH EEPROM Browse Select eep file for EEPROM Switch the Ethernut power supply back on and select In System Programmer from the Tools menu Then select the file httpserv hex for the FLASH by clicking on the Browse button We do not need to program the EEPROM Now press the 12 Quick Start with ICCAVR button labeled Program FLASH EEPROM to start in system programming This takes some seconds Some version of ICCAVR display an error message on empty EEPROM entries You can ignore this Finally press the OK button to close the n System Programming window Your Ethernut Board will immediately start the webserver application waiting for a web browser to connect Skip the next two chap
22. to NutNetlfConfig to get the network interface up and running NutNetlfConfig will store the specified address as a hard IP address into the EEPROM Remember that DHCP will check the hard IP address When Ethernut reboots again and call NutDhcplfConfig it will use this hard IP address and never try DHCP again unless the EEPROM is erased Why is this so complicated Well it isn t really but granted it isn t put straight either Since its early releases this part had been changed often and confused newcomers even more often There are two things to consider Nowadays most networks use DHCP and when Ethernut initially boots with DHCP it will reboot without problems later Second setting up IP addresses is beyond the scope of an operating system Instead this is part of the user interface and therefore part of the application From the application s point of view Nut Net network configuration is quite flexible Socket API On top of the protocol stack Nut Net provides an easy to use Application Programming Interface API based on sockets A socket can be thought of as a plug socket where applications can be attached to in order to transfer data between them Two items are used to establish a connection between applications the IP address to determine the host to connect to and a port number to determine the specific application on that host Because Nut Net is specifically designed for low end embedded systems its socket API is a su
23. to connect to port 12345 of the host with the IP address of 192 168 171 1 NutTcpConnect sock inet_addr 192 168 171 1 12345 44 Simple TCP Server In our sample application we decided to take over the server part which is done by calling NutTcpAccept sock 12345 This call will block until a client tries to connect us As soon as that happens we can send data to the client by calling NutTcpSend or receive data from the client through NutTcpReceive Communicating with the Client Most application protocols in the Internet environment exchange information by transmitting ASCII text lines terminated by a carriage return followed by a line feed character This might not be a big problem while sending data but it requires some extra effort for incoming data as arriving segments may contain either a fraction of a line or multiple lines or both And even sending data becomes more complicated with numeric values because we need to transfer them to there ASCII representation first For stream devices Nut OS offers the standard I O stream library functions In order to use them you need to attach a connected TCP socket to a stream FILE stream stream _fdopen int sock rtb This device can be used like any other Nut OS stream device and simplifies formatted and line oriented data I O The first thing servers usually do after a client connected them is to send a welcome message fprintf stream 200 Welcome t
24. without MAC address you need at least to make sure that the address is unique in your local network Save the changes When the Configurator created the sample directory it added a user configuration file with default settings for Ethernut 2 boards or more precisely for boards with the SMSC LAN91C111 Ethernet controller If your board is equipped with a different controller e g Charon Il or Ethernut 1 you have to modify a second file in the sample directory named UserConf mk Load this file in your editor and remove the entry HWDEF DETHERNUT2 w4 UserConf mk Editor 5 x Datei Bearbeiten Format Automatically created on Wed Sep 08 15 04 56 2004 You can use this file to modify values in NutConf mk HUDEF DETHERNUT2 If you are creating the sample directory again using the same path then the Configurator will overwrite all changes but it will never modify UserConf mk We are ready to build the webserver application and program the resulting binary into the target board Change to the httpd subdirectory within the sample directory and enter make clean make all Check that no errors occurred during this process As a result we will find the newly created binary named httpd hex in Intel hex file format If not already done connect your programming adapter to the Ethernut board and the proper PC interface and power up the Ethernut In case you selected the correct adapter in the Configurato
25. 1 arg for NutSleep 125 NutPostEvent sevt h int main void Nut ThreadCreate t1 Threadl 0 192 for NutEventWait sevt h NUT WAIT INFINITE Again Thread1 is running an endless loop of sleeps The main thread waits for an event posted to an event queue Event queues are specified by variables of type HANDLE The endless loop of the main thread is blocked in NutEventWait and woken up each time an event is posted by Thread1 Btw it hadn t been very smart to introduce the variable type HANDLE But it s there since the very early releases of Nut OS and most people don t care much Some more background information Waiting threads line up in priority ordered queues so more than one thread may wait for the same event Events are posted to a wait queue moving the thread from waiting sleeping state to the ready to run state A running thread may also broadcast an event to a specified queue waking up all threads on that queue Usually a woken up thread takes over the CPU if it s priority is equal or higher than the currently running thread However events can be posted asynchronously in which case the posting thread continues to run Interrupt routines must always post events asynchronously Actually NutEventPostAsync is one of the rare API routines which can be called by interrupt routines Stream I O Typical C applications make use of the standard I O library which is provided by th
26. 1 3F conf 8 xnut 100 at90can128 c babaan E ethernut13g conf b8 xnut 100 atmega128 c directo ry W he re the Desktop a ethernut20a conf p88 xnut 105 conf hardware configuration ba ethernut21b conf ail an ethernut30 coc files are located Ba pro sa ethernut304 Typ Configuration File a artherneti conf a gbaxport2 1 Gr e 2 40 KB sa tan at91eb40a conf MMnet02 conf Select the configuration file for your board and press Open El Dateiname w ffnen Netzwerkumg ical Dateityp Nut 0S Configuration conf v Abbrechen As E ethernut13f conf for board versions 1 3 Rev F or previous E ethernut13g conf for board versions 1 3 Rev G E ethernut21b conf for board versions 2 0 Rev A or Ethernut 2 1 Rev B Nut 0S Configurator ethernut21b File Edit view Build Help AB n7 The selected file will be loaded and the hardware related ee Nut OS Components configuration for this board will gt Hardware Platform 0015 be automatically set by the H Architecture RTOS Kernel Configurator When the main configuration window receives the focus select Settings from the Edit entry of the main menu Device drivers C runtime tool specific C runtime target specific pi Network general le niet ed See eben bine In gt E 09 59 45 Nut OS Configurator Version 1 2 3 09 59 45 Linked to weWidgets 2 6 0 09 59 45 Running
27. Ethernut Software Manual EMBEDDED ETHERNET ETHERNUT Manual Revision 2 4 Issue date November 2005 Copyright 2001 2005 by egnite Software GmbH All rights reserved egnite makes no warranty for the use of its products and assumes no responsibility for any errors which may appear in this document nor does it make a commitment to update the information contained herein egnite products are not intended for use in medical life saving or life sustaining applications egnite retains the right to make changes to these specifications at any time without notice All product names referenced herein are trademarks of their respective companies Ethernut is a registered trademark of egnite Software GmbH Contents About Nut OS and Nut Net cia sc ice ene i A A 1 NUT OS PeatUTES 6a ta GANA seedy RALE 1 Nut Net Features eee 1 Quick Start with ICCAVR 24 na cass c eave i ee he PER ee i 2 Installing ICCAVR 245 siria o aa 2 installing NUUVOS 4 2a KA KAN KABA dl TRA a 2 Configuring NUUOS saa pacts Nika ee eee a eae eee KA AA 4 Configuring ImageCraft 0 0 0 ccc ee eee 8 Creating the First Nut OS Application 11 Quick Start with AVR GCC on Linux 0 0 0 cee es 14 Installing AVR GCC on Linux LL 14 Installing Nut OS 0 0 cc eee eee eee 14 CONNGUNING NUVOS ocist cane cadaensioeddetaea ete avowed eure ea ees 14 Creating the First Nut OS Application 19 Quick Start with WinAVR cs GERA cane iene ieee a
28. It is assumed that you have a working knowledge of the protocol Also check the Nut OS API Reference for a detailed description Network Device Initialization With DHCP Before using any Nut Net function the application must register the network device driver by calling NutRegisterDevice and configure the network interface by calling NutDhcplfConfig or similar routines NutDhcplfConfig will try to retrieve the local IP address network mask and default gateway from a DHCP server If no DHCP server responds within a specified number of milliseconds NutDhcplfConfig uses the previously stored configuration from the on chip EEPROM of the ATmega CPU If the EEPROM doesn t contain any valid address NutDhcplfConfig will wait for an ICMP packet and use the IP address contained in its header In this case the netmask will be 255 255 255 0 and no default gateway will be configured Applications may also choose to configure a fixed IP address and network mask by calling NutNetlfConfig or may even use both NutDhcplfConfig and NutNetlfConfig To make things even more complicated there are two IP addresses stored in EEPROM a soft and a hard one The soft IP address is the last used one If Ethernut reboots and no DHCP server is available then the soft IP address will be used again If however a hard IP address is stored in EEPROM NutDhcplfConfig will not send out any DHCP query but use the hard IP address immediately Even worse DHCP requires an E
29. P sockets to standard I O streams which makes our code looking more familiar at least for Linux people The following line is used to attach a connected socket to a Nut OS stream stream _fdopen int uptr t sock rtb The code can use fprintf fouts fscanf fgets and other stdio functions to talk TCP UDP server applications will provide their port number when calling NutUdpCreateSocket while UDP client applications pass a zero to this call in which case Nut Net selects a port number greater than 1023 which is currently not in use Data is transferred by calling NutUdpSendTo and NutUdpReceiveFrom quite similar to the well known BSD functions sendto and recvfrom NutUdpDestroySocket may be called to release all memory occupied by the UDP socket structure While UDP read provides a timeout parameter TCP read doesn t At least not directly but a some special ioctrls are available including one to set the read timeout BSD calls them socket options and so does Nut Net unsigned long to 1000 millisecs NutTcpSetSockOpt sock SO RCVTIMEO amp to sizeof to Like with most TCP IP stacks there is no provision to set any connection timeout value and NutTcpConnect may block for half a minute or more That s how TCP IP is designed Most people experience this from the webbrowser on the desktop PC when trying to connect a webserver that doesn t respond Nevertheless this seems to be unacceptable for embedded sys
30. To build the libraries enter make clean followed by make install At the end you should see some kind of error message Best check the Ethernut FAO or ask the Ethernut mailing list for further assistance Creating the First Nut OS Application Although possible we will not modify the source directory which contains the application samples Instead we will use the Configurator to create a copy of the sample directory for us Creating samples Select Create Sample Directory from the g Source directory homefharald ethernut 3 9 9 app Build entry of the main menu After le tal ia EE confirming the message box the Configurator will create a new or update an existing directory for application development and fill in a copy of the Nut OS sample applications Do you like to create the sample directory By default Nut OS uses DHCP to automatically setup its TCP IP configuration Even without DHCP typical applications will store these settings in the on chip EEPROM and thus will not require modifications of the source code In order not to overload this tutorial we use hard coded addresses Run your favorite editor and load the file httpd httpserv c which is located in the sample directory just created You probably have to change the IP address and may also modify the IP mask to fit your network environment Otherwise your web browser won t be able to talk to your Ethernut Board later on If unsure what to do better ask s
31. blocks Allocating a buffer for 1024 bytes senseless filling it with OxFF and releasing the buffer again will look like this char buffer buffer malloc 1024 if buffer memset buffer OxFF 1024 free buffer else puts Out of memory error You should make intensive use of dynamic memory allocation for two reasons First large local variables will occupy stack space As each thread gets its own stack you may waste a lot of memory by reserving large stacks Second large global variables occupy space during the complete lifetime of the application although they may not be used during that time For some environments the global variable space may be much more limited than heap space Some developers argue that dynamic memory allocation produces less reliable code and is slower If you agree to this opinion allocate all memory once during Initialization The heap manager uses best fit address ordered algorithm to keep the free list as defragmented as possible This strategy is intended to ensure that more useful allocations can be made We end up with relatively few large free blocks rather than lots of small ones Event Management Threads may wait for events from other threads or interrupts or may post or broadcast events to other threads For using events a modified version of our thread example will look like this 33 Ethernut Software Manual 34 HANDLE evt h THREAD Thread
32. bset of what is typically available on desktop computers and differs in some aspects from the standard Berkeley interface However programmers used to develop TCP IP applications for desktop system will soon become familiar with the Nut Net socket API TCP IP applications take over one of two possible roles the server or the client role Servers use a specific port number on which they listen for connection requests The port number of clients are automatically selected by Nut Net Nut Net provides a socket API for the TCP protocol as well as the UDP protocol The first step to be done is to create a socket by calling NutTcpCreateSocket or NutUdpCreateSocket Nut Net TCP server applications will then call NutTcpAccept with a specific port number This call will block until a TCP client application tries to connect that port number After a connection has been established both partners exchange data by calling NutTcpSend and NutTcpReceive A simple TCP client looks like this TCPSOCKET sock NutTcpCreateSocket NutTcpConnect sock inet_addr 192 168 192 2 80 NutTcpSend sock Hello r n 7 NutTcpReceive sock buff sizeof buff Nut TcpCloseSocket sock A Nut Net TCP server looks similar TCPSOCKET sock NutTcpCreateSocket NutTcpAccept sock 80 NutTcpReceive sock buff sizeof buff NutTcpSend sock 2U2 r n 5 Nut TcpCloseSocket sock Furthermore Nut OS allows to attach TC
33. bug info T ARM Linker Script ImageCraft AVR Settings gt 16 00 37 Nut OS Configurator Version 1 2 2 16 00 37 Linked to wxWidgets 2 6 0 16 00 37 Running on Windows 2000 build 2195 Service Pack 4 16 00 44 Loading c ethernut 3 9 6 nut conf repository nut 16 00 44 Loading C ethernut 3 9 6 nut conf ethernut21b conf 16 00 44 OK The focus returns to the Configurator s main window We are almost done with just one configuration option left Actually we already selected the proper tools when specifying the platform Due to the internal structures used by the Configurator we need to specify once again that we are going to use GCC for the AVR Click on Tools in the tree on the left side of the main window to open the trunk and activate GCC for AVR if not already selected Build the configured Nut OS is done in two steps First select Generate Build Tree from the Build entry of the main menu After confirming the message box the configuration tool prepares a new build directory or modifies an already existing one using the build path specified in the settings notebook It creates a set of files including some C language header files in a subdirectory named include cfg These files are included into the Nut OS source code to tailor the system to our specific target hardware Then select Build Nut OS from the Build entry of the main menu The Configurator will now run make clean make all and finally make install Thi
34. conf ethernut21 b conf 10 43 24 OK Make sure you have deselected all othe includejcfgjarch h ICCAYR True We are back to Configurator s main window with one configuration option left Actually we already selected the proper tools when specifying the platform Due to the internal structure used by the Configurator we need to specify once again that we are going to use the ImageCraft compiler Click on Tools in the tree Quick Start with ICCAVR shown on the left to open the trunk deselect any GCC entry and select ImageCraft for AVR Finally we are ready to build the configured Nut OS Select Build Nut OS from the Build item of the main menu After confirming two message boxes the configuration tool prepares a new build directory or modifies an already existing one using the build path specified in the settings notebook It creates a set of files including some C language header files in a subdirectory named cfg These files are added to the Nut OS source code to tailor the system to a specific hardware The Configurator will then run an external utility to clean any previous build make clean create new libraries make a11 and finally copy them to the install directory make install As a result we get the following ICCAVR libraries E libnutarch a Architecture dependent library E libnutcrt a C runtime support library E libnutdev a Device driver library E libnutfs a File system library E libnutnet a Netw
35. ctory and choose a meaningful name For example if Nut OS has been installed in C ethernut 3 9 9 nut then C Ethernut nutbld 21b icc would be a good directory name to build a Ethernut Software Manual system for Ethernut 2 1 Rev B with ICCAVR Using the Browse button offers to create new directories Finally enter an nstall Directory It is recommended to specify a directory within the build tree Previous versions of the ImageCraft compiler can t search more than one directory for libraries Thus it was required to enter the path name of the ICCAVR lib directory After system build the Configurator will copy the libraries to this destination xi Repository Build Tools Samples On the third page enter the paths to the directories containing the required tools separated with semicoli It is very important to add one additional semicolon after the last path The Nut OS tools should be first followed by the ImageCraft bin directory c ethernut 3 9 94nuktools4win32 C Nicev avrsbin Tool Paths The tools directory contains a set of executables which are required to build the system on the Windows PC Most of them mimic Unix like commands which are typically more powerful than their Windows counterparts Some of them do not like backslashes That s why we specify all paths with slashes However the Tools Path itself is passed to the Windows command line interpreter which requires backslashes T
36. da ew se LAKE KA KA 22 Installing AVR GCC on Windows 22 Installing Nut OS 0 0 cette eens 22 Configuring NUVOS 4 na kah AWRA Petes EHI KREW BA epi A 24 Creating the First Nut OS Application cece ees 27 Running the Embedded Webserver cece eee eee eeeeaee 29 ke ET eee eae 3 System Initialization ee eee eens 31 Thread Management ccc eee eee eee 31 Timer Management 2 a 32 Heap Management Xa a kak KA PAANAN Ge beeen Ree Gee eee eS 33 Event Management 33 SEUI RR RR RR TO 34 File Systems en et RAIL i 36 DEVICE DINETT sensata nti amet 36 QU one goog AA eye ewes ede bees he bee 37 Network Device Initialization with DHCP 37 SOCKET AE Sauce dah acu Sad ace ge hb EEE Soka e rh eee ee 38 FROLOCONS 4244465504 6nd ob be eee ae Ge Oe nee bee one eee 40 Conversioni FUNCHON sester seu de soe aw e bee Baws weed 41 Network Buffers inerisici ira odes PN NA ae ee KAN 41 Simple TCP Server irrita i 43 Initializing the Ethernet Device a 43 Connecting a Client to a Server 2 a 44 Communicating with the Client 45 Trying the Sample Code eee eas 46 Reference Material sicrseniarae nia ns e cen seers ese cese ea kes 47 Troubleshooting irish te tage Reet denne a oan PAG eee eee 49 About Nut OS and Nut Net About Nut OS and Nut Net Connects embedded applications to a local Ethernet and the global Internet Nut OS Features Nut OS is a very sim
37. e using the build path specified in the settings notebook lt creates a set of files _X ativan go including some C language header files in a subdirectory named include cfg These files are included into the Nut OS source code to tailor the system to our specific target hardware Do you like to generate this build tree Build Nut OS After confirming another message box the Source directory homefharald ethernut 3 9 9 Configurator will run make clean make all Build directory home harald ethernut 3 9 9 bld 21b x z Target platform avr gcc an d fi na ly ma ke In Sta B ga directory fhome harald ethernut 3 9 9 bld 21bylib Do you like to build the Nut OS libraries The Configurator created the following AVR X Abbrechen libraries E libnutarch a Architecture dependent library E libnutcrt a C runtime support library E libnutdev a Device driver library E libnutfs a File system library E libnutnet a Network library E libnutos a RTOS kernel library E libnutpro a Protocol library E nutinit o RTOS initialization Quick Start with AVR GCC on Linux If this step fails check your settings again If you can t determine the problem then try the command line to fix this or at least find out more about what went wrong Change to the build directory directory and enter export PATH ethernut 3 9 9 nut tools linux PATH to add the directories containing the Nut OS tools to your PATH environment
38. e avr libc for GCC and by ImageCraft s libraries However only simple devices are supported Therefore Nut OS provides its own library nutcrt which overrides the functions of the compiler s runtime library The list of available functions is quite impressive void clearerr FILE stream int fclose FILE stream void fcloseall void FILE fdopen int fd CONST char mode int feof FILE stream int ferror FILE stream int fflush FILE stream int fgetc FILE stream char fgets char buffer int count FILE stream int _fileno FILE stream void _flushall void FILE fopen CONST char name CONST char mode int fprintf FILE stream CONST char fmt int fpurge FILE stream int fputc int c FILE stream int fputs CONST char string FILE stream size t fread void buffer size t size size t count FILE stream FILE freopen CONST char name CONST char mode FILE stream int fscanf FILE stream CONST char fmt int fseek FILE stream long offset int origin long ftell FILE stream size t fwrite CONST void data size t size size t count FILE stream int getc FILE stream int getchar void int kbhit void char gets char buffer int printf CONST char fmt int putc int c FILE stream int putchar int c int puts CONST char string int scanf CONST char fmt int sprintf char buffer CONST char fmt
39. eas or I O port access As a result there is no special kernel mode for device drivers to run in Thus there is no requirement for a device driver at all To phrase it favorably application code can freely use any kind of resource One advantage of device drivers is still left for Nut OS Abstraction If a device driver exists for let s say an LCD display it may be used with stdio streams like other devices Device usage can be switched easily by changing a few lines of code Look at our Hello world output going to an LCD include lt stdio h gt include lt dev hd44780 h gt include lt dev term h gt int main void Register the device we want to use NutRegisterDevice amp devLcd 0 0 Assign the device to stdout freopen lcd w stdout printf Hello world n Note that real applications may contain a lot of input and output statements Using stream I O devices offers to write code which is almost device independent Provided that Nut OS drivers exist for the devices to be used 36 Nut Net Nut Net Network enabling an overview Most TCP IP implementations came from desktop PCs requiring large code and buffer space Available memory of embedded systems like the Ethernut board is much smaller Nut Net has been specifically designed for small systems Although this chapter tries to explain some basics it makes no attempt to describe all aspects of TCP IP in full detail
40. ehemut33 3m Browse empty make sure that the first entry points to the correct Source Directory and that this directory Platform avrice 5 contains a file named Makedefs avr icc Include Directories Select avr icc as the platform Fist TO Browse The First and Last Include Directories should be left ne empty If using ICCAVR V6 enter the path of your Browse ImageCraft include directory as the Last include ent directo ry c ethemut 3 9 9 nutbld Browse For the next step it is Important to understand that raed Dieci l we distinguish between the source directory and the c ethemu 3 33 nutbid ib Browse build directory During Nut OS installation the Nut OS source code is copied to the source EE directory Files in the source directory will not ESE change and no new files will be added to this directory On the other hand all system configurations will result in one or more new header files which will be created by the Configurator in the build tree Later when building the newly configured system the compiler will first check the build tree for the required header files The big advantage is that we are able to create several system builds for different configurations from a single source tree e g building Nut OS for different Ethernut board revisions The build directory can be located anywhere but it is recommended to put it in the parent of the top source dire
41. er case letters memory Displays the number of available SRAM bytes threads Lists all created threads timers Lists all running timers Reference Material Reference Material Interested in more Books Comer D Internetworking with TCP IP Vol Principles Protocols and Architecture Prentice Hall Covers many protocols including IP UDP TCP and gateway protocols It also includes discussions of higher level protocols such as FTP TELNET and NFS Comer D Stevens D Internetworking with TCP IP Vol Il Design Implementation and Internals Prentice Hall Discusses the implementation of the protocols with many code examples Comer D Stevens D Internetworking with TCP IP Vol III Client Server Programming and Applications Prentice Hall Discusses application programming using the internet protocols It includes examples of telnet ftp clients and servers Stevens W TCP IP Illustrated Vol 1 Addison Wesley One of if not the most recommended introduction to the entire TCP IP protocol suite covering all the major protocols and several important applications Stevens W TCP IP Illustrated Vol 2 Addison Wesley Discusses the internals of TCP IP based on the Net 2 release of the Berkeley System Stevens W TCP IP Illustrated Vol 3 Addison Wesley Covers some special topics of TCP IP RFCs RFCs Request For Comment are documents that define the protocols used in the Internet Some are standards others are s
42. erested in looking to the Nut Net source code Network buffers are one of the central data structure within Nut Net A network buffer structure contains four equal substructures each of which contains a pointer to a data buffer and the length of that buffer Each substructure is associated to a specific protocol layer datalink network transport and application layer An additional flag field in the network buffer structure indicates if the associated buffer has been dynamically allocated Network buffers are created and extended by calling NutNetBufAlloc and destroyed by calling NutNetBufFree When a new packet arrives at the network interface the driver creates a network buffer with all data stored in the datalink substructure The Ethernet layer will then split this buffer by simply setting the pointer of the network buffer substructure beyond the Ethernet header and 41 Ethernut Software Manual 42 adjusting the buffer lengths before passing the packet to the IP or ARP layer This procedure is repeated by each layer and avoids copying data between buffers by simple pointer arithmetic When application data is passed from the top layer down to the driver each layer allocates and fills only its specific part of the network buffer leaving buffers of upper layers untouched There is no need to move a single data byte of an upper layer to put a lower level header in front of it Simple TCP Server Simple TCP Server Walking thro
43. ftware Manual 18 Nut OS Configurator ethernut21b C X File Edit View Build Help oh AS F 6a ae T GCC for ARM Requires TOOL CC AVR GCC for ARM no libe Provides HW TARGET HW MCU AVR H MM GCC for AVR File include cfg arch h GCC for Linux Macro MCU ATMEGA128 Imagecraft for AVR 1 gt GCC Settings 8 bit RISC microcontroller with 128K bytes flash a a 4K bytes RAM 4K bytes EEPROM 64K bytes Include debug info data memory space 2 USARTs 4 timers 8 7 ARM Linker Script channel ADC SPI and TWI W ImageCraft AVR Settings v Architecture se Target CPU I Atmel ATmega 103 r L 7 AtmelAT90CAN128 gt 12 30 20 Nut OS Configurator Version 1 2 3 12 30 20 Linked to wxWidgets 2 6 0 12 30 20 Running on Linux 2 4 27 2 k7 i686 12 30 21 Failed to load help file 12 37 38 Loading home harald ethernut 3 9 9 conf repository nut 12 37 38 Loading home harald ethernut 3 9 9 conf ethernut21b conf 12 37 38 OK y ei A a E We are ready to build the configured Nut OS which is done in two steps Generate Build First select Build Nut OS from the Build entry a Source directory homefharald ethernut 3 9 9 of the main menu After co nfirming the Build directory horme harald ethernut 3 9 9 bld 21b 8 Target platform avr gcd message box the configuration tool prepares a new build directory or modifies an already existing on
44. he next dialog will show the Instaling dr I i PI it while Nut OS 3 9 9 is being installed installation progress This will ease wait while Nut is being installe take a few seconds You can Extract dir_000039 html click Show details to view the 2r list of files being installed Nullsoft Install System v2 06 Gancel Ethernut Software Manual Nut OS 3 9 9 Setup gy me E When all files had been copied to the installation directory a final dialog appears We will later use the ImageCraft IDE to start the Nut OS Configurator Thus leave the checkbox to Start Nut OS Configurator unchecked Completing the Nut OS 3 9 9 Setup Wizard Nut OS 3 9 9 has been installed on your computer Click Finish to close this wizard Click Finish to close the installation wizard http www ethernut de Cancel Configuring Nut OS Start the ImageCraft IDE and select Configure Tools from the Tools menu Enter Nut OS Configurator as a menu name x select nutconf exe in the Nut OS installation ma directory Chenge C ethernut x y z nutconf exe as the Delete Program Options Program and enter the installation directory Menu Name Nut 0S Configurator Clear Fields C ethernut x y z as the Initial Directory Then click on Add to store this new entry and Program c ethemut 3 9 S nut Browse Parameters TT click on OK to return to the main window Now you can select Nut
45. hen creating your own http project in a different directory TM the not run running Linux Either nutconf executable is available does not or fails to build The Nut OS Configurator is a complex application with many dependencies and it is beyond the scope of this manual to handle all possible pitfalls It is a good idea to try one of the samples included in wxWidgets 2 6 0 first If this is working you should try the same with Lua 5 02 If either Lua or wxWidgets fail try to get help from these communities Both are running mailing lists with helpful users After having passed these steps it should not be too difficult to fix the Makefile in tools nutconf and successfully run make install If all this doesn t help try the configure script in the Nut OS source directory We d like to provide a more advanced build configuration or readily build binaries in the future But we probably need help from more advanced Linux users The Configurator fails on Windows with a missing DLL At least MSVCR71 dll is missing with Nut OS 3 9 6 You should be able to get this file from another source Microsoft confirmed that it is freely redistributable Troubleshooting 49 Ethernut Hardware Manual 50 Problem Solution Building for ARM H8 300 or any of the other officially supported CPUs tails Only the ATmega103 128 the GBA and the AT91R40008 are officially supported in
46. hus we must use backslashes here Entries on the last page of the settings notebook are x used to create a sample application directory Repository Build Tools Samples Nut OS comes with a few samples which demonstrate its capabilities This includes the HTTP server we are going to build in this chapter The Configurator can create a new directory for you copying the sources from the source tree and creating ImageCraft project files Such a directory may also host your own Nut OS applications later m Application Directory fe ethernut 3 9 9 nutapel Browse Programmer avi dude The Programmer selection can be left alone because the ICCAVR IDE provides its own programming interface Press OK to save your entries Nut 0S Configurator ethernut21b File Edit View Build Help ABAT EB Nut OS Components Hardware Platform 10 x TOOL CC AVR TOOL_ICC E Tools GCC for ARM GCC for ARM no libe GCC for AYR GCC for Linux ae Imagecraft For AYR GCC Settings W ImageCraft AYR Settings Architecture Target CPU Atmel ATmega 103 J Atmel ATmega 128 Atmel AT9OCANI28 10 27 01 Nut OS Configurator Version 1 2 3 10 27 01 Linked to we Widgets 2 6 0 10 27 01 Running on Windows 2000 build 2195 Service Pack 4 10 43 24 Loading c ethernut 3 9 9 nut conf repository nut compilers 10 43 24 Loading C ethernut 3 9 9 nut
47. in the source tree c ethemut 3 3 6 nutbld Browse When building Nut OS the Configurator will Install Directory automatically add all Nut OS include directories c ethemut 3 9 6 nutbid ib Browse It is Important to note that we distinguish between the source directory and the build directory The big bored advantage is that we are able to create several system builds for different configurations from a single source tree e g building Nut OS for different Ethernut board revisions Nach einem Ordner durchsuchen Ki The build directory can be located anywhere Shoose a build directory but it is recommended to put it in the parent of the top source directory and choose a meaningful name like c ethernut 3 9 6 nutbld Using the Browse button offers to create new directories Finally enter an Install Directory It is recommended to choose a directory within the build tree e g c ethernut 3 9 6 nutbld lib During system build the Configurator will i P a i E C include copy the libraries to this destination GR lih pa OK Abbrechen Neuer order 4 Nutconfsettings NE On the third page enter the paths to the Repository Buld Tools Samples Tool Paths directories containing the required tools separated with semicoli Do not miss to add a semicolon after the last path The Nut OS tools should be first followed by OK Cancel the paths to the WinAVR executables bin and utils bin if they
48. mk in this directory for Ethernut 2 Use a text editor and remove the ETHERNUT2 entry With the ImageCraft IDE this is no problem but still the ETHERNUT2 macro should be defined for Ethernut 2 x boards only I can t figure out how to solve my problem The Ethernut mailing list preferably the English list en nut discussion is the recommended forum for Nut OS users Please be aware that all the helpful people are volunteers Make sure that your question is not answered in the FAQ Try to be as friendly as possible and post Nut OS related messages only Do not ask questions about general programming or networking There are be better places to get answers in such cases Troubleshooting 51 egnite Software GmbH Erinstr 9 44575 Castrop Rauxel Germany Phone 49 0 23 05 44 12 56 Fax 49 0 23 05 44 14 87 Email info egnite de http www egnite de http www ethernut de
49. n32 robi C ethernut nut appicc httpd Done 1 1 C ethernut nut app httpd httpserv c C ethernut nut appiceshttpd 4 As a result of the this step ICCAVR created several files in the project directory One is named httpserv hex and contains the binary code in Intel Hex Format The second file httpserv cof can be loaded into the AVR Studio Debugger and contains the binary code plus additional debugging information Unless debugging is required you can directly use the ICCAVR IDE to program the ATmega flash memory with an ISP Adapter like the one you received with your Ethernut Starter Kit For debugging you need a JTAG Adapter with debugging capabilities for example the ATJTAGICE from Atmel The JTAG interface of the SP Duo doesn t support debugging If not already done connect the ISP Adapter to the Ethernut Board and the PC While doing this you must have switched off the Ethernut s power supply In System Programming x Programmer Interfac Advanced Manual Mode NOTE NT 2K users must have Lock Bits R w C STK 200 300 administrative privilege to use the SI Prog parallel port interface Fa Bia R wi gt i Flash Design ICE s supported SITA STK 500 under STK200 PAR and SI Prog Chip Erase NB ie i edi DT 006 SER modes STK500 requires AVR Studio to be installed Please refer to the device specific C STAVER l i datasheet for lock bits and fuse bits STAVER is for the Lawicel
50. nfigurator Version 1 2 3 12 30 20 Linked to wxWidgets 2 6 0 12 30 20 Running on Linux 2 4 27 2 k7 i686 12 30 21 Failed to load help file 12 37 38 Loading home harald ethernut 3 9 9 conf repository nut 12 37 38 Loading home harald ethernut 3 9 9 conf ethernut21b conf 12 37 38 OK From the Edit entry of the main menu select Settings The settings notebook with four pages named Repository Build Tools and Samples will appear 15 Ethernut Software Manual 16 NutConf Settings The first page defines the path the the so Repository Build Tools Samples called repository file You may want Repository File change the relative path to an absolute momerharaltethernut 2 3 9fconfireposkoryrt Browse One In case the main window didn t show the component tree that s because the path to the repository had been incorrect D OK X Abbrechen NutConf Settings On the second page enter the correct top Repository Build Tools Samples source directory opt ethernut nut by Source Directory default The Configurator will scan the imometharaldetherrut 399 area conf subdirectory in the specified path for predefined platform settings and add er avrgce vl them to the Platform drop down list Include Directories Select avr gcc as the platform 7 Browse The entries for First and Last include directories can be ignored when using Browesa GCC For special config
51. nvironment The Configurator will add these entries to an existing PATH environment when running the compiler D OK x Abbrechen NutConf Settings Entries on the last page of the settings Repository Build Tools Samples notebook are used to create a sample Application Directory application directory Nut OS comes with mometharakethernut 3 9 3 app 21b paang a few samples which demonstrate its capabilities This includes the HTTP Boab avr dude M server we are going to build in this chapter The configurator can create a new directory for you copying the sources from the source tree and creating templates for the Makefiles Such a directory will be also quite usefull when writing your own Nut OS applications later When selecting the correct Programmer from the drop down list applications may be build and uploaded to the target board in one go with make burn For the SP Pa NE Duo Programming Adapter select avr dude Press OK to save your entries The focus returns to the Configurator s main window We are almost done with one configuration option left Actually we already selected the proper tools when specifying the platform But due to the internal structures used by the Configurator we need to specify once more that we are going to use GCC for the AVR Click on Tools in the tree on the left side of the main window to open the trunk and activate GCC for AVR if not already selected 17 Ethernut So
52. o Ethernut r n Note that it s a good idea to prepend a numeric code in front of server responses This way both a human user as well as a client program can easily interpret the message On the other hand the message above occupies 26 bytes of SRAM space Alternatives are fputs 200 OK r n stream or fputs_P PSTR 200 Welcome to Ethernut r n stream In the second example the message is stored in program space and only temporarily copied to SRAM when needed The PSTR macro is only available with AVR GCC When using ICCAVR you have to write it in a different way prog_char vbanner_P 200 Welcome to Ethernut r n fputs_P vbanner_P stream In the next step TCP servers typically await a command from the client perform the associated activity return a response to the client and await the next command 45 Ethernut Hardware Manual 46 Disconnecting Finally the client will disconnect or as preferred send a special command to force the server to disconnect The server will then call fclose stream to release all memory occupied by the stream device and then call NutTcpCloseSocket sock to terminate the socket connection Next the server may create a new socket and wait for a new client connection Trying the Sample Code The complete source code of a TCP server example can be found in subdirectory app tcps of your installation directory If there s no DHCP server in your local network you
53. oader is much faster than any other method of in system programming Click on the Target tab Again make sure that the right options are set Specifically check the device for ATmega103 or ATmega128 Ethernut Software Manual 10 xjl The following Additional Libs are Paths Compier Target Config Salvo required for the webserver project Device Configuration 1 PRINTF Version ATMega1 28 v small fint only no modifier nutp ro nutfs nutnet nutos Memory Sizes Bytes fe Re F long long and modifiers nutdev nutcrt nutarch rogram Memory C float float needs gt 8K Bats zo ose I AVR Studio Simulator 10 ili dia If your application requires floating EEPROM 4096 Additional Lib Kamara point operations replace nutcrt by Text Address WORD Ox4E Strings in FLASH only Fane AES PAOLO nutcrtf This will however produce IV Use long CALL JMP Return Stack Size fi 6 la rger code w Enhanced Core i s HER Non default Startup IY G Regs Offset Internal SRAM Use RAMPZ ELPM Unused ROM Fill Bytes Boot Loader Options ucrtnutram o c 5 E nae Other Options ucrtnutram o cS Application Boot Size TT DoNOT use R20 R23 C Boot Loader None External 32K SRAM Note on External RAM Cancel Set As Default Load Default Help For Other Options enter ucrtnutram o c ethernut 3 9 9 nutbld lib nutinit o or for Ethe
54. omeone with IP network experience 19 Ethernut Software Manual 20 fopt ethernut nut app21b httpd httpserv c gedit File Edit View Search Tools Documents Help DE HS 9 ext Bb 8 B New Open Save Print Undo Redo Cut Copy Paste Find Replace httpservic X EY These values are used if there is no valid configuration in EEPROM define MYMAC 0x00 0x06 0x98 0x00 0x00 0x00 define MYIP 192 168 192 100 define MYMASK 255 255 255 0 include lt string h gt include lt io h gt i ifdef ETHERNUT2 include lt dev lanclll h gt else include lt dev nicrtl h gt endi f Ln 1 Coll You can also change the MAC Address to the one which you received with your Ethernut Board For self build boards or other boards without MAC address you need at least to make sure that the address is unique in your local network Save the changes When the Configurator created the sample directory it added a user configuration file with default settings for Ethernut 2 boards or more precisely for boards with the SMSC LAN91C111 Ethernet controller If your board is equipped with a different controller e g Charon Il or Ethernut 1 you have to modify a second file in the sample directory named UserConf mk Load this file in your editor and remove the entry HWDEF DETHERNUT2 opt ethernut nut app21 b UserConf mk gedit File Edit View Search Tools Documents Help De 4 69 SBB a B New Open Save P
55. on Windows 2000 build 2195 Service Pack 4 10 02 27 Loading c ethernut 3 9 9 nut conf repository nut 10 02 27 Loading C ethernut 3 9 9 nut conf ethermut21b conf 10 02 27 OK a fe fF fF FH NutConf Settings x The settings notebook with four pages named Repository Build Tools Samples Repository Build Tools and Samples will ia papa appear Usually the first page can be left ren Tama Browse unchanged The entry points to the Nut OS component repository It is important to note that we use slashes instead of backslashes for path names because most tools we will use for building the system are derivated from Unix programs Some of them do not like backslashes 24 Quick Start with WinAVR xl On the second page enter the correct top source Repositoy Build Tools Samples directory where you installed Nut OS The kaganapan Configurator will scan the conf subdirectory of the c ethemut 3 5 6 nut Browse specified path for predefined platform settings and add them to the Platform drop down list Platform pama Select avr gcc as the platform america Decree First Browse The entries for First and Last include directories can ae be ignored when using GCC For special Lat Browse configurations they allow to set include directories which will be searched before First or after Last m Build Directory the standard directories
56. ork library E libnutos a RTOS library E libnutpro a Protocol library E crtenutram o Runtime initialization for Ethernut 1 3 Rev G E crtnutram o Runtime initialization for all other boards E nutinit o Nut OS initialization bid If this step fails check your settings again If you can t XxX Building Nut O5 Failed Continue determine the problem and if you re using a licensed version try the command line to fix this or at least find out more about what went wrong The compiler demo will not run on the command line Open a DOS window change to the build directory directory and enter PATH c ethernut 3 9 9 nut tools win32 c icc7avr bin PATH to add the directories containing all required tools to your PATH environment The directories given above are an example You may have installed ImageCraft and Nut OS in different directories Enter make clean followed by make install At the end you should see some kind of error message If this is all Greek to you best check the Ethernut FAO before asking the Ethernut mailing list for further assistance Ethernut Software Manual If everything went fine we will set up a sample directory Although possible we will not touch the source directory which contains the application samples Instead we will use the Configurator to create a copy of the sample directory for US Select Create Sample Directory from the Build entry of the main menu After confirming the message bo
57. ple Realtime Operating System RTOS providing the following features E Open Source E Modular design mE Highly portable AVR and ARM7 available more to come E Cooperative multithreading E Event queues E Dynamic memory management E Timer support E Stream I O functions E Expandable device driver interface E File system support Nut Net Features Nut Net is a TCP IP stack providing E Open Source E ARP IP UDP ICMP and TCP protocol over Ethernet and PPP E Automatic configuration via DHCP m HTTP API with file system access and CGI functions E SNTP DNS Syslog TFTP FTP and more mE TCP and UDP socket API for other protocols The first decision that has to be made for the AVR platform is to select the development environment you want to use either ImageCraft s ICCAVR or GNU s AVR GCC The commercial ImageCraft Compiler offers an advanced IDE and is the first choice of most professional developers using a Windows PC The GNU compiler is available for Linux and Windows For the ARM platform only GCC had been tested The next chapters will guide you to quickly set up and start Nut OS application development for each environment It is assumed that you are using Nut OS 3 9 9 or above Ethernut Software Manual Quick Start with ICCAVR Getting a professional environment up and running Users of GCC will skip this chapter Not all sample applications may run with the demo version A license is available from most distribu
58. protocol UDP The advantage of the User Datagram Protocol UDP is its reduced overhead User data is encapsulated in only eight additional header bytes and needs not to be buffered for retransmission However if telegrams get lost during transmission the application itself is responsible for recovery Note also that in complex networks like the Internet packets may not arrive in the same order as they have been sent Applications should use the socket API to make use of the UDP protocol ICMP The Internet Control Message Protocol Nut Net automatically responds to an ICMP echo request with an ICMP echo reply which is useful when testing network connections with a Packet InterNet Groper PING program which is available on nearly all TCP IP implementations for desktop computers IP The Internet Protocol is used by UDP and TCP Typical applications do not directly use this network layer ARP The Address Resolution Protocol is used by IP over Ethernet to resolve IP and MAC address relations Ethernet Protocol This physical network layer is used by IP ICMP and ARP Nut Net PPP The Point to Point is as an alternative to the Ethernet protocol and can be used with serial ports modems GPRS etc Nut Net provides PPP client mode only That means other nodes can be actively connected but Nut Net can t listen to incoming connection attempts This is related to establishing PPP connections and should not be confused wi
59. r s settings dialog you can simple enter make burn to upload the hex file to the Ethernut Otherwise consult the documentation of your AVR programming software Running the Embedded Webserver Running the Embedded Webserver Connecting the 8 bit world Although this chapter looks quite window ish it s targeted to Linux users too In the previous chapters we compiled the binary for our first Nut OS application an embedded webserver and uploaded it to the Ethernut board Most application samples use the serial port of the Ethernut board to provide some feedback about program progress or any kind of errors that may occur Connect the serial port of your Ethernut with one of the serial ports on your PC using the cable that came with your Ethernut Starter Kit or any 1 1 DB 9 cable There s no need to switch off the Ethernut serial ports are quite safe and protected against shortcuts or electrical discharge But remember not to touch any bare contacts on the Ethernut board before taking some pre cautions Dissipate static electricity by touching a grounded metal object Eigenschaften yon COM2 21x Now start your favorite terminal emulator on Anschiusseinstellungen the PC or use the standard Hypertem on Windows The required settings for the serial Bits pro Sekunde EFE port are 115200 Baud eight data bits no parity one stop bit and no handshake Datenbits 8 Paritat Keine Stoppbits fi Flusssteuerung Kein
60. ress of the Ethernet controller A MAC address also referred to as the hardware or Ethernet address is a unique number assigned to every Ethernet node The upper 24 bits are the manufacturer s ID assigned by the IEEE Standards Office The ID of Ethernut boards manufactured by egnite Software GmbH is 000698 hex The lower 24 bits are the board s unique ID assigned by the manufacturer of the board Nut Net will store this address in EEPROM but we may also define a static variable to keep it in the application static u_char mac 0x00 0x06 0x98 0x09 0x09 0x09 The two remaining parameters of NutNetlfConfig are used to specify the minimum IP Internet Protocol information the IP address of our node and the network mask In our example we simply set both to zero which will invoke a DHCP client to query this information from a DHCP server in the local network 43 Ethernut Software Manual Therefore it may take some seconds until the call returns depending on the response time of the DHCP server If there s no DHCP server available in your network you must specify these two 4 byte values in network byte order In this byte order the most significant byte is stored at the first address of a multi byte value which differs from the byte order used by AVR processors our host byte order Fortunately Nut Net provides a routine named inet_addr which takes a string containing the dotted decimal form of an IP address and returns the req
61. rint Undo Redo Cut Copy Paste Find Replace UserConf mk X Automatically created on Sat Sep 11 19 51 15 2004 You can use this file to modify values in NutConf mk a HWDEF DETHERNUT2 Ln 6 Col 21 If you are creating the sample directory again using the same path then the Configurator will overwrite all changes but it will never modify UserConf mk We are ready to build the webserver application and program the resulting binary into the target board Change to the httpd subdirectory within the sample directory and enter make clean followed by make all Quick Start with AVR GCC on Linux Check that no errors occurred during this process As a result you will find the newly created binary file named httpd hex in Intel hex format For Linux we need to modify the file app Makeburn avr dude in the source directory Change the line BURNPORT com1 to BURNPORT dev ttyS0 If not already done connect your programming adapter to the Ethernut board and the proper PC interface and power up the Ethernut In case you selected the correct adapter in the Configurator s settings dialog you can simple enter make burn to upload the hex file to the Ethernut You may consult the documentation of your AVR programming software 21 Ethernut Software Manual 22 Quick Start With WinAVR Running free tools out of the box Installing AVR GCC on Windows WinAVR pronounced whenever is a suite of
62. rnut 1 3 Rev G ucrtenutram o c ethernut 3 9 9 nutbld lib nutinit o This will instruct the compiler to use a Nut OS specific runtime initialization routine The main difference to the standard routine is that Nutlnit is called before main so any RTOS specific initialization is hidden from your application code You can simply start coding main while the idle thread and the Nut OS timer is already running in the background In fact main is started as a Nut OS thread This feature makes Nut OS applications look like normal C programs and preserves portability Most Nut OS applications will need more than the 4 kBytes of RAM provided internally by the ATmega CPU Thus the compiler is intentionally set to External 32k SRAM You can find more information about this topic in a separate document named Nut OS Memory Considerations We ignore the last page for Salvo settings Salvo is another RTOS similar to Nut OS Press OK to close the Compiler Option Window Specially for our HTTP Server project another entry in Tools Menu will be helpful Select Configure Tool and add the following entries in the Edit Tool Menu Dialog Configure Tool x Menu Name Create urom c Snem Add Program c ethernut Change 3 9 9 nut tools win32 crurom exe Parameters r ourom c sample Delete Initial Directory c ethernut Program Options 3 9 9 nutapp httpd Menu Name Create ome _ Clear Fields Activate Capture Output Program 3 c tethe
63. rnut 3 231nutt Browse pre a F Parameters j F The crurom utility converts all files in a directory Li x nitial Directory fo 39 to a C source file This is used to include HTML ent EEEE a a r w Capture Output onsole Mode Program only files images Java Applets or other stuff into the rr dan Quick Start with ICCAVR Webserver s simple file system The C source will be compiled and linked to the Nut OS code Creating the First Nut OS Application By default Nut OS uses DHCP to automatically setup its TCP IP configuration Even without DHCP typical applications will store these settings in the on chip EEPROM In order not to overload this tutorial we will use hard coded addresses ImageCraft IDE for ICCA R PROFESSIONAL ol x File Edit Search View Project Studio RCS Tools Terminal Help A ALA IE CEE httpserv c Project Browser x amp HTTPD Simple multithreaded HTTP daemon 2 Files ty urom e lt p httpserv c These values are used if there is no valid configure O Headers amp Documents define MYMAC 0x00 0x06 0x98 0x00 0x00 0x00 index html define MYIP 192 168 192 100 form htm define MYMASK 255 255 255 0 l E C Sethermnutinutsapp shttpdshttpserv c C ethernut nut appiccShttpd 4 Open the file httpserv c in the integrated editor Consult your ICCAVR manual on how to do this and how to use the
64. rver is working The following chapters will introduce Nut OS and Nut Net in more detail Some of you may not be able to follow every part Don t worry Try to code a few basic samples and have a look to the list of books at the end of this manual Nut OS Nut OS A kernel routine overview Check the Nut OS API Reference for a detailed description Be aware that this chapter makes no attempts to explain details of the C language It is assumed that you have a basic knowledge of C programming System Initialization By default C programs are started with a routine called main This isn t much different in Nut OS however the operating system requires certain initialization before the application is started This initialization is included in a module named nutinit It will initialize memory management and the thread system and start an idle thread which in turn initializes the timer functions Finally the application main routine is called Because there s nothing to return to this routine should never do so A sample application called simple demonstrates the most simple application that could be build with Nut OS It does nothing else than running in an endless loop consuming CPU time include lt compiler h gt int main void for The file compiler h is included to fix a problem with AVR GCC which insists on setting the stack pointer again on entry to main When using this compiler main is re defined to
65. s step created the following AVR libraries E libnutcrt a C runtime support library E libnutcrtf a C runtime support library with floating point E libnutdev a Device driver library E libnutfs a File system library 26 Quick Start with WinAVR E libnutnet a Network library E libnutos a RTOS kernel library E libnutpro a Protocol library E nutinit o RTOS initialization If this fails check your settings again If you can t determine the problem try the command line to fix this or at least find out more about what went wrong Open a DOS command line window change to the build directory and enter set PATH c ethernut 3 9 6 nut tools win32 SPATHS to add the directories containing the Nut OS tools to your PATH environment Depending on your WinAVR installation it may be required to add two more directories set PATH c WinAVR bin c WinAVR utils bin PATHS To manually build the libraries enter make clean followed by make install At the end you should see some kind of error message Best check the Ethernut FAO or ask the Ethernut mailing list for further assistance Creating the First Nut OS Application Although possible we will not modify the source directory which contains the application samples Instead we will use the Configurator to create a copy of the sample directory for us Select Create Sample Directory from the Build entry of the Configurator s main menu After confirming the message box the
66. tems and may be changed in later Nut Net releases Another socket option allows to modify the TCP maximum segment size unsigned long to 1024 NutTcpSetSockOpt sock TCP_MAXSEG amp mss sizeof mss It is also possible to define an initial TCP window size unsigned long win 8192 Nut TcpSetSockOpt sock SO RCVBUF gwin sizeof win 39 Ethernut Software Manual 40 The maximum segment size MSS and the initial window size may become useful when you need the maximum TCP throughput The 8 bit AVR CPU running at 14 7456 MHz on the Ethernut easily reaches 2 MBit with the default values One last note to an often asked question The number of concurrent connections is limited by memory space only It is generally no problem to run several TCP and or UDP server and or client connections on a single Ethernut The application may even use the same socket in more than one thread HTTP The Hypertext Transfer Protocol HTTP is based on TCP Nut Net offers a set of helper APIs to simplify writing Embedded Webservers which are described in detail in the Nut OS API Reference TCP The Transmission Control Protocol TCP is a connection oriented protocol for reliable data transmission Nut Net takes care that all data is transmitted reliable and in correct order On the other hand this protocol requires more code and buffer space than any other part of Nut Net Applications should use the socket API to make use of the TCP
67. ters which are related to GCC 13 Ethernut Software Manual 14 Quick Start with AVR GCC on Linux Using free tools on a free platform Installing AVR GCC on Linux The Windows version of the compiler will be presented in the next chapter The following packages are required to build and install an AVR development environment on Linux E GNU Binutils 2 14 E GNU Compiler Collection GCC 3 3 E AVR Libc E avrdude 5 0 Detailed information is available at www nongnu org avr libc user manual install_tools html Installing Nut OS The installation for Linux is as a compressed tar file Execute bzip2 d ethernut X Y Z src tar bz2 tar xvf ethernut X Y Z src tar where XYZ has to be replaced by the version number Change to the newly created directory ethernut X Y Z and run configure However make sure to have the following source packages installed E wxGTK 2 6 0 tar bz2 E lua 5 0 2 tar gz E doxygen 1 4 2 E graphviz 2 2 1 There may be binary packages for your specific Linux variant available too Make sure that they were build from exactly these sources Configuring Nut OS It is assumed that you are running a GTK based window manager Change to the parent of the installation directory and enter nutconf This will execute the Nut OS Configurator In this chapter we will not explain the details of this tool but concentrate on the AVR GCC specific settings Quick Start with AVR GCC on Linux Select a file
68. th TCP UDP client and server capabilities which are fully available over PPP 802 11 WLAN Working with PCMCIA and CF cards but experimental Bluetooth Seems to be working too but not included Visit http otnode ethz ch for more information Conversion Functions If multi byte values are to be transferred over the network in binary form the most significant byte must always appear first followed by less significant bytes This is called the network byte order which differs from the host byte order the order how multi byte values are stored in memory The AVR compilers store least significant bytes first Several functions are provided to swap bytes from network byte order to host byte order or vice versa htonl and htons convert 4 byte resp 2 byte values from host to network byte order while ntohl and ntohs convert 4 byte resp 2 byte values from network to host byte order More conversions are provided by inet_addr and inet_ntoa While the first converts an IP address from the decimal dotted ASCII representation to a 32 bit numeric value in network byte order the second routine offers the reverse function Network Buffers Nut Net uses a special internal representation of TCP IP packets which is designed for minimal memory allocation and minimal copying when packets are passed between layers Application programmers don t need to care about this internal stuff It is included here in case you might become int
69. thernet MAC address to be assigned to the node first which can be passed to NutDhcplfConfig or may not be passed in which case the DHCP client expects this address in EEPROM The following table lists all Nut Net specific item stored in the EEPROM Type Default Description Total size of the Byte value 31 configuration structure Used to check validity Name of the network interface Maximum size is 8 characters Character array 6 byt i MAC mac Byte array 000698000000 ke address 37 Ethernut Software Manual 38 A certain part of code has been proven to fulfill most requirements if NutDhcpIfConfig eth0 0 60000 u_char my mac 0x00 0x06 0x98 0x20 0x00 0x00 if NutDhcpIfConfig eth0 my mac 60000 u long ip addr inet_addr 192 168 192 100 u long ip mask inet addr 255 255 255 0 NutNetIfConfig eth0 my mac ip addr ip mask In the first call to NutDhcplfConfig no MAC address is passed If one is found in EEPROM then the DHCP server will be queried for the related IP settings and the function returns 0 Otherwise it returns 1 but we do not know wether the EEPROM doesn t contain a valid MAC address or DHCP failed Thus NutDhcplfConfig is called once again but this time with a hard coded MAC address If it fails again then we are sure that there is no valid EEPROM contents and no available DHCP server Last thing we can do is to pass a hard coded IP address and IP mask
70. tors of the Ethernut Hardware or from ImageCraft directly Installing ICCAVR This guide has been tested with ICCAVR Version 7 03C with Beta2 Patch and may work with Version 6 31A Please follow the installation instructions that came with your compiler By default the target directory will be C icc7avr or C iccavr for the Version 6 Installing Nut OS The installation for Windows is packed into a self extracting executable named ethernut X Y Z exe where X Y Z has to be replaced with the version number The file contains the complete code some Nut OS tools and the API reference Installer Language x After starting the installation you can choose the Please select a language language The selected language is used during the installation only All other parts and the Nut OS English tl documentation are available in English only coca Nut 0S 3 9 9 Setup i m fed After selecting the installer language and clicking OK a welcome screen will appear Click Next to continue Welcome to the Nut OS 3 9 9 Setup Wizard This wizard will guide you through the installation of Nut OsS 3 9 9 It is recommended that you close all other applications before starting Setup This will make it possible to update relevant system files without having to reboot your computer Click Next to continue i Cancel Quick Start with ICCAVR nutyos 3 9 3 setup lc x Choose Components Th e next d
71. uggestions or even jokes Many Internet sites offer them for download via http or ftp Postel Jon RFC768 User Datagram Protocol Postel Jon RFC791 Internet Protocol Postel Jon RFC792 Internet Control Message Protocol Postel Jon RFC793 Transmission Control Protocol Plummer D C RFC826 Ethernet Address Resolution Protocol Braden R T RFC1122 Requirements for Internet Hosts Communication Layers T Berners Lee R Fielding and H Frystyk RFC1945 Hypertext Transfer Protocol 47 Ethernut Hardware Manual 48 Web Links http www ethernut de http www egnite de http www atmel com http www avrfreaks org http www imagecraft com Ethernut support Ethernut Online Shop Manufacturers of AVR microcontrollers Lots of useful infos about AVR microcontrollers Compilers with commercial support Troubleshooting The source file urom c is missing On the initial compile or after running make clean this file does not exist It will be created by the crurom utility With GCC try make urom c to find out what s going wrong In most cases make can t find the crurom utilicy because it is not in the PATH environment On Linux you may have to build this tool first Change to the directory nut tools crurom and run make install When using ImageCraft follow the instructions in this manual to create a tool menu entry for crurom exe Unfortunately you need to edit this entry w
72. ugh a typical Nut Net application This chapter explains how to use Nut OS and Nut Net to create a simple TCP server program Initializing the Ethernet Device As with other Nut OS applications you need to declare a function named main containing an endless loop The loop should call NutSleep or any other blocking function to enable sibling threads to take over the CPU include lt sys timer h gt int main void for NutSleep 500 To communicate via Ethernet you have to initialize the Ethernet hardware This takes two steps The first is to register the device A call to NutRegisterDevice will add all hardware dependent routines and data structures to your final code The I O port address and interrupt number parameters of this call are left for historical reasons and ignored by most device drivers NutRegisterDevice amp devEthO 0 0 devEth0 is the device information structure of the LAN device driver It contains the device name eth0 the type of this interface IFTYP_NET and among other things the address of the hardware initialization routine NutRegisterDevice will set up some data structures and initialize the controller hardware Network devices require specific configurations which is done by calling NutNetIfConfig eth0 mac 0 0 The first parameter is the name of the registered device The second parameter needs some additional attention It s an array of 6 bytes containing the MAC add
73. uired 4 byte value in host byte order If you want to assign IP address 192 168 171 2 with a network mask of 255 255 255 0 call NutNetIfConfig eth0 mac inet_addr 192 168 171 2 inet_addr 255 255 255 0 NutNetlfConfig will initialize the Ethernet controller hardware and should lit the link LED on your board if it is properly connected to an Ethernet hub or switch At this point Ethernut will already respond to ARP and ping requests include lt dev nicrtl h gt include lt sys timer h gt include lt arpa inet h gt static u_char mac 0x00 0x06 0x98 0x09 0x09 0x09 int main void NutRegisterDevice amp devEth0 0x8300 5 NutNetIfConfig eth0 mac 0 0 for NutSleep 500 Connecting a Client With a Server Up to now we followed the standard path common to all TCP IP applications created for Ethernut The next task is to create the application specific part In order to communicate via TCP we need a TCP socket which is actually a data structure containing all information about the state of a connection between two applications TCPSOCKET sock sock NutTcpCreateSocket This call allocates the data structure from heap memory initializes it and returns a pointer to the structure The next step specifies wether we take over the client or the server part of the communication As a client we would try to connect to a specified host on a specified port number Here s an example
74. urations they allow to set include directories which will be Build Directory searched before First or after Last the mometharalletherrut 39 9 bd 21b Browse standard directories in the source tree Install Directory When building Nut OS the Configurator nometharakethernut 3 9 5 bl4 21bib Browse will automatically add all Nut OS include directories x Abbrechen It is important to note that we distinguish between the source directory and the build directory The big advantage is that we are able to create several system builds for different configurations from a single source tree e g building Nut OS for different Ethernut board revisions The build directory can be located anywhere but it is recommended to use a sibling of the source directory and choose a meaningful name Using the Browse button offers to create new directories Finally enter an Install Directory It is a good idea to choose a directory within the build tree e g ethernut 3 9 9 bld lib After system build the Configurator will copy the libraries to this destination Quick Start with AVR GCC on Linux NutConf Settings On the third page enter the paths to the Repository Buid Tools Samples directories containing the required tools Tool Paths separated with semicoli Do not miss to add a semicolon after the last path The Nut OS tools should be first followed by any optional directory which ts not included in your PATH e
75. urs every 62 5 ms by default but may vary depending on the configuration The following minimal application will run in an endless loop but spend most of the time sleeping for 125 milliseconds two system clock ticks During sleep time any other thread may take over However if no other thread is ready to run or as in our example no other threads had been created CPU control is passed to the Nut OS Idle Thread include lt sys timer h gt int main void for NutSleep 125 Another useful routine is NutGetCpuClock which returns the CPU clock in Hertz 32 Nut OS Beside these directly called API routines device timeouts are handled by the timer management The following code fragment opens device uart0 for binary reading and writing and sets the read timeout to 1000 milliseconds int com unsigned long tmo 1000 com _open uart0 _O RDWR O BINARY _ioctl com UART_SETREADTIMEOUT amp tmo Note that Nut OS uses on chip hardware timer 0 of the ATmega CPU All remaining timers are available for the application You can use them in cases where the system timer resolution is insufficient Heap Management Dynamic memory allocations are made from the heap The heap is a global resource containing all of the free memory in the system The heap is handled as a linked list of unused blocks of memory the so called free list Applications can use standard C calls to allocate and release memory
76. x the Configurator will create a new or update an existing directory for application development and fill in a copy of the Nut OS sample applications Configuring ImageCraft Everything is ready to try our first Ethernut project Go back to the ImageCraft IDE If it has been started for the first time the IDE will appear without any opened project A ImageCraft IDE for ICCAYR ADYANCED Dongle Yersion File Edit Search wiew Project Studio RCS Tools Terminal Help ReWsgi esal Ss Daeel xe Project Browser Itt NO PROJECT OPEN 15 x No Open File Select Open from the project menu navigate to the Nut OS sample directory and load the project file httpd prj which is located in the subdirectory httpd The prepared webserver project Suchen in Bha see contains most required settings Later htedps on you will create your own projects and refer to the following steps to configure it If the project files in your Nut OS distribution had been created for a Dateiname EME different version of the ImageCraft Dateisp Project Fiesp Abbrechen compiler you will see a warning message reminding you to select the correct target You can ignore this for now we will get to this step anyway IT Schreibgeschiitzt ffnen Select Options from the project menu and click on the tab named Paths Two additional paths Quick Start with ICCAVR Compiler Options i x Paths

Download Pdf Manuals

image

Related Search

Related Contents

Yamam  X-MINI II Capsule  Series 90-20 Programmable Controller User`s Manual, GFK  LittoLevureTM B52  Best Barns belmont_1216 Instructions / Assembly  111620  Silence Sensor User Manual  Aquarius iNtuition Mobile (AQMobile)  こ.こ ・・退 團TA 冊  CASE/ CardioSoft  

Copyright © All rights reserved.
Failed to retrieve file