CC3200 Tutorial

CC3200 Wi-Fi Project






If you own a CC3200 development board or want to learn about CC3200 WiFi SoC you will find this we page usefull.
It is a WiFi CC3200 example project I am currently working on. The web page is constantly reviewed and updated. Come back to this page once a week and you will find new updates to the project.
Have a comment, question, or need a project to develop?
Email to: info@cnktechlabs.com.







The goal of the project is to develop an IoT system with CC3200MOD or CC3200 development board and hopefully learn something new along the way. Created for the Internet of Things (IoT), the SimpleLink CC3200 Internet-on-a-chip solution is a wireless MCU that integrates a high-performance ARM Cortex-M4 MCU allowing the development of entire application with a single IC. What I am planning on doing at this point is to make modifications to the original code to monitor and control electronic devices that will be attached to the board. I am planning on adding analog interface. This chip can run as HTTP server or client which makes it possible to run cloud applications. I will be updating my design files as I go. At this point it is a beginning project. The code I am currently running can be found at: Project Source Code In this example CC3200 runs mysimplelink.com website, current web pages of the website can be found in the "flash" folder. The current code allows to remotely see data and interact with an external hardware.
The board can run as a client where it connects to TI's Exosite. The Exosite free account in the ti.exosite.com domain is provided by TI and Exosite for evaluation purposes. There are no time limits, you can choose to use it as long as you want (quote from the above webpage). The following 3 images show my phone connected to the dev board with CC3200 WiFi as an Access Point. CC3200 is in server mode and it runs mysimplelink.net webpage. Tune in for project updates. I am going to start with CC3200 run in web server mode.

The following image displays main components of the CC3200 development board:

To develop code you will need to download and install the CCS studio (v6 may not be the latest one).


Download source code files from Project Source Code Unzip the files and import them into the CCS studio.

To run the example in AP mode

  1. Clone the Project Source Code or download the zip and extract.
  2. Open Code Composer Studio v6.0 or greater.
  3. Import the project files:
    • Select "Projects -> Import CCS Projects..."
    • Browse for and select the folder you created in step one.
    • Check the box for this project in "Discovered Projects"
    • Click Finish
  4. Build The Project
  5. You can now flash the device using uniflash or run the debugger, but note that you must do a full system flash using uniflash at least once before you will be able to run the application in the debugger to install necessary supporting files.
  6. Open the ucf file using the uniflash tool, select the proper serial port and press the "Program" button, it may then ask you to press the reset button. Note that the board must be in flash more, do this by placing a jumper on the SOP2 header.
  7. Open a serial terminal application such as CoolTerm or Putty or termite and connect to the debugging serial port.
  8. Run the application.
    • Remove the SOP2 jumper.
    • Reset the board.
  9. Press and hold SW2 push button on the development board then press reset. If you are working with the original CC3200CloudDemo code place jumper to between P58 and 3.3V VCC. It will switch the board into AP mode.
  10. Connect to the "mysimplelink-XXXXXX" Access Point on smartphone, tablet or laptop and open the webpage at "mysimplelink.net".
  11. Take note of the MAC address of your board from the status page, you'll need it in a minute.
  12. Open the "Setup" page and enter your SSID, security type, and password of your WiFi network. Then click "Add."

Image of the setup page


The following 2 images show RED LED On and Off with the web page switch.

Image below will change on mouse over:

I am running CC3200 board in AP mode. AP mode allows me to communicate with the CC3200 development board directly from my mobile device. The CC3200 development board is connected to my cell phone via a WiFi connection.

Once CC3200 board is powered, open "Wi-Fi Settings" on your mobile device and connect to the "mysimplelink-XXXXXX" Access Point then go to "mysimplelink.net" webpage.

I have made a few changes to the mysimplelink.net welcome page, and now it looks as follows:

Access Point mode is used to connect the CC3200 board to wireless clients (wireless adapter cards) such as laptops, desktops with WiFi, and mobile devices. Wireless clients can only communicate to AP's in Access Point mode.
My cell phone is a wireless client connected to the TI's CC3200 board which is the HTTP server. The cell phone sends HTTP requests to the HTTP server and waits for the server responses.
In general, the HTTP protocol is a request/response protocol. A client sends a request to the server in the form of a request method, URI, and protocol version, followed by a MIME-like message containing request modifiers, client information, and possible body content over a connection with a server. The server responds with a status line, including the message’s protocol version and a success or error code, followed by a MIME-like message containing server information, entity metainformation, and possible entity-body content.


Uniform Resource Identifiers

URIs have been known by many names: WWW addresses, Universal Document Identifiers, Universal Resource Identifiers, and finally the combination of Uniform Resource Locators (URL) and Names (URN). As far as HTTP is concerned, Uniform Resource Identifiers are simply formatted strings which identify via name, location, or any other characteristic - a resource

http URL

The "http" scheme is used to locate network resources via the HTTP protocol. This section defines the schemespecific syntax and semantics for http URLs.
http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
If the port is empty or not given, port 80 is assumed. The semantics are that the identified resource is located at the server listening for TCP connections on that port of that host, and the Request-URI for the resource is abs_path. The use of IP addresses in URLs SHOULD be avoided whenever possible (see RFC1900). If the abs_path is not present in the URL, it MUST be given as “/” when used as a Request-URI for a resource (section 5.1.2). If a proxy receives a host name which is not a fully qualified domain name, it MAY add its domain to the host name it received. If a proxy receives a fully qualified domain name, the proxy MUST NOT change the host name.

URL is acronym of Universal Resource Locator and it’s used to locate the server and resource. Every resource on the web has it’s own unique address. Let’s see parts of URL with an example.

