Beispiel #1
0
void SEC_InitializeNetworking(uint_32 pcbs, uint_32 msgs, uint_32 sockets, boolean dhcp) 
{
  int_32                 error;
  IPCFG_IP_ADDRESS_DATA  ip_data;
  _enet_address          enet_address;
    
#if PSP_MQX_CPU_IS_MCF51CN
   _enet_handle ehandle;
   _rtcs_if_handle ihandle;
#endif



    /* runtime RTCS configuration */
   _RTCSPCB_init = pcbs;
   _RTCS_msgpool_init = msgs;
   _RTCS_socket_part_init = sockets;
    
   error = RTCS_create();
   if (error == RTCS_OK) {

      ip_data.ip = ENET_IPADDR;
      ip_data.mask = ENET_IPMASK;
      ip_data.gateway = ENET_IPGATEWAY;
#if RTCSCFG_ENABLE_LWDNS
      LWDNS_server_ipaddr = ENET_IPDNS;
#endif 

      ENET_get_mac_address(BSP_DEFAULT_ENET_DEVICE, ENET_IPADDR, enet_address);
#if PSP_MQX_CPU_IS_MCF51CN
      ENET_initialize_ex(&ENET_param, BSP_DEFAULT_ENET_DEVICE, &ehandle);
      
      if (RTCS_if_add(ehandle, RTCS_IF_ENET, &ihandle) == 0) {
         if (ipcfg_init_interface(-1, ihandle) != 0) {
            RTCS_if_remove(ihandle);
            ENET_shutdown(ehandle);
                _mqx_exit(1);
         }
      }
      else {
         ENET_shutdown(ehandle);
      }
#else
      ipcfg_init_device(BSP_DEFAULT_ENET_DEVICE, enet_address);
#endif
      ipcfg_add_dns_ip(BSP_DEFAULT_ENET_DEVICE,LWDNS_server_ipaddr);

      // check link status
      printf("\nWaiting for ethernet cable plug in ... ");
      while(!ipcfg_get_link_active(BSP_DEFAULT_ENET_DEVICE)) {};
      printf("Cable connected\n");

       /* If DHCP Enabled, get IP address from DHCP server */
      if (dhcp) {
         printf("\nDHCP bind ... ");
         error = ipcfg_bind_dhcp_wait(BSP_DEFAULT_ENET_DEVICE, 1, &ip_data);
            if (error != IPCFG_ERROR_OK) {
               printf("Error %08x!\n", error);
            }
            else {
               printf("Successful!\n");
            }
      } else {
         /* Else bind with static IP */
         printf ("\nStatic IP bind ... ");
         error = ipcfg_bind_staticip(BSP_DEFAULT_ENET_DEVICE, &ip_data);

         if (error != IPCFG_ERROR_OK) {
            printf("Error %08x!\n",error);
         }
         else {
            printf("Successful!\n");
         }
       }

       if (error == IPCFG_ERROR_OK) {
          ipcfg_get_ip(BSP_DEFAULT_ENET_DEVICE, &ip_data);
          printf("\nIP Address      : %d.%d.%d.%d\n",IPBYTES(ip_data.ip));
          printf("\nSubnet Address  : %d.%d.%d.%d\n",IPBYTES(ip_data.mask));
          printf("\nGateway Address : %d.%d.%d.%d\n",IPBYTES(ip_data.gateway));
          printf("\nDNS Address     : %d.%d.%d.%d\n",IPBYTES(ipcfg_get_dns_ip(BSP_DEFAULT_ENET_DEVICE,0)));
       }
   } else {
       printf("\nRTCS_Create failed !\n");
       _task_block();
   }
    SEC_GetTime();
}
Beispiel #2
0
void Mouse_Task( uint_32 param )
{
    USB_STATUS              status = USB_OK;
    TR_INIT_PARAM_STRUCT    tr;
    HID_COMMAND_PTR         hid_com;
    uchar_ptr               buffer;
    PIPE_STRUCT_PTR         pipe;
    uint_32                 e;
    _usb_host_handle        mouse_host_handle = (_usb_host_handle) param;
   
    hid_com = (HID_COMMAND_PTR) _mem_alloc(sizeof(HID_COMMAND));

    /* event for USB callback signaling */
    _lwevent_create(&USB_Mouse_Event, LWEVENT_AUTO_CLEAR);

    printf("\nMQX USB HID Mouse Demo\nWaiting for USB Mouse to be attached...\n");
    fflush(stdout);
   
    /*
    ** Infinite loop, waiting for events requiring action
    */
    for ( ; ; ) {
    
        // Wait for insertion or removal event
        _lwevent_wait_ticks(&USB_Mouse_Event, USB_EVENT_CTRL, FALSE, 0);
        
        switch ( mouse_hid_device.DEV_STATE ) {
            case USB_DEVICE_IDLE:
                break;
            case USB_DEVICE_ATTACHED:
                printf("\nMouse device attached\n");
                fflush(stdout);
                mouse_hid_device.DEV_STATE = USB_DEVICE_SET_INTERFACE_STARTED;
                status = _usb_hostdev_select_interface(mouse_hid_device.DEV_HANDLE, mouse_hid_device.INTF_HANDLE, (pointer)&mouse_hid_device.CLASS_INTF);
                if (status != USB_OK) {
                    printf("\nError in _usb_hostdev_select_interface: %x", status);
                    fflush(stdout);
                    _task_block();
                } /* Endif */
                break;
            case USB_DEVICE_SET_INTERFACE_STARTED:
                break;

            case USB_DEVICE_INTERFACED:
                pipe = _usb_hostdev_find_pipe_handle(mouse_hid_device.DEV_HANDLE, mouse_hid_device.INTF_HANDLE, USB_INTERRUPT_PIPE, USB_RECV);
                if (pipe == NULL) {
                    printf("\nError getting interrupt pipe.");
                    fflush(stdout);
                    _task_block();
                }
                _usb_hostdev_get_buffer(mouse_hid_device.DEV_HANDLE, pipe->MAX_PACKET_SIZE, (pointer *) &buffer);
                if (buffer == NULL) {
                    printf("\nMemory allocation failed. STATUS: %x", status);
                    fflush(stdout);
                    _task_block();
                }

                printf("Mouse interfaced, setting protocol...\n");
                /* now we will set the USB Hid standard boot protocol */
                mouse_hid_device.DEV_STATE = USB_DEVICE_SETTING_PROTOCOL;
            
                hid_com->CLASS_PTR = (CLASS_CALL_STRUCT_PTR)&mouse_hid_device.CLASS_INTF;
                hid_com->CALLBACK_FN = usb_host_hid_mouse_ctrl_callback;
                hid_com->CALLBACK_PARAM = 0;
            
                status = usb_class_hid_set_protocol(hid_com, USB_PROTOCOL_HID_MOUSE);
         
                if (status != USB_STATUS_TRANSFER_QUEUED) {
                      printf("\nError in usb_class_hid_set_protocol: %x", status);
                      fflush(stdout);
                }
                break;
            case USB_DEVICE_INUSE:
                printf("Mouse device ready, try to move the mouse\n");
                while (1) {
                    /******************************************************************
                    Initiate a transfer request on the interrupt pipe
                    ******************************************************************/
                    usb_hostdev_tr_init(&tr, usb_host_hid_mouse_recv_callback, NULL);
                    tr.G.RX_BUFFER = buffer;
                    tr.G.RX_LENGTH = pipe->MAX_PACKET_SIZE;                     
                        
                    status = _usb_host_recv_data(mouse_host_handle, pipe, &tr);
                        
                    if (status != USB_STATUS_TRANSFER_QUEUED) {
                        printf("\nError in _usb_host_recv_data: %x", status);
                        fflush(stdout);
                    }
                    
                    /* Wait untill we get the data from keyboard. */
                    _lwevent_wait_ticks(&USB_Mouse_Event, USB_EVENT_CTRL | USB_EVENT_DATA | USB_EVENT_DATA_CORRUPTED, FALSE, 0);
                        
                    e = _lwevent_get_signalled();
                    if (USB_EVENT_DATA == e) {
                        if(mouse_hid_device.DEV_STATE == USB_DEVICE_INUSE) {
                            process_mouse_buffer((uchar *)buffer);
                        }
                    }
                    else if (USB_EVENT_CTRL == e) {
                        /* kick the outer loop again to handle the CTRL event */
                        _lwevent_set(&USB_Mouse_Event, USB_EVENT_CTRL);
                        break;
                    }
                }
                break;
            case USB_DEVICE_DETACHED:
                printf("Going to idle state\n");
                mouse_hid_device.DEV_STATE = USB_DEVICE_IDLE;
                break;
            case USB_DEVICE_OTHER:
                break;
             default:
                printf("Unknown Mouse Device State = %d\n", mouse_hid_device.DEV_STATE);
                fflush(stdout);
                break;
        } /* Endswitch */
    } /* Endfor */
} /* Endbody */
void Main_task(uint32_t temp)
{
   #include <ipcfg.h>
   
   IPCFG_IP_ADDRESS_DATA    ip_data;
   
   _rtcs_if_handle   ihandle;
   uint32_t           error;
   _ip_address       new_target; 
   _enet_address     enet_address;                                   

    /* runtime RTCS configuration */
    _RTCSPCB_init = 4;
    _RTCSPCB_grow = 2;
    _RTCSPCB_max = 6;
    _RTCS_socket_part_init = 4;
    _RTCS_socket_part_grow = 2;
    _RTCS_socket_part_max  = 6;
    
   
    error = RTCS_create();
    if (error) {
        printf("\nFailed to initialize RTCS, error = %X", error);
        _task_block();
    } /* Endif */

    ip_data.ip = ENET_IPADDR;
    ip_data.mask = ENET_IPMASK;
    ip_data.gateway = ENET_IPGATEWAY;
    
    ENET_get_mac_address (BSP_DEFAULT_ENET_DEVICE, ENET_IPADDR, enet_address);
    error = ipcfg_init_device (BSP_DEFAULT_ENET_DEVICE, enet_address);
    error = ipcfg_bind_staticip (BSP_DEFAULT_ENET_DEVICE, &ip_data);
    
    ihandle = ipcfg_get_ihandle( BSP_DEFAULT_ENET_DEVICE );

   /* 
   ** Install some MIBs for the SNMP agent
   ** MIB1213_init must be called before SNMP_init functions 
   ** It should not be removed.
   ** If application wishes to use MQX RTOS, MIBMQX_init must be called
   ** before SNMP_init functions.
   */  
   MIB1213_init();
   /* init MQX MIB */
#if 0
   /* It conflicts with the sample MIB and should only be reinstated when 
    * "your_company" is changed to a more appropriate identifier. 
    * You can find it in the snmp_demo.def file. */
   MIBMQX_init();
#endif
   /* demo MIB table init */
   MIBdemo_init();
    
   /* 
   ** Initialize the agent. 
   ** There are two functions for initializing SNMP agent.
   ** If application wants to send ColdStart/WarmStart traps at 
   ** the initialization time, it must call: 
   ** SNMP_init_with_traps(agent task name, agent task priority, 
   **                      agent task stack size, list of trap receivers);
   **
   ** Calling this function will initialize SNMP agent and send 
   ** ColdStart/WarmStart (depending on system up time) traps to the 
   ** station(s).
   **
   ** If application does not want to send ColdStart/WarmStart traps at 
   ** the initialization time, it must call:
   ** SNMP_init(agent task name, agent task priority, 
   **           agent task stack size);
   **
   ** Note1: If application wishes to use SNMP_init() to initialize the 
   **        SNMP agent, there is no IP address for trap to be sent.
   **        Application must add trap receivers to the list by calling
   **        RTCS_trap_target_add(_ip_address). To remove receiver from
   **        trap receivers list call RTCS_trap_target_remove(_ip_address).
   **
   ** This function initializes SNMP agent without sending any traps. 
   **
   ** This example will use SNMP_init_with_traps. 
   */
   
   //error = SNMP_init("SNMP", 7, 3000);
   
   error = SNMP_init_with_traps("SNMP", 7, 2500, my_trap_list);
   if (error) {
      printf("\nFailed to initialize SNMP agent, error = %X", error);
      _task_block();
   } /* Endif */

    printf("Demo started, wait... \n\r");   
   /* 
   ** RTCS/SNMP agent now supports private and public communities. 
   ** User can add community to the community list, that is defined 
   ** in snmpcfg.h by adding community string to the SNMPCFG_COMMUNITY_LIST
   ** and changing the SNMPCFG_NUM_COMMUNITY respectively.
   **
   ** Note1: Communities cannot be added dynamically.
   ** Note2: RTCS/SNMP agent will respond to get, set and getnext messages 
   **        to communities defined in SNMPCFG_COMMUNITY_LIST.
   **
   ** Application can select communities for send and receive traps by calling
   ** SNMP_trap_select_community(community name); Where community name should 
   ** match one of the strings in the SNMPCFG_COMMUNITY_LIST. By default
   ** current community is set to first string in SNMPCFG_COMMUNITY_LIST[].
   ** This function returns TRUE if the community was changed successfully,
   ** FALSE on failure.
   ** 
   ** Note3: SNMP_trap_select_community(char *community_name); should be
   **        called after SNMP_init (or with trap) has been called. 
   ** 
   ** Note4: mylinkdown trap is enterprise specific, therefore application 
   ** need to implement this trap. SNMP_trap_myLinkDown is just an example 
   ** for use as reference.
   */
   
   /* Send some traps to private and public communities */
   
   /* trap will be sent to four IPs in my_trap_list */
   if(SNMP_trap_select_community("private")) 
   {
      SNMP_trap_linkDown(ihandle);
      SNMP_trap_linkUp(ihandle);
      SNMP_trap_myLinkDown(ihandle);
      SNMP_trap_coldStart(); 
      SNMP_trap_warmStart(); 
   }

   new_target = ENET_TRAP_ADDR5;
   
   /* Add a new IP address to the trap list */
   error = RTCS_trap_target_add(new_target);
   if (error) {
      printf("\nFailed to add target trap, error = %X", error);
   } /* Endif */
   
   /* trap will be sent to five IPs */
   if(SNMP_trap_select_community("public")) 
   {
      SNMP_trap_linkDown(ihandle);
      SNMP_trap_linkUp(ihandle);
      SNMP_trap_myLinkDown(ihandle);
      SNMP_trap_coldStart(); 
      SNMP_trap_warmStart(); 
   }

   /* Remove the new IP address from trap list */
   error = RTCS_trap_target_remove(new_target);
   if (error) {
      printf("\nFailed to remove target trap, error = %X", error);
   } /* Endif */
   
   
#ifdef SNMPCFG_SEND_V2_TRAPS   
   if (SNMP_trap_select_community("public"))
   {
      SNMPv2_trap_linkDown(ihandle);
      SNMPv2_trap_linkUp(ihandle);
      SNMPv2_trap_coldStart();
      SNMPv2_trap_warmStart();
   }
#endif
    
    /* Call the counter demo function */
    Snmp_task(0);
   _task_block();

}
Beispiel #4
0
void main_task
(
        uint_32 initial_data
)
{
    DATE_STRUCT     time_rtc;
    TIME_STRUCT     time_mqx;

    if (_lwevent_create(&lwevent,0) != MQX_OK)
    {
        printf("\nMake event failed");
        _task_block();
    }

    printf ("\fStart time (MQX synchronized to RTC time during bsp init):\n\n");


    /* initialize time */
    time_rtc.YEAR     = 2010;
    time_rtc.MONTH    = 10;
    time_rtc.DAY      = 15;
    time_rtc.HOUR     = 10;
    time_rtc.MINUTE   = 8;
    time_rtc.SECOND   = 0;
    time_rtc.MILLISEC = 0;

    _time_from_date (&time_rtc, &time_mqx);

    _time_set( &time_mqx);
    if( _rtc_sync_with_mqx(FALSE) != MQX_OK )
    {
        printf("\nError synchronize time!\n");
        _task_block();
    }
    _time_get (&time_mqx);

    _time_to_date (&time_mqx, &time_rtc);
    print_mqx_time(&time_rtc, &time_mqx);
    print_current_time();

    /* except MPC5125 */
#ifndef BSP_TWRMPC5125
    install_interrupt();

    /* enable stopwatch */
    install_stopwatch();

    /* enable alarm */
    install_alarm();

    _lwevent_wait_ticks(&lwevent,LWE_ALARM,FALSE,0);
    _lwevent_clear(&lwevent,LWE_ALARM);

    printf ("\nALARM!\n");
    print_current_time();
    /* end of alarm */

    printf ("Continue wasting time (2 minutes max) ...\n");
    _lwevent_wait_ticks(&lwevent,LWE_STOPWATCH,FALSE,0);
    _lwevent_clear(&lwevent,LWE_STOPWATCH);

    printf ("\nSTOPWATCH!\n");
    print_current_time();

    printf ("\nClearing RTC:\n");
    _rtc_init (RTC_INIT_FLAG_CLEAR | RTC_INIT_FLAG_ENABLE);

    print_current_time();

    install_alarm();
    _lwevent_wait_ticks(&lwevent,LWE_ALARM,FALSE,0);
    _lwevent_clear(&lwevent,LWE_ALARM);

    printf ("ALARM!\n");
    print_current_time();

#else /* BSP_TWRMPC5125 */
    printf ("Waste 10 seconds here\n");
    _time_delay(10000);
    _rtc_get_time_mqxd (&time_rtc);
    print_rtc_time(&time_rtc, &time_mqx);
#endif

    printf ("Synchronize RTC to MQX time again:\n");
    _rtc_sync_with_mqx (FALSE);
    _rtc_get_time_mqxd (&time_rtc);
    _time_from_date (&time_rtc, &time_mqx);
    print_rtc_time(&time_rtc, &time_mqx);

#if PSP_HAS_IRTC == 1
    irtc_test();
#endif /* PSP_HAS_IRTC == 1 */

    /* Test tamper event functionality on MCF51EMxx device */
#if PSP_MQX_CPU_IS_MCF51EM
    test_tamper();
#else
    printf ("Finish, press/hold reset to repeat.\n");
    _task_block() ;
#endif
}
Beispiel #5
0
/*TASK*-----------------------------------------------------
* 
* Task Name    : mem_flash_app
* Comments     :
*    This task finds a string at 'the end' of flash memory
*    then it tries to rewrite it. The successfull rewrite
*    can be proved by re-executing this example application.
*
*END*-----------------------------------------------------*/
void mem_flash_app
   (
      uint_32 initial_data
   )
{
    ///////////////////////////////////////////////////////////// Flashx mfs demo =0x00060000~0x00080000#dx 20130103
#define FLASH_NAME_B       "flashx:"   //FLASH_NAME
    char  flashx_filesystem_name[] = "f:",flashx_partman_name[]="pmb:";///////////////////安装盘符
    MQX_FILE_PTR flashx_handle,flashx_file_handle,flashx_partman_handle;
    _mqx_uint  param; 
    uint_32 error;
    printf("\nMQX Flash Task.");
    
    /* wk --> open flash device */
    flashx_handle = fopen(FLASH_NAME_B, NULL); // "flashx:bank0"
    
     /*wk@130330 -->  test mfs function */
    uchar result;   
//    char pathname[261];
//    ioctl(mfs_fs_ptr, IO_IOCTL_GET_CURRENT_DIR,(uint_32_ptr) pathname);
//    printf("The current directory is: %s\n", pathname);  
   
    if (flashx_handle == NULL) {
      printf("\nUnable to open file %s", FLASH_NAME_B);
      _task_block();
   } else {
      printf("\nFlash file %s opened", FLASH_NAME_B);
   } 
   
   ioctl(flashx_handle, FLASH_IOCTL_ENABLE_SECTOR_CACHE, NULL);/////////////////////重要
//   int len;
//   len = write(flashx_handle, "world",strlen("world"));
//   fseek(flashx_handle, 0, IO_SEEK_SET);
//   
//   fseek(flashx_handle, -32, IO_SEEK_END);
//   len = write(flashx_handle, "hello",strlen("hello"));

   /* wk --> 安装分区 */
    error = _io_part_mgr_install(flashx_handle, flashx_partman_name, 0);// 分区管理
    if (error!= MFS_NO_ERROR)
    {
      printf("\nError installing partition manager: %s", MFS_Error_text((uint_32)error));
      _task_block();
    }
    
    /* Open partition manager */
    flashx_partman_handle = fopen(flashx_partman_name, NULL);// 打开分区
    if (flashx_partman_handle == NULL)
    {
      error = ferror(flashx_partman_handle);
      printf("\nError opening partition manager: %s", MFS_Error_text((uint_32)error));
      _task_block();
    }
    /* Validate partition 1 */
    param = 1;
    error = _io_ioctl(flashx_partman_handle, IO_IOCTL_VAL_PART, &param);// 控制分区
    if (error == MQX_OK)
    { 
      /* Install MFS over Flashx driver */
      error = _io_mfs_install(flashx_partman_handle, flashx_filesystem_name, param);// 安装文件系统,基于分区
      if (error != MFS_NO_ERROR)
      {
        printf("\nError initializing MFS: %s", MFS_Error_text((uint_32)error));
        _task_block();
      }
    } else
    { 
      /* Install MFS over SD card driver */
      error = _io_mfs_install(flashx_handle, flashx_filesystem_name, (_file_size)0);// 安装文件系统,无分区
      if (error != MFS_NO_ERROR)
      {
        printf("\nError initializing MFS: %s", MFS_Error_text((uint_32)error));
        _task_block();
      }
    }

   /* Open file system */
   flashx_file_handle = fopen(flashx_filesystem_name, NULL);// 打开文件系统
   error = ferror (flashx_file_handle);
   if ((error != MFS_NO_ERROR) && (error != MFS_NOT_A_DOS_DISK))
   {
     printf("\nError opening filesystem: %s", MFS_Error_text((uint_32)error));
     _task_block();
   }
   if ( error == MFS_NOT_A_DOS_DISK )//////////////////
   {
     printf("\nNOT A DOS DISK! You must format to continue.");
     
   }
  
   printf ("\nFlashx  installed to %s", flashx_filesystem_name);
    ////////////////////////////////////////////////////////////////#dx 20130103

   _task_block();
   //_task_destroy(_task_get_id());
   
}
Beispiel #6
0
/*TASK*-------------------------------------------------------------------
*
* Task Name : main_task
* Comments  :
*
*END*----------------------------------------------------------------------*/
void main_task
   (
      uint_32 dummy
   )
{
    MQX_FILE_PTR           qspifd;
    int_32 ret = 0, i, byte_write, byte_read;
    uint_8_ptr data;
    uint_8 test_data[512];
    TIME_STRUCT start_time, end_time, diff_time;

    printf ("\n-------------- QSPI driver example --------------\n\n");
    printf ("This example application demonstrates usage of QSPI driver.\n");

    /* Open the QSPI driver */
    qspifd = fopen (TEST_CHANNEL, NULL);
    if (qspifd == NULL) {
        printf ("Error opening QSPI driver!\n");
        _time_delay (200L);
        _task_block ();
    }

    /* erase all */
    printf("\n\n************************************************************************\n");
    printf("Erase the first flash chip, for S25FL128S/256S, it might take 30s/60s....\n");
    printf("************************************************************************\n");
    _time_get(&start_time);

    memory_chip_erase(qspifd, FLASH_BASE_ADR);

    _time_get(&end_time);
    _time_diff(&start_time, &end_time, &diff_time);
    printf("\nErase whole flash %ld sec, %ld millisec\n", diff_time.SECONDS, diff_time.MILLISECONDS);
    printf("Finish erase all flash\n");

    printf("\n\n*****************************************\n");
    printf("*** Function Test <memory_read_data> ****\n");
    printf("*****************************************\n");
    printf("From Flash %08x: first 20 btyes\n", TEST_BUFFER1);
    byte_read = memory_read_data(qspifd, TEST_BUFFER1, 20, test_data);
    if (byte_read < 0) {
        printf("memory_read_data failed!\n");
        return;
    }

    for (i = 0; i < 20; i++) {
        printf("0x%02x ", test_data[i]);
    }

    printf("\n\n*****************************************\n");
    printf("*** Function Test <memory_read_byte> ****\n");
    printf("*****************************************\n");
    printf("From Flash %08x: first 20 bytes\n", TEST_BUFFER1);
    for (i = 0; i < 20; i++) {
        printf("0x%02x ", memory_read_byte(qspifd, TEST_BUFFER1 + i));
    }
    printf("\n");

    printf("\n\n*****************************************\n");
    printf("*** Function Test <memory_write_data> ***\n");
    printf("*****************************************\n");
    data = (uint_8_ptr)_mem_alloc_zero(TEST_BUF_SIZE1);
    if (data == NULL) {
        printf("fail to allocate write buffer\n");
        fclose(qspifd);
        return;
    }
    for (i = 0; i < TEST_BUF_SIZE1; i++) {
        data[i] = i % 256;
    }

    _time_get(&start_time);

    byte_write = memory_write_data (qspifd, TEST_BUFFER1, TEST_BUF_SIZE1, data);
    if (byte_write < 0) {
        printf("memory_write_data failed!\n");
        return;
    }

    _time_get(&end_time);
    _time_diff(&start_time, &end_time, &diff_time);
    printf("\ndata = %d, Time spends on Flash write is %ld sec, %ld millisec, rate = %ld kbps\n",
        byte_write, diff_time.SECONDS, diff_time.MILLISECONDS,
        (byte_write)/(diff_time.SECONDS * 1000 + diff_time.MILLISECONDS));

    printf("\n\n*****************************************\n");
    printf("***** Time Test <memory_read_data> ******\n");
    printf("*****************************************\n");
    for (i = 0; i < TEST_BUF_SIZE1; i++) {
        data[i] = 255;
    }

    _time_get(&start_time);

    byte_read = memory_read_data (qspifd, TEST_BUFFER1, TEST_BUF_SIZE1, data);
    if (byte_read < 0) {
        printf("memory_read_data failed!\n");
        return;
    }

    _time_get(&end_time);
    _time_diff(&start_time, &end_time, &diff_time);
    printf("\ndata = %d, Time spends on Flash read is %ld sec, %ld millisec, rate = %ld kbps\n\n",
        byte_write, diff_time.SECONDS, diff_time.MILLISECONDS,
        (byte_write)/(diff_time.SECONDS * 1000 + diff_time.MILLISECONDS));

    printf("memory_read_data read data from %08x: first 20 bytes \n", TEST_BUFFER1);
    for(i = 0; i < 20; i++) {
        printf ("0x%02x ", data[i]);
    }
    printf("\n");

    printf("\n\n*****************************************\n");
    printf("**** Compare Test <memory_read_byte> ****\n");
    printf("*****************************************\n");
    printf("memory_read_byte from %08x: first 20 bytes \n", TEST_BUFFER1);
    for (i = 0; i < 20; i++) {
        printf("0x%02x ", memory_read_byte(qspifd, TEST_BUFFER1 + i));
    }
    printf("\n");

    /* Close the SPI */
    _mem_free(data);
    ret = (uint_32)fclose (qspifd);
    if (ret) {
        printf ("Error closing QSPI, returned: 0x%08x\n", ret);
    }

    printf ("\n-------------- End of example --------------\n\n");

}
/*TASK*-----------------------------------------------------------
 *
 * Task Name : Spi_Task
 * Comments :
 *
 *
 *END*-----------------------------------------------------------*/
