Programmer’s Guide for Moxa’s Windows CE Embedded Computers Third Edition, March 2008 www.moxa.com/product © 2008 Moxa Inc., all rights reserved. Reproduction without permission is prohibited.
Programmer’s Guide for Moxa’s Windows CE Embedded Computers The software described in this manual is furnished under a license agreement and may be used only in accordance with the terms of that agreement. Copyright Notice Copyright © 2008 Moxa Inc. All rights reserved. Reproduction without permission is prohibited. Trademarks MOXA is a registered trademark of Moxa Inc. All other trademarks or registered marks in this manual belong to their respective manufacturers.
Table of Contents Chapter 1 Installing Development Tools .....................................................................1-1 Visual Studio 2005................................................................................................................... 1-2 Installing Visual Studio 2005 ....................................................................................... 1-2 Uninstalling Microsoft .Net Compact Framework 2.0 ................................................. 1-2 Installing the .
1 C h apt er 1 Installing Development Tools A number of well-known Integrated Development Environments (IDE) tools can be used to ease the development of applications on Moxa Windows® CE embedded computers. Choose the tools based on the application language that you plan to use, and then install the tools on your development workstation. C++ developers can choose Visual Studio 2005 or eMbedded Visual C++ 4.0 (eVc 4.0). eMbedded Visual C++ 4.
Windows CE Programmer’s Guide Installing Development Tools Visual Studio 2005 Microsoft® Visual Studio 2005 is a complete set of development tools for building ASP.NET Web applications, XML web services, desktop applications, and mobile applications. The same IDE is used by Visual Basic, Visual C++ and Visual J#, allowing them to share tools and facilitating the creation of mixed-language solutions. Visual Studio 2005 Setup will install .Net Compact Framework 2.0 on your development station.
Windows CE Programmer’s Guide Installing Development Tools 2. Click Remove to confirm that you would like to remove the software. 3. Wait patiently while the software is uninstalled from your computer. 4. Click Finish to exit the wizard. You may now install Service Pack 1 for.Net Compact Framework 2.0.
Windows CE Programmer’s Guide Installing Development Tools Installing the .Net Compact Framework 2.0 with Service Pack 1. Wait while the Windows Installer prepares to install the software. 2. Click Next to proceed with the installation. 3. Select I accept the terms in the license agreement and click Next to proceed.
Windows CE Programmer’s Guide Installing Development Tools 4. Select Complete and click Next to proceed. 5. Click Install to begin installing the software. 6. Wait patiently while the software is installed.
Windows CE Programmer’s Guide 7. Installing Development Tools Click Finish to complete the installation procedure. eMbedded Visual C++ (eVC) 4.0 The eVC 4.0 tools can be downloaded for free from the MSDN’s eMbedded Visual Tools Download Page. Install the eVC 4.0 tools, and then install the service pack in the following order: y y y Install eMbedded Visual C++ 4.0 (230 MB) Install Service Pack 4 for eVC 4.0 (68 MB) Install Moxa Windows® CE C/C++ SDKs NOTE: Only Windows CE 5.
Windows CE Programmer’s Guide Installing Development Tools http://www.microsoft.com/downloads/details.aspx?FamilyID=0856EACB-4362-4B0D-8EDD -AAB15C5E04F5&displaylang=en NET Framework 2.0 Software Development Kit (SDK) (x86) (354 MB) http://www.microsoft.com/downloads/details.aspx?FamilyID=FE6F2099-B7B4-4F47-A244-C 96D69C35DEC&displaylang=en 3. Assuming that you have saved these two files as dotnetfx and setup, take the following steps to install the tools: y Execute the program dotnetfx. y Install .
Windows CE Programmer’s Guide Installing Development Tools 2. Type your name for User Name, and the name of your company for Organization. Click Next to proceed. 3. To install all functionality provided with the SDK, click Complete and then click Next.
Windows CE Programmer’s Guide Installing Development Tools 4. To change the name of the folder in which the SDK will reside, click Change and browse to the folder. Otherwise, click Next to proceed. 5. To install the SDK, click Install.
Windows CE Programmer’s Guide Installing Development Tools 6. Wait patiently while the software is installed. 7. When the installation is complete, click Finish to close the installer.
2 C h apt er 2 Application Development Application developers that are familiar with Windows® IDE tools and application programming interfaces (APIs) will appreciate the versatility of scripting languages that is found with Windows® CE and the .NET Compact Framework environment. The Moxa SDK enables developers to easily develop native code for Moxa embedded computers. In this chapter, we present examples using Visual Studio 2005 and eMbedded Visual C++ 4.
Windows CE Programmer’s Guide Application Development Developing an Application with Visual Studio 2005 • • • • • • • • • • • Open Microsoft® Visual Studio .Net 2005. From the File menu, choose New Æ Project. Choose the Project Type and then select the Smart Device Application as the type of project. Fill in the project name and click OK. Choose Windows CE as the target platform. Select the desired project type and click OK. Write your application code. From the Device toolbar, choose Windows CE.
Windows CE Programmer’s Guide 6. Click Device Option. 7. Click Properties….
Windows CE Programmer’s Guide Application Development 8. Click Configure…. 9. Click the Use specific IP Address radio button and enter the network address of the embedded computer. Click OK to continue. 10. Click the Connect to Device button.
Windows CE Programmer’s Guide Application Development 11. Wait for the connection to be made. 12. You may now start the debugging process. Developing an eMbedded Visual C++ 4.0 Application 1. Before you perform on-line debugging, please make sure that no other ActiveSync device is connected to your workstation. 2. Open Microsoft® eMbedded Visual C++ 4.0. 3. From the File menu, choose New. 4. Choose the Projects tab and then select the type of application that you would like to build.
Windows CE Programmer’s Guide Application Development 5. Choose the type of application that you would like to create and then click Finish. 6. From the Build toolbar, choose the SDK (UC7400CE1.0 for this example), the type of run-time image (Release or Debug), and the target device (UC7400CE1.0 Device for this example).
Windows CE Programmer’s Guide Application Development 7. Write your code. 8. From the Build menu, choose Rebuild All to compile your application. 9. If the following window pops up, you may disregard it. The message is generated by ActiveSync while developing a mobile application. Your computer is not a mobile device. 10. When you complete your application, upload it to the embedded computer. 11. Log on the embedded computer and execute the program at the console prompt.
Windows CE Programmer’s Guide Application Development 5. Back to eMbedded Visual C++ 4.0 and open or create a project. 6. Select the right SDK and the Win32 (WCE ARMV4I) DEBUG option. 7. Set break points in your source code and press F5 to start the on-line-debug. 8. On the popup Manuel Server – Action window, copy the string inside the text box. NOTE: Do NOT click OK or Cancel at this time! 9. Log on the embedded computer using a Telnet client.
Windows CE Programmer’s Guide Application Development 10. Paste the copied string to the Telnet window, and then press Enter. 11. Return to the Manuel Server – Action window and click OK to start a connection. 12. The following window will appear: 13. When a successful connection has been established, use F10 for code debugging.
3 C h apt er 3 Programming Examples In this chapter, we present Before You Begin Programming ¾ Understanding the File System ¾ Use the Flash Memory Cautiously ¾ Storing Data in RAM vs.
Windows CE Programmer’s Guide Programming Examples Before You Begin Programming Understanding the File System Before you begin programming your embedded computer, you should take time to understand the file system used by the embedded computer’s operating system, and the characteristics of the storage media. This knowledge will help you make better use of the embedded computer’s resources, and as a result, develop more efficient and effective applications.
Windows CE Programmer’s Guide Programming Examples Storing Data in RAM vs. Flash Memory Although data saved in RAM will be deleted when the system shuts down, RAM storage has the advantages of faster read/write access and no life cycle. For applications that require transmitting important data immediately and directly to a host, you can store the necessary log data in RAM. After the host receives the data, the data does not need to be retained and can be deleted.
Windows CE Programmer’s Guide NOTE Programming Examples The programming examples for Moxa embedded computers are frequently updated. The latest examples can be downloaded from the following FTP site: ftp://esource.moxa.com/moxasys/WinCE_Examples/C#. C# Example—Moxa UART (RS-232/422/485) The following code is a C# sample program for the transmission of data to serial port COM3: This serial port can be configured to support RS-232, RS-422 or RS-485 operation mode.
Windows CE Programmer’s Guide Programming Examples OPEN_EXISTING, 0, IntPtr.Zero); if (comPort == INVALID_HANDLE_VALUE) return false; int nBytesReturned = 0; byte bIn = (byte)mode; byte bOut = 0; DeviceIoControl(comPort, MOXA_SET_OP_MODE, ref bIn, 1, ref bOut, 0, ref nBytesReturned, IntPtr.
Windows CE Programmer’s Guide Programming Examples private void ErrorEvent(object sender, SerialErrorReceivedEventArgs e) { Console.WriteLine(“error”); } private void DataReceived(object sender, SerialDataReceivedEventArgs e) { while (port.BytesToRead > 0) { Console.WriteLine(“Receiving Data: “ + port.ReadByte()); } } private bool IsOpen() { return port. IsOpen; } static void Main(string[] args) { MxComPortEx comPort = new MxComPortEx(“COM3:”, 115200); comPort.Open(); if (comPort.
Windows CE Programmer’s Guide using using using using Programming Examples System; System.Collections.Generic; System.Text; moxa; namespace test { class Program { static void Main(string[] args) { // start buzzer moxa.uc712x.Buzzer.BeepOn(); // wait 20 milliseconds System.Threading.Thread.Sleep(20); // stop buzzer moxa.uc712x.Buzzer.BeepOff(); } } } C# Example—Digital I/O (UC-7408-CE, IA-26X-CE, V468-CE) Digital input/output channels are featured in some models of embedded computer.
Windows CE Programmer’s Guide Programming Examples sdout = System.Console.ReadLine(); port = int.Parse(sdout); System.Console.Write(“DOut value=“); sdout = System.Console.ReadLine(); value = int.Parse(sdout); if (!moxa.uc7400.DigitalOutput.Set(port, value)) { System.Console.WriteLine(“set dout failed!”); break; } for (i = 0; i < 8; i++) { value = moxa.uc7400.DigitalOutput.Get(i); System.Console.WriteLine(“DOut{0}={1}”, i, value); } break; } sin = System.Console.ReadLine(); n = int.
Windows CE Programmer’s Guide Programming Examples C# Example—Function Keys (UC-7410-CE, UC-7420-CE) For embedded computers with programmable function keys, your application can drive them as shown in the following code examples. For example, your program can control a specified function key to trigger another application or switch your program between different operation modes. An internal service is pre-installed and mimics key presses for your application.
Windows CE Programmer’s Guide Programming Examples { // close function key object fkey[i].stop(); } } ~Program() { System.Console.WriteLine(“~Program()”); int i=0; for ( i=0; i<5; i++) { // remove object from memory fkey[i]=null; } fkey=null; } public void keyOnclick (object sender, int e) { System.Console.WriteLine(“key” + e.ToString() + “ clicked“); } } } C# Example—Real-time Clock (UC-74XX-CE, DA-66X-CE) The real time clock (RTC) is a hardware implementation of time.
Windows CE Programmer’s Guide Programming Examples try { if (args.Length == 0) { System.Console.WriteLine(“e.g. tcpsvr [port]\n”); return; } // Set the TcpListener on port 13000. Int32 port = int.Parse(args[0]); System.Console.WriteLine(“Listening port: “ + args[0]); TcpListener server = new TcpListener(port); // Start listening for client requests.server.
Windows CE Programmer’s Guide Programming Examples C# Example—TCP Client using using using using using System; System.Collections.Generic; System.Text; System.Net; System.Net.Sockets; namespace socketcli { class Program { static void Main(string[] args) { if (args.Length != 2) { System.Console.WriteLine(“socketcli [ip] [port]”); return; } IPHostEntry myIpHostEntry = Dns.GetHostEntry( args[0] ); Int32 port = Int32.Parse(args[1]); IPEndPoint myIpEndPoint = new IPEndPoint(myIpHostEntry.
Windows CE Programmer’s Guide Programming Examples myNetworkStream.Write(myReadBuffer, 0, myReadBuffer.Length); } } // Close the NetworkStream myNetworkStream.Close(); } catch (Exception exception) { Console.WriteLine(“Exception Thrown: “ + exception.ToString()); } Console.Write(Console.Read()); Console.Read(); } } } Visual C++ Examples A library (mxdev.lib) is provided to simplify application development. This library covers APIs for the buzzer, LCM, function key, and digital I/O devices.
Windows CE Programmer’s Guide Programming Examples C++ Example—Moxa UART (RS-232/422/485) The following C/C++ code shows a sample application that transmits text data from port COM3 to port COM4 in the RS-232 operation mode. The application opens these two ports, generates a thread to receive data from port COM4, and then executes as a main thread to transmit data to port COM3. #include “stdafx.h” #include #include
Windows CE Programmer’s Guide Programming Examples } CloseHandle(hCom); } int comPair(WCHAR *wComPort, WCHAR *rComPort, unsigned int baudrate) { HANDLE wCom, rCom; WCHAR sPort[64]; DWORD rtn, i, loop=0; unsigned char buffer[MAX_DATA_LEN]; HANDLE waitH = CreateEvent(NULL, FALSE, FALSE, NULL); if (waitH==NULL) return 99; /* create a handle to port “COM3” for transmitting data */ wsprintf(sPort, L”$device\\%s\0”, wComPort); wCom = createComHandle(sPort, baudrate); if (wCom==NULL) { printf(“Fail to create wri
Windows CE Programmer’s Guide Programming Examples Windows® API function CreateFile(...) opens a named file corresponding to a serial port. For serial ports COM10 or after, the file name must be prefixed by “$device\\”. For ports COM1 to COM9, the file name may be prefixed by “$device\\” but it is not required. API function GetCommState(..) is the standard function to obtain a serial port’s current parameters, such as baudrate, data bits (bytesize),parity and stop bits. API function SetCommState(...
Windows CE Programmer’s Guide Programming Examples returns 0. handle created by mxdio_init port number 0~7 callback function with prototype (unsigned int, unsigned int, unsigned int) macro DIN_EVENT_LOW_TO_HIGH or DIN_EVENT_HIGH _TO _LOW 10 milliseconds minimal */ int mxdio_set_input_event( HANDLE hndl, unsigned int port, mxdio_input_cb handler, unsigned int low_high, unsigned int tick_slot); /* this function starts a dispatcher to handle events.
Windows CE Programmer’s Guide Programming Examples In the example shown above, the dispatcher checks digit level changes every 20 milliseconds and every 30 milliseconds from the moment that the dispatcher function mxdio_dispatch() is called. If there is any change, the associated callback function is initiated. C++ Example—LCM (UC-7410-CE, UC-7420-CE) Certain models of embedded computer have an LCM, with text display managed by a pre-installed internal service.
Windows CE Programmer’s Guide Programming Examples C++ Example—Function Keys (UC-7410-CE, UC-7420-CE) For embedded computers with programmable function keys, your application can drive them as shown in the following code examples. For example, your program can control a specified function key to trigger another application or switch your program between different operation modes. An internal service is pre-installed and mimics key presses for your application.
Windows CE Programmer’s Guide Programming Examples hEvent = CreateEvent( NULL, FALSE, FALSE, NULL ); WaitForSingleObject( hEvent,20000 ); mxfkey_stop(); return 0; } C++ Example—TCP Client and TCP Server The following is an example of TCP client/server programming. To build a server program, compile this sample code in the eVC4.0++ tool with library ws2.lib to build a client program, compile same exact code in a Windows development tool, such as Visual Studio 6.0 with library wsock32. lib.
Windows CE Programmer’s Guide Programming Examples global_t global; #ifndef _WIN32_WCE /* --------- client program -------------------- */ static unsigned int send_bytes=0; int test_client_thread(LPVOID param) { static char *alphaNumber=“abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ”; int fd = (int) param; char buf[MAX_BUF_LEN]; int i,len; srand(RNADOM_SEED); while (send_bytes<0xfffffff) { len = rand()%1024; if (len ==0) continue; for (i=0; i < len; i++) buf[i] = 0; send(fd, buf, len, 0);
Windows CE Programmer’s Guide Programming Examples argv: ... */ void clients_post_init(int argc, char **argv, HINFO *hosts, int max) { int i; for (i=0; i < max; i++) { ipc_create_thread(test_client_thread, (void*)hosts[i].
Windows CE Programmer’s Guide Programming Examples #endif unsigned int lookup_ip (const char *host) { struct hostent *he; unsigned int ip; ip = inet_addr (host); if (ip == INADDR_NONE) { he = gethostbyname (host); if (!he) { printf (“lookup_ip: can’t find ip for host %s\n”, host); return 0; } memcpy (&ip, he->h_addr_list[0], he->h_length); } return ip; } /* set socket to be nonblocking */ int tcp_set_nonblocking (int f) { long val = 1; if (ioctlsocket (f, FIONBIO, &val) != 0) { printf (“tcp_set_nonblockin
Windows CE Programmer’s Guide Programming Examples return f; } /* bind a socket on a specific interface */ static int bind_interface (int fd, unsigned int ip, int port) { struct sockaddr_in sin; memset (&sin, 0, sizeof (sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = ip? ip:htonl(INADDR_ANY); sin.
Windows CE Programmer’s Guide Programming Examples if (bind_interface (sockfd, iface, port) == -1) return 0; if (listen (sockfd, 5) < 0) return 0; addr.s_addr = iface; printf(“startup a server %s at port %d\n”,inet_ntoa (addr),port); return sockfd; } void enable_read (int fd) { FD_SET ((unsigned int) fd, &global. read_fds); if (global.max_fd < fd) global.max_fd = fd; } void disable_read (int fd) { FD_CLR ((unsigned int) fd, &global.
Windows CE Programmer’s Guide Programming Examples p = cmdline; argc=1; while (argc < 32) { while(isspace(*p)) p++; if (*p==0) break; argv[argc++] = p; p = strchr(p, ‘ ‘); if (!p) break; *p = 0; p++; } #endif WSAStartup (MAKEWORD (2, 2), &wsa); memset(&global, 0, sizeof(global_t)); memset(hosts, 0, MAX_SOCKETS*sizeof(HINFO)); /* obtain listen ports from user-defined function */ num_ports = servers_init(argc-1, argv+1, hosts, MAX_SOCKETS); for (i = 0; i < num_ports; i++) { fd = tcp_startup_server(0, hosts[
Windows CE Programmer’s Guide Programming Examples /* handle connection requests */ for (i = 0; i < global.server_num; i++) { fd = global.servers[i].fd; if (FD_ISSET(fd,&read_fds)) accept_connection(fd); } } /* close all open file descriptors properly */ for (i = 0; i < global.client_num; i++) closesocket (global.clients[i].fd); for (i = 0; i < global.server_num; i++) closesocket (global.servers[i].fd); #ifdef WIN32 WSACleanup (); #endif return 0; C++ Example—Message Queue // MessageQueue.
Windows CE Programmer’s Guide Programming Examples while (TRUE) { // waiting for data goes into the Message Queue switch ( WaitForSingleObject(hMsq, 500) ) { case WAIT_OBJECT_0: // read data from message queue if ( ReadMsgQueue( hMsq, &m_data, sizeof(m_data), &dwRead, INFINITE, &dwflags) ) { dwDataRecvCount[m_data.id-1]++; dwDataRecvBytes[m_data.id-1] += m_data.
Windows CE Programmer’s Guide Programming Examples // close message queue CloseMsgQueue(hTask); return 0; } int getRand(int nID) { EnterCriticalSection(&cs); /* Seed the random-number generator with GetTickCount so that the numbers will be different every time we run.
A A p pe n di x A Frequently Asked Questions Q: I have an eVB3.0 program. Can I run it on the embedded computer? A: The old version of Embedded Windows CE programs cannot run on the embedded computer. The target computer is headless with no screen. It may only run applications that are at the console level. To port your console program, paste your source code into a new Visual Basic .Net 2005 console application project.
Windows CE Programmer’s Guide Frequently Asked Questions Q: What is the Moxa WinCE SDK? What can I do with it? A: This SDK allows you to write programs in C/C++ that will run on embedded computers. With this SDK installed in the environment of Microsoft Embedded Visual C++ 4.0 or Visual Studio 2005, you can develop WIN32 applications, DLL, and others. In addition, the SDK provides a C library, namely mxdev.lib, which allows control of the LCM, function keys, buzzer and other hardware devices.