http://localhost:8080/Project/jsps/hello.jsp

http:// – This is the first part of URL and provides the communication protocol to be used in server-client communication.

localhost – The unique address of the server, most of the times it’s the hostname of the server that maps to unique IP address. Sometimes multiple hostnames point to same IP addresses and web server virtual host takes care of sending request to the particular server instance.

8080 – This is the port on which server is listening, it’s optional and if we don’t provide it in URL then request goes to the default port of the protocol. Port numbers 0 to 1023 are reserved ports for well known services, for example 80 for HTTP, 443 for HTTPS, 21 for FTP etc.

Project/jsps/hello.jsp – Resource requested from server. It can be static html, pdf, JSP, servlets, PHP etc.

Introducing IP Addresses

An IP address is a number that uniquely identifies every host on an IP network. An IP address (abbreviation of Internet Protocol address) is an identifier assigned to each computer and other device (e.g., printer, router, mobile device, etc.) connected to a TCP/IP network that is used to locate and identify the node in communications with other nodes on the network.
IP addresses operate at the Network layer of the TCP/IP protocol stack, so they’re independent of lower-level addresses, such as MAC addresses. (MAC stands for Media Access Control.)
IP addresses are 32-bit binary numbers, which means that theoretically, 232 = 4294967296 unique host addresses can exist throughout the Internet.

The primary purpose of Internet Protocol (IP) is to enable communications between networks. As a result, a 32-bit IP address consists of two parts:

  • The network ID (or network address): Identifies the network on which a host computer can be found
  • The host ID (or host address): Identifies a specific device on the network indicated by the network ID

IP addresses are usually represented in a format known as dotted-decimal notation. In dotted-decimal notation, each group of eight bits — an octet — is represented by its decimal equivalent. For example, consider the following binary IP address:

11000000101010001000100000011100

The dotted-decimal equivalent to this address is

192.168.136.28

Here, 192 represents the first eight bits (11000000); 168, the second set of eight bits (10101000); 136, the third set of eight bits (10001000); and 28, the last set of eight bits (00011100). This is the format in which you usually see IP addresses represented.

The IP protocol defines five different address classes: A, B, C, D, and E. Each of the first three classes, A–C, uses a different size for the network ID and host ID portion of the address. Class D is for a special type of address called a multicast address. Class E is an experimental address class that isn’t used.

The first four bits of the IP address are used to determine into which class a particular address fits:

  • If the first bit is 0, the address is a Class A address.
  • If the first bit is 1 and the second bit is 0, the address is a Class B address.
  • If the first two bits are both 1 and the third bit is 0, the address is a Class C address.
  • If the first three bits are all 1 and the fourth bit is 0, the address is a Class D address.
  • If the first four bits are all 1, the address is a Class E address.
Class Address Range Starting Bits Length of Network ID Number of Networks
on the internet
Number of Host
linked to the
Network
A 1–126.x.y.z 0 8 126 16,777,214
B 128–191.x.y.z 10 16 16,384 65,534
C 192–223.x.y.z 110 24 2,097,152 254


Example Code

To run the above example download CC3200CloudDemo or the Project Source Code, follow the steps described in the README.md file.
You will find a lot of useful information on: TEXAS INSTRUMENTS EXOSITEREADY™ PLATFORMS.
Connect your Wi-Fi mobile device or a computer to the board and run the example.

Breaking down the AP mode example (a direct connection between a WiFi client and CC3200 board).

All the magic of switching ON and OFF the RED LED happens inside the SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT server event. This event is a part of

void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent, SlHttpServerResponse_t *pSlHttpServerResponse)

function as shown in the image below (click on the image to enlarge).

Inside the callback you will find SL_NETAPP_HTTPGETTOKENVALUE_EVENT and SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT. The first one is used to get information from the CC3200 board, the second one is used to apply commands to the CC3200 board.



POST Token

POST_token tells the server, CC3200 board, to run a section of code in our case turn LED ON or OFF. This is the place in the code where you can add functions that will remotely control external LEDs and other devices.
The following code excerpt reads POST token value which is stored in EventData.httpPostData.token_name.data class. Based on the value received the LED is turned ON, OFF, blinked.


	
void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent, 
                                SlHttpServerResponse_t *pSlHttpServerResponse){
		....
		....
	case SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT:
        {
            unsigned char led;
            unsigned char *ptr = pSlHttpServerEvent->EventData.httpPostData.token_name.data;
            
           // memcmp reference: tutorialspoint
            // If the received token is "__SL_P_ULD"
            if(memcmp(ptr, POST_token, strlen((const char *)POST_token)) == 0)
            {
                ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;		// Read value sent by the demos-sprinkler.html page
                if(memcmp(ptr, "LED", 3) != 0)
                    break;
                ptr += 3; // The first 3 characters are "LED", skip them. Advance the pointer 3 characters forward.
                
                // The value of the variable that ptr points to in this case is character 1 or 2
                
                led = *ptr; // Read data poted by the ptr                 
                ptr += 2; // Advance the pointer 2 characters forward.
                if(led == '1')
                {
                    if(memcmp(ptr, "ON", 2) == 0)
                    {
                        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
                        g_ucLEDStatus = LED_ON;

                    }
                    else if(memcmp(ptr, "Blink", 5) == 0)
                    {
                        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
                        g_ucLEDStatus = LED_BLINK;
                    }
                    else
                    {
                        GPIO_IF_LedOff(MCU_RED_LED_GPIO);
                        g_ucLEDStatus = LED_OFF;
                    }
                }
                else if(led == '2')
                {
                    if(memcmp(ptr, "ON", 2) == 0)
                    {
                        GPIO_IF_LedOn(MCU_ORANGE_LED_GPIO);
                    }
                    else if(memcmp(ptr, "Blink", 5) == 0)
                    {
                        GPIO_IF_LedOn(MCU_ORANGE_LED_GPIO);
                        g_ucLEDStatus = 1;
                    }
                    else
                    {
                       GPIO_IF_LedOff(MCU_ORANGE_LED_GPIO);
                    }
                }

            }
        }
            break;
            ....
            ....
}
		