void Spi_Task(uint32_t parameter) {

	 MQX_FILE_PTR           spifd;
	uint32_t                param, result, i = 0;
	SPI_STATISTICS_STRUCT  stats;
	SPI_READ_WRITE_STRUCT  rw;
	uint8_t addr;
	uint8_t rvByte;

	/* Open the SPI driver */
	spifd = fopen (TEST_CHANNEL, NULL);

	if (NULL == spifd)
	{
		printf ("Error opening SPI driver!\n");
		_time_delay (200L);
		_task_block ();
	}

   /* Display baud rate */
	printf ("Current baud rate ... ");
	if (SPI_OK == ioctl (spifd, IO_IOCTL_SPI_GET_BAUD, &param))
	{
		printf ("%d Hz\n", param);
	}
	else
	{
		printf ("ERROR\n");
	}

	/* Set a different rate */
	param = 1000000;
	printf ("Changing the baud rate to %d Hz ... ", param);
	if (SPI_OK == ioctl (spifd, IO_IOCTL_SPI_SET_BAUD, &param))
	{
		printf ("OK\n");
	}
	else
	{
		printf ("ERROR\n");
	}
	/* Set clock mode */
	param = SPI_CLK_POL_PHA_MODE0;
	printf ("Setting clock mode to %s ... ", clock_mode[param]);
	if (SPI_OK == ioctl (spifd, IO_IOCTL_SPI_SET_MODE, &param))
	{
		printf ("OK\n");
	}
	else
	{
		printf ("ERROR\n");
	}

	/* Get clock mode */
	printf ("Getting clock mode ... ");
	if (SPI_OK == ioctl (spifd, IO_IOCTL_SPI_GET_MODE, &param))
	{
		printf ("%s\n", clock_mode[param]);
	}
	else
	{
		printf ("ERROR\n");
	}

	/* Set big endian */
	param = SPI_DEVICE_BIG_ENDIAN;
	printf ("Setting endian to %s ... ", param == SPI_DEVICE_BIG_ENDIAN ? "SPI_DEVICE_BIG_ENDIAN" : "SPI_DEVICE_LITTLE_ENDIAN");
	if (SPI_OK == ioctl (spifd, IO_IOCTL_SPI_SET_ENDIAN, &param))
	{
		printf ("OK\n");
	}
	else
	{
		printf ("ERROR\n");
	}

	/* Get endian */
	printf ("Getting endian ... ");
	if (SPI_OK == ioctl (spifd, IO_IOCTL_SPI_GET_ENDIAN, &param))
	{
		printf ("%s\n", param == SPI_DEVICE_BIG_ENDIAN ? "SPI_DEVICE_BIG_ENDIAN" : "SPI_DEVICE_LITTLE_ENDIAN");
	}
	else
	{
		printf ("ERROR\n");
	}

	/* Set transfer mode */
	param = SPI_DEVICE_MASTER_MODE;
	printf ("Setting transfer mode to %s ... ", device_mode[param]);
	if (SPI_OK == ioctl (spifd, IO_IOCTL_SPI_SET_TRANSFER_MODE, &param))
	{
		printf ("OK\n");
	}
	else
	{
		printf ("ERROR\n");
	}

	/* Get transfer mode */
	printf ("Getting transfer mode ... ");
	if (SPI_OK == ioctl (spifd, IO_IOCTL_SPI_GET_TRANSFER_MODE, &param))
	{
		printf ("%s\n", device_mode[param]);
	}
	else
	{
		printf ("ERROR\n");
	}

	while(1) {

		for( addr=0x00; addr<0xFF; addr++)
		{
			writeEEPROM( spifd, addr, addr);
			rvByte = readEEPROM(spifd, addr);

			printf("(%02X) = %02X\r\n", addr, rvByte);
		}

	}

}
Beispiel #8
0
void lcd_task(uint32_t initial_data)
{
 // MQX_FILE_PTR   adc_file;
  TCHRES_INSTALL_PARAM_STRUCT install_params;
  
  printf("Hello from LCD demo\n\r");     

#if (defined BSP_TCHRES_ADC_XPLUS_DEVICE) && (defined BSP_TCHRES_ADC_YPLUS_DEVICE)
    printf("Opening ADC device for XPLUS electrode ... " BSP_TCHRES_ADC_XPLUS_DEVICE " ");
    if (fopen(BSP_TCHRES_ADC_XPLUS_DEVICE, (const char*)&adc_init) == NULL) {
        printf("failed\n");
        _task_block();
    } else {
        install_params.ADC_XPLUS_DEVICE = BSP_TCHRES_ADC_XPLUS_DEVICE;
        printf("done\n");
    }

    printf("Opening ADC device for YPLUS electrode ... " BSP_TCHRES_ADC_YPLUS_DEVICE " ");
    if (fopen(BSP_TCHRES_ADC_YPLUS_DEVICE, (const char*)&adc_init) == NULL) {
        printf("failed\n");
        _task_block();
    } else {
        install_params.ADC_YPLUS_DEVICE = BSP_TCHRES_ADC_YPLUS_DEVICE;
        printf("done\n");
    }
#elif (defined BSP_TCHRES_ADC_DEVICE)
    printf("Opening ADC device for XPLUS and YPLUS electrodes ... " BSP_TCHRES_ADC_DEVICE " ");
    if (fopen(BSP_TCHRES_ADC_DEVICE, (const char*)&adc_init) == NULL) {
        printf("failed\n");
        _task_block();
    } else {
        install_params.ADC_XPLUS_DEVICE = install_params.ADC_YPLUS_DEVICE = BSP_TCHRES_ADC_DEVICE;
        printf("done\n");
    }
#else
    printf("This demo application requires ADC devices for TCHRES to be defined!\n");
    _task_block();
#endif
  
  #if ADC_IOCTL_CALIBRATE   
//    ioctl( adc_file, ADC_IOCTL_CALIBRATE, NULL );
  #endif

  _io_tchres_install("tchscr:", &_bsp_tchscr_resisitve_init, &install_params );

  // Create the lwtimer component
  _lwtimer_create_periodic_queue(&lwt_ps, 25 / 5, 40);
  _lwtimer_add_timer_to_queue(&lwt_ps, &lwt_st25, 0, Time_event25ms, 0);

  if(!D4D_Init(&screen_entry))
  {
    // D4D initialization failed
    printf("eGUI/D4D initialization failed\n\r");   
    _mqx_exit(0);
  }

  D4D_SetOrientation(D4D_ORIENT_LANDSCAPE);

  D4D_CheckTouchScreen();

  for(;;)
  {
    D4D_Poll();
    _time_delay(10);
  }
}
Beispiel #9
0
boolean SEC_InitializeIO(void)
{

    /* Init Gpio for Leds as output to drive LEDs (LED10 - LED13) */
#ifdef LED_1
       output_port = lwgpio_init(&led1, LED_1, LWGPIO_DIR_OUTPUT, LWGPIO_VALUE_NOCHANGE);
       if(!output_port){
          printf("Initializing LWGPIO for LED1 failed.\n");
       }
       lwgpio_set_functionality(&led1, BSP_LED1_MUX_GPIO);
       /*Turn off Led */
       lwgpio_set_value(&led1, LWGPIO_VALUE_LOW);
#endif

#ifdef LED_2
       output_port = lwgpio_init(&led2, LED_2, LWGPIO_DIR_OUTPUT, LWGPIO_VALUE_NOCHANGE);
       if(!output_port){
          printf("Initializing LWGPIO for LED2 failed.\n");
       }
       lwgpio_set_functionality(&led2, BSP_LED2_MUX_GPIO);
       /*Turn off Led */
       lwgpio_set_value(&led2, LWGPIO_VALUE_LOW);
#endif

#ifdef LED_3
       output_port = lwgpio_init(&led3, LED_3, LWGPIO_DIR_OUTPUT, LWGPIO_VALUE_NOCHANGE);
       if(!output_port){
          printf("Initializing LWGPIO for LED3 failed.\n");
       }
       lwgpio_set_functionality(&led3, BSP_LED3_MUX_GPIO);
       /*Turn off Led */
       lwgpio_set_value(&led3, LWGPIO_VALUE_LOW);
#endif

#ifdef LED_4
       output_port = lwgpio_init(&led4, LED_4, LWGPIO_DIR_OUTPUT, LWGPIO_VALUE_NOCHANGE);
       if(!output_port){
          printf("Initializing LWGPIO for LED3 failed.\n");
       }
       lwgpio_set_functionality(&led4, BSP_LED4_MUX_GPIO);
       /*Turn off Led */
       lwgpio_set_value(&led4, LWGPIO_VALUE_LOW);
#endif

#ifdef BSP_BUTTON1
    /* Open and set port DD as input to read value from switches */
       input_port = lwgpio_init(&button1, DOOR_STATE, LWGPIO_DIR_INPUT, LWGPIO_VALUE_NOCHANGE);
       if(!input_port)
       {
           printf("Initializing LW GPIO for button1 as input failed.\n");
           _task_block();
       }    
       #if (defined BSP_BUTTON1_MUX_IRQ && defined SECEMAIL_TWRMCF51CN_STOP_ENABLED)
       lwgpio_set_functionality(&button1 ,BSP_BUTTON1_MUX_IRQ);
       lwgpio_set_attribute(&button1, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
       if (!lwgpio_int_init(&button1, LWGPIO_INT_MODE_RISING))
       {
           printf("Initializing button GPIO for interrupt failed.\n");
       }
       #else 
       lwgpio_set_functionality(&button1 ,BSP_BUTTON1_MUX_GPIO);
       lwgpio_set_attribute(&button1, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
       #endif
       /* install gpio interrupt service routine */
       _int_install_isr(lwgpio_int_get_vector(&button1), kbi_callback, (void *) &button1);
       _bsp_int_init(lwgpio_int_get_vector(&button1), 3, 0, TRUE);
       lwgpio_int_enable(&button1, TRUE);
#endif
       
#ifdef BSP_BUTTON2
       input_port = lwgpio_init(&button2, WINDOW_STATE, LWGPIO_DIR_INPUT, LWGPIO_VALUE_NOCHANGE);
       if(!input_port)
       {
           printf("Initializing LW GPIO for button2 as input failed.\n");
           _task_block();
       }
       #if (defined BSP_BUTTON2_MUX_IRQ && defined SECEMAIL_TWRMCF51CN_STOP_ENABLED)
       lwgpio_set_functionality(&button2 ,BSP_BUTTON2_MUX_IRQ);
       lwgpio_set_attribute(&button2, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
       if (!lwgpio_int_init(&button2, LWGPIO_INT_MODE_FALLING))
       {
           printf("Initializing button GPIO for interrupt failed.\n");
       }
       #else 
       lwgpio_set_functionality(&button2 ,BSP_BUTTON2_MUX_GPIO);
       lwgpio_set_attribute(&button2, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
       #endif
       /* install gpio interrupt service routine */
       _int_install_isr(lwgpio_int_get_vector(&button2), kbi_callback, (void *) &button2);
       _bsp_int_init(lwgpio_int_get_vector(&button2), 3, 0, TRUE);
       lwgpio_int_enable(&button2, TRUE);
#endif

    return (input_port!=0) && (output_port!=0);
}
Beispiel #10
0
void rtcs_init()
{
   IPCFG_IP_ADDRESS_DATA ip_data;
   _enet_address           enet_address;   

   uint_32 error = RTCS_create();
   if (error != RTCS_OK) 
   {
      printf("\nRTCS failed to initialize, error = %X", error);
      _task_block();
   }

   _IP_forward = TRUE;

#ifdef BSP_ENET_DEVICE_COUNT
#if  (BSP_ENET_DEVICE_COUNT > 0) 
   /*Following section is relevant only in case there as some enet driver available in BSP (FEC, MACNET, WIFI or other enet driver)*/
   
   ip_data.ip = ENET_IPADDR;
   ip_data.mask = ENET_IPMASK;
   ip_data.gateway = ENET_GATEWAY;  
   
   /* calcualte unique mac address from IP ADDRES */
   ENET_get_mac_address (ENET_DEVICE, ENET_IPADDR, enet_address);
   error = ipcfg_init_device (ENET_DEVICE, enet_address);
   if (error != RTCS_OK) 
   {
      printf("\nFailed to initialize ethernet device, error = %X", error);
      _task_block();
   }

#if RTCSCFG_ENABLE_LWDNS
   LWDNS_server_ipaddr = ENET_GATEWAY;   
   ipcfg_add_dns_ip(ENET_DEVICE,LWDNS_server_ipaddr);
#endif /* RTCSCFG_ENABLE_LWDNS */

   printf("\nWaiting for ethernet cable plug in ... ");
   while(!ipcfg_get_link_active(ENET_DEVICE)) {};
   printf("Cable connected\n");

#if RTCS_DHCP
   printf("Contacting DHCP server ... ");
   error = ipcfg_bind_dhcp_wait(ENET_DEVICE, FALSE, &ip_data);
#else
   printf("Setting static IP address ... ");
   error = ipcfg_bind_staticip (ENET_DEVICE, &ip_data);
#endif /* RTCS_DHCP */
   if (error != IPCFG_ERROR_OK) 
   {
      printf("\nRTCS failed to bind interface with IPv4, error = %X", error);
      _task_block();
   }
   else
   {
	  printf("OK\n");	   
   }

   ipcfg_get_ip(ENET_DEVICE, &ip_data);
   printf("\nIP Address      : %d.%d.%d.%d\n",IPBYTES(ip_data.ip));
   printf("\nSubnet Address  : %d.%d.%d.%d\n",IPBYTES(ip_data.mask));
   printf("\nGateway Address : %d.%d.%d.%d\n",IPBYTES(ip_data.gateway));
   printf("\nDNS Address     : %d.%d.%d.%d\n",IPBYTES(ipcfg_get_dns_ip(ENET_DEVICE,0)));

#endif /* BSP_ENET_DEVICE_COUNT > 0 */
#endif /* BSP_ENET_DEVICE_COUNT */   
   
#if RTCS_PPP
    PPP_start();
#endif /* RTCS_PPP */

   /* TODO: start server(s) in separate tasks */
}
Beispiel #11
0
/*TASK**************************************************************************
*
* Function Name   : dcd_task
*
* Input Params    : initial_data
*
* Returned Value  : None
*
* Comments        : Detect connect to USB, test IOCTL for USB DCD driver
*
*END***************************************************************************/
void dcd_task
   (
      uint_32 initial_data
   )
{
   uint_32                      param;
   char ch;
#if defined BSP_TWR_K60N512 || BSP_TWR_K70F120M || BSP_TWR_K60F120M
   ADC_RESULT_STRUCT data;
#else
   LWGPIO_STRUCT vbus_file;
#endif

   printf("\nUSB DCD testing... %d \n ");
   fd = fopen ("usbdcd:", NULL);
   if (fd == NULL)
   {
       printf ("ERROR opening the USB DCD driver!\n");
        _task_block();
   }
#if defined BSP_TWR_K60N512 || BSP_TWR_K70F120M || BSP_TWR_K60F120M
   Adc_Vbus();
#else
    lwgpio_init(&vbus_file, USB_DCD_PIN_VBUS, LWGPIO_DIR_INPUT, LWGPIO_VALUE_NOCHANGE);
    lwgpio_set_functionality(&vbus_file, USB_DCD_PIN_VBUS_MUX_GPIO);

   if (!(lwgpio_get_value(&vbus_file)))
   {
         printf("Vbus is disable...\n");
         Vbus_flag = 0x00;
   }
#endif
   printf("\n---------------------------------------------------");
   printf("\n Press 1 to select testing IOCTL for USB DCD driver");
   printf("\n Press 2 to start detecting USB charger");
   printf("\n---------------------------------------------------");
   printf("\n Your choice: ");
   do{
      ch = fgetc(stdin);
   }while ((ch != '1') && (ch != '2'));
   if (ch == '1')
   {
      IO_IOCTL_TEST();
   }

   printf("\nStart detecting USB charger");
   for (;;)
   {

#if defined BSP_TWR_K60N512 || BSP_TWR_K70F120M || BSP_TWR_K60F120M
   read(f_ch1, &data, sizeof(data));

      if (( data.result  > VBUS_DETECT)&& (!Vbus_flag) )
      {
         /* Starting DCD - IO_IOCTL_USB_DCD_START */
         printf("\nVbus is enable ...\n");
         if (USB_DCD_OK == ioctl (fd, IO_IOCTL_USB_DCD_START, &param))
         {
                 printf ("Starting detecting...\n");
         } else {
                 printf ("ERROR\n");
         }
         Vbus_flag = 0x01;
      }

      if ((data.result  < VBUS_DETECT)&& (Vbus_flag))
      {
         printf("Vbus is disable...\n");
         Vbus_flag = 0x00;
      }
#else
      if ( (lwgpio_get_value(&vbus_file)) && (!Vbus_flag) )
            {
               /* Starting DCD - IO_IOCTL_USB_DCD_START */
               printf("\nVbus is enable...\n");
               if (USB_DCD_OK == ioctl (fd, IO_IOCTL_USB_DCD_START, &param))
               {
                       printf ("Starting detecting...\n");
               } else {
                       printf ("ERROR\n");
               }
               Vbus_flag = 0x01;
            }

            if ((!(lwgpio_get_value(&vbus_file))) && (Vbus_flag))
            {
               printf("Vbus is disable ...\n");
               Vbus_flag = 0x00;
            }

#endif /* BSP_TWR_K60N512 */
      if (USB_DCD_OK == ioctl (fd, IO_IOCTL_USB_DCD_GET_STATE, &param))
      {
         if (param == USB_DCD_SEQ_COMPLETE )
         {
            if (USB_DCD_OK == ioctl (fd, IO_IOCTL_USB_DCD_GET_CHARGER_TYPE, &param))
            {
               if ((param & 0x0F) == STANDARD_HOST )
               {
                  printf("Connected to a Standard Host\n");
               }
               else if ((param & 0x0F) == CHARGING_HOST)
               {
                  printf("Connected to a Charging Host\n");
               }
               else if ((param & 0x0F) == DEDICATED_CHARGER)
               {
                  printf("Connected to a dedicated Charger\n");
               }
               else // if (param & 0xF0)
                  printf("------------- DCD Sequence occurs error (param = 0x%X)....  \r\n",param);
            }
            else
            {
               printf("IO_IOCTL_USB_DCD_GET_CHARGER_TYPE - ERROR...\n");
            }
            if (USB_DCD_OK == ioctl (fd, IO_IOCTL_USB_DCD_RESET, &param))
            {
               printf("USB-DCD module : Reset\n");
            }
            else
            {
               printf("Cannot reset USB-DCD module\n");
            }
         }
         /* ioctl command test*/
          _time_delay(20);
      }
      else
      {
         printf("Can not get state...\n");
         /* ioctl command test*/
          _time_delay(20);
      }

   }
   printf("Closing channels...");
   fclose(f_ch1);

   _task_block();

}
Beispiel #12
0
void Main_Task(uint_32 param)
{
    USB_STATUS status = USB_OK;
    _usb_pipe_handle pipe;
    TR_INIT_PARAM_STRUCT tr;
    HID_COMMAND hid_com;
    uchar *buffer;

    printf("\n** MQX USB Keyboard To Mouse Demo **\n");
    
    printf("\nDemo will allow you control mouse cursor on your PC using keyboard attached to TWR-SER2 board.");
    printf("\nThis demo requires TWR-SER2 card and correct BSP setting.");
    printf("\nSee FSL_MQX_getting_started.pdf chapter 7 for details.");
    fflush(stdout);

    MouseDev_Init();

    /* Allocate buffer to receive data from interrupt. It must be created on uncached heap,
    ** since some USB host controllers use DMA to access those buffers.
    */
    buffer = USB_mem_alloc_uncached(HID_BUFFER_SIZE);
    if (buffer == NULL) {
        printf("\nMemory allocation failed. STATUS: %x", status);
        fflush(stdout);
        _task_block();
    }
    
    /* _usb_otg_init needs to be done with interrupts disabled */
    _int_disable();

    /* event for USB callback signaling */
    _lwevent_create(&USB_Event, LWEVENT_AUTO_CLEAR);

    _int_install_unexpected_isr();

    /* Register USB interface and its settings from BSP */
    if (MQX_OK != _usb_host_driver_install(&_bsp_usb_host_khci0_if)) {
        printf("\n\nUSB Host Installation failed.");
        fflush(stdout);
        _task_block();
    }

    /*
     ** It means that we are going to act like host, so we initialize the
     ** host stack. This call will allow USB system to allocate memory for
     ** data structures, it uses later (e.g pipes etc.).
     */
    status = _usb_host_init(&_bsp_usb_host_khci0_if, &host_handle);

    if(status != USB_OK) {
        printf("\nUSB Host Initialization failed. STATUS: %x", status);
        fflush(stdout);
        _task_block();
    }

    /*
     ** since we are going to act as the host driver, register the driver
     ** information for wanted class/subclass/protocols
     */
    status = _usb_host_driver_info_register(host_handle, DriverInfoTable);
    if(status != USB_OK) {
        printf("\nDriver Registration failed. STATUS: %x", status);
        fflush(stdout);
        _task_block();
    }

    _int_enable();
    printf("\nHost initialization finished. Attach USB Keyboard to the board.");

    /*
     ** Infinite loop, waiting for events requiring action
     */
    for(;;) {

        // Wait for insertion or removal event
        _lwevent_wait_ticks(&USB_Event, USB_EVENT_CTRL, FALSE, 0);

        switch (hid_device.DEV_STATE) {

        case USB_DEVICE_IDLE:
            break;

        case USB_DEVICE_ATTACHED:
            hid_device.DEV_STATE = USB_DEVICE_SET_INTERFACE_STARTED;

            status = _usb_hostdev_select_interface(hid_device.DEV_HANDLE, hid_device.INTF_HANDLE, (pointer) & hid_device.CLASS_INTF);
            if(status != USB_OK) {
                printf("\nError in _usb_hostdev_select_interface: %x", status);
                fflush(stdout);
                _task_block();
            }
            break;

        case USB_DEVICE_SET_INTERFACE_STARTED:
            break;

        case USB_DEVICE_INTERFACED:
            printf("\nKeyboard device interfaced, setting protocol.");
            /* now we will set the USB Hid standard boot protocol */
            hid_device.DEV_STATE = USB_DEVICE_SETTING_PROTOCOL;

            hid_com.CLASS_PTR = (CLASS_CALL_STRUCT_PTR) & hid_device.CLASS_INTF;
            hid_com.CALLBACK_FN = usb_host_hid_ctrl_callback;
            hid_com.CALLBACK_PARAM = 0;

            /* Force the keyboard to behave as in USB Hid class standard boot protocol */
            status = usb_class_hid_set_protocol(&hid_com, USB_PROTOCOL_HID_KEYBOARD);

            if(status != USB_STATUS_TRANSFER_QUEUED) {
                printf("\nError in usb_class_hid_set_protocol: %x", status);
                fflush(stdout);
            }

            break;

        case USB_DEVICE_INUSE:
            pipe = _usb_hostdev_find_pipe_handle(hid_device.DEV_HANDLE, hid_device.INTF_HANDLE, USB_INTERRUPT_PIPE, USB_RECV);

            if(pipe) {
                printf("\n\nUse W, A, S or D to move the cursor.\nW = UP\nS = DOWN\nA = LEFT\nD = RIGHT\n");

                while(1) {
                  /******************************************************************
                    Initiate a transfer request on the interrupt pipe
                  ******************************************************************/
                    usb_hostdev_tr_init(&tr, usb_host_hid_recv_callback, NULL);
                    tr.G.RX_BUFFER = (uchar *) buffer;
                    tr.G.RX_LENGTH = HID_BUFFER_SIZE;

                    status = _usb_host_recv_data(host_handle, pipe, &tr);

                    if(status != USB_STATUS_TRANSFER_QUEUED) {
                        printf("\nError in _usb_host_recv_data: %x", status);
                        fflush(stdout);
                    }

                    /* Wait untill we get the data from keyboard. */
                    _lwevent_wait_ticks(&USB_Event, USB_EVENT_CTRL | USB_EVENT_DATA, FALSE, 0);

                    /* if not detached in the meanwhile */
                    if(hid_device.DEV_STATE == USB_DEVICE_INUSE) {
                        process_kbd_buffer((uchar *)buffer);
                    }
                    else {
                        /* kick the outer loop again to handle the CTRL event */
                        _lwevent_set(&USB_Event, USB_EVENT_CTRL);
                        break;
                    }

                    /* Slight delay to be nice to other processes. (Note that keyboards have its 
                       own autorepeat delay typically much longer than one would expect. In case 
                       the user holds the key (without any other keys changed), the USB response 
                       from keyboard is delayed (typ by 500ms). This is why the USB host should 
                       handle autorepeat feature by itself (not done in this example) */
                    _time_delay(1);

                    USB_HID_Periodic_Task(); //feed the USB device with the correct setup answers
                }
            }
            break;

        case USB_DEVICE_DETACHED:
            printf("Going to idle state\n");
            hid_device.DEV_STATE = USB_DEVICE_IDLE;
            break;
        }
    }
}
Beispiel #13
0
_mqx_uint _lwmsgq_send
   (
      /* Handle to the queue */
      pointer           handle,

      /* location of message to copy in */
      _mqx_max_type_ptr message,

      /* flags for blocking on full, blocking on send */
      _mqx_uint         flags
   )
{/* Body */
   KERNEL_DATA_STRUCT_PTR kernel_data;
   TD_STRUCT_PTR          td_ptr;
   LWMSGQ_STRUCT_PTR      q_ptr = (LWMSGQ_STRUCT_PTR)handle;
   _mqx_uint              i;
   _mqx_max_type_ptr      from_ptr;
   _mqx_max_type_ptr      to_ptr;

#if MQX_ENABLE_USER_MODE && MQX_ENABLE_USER_STDAPI
    if (MQX_RUN_IN_USER_MODE) {
        return _usr_lwmsgq_send(handle, message, flags);
    }
#endif
    
   /* Start CR 1944 */
   _GET_KERNEL_DATA(kernel_data);
   _KLOGE4(KLOG_lwmsgq_send, handle, message, flags);
   /* End CR 1944 */
   
   _int_disable();
#if MQX_CHECK_VALIDITY
   if (q_ptr->VALID != LWMSGQ_VALID){
      _int_enable();
      /* Start CR 1944 */
      _KLOGX2(KLOG_lwmsgq_send, LWMSGQ_INVALID);
      /* End CR 1944 */
      return LWMSGQ_INVALID;
   } /* Endif */
#endif
   if (LWMSGQ_IS_FULL(q_ptr)) {
      if (flags & LWMSGQ_SEND_BLOCK_ON_FULL) {
         td_ptr = kernel_data->ACTIVE_PTR;
         while (LWMSGQ_IS_FULL(q_ptr)) {
            td_ptr->STATE = LWMSGQ_WRITE_BLOCKED;
            td_ptr->INFO  = (_mqx_uint)&q_ptr->WAITING_WRITERS;
            _QUEUE_UNLINK(td_ptr);
            _QUEUE_ENQUEUE(&q_ptr->WAITING_WRITERS, &td_ptr->AUX_QUEUE);
            _sched_execute_scheduler_internal(); /* Let other tasks run */
         } /* Endwhile */
      } else {
         _int_enable();
         /* Start CR 1944 */
         _KLOGX2(KLOG_lwmsgq_send, LWMSGQ_FULL);
         /* End CR 1944 */
         return LWMSGQ_FULL;
      } /* Endif */
   }/* Endif */
   to_ptr = q_ptr->MSG_WRITE_LOC;
   from_ptr = message;
   i = q_ptr->MSG_SIZE+1;
   while (--i) {
      *to_ptr++ = *from_ptr++;
   } /* Endwhile */
   q_ptr->MSG_WRITE_LOC += q_ptr->MSG_SIZE;
   if (q_ptr->MSG_WRITE_LOC >= q_ptr->MSG_END_LOC) {
      q_ptr->MSG_WRITE_LOC = q_ptr->MSG_START_LOC;
   } /* Endif */
   q_ptr->CURRENT_SIZE++;
   if (! _QUEUE_IS_EMPTY(&q_ptr->WAITING_READERS)) {
      _QUEUE_DEQUEUE(&q_ptr->WAITING_READERS, td_ptr);
      _BACKUP_POINTER(td_ptr, TD_STRUCT, AUX_QUEUE);
      _TIME_DEQUEUE(td_ptr, kernel_data);
      td_ptr->INFO = 0;  /* Signal that post is activating the task */
      _TASK_READY(td_ptr, kernel_data);
      if (flags & LWMSGQ_SEND_BLOCK_ON_SEND) {
         _task_block();
      } else {
         _CHECK_RUN_SCHEDULER(); /* Let higher priority task run */
      }/* Endif */
   } else {
      if (flags & LWMSGQ_SEND_BLOCK_ON_SEND) {
         _task_block();
      }/* Endif */
   } /* Endif */
   _int_enable();
   /* Start CR 1944 */
   _KLOGX2(KLOG_lwmsgq_send, MQX_OK);
   /* End CR 1944 */
   return MQX_OK;

}/* Endbody */
Beispiel #14
0
void TestApp_Init(void)
{
   AUDIO_CONFIG_STRUCT       audio_config;
   USB_CLASS_AUDIO_ENDPOINT  * endPoint_ptr;

   /* Pointer to audio endpoint entry */  
   endPoint_ptr = USB_mem_alloc_zero(sizeof(USB_CLASS_AUDIO_ENDPOINT)*AUDIO_DESC_ENDPOINT_COUNT);
   /* USB descriptor endpoint */
   audio_config.usb_ep_data = &usb_desc_ep;
   /* USB audio unit */
   audio_config.usb_ut_data = &usb_audio_unit;
   /* Endpoint count */
   audio_config.desc_endpoint_cnt = AUDIO_DESC_ENDPOINT_COUNT;
   /* Application callback */
   audio_config.audio_class_callback.callback = USB_App_Callback;
   /* Application callback argurment */
   audio_config.audio_class_callback.arg = &g_app_handle;
   /* Vendor callback */
   audio_config.vendor_req_callback.callback = NULL;
   /* Vendor callback argurment */
   audio_config.vendor_req_callback.arg = NULL;
   /* Param callback function */
   audio_config.param_callback.callback = USB_Notif_Callback;
   /* Param callback argurment */
   audio_config.param_callback.arg = &g_app_handle;
   /* Memory param callback */
   audio_config.mem_param_callback.callback = NULL;
   /* Memory param callback argurment */
   audio_config.mem_param_callback.arg = &g_app_handle;
   /* Descriptor callback pointer */
   audio_config.desc_callback_ptr =  &desc_callback;
   /* Audio enpoint pointer */
   audio_config.ep = endPoint_ptr;

   /* Initialize timer module */
//   audio_timer_init();

//   _audio_timer_init_freq(AUDIO_TIMER, AUDIO_TIMER_CHANNEL, AUDIO_SPEAKER_FREQUENCY, AUDIO_TIMER_CLOCK, TRUE);

    if (MQX_OK != _usb_device_driver_install(USBCFG_DEFAULT_DEVICE_CONTROLLER)) {
        printf("Driver could not be installed\n");
        return;
    }

   /* Initialize the USB interface */
   g_app_handle = USB_Class_Audio_Init(&audio_config);

   if (MQX_OK != _lwevent_create(&app_event, LWEVENT_AUTO_CLEAR)) {
      printf("\n_lwevent_create app_event failed.\n");
      _task_block();
   }
   
   if (MQX_OK != _lwevent_wait_ticks(&app_event, USB_APP_ENUM_COMPLETE_EVENT_MASK, FALSE, 0)) {
      printf("\n_lwevent_wait_ticks app_event failed.\n");
      _task_block();
   }
   
   if (MQX_OK != _lwevent_clear(&app_event, USB_APP_ENUM_COMPLETE_EVENT_MASK)) {
      printf("\n_lwevent_clear app_event failed.\n");
      _task_block();
   }
   printf("Audio speaker is working ... \r\n");
   /* Prepare buffer for first isochronous input */
   USB_Class_Audio_Recv_Data(g_app_handle,AUDIO_ISOCHRONOUS_ENDPOINT,
                  audio_data_buff0, DATA_BUFF_SIZE);

   _task_block();   
} 
Beispiel #15
0
void main_task 
   (
      uint_32 initial_data
   )
{
   MQX_FILE_PTR port_file1, port_file2, port_file3, port_file4;
   
#if defined BSP_LED2 && defined BSP_LED3 && defined BSP_LED4
    #define PINS1
    GPIO_PIN_STRUCT pins1[] = {
        /* when opening, explicitly set output to 0 */
        BSP_LED2 | GPIO_PIN_STATUS_0,
        /* when opening, explicitly set output to 1 */
        BSP_LED3 | GPIO_PIN_STATUS_1,
        /* when opening, implicitly set output to 0 */
        BSP_LED4,
        GPIO_LIST_END
    };
#endif

#if defined BSP_LED2
    #define PINS2       
    GPIO_PIN_STRUCT pins2[] = {
        BSP_LED2,
        GPIO_LIST_END
    };
#endif

#if defined BSP_LED1
    #define PINS3
    GPIO_PIN_STRUCT pins3[] = {
        BSP_LED1,
        GPIO_LIST_END
    };
#endif

#if defined BSP_BUTTON1 && defined BSP_BUTTON2
    #define PINS4
    GPIO_PIN_STRUCT pins4[] = {
        BSP_BUTTON1,
        BSP_BUTTON2,
        GPIO_LIST_END
    };
#endif

/************************************************
 Opening file for write with associated pins,
 write LOG 0 and LOG 1 to file.
*************************************************/
#if defined PINS1 && defined PINS2  
   /* open file containing pin1 set of pins/signals */
   if (NULL == (port_file1 = fopen("gpio:write", (char_ptr) &pins1 ))) 
   {
       printf("Opening file1 GPIO for pins1 failed.\n");
      _task_block();
   }
   /* write logical 1 to all signals in the file (fast) */
   if (IO_OK != ioctl(port_file1, GPIO_IOCTL_WRITE_LOG1, NULL ))
   {
       printf("Writing to whole file1 failed.\n");
      _task_block();
   }
   /* write logical 0 to the pins/signals listed in pins2 array (slow) */
   if (IO_OK != ioctl(port_file1, GPIO_IOCTL_WRITE_LOG0, &pins2 ))
   {
       printf("Writing to pins2 of file1 failed.\n");
      _task_block();
   }
   /* close file1 */
   fclose(port_file1);
#endif
/************************************************
 Opening file for write without associated pins,
 pins are added later via IOCTL commans,
 write LOG 0 and LOG 1 to file.
************************************************/   
#ifdef PINS3  
   /* open file not containing any pin/signal */
   if (NULL == (port_file2 = fopen("gpio:write", (char_ptr) NULL)))
   {
       printf("Opening file2 GPIO without associated pins failed.\n");
      _task_block();
   }

   /* add pins/signals to the existing file */
   if (IO_OK != ioctl(port_file2, GPIO_IOCTL_ADD_PINS, &pins3 ))
   {
       printf("Adding pins3 to file2 failed.\n");
      _task_block();
   }

   /* write logical 0 to all signals in the file (fast) */
   if (IO_OK != ioctl(port_file2, GPIO_IOCTL_WRITE_LOG0, NULL ))
   {
       printf("Writing to pins3 of file2 failed.\n");
      _task_block();
   }
   /* close port 2 */
   fclose(port_file2);
#endif
/************************************************
 Opening file for read with associated pins(buttons),
 Opening file for write with associated pins(LEDs),
 After pressing button LED is activated.
************************************************/  
#if defined PINS4 && defined PINS2 
   

#if BSP_TWRMCF51MM || BSP_TWR_K40X256 || BSP_TWR_K40D100M || BSP_TWR_K60N512 ||\
    BSP_TWR_K53N512 || BSP_TWRMCF51QM || BSP_TWR_K60D100M
/* test interrupt capability for TWRMCF51MM board */
    {
        GPIO_PIN_STRUCT pins_int[] = {
            BSP_BUTTON1 | GPIO_PIN_IRQ_FALLING,
            GPIO_LIST_END
        };

        /* opening pins/signals for input */
        if (NULL == (port_file4 = fopen("gpio:read", (char_ptr) &pins_int )))
        {
           printf("Opening file4 GPIO with associated pins failed.\n");
          _task_block();
        }


        /* install gpio interrupt callback */
        ioctl(port_file4, GPIO_IOCTL_SET_IRQ_FUNCTION, (pointer)int_callback);


        while (int_counter < 5);
        
        fclose(port_file4);

    }
#endif   
   
   
   
   /* opening pins/signals for input */
   if (NULL == (port_file3 = fopen("gpio:read", (char_ptr) &pins4 )))
   {
       printf("Opening file3 GPIO with associated pins failed.\n");
      _task_block();
   }

   /* prepare new file with only one pin output */
   /* and open with new specification */
   if (NULL == (port_file1 = fopen("gpio:write", (char_ptr) &pins2 )))
   {
       printf("Opening file1 GPIO for pins2 failed.\n");
      _task_block();
   }

   /* It is not easy to generalize switch: every board has its own switch names */
   printf("Use SWITCH on board to switch LED on or off\n");
   while (TRUE)
   {
       /* read pin/signal status to pin list */
       if (IO_OK != ioctl(port_file3, GPIO_IOCTL_READ, (char_ptr) &pins4))
       {
           printf("Reading pin status from file3 to pins4 list failed.\n");
          _task_block();
       }
       /* test first's pin of file binary value */       
       if (pins4[0] & GPIO_PIN_STATUS)
       {
           printf("LED OFF.\n"); 
           /* clear pin to 0 (fast) */
           if (IO_OK != ioctl(port_file1, GPIO_IOCTL_WRITE_LOG0, NULL))
           {
               printf("Clearing pins2 to log 0 failed.\n");
              _task_block();
           }
       }
       else 
       {
           printf("LED ON.\n");
           /* set pin to 1 (fast) */
           if (IO_OK != ioctl(port_file1, GPIO_IOCTL_WRITE_LOG1, NULL))
           {
               printf("Setting pins2 to log 1 failed.\n");
              _task_block();
           }
       }
       
   }
/************************************************
 In case board does not have BUTTONS, 
 Only blink with LED.
************************************************/    
   
#elif defined PINS3

    
    
    /* if we don't have PINS4 set, blink */
    /* open file not containing any pin/signal */
    if (NULL == (port_file3 = fopen("gpio:write", (char_ptr) &pins3)))
    {
        printf("Opening file2 GPIO without associated pins failed.\n");
        _task_block();
    }

    while(TRUE){
    
        /* write logical 0 to all signals in the file (fast) */
        if (IO_OK != ioctl(port_file3, GPIO_IOCTL_WRITE_LOG0, NULL ))
        {
            printf("Writing to pins3 of file2 failed.\n");
            _task_block();
        }
        _time_delay(1000);
        /* write logical 1 to all signals in the file (fast) */
        if (IO_OK != ioctl(port_file3, GPIO_IOCTL_WRITE_LOG1, NULL ))
        {
            printf("Writing to pins3 of file2 failed.\n");
            _task_block();
        }   
        _time_delay(1000);
   }
#endif  
}  
Beispiel #16
0
void main_task
(
    uint32_t initial_data
)
{ /* Body */
    uint32_t        rtc_time;
    uint32_t        rtc_time_default;
    TIME_STRUCT     mqx_time;
    DATE_STRUCT     date_time;

    if (_lwevent_create(&lwevent,0) != MQX_OK)
    {
        printf("\nMake event failed");
        _task_block();
    }
    printf ("\f RTC Demo :\n\n");
    _rtc_get_time(&rtc_time);
    print_rtc_time(rtc_time);

    /* initialize time */
    date_time.YEAR     = RTC_TIME_INIT_TM_YEAR;
    date_time.MONTH    = RTC_TIME_INIT_TM_MON;
    date_time.DAY      = RTC_TIME_INIT_TM_MDAY;
    date_time.HOUR     = RTC_TIME_INIT_TM_HOUR;
    date_time.MINUTE   = RTC_TIME_INIT_TM_MIN;
    date_time.SECOND   = RTC_TIME_INIT_TM_SEC;
    date_time.MILLISEC = 0;

    /* Convert date time to time struct */
    if ( _time_from_date(&date_time, &mqx_time) == FALSE)
    {
        printf("\n Cannot convert date_time ");
        _task_block();
    }

    /* Convert rtc time to TIME_STRUCT */
    rtc_time = mqx_time.SECONDS;

    printf(" Set RTC time is: %s %s %3d %.2d:%.2d:%.2d %d\n",
            _days_abbrev[date_time.WDAY],
            _months_abbrev[date_time.MONTH - 1],
            date_time.DAY,
            date_time.HOUR,
            date_time.MINUTE,
            date_time.SECOND,
            date_time.YEAR);
    /* Set MQX time*/
    _time_set(&mqx_time);
    /* Set RTC time*/
    _rtc_set_time(rtc_time);
    printf("\n MQX time: %d SECONDS, %d MILISECOND ", mqx_time.SECONDS, mqx_time.MILLISECONDS);

    /*
     * set-up alarm
     */

    /* install callback */
    _rtc_callback_reg((INT_ISR_FPTR)rtc_callback, (void*)NULL);
    /* Set alarm to maximum time to avoid unexpected interrupt in next running */
    _rtc_set_alarm(MAXIMUM_SECONDS_IN_TIME,(uint32_t)0);
    _lwevent_clear(&lwevent,LWE_ALARM);
    
    /* Get current time */
    _rtc_get_time(&rtc_time);

    /* setup alarm in next 10 seconds & period 4 seconds*/
    rtc_time += (uint32_t)ALARM_NEXT_TIME; /* Alarm occurs in next 10 seconds */
    printf("\n Setup to occur alarm in next %d seconds & with period: %d seconds",ALARM_NEXT_TIME, ALARM_PERIOD);
    _rtc_set_alarm(rtc_time,(uint32_t)ALARM_PERIOD);
    printf("\n Wait %d seconds ....",ALARM_NEXT_TIME);
    /* Wait to clear LWE_ALARM event */
    _lwevent_wait_ticks(&lwevent,LWE_ALARM,FALSE,0);
    _lwevent_clear(&lwevent,LWE_ALARM);
    printf ("\nALARM! ALARM! ALARM!\n");
    /* Print current time */
    _rtc_get_time(&rtc_time);
    print_rtc_time(rtc_time);

    printf("\n Wait next alarm in %d seconds....",ALARM_PERIOD);
    _lwevent_wait_ticks(&lwevent,LWE_ALARM,FALSE,0);
    _lwevent_clear(&lwevent,LWE_ALARM);
    printf ("\nALARM! ALARM! ALARM!\n");
    _rtc_get_time(&rtc_time);
    print_rtc_time(rtc_time);

    printf ("\nClearing RTC:\n");
    _rtc_set_time(0);
    _rtc_get_time(&rtc_time_default);
    print_rtc_time(rtc_time_default);
    /* Wait 2 seconds after resynchronize rtc time with mqx time*/
    do{
       _rtc_get_time(&rtc_time);
    } while ((rtc_time - rtc_time_default) < 2);

    /* Get current time & display on terminal */
    _rtc_get_time(&rtc_time);
    print_rtc_time(rtc_time);

    printf ("Synchronize RTC to MQX time again:\n");
    _time_get(&mqx_time);
    rtc_time = mqx_time.SECONDS;
    _rtc_set_time(rtc_time);
    
    _rtc_get_time(&rtc_time);
    print_rtc_time(rtc_time);
    
#if PSP_HAS_IRTC == 1
    irtc_test();
#endif /* PSP_HAS_IRTC == 1 */

    printf ("Finish, press/hold reset to repeat.\n");
    _task_block() ;
} /* Endbody */
Beispiel #17
0
/*TASK*-----------------------------------------------------------------
*
* Function Name  : sdcard_task
* Returned Value : void
* Comments       :
*
*END------------------------------------------------------------------*/
void sdcard_task(uint_32 temp)
{
    boolean      inserted = TRUE, readonly = FALSE, last = FALSE;
    _mqx_int     error_code;
    _mqx_uint    param;
    MQX_FILE_PTR com_handle, sdcard_handle, filesystem_handle, partition_handle;
    char         filesystem_name[] = "a:";
    char         partman_name[] = "pm:";
    char         partition_name[] = "pm:1";
#if defined BSP_SDCARD_GPIO_DETECT
    LWGPIO_STRUCT      sd_detect;
#endif
#if defined BSP_SDCARD_GPIO_PROTECT
    LWGPIO_STRUCT      sd_protect;
#endif
#ifdef BSP_SDCARD_GPIO_CS

    LWGPIO_STRUCT          sd_cs;
    SPI_CS_CALLBACK_STRUCT callback;

#endif

    /* Open low level communication device */
    com_handle = fopen(SDCARD_COM_CHANNEL, (void *)(SPI_FLAG_FULL_DUPLEX));

    if (NULL == com_handle)
    {
        printf("Error opening communication handle %s, check your user_config.h.\n", SDCARD_COM_CHANNEL);
        _task_block();
    }

#ifdef BSP_SDCARD_GPIO_CS

    /* Open GPIO file for SPI CS signal emulation */
    error_code = lwgpio_init(&sd_cs, BSP_SDCARD_GPIO_CS, LWGPIO_DIR_OUTPUT, LWGPIO_VALUE_NOCHANGE);
    if (!error_code)
       {
           printf("Initializing GPIO with associated pins failed.\n");
           _task_block();
       }
    lwgpio_set_functionality(&sd_cs,BSP_SDCARD_CS_MUX_GPIO);
    lwgpio_set_attribute(&sd_cs, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
    /* Set CS callback */
    callback.MASK = BSP_SDCARD_SPI_CS;
    callback.CALLBACK = set_CS;
    callback.USERDATA = &sd_cs;
    if (SPI_OK != ioctl(com_handle, IO_IOCTL_SPI_SET_CS_CALLBACK, &callback))
    {
        printf ("Setting CS callback failed.\n");
        _task_block();
    }

#endif

#if defined BSP_SDCARD_GPIO_DETECT
    /* Init GPIO pins for other SD card signals */
    error_code = lwgpio_init(&sd_detect, BSP_SDCARD_GPIO_DETECT, LWGPIO_DIR_INPUT, LWGPIO_VALUE_NOCHANGE);
       if (!error_code)
       {
           printf("Initializing GPIO with sdcard detect pin failed.\n");
           _task_block();
       }
       /*Set detect and protect pins as GPIO Function */
       lwgpio_set_functionality(&sd_detect,BSP_SDCARD_DETECT_MUX_GPIO);
       lwgpio_set_attribute(&sd_detect, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
#endif

#if defined BSP_SDCARD_GPIO_PROTECT
    /* Init GPIO pins for other SD card signals */
    error_code = lwgpio_init(&sd_protect, BSP_SDCARD_GPIO_PROTECT, LWGPIO_DIR_INPUT, LWGPIO_VALUE_NOCHANGE);
       if (!error_code)
       {
           printf("Initializing GPIO with sdcard protect pin failed.\n");
           _task_block();
       }
       /*Set detect and protect pins as GPIO Function */
       lwgpio_set_functionality(&sd_protect,BSP_SDCARD_PROTECT_MUX_GPIO);
       lwgpio_set_attribute(&sd_protect, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
#endif

    /* Install SD card device */
    error_code = _io_sdcard_install("sdcard:", (pointer)&_bsp_sdcard0_init, com_handle);
    if ( error_code != MQX_OK )
    {
        printf("Error installing SD card device (0x%x)\n", error_code);
        _task_block();
    }

    for (;;)
    {

#if defined BSP_SDCARD_GPIO_DETECT
        #ifdef BSP_MPC8308RDB
        /* Set function as GPIO to detect sdcard */
        lwgpio_set_functionality(&sd_detect,BSP_SDCARD_DETECT_MUX_GPIO);
        lwgpio_set_attribute(&sd_detect, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
        #endif
        inserted = !lwgpio_get_value(&sd_detect);
#endif

#if defined BSP_SDCARD_GPIO_PROTECT
        /* Get value of protect pin */
        readonly = lwgpio_get_value(&sd_protect);
#endif
#ifdef BSP_MPC8308RDB
        /* Set function as SD_CD which indicate that card is present in Present State Register */
        lwgpio_set_functionality(&sd_detect,BSP_SDCARD_DETECT_MUX_SD_CD);
        lwgpio_set_attribute(&sd_detect, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
#endif
        if (last != inserted)
        {
            last = inserted;
        	        
            if (inserted)
            {
                _time_delay (200);
                /* Open the device which MFS will be installed on */
                sdcard_handle = fopen("sdcard:", 0);
                if (sdcard_handle == NULL)
                {
                    printf("Unable to open SD card device.\n");
                    continue;
                }

                /* Set read only flag as needed */
                param = 0;
                if (readonly)
                {
                    param = IO_O_RDONLY;
                }
                if (IO_OK != ioctl(sdcard_handle, IO_IOCTL_SET_FLAGS, (char_ptr) &param))
                {
                    printf("Setting device read only failed.\n");
                    continue;
                }

                /* Install partition manager over SD card driver */
                error_code = _io_part_mgr_install(sdcard_handle, partman_name, 0);
                if (error_code != MFS_NO_ERROR)
                {
                    printf("Error installing partition manager: %s\n", MFS_Error_text((uint_32)error_code));
                    continue;
                }

                /* Open partition */
                partition_handle = fopen(partition_name, NULL);
                if (partition_handle != NULL)
                {
                    printf("Installing MFS over partition...\n");
                    
                    /* Validate partition */
                    error_code = _io_ioctl(partition_handle, IO_IOCTL_VAL_PART, NULL);
                    if (error_code != MFS_NO_ERROR)
                    {
                        printf("Error validating partition: %s\n", MFS_Error_text((uint_32)error_code));
                        printf("Not installing MFS.\n");
                        continue;
                    }

                    /* Install MFS over partition */
                    error_code = _io_mfs_install(partition_handle, filesystem_name, 0);
                    if (error_code != MFS_NO_ERROR)
                    {
                        printf("Error initializing MFS over partition: %s\n", MFS_Error_text((uint_32)error_code));
                    }

                } else {

                    printf("Installing MFS over SD card driver...\n");
                	
                    /* Install MFS over SD card driver */
                    error_code = _io_mfs_install(sdcard_handle, filesystem_name, (_file_size)0);
                    if (error_code != MFS_NO_ERROR)
                    {
                        printf("Error initializing MFS: %s\n", MFS_Error_text((uint_32)error_code));
                    }
                }

                /* Open file system */
                if (error_code == MFS_NO_ERROR) {
                    filesystem_handle = fopen(filesystem_name, NULL);
                    error_code = ferror(filesystem_handle);
                    if (error_code == MFS_NOT_A_DOS_DISK)
                    {
                        printf("NOT A DOS DISK! You must format to continue.\n");
                    }
                    else if (error_code != MFS_NO_ERROR)
                    {
                        printf("Error opening filesystem: %s\n", MFS_Error_text((uint_32)error_code));
                        continue;
                    }

                    printf ("SD card installed to %s\n", filesystem_name);
                    if (readonly)
                    {
                        printf ("SD card is locked (read only).\n");
                    }
                }
            }
            else
            {
                /* Close the filesystem */
            	if ((filesystem_handle != NULL) && (MQX_OK != fclose(filesystem_handle)))
                {
                    printf("Error closing filesystem.\n");
                }
            	filesystem_handle = NULL;

                /* Uninstall MFS  */
                error_code = _io_dev_uninstall(filesystem_name);
                if (error_code != MFS_NO_ERROR)
                {
                    printf("Error uninstalling filesystem.\n");
                }
                
                /* Close partition */
                if ((partition_handle != NULL) && (MQX_OK != fclose(partition_handle)))
                {
                    printf("Error closing partition.\n");
                }
                partition_handle = NULL;

                /* Uninstall partition manager  */
                error_code = _io_dev_uninstall(partman_name);
                if (error_code != MFS_NO_ERROR)
                {
                    printf("Error uninstalling partition manager.\n");
                }

                /* Close the SD card device */
                if ((sdcard_handle != NULL) && (MQX_OK != fclose(sdcard_handle)))
                {
                    printf("Unable to close SD card device.\n");
                }
                sdcard_handle = NULL;

                printf ("SD card uninstalled.\n");
            }
        }
        
        _time_delay (200);
    }
}
Beispiel #18
0
void uart_tx_task ( uint32_t initial_data )
{  
   SMTPLG_Header * plg_head_p = (SMTPLG_Header *) command_txd_buf;
   SMTPLG_Body * plg_body_p = (SMTPLG_Body *)(command_txd_buf + CMD_HEAD_NUM);  //Note, fix a bug,  not plg_head_p + CMD_HEAD_NUM;
   uint32_t len = 0;
   _mqx_uint res;
   msg_t msg;
   static uint8_t opt_cnt = SMTPLG_CMD_OP_GET_ACT_PWR;
   
   uart_tx_dev  = fopen( UART_CHANNEL, NULL );					   
   if( uart_tx_dev == NULL )
   {
     /* device could not be opened */
     printf("__Evanguo: Open uart tx dev failed, uart_tx_task blocked\n");
     _task_block();
   }
   
   if (MQX_OK != _lwmsgq_init(uart_tx_taskq, 10, TX_TASKQ_GRANM)) 
   {
     printf("lwmsgq_init connect_taskq failed\n");
     _task_block();
   }
   
   command_send(CMD_GET, cls_shiftor_opc(SMTPLG_CMD_CLS_APP, SMTPLG_CMD_OP_GET_PWR_STS), NULL, 0);
   
   rtc_date.fullYear = 2014;
   rtc_date.month = 1;
   rtc_date.mDay = 1;
   
   while(1){
     if((res = _lwmsgq_receive(&uart_tx_taskq, (_mqx_max_type *) &msg, LWMSGQ_RECEIVE_BLOCK_ON_EMPTY,  100 /* ticks */, 0)) == MQX_OK){  /* 1tick =5ms */
       plg_head_p->CLA = msg.cmd_cls;
       plg_head_p->INS = msg.cmd_opc;
       
       if(msg.type == CMD_SET){
         if(msg.len > 1){
          // if((plg_head_p->CLA == SMTPLG_CMD_CLS_APP)&&((plg_head_p->INS == SMTPLG_CMD_OP_SET_TIMER_BEGIN)||  \
		  	             //                               (plg_head_p->INS == SMTPLG_CMD_OP_SET_TIMER_END)||(plg_head_p->INS == SMTPLG_CMD_OP_SET_CUR_TIME)))
           { /* SET work time */
             plg_head_p->P1 = 0;
             plg_head_p->P2 = 0;
             plg_head_p->P3 = 0;
             plg_head_p->LC = (uint8_t)msg.len;
             if(plg_head_p->LC > CMD_BODY_NUM) 
               plg_head_p->LC = CMD_BODY_NUM;
                                           
             _mem_zero((void *)plg_body_p->Data, CMD_BODY_NUM);
             _mem_copy((void *)msg.data, (void *)plg_body_p->Data, plg_head_p->LC);
             //len = CMD_HEAD_NUM + plg_head_p->LC;
             len = CMD_HEAD_NUM + CMD_BODY_NUM;
           } 
         }
         else if(msg.len == 1){
           plg_head_p->P1 = *(uint8_t *)msg.data;   /* ON/OFF */
           plg_head_p->P2 = 0;
           plg_head_p->P3 = 0;
           plg_head_p->LC = 0;
           len = CMD_HEAD_NUM;
        }
       }
       else if(msg.type == CMD_GET){
           plg_head_p->P1 = 0;
           plg_head_p->P2 = 0;
           plg_head_p->P3 = 0;
           plg_head_p->LC = 0;
           len = CMD_HEAD_NUM;      
       }
       else if(msg.type == CMD_ACK){
         if((plg_head_p->CLA == SMTPLG_CMD_CLS_WIFI_CTL)&&(plg_head_p->INS == SMTPLG_CMD_OP_WIFI_INIT)){
           plg_head_p->P1 = *(uint8_t *)msg.data;   /* ON/OFF */
           plg_head_p->P2 = *((uint8_t *)msg.data + 1);
           plg_head_p->P3 = 0;
           plg_head_p->LC = 0;
           len = CMD_HEAD_NUM;
        }
       }
     }  
     else if(res == LWMSGQ_TIMEOUT){		
       //printf("__Evanguo: wait msg time out\n");
       msg.type == CMD_GET;
       plg_head_p->CLA = SMTPLG_CMD_CLS_APP;
       plg_head_p->INS = opt_cnt ++;	  
       plg_head_p->P1 = 0;
       plg_head_p->P2 = 0;
       plg_head_p->P3 = 0;
       plg_head_p->LC = 0;
       len = CMD_HEAD_NUM;
       if( opt_cnt > SMTPLG_CMD_OP_GET_HIST_TIME)
         opt_cnt = SMTPLG_CMD_OP_GET_ACT_PWR;
     }
     else{
       printf("__Evanguo: _lwmsgq_receive uart_tx_taskq failed\n");
     }
     plg_head_p->MAGIC1 = MAGIC_NUMBER_1;
     plg_head_p->MAGIC2 = MAGIC_NUMBER_2;

     if(UI_data_flag == TRUE){
       write( uart_tx_dev, (void *)plg_head_p, len);
       fflush( uart_tx_dev );  /* ioctl  IO_IOCTL_FLUSH_OUTPUT */
     }
     
   }

   fclose(uart_tx_dev);
}
Beispiel #19
0
void USB_task(uint_32 param)
{ 
    _usb_host_handle     host_handle;
    USB_STATUS           error;
    pointer              usb_fs_handle = NULL;
    usb_msg_t            msg;
    /* Store mounting point used. A: is the first one, bit #0 assigned, Z: is the last one, bit #25 assigned */
    uint_32              fs_mountp = 0;
   
#if DEMOCFG_USE_POOLS && defined(DEMOCFG_MFS_POOL_ADDR) && defined(DEMOCFG_MFS_POOL_SIZE)
    _MFS_pool_id = _mem_create_pool((pointer)DEMOCFG_MFS_POOL_ADDR, DEMOCFG_MFS_POOL_SIZE);
#endif

    /* This event will inform other tasks that the filesystem on USB was successfully installed */
    _lwsem_create(&USB_Stick, 0);
    
    if (MQX_OK != _lwmsgq_init(usb_taskq, 20, USB_TASKQ_GRANM)) {
        // lwmsgq_init failed
        _task_block();
    }

    USB_lock();
    _int_install_unexpected_isr();
   if (MQX_OK != _usb_host_driver_install(USBCFG_DEFAULT_HOST_CONTROLLER)) {
      printf("\n Driver installation failed");
      _task_block();
   }

    error = _usb_host_init(USBCFG_DEFAULT_HOST_CONTROLLER, &host_handle);
    if (error == USB_OK) {
        error = _usb_host_driver_info_register(host_handle, (pointer)ClassDriverInfoTable);
        if (error == USB_OK) {
            error = _usb_host_register_service(host_handle, USB_SERVICE_HOST_RESUME,NULL);
        }
    }

    USB_unlock();

    if (error != USB_OK) {
        _task_block();
    }
      
    for (;;) {
        /* Wait for event sent as a message */
        _lwmsgq_receive(&usb_taskq, (_mqx_max_type *) &msg, LWMSGQ_RECEIVE_BLOCK_ON_EMPTY, 0, 0);
         
        //if (device.STATE == USB_DEVICE_ATTACHED) {
        if (msg.body == USB_EVENT_ATTACH) {
          /* This event is not so important, because it does not inform about successfull USB stack enumeration */
        } else if (msg.body == USB_EVENT_INTF && fs_mountp != 0x3FFC)  { /* if mountpoints c: to z: are already used */
            char              drive[3];

            /* get free mountpoint as a string like "c:" */
            for (drive[0] = 'c'; drive[0] <= 'z'; drive[0]++)
                if (!(fs_mountp & (1 << (drive[0] - 'a'))))
                    break;
            drive[1] = ':';
            drive[2] = 0;
            
            // Install the file system, use device->ccs as a handle
            usb_fs_handle = usb_filesystem_install( (pointer) msg.ccs, "USB:", "PM_C1:", drive );
                  
            if (usb_fs_handle) {
                DEVICE_STRUCT_PTR dsp = (DEVICE_STRUCT_PTR) msg.ccs;
                dsp->mount = drive[0];

                // Mark file system as mounted
                fs_mountp |= 1 << (dsp->mount - 'a');
                // Unlock the USB_Stick = signal to the application as available
                _lwsem_post(&USB_Stick);
            }
        } else if (msg.body == USB_EVENT_DETACH) {
            DEVICE_STRUCT_PTR dsp = (DEVICE_STRUCT_PTR) msg.ccs;

            if (dsp->mount >= 'a' && dsp->mount <= 'z') {
                // Lock the USB_Stick = mark as unavailable
                _lwsem_wait(&USB_Stick);

                // Remove the file system 
                usb_filesystem_uninstall(usb_fs_handle);
                // Mark file system as unmounted
                fs_mountp &= ~(1 << (dsp->mount - 'a'));
            }

            /* Here, the device finishes its lifetime */            
            _mem_free(dsp);
        }
    }
}
Beispiel #20
0
boolean SEC_InitializeIO(void) 
{

    /* Init Gpio for Leds as output to drive LEDs (LED10 - LED13) */
#ifdef LED_1
       output_port = lwgpio_init(&led1, LED_1, LWGPIO_DIR_OUTPUT, LWGPIO_VALUE_NOCHANGE);
       if(!output_port){
          printf("Initializing LWGPIO for LED1 failed.\n");
       }
       lwgpio_set_functionality(&led1, BSP_LED1_MUX_GPIO);
       /*Turn off Led */
       lwgpio_set_value(&led1, LWGPIO_VALUE_LOW);
#endif

#ifdef LED_2
       output_port = lwgpio_init(&led2, LED_2, LWGPIO_DIR_OUTPUT, LWGPIO_VALUE_NOCHANGE);
       if(!output_port){
          printf("Initializing LWGPIO for LED2 failed.\n");
    
       }
       lwgpio_set_functionality(&led2, BSP_LED2_MUX_GPIO);
       /*Turn off Led */
       lwgpio_set_value(&led2, LWGPIO_VALUE_LOW);
#endif
    
#ifdef LED_3
       output_port = lwgpio_init(&led3, LED_3, LWGPIO_DIR_OUTPUT, LWGPIO_VALUE_NOCHANGE);
       if(!output_port){
          printf("Initializing LWGPIO for LED3 failed.\n");
       }
       lwgpio_set_functionality(&led3, BSP_LED3_MUX_GPIO);
       /*Turn off Led */
       lwgpio_set_value(&led3, LWGPIO_VALUE_LOW);
#endif

#ifdef LED_4
       output_port = lwgpio_init(&led4, LED_4, LWGPIO_DIR_OUTPUT, LWGPIO_VALUE_NOCHANGE);
       if(!output_port){
          printf("Initializing LWGPIO for LED4 failed.\n");
       }
       lwgpio_set_functionality(&led4, BSP_LED4_MUX_GPIO);
       /*Turn off Led */
       lwgpio_set_value(&led4, LWGPIO_VALUE_LOW);
#endif

#ifdef BSP_BUTTON1
        /* Open and set port DD as input to read value from switches */
           input_port = lwgpio_init(&button1, DOOR_STATE, LWGPIO_DIR_INPUT, LWGPIO_VALUE_NOCHANGE);
           if(!input_port)
           {
               printf("Initializing LW GPIO for button1 as input failed.\n");
               _task_block();
           }    
           lwgpio_set_functionality(&button1 ,BSP_BUTTON1_MUX_GPIO);
           lwgpio_set_attribute(&button1, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
#endif

#ifdef BSP_BUTTON2
           input_port = lwgpio_init(&button2, WINDOW_STATE, LWGPIO_DIR_INPUT, LWGPIO_VALUE_NOCHANGE);
           if(!input_port)
           {
               printf("Initializing LW GPIO for button2 as input failed.\n");
               _task_block();
           }
           lwgpio_set_functionality(&button2, BSP_BUTTON2_MUX_GPIO);
           lwgpio_set_attribute(&button2, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
     
#endif
    return (input_port!=0) && (output_port!=0);
}
Beispiel #21
0
/*TASK*-----------------------------------------------------
*
* Task Name    : main_task
* Comments     : Low power modes switching.
*
*END*-----------------------------------------------------*/
void main_task
    (
        uint32_t initial_data
    )
{
    LPM_OPERATION_MODE operation_mode;
    IDLE_LOOP_STRUCT   idle_loops;
    uint32_t            loop1;

    /* Initialize switches */
    button_led_init();
    
    _int_install_unexpected_isr();
    _lpm_register_wakeup_callback(BSP_LLWU_INTERRUPT_VECTOR, BSP_LLWU_INTERRUPT_PRIORITY, NULL);

    /* Install interrupt for timer wakeup */
    install_timer_interrupt();
    
    /* Create global event */
    if (_lwevent_create(&app_event, 0) != MQX_OK)
    {
        printf("\nCreating app_event failed.\n");
        _task_block();
    }

#if (PSP_MQX_CPU_IS_KINETIS)
    if (_lpm_get_reset_source() != MQX_RESET_SOURCE_LLWU)
        printf("\nMQX Low Power Modes Demo\n");
    else
#endif
        printf("\nWake up by reset from LLWU\n");

    while (1)
    {
        /* Find out current mode setting */
        operation_mode = _lpm_get_operation_mode();

        printf("\n******************************************************************************\n");
        printf("************** Operation mode : %s ***********************\n", get_operation_mode_name (operation_mode));
        printf("******************************************************************************\n");

        display_operation_mode_setting(operation_mode);

        printf(
        "Info: RUN operation mode is mapped on RUN power mode by default.\n"
        "      The core runs at full clock speed.\n"
        "      It continues the execution after entering the mode.\n"
        "      LED2 blinks quickly, LED1 toggles after the button press.\n");

        /* Demonstration of idle task sleep feature */
        printf("\nIdle task sleep feature disabled.\n");
        _lpm_idle_sleep_setup (FALSE);
        
        printf("Task suspended for 1 second to let run the idle task.\n");
        _mqx_get_idle_loop_count (&idle_loops);
        loop1 = idle_loops.IDLE_LOOP1;
        _time_delay (1000);
        
        _mqx_get_idle_loop_count (&idle_loops);
        printf ("Idle loops per second with idle sleep disabled: %d\n", idle_loops.IDLE_LOOP1 - loop1);
        
        printf("Idle task sleep feature enabled.\n");
        _lpm_idle_sleep_setup (TRUE);
        
        printf("Task suspended for 1 second to let run the idle task.\n");
        _mqx_get_idle_loop_count (&idle_loops);
        loop1 = idle_loops.IDLE_LOOP1;
        _time_delay (1000);
        
        _mqx_get_idle_loop_count (&idle_loops);
        printf ("Idle loops per second with idle sleep enabled:  %d\n", idle_loops.IDLE_LOOP1 - loop1);

        printf("Idle task sleep feature disabled.\n\n");
        _lpm_idle_sleep_setup (FALSE);
        
        /* Wait for button press */
        printf ("Press button to move to next operation mode.\n");
        _lwevent_wait_ticks (&app_event, SW_EVENT_MASK, FALSE, 0);
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        printf("\nButton pressed. Moving to next operation mode.\n");

        operation_mode = LPM_OPERATION_MODE_WAIT;
        
        printf("\n******************************************************************************\n");
        printf("************** Operation mode : %s **********************\n", get_operation_mode_name (operation_mode));
        printf("******************************************************************************\n");

        display_operation_mode_setting(operation_mode);

        printf(
        "Info: WAIT operation mode is mapped on VLPR power mode by default.\n"
        "      It requires 2 MHz core clock and bypassed pll.\n"
        "      Core continues the execution after entering the mode.\n"
        "      LED2 blinks slowly, LED1 toggles after the button press.\n");

        /* The LPM_OPERATION_MODE_WAIT is mapped on LPM_CPU_POWER_MODE_VLPR by default,
        this mode requires 2 MHz, bypassed PLL clock setting. Change clocks to appropriate mode */
        printf("\nChanging frequency to 2 MHz.\n");
        if (CM_ERR_OK != _lpm_set_clock_configuration(BSP_CLOCK_CONFIGURATION_2MHZ))
        {
            printf("Cannot change clock configuration");
            _task_block();
        }
        /* Change the operation mode */
        printf ("\nSetting operation mode to %s ... ", get_operation_mode_name (operation_mode));
        printf ("%s\n", _lpm_set_operation_mode (LPM_OPERATION_MODE_WAIT) == 0 ? "OK" : "ERROR");

        /* Wait for button press */
        printf ("\nPress button to move to next operation mode.\n");
        _lwevent_wait_ticks (&app_event, SW_EVENT_MASK, FALSE, 0);
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        printf("\nButton pressed.\n");

        /* Return to RUN mode */
        printf ("\nSetting operation mode back to %s ... ", get_operation_mode_name (LPM_OPERATION_MODE_RUN));
        printf ("%s\n", _lpm_set_operation_mode (LPM_OPERATION_MODE_RUN) == 0 ? "OK" : "ERROR");

        /* Return default clock configuration */
        printf("\nChanging frequency back to the default one.\n");
        if (CM_ERR_OK != _lpm_set_clock_configuration(BSP_CLOCK_CONFIGURATION_DEFAULT))
        {
            printf("Cannot change clock configuration");
            _task_block();
        }

        printf("\nMoving to next operation mode.\n");

        operation_mode = LPM_OPERATION_MODE_SLEEP;

        printf("\n******************************************************************************\n");
        printf("************** Operation mode : %s *********************\n", get_operation_mode_name (operation_mode));
        printf("******************************************************************************\n");

        display_operation_mode_setting(operation_mode);

        printf(
        "Info: SLEEP operation mode is mapped on WAIT power mode by default.\n"
        "      The core is inactive in this mode, reacting only to interrupts.\n"
        "      The LPM_CPU_POWER_MODE_FLAG_SLEEP_ON_EXIT is set on Kinetis, therefore\n"
        "      core goes to sleep again after any isr finishes. The core will stay awake\n"
        "      after call to _lpm_wakeup_core() from timer wakeup or serial interrupt.\n"
        "      LED2 doesn't blink, LED1 toggles after the button press.\n");

        /* Wake up in 10 seconds */
        set_timer_wakeup ();

        /* Change the operation mode */
        printf ("\nSetting operation mode to %s ... ", get_operation_mode_name (operation_mode));
        printf ("%s\n", _lpm_set_operation_mode (operation_mode) == 0 ? "OK" : "ERROR");
        
        if (LWEVENT_WAIT_TIMEOUT == _lwevent_wait_ticks (&app_event, TIMER_EVENT_MASK, FALSE, 1))
        {
            printf("\nCore woke up by interrupt. Waiting for timer wakeup ... ");
            _lwevent_wait_ticks (&app_event, TIMER_EVENT_MASK, FALSE, 0);
            printf("OK\n");
        }
        else
        {
            printf("\nCore woke up by timer wakeup.\n");
        }
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        
        /* Wait for button press */
        printf ("\nPress button to move to next operation mode.\n");
        _lwevent_wait_ticks (&app_event, SW_EVENT_MASK, FALSE, 0);
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        printf("\nButton pressed. Moving to next operation mode.\n");

        operation_mode = LPM_OPERATION_MODE_STOP;

        printf("\n******************************************************************************\n");
        printf("************** Operation mode : %s **********************\n", get_operation_mode_name (operation_mode));
        printf("******************************************************************************\n");

        display_operation_mode_setting(operation_mode);

        printf(
        "Info: STOP operation mode is mapped to LLS power mode by default.\n"
        "      Core and most peripherals are inactive in this mode, reacting only to\n"
        "      specified wake up events. The events can be changed in BSP (init_lpm.c).\n"
        "      Serial line is turned off in this mode. The core will wake up from\n"
        "      timer wakeup interrupt.\n"
        "      LED2 doesn't blink, LED1 toggles after the button press.\n");

        /* Wake up in 10 seconds */
        set_timer_wakeup ();

        /* Change the operation mode */
        printf ("\nSetting operation mode to %s ... \n", get_operation_mode_name (operation_mode));
        _lpm_set_operation_mode (operation_mode);

        /**************************************************************************************************/
        /* SCI HW MODULE IS DISABLED AT THIS POINT - SERIAL DRIVER MUST NOT BE USED UNTIL MODE IS CHANGED */
        /**************************************************************************************************/
        
        /* Return to RUN mode */
        _lpm_set_operation_mode (LPM_OPERATION_MODE_RUN);
        
        printf("\nCore is awake. Moved to next operation mode.\n");
    }
}
Beispiel #22
0
void SEC_EmailAlert()
{
   MQX_TICK_STRUCT      ticks;
   MQX_XDATE_STRUCT     xdate;
   sockaddr             addr;
   _ip_address          ipaddr;
   uint_32              sock;
   uint_32              error;
   uint_32              option;
   char_ptr             event_ptr;
   char                 temp[150];
   char                 domain[30];
   char                 user[30];
    
#if DEMOCFG_AUTH_REQUIRED    
   char                 temp_encoded[40];
#endif
    

  
   if (!RTCS_resolve_ip_address(EMAIL_SERVER,&ipaddr,NULL,0)) {
      printf("Error resolving IP address for %s using DNS Server at %d.%d.%d.%d\n", EMAIL_SERVER, IPBYTES(ipcfg_get_dns_ip(BSP_DEFAULT_ENET_DEVICE, 0)));
      return;
   }
  
    /* Create socket */        
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == RTCS_SOCKET_ERROR) 
    {
        printf("Error creating socket\n");
        return;
    } 

   /* Reduce buffer size of socket to save memory */
   option = SMTP_BUFFER_SIZE;   
   error = setsockopt(sock, SOL_TCP, OPT_TBSIZE, &option, sizeof(option));
   option = SMTP_BUFFER_SIZE;   
   error = setsockopt(sock, SOL_TCP, OPT_RBSIZE, &option, sizeof(option));
   option = 1000;   
   error = setsockopt(sock, SOL_TCP, OPT_TIMEWAIT_TIMEOUT, &option, sizeof(option));


    /* Allow binding to any address */
   
    #if RTCSCFG_ENABLE_IP4  
    ((sockaddr_in*)(&addr))->sin_family      = AF_INET;
    ((sockaddr_in*)(&addr))->sin_port        = 0;
    ((sockaddr_in*)(&addr))->sin_addr.s_addr = INADDR_ANY;
 
    #elif RTCSCFG_ENABLE_IP6
        printf("\nThis application don't support IPv6 only.\n");
        _task_block();
    #endif

    error = bind(sock, &addr, sizeof(addr));
    if (error != RTCS_OK) {
        printf("Error in binding socket %08x\n",error);
        shutdown(sock, FLAG_ABORT_CONNECTION);
        return;
    } 

    /* Connect to SMTP server */
    #if RTCSCFG_ENABLE_IP4
        ((sockaddr_in*)(&addr))->sin_port        = IPPORT_SMTP;
        ((sockaddr_in*)(&addr))->sin_addr.s_addr = ipaddr;
    #elif RTCSCFG_ENABLE_IP6
        printf("\nThis application does not support IPv6 only.\n");
        _task_block();
    #endif


    error = connect(sock, &addr, sizeof(addr));
    if (error != RTCS_OK) {
        printf("Error in connection %08x\n",error);
        shutdown(sock, FLAG_ABORT_CONNECTION);
        return;
    }
  
    printf("\nConnecting to SMTP server %s...\n",EMAIL_SERVER);
    printf("SMTP Server Response:\n");
    SMTP_Receive_string(sock, temp, sizeof(temp));


    /* Follow SMTP protocol to send email */   

    /* Parse domain name from the FROM address, 
     for use with the EHLO or HELO commands */
    sscanf(EMAIL_FROM,"%30s@%30s",user,domain);
  
#if DEMOCFG_AUTH_REQUIRED 
  
    /* If Authentification is required, use EHLO command */
    SMTP_Send_command(sock, "EHLO", domain, temp, sizeof(temp));
    SMTP_Send_command(sock,"AUTH LOGIN",NULL,temp,sizeof(temp));

    /* Find base64 econding of login name and send to SMTP server */
    sprintf(temp,"%s\r\n",base64_encode(AUTH_USERNAME,temp_encoded));
    SMTP_Send_string(sock,temp);
    SMTP_Receive_string(sock,temp,sizeof(temp)-1);

    /* Find base64 econding of password and send to SMTP server */
    sprintf(temp,"%s\r\n",base64_encode(AUTH_PASSWORD,temp_encoded));
    SMTP_Send_string(sock,temp);
    SMTP_Receive_string(sock,temp, sizeof(temp)-1);
#else
    /* If Authentification is not required, use HELO command as not all servers recognize EHLO */
    SMTP_Send_command(sock, "HELO", domain, temp, sizeof(temp));
#endif


   /* Transfer sender email address to server */     
   SMTP_Send_command(sock,"MAIL FROM:","<" EMAIL_FROM ">" ,temp,sizeof(temp));
   /* Transfer recipient email address to server */            
   SMTP_Send_command(sock,"RCPT TO:","<" EMAIL_TO ">" ,temp,sizeof(temp));

   /* Start DATA section */
   SMTP_Send_command(sock,"DATA",NULL,temp,sizeof(temp));

   printf("Sent:\n");
   /* Send Subject, To, and From fields */
   SMTP_Send_string(sock,(pointer)Email_header);


   /* Determine what to send as body of message */
   _time_get_ticks(&ticks);
   _time_ticks_to_xdate(&ticks,&xdate);    

   sprintf(temp, "Date: %s, %d %s %d %02d:%02d:%02d -0000\r\n\r\n",
      wday[xdate.WDAY],xdate.MDAY, months[xdate.MONTH-1],xdate.YEAR, xdate.HOUR, xdate.MIN, xdate.SEC  );
   SMTP_Send_string(sock,temp);


   /* If button pushed was the "Door"... */
   if(SEC_Params.Status==SEC_DOOR_OPEN_STATUS)
   {
      event_ptr = "Door was opened ";
   } else 
   /* If button pushed was the "Window"... */
   if(SEC_Params.Status==SEC_WINDOW_OPEN_STATUS)
   {
      event_ptr = "Window was opened ";
   }
   /* If not sure what caused stop mode to exit... */  
   else 
   {
      event_ptr = "Unknown event occurred ";
   }    
   SMTP_Send_string(sock,event_ptr);

   /* If SNTP enabled, then send exact date and time button press happened */
   #if DEMOCFG_ENABLE_SNTP
      sprintf(temp,"on %d/%d/%d at %02d:%02d:%02d GMT. \r\n",xdate.MONTH,xdate.MDAY,xdate.YEAR,xdate.HOUR,xdate.MIN,xdate.SEC);
   /* If SNTP not enabled, then give elapsed time instead */
   #else
      sprintf(temp,"%02d:%02d:%02d after system was started. \r\n",xdate.HOUR,xdate.MIN,xdate.SEC);
   #endif
   SMTP_Send_string(sock,temp);  

   if (last[0]) {
      /* Send out how long ago the last event was */
      SMTP_Send_string(sock,"Previous event was ");
      SMTP_Send_string(sock,last);
   }
   strcpy(last,temp); 
   
   /* Send Freescale signature and disconnect from server with QUIT command */
   SMTP_Send_string(sock,"\r\n-Freescale Semiconductor\r\n.\r\n");
   
   SMTP_Send_command(sock,"QUIT",NULL,temp,sizeof(temp));

  /* Close socket */
    shutdown(sock, FLAG_CLOSE_TX);  
}
Beispiel #23
0
void main_task
   (
      uint32_t            dummy
   )
{
   MQX_FILE_PTR          fd;
   _mqx_int            param, result, nack;
   unsigned char                 address;

   printf ("\n%s I2C slave example - 256 byte EEPROM emulation\n\n", I2C_POLLED_MODE ? "Polled" : "Interrupt");
   printf ("Please attach I2C master to appropriate I2C bus.\n");
   printf ("I2C EEPROM communication protocol should be used (e.g. 'i2c' example).\n\n");

   /* Open the I2C driver */         
   fd = fopen (I2C_DEVICE, NULL);
   if (fd == NULL) 
   {
      printf ("ERROR opening the I2C driver!\n");
      _task_block ();
   }

   /* Test ioctl commands */
   param = 100000;
   printf ("Set current baud rate to %d ... ", param);
   if (I2C_OK == ioctl (fd, IO_IOCTL_I2C_SET_BAUD, &param))
   {
      printf ("OK\n");
   } else {
      printf ("ERROR\n");
   }

   printf ("Get current baud rate ... ");
   if (I2C_OK == ioctl (fd, IO_IOCTL_I2C_GET_BAUD, &param))
   {
      printf ("%d\n", param);
   } else {
      printf ("ERROR\n");
   }

   printf ("Set slave mode ... ");
   if (I2C_OK == ioctl (fd, IO_IOCTL_I2C_SET_SLAVE_MODE, NULL))
   {
      printf ("OK\n");
   } else {
      printf ("ERROR\n");
   }

   printf ("Get current mode ... ");
   if (I2C_OK == ioctl (fd, IO_IOCTL_I2C_GET_MODE, &param))
   {
      printf ("0x%02x\n", param);
   } else {
      printf ("ERROR\n");
   }
   
   param = I2C_EEPROM_ADDRESS;
   printf ("Set station address to 0x%02x ... ", param);
   if (I2C_OK == ioctl (fd, IO_IOCTL_I2C_SET_STATION_ADDRESS, &param))
   {
      printf ("OK\n");
   } else {
      printf ("ERROR\n");
   }
   
   param = 0x00;
   printf ("Get station address ... ");
   if (I2C_OK == ioctl (fd, IO_IOCTL_I2C_GET_STATION_ADDRESS, &param))
   {
      printf ("0x%02x\n", param);
   } else {
      printf ("ERROR\n");
   }

   printf ("\nSend character over terminal to dump memory contents.\n");
   
   

#if I2C_POLLED_MODE
   
   /* I2C slave polled mode EEPROM emulation */
   result = 0;
   address = 0;
   while (1)
   {
      /* EEPROM always ACKs incoming bytes */
      param = 0xFFFFFFFF;
      if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_SET_RX_REQUEST, &param))
      {
         printf ("ERROR: set rx request\n");
      }
      
      /* Wait to be addressed */
      if (0 == result)
      {
         /* Enable memory dumping when idle */
         dump = TRUE;
         
         do 
         {
            /* Get memory address for read/write operation */
            result = fread (&address, 1, 1, fd);
            
            /* Handle special states */
            if (0 == result)
            {
               if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_GET_STATE, &param))
               {
                  printf ("ERROR: get state read address\n");
               }
               if (I2C_STATE_FINISHED == param)
               {
                  /* Stop condition detected on the bus, return to ready state */
                  if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_STOP, NULL))
                  {
                     printf ("ERROR: stop read address\n");
                  }
                  
                  /* EEPROM always ACKs incoming bytes */
                  param = 0xFFFFFFFF;
                  if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_SET_RX_REQUEST, &param))
                  {
                     printf ("ERROR: set rx request\n");
                  }
               }
               else if ((I2C_STATE_RECEIVE != param) && (I2C_STATE_ADDRESSED_AS_SLAVE_RX != param))
               {
                  /* Memory address was omitted or unknown event */
                  result = 1;
               }
            }
         } while (1 != result);
         
         /* Temporarily disable memory dump when changing/sending contents */
         dump = FALSE;
      }
      
      /* Check for next byte and required operation */
      result = fread (&(memory[address]), 1, 1, fd);
      
      /* Get required operation */
      if (result)
      {
         param = I2C_STATE_ADDRESSED_AS_SLAVE_RX;
      }
      else
      {
         if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_GET_STATE, &param))
         {
            printf ("ERROR: get required operation\n");
         }
      }
      
      switch (param)
      {
         case I2C_STATE_RECEIVE:
         case I2C_STATE_ADDRESSED_AS_SLAVE_RX:
        
            if (result)
            {
               /* Receive data, store bytes from given address, loop within page size */
               while (result)
               {
                  address++;
                  if (0 == (address % I2C_EEPROM_PAGE_SIZE))
                  {
                     address -= I2C_EEPROM_PAGE_SIZE;
                  }
                  result = fread (&(memory[address]), 1, 1, fd);
               }

               /* Signal internal programming by NACK on I2C bus */
               if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_DISABLE_DEVICE, NULL))
               {
                  printf ("ERROR: disable device\n");
               }
            
               /* Simulate programming process */
               _time_delay (5);

               /* Programming finished, enable device on the bus again */
               if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_ENABLE_DEVICE, NULL))
               {
                  printf ("ERROR: enable device\n");
               }
               
               /* Wait to be addressed, send ACK, synchronize with master */
               result = fread (&address, 1, 1, fd);
            }
            break;

         case I2C_STATE_TRANSMIT:
         case I2C_STATE_ADDRESSED_AS_SLAVE_TX:
         
            /* Try to send first byte */
            fwrite (&(memory[address]), 1, 1, fd);
            
            /* Wait for transfer complete */
            if (I2C_OK != ioctl (fd, IO_IOCTL_FLUSH_OUTPUT, &nack))
            {
               printf ("ERROR: flush first byte\n");
            }
            
            if (nack)
            {
               /* 1 byte sent */
               address = (address + 1) % I2C_EEPROM_SIZE;
            }
            else
            {
               /* Check if stop condition occurred */
               if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_GET_STATE, &param))
               {
                  printf ("ERROR: get state read address\n");
               }
                
               /* Write data until NACK or STOP */
               while ((0 == nack) && (I2C_STATE_FINISHED != param))
               {
                  /* Send next data */
                  address = (address + 1) % I2C_EEPROM_SIZE;
                  fwrite (&(memory[address]), 1, 1, fd);
                  
                  /* Wait for transfer complete */
                  if (I2C_OK != ioctl (fd, IO_IOCTL_FLUSH_OUTPUT, &nack))
                  {
                     printf ("ERROR: flush data\n");
                  }
                  
                  /* Check if stop condition occurred */
                  if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_GET_STATE, &param))
                  {
                     printf ("ERROR: get state read address\n");
                  }
               }
            }
            
            /* Return to ready state, wait for bus idle */
            if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_STOP, NULL))
            {
               printf ("ERROR: stop tx\n");
            }
            result = 0;
            break;
            
         case I2C_STATE_FINISHED:
         case I2C_STATE_LOST_ARBITRATION:
            
            /* Return to ready state, wait for bus idle */
            if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_STOP, NULL))
            {
               printf ("ERROR: stop lost arbitration\n");
            }
            result = 0;
            break;
            
         default: 
            break;
      }
   }
   
   
   
#else
   
   
   
   /* I2C slave interrupt mode EEPROM emulation */ 
   
   result = 0;
   address = 0;
   while (1)
   {
      /* EEPROM always ACKs incoming bytes */
      param = 0xFFFFFFFF;
      if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_SET_RX_REQUEST, &param))
      {
         printf ("ERROR: set rx request\n");
      }
      
      /* Enable memory dumping when idle */
      dump = TRUE;
      
      do {
         /* Get memory address for read/write operation */
         result = fread (&address, 1, 1, fd);
      
         /* Handle special states */
         if (0 == result)
         {
            if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_GET_STATE, &param))
            {
               printf ("ERROR: get state read address\n");
            }
            if (I2C_STATE_FINISHED == param)
            {
               /* Stop condition detected on the bus, return to ready state */
               if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_STOP, NULL))
               {
                  printf ("ERROR: stop read address\n");
               }
           
               /* EEPROM always ACKs incoming bytes */
               param = 0xFFFFFFFF;
               if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_SET_RX_REQUEST, &param))
               {
                  printf ("ERROR: set rx request read address\n");
               }
            }
            else if ((I2C_STATE_RECEIVE != param) && (I2C_STATE_ADDRESSED_AS_SLAVE_RX != param))
            {
               /* Memory address was omitted, using the last one */
               result = 1;
            }
         }
      } while (0 == result);
    
      /* Temporarily disable memory dump when changing/sending contents */
      dump = FALSE;

      do 
      {
         /* Check next byte */
         result = fread (&(memory[address]), 1, 1, fd);
         
         /* Get required operation */
         if (result)
         {
            param = I2C_STATE_ADDRESSED_AS_SLAVE_RX;
         }
         else
         {
            if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_GET_STATE, &param))
            {
               printf ("ERROR: get required operation\n");
            }
         }
      } while ((0 == result) && (I2C_STATE_ADDRESSED_AS_SLAVE_RX == param));
      
      switch (param)
      {
         case I2C_STATE_RECEIVE:
         case I2C_STATE_ADDRESSED_AS_SLAVE_RX:
         
            if (result)
            {
               /* Receive data, store bytes from given address, loop within page size */
               while (result)
               {
                  address++;
                  if (0 == (address % I2C_EEPROM_PAGE_SIZE))
                  {
                     address -= I2C_EEPROM_PAGE_SIZE;
                  }
                  do {
                     /* Check if there's still anything to read */
                     result = fread (&(memory[address]), 1, 1, fd);
                    
                     /* Check state change */
                     if (result)
                     {
                        param = I2C_STATE_ADDRESSED_AS_SLAVE_RX;
                     }
                     else
                     {
                        if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_GET_STATE, &param))
                        {
                           printf ("ERROR: get required operation\n");
                        }
                     }
                  } while ((0 == result) && (I2C_STATE_ADDRESSED_AS_SLAVE_RX == param));
               }

               /* Signal internal programming by NACK on I2C bus */
               if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_DISABLE_DEVICE, NULL))
               {
                  printf ("ERROR: disable device\n");
               }
            
               /* Simulate programming process */
               _time_delay (5);

               /* Programming finished, enable device on the bus again */
               if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_ENABLE_DEVICE, NULL))
               {
                  printf ("ERROR: enable device\n");
               }
            }
            break;

         case I2C_STATE_TRANSMIT:
         case I2C_STATE_ADDRESSED_AS_SLAVE_TX:

            /* Try to send first byte */
            fwrite (&(memory[address]), 1, 1, fd);
             
            /* Wait for transfer complete */
            if (I2C_OK != ioctl (fd, IO_IOCTL_FLUSH_OUTPUT, &nack))
            {
               printf ("ERROR: flush first byte\n");
            }
            
            if (nack)
            {
               /* 1 byte sent */
               address = (address + 1) % I2C_EEPROM_SIZE;
            }
            else
            {
               /* Check if stop condition occurred */
               if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_GET_STATE, &param))
               {
                  printf ("ERROR: get state read address\n");
               }
                
               /* Write data until NACK or STOP */
               while ((0 == nack) && (I2C_STATE_FINISHED != param))
               {
                  /* Send next byte */
                  address = (address + 1) % I2C_EEPROM_SIZE;
                  fwrite (&(memory[address]), 1, 1, fd);
                  
                  /* Wait for transfer complete */
                  if (I2C_OK != ioctl (fd, IO_IOCTL_FLUSH_OUTPUT, &nack))
                  {
                     printf ("ERROR: flush data\n");
                  }
                  
                  /* Check if stop condition occurred */
                  if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_GET_STATE, &param))
                  {
                     printf ("ERROR: get state read address\n");
                  }
               }
            }
            
            /* Return to ready state, wait for bus idle */
            if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_STOP, NULL))
            {
               printf ("ERROR: stop tx\n");
            }
            break;

         case I2C_STATE_FINISHED:
         case I2C_STATE_LOST_ARBITRATION:

            /* Return to ready state, wait for bus idle */
            if (I2C_OK != ioctl (fd, IO_IOCTL_I2C_STOP, NULL))
            {
               printf ("ERROR: stop finished/lost arbitration\n");
            }
            break;
            
         default: 
            break;
      }
   }
   