Web page "demos-sprinkler.html" and "page-actions.js" invoke the "$.post" method: $.post("No_content", {"__SL_P_ULD": params});

The "$.post" method controls the onboard RED LED. The following are two code excerpts from "demos-sprinkler.html" and "page-actions.js"

      	
		//demos-sprinkler.html
	if (switchBtn.hasClass('on')) {
    		switchBtn.removeClass('on');
    		com.TI.toggleLED('_OFF');		// Turn off the LED			
    		spriklerRunning = false;
    		sprinkler.attr('src',"images/demo-sprinkler-off.jpg");	
    		imageOn = false;
	} else {
    		switchBtn.addClass('on');
    		com.TI.toggleLED('_Blink');		// Turn LED ON		
    		spriklerRunning = true;
    		imageOn = true;
	}

	// page-actions.js
	com.TI.toggleLED = function(whichOne) {
    		var LEDnum = "1",
        	params = "LED"+LEDnum;
    		params += whichOne;
    		$.post("No_content", {"__SL_P_ULD": params});
	};

	        
	
	Web page "demos-sprinkler.html" calls com.TI.toggleLED('_Blink'); function from 
	"page-actions.js", which enacts $.post("No_content", {"__SL_P_ULD": params}) method.
	This $.post method enables RED LED turn on case 

		else if(memcmp(ptr, "Blink", 5) == 0)
	{
     		GPIO_IF_LedOn(MCU_RED_LED_GPIO);		// Turn On LED
     		g_ucLEDStatus = LED_BLINK;
	}
	else
	{
     		GPIO_IF_LedOff(MCU_RED_LED_GPIO);
     		g_ucLEDStatus = LED_OFF;
	}
	
	
	in the
	
	void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent, 
 		SlHttpServerResponse_t *pSlHttpServerResponse){
		...
	}
	
	

Changes

I did a few modifications to the original code. I have inserted a for loop into SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT shown below. This is the loop that runs the LEDs ON/OFF shown in the video below.
Download the updated code from My Github.

	
	case SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT:
        	{
            unsigned char led, i;
            unsigned long delay = 1000000;
            unsigned char *ptr = pSlHttpServerEvent->EventData.httpPostData.token_name.data;
            UART_PRINT("\n\n\rHTTP_POST: %s",ptr);  // add this line only
            //g_ucLEDStatus = 0;
            if(memcmp(ptr, POST_token, strlen((const char *)POST_token)) == 0) //"__SL_P_ULD"
            {
            	// static unsigned char POST_token[] = "__SL_P_ULD";
            	ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
                if(memcmp(ptr, "LED", 3) != 0)
                    break;
                ptr += 3;	// First 3 received characters are "LED"
                led = *ptr;	// has character '1'
                ptr += 2;	// Skips the _ character sent by the web page
                if(led == '1')
                {
                    if(memcmp(ptr, "ON", 2) == 0)
                    {
                        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
                        g_ucLEDStatus = LED_ON;

                    }
                    else if(memcmp(ptr, "Blink", 5) == 0) // com.TI.toggleLED('_Blink');
                    {
                    
		// The following is the loop that runs LEDs 50 times
                        for (i = 0; i < 50; i++){
                        	GPIO_IF_LedOn(MCU_RED_LED_GPIO);		// Turn On LED
                        	MAP_UtilsDelay(delay);
                        	GPIO_IF_LedOff(MCU_RED_LED_GPIO);		// Turn Off LED
                        	MAP_GPIOPinWrite(GPIOA3_BASE,0x10,0x10);
                        	MAP_UtilsDelay(delay);
                        	MAP_GPIOPinWrite(GPIOA2_BASE,0x40,0x40);
                        	MAP_UtilsDelay(delay);
                        	MAP_GPIOPinWrite(GPIOA3_BASE,0x10,0);
                        	MAP_UtilsDelay(delay);
                        	MAP_GPIOPinWrite(GPIOA2_BASE,0x40,0);
                        	MAP_UtilsDelay(delay);
                        }

GPIO_IF_LedOn(MCU_RED_LED_GPIO); // Turn On LED MAP_GPIOPinWrite(GPIOA2_BASE,0x40,0x40); // LED ON MAP_GPIOPinWrite(GPIOA3_BASE,0x10,0); // LED OFF g_ucLEDStatus = LED_BLINK; }

SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT tells the server to run the LEDs 50 times.

GET Token

Get token request information from the server. In this case temperature and acceleration values.
I also made a few changes to the GET method Get method is used to get data from the HTTP server.


//*****************************************************************************
//
//! \brief This function handles HTTP server events
//!
//! \param[in]  pServerEvent - Contains the relevant event information
//! \param[in]    pServerResponse - Should be filled by the user with the
//!                                      relevant response information
//!
//! \return None
//!
//****************************************************************************
void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent, 
                                SlHttpServerResponse_t *pSlHttpServerResponse)
{
    switch (pSlHttpServerEvent->Event)
    {
        case SL_NETAPP_HTTPGETTOKENVALUE_EVENT:     // Get data from the server
        {
            unsigned char *ptr;
            unsigned char *ptraccX;
            unsigned char *ptraccY;
            unsigned char *ptraccZ;
            unsigned char *uart;
            //unsigned char *tokenName;
            ptr = pSlHttpServerResponse->ResponseData.token_value.data;     // initialize pointer to location data: _u8     *data;
            pSlHttpServerResponse->ResponseData.token_value.len = 0;        // initialize length to zero
            UART_PRINT("\n\n\rHTTP_GET Tocken:\t %s",ptr);  // add this line only. Print string pointed by ptr. Basically .data will be printed
            if(memcmp(pSlHttpServerEvent->EventData.httpTokenName.data, 
                    GET_token_TEMP, strlen((const char *)GET_token_TEMP)) == 0) //__SL_G_UTP
            {
                float fCurrentTemp;
                TMP006DrvGetTemp(&fCurrentTemp);        // Get the temperature value and write it to fCurrentTemp
                char cTemp = (char)fCurrentTemp;        // 8 bit temperature value
                short sTempLen = itoa(cTemp,(char*)ptr);// Convert integer to ASCII in decimal base
                ptr[sTempLen++] = ' ';
                ptr[sTempLen] = 'F';
                pSlHttpServerResponse->ResponseData.token_value.len += sTempLen;

                //********************************************************************
                Report("\n\r Temperature HEX: \t");
                MAP_UARTCharPut(CONSOLE, (unsigned char) cTemp);
                Report("\n\r");
                //********************************************************************


            }

            if(memcmp(pSlHttpServerEvent->EventData.httpTokenName.data, 
                      GET_token_UIC, strlen((const char *)GET_token_UIC)) == 0)
            {
                if(g_iInternetAccess==0)
                    strcpy((char*)pSlHttpServerResponse->ResponseData.token_value.data,"1");    // LED ON
                else
                    strcpy((char*)pSlHttpServerResponse->ResponseData.token_value.data,"0");    // LED OFF
                pSlHttpServerResponse->ResponseData.token_value.len =  1;
            }
			if(memcmp(pSlHttpServerEvent->EventData.httpTokenName.data, 
                       GET_token_ACC, strlen((const char *)GET_token_ACC)) == 0)
            {

            	//unsigned char *str3;
            	//int i=0;
            	ReadAccSensor(); //float *pfCurrTemp
            	ptraccX = pSlHttpServerResponse->ResponseData.token_value.data;
            	//ptraccY = pSlHttpServerResponse->ResponseData.token_value.data;
            	//ptraccZ = pSlHttpServerResponse->ResponseData.token_value.data;
            	signed char cAccXT1, cAccYT1, cAccZT1;
            	//unsigned char cAccXTu, cAccYTu, cAccZTu;
            	unsigned char cAccYTu, cAccZTu;
            	//_u8     *cAccXT2;	//_u8     *data;
            	_u8     *cAccYT2;
            	_u8     *cAccZT2;	//_u8     *data;

            	BMA222ReadNew(&cAccXT1, &cAccYT1, &cAccZT1);

            	//cAccXTu = (unsigned char) cAccXT1;
            	cAccYTu = (unsigned char) cAccYT1;
            	cAccZTu = (unsigned char) cAccZT1;

            	//cAccXT2 = &cAccXTu;
            	cAccYT2 = &cAccYTu;
            	cAccZT2 = &cAccZTu;

            	//ptraccX = cAccXT2;
            	ptraccY = cAccYT2;
            	ptraccZ = cAccZT2;
            	
				// Convert integer to ASCII in decimal base. Convert x-axis value to a decimal string.
                short sLenAccX = itoa(g_accXIntervalSum,(char*)ptraccX);
                
                // String that contains Y-axis data
                short sLenAccY = itoa(g_accYIntervalSum,(char*)ptraccY);
                
                ptraccY[sLenAccY++] = ' ';
                // String that contains Z-axis data
                short sLenAccZ = itoa(g_accZIntervalSum,(char*)ptraccZ);
                
                ptraccY[sLenAccZ++] = ' ';
                ptraccX[sLenAccX++] = ' ';
                ptraccX[sLenAccX++] = ' ';
                ptraccX[sLenAccX++] = 'X';
                ptraccX[sLenAccX++] = '-';
                ptraccX[sLenAccX++] = 'a';
                ptraccX[sLenAccX++] = 'x';
                ptraccX[sLenAccX++] = 'e';
                ptraccX[sLenAccX++] = 's';
                ptraccX[sLenAccX++] = ' ';
                ptraccX[sLenAccX++] = ' ';
                ptraccX[sLenAccX++] = ' ';


                ptraccX[sLenAccX++] = ptraccY[0];
                ptraccX[sLenAccX++] = ptraccY[1];
                ptraccX[sLenAccX++] = ptraccY[2];

                ptraccX[sLenAccX++] = ' ';
                ptraccX[sLenAccX++] = ' ';
                ptraccX[sLenAccX++] = 'Y';
                ptraccX[sLenAccX++] = '-';
                ptraccX[sLenAccX++] = 'a';
                ptraccX[sLenAccX++] = 'x';
                ptraccX[sLenAccX++] = 'e';
                ptraccX[sLenAccX++] = 's';
                ptraccX[sLenAccX++] = ' ';
                ptraccX[sLenAccX++] = ' ';
                ptraccX[sLenAccX++] = ' ';

                ptraccX[sLenAccX++] = ptraccZ[0];
                ptraccX[sLenAccX++] = ptraccZ[1];
                ptraccX[sLenAccX++] = ptraccZ[2];

                ptraccX[sLenAccX++] = ' ';
                ptraccX[sLenAccX++] = ' ';
                ptraccX[sLenAccX++] = 'Z';
                ptraccX[sLenAccX++] = '-';
                ptraccX[sLenAccX++] = 'a';
                ptraccX[sLenAccX++] = 'x';
                ptraccX[sLenAccX++] = 'e';
                ptraccX[sLenAccX++] = 's';
                ptraccX[sLenAccX++] = ' ';
                ptraccX[sLenAccX++] = ' ';
                ptraccX[sLenAccX++] = ' ';
                
                UART_PRINT("\t\t Accelerometer data is sent \n\r");
            }   
            
            ....
            ....
            
            }
        }
            break;
        default:
            break;
    }
}        
	
	

Displaying data in the web browser

The following image shows the LED driver circuit diagram

V1 and V2 is the 3.3V on-board supply.

Web page "demos-appliances.html" runs com.TI.tokenPoller.js function. In turn com.TI.tokenPoller.js runs param_demos.html which lists all the GET tockens.
com.TI.tokenPoller.js function:

/*com.TI.tokenPoller.js*/

if(!window.com) com = new Object();
if(!com.TI) com.TI = new Object();
com.TI.tokenPoller = function(options) {
	var WIDGET_NAMESPACE = 'TITokenPoller',
		INSTANCE_INTERVAL_ID;
				
	// define some defaults at this level so that we can overwrite after it's been extended
	var defaults = {
			"paramPage": "somepage.html", 
			"refreshRate": 10 * 1000,
			"valueMap": [{
				"paramId": "",
				"outputSuccess": function(output) {},
				"outputDefault": function() {}
			}]
		},
		options = $.extend(defaults, options),
		invervalRunning = false;

	function intervalFunc() {
		$.ajax({
			"type": "GET",
			"url": options.paramPage,
			"cache": false,
			"dataType": "html"
		}).done(function(data, status, xhr) {
			var i = 0,
				len = options.valueMap.length;
			if (status != 'success') {
				for (i=0;i<len;i++) {
					options.valueMap[i].outputDefault();
				}
			} else {
				var dataPage = $(data);
				for (i=0;i<len;i++) {
					options.valueMap[i].outputSuccess(dataPage.filter('#'+options.valueMap[i].paramId).text());
				}	
			}
			invervalRunning = false;
		});
	}

	INSTANCE_INTERVAL_ID = setInterval(function(){
		if (!invervalRunning) {
			invervalRunning = true;
			intervalFunc();
		}
	}, options.refreshRate);

	this.destroy = function() {
		invervalRunning = false;
		clearInterval(INSTANCE_INTERVAL_ID);
	};
};



param_demos.html:

param_demos.html:

Working on the UART serial communication

Currently there are tree tockens defined in param_demos.html:

<p id="Device_Temperature">__SL_G_UTP</p>
<p id="Device_Accelerometer">__SL_G_UAC</p>
<p id="Device_LED_Status">__SL_G_ULD</p>

The tockens are used to receive data from the TI CC3200 development board.

The tockens are defined in the main.c function:

//*****************************************************************************
// GLOBAL VARIABLES -- Start
//*****************************************************************************
static const char pcDigits[] = "0123456789";
static unsigned char POST_token[] = "__SL_P_ULD";
static unsigned char GET_token_TEMP[] = "__SL_G_UTP";
static unsigned char GET_token_ACC[] = "__SL_G_UAC";
static unsigned char GET_token_UIC[] = "__SL_G_UIC";
static unsigned char GET_token_URT[] = "__SL_G_URT";

I have added __SL_G_URT token to the definition list above. I will be using it for UART communications.

demos-appliances.html:

The following code is an exerpt from demos-appliances.html shown above.

Page "param_demos.html", referenced below in "paramPage" has a list of 
tockens that will be polled by the "com.TI.tokenPoller."

$(function() {
    var Device_Temperature = $('#Device_Temperature_out'),
        Device_Accelerometer = $('#Device_Accelerometer_out'),
        demoPolling = new com.TI.tokenPoller({
            "paramPage": "param_demos.html", 
            "refreshRate": 200,
            "valueMap": [{
            "paramId": "Device_Temperature",
                "outputSuccess": function(output) {
		// Print temperature data. id="Device_Temperature" __SL_G_UTP tocken is received
                    Device_Temperature.html(output);
                },
                "outputDefault": function() {
                    Device_Temperature.html("reloading");
                }
            },
            {
            "paramId": "Device_Accelerometer",
                "outputSuccess": function(output) {
                	// Print accelerometer data. Device_Accelerometer is the token received
                    Device_Accelerometer.html(output);
                },
                "outputDefault": function() {
                    Device_Accelerometer.html("reloading");
                }
            }]
        });
});


I plan to add the following code to demos-appliances.html
page to read and display UART data:

{
"paramId": "UART",
"outputSuccess": function(output) {
        	Device_UART.html(output); // Print UART data
        },
"outputDefault": function() {
        	Device_UART.html("reading UART");
		}

//Additional tocken for UART communication
<p id="UART">__SL_G_URT</p>

First message sent with the help of the __SL_G_URT tocken:

I have added a new GET_token_URT token to the definition list: static unsigned char GET_token_URT[] = "__SL_G_URT"; Below is shown new token reader I am using for UART communications.


The tocken listed below located in the:

void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent, SlHttpServerResponse_t *pSlHttpServerResponse)
function.

The shown below tocken sends a fixed string - "hello uart"



/*
* The tew UART token: 
* this tocken sends fixed string - "hello uart"
*/
if(memcmp(pSlHttpServerEvent->EventData.httpTokenName.data,
	GET_token_URT, strlen((const char *)GET_token_URT)) == 0)
	{

		UART_PRINT("\n\r\rExecuting UptimeTask Enter a string and press enter\n\r\r");
							
		//Get length of the sring stored in g_ucUARTRecvBuffer
		strcpy((char*)pSlHttpServerResponse->ResponseData.token_value.data,"hello uart");
		pSlHttpServerResponse->ResponseData.token_value.len += strlen("hello uart");		
	}
}



The new UART tocken that can send variable messages is listed below and located in the

void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent, SlHttpServerResponse_t *pSlHttpServerResponse)