#endif



} /* Endbody */
Beispiel #24
0
/*TASK*-----------------------------------------------------
* 
* Task Name    : main_task
* Comments     :
*    This task does nothing
*
*END*-----------------------------------------------------*/
void main_task
   (
      uint_32 initial_data
   )
{
    MQX_FILE_PTR flash_file;
    uint_32 val;
    FLEXNVM_PROG_PART_STRUCT part_param;
    _mqx_int result;
    uint_8 *byte_ptr = (uint_8*) BSP_INTERNAL_FLEXRAM_BASE;
    uint_16 *half_ptr = (uint_16*) BSP_INTERNAL_FLEXRAM_BASE + 1;
    uint_32 *word_ptr = (uint_32*) BSP_INTERNAL_FLEXRAM_BASE + 1;

    _int_install_unexpected_isr();

    printf("\n\nMQX FlexNVM example");
   
    /* Open the flash device */
    flash_file = fopen("flashx:flexram0", NULL);
    if (NULL == flash_file) {
        _task_block();
    }
    
    /* read partition code to check FlexNVM settings */
    result = _io_ioctl(flash_file, FLEXNVM_IOCTL_GET_PARTITION_CODE, &part_param);
    
    if (IO_OK != result) {
        printf("\nError when reading FlexNVM configuration.");
        _task_block();
    }

    /* check FlexNVM partition settings */
    if (FLEXNVM_PART_CODE_NOPART == part_param.FLEXNVM_PART_CODE) {
        printf("\n\nEnabling FlexEEPROM - partition memory.");
        
        /* set FlexNVM partition and EEPROM size */
        part_param.EE_DATA_SIZE_CODE = (FLEXNVM_EE_SPLIT_1_1 | FLEXNVM_EE_SIZE_4096);
        part_param.FLEXNVM_PART_CODE = FLEXNVM_PART_CODE_DATA128_EE128;
        _io_ioctl(flash_file, FLEXNVM_IOCTL_SET_PARTITION_CODE, &part_param);         

        /* switch FlexRAM to EEPROM mode */
        val = FLEXNVM_FLEXRAM_EE;
        _io_ioctl(flash_file, FLEXNVM_IOCTL_SET_FLEXRAM_FN, &val); 
    }
    else
        printf("\nDevice has FlexEEPROM already enabled.");

    printf("\n\nReading actual memory values:\n");
    printf("byte: 0x%p = 0x%x\n", byte_ptr, *byte_ptr);
    printf("half: 0x%p = 0x%x\n", half_ptr, *half_ptr);
    printf("word: 0x%p = 0x%x\n", word_ptr, *word_ptr);
    
    printf("\n\nWriting new values to memory:\n");
    
    /* wait for FlexEEPROM ready */
    _io_ioctl(flash_file, FLEXNVM_IOCTL_WAIT_EERDY, NULL); 
    *byte_ptr += 1;
    
    /* wait for FlexEEPROM ready - after write */
    _io_ioctl(flash_file, FLEXNVM_IOCTL_WAIT_EERDY, NULL); 
    *half_ptr += 2;
    
    /* wait for FlexEEPROM ready - after write */
    _io_ioctl(flash_file, FLEXNVM_IOCTL_WAIT_EERDY, NULL);     
    *word_ptr += 3;
    
    /* wait for FlexEEPROM ready - after write */
    _io_ioctl(flash_file, FLEXNVM_IOCTL_WAIT_EERDY, NULL);     
    
    printf("\n\nReading new memory values:\n");
    printf("byte: 0x%p = 0x%x\n", byte_ptr, *byte_ptr);
    printf("half: 0x%p = 0x%x\n", half_ptr, *half_ptr);
    printf("word: 0x%p = 0x%x\n", word_ptr, *word_ptr);
   
    printf("\nProgram finshed, you can try restart !");

    fclose(flash_file);
    
    _task_block();
}
Beispiel #25
0
/*TASK*-----------------------------------------------------
* 
* Task Name    : flash_task
* Comments     :
*    This task finds a string at 'the end' of flash memory
*    then it tries to rewrite it. The successfull rewrite
*    can be proved by re-executing this example application.
*
*END*-----------------------------------------------------*/
void flash_task
   (
      uint_32 initial_data
   )
{
   MQX_FILE_PTR   flash_file;
   _mqx_int      i, len = 0;
   uint_32        ioctl_param;

   _int_install_unexpected_isr();

   printf("\n\nMQX Flash Example");
   
   /* Open the flash device */
   flash_file = fopen(FLASH_NAME, NULL);
   if (flash_file == NULL) {
      printf("\nUnable to open file %s", FLASH_NAME);
      _task_block();
   } else {
      printf("\nFlash file %s opened", FLASH_NAME);
   }

   /* Get the size of the flash file */
   fseek(flash_file, 0, IO_SEEK_END);
   printf("\nSize of the flash file: 0x%x Bytes", ftell(flash_file));

   /* Disable sector cache */
   ioctl(flash_file, FLASH_IOCTL_ENABLE_SECTOR_CACHE, NULL);
   printf("\nFlash sector cache enabled.");

   /* Move 32B back */
   printf("\nReading last 32 Bytes.");
   fseek(flash_file, -32, IO_SEEK_END);
   
   len = read(flash_file, buffer, 32);
   if (32 != len) {
      printf("\nERROR! Could not read from flash. Exiting...");
      goto example_end;
   }
   for (i = 0; i < 32; i++) {
      if (buffer[i] != (char)0xFF)
         break;
   }
   if (i == 32) {
      printf("\nBytes are blank.");
   }
   else {
      while ((buffer[i] != 0) && (i < 32)) {
         i++;
      }

      if (i == 32) {
         printf("\nFound non-blank data, but not zero-ended string.");
      }
      else {
         printf("\nString found: %s", buffer);
      }
   }

   do {
      printf("\nType a string to be written to the end of file (32 chars max.):");
      fgets(buffer, sizeof(buffer), stdin);
      len = strlen(buffer);
   } while (!len || len > 32);
   
   /* Move 32B back */
   fseek(flash_file, -32, IO_SEEK_END);

   /* Unprotecting the the FLASH might be required */
   ioctl_param = 0;
   ioctl(flash_file, FLASH_IOCTL_WRITE_PROTECT, &ioctl_param);
           
   len = write(flash_file, buffer, 32);
   if (len != 32) {
      printf("\nError writing to the file. Error code: %d", _io_ferror(flash_file));
   }
   else {
      printf("\nData written to the flash.\nNow you can power down and power up your device");
      printf("\nand then retry the test to see if the string was written correctly.");
   }

example_end:
   fclose(flash_file);
   printf("\nFlash example finished.");

   _task_block();    
}
Beispiel #26
0
/*
** Send extended string to socket (dynamic webpages).
**
** IN:
**      HTTPSRV_STRUCT         *server - server structure.
**      HTTPSRV_SESSION_STRUCT *session - session for sending.
**      char                   *str - string to send.
**      uint32_t                length - length of source string.
**
** OUT:
**      none
**
** Return Value:
**      int - number of bytes processed.
*/
static _mqx_int httpsrv_sendextstr(HTTPSRV_STRUCT *server, HTTPSRV_SESSION_STRUCT *session, char *str, uint32_t length)
{
    char *src;
    int len, res;
    int add = 0;
    char fname[HTTPSRVCFG_MAX_SCRIPT_LN + 1];
    uint32_t old_data = session->buffer.offset;
        
    src = str;
    fname[0] = 0;
    
    if (session->response.script_token)
    {
        // script token found
        len = (int)strcspn(src, " ;%<>\r\n\t");

        if (len > 1 && len < HTTPSRVCFG_MAX_SCRIPT_LN)
        {
            HTTPSRV_SCRIPT_MSG* msg_ptr;

            snprintf(fname, len+1, "%s", src);
            /* Form up message for handler task and send it */
            msg_ptr = _msg_alloc(server->script_msg_pool);
            if (msg_ptr != NULL)
            {
                msg_ptr->header.TARGET_QID = server->script_msgq;
                msg_ptr->header.SOURCE_QID = server->script_msgq;
                msg_ptr->header.SIZE = sizeof(HTTPSRV_SCRIPT_MSG);
                msg_ptr->session = session;
                msg_ptr->type = HTTPSRV_SSI_CALLBACK;
                msg_ptr->name = fname;
                msg_ptr->ses_tid = _task_get_id();
                _msgq_send(msg_ptr);
                /* wait until SSI is processed */
                _task_block();
            }
        }

        if (src[len] == '%' && src[len + 1] == '>')
        {
            session->response.script_token = 0;
            len += 1;
        }
        len++;
    }
    else
    {
        for (len = 0; *src && len < length; src++, len++)
        {
            if (src[0] == '<' && src[1] == '%')
            {
                session->response.script_token = 1;
                src += 2;
                add = 2;
                break;
            }
        }
        res = send(session->sock, str, len, 0);
        session->buffer.offset = 0;
        _mem_zero(session->buffer.data, HTTPSRV_SES_BUF_SIZE_PRV);
        if (res < 0)
        {
            session->response.script_token = 0;
#if MQX_USE_IO_OLD
            res = errno;
#else
			res = _task_errno;
#endif
            if (res != EAGAIN)
            {
                len = 0;
            }  
        }
        else if (len != res)
        {
            session->response.script_token = 0;
        }
    }
    return ((len+add)-old_data);
}
Beispiel #27
0
/*!
 * \cond DOXYGEN_PRIVATE
 * \private
 *
 * \brief This is internal function used by a task to wait for a specified event.
 *
 * \param[in] event_ptr          Read only. Pointer to the lightweight event.
 * \param[in] bit_mask           Bit mask. Each set bit represents an event bit
 * to wait for.
 * \param[in] all                TRUE (wait for all bits in bit_mask to be set),
 * FALSE (wait for any bit in bit_mask to be set).
 * \param[in] tick_ptr           Pointer to the maximum number of ticks to wait
 * for the events to be set. If the value is NULL, then the timeout will be infinite.
 * \param[in] ticks_are_absolute TRUE (ticks represents absolute time), FALSE
 * (ticks represents relative time).
 *
 * \return MQX_OK
 * \return LWEVENT_WAIT_TIMEOUT (The time elapsed before an event signalled.)
 * \return MQX_LWEVENT_INVALID (Lightweight event is no longer valid or was never valid.)
 * \return MQX_CANNOT_CALL_FUNCTION_FROM_ISR (Function cannot be called from an ISR.)
 *
 * \see _lwevent_wait_for
 * \see _usr_lwevent_wait_for
 * \see _lwevent_wait_until
 * \see _usr_lwevent_wait_until
 * \see _lwevent_wait_ticks
 * \see _usr_lwevent_wait_ticks
 * \see LWEVENT_STRUCT
 * \see MQX_TICK_STRUCT
 */
_mqx_uint _lwevent_wait_internal
(
    LWEVENT_STRUCT_PTR  event_ptr,
    _mqx_uint           bit_mask,
    bool             all,
    MQX_TICK_STRUCT_PTR tick_ptr,
    bool             ticks_are_absolute
)
{
    KERNEL_DATA_STRUCT_PTR  kernel_data;
    TD_STRUCT_PTR           td_ptr;
    _mqx_uint               result;

    _GET_KERNEL_DATA(kernel_data);

#if MQX_CHECK_ERRORS
    if (kernel_data->IN_ISR)
    {
        return (MQX_CANNOT_CALL_FUNCTION_FROM_ISR);
    } /* Endif */
#endif

    result = MQX_OK;
    td_ptr = kernel_data->ACTIVE_PTR;
    _INT_DISABLE();

#if MQX_CHECK_VALIDITY
    if (event_ptr->VALID != LWEVENT_VALID)
    {
        _int_enable();
        return (MQX_LWEVENT_INVALID);
    } /* Endif */
#endif

    if (    (all &&  (event_ptr->VALUE & bit_mask) == bit_mask)
         || (!all && (event_ptr->VALUE & bit_mask)))
    {
        /* store information about which bits caused task to be unblocked */
        td_ptr->LWEVENT_BITS = event_ptr->VALUE & bit_mask;
        /* clear used automatic events */
        event_ptr->VALUE &= ~(event_ptr->AUTO & bit_mask);

        _INT_ENABLE();
        return (result);
    } /* Endif */

    /* Must wait for a event to become available */

    td_ptr->LWEVENT_BITS = bit_mask;
    if (all)
    {
        td_ptr->FLAGS |= TASK_LWEVENT_ALL_BITS_WANTED;
    }
    else
    {
        td_ptr->FLAGS &= ~TASK_LWEVENT_ALL_BITS_WANTED;
    } /* Endif */

    /* Enqueue at end */
    _QUEUE_ENQUEUE(&event_ptr->WAITING_TASKS, &td_ptr->AUX_QUEUE);

    /* Now put the task to sleep */
    td_ptr->STATE = LWEVENT_BLOCKED;
    td_ptr->INFO = (_mqx_uint) &event_ptr->WAITING_TASKS;
    if (tick_ptr)
    {
        if (ticks_are_absolute)
        {
            _time_delay_until(tick_ptr);
        }
        else
        {
            _time_delay_for(tick_ptr);
        } /* Endif */
        if (td_ptr->INFO)
        {
            /* Must have timed out */
            /*_QUEUE_REMOVE(&event_ptr->WAITING_TASKS, &td_ptr->AUX_QUEUE);*/
            result = LWEVENT_WAIT_TIMEOUT;
        } /* Endif */
    }
    else
    {
        _task_block();
    } /* Endif */

#if MQX_COMPONENT_DESTRUCTION
    if (event_ptr->VALID == 0)
    { /* We've been deleted */
        result = MQX_LWEVENT_INVALID;
    } /* Endif */
#endif

    _INT_ENABLE();
    return (result);
}
Beispiel #28
0
void _io_pcb_mqxa_read_task
   (
      /* [IN] the device info */
      uint_32 parameter
   )
{ /* Body */
   IO_PCB_MQXA_INFO_STRUCT_PTR info_ptr;
   IO_PCB_STRUCT_PTR           pcb_ptr;
   uchar_ptr                   input_ptr;
   uchar_ptr                   input_init_ptr;
   boolean                     got_length = 0;
   _mem_size                   input_length = 0;
   _mem_size                   max_length = 0;
   _mem_size                   count = 0;
   _mqx_uint                   state = 0;
   _mqx_uint                   next_state = 0;
   uchar                       crc0 = 0;
   uchar                       crc1 = 0;
   uchar                       packet_crc0 = 0;
   uchar                       packet_crc1 = 0;
   uchar                       tmp;
   uchar                       c;

   info_ptr = (IO_PCB_MQXA_INFO_STRUCT_PTR)parameter;

   /* Get a PCB */
   pcb_ptr = _io_pcb_alloc(info_ptr->READ_PCB_POOL, FALSE);
#if MQX_CHECK_ERRORS
   if (pcb_ptr == NULL) {
      _task_block();
   } /* Endif */
#endif
   max_length     = info_ptr->INIT.INPUT_MAX_LENGTH;
   input_init_ptr = pcb_ptr->FRAGMENTS[0].FRAGMENT;

   state      = AP_STATE_SYNC; /* Waiting for sync */
   next_state = AP_STATE_SYNC; /* Waiting for sync */

   while (TRUE) {

      if (info_ptr->INIT.IS_POLLED) {
         while (!fstatus(info_ptr->FD)) {
            _time_delay_ticks(1);
         } /* Endwhile */
      } /* Endif */
      c = (uchar)fgetc(info_ptr->FD);

      switch (state) {

         case AP_STATE_SYNC:
            if (c == AP_SYNC) {
               /* Sync detected. Start packet reception. */
               state      = AP_STATE_READING;
               next_state = AP_STATE_SYNC;
               count      = 0;
               input_ptr  = input_init_ptr;
               crc0       = 0x7e;
               crc1       = 0x7e;
               got_length = FALSE;
            } /* Endif */
            break;

         case AP_STATE_SYNC_SKIP:
            if (c != AP_SYNC) {
               /* Single sync detected. Restart message reception. */
               count      = 0;
               input_ptr  = input_init_ptr;
               crc0       = 0x7e;
               crc1       = 0x7e;
               got_length = FALSE;
               *input_ptr++ = c;
               ++count;
               AP_CHECKSUM(c, crc0, crc1);
               state = AP_STATE_READING;
            } else {
               state = next_state;
            } /* Endif */
            break;

         case AP_STATE_READING:
            *input_ptr++ = c;
            ++count;
            AP_CHECKSUM(c, crc0, crc1);

            if (got_length ) {
               if (count >= input_length){
                  state = AP_STATE_CS0;
               } /* Endif */
            } else {
               if ( count > MQXA_MSG_CONTROL_OFFSET) {
                  /* The complete packet header has been read in */
                  input_length = GET_LENGTH(input_init_ptr);
                  if (input_length > max_length) {
                     next_state = AP_STATE_SYNC;
                     ++info_ptr->RX_PACKETS_TOO_LONG;
                  } else {
                     got_length = TRUE;
                     if (count >= input_length) {
                        state = AP_STATE_CS0;
                     } /* Endif */
                 } /* Endif */
               } /* Endif */
            } /* Endif */

            if (c == AP_SYNC) {
               next_state = state;
               state      = AP_STATE_SYNC_SKIP;
            } /* Endif */
            break;

         case AP_STATE_CS0:
            packet_crc0 = c;
            state = AP_STATE_CS1;
            if (c == AP_SYNC) {
               next_state = state;
               state      = AP_STATE_SYNC_SKIP;
            } /* Endif */
            break;

         case AP_STATE_CS1:
            packet_crc1 = c;
            state = AP_STATE_DONE;
            if (c == AP_SYNC) {
               next_state = state;
               state      = AP_STATE_SYNC_SKIP;
            } /* Endif */
            break;

         default:
            state = AP_STATE_SYNC;
            break;

      } /* Endswitch */

      if ( state == AP_STATE_DONE ) {
         /* Calculate the CRCs */
         crc1  = (crc1 + 2 * crc0) & 0xFF;
         tmp   = crc0 - crc1;
         crc1  = (crc1 - (crc0 * 2)) & 0xFF;
         crc0  = tmp & 0xFF;

         if ((crc0 == packet_crc0) && (crc1 == packet_crc1)) {
            ++info_ptr->RX_PACKETS;
            pcb_ptr->FRAGMENTS[0].LENGTH = input_length;
            if (info_ptr->READ_CALLBACK_FUNCTION) {
               /* Start CR 398 */
               (*info_ptr->READ_CALLBACK_FUNCTION)(info_ptr->CALLBACK_FD, pcb_ptr);
               /* End CR */
            } else {
               _queue_enqueue((QUEUE_STRUCT_PTR)&info_ptr->READ_QUEUE,
                  (QUEUE_ELEMENT_STRUCT_PTR)&pcb_ptr->QUEUE);
               _lwsem_post(&info_ptr->READ_LWSEM);
            }/* Endif */
            pcb_ptr = _io_pcb_alloc(info_ptr->READ_PCB_POOL, TRUE);
            /* Start CR 385 */
            if (pcb_ptr == NULL) {
               /* Start CR 399 */
               while (pcb_ptr == NULL) {
                  _time_delay_ticks(2);
                  pcb_ptr = _io_pcb_alloc(info_ptr->READ_PCB_POOL, TRUE);
               } /* Endwhile */
               /* End CR 399 */
            } /* Endif */
            /* End CR 385 */
            input_init_ptr = pcb_ptr->FRAGMENTS[0].FRAGMENT;
         } else {
            ++info_ptr->RX_PACKETS_BAD_CRC;
         } /* Endif */
         state = AP_STATE_SYNC;
      } /* Endif */

   } /* Endwhile */

} /* Endbody */
Beispiel #29
0
int adcc_init(int adc_num)
{
    //PORT_MemMapPtr pctl = NULL;
    //uint8_t gpio_port;

	/* led pin init */
    if(!lwgpio_init(&pm2p5_ledgpio, PM2P5_LED_PWREN, LWGPIO_DIR_OUTPUT, LWGPIO_VALUE_NOCHANGE)) {
        printf("Initializing GPIO with associated pins failed.\n");
        _time_delay (200L);
        _task_block();
    }
    lwgpio_set_functionality(&pm2p5_ledgpio, PM2P5_LED_MUX_GPIO);
    //lwgpio_set_value(&pm2p5_ledgpio, LWGPIO_VALUE_LOW);
    lwgpio_set_value(&pm2p5_ledgpio, LWGPIO_VALUE_HIGH);
    
	if(adc_num == 0) {
		/* SIM_SCGC6: ADC0=1 */
		adc_ptr = ADC0_BASE_PTR;
		SIM_SCGC6 |= SIM_SCGC6_ADC0_MASK;
	}
	else {
		adc_ptr = ADC1_BASE_PTR;
		SIM_SCGC6 |= SIM_SCGC6_ADC1_MASK;
	}

#ifdef ADC_HW_TRIGER
    SIM_SCGC6 |= SIM_SCGC6_PIT_MASK;                 /* enable PIT */

    SIM_SOPT7 |= SIM_SOPT7_ADC1ALTTRGEN_MASK;
    SIM_SOPT7 |= (SIM_SOPT7_ADC1PRETRGSEL_MASK);     /* Pre Trigger B */
    SIM_SOPT7 &= ~(SIM_SOPT7_ADC1TRGSEL_MASK); 
    SIM_SOPT7 |= SIM_SOPT7_ADC1TRGSEL(7);            /* PIT trigger 3 */
    PIT_MCR_REG(PIT_BASE_PTR) = 0;
#endif

	// pin mux config : spec P216 ADC0_DP0/ADC1_DP3 is default
	/* set pin's multiplexer to analog
    gpio_port = ADC_SIG_PORTB | 4;
    pctl = (PORT_MemMapPtr) PORTB_BASE_PTR;
    pctl->PCR[gpio_port & 0x1F] &= ~PORT_PCR_MUX_MASK; 
	*/

    // Initialize ADC0/1 =================================================================================
    //averages (4 h/w)   // bus 60M /8/2 = 3.75M ADC clock
    ADC_CFG1_REG(adc_ptr) = ADLPC_NORMAL | ADC_CFG1_ADIV(ADIV_8) /*| ADLSMP_LONG*/ | ADC_CFG1_MODE(MODE_16)
      | ADC_CFG1_ADICLK(/*ADICLK_BUS_2*/ADICLK_BUS);

    // do calibration
    if(adc_calibrate(adc_ptr))
        printf("adc-%x calibrate failed\n",(int)adc_ptr);

    /* channel A/B selected */
#ifdef ADC_HW_TRIGER
    ADC_CFG2_REG(adc_ptr)  = MUXSEL_ADCB | ADACKEN_ENABLED | ADHSC_HISPEED | ADC_CFG2_ADLSTS(ADLSTS_20);
#else
	ADC_CFG2_REG(adc_ptr)  = MUXSEL_ADCA /*| ADACKEN_ENABLED */| ADHSC_HISPEED | ADC_CFG2_ADLSTS(ADLSTS_20);
#endif
	
    //ADC_CV1_REG(adc_ptr) = 0x0;
    //ADC_CV2_REG(adc_ptr) = 0x0;
        
    //ADC_SC1_REG(adc_ptr,0) =  AIEN_ON | DIFF_SINGLE | ADC_SC1_ADCH(ADC_INPUT_CH);   /* SC1 A */
    //ADC_SC1_REG(adc_ptr,1) =  AIEN_ON | DIFF_SINGLE | ADC_SC1_ADCH(ADC_INPUT_CH);   /* SC1 B */

#ifdef ADC_HW_TRIGER
    ADC_SC2_REG(adc_ptr) = ADTRG_HW /*ADTRG_SW*/ | ACFE_DISABLED | ACFGT_GREATER | ACREN_DISABLED
                     | DMAEN_DISABLED /* DMAEN_ENABLED*/| ADC_SC2_REFSEL(REFSEL_EXT);
#else
    ADC_SC2_REG(adc_ptr) = ADTRG_SW /*| ACFE_DISABLED | ACFGT_GREATER | ACREN_DISABLED
                     | DMAEN_DISABLED*/ | ADC_SC2_REFSEL(REFSEL_EXT);
#endif

    ADC_SC3_REG(adc_ptr) = /*ADC_SC3_CALF_MASK |*/ CAL_OFF | ADCO_SINGLE /*| AVGE_ENABLED | ADC_SC3_AVGS(AVGS_4)*/;  /* averages 4 h/w */
}
/******************************************************************************
*
* Functio Name      : I2C_init_routine
* Comments          : I2C initialization
*
******************************************************************************/
void I2C_init(void)
{
    _mqx_int param;
    I2C_STATISTICS_STRUCT stats;

    /* I2C transaction lock */
    _lwsem_create(&lock, 1);

    /* Open the I2C driver */
    fd_i2c = fopen(I2C_DEVICE_POLLED, NULL);
    if (fd_i2c == NULL)
    {
        printf("ERROR opening the I2C driver!\n");
        _task_block();
    }

    /* Test ioctl commands */
    param = I2C_BAUDRATE;
    if (I2C_OK != ioctl(fd_i2c, IO_IOCTL_I2C_SET_BAUD, &param))
    {
        printf("ERROR set budrate\n");
    }

    if (I2C_OK != ioctl(fd_i2c, IO_IOCTL_I2C_GET_BAUD, &param))
    {
        printf("ERROR get budrate\n");
    }

    if (I2C_OK != ioctl(fd_i2c, IO_IOCTL_I2C_SET_MASTER_MODE, NULL))
    {
        printf("ERROR set mode\n");
    }

    if (I2C_OK != ioctl(fd_i2c, IO_IOCTL_I2C_GET_MODE, &param))
    {
        printf("ERROR get mode\n");
    }

    param = I2C_MCU_BUS_ADDRESS;
    if (I2C_OK != ioctl(fd_i2c, IO_IOCTL_I2C_SET_STATION_ADDRESS, &param))
    {
        printf("ERROR set station address\n");
    }

    param = 0x00;
    if (I2C_OK != ioctl(fd_i2c, IO_IOCTL_I2C_GET_STATION_ADDRESS, &param))
    {
        printf("ERROR get station address\n");
    }

    if (I2C_OK != ioctl(fd_i2c, IO_IOCTL_I2C_CLEAR_STATISTICS, NULL))
    {
        printf("ERROR clear stats\n");
    }

    if (I2C_OK != ioctl(fd_i2c, IO_IOCTL_I2C_GET_STATISTICS, (void *)&stats))
    {
        printf("ERROR get stats\n");
    }

    if (I2C_OK != ioctl(fd_i2c, IO_IOCTL_I2C_GET_STATE, &param))
    {
        printf("ERROR get state\n");
    }

    param = I2C_SENSOR_BUS_ADDRESS;
    if (I2C_OK != ioctl(fd_i2c, IO_IOCTL_I2C_SET_DESTINATION_ADDRESS, &param))
    {
        printf("ERROR set destination address\n");
    }

    param = 0x00;
    if (I2C_OK != ioctl(fd_i2c, IO_IOCTL_I2C_GET_DESTINATION_ADDRESS, &param))
    {
        printf("ERROR get destination address\n");
    }
}