function.

This tocken replaces the one I used before to send a fixed message "hello uart"


/*
* The New UART token for variable messages
*/
if(memcmp(pSlHttpServerEvent->EventData.httpTokenName.data,
	GET_token_URT, strlen((const char *)GET_token_URT)) == 0)
{	
	uart = g_ucUARTRecvBuffer1; //Buffer filled with the text message, 80 characters long 
	strcpy((char*)pSlHttpServerResponse->ResponseData.token_value.data, (const char *) uart);//Copy uart string to data variable
	pSlHttpServerResponse->ResponseData.token_value.len += strlen((const char *) uart);	//Determine and save string length
}

The updated list of tockes on the param_demos.html web page looks like as follows:

<p id="Device_Temperature"> __SL_G_UTP </p>
<p id="Device_Accelerometer"> __SL_G_UAC </p>
<p id="Device_LED_Status"> __SL_G_ULD </p>
<p id="UART"> __SL_G_URT </p>


demos-appliances.html has a new "paramId" for reading data from UART tocken:

{
	"paramId": "UART",
	"outputSuccess": function(output) {
		// Print accelerometer data. Device_Accelerometer is the token received
		Device_UART.html(output);
	},
	"outputDefault": function() {
		Device_UART.html("Reading UART data");
	}
}]

The updated list of tockes on the param_demos.html web page looks like as follows:

What I am hoping to achieve is to send string of text from my Termite terminal to a mobile device. File "uart_config.c" has unsigned int GETChar(unsigned char *ucBuffer) function shown below.

/*uart_config.c*/

//*****************************************************************************
//
//! GETChar
//!
//!  \param  ucBuffer to which Command will be populated
//!
//!  \return Success or Failure
//!
//!  \brief   Get the char string from UART
//
//*****************************************************************************
unsigned int GETChar(unsigned char *ucBuffer)
{
    int i=0;
    char c;
    uiUartline=0;
    //
    // Wait to receive a character over UART
    //
    while(MAP_UARTCharsAvail(CONSOLE) == false)  // Read UART0                              
    {
        osi_Sleep(1);
    }
    c = MAP_UARTCharGetNonBlocking(CONSOLE);        // Get a single character

    MAP_UARTCharPut(CONSOLE, c);
    ilength=0;
    //
    // Checking the end of line
    //
    while(c!='\r' && c!='\n' )
    {
        uiUartline=1;
        //
        // Copying Data from UART into a buffer
        //
        if(  c!='\b')
        {
            ilength++;
            *(ucBuffer+i)=c;
            i++;
        }
        //
        // Deleting last character when you hit backspace
        //
        if(c=='\b')
        {
            i--;
            ilength--;
        }
        while(MAP_UARTCharsAvail(CONSOLE) == false)
        {
            osi_Sleep(1);
        }
        c = MAP_UARTCharGetNonBlocking(CONSOLE);
        MAP_UARTCharPut(CONSOLE, c);
    }

    strncpy((char*)g_ucUARTBuffer,(char *)ucBuffer,ilength);
    memset(g_ucUARTRecvBuffer, 0, sizeof(g_ucUARTRecvBuffer));

   return uiUartline;
}

I have placed UART GETChar function, shown above, inside the UptimeTask.

GETChar function waits for a character input from a serial terminal.


//*****************************************************************************
//
//! Inc the uptime counter.
//!
//! \param  none
//!
//! \return none
//!
//*****************************************************************************
static void UptimeTask( void *pvParameters )
{
	char c = 0;

	while(1)
	{
		//GPIO_IF_LedOff(MCU_ORANGE_LED_GPIO);
		//GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);
		g_uptimeSec++;
		c = MAP_UARTCharGetNonBlocking(CONSOLE);        // Get a single character
		if (c != 0){
			UART_PRINT("\n\r\rExecuting UptimeTask Enter a string and press enter\n\r\r");
			g_UartHaveCmd=GETChar(&g_ucUARTRecvBuffer1[0]);
		}

		osi_Sleep(1000);
	}
} 
The GETChar(&g_ucUARTRecvBuffer[0]) function reads characters from the terminal, loads them into the g_ucUARTRecvBuffer buffer, and echos the entered string.

To get ready to send strings of variable length I have done a couple of changes to the GET_token_URT.
First I have declared unsigned char *uart in the SL_NETAPP_HTTPGETTOKENVALUE_EVENT

switch (pSlHttpServerEvent->Event)
    {
        case SL_NETAPP_HTTPGETTOKENVALUE_EVENT:     // Get data from the server
        {
            unsigned char *ptr;
            unsigned char *ptraccX;
            unsigned char *ptraccY;
            unsigned char *ptraccZ;
            unsigned char *uart;
            ...
        }
        ...
    }
And the new UART tocken looks like this now:

/*
* New UART token ****************************New UART token*************************
*/
if(memcmp(pSlHttpServerEvent->EventData.httpTokenName.data,
GET_token_URT, strlen((const char *)GET_token_URT)) == 0)
{
	uart = "Sending srings of data";                
	strcpy((char*)pSlHttpServerResponse->ResponseData.token_value.data, (const char *) uart);
	pSlHttpServerResponse->ResponseData.token_value.len += strlen((const char *) uart);
} 
I have declared unsigned char g_ucUARTRecvBuffer1[80] a Global 80 character long array. The array will be used to store entered strings.

.....
unsigned char printflag = 0;
unsigned char g_ucUARTRecvBuffer1[80];
typedef enum
{
  LED_OFF = 0,
  LED_ON,
  LED_BLINK
}eLEDStatus;
.....
The Uptime Task with the new g_ucUARTRecvBuffer1[80] array now looks as follows:

static void UptimeTask( void *pvParameters )
{
    while(1)
    {
        //GPIO_IF_LedOff(MCU_ORANGE_LED_GPIO);
        g_uptimeSec++;
        UART_PRINT("\n\r\rExecuting UptimeTask Enter a string and press enter\n\r\r");
        // Returns UART line read from the console. Parameter is unsigned char array
        g_UartHaveCmd = GETChar(&g_ucUARTRecvBuffer1[0]);	// Load buffer from the serial terminal        
        osi_Sleep(1000);
    }
}
The only change to the UART tocken is that *uart now points to the beginning address of the g_ucUARTRecvBuffer1 buffer.

/*
 * The New UART token **************************** The New UART token *****************************
 */
if(memcmp(pSlHttpServerEvent->EventData.httpTokenName.data,
GET_token_URT, strlen((const char *)GET_token_URT)) == 0)
{               
	uart = g_ucUARTRecvBuffer1; //g_ucUARTRecvBuffer                
	strcpy((char*)pSlHttpServerResponse->ResponseData.token_value.data, (const char *) uart);	//Works
	pSlHttpServerResponse->ResponseData.token_value.len += strlen((const char *) uart);		//Works
}
This code allows me to send varios messages to the demos-appliences.html webpage, the only issue is that I cannot clear old messages off the screen. I also change #define HIGH_TASK_PRIORITY to 4. Download all the updated files from the GITHUB.

I am making changes to the original webpages. Here is the image of my new demos-sprinkler.html mobile friendly web page.

Download all the updated files from the GITHUB.


Replacing PIN_58 jumper with the SW2 push button action

To make it a little more convenient to switch to the AP mode, I have made SW2 has the same function as the pull-up jumper on PIN_58. With the SW2 push button you can switch to AP mode at reset or after if board did not connect to a network.

To implemet SW2 push buttn as AP mode selection switch I have made a few changes to the ConnectToNetwork() function. The updated code for the ConnectToNetwork() is:

//****************************************************************************
//
//! \brief Connects to the Network in AP or STA Mode - If Force AP SW2 is
//!                                             pressed, Force it to AP mode
//!
//! \return  0 - Success
//!            -1 - Failure
//
//****************************************************************************
long ConnectToNetwork()
{
    long lRetVal = -1;
    unsigned int uiConnectTimeoutCnt =0;


    unsigned int uiGPIOPort;
    unsigned char pucGPIOPin;
    unsigned char ucPinValue, flag;
   
    lRetVal =  sl_Start(NULL,NULL,NULL);	// staring simplelink
    ASSERT_ON_ERROR( lRetVal);
    
    flag = 0;

    // Device is in AP Mode and Force AP Jumper is not Connected
    if(ROLE_STA != lRetVal && g_uiDeviceModeConfig == ROLE_STA )
    {
        if (ROLE_AP == lRetVal)
        {
            UART_PRINT("\r\nConnectToNetwork: Current AP mode, the jumper is not connected\r\n");
            // If the device is in AP mode, we need to wait for this event
            // before doing anything 
            while(!IS_IP_ACQUIRED(g_ulStatus))
            {
            #ifndef SL_PLATFORM_MULTI_THREADED
              _SlNonOsMainLoopTask(); 
            #endif
            }
        }
        //Switch to STA Mode
        lRetVal = ConfigureMode(ROLE_STA);
        UART_PRINT("\r\nConnectToNetwork: Switch to STA mode\r\n");
        ASSERT_ON_ERROR( lRetVal);
    }

    //Device is in STA Mode and Force AP Jumper is Connected
    if(ROLE_AP != lRetVal && g_uiDeviceModeConfig == ROLE_AP )
    {
    	UART_PRINT("\r\nConnectToNetwork: Current ST mode, the jumper is connected\r\n");
    	 //Switch to AP Mode
         lRetVal = ConfigureMode(ROLE_AP);
         UART_PRINT("\r\nConnectToNetwork: Switch to AP mode\r\n");
         ASSERT_ON_ERROR( lRetVal);

    }

    //No Mode Change Required
    if(lRetVal == ROLE_AP)
    {
    	UART_PRINT("\r\nConnectToNetwork: Current AP mode\r\n");
    	//waiting for the AP to acquire IP address from Internal DHCP Server
        // If the device is in AP mode, we need to wait for this event 
        // before doing anything 
        while(!IS_IP_ACQUIRED(g_ulStatus))
        {
        #ifndef SL_PLATFORM_MULTI_THREADED
            _SlNonOsMainLoopTask(); 
        #endif
        }
        //Stop Internal HTTP Server
        lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
        ASSERT_ON_ERROR( lRetVal);

        //Start Internal HTTP Server
        lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
        ASSERT_ON_ERROR( lRetVal);

       char cCount=0;
       
       //Blink LED 3 times to Indicate AP Mode
       for(cCount=0;cCount<3;cCount++)
       {
           //Turn RED LED On
           GPIO_IF_LedOn(MCU_RED_LED_GPIO);
           osi_Sleep(400);
           
           //Turn RED LED Off
           GPIO_IF_LedOff(MCU_RED_LED_GPIO);
           osi_Sleep(400);
       }

       char ssid[32];
	   unsigned short len = 32;
	   unsigned short config_opt = WLAN_AP_OPT_SSID;
	   sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt , &len, (unsigned char* )ssid);
	   UART_PRINT("\n\r Connect to : \'%s\'\n\r\n\r",ssid);	//Connect to : 'mysimplelink-XXXXXX'
    }
    else
    {
    	UART_PRINT("\r\nConnectToNetwork: Current STA mode\r\n");
    	//Stop Internal HTTP Server
        lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
        ASSERT_ON_ERROR( lRetVal);

        //Start Internal HTTP Server
        lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
        ASSERT_ON_ERROR( lRetVal);

    	//Waiting for the device to Auto Connect.
        while(uiConnectTimeoutCnt < AUTO_CONNECTION_TIMEOUT_COUNT &&  (g_ulStatus == 0) && 
        		((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus)))) 
        {
            //Turn RED LED On
            GPIO_IF_LedOn(MCU_RED_LED_GPIO);
            osi_Sleep(50);
            
            //Turn RED LED Off
            GPIO_IF_LedOff(MCU_RED_LED_GPIO);
            osi_Sleep(50);
            
            uiConnectTimeoutCnt++;
        }
        //Couldn't connect Using Auto Profile
        if(uiConnectTimeoutCnt == AUTO_CONNECTION_TIMEOUT_COUNT)
        {
        	UART_PRINT("\r\nConnectToNetwork: Couldn't connect Using Auto Profile\r\n");
        	//Blink Red LED to Indicate Connection Error
            GPIO_IF_LedOn(MCU_RED_LED_GPIO);
            
            CLR_STATUS_BIT_ALL(g_ulStatus);

            //Connect Using Smart Config
            lRetVal = SmartConfigConnect();
            UART_PRINT("\r\nConnectToNetwork: Connecting Using Smart Config\r\n");
            ASSERT_ON_ERROR(lRetVal);

            /*
             * Waiting for the device to Auto Connect. If device did not get connected
             * pressing SW2 will set flag variable to 1.
            */
            while(((!IS_CONNECTED(g_ulStatus)) || 
            		(!IS_IP_ACQUIRED(g_ulStatus))) &&  (flag == 0))
            {
            	//Read status of GPIO22 (SW2 switch): SH_GPIO_22 - input, uiGPIOPort, pucGPIOPin - output.
            	GPIO_IF_GetPortNPin(SH_GPIO_22, &uiGPIOPort, &pucGPIOPin);	// Computes port and pin number from the GPIO number
            	ucPinValue = GPIO_IF_Get(SH_GPIO_22, uiGPIOPort, pucGPIOPin);	// Read pin status of GPIO22

            	//If SH_GPIO_22 is set , Mode is AP
            	if(ucPinValue == 1) //*****************************---------------------------**********************
            	{
            		UART_PRINT("\r\n SW2 is pressed \r\n");
            		flag = 1;
            	}
            	MAP_UtilsDelay(500);
            }

            if (flag == 1){ //When flag is set to 1 user wants to switch to AP mode
            	flag = 2;

            	long lRetVal = -1;

            	lRetVal = sl_Stop(0xFF);
            	ASSERT_ON_ERROR(lRetVal);
            	g_uiDeviceModeConfig = ROLE_AP;

            	// staring simplelink
            	lRetVal =  sl_Start(NULL,NULL,NULL);
            	ASSERT_ON_ERROR( lRetVal);

            	UART_PRINT("\r\nConnectToNetwork: Current AP mode\r\n");

            	//Switch to AP Mode
            	lRetVal = ConfigureMode(ROLE_AP);
            	UART_PRINT("\r\nConnectToNetwork: Switch to AP mode\r\n");
            	ASSERT_ON_ERROR( lRetVal);
            	//waiting for the AP to acquire IP address from Internal DHCP Server
            	// If the device is in AP mode, we need to wait for this event
            	// before doing anything
            	while(!IS_IP_ACQUIRED(g_ulStatus))
            	{
            	 	#ifndef SL_PLATFORM_MULTI_THREADED
            	    _SlNonOsMainLoopTask();
            	    #endif
            	}

            	//Stop Internal HTTP Server
            	lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
            	ASSERT_ON_ERROR( lRetVal);

            	//Start Internal HTTP Server
            	lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
            	ASSERT_ON_ERROR( lRetVal);

            	char cCount=0;

            	//Blink LED 3 times to Indicate AP Mode
            	for(cCount=0;cCount<3;cCount++)
            	{
            		//Turn RED LED On
            		GPIO_IF_LedOn(MCU_RED_LED_GPIO);	//RED LED ON
            		osi_Sleep(400);						//400ms delay

            		//Turn RED LED Off
            		GPIO_IF_LedOff(MCU_RED_LED_GPIO);	//RED LED OFF
            		osi_Sleep(400);
            	}

            	char ssid[32];							//WiFi Password
            	unsigned short len = 32;
            	unsigned short config_opt = WLAN_AP_OPT_SSID;
            	sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt , &len, (unsigned char* )ssid);
            	UART_PRINT("\n\r Connect to : \'%s\'\n\r\n\r",ssid);	//Connect to : 'mysimplelink-XXXXXX'
            }
    }

    //Turn RED LED Off
    GPIO_IF_LedOff(MCU_RED_LED_GPIO);

    g_iInternetAccess = ConnectionTest();

    }
    return SUCCESS;
}
		

Project Source Code