Beispiel #1
0
void redo(void)
{
	char buf[5000];

	// Read the rest of the menu
	ReadUntilString( 0, "-> ", buf, 500);

	// Leave the menu
	SendString(0, "7\n");

	// Read the main menu
	ReadUntilString( 0, "-> ", buf, 500);

	// Enter the pantry menu
	SendString(0, "2\n");

	// Read the pantry menu
	ReadUntilString( 0, "-> ", buf, 500);

	// Delete a pantry
	SendString(0, "2\n");

	// Read all of the pantry list and then the prompt
	ReadUntilString( 0, "128]: ", buf, 5000);

	// Delete the 8th entry
	SendString(0, "7\n");

	/// Read the pantry menu again
	ReadUntilString( 0, "-> ", buf, 500);

	// Create a new pantry
	SendString(0, "1\n");

	// Read the pantry prompt
	ReadUntilString( 0, ": ", buf, 500);

	// Send the name
	SendString(0, "gggg\n");

	// Read the ingredient prompt
	ReadUntilString( 0, ": ", buf, 500);

	// Send blank
	SendString(0, "\n");

	// Read the pantry menu
	ReadUntilString( 0, "-> ", buf, 500);

	// Leave the pantry menu
	SendString(0, "6\n");

	// Read the main menu
	ReadUntilString( 0, "-> ", buf, 500);

	// Enter the recipe menu
	SendString( 0, "1\n");

	// Read the recipe menu
	ReadUntilString( 0, "-> ", buf, 500);

	return;
}
//*****************************************************************************
//
// This is the main loop that runs the application.
//
//*****************************************************************************
int
main(void)
{
    unsigned long ulButton, ulPrevious, ulLastTickCount;
    tBoolean bLastSuspend;

    //
    // Set the clocking to run from the PLL at 50MHz.
    //
    ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // Enable the UART.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
    GPIOPinConfigure(GPIO_PA0_U0RX);
    GPIOPinConfigure(GPIO_PA1_U0TX);
    ROM_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
    UARTStdioInit(0);
    UARTprintf("\033[2JKeyboard device application\n");

    //
    // Enable the GPIO that is used for the on-board push button.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    ROM_GPIOPinTypeGPIOInput(GPIO_PORTB_BASE, GPIO_PIN_4);
    ROM_GPIOPadConfigSet(GPIO_PORTB_BASE, GPIO_PIN_4, GPIO_STRENGTH_2MA,
                         GPIO_PIN_TYPE_STD_WPU);

    //
    // Enable the GPIO that is used for the on-board LED.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    ROM_GPIOPinTypeGPIOOutput(GPIO_PORTD_BASE, GPIO_PIN_0);
    ROM_GPIOPinWrite(GPIO_PORTD_BASE, GPIO_PIN_0, 0);

    //
    // Not configured initially.
    //
    g_bConnected = false;
    g_bSuspended = false;
    bLastSuspend = false;

    //
    // Enable the peripherals used by this example.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);

    //
    // Set the USB stack mode to Device mode with VBUS monitoring.
    //
    USBStackModeSet(0, USB_MODE_DEVICE, 0);

    //
    // Pass our device information to the USB HID device class driver,
    // initialize the USB
    // controller and connect the device to the bus.
    //
    USBDHIDKeyboardInit(0, &g_sKeyboardDevice);

    //
    // Set the system tick to fire 100 times per second.
    //
    ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / SYSTICKS_PER_SECOND);
    ROM_SysTickIntEnable();
    ROM_SysTickEnable();

    //
    // The main loop starts here.  We begin by waiting for a host connection
    // then drop into the main keyboard handling section.  If the host
    // disconnects, we return to the top and wait for a new connection.
    //
    ulPrevious = 1;
    while(1)
    {
        //
        // Tell the user what we are doing and provide some basic instructions.
        //
        UARTprintf("Waiting for host...\n");

        //
        // Wait for USB configuration to complete. 
        //
        while(!g_bConnected)
        {
        }

        //
        // Update the status.
        //
        UARTprintf("Host connected...\n");

        //
        // Enter the idle state.
        //
        g_eKeyboardState = STATE_IDLE;

        //
        // Assume that the bus is not currently suspended if we have just been
        // configured.
        //
        bLastSuspend = false;

        //
        // Keep transfering characters from the UART to the USB host for as
        // long as we are connected to the host.
        //
        while(g_bConnected)
        {
            //
            // Remember the current time.
            //
            ulLastTickCount = g_ulSysTickCount;

            //
            // Has the suspend state changed since last time we checked?
            //
            if(bLastSuspend != g_bSuspended)
            {
                //
                // Yes - the state changed so update the display.
                //
                bLastSuspend = g_bSuspended;
                UARTprintf(bLastSuspend ? "Bus suspended...\n" :
                           "Host connected...\n");
            }

            //
            // See if the button was just pressed.
            //
            ulButton = ROM_GPIOPinRead(GPIO_PORTB_BASE, GPIO_PIN_4);
            if((ulButton == 0) && (ulPrevious != 0))
            {
                //
                // If the bus is suspended then resume it.  Otherwise, type
                // some "random" characters.
                //
                if(g_bSuspended)
                {
                    //
                    // We are suspended so request a remote wakeup.
                    //
                    USBDHIDKeyboardRemoteWakeupRequest(
                                                   (void *)&g_sKeyboardDevice);
                }
                else
                {
                    SendString("Make the Switch to TI Microcontrollers!");
                }
            }
            ulPrevious = ulButton;

            //
            // Wait for at least 1 system tick to have gone by before we poll
            // the buttons again.
            //
            while(g_ulSysTickCount == ulLastTickCount)
            {
                //
                // Hang around doing nothing.
                //
            }
        }

        //
        // Dropping out of the previous loop indicates that the host has
        // disconnected so go back and wait for reconnection.
        //
        if(g_bConnected == false)
        {
            UARTprintf("Host disconnected...\n");
        }
    }
}
void AT_CMD()
{
	SendString("AT+CWMODE=1\r\n");		Delay(5000);	DispOne(10,5,'.',0);
	SendString("AT+RST\r\n");					Delay(5000);	DispOne(11,5,'.',0);
	SendString("AT+CIPMODE=1\r\n");		Delay(5000);	DispOne(12,5,'.',0);
	SendString("AT+CIPMUX=0\r\n");		Delay(5000);	DispOne(13,5,'.',0);
	SendString("AT+CWLAP\r\n");				Delay(5000);	DispOne(14,5,'.',0);
	SendString("AT+CWJAP=\"Route Device Name\",\"PassWord\"\r\n");		Delay(5000);	DispOne(15,5,'.',0);//change to suit your net environment
	SendString("AT+CWJAP?\r\n");			Delay(5000);	DispOne(16,5,'.',0);
	SendString("AT+CIFSR\r\n");				Delay(5000);	DispOne(17,5,'.',0);
	SendString("AT+CIPSTART=\"TCP\",\"*.*.*.*\",Port\r\n");	Delay(5000);	DispOne(18,5,'.',0);//the *.*.*.* is your server address,And don't forget the Port
	SendString("AT+CIPSEND\r\n");			Delay(5000);	DispOne(19,5,'.',0);
	SendString("Acquire Info! From:STC12\r\n");		Delay(5000);	DispOne(20,5,'.',0);
}
Beispiel #4
0
int skapmot(void) {
    struct ShortUser *shortUser;
    int mad, setPermission, changed, ch, i, fidoDomainId, highestId;
    struct FidoDomain *fidoDomain;
    BPTR lock;
    struct User user;
    struct Mote tmpConf,*searchConf,*newConf;

    memset(&tmpConf, 0, sizeof(struct Mote));
    if(argument[0] == '\0') {
        SendString("\r\n\nNamn på mötet: ");
        if(GetString(40,NULL)) {
            return 1;
        }
        strcpy(tmpConf.namn, inmat);
    } else {
        strcpy(tmpConf.namn, argument);
    }
    if(parsemot(tmpConf.namn) != -1) {
        SendString("\r\n\nFinns redan ett sådant möte!\r\n");
        return 0;
    }
    tmpConf.skapat_tid = time(NULL);;
    tmpConf.skapat_av = inloggad;
    for(;;) {
        SendString("\r\nMötesAdministratör (MAD) : ");
        if(GetString(5,NULL)) {
            return 1;
        }
        if(inmat[0]) {
            if((mad = parsenamn(inmat)) == -1) {
                SendString("\r\nFinns ingen sådan användare!");
            } else {
                tmpConf.mad = mad;
                break;
            }
        }
    }
    SendString("\n\rSorteringsvärde: ");
    tmpConf.sortpri = GetNumber(0, LONG_MAX, NULL);

    if(EditBitFlagShort("\r\nSka mötet vara slutet?", 'j', 'n', "Slutet", "Öppet",
                        &tmpConf.status, SLUTET)) {
        return 1;
    }
    if(tmpConf.status & SLUTET) {
        SendString("\r\nVilka grupper ska ha tillgång till mötet? (? för lista)\r\n");
        if(editgrupp((char *)&tmpConf.grupper)) {
            return 1;
        }
    }
    if(EditBitFlagShort("\r\nSka mötet vara skrivskyddat?", 'j', 'n',
                        "Skyddat", "Oskyddat", &tmpConf.status, SKRIVSKYDD)) {
        return 1;
    }
    if(EditBitFlagShort("\r\nSka mötet vara kommentarsskyddat?", 'j', 'n',
                        "Skyddat", "Oskyddat", &tmpConf.status, KOMSKYDD)) {
        return 1;
    }
    if(EditBitFlagShort("\r\nSka mötet vara hemligt?", 'j', 'n',
                        "Hemligt", "Ej hemligt", &tmpConf.status, HEMLIGT)) {
        return 1;
    }
    if(!(tmpConf.status & SLUTET)) {
        if(EditBitFlagShort("\r\nSka alla användare bli medlemmar automagiskt?", 'j', 'n',
                            "Ja", "Nej", &tmpConf.status, AUTOMEDLEM)) {
            return 1;
        }
        if(EditBitFlagShort("\r\nSka rättigheterna styra skrivmöjlighet?", 'j', 'n',
                            "Ja", "Nej", &tmpConf.status, SKRIVSTYRT)) {
            return 1;
        }
        if(tmpConf.status & SKRIVSTYRT) {
            SendString("\r\nVilka grupper ska ha tillgång till mötet? (? för lista)\r\n");
            if(editgrupp((char *)&tmpConf.grupper)) {
                return 1;
            }
        }
    }
    if(EditBitFlagShort("\r\nSka mötet enbart kommas åt från ARexx?", 'j', 'n',
                        "Ja", "Nej", &tmpConf.status, SUPERHEMLIGT)) {
        return 1;
    }

    SendString("\n\n\rVilken typ av möte ska det vara?\n\r");
    SendString("1: Lokalt möte\n\r");
    SendString("2: Fido-möte\n\n\r");
    SendString("Val: ");
    for(;;) {
        ch = GetChar();
        if(ch == GETCHAR_LOGOUT) {
            return 1;
        }
        if(ch == '1' || ch == '2') {
            break;
        }
    }
    if(ch == '1') {
        SendString("Lokalt möte\n\n\r");
        tmpConf.type = MOTE_ORGINAL;
    } else {
        SendString("Fido-möte\n\n\r");
        tmpConf.type = MOTE_FIDO;
        if(EditString("Katalog for .msg-filerna", tmpConf.dir, 79, TRUE)) {
            return 1;
        }
        if(!(lock = Lock(tmpConf.dir, SHARED_LOCK))) {
            if(!(lock = CreateDir(tmpConf.dir)))
                SendString("\n\rKunde inte skapa katalogen\n\r");
        }
        if(lock) {
            UnLock(lock);
        }
        if(EditString("FidoNet tag-namn", tmpConf.tagnamn, 49, TRUE)) {
            return 1;
        }
        strcpy(tmpConf.origin, Servermem->fidodata.defaultorigin);
        if(MaybeEditString("Origin-rad", tmpConf.origin, 69)) {
            return 1;
        }

        SendString("\n\n\rVilken teckenuppsättning ska användas för utgående texter?\n\r");
        SendString("1: ISO Latin 1 (ISO 8859-1)\n\r");
        SendString("2: SIS-7 (SF7, 'Måsvingar')\n\r");
        SendString("3: IBM CodePage\n\r");
        SendString("4: Mac\n\n\r");
        SendString("Val: ");
        for(;;) {
            ch = GetChar();
            if(ch == GETCHAR_LOGOUT) {
                return 1;
            }
            if(ch == '1' || ch == '2' || ch == '3' || ch == '4') {
                break;
            }
        }
        switch(ch) {
        case '1':
            SendString("ISO Latin 1\n\n\r");
            tmpConf.charset = CHRS_LATIN1;
            break;
        case '2':
            SendString("SIS-7\n\n\r");
            tmpConf.charset = CHRS_SIS7;
            break;
        case '3':
            SendString("IBM CodePage\n\n\r");
            tmpConf.charset = CHRS_CP437;
            break;
        case '4':
            SendString("Mac\n\n\r");
            tmpConf.charset = CHRS_MAC;
            break;
        }
        SendString("Vilken domän är mötet i?\n\r");
        highestId = 0;
        for(i = 0; i < 10; i++) {
            if(!Servermem->fidodata.fd[i].domain[0]) {
                break;
            }
            highestId = max(highestId, Servermem->fidodata.fd[i].nummer);
            SendString("%3d: %s (%d:%d/%d.%d)\n\r",
                       Servermem->fidodata.fd[i].nummer,
                       Servermem->fidodata.fd[i].domain,
                       Servermem->fidodata.fd[i].zone,
                       Servermem->fidodata.fd[i].net,
                       Servermem->fidodata.fd[i].node,
                       Servermem->fidodata.fd[i].point);
        }
        if(i == 0) {
            SendString("\n\rDu måste definiera en domän i NiKomFido.cfg först!\n\r");
            return 0;
        }
        for(;;) {
            SendString("\r\nDomän: ");
            if(GetString(5, NULL)) {
                return 1;
            }
            fidoDomainId = atoi(inmat);
            if(fidoDomain = getfidodomain(fidoDomainId, 0)) {
                break;
            } else {
                SendString("\n\rFinns ingen sådan domän.\n\r");
            }
        }
        tmpConf.domain = fidoDomain->nummer;
        SendString("%s\n\n\r", fidoDomain->domain);
    }
    for(i = 0; i < MAXMOTE; i++) {
        if(getmotpek(i) == NULL) {
            break;
        }
    }
    if(i >= MAXMOTE) {
        SendString("\n\n\rDet finns inte plats för fler möten.\n\r");
        return 0;
    }
    tmpConf.nummer = i;
    if(!(newConf = (struct Mote *)AllocMem(sizeof(struct Mote),
                                           MEMF_CLEAR | MEMF_PUBLIC))) {
        LogEvent(SYSTEM_LOG, ERROR, "Could not allocate %d bytes.", sizeof(struct Mote));
        DisplayInternalError();
        return 0;
    }
    memcpy(newConf, &tmpConf, sizeof(struct Mote));
    ITER_EL(searchConf, Servermem->mot_list, mot_node, struct Mote *) {
        if(searchConf->sortpri > newConf->sortpri) {
            break;
        }
    }

    searchConf = (struct Mote *)searchConf->mot_node.mln_Pred;
    Insert((struct List *)&Servermem->mot_list, (struct Node *)newConf,
           (struct Node *)searchConf);
    writemeet(newConf);

    if((newConf->status & AUTOMEDLEM) && !(newConf->status & SKRIVSTYRT)) {
        return 0;
    }
    if(newConf->status & SUPERHEMLIGT) {
        return 0;
    }

    setPermission = (newConf->status & (SLUTET | SKRIVSTYRT)) ? FALSE : TRUE;
    for(i = 0; i < MAXNOD; i++) {
        BAMCLEAR(Servermem->inne[i].motmed, newConf->nummer);
        if(setPermission) {
            BAMSET(Servermem->inne[i].motratt, newConf->nummer);
        } else {
            BAMCLEAR(Servermem->inne[i].motratt, newConf->nummer);
        }
    }

    SendString("\r\nÄndrar i användardata..\r\n");
    ITER_EL(shortUser, Servermem->user_list, user_node, struct ShortUser *) {
        if(!(shortUser->nummer % 10)) {
            SendString("\r%d", shortUser->nummer);
        }
        if(readuser(shortUser->nummer, &user)) {
            LogEvent(SYSTEM_LOG, ERROR, "Could not read user %d to set "
                     "membership/permissions for new conference.", shortUser->nummer);
            DisplayInternalError();
            return 0;
        }
        changed = FALSE;
        if(setPermission != BAMTEST(user.motratt, newConf->nummer)) {
            if(setPermission) {
                BAMSET(user.motratt, newConf->nummer);
            } else {
                BAMCLEAR(user.motratt, newConf->nummer);
            }
            changed = TRUE;
        }
        if(!(newConf->status & AUTOMEDLEM) && BAMTEST(user.motmed, newConf->nummer)) {
            BAMCLEAR(user.motmed, newConf->nummer);
            changed = TRUE;
        }
        if(changed && writeuser(shortUser->nummer, &user)) {
            LogEvent(SYSTEM_LOG, ERROR, "Could not write user %d to set "
                     "membership/permissions for new conference.", shortUser->nummer);
            DisplayInternalError();
            return 0;
        }

    }
    for(i = 0; i < MAXNOD; i++) {
        BAMCLEAR(Servermem->inne[i].motmed, newConf->nummer);
        if(setPermission) {
            BAMSET(Servermem->inne[i].motratt, newConf->nummer);
        } else {
            BAMCLEAR(Servermem->inne[i].motratt, newConf->nummer);
        }
    }
    BAMSET(Servermem->inne[nodnr].motratt, newConf->nummer);
    BAMSET(Servermem->inne[nodnr].motmed, newConf->nummer);
    if(newConf->type == MOTE_FIDO) {
        ReScanFidoConf(newConf, 0);
    }
    return 0;
}
Beispiel #5
0
int parse(char *str) {
    int argType, timeSinceFirstLogin;
    char *arg2 = NULL, *word2;
    struct Kommando *cmd, *foundCmd = NULL;
    struct LangCommand *langCmd;

    timeSinceFirstLogin = time(NULL) - Servermem->inne[nodnr].forst_in;
    if(str[0] == 0) {
        return -3;
    }
    if(str[0] >= '0' && str[0] <= '9') {
        argument = str;
        return 212;
    }

    arg2 = FindNextWord(str);
    if(IzDigit(arg2[0])) {
        argType = KOMARGNUM;
    } else if(!arg2[0]) {
        argType = KOMARGINGET;
    } else {
        argType = KOMARGCHAR;
    }

    ITER_EL(cmd, Servermem->kom_list, kom_node, struct Kommando *) {
        if(cmd->secret) {
            if(cmd->status > Servermem->inne[nodnr].status) continue;
            if(cmd->minlogg > Servermem->inne[nodnr].loggin) continue;
            if(cmd->mindays * 86400 > timeSinceFirstLogin) continue;
            if(cmd->grupper && !(cmd->grupper & Servermem->inne[nodnr].grupper)) continue;
        }
        langCmd = chooseLangCommand(cmd);
        if(langCmd->name[0] && matchar(str, langCmd->name)) {
            word2 = FindNextWord(langCmd->name);
            if((langCmd->words == 2 && matchar(arg2, word2) && arg2[0]) || langCmd->words == 1) {
                if(langCmd->words == 1) {
                    if(cmd->argument == KOMARGNUM && argType == KOMARGCHAR) continue;
                    if(cmd->argument == KOMARGINGET && argType != KOMARGINGET) continue;
                }
                if(foundCmd == NULL) {
                    foundCmd = cmd;
                }
                else if(foundCmd == (struct Kommando *)1L) {
                    SendString("%s\n\r", chooseLangCommand(cmd)->name);
                } else {
                    SendString("\r\n\n%s\r\n\n", CATSTR(MSG_KOM_AMBIGOUS_COMMAND));
                    SendString("%s\n\r", chooseLangCommand(foundCmd)->name);
                    SendString("%s\n\r", chooseLangCommand(cmd)->name);
                    foundCmd = (struct Kommando *)1L;
                }
            }
        }
    }
    if(foundCmd != NULL && foundCmd != (struct Kommando *)1L) {
        argument = FindNextWord(str);
        if(chooseLangCommand(foundCmd)->words == 2) {
            argument = FindNextWord(argument);
        }
        memset(argbuf, 0, 1080);
        strncpy(argbuf, argument, 1080);
        argbuf[strlen(argument)] = 0;
        argument = argbuf;
    }
    if(foundCmd == NULL) {
        return -1;
    }
    else if(foundCmd == (struct Kommando *)1L) {
        return -2;
    } else {
        if(foundCmd->status > Servermem->inne[nodnr].status || foundCmd->minlogg > Servermem->inne[nodnr].loggin) {
            return -4;
        }
        if(foundCmd->mindays * 86400 > timeSinceFirstLogin) {
            return -4;
        }
        if(foundCmd->grupper && !(foundCmd->grupper & Servermem->inne[nodnr].grupper)) {
            return -4;
        }
    }
    if(foundCmd->losen[0]) {
        SendString("\r\n\n%s: ", CATSTR(MSG_KOM_COMMAND_PASSWORD));
        if(Servermem->inne[nodnr].flaggor & STAREKOFLAG) {
            getstring(STAREKO,20,NULL);
        } else {
            getstring(EJEKO,20,NULL);
        }
        if(strcmp(foundCmd->losen, inmat)) {
            return -5;
        }
    }
    return foundCmd->nummer;
}
Beispiel #6
0
void printAccel(int* accelData) {
	mini_snprintf(str,100,"%d %d %d\n",accelData[0],accelData[1],accelData[2]);
	SendString(str);
}
Beispiel #7
0
// 发送设置文本内容消息,文本填入当前获得焦点的控件
void CMsgHelper::SM_Text(HWND hMainWnd, char* text)
{
    ::SetForegroundWindow(hMainWnd);
    SendString(text);
}
/**
  * @brief  Execute the demo application.
  * @param  None
  * @retval None
  */
static void Demo_Exec(void)
{
  RCC_ClocksTypeDef RCC_Clocks;
  
  /* 串口配置 */
  USART1_Config();
  NVIC_Config();
  
  /* Initialize LEDs to be managed by GPIO */
  STM_EVAL_LEDInit(LED4);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED5);
  STM_EVAL_LEDInit(LED6);
  
  //每次系统初始化后,都读取flash查看存储空间剩余情况
  flash_readIndex(IndexList,uniIndexLength, &IndexCount);
  
  while(1)
  {
    DemoEnterCondition = 0x00;
    
    /* Reset UserButton_Pressed variable */
    UserButtonPressed = 0x00;
//    SerialButtonPressed = 0x00;
    
    /* SysTick end of count event each 2.5ms */
    RCC_GetClocksFreq(&RCC_Clocks);
    SysTick_Config(RCC_Clocks.HCLK_Frequency / TimeDev);
    
    

    /******************************************/
    /***空闲状态,清空flash或者发送数据选项****/
    /******************************************/
    /* Waiting User Button is pressed */
    while (UserButtonPressed == 0x00)
    {
      /********通过串口与上位机通信*******************/
      /* if Send serial data Button(PB11) is pressed */
      if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11) == Bit_SET)//不太灵敏
      {
        while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11) == Bit_SET);
        
        /*串口通信状态指示灯*/
        STM_EVAL_LEDOn(LED4);
        STM_EVAL_LEDOn(LED3);
        STM_EVAL_LEDOn(LED5);
        STM_EVAL_LEDOn(LED6);
        
        //读取flash中index区域
        flash_readIndex(IndexList,uniIndexLength, &IndexCount);
        
        
        //与上位机握手操作
        unsigned char* shakeHandSend = "ready? ";//最后一个字符必须是空格字符
        while (*shakeHandSend != ' ')
        {
          SendChar(*shakeHandSend);
          shakeHandSend++;
        }
        
        Delay(100);//等待1s确认接收自上位机的握手信号"ok!"
        if (serialRecv[0] == 'o'&&serialRecv[1] == 'k'&&serialRecv[2] == '!')
        {
          //与上位机握手成功,可发送数据
          serialFlag = 1;
        }
        else
        {
          //与上位机握手失败,无法发送数据
          serialFlag = 0;
          
          /*串口握手失败指示灯*/
          STM_EVAL_LEDOff(LED4);
          Delay(10);
          STM_EVAL_LEDOff(LED3);
          Delay(10);
          STM_EVAL_LEDOff(LED5);
          Delay(10);
          STM_EVAL_LEDOff(LED6);
          Delay(100);
        }
        
        
        if (1 == serialFlag)
        {
          //先发送IndexList数据给上位机,上位机选择需要的记录段(segment)反馈给下位机,下位机据此发送相应记录段给上位机
          uint8_t i;
          unsigned char sendData[4];
          
          SendString("index");
          SendCounter = 0;
          while(SendCounter < IndexCount)
          {
            uint32_to_uint8(sendData,IndexList[SendCounter]);
            i = 0;
            while(i < 4)
            {
              SendChar((unsigned char)sendData[i]);
              i+= 1 ;
            }
            SendCounter += 1;
          }
          
          
          /*开始发送segment数据给上位机*/
          
          while(serialRecv[0] == 'o');//等待确认接收自上位机的选择信号"0"——"6"
          Delay(2);//等待20ms后开始发送data,实现收发同步
          
          if (serialRecv[0] == '0'||serialRecv[0] == '1'||serialRecv[0] == '2'||serialRecv[0] == '3'||serialRecv[0] == '4'||serialRecv[0] == '5'||serialRecv[0] == '6')
          {
            tempCount = IndexList[(serialRecv[0]-48)*uniIndexLength+2];
            tempCount2 = 0;
            //读取flash user data area中对应数据
            while (tempCount > lowerComputerBufferNum)
            {
              
              flash_readData(SendData,lowerComputerBufferNum, tempCount2*lowerComputerBufferNum, IndexList[(serialRecv[0]-48)*uniIndexLength]);
              SendCounter = 0;
              while(SendCounter < lowerComputerBufferNum)
              {
                SendChar((unsigned char)SendData[SendCounter]);
                SendCounter += 1 ;
              }
              tempCount -= lowerComputerBufferNum;
              tempCount2 += 1;
              Delay(9);//延时9ms以便上位机有时间处理缓冲区(上位机缓冲区大小同下位机) 
            }
            
            if (tempCount != 0)
            {
               flash_readData(SendData,tempCount, tempCount2*lowerComputerBufferNum, IndexList[(serialRecv[0]-48)*uniIndexLength]);
               SendCounter = 0;
               while(SendCounter < tempCount)
               {
                  SendChar((unsigned char)SendData[SendCounter]);
                  SendCounter += 1 ;
               } 
            }
          }
          
          /*选择是否擦除对应segment和index*/
          //接收自上位机的删除信号 'Y' for 删除,'N' for 不删除
          if(serialRecv[1] == 'Y')
          {
             //uint32_t tempIndexList[uniIndexLength*7];
             flash_init_sector(IndexList[(serialRecv[0]-48)*uniIndexLength]);//擦除该index所对应flash user data area区域
             flash_init_sector(((uint32_t)0x08010000));//先擦除Index区域(sector 4)
             i = 0;
             uint8_t k = 0;
             while(i < IndexCount)
             {
               if (i != (serialRecv[0]-48)*uniIndexLength)
               {
                  IndexList[k] = IndexList[i];
                  IndexList[k+1] = IndexList[i+1];
                  IndexList[k+2] = IndexList[i+2];
                  k += uniIndexLength;
               }
               i += uniIndexLength;
             }
             flash_writeIndex(IndexList,IndexCount-uniIndexLength);//后重写该条index记录
             IndexCount -= 3;
          }
          
        }
      }
      
      /********************清空flash********************************/
      /* if Button(PB12) is pressed, flash user area will be erased*/
      if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_12) == Bit_SET)
      {
        /*waiting Button(PB12) being released*/
        while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_12) == Bit_SET);
        
        /* flash初始化 */
        flash_init();
        IndexCount = 0;
        /*灯全闪烁后全灭,指示flash中用户数据被擦除*/
         STM_EVAL_LEDToggle(LED4);
         STM_EVAL_LEDToggle(LED3);
         STM_EVAL_LEDToggle(LED5);
         STM_EVAL_LEDToggle(LED6);
         Delay(10);
         STM_EVAL_LEDOff(LED4);
         STM_EVAL_LEDOff(LED3);
         STM_EVAL_LEDOff(LED5);
         STM_EVAL_LEDOff(LED6);
         Delay(100);
      }
      
      /* Toggle LED4 */
      STM_EVAL_LEDToggle(LED6);
      Delay(50);
      //LED4 3 5用于二进制编码指示flash存储区占用个数
      if((IndexCount/uniIndexLength)&(0x01))//最低位
      { 
        STM_EVAL_LEDOn(LED5);
      }
      else
      {
         STM_EVAL_LEDOff(LED5);
      }
      if((IndexCount/uniIndexLength)&(0x02))
      { 
        STM_EVAL_LEDOn(LED3);
      }
      else
      {
         STM_EVAL_LEDOff(LED3);
      }
      if((IndexCount/uniIndexLength)&(0x04))//最高位
      { 
        STM_EVAL_LEDOn(LED4);
      }
      else
      {
         STM_EVAL_LEDOff(LED4);
      }
    }
    
    /* Waiting User Button is Released */
    while (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)
    {}
    
    
    
    /******************************************/
    /***退出空闲状态,采样状态配置初始化*******/
    /******************************************/
    STM_EVAL_LEDOn(LED4);
    STM_EVAL_LEDOff(LED4);
    Delay(10);
    STM_EVAL_LEDOn(LED3);
    STM_EVAL_LEDOff(LED3);
    Delay(10);
    STM_EVAL_LEDOn(LED5);
    STM_EVAL_LEDOff(LED5);
    Delay(10);
    STM_EVAL_LEDOn(LED6);
    STM_EVAL_LEDOff(LED6);
    Delay(10);
    
    
    
    
    /*各段记录相互独立的标志位均清零*/
    Counter = 0;//分组采用计数器复位
    DataWriteErrorFlag = 0;//flash写入错误标志位复位
    NoWrittenFlag = 0;//未写入标志位复位
    WritingSectorFlag = 0;//正在写入sector标志位复位
    totalDataNumber = 0;//各段记录数据个数计数器复位
    
    
    UserButtonPressed = 0x00;

    
    /* MEMS configuration */
    LIS302DL_InitStruct.Power_Mode = LIS302DL_LOWPOWERMODE_ACTIVE;
    LIS302DL_InitStruct.Output_DataRate = LIS302DL_DATARATE_400;//加速度传感器采用率400HZ
    LIS302DL_InitStruct.Axes_Enable = LIS302DL_XYZ_ENABLE;
    LIS302DL_InitStruct.Full_Scale = LIS302DL_FULLSCALE_2_3;//18 mg/digit
    LIS302DL_InitStruct.Self_Test = LIS302DL_SELFTEST_NORMAL;
    LIS302DL_Init(&LIS302DL_InitStruct);
    
    /* Required delay for the MEMS Accelerometre: Turn-on time = 3/Output data Rate 
    = 3/400 = 7.5ms */
    Delay(1);
    
    /* MEMS High Pass Filter configuration */
    LIS302DL_FilterStruct.HighPassFilter_Data_Selection = LIS302DL_FILTEREDDATASELECTION_OUTPUTREGISTER;
    LIS302DL_FilterStruct.HighPassFilter_CutOff_Frequency = LIS302DL_HIGHPASSFILTER_LEVEL_1;
    LIS302DL_FilterStruct.HighPassFilter_Interrupt = LIS302DL_HIGHPASSFILTERINTERRUPT_1_2;
    LIS302DL_FilterConfig(&LIS302DL_FilterStruct);
    
    LIS302DL_Read(Buffer, LIS302DL_OUT_X_ADDR, 6);
    X_Offset = Buffer[0];
    Y_Offset = Buffer[2];
    Z_Offset = Buffer[4];
  
    
    
    /******************************************/
    /***********开始进入采样模式,写入flash****/
    /******************************************/
    DemoEnterCondition = 0x01;
    /* Waiting User Button is pressed */
    while (UserButtonPressed == 0x00) //利用采样间隙写入缓冲器内数据,提高效率
    {
      if((0 == Counter)&&(1 == NoWrittenFlag)&&(0 == DataWriteErrorFlag))
      {
        if (WritingSectorFlag == 0)
        {
          writingDataAddr = getFreeDataStartAddr();
          if (writingDataAddr == 0)
          {
            NoFreeSectors = 1;//无空闲sector块置位
            NoWrittenFlag = 0;
            
            /* 指示灯全亮,指示存储空间已满 */
            STM_EVAL_LEDOn(LED4);
            STM_EVAL_LEDOn(LED3);
            STM_EVAL_LEDOn(LED5);
            STM_EVAL_LEDOn(LED6);
            break;//退出采样模式
          }
          else
          {
            //一次完整flash写入
            flash_init_sector(writingDataAddr);//保险起见,先擦除该空闲sector块
            DataWriteErrorFlag = flash_writeData(Total_Buffer, Total_Buffer_Number,writingDataAddr);
            NoWrittenFlag = 0;//表示已写入(flash)
            WritingSectorFlag = 1;//正在写入sector标志位置位,表示启用该块sector
          }
        }
        else
        {
          //flash写入
          DataWriteErrorFlag = flash_writeData(Total_Buffer, Total_Buffer_Number,writingDataAddr);
          NoWrittenFlag = 0;//表示已写入(flash)
        }
      }
      if(DataWriteErrorFlag != 0)
      {
        flash_init_sector(writingDataAddr);//flash写入错误后,擦除相应存储空间,退出采样状态
        WritingSectorFlag = 0;//归还对该块存储空间的使用权
        
        /* 指示灯全亮后全灭,指示进入采样状态 */
        STM_EVAL_LEDOn(LED4);
        STM_EVAL_LEDOn(LED3);
        STM_EVAL_LEDOn(LED5);
        STM_EVAL_LEDOn(LED6);
        Delay(100);
        STM_EVAL_LEDOff(LED4);
        STM_EVAL_LEDOff(LED3);
        STM_EVAL_LEDOff(LED5);
        STM_EVAL_LEDOff(LED6);
        Delay(100);
        break;
      }
      
      /* 指示灯全灭,指示进入采样状态 */
      STM_EVAL_LEDOff(LED4);
      STM_EVAL_LEDOff(LED4);
      STM_EVAL_LEDOff(LED3);
      STM_EVAL_LEDOff(LED5);
      STM_EVAL_LEDOff(LED6);
    }
    
    /* Waiting User Button is Released */
    while (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)
    {}
    
   
    
    /******************************************/
    /***********退出采样模式,做善后处理*******/
    /******************************************/
    DemoEnterCondition = 0x00;//防止此时进入采样模式
    
    /*如果退出采样模式时尚有数据未写入flash,在此一并写入flash*/
    if(1 == NoWrittenFlag)  flash_writeData(Total_Buffer, Counter,writingDataAddr);
    
    if ((0 == NoFreeSectors)&&(1 == WritingSectorFlag))
    {
      /* 指示灯全灭后全亮,指示进入数据善后状态 */
      STM_EVAL_LEDOff(LED4);
      STM_EVAL_LEDOff(LED3);
      STM_EVAL_LEDOff(LED5);
      STM_EVAL_LEDOff(LED6);
      Delay(10);
      STM_EVAL_LEDOn(LED4);
      STM_EVAL_LEDOn(LED3);
      STM_EVAL_LEDOn(LED5);
      STM_EVAL_LEDOn(LED6);
      Delay(10);
      
      /*至此,一条“完整”记录写入flash完毕,需要在flash中建立关于这条记录的索引index*/    
      flash_readIndex(IndexList,uniIndexLength, &IndexCount);//从flash中读取原IndexList
      IndexList[IndexCount] = writingDataAddr;//写入最新的数据地址块首地址
      srand((int)time(0));
      IndexList[IndexCount+1] = rand()%100;//写入最新的记录名
      IndexList[IndexCount+2] = totalDataNumber;//写入最新的段记录总个数
      flash_init_sector(((uint32_t)0x08010000));//先擦除Index区域(sector 4)
      flash_writeIndex(IndexList,IndexCount+3);//后写入
      IndexCount += 3;
    }
         
    /* Disable SPI1 used to drive the MEMS accelerometre */
    SPI_Cmd(LIS302DL_SPI, DISABLE);  
  }
}
Beispiel #9
0
int main(void) {

    int accelData[3];
    int analogIn = 0;

    /* Initialize system */
    SystemInit();

    /* Initialize delay */
    TM_DELAY_Init();

    /* Initialize PG13 (GREEN LED) and PG14 (RED LED) */
    TM_GPIO_Init(GPIOG, GPIO_PIN_13 | GPIO_PIN_14, TM_GPIO_Mode_OUT, TM_GPIO_OType_PP, TM_GPIO_PuPd_NOPULL, TM_GPIO_Speed_Fast);
    TM_GPIO_SetPinValue(GPIOG, GPIO_PIN_14, 1); // Red: ON

#ifdef ENABLE_USART
    /* Initialize USART1 at 115200 baud, TX: PA10, RX: PA9 */
    TM_USART_Init(USART1, TM_USART_PinsPack_1, 115200);
#endif

#ifdef ENABLE_VCP
    /* Initialize USB Virtual Comm Port */

    TM_USB_VCP_Result status = TM_USB_VCP_NOT_CONNECTED;
    while (TM_USB_VCP_GetStatus() != TM_USB_VCP_CONNECTED) {
    	TM_USB_VCP_Init();
    	TM_GPIO_TogglePinValue(GPIOG, GPIO_PIN_14);
    	Delay(500000);
    }
    SendString("USB VCP initialized and connected\n");
    TM_GPIO_TogglePinValue(GPIOG, GPIO_PIN_14 | GPIO_PIN_13); // Red: OFF, Gr: ON

#endif

#ifdef ENABLE_MMA

    /* Initialize MMA845X */
    uint8_t mma_status = MMA845X_Initialize(MMA_RANGE_4G);
    if (mma_status == MMA_OK) {
    	SendString("MMA initialized\n");
    } else {
    	SendString("MMA initialization failed, error code: ");
    	// Add 48 to the byte value to have character representation, (48 = '0')
    	SendChar('0'+mma_status);
    	SendChar('\n');
    }

#endif

    /* Initialize Display */
	TM_ILI9341_Init();
	TM_ILI9341_Rotate(TM_ILI9341_Orientation_Portrait_1);
	TM_ILI9341_SetLayer1();
	TM_ILI9341_Fill(ILI9341_COLOR_BLACK); /* Fill data on layer 1 */

	/* Initialize ADC1 */
	TM_ADC_Init(CURRENT_ADC, CURRENT_CH);

	/* Initialize PE2 and PE3 for digital output (Motor direction) */
    TM_GPIO_Init(GPIOE, GPIO_PIN_2 | GPIO_PIN_3, TM_GPIO_Mode_OUT, TM_GPIO_OType_PP, TM_GPIO_PuPd_NOPULL, TM_GPIO_Speed_Fast);
    // Set them to HIGH/LOW
    TM_GPIO_SetPinHigh(GPIOE, GPIO_PIN_3);
    TM_GPIO_SetPinLow(GPIOE, GPIO_PIN_2);

    /* Set up PE5 (in front of PE4) for PWM (TIM9 CH1 PP2) (Motor speed control) */
    TM_PWM_TIM_t TIM9_Data;
    // Set PWM to 1kHz frequency on timer TIM4, 1 kHz = 1ms = 1000us
	TM_PWM_InitTimer(TIM9, &TIM9_Data, 1000);
	// Initialize PWM on TIM9, Channel 1 and PinsPack 2 = PE5
	TM_PWM_InitChannel(&TIM9_Data, TM_PWM_Channel_1, TM_PWM_PinsPack_2);
	// Set channel 1 value, 50% duty cycle
	TM_PWM_SetChannelPercent(&TIM9_Data, TM_PWM_Channel_1, 50);

	/* Initialize DAC channel 2, pin PA5 (Shaker control) */
	//TM_DAC_Init(TM_DAC2);
	/* Set 12bit analog value of 2047/4096 * 3.3V */
	//TM_DAC_SetValue(TM_DAC2, 4096);

	// DAC PIN PA5
	/* Initialize DAC1, use TIM4 for signal generation */
	TM_DAC_SIGNAL_Init(TM_DAC2, TIM4);
	/* Output predefined triangle signal with frequency of 5kHz */
	TM_DAC_SIGNAL_SetSignal(TM_DAC2, TM_DAC_SIGNAL_Signal_Sinus, 50);

	/* MAIN LOOP */
    while (1) {

    	// Read acceleration data
#ifdef ENABLE_MMA
		MMA845X_ReadAcceleration(accelData);
#endif

		// Read analog input
		analogIn = TM_ADC_Read(CURRENT_ADC, CURRENT_CH);

		// Print graphs
		printGraphsLCD(accelData, analogIn);

		// Toggle Green led
		TM_GPIO_TogglePinValue(GPIOG, GPIO_PIN_13);

    }
}
Beispiel #10
0
//*******************************************************************************************************    
// SendHTTP:     
//                  Main entry point for this code.      
//                    url           - The URL to GET/POST to/from.    
//                    headerSend        - Headers to be sent to the server.    
//                    post          - Data to be posted to the server, NULL if GET.    
//                    postLength    - Length of data to post.    
//                    req           - Contains the message and headerSend sent by the server.    
//    
//                    returns 1 on failure, 0 on success.    
//*******************************************************************************************************    
int Request::SendHTTP(string url,LPCSTR headerReceive,BYTE *post,    
                      DWORD postLength,HTTPRequest *req)    
{    
    WSADATA         WsaData;    
    SOCKADDR_IN     sin;    
    SOCKET          sock;    
    char            buffer[512];    
    char            protocol[20],host[256],request[1024];    
    int             l,port,chars,err;    
    MemBuffer       headersBuffer,messageBuffer;    
    char            headerSend[1024];    
    BOOL            done;    
   
   
   
   
    ParseURL(url,protocol,sizeof(protocol),host,sizeof(host),       // Parse the URL    
        request,sizeof(request),&port);    
    if(strcmp(protocol,"HTTP"))    
        return 1;    
   
    err = WSAStartup (0x0101, &WsaData);                            // Init Winsock    
    if(err!=0)    
        return 1;    
   
    sock = socket (AF_INET, SOCK_STREAM, 0);    
    //if (socket == INVALID_SOCKET)    
    if (sock == INVALID_SOCKET)    
    {    
        return 1;    
    }    
   
    sin.sin_family = AF_INET;                                       //Connect to web sever    
    sin.sin_port = htons( (unsigned short)port );    
    sin.sin_addr.s_addr = GetHostAddress(host);    
   
    if( connect (sock,(LPSOCKADDR)&sin, sizeof(SOCKADDR_IN) ) )    
    {    
   
        return 1;    
    }    
   
   
    if( !*request )    
        lstrcpynA(request,"/",sizeof(request));    
   
    if( post == NULL )    
    {    
        SendString(sock,"GET ");    
        strcpy(headerSend, "GET ");    
    }    
    else     
    {    
        SendString(sock,"POST ");    
        strcpy(headerSend, "POST ");    
    }    
    SendString(sock,request);    
    strcat(headerSend, request);    
   
    SendString(sock," HTTP/1.0/r/n");    
    strcat(headerSend, " HTTP/1.0/r/n");    
   
    SendString(sock,"Accept: image/gif, image/x-xbitmap,"   
        " image/jpeg, image/pjpeg, application/vnd.ms-excel,"   
        " application/msword, application/vnd.ms-powerpoint,"   
        " */*/r/n");    
    strcat(headerSend, "Accept: image/gif, image/x-xbitmap,"   
        " image/jpeg, image/pjpeg, application/vnd.ms-excel,"   
        " application/msword, application/vnd.ms-powerpoint,"   
        " */*/r/n");    
   
    SendString(sock,"Accept-Language: en-us/r/n");    
    strcat(headerSend, "Accept-Language: en-us/r/n");    
   
    SendString(sock,"Accept-Encoding: gzip, default/r/n");    
    strcat(headerSend, "Accept-Encoding: gzip, default/r/n");    
   
    SendString(sock,"User-Agent: Neeao/4.0/r/n");    
    strcat(headerSend, "User-Agent: Neeao/4.0/r/n");    
   
    if(postLength)    
    {    
        sprintf(buffer,"Content-Length: %ld/r/n",postLength);    
        SendString(sock,buffer);    
        strcat(headerSend, buffer);    
    }    
    //SendString(sock,"Cookie: mycookie=blablabla/r/n");    
    //  printf("Cookie: mycookie=blablabla/r/n");    
    SendString(sock,"Host: ");    
    strcat(headerSend, "Host: ");    
   
    SendString(sock,host);    
    strcat(headerSend, host);    
   
    SendString(sock,"/r/n");    
    strcat(headerSend, "/r/n");    
   
    if( (headerReceive!=NULL) && *headerReceive )    
    {    
        SendString(sock,headerReceive);    
        strcat(headerSend, headerReceive);    
    }    
   
    SendString(sock,"/r/n");                                // Send a blank line to signal end of HTTP headerReceive    
    strcat(headerSend, "/r/n");    
   
    if( (post!=NULL) && postLength )    
    {    
        send(sock,(const char*)post,postLength,0);    
        post[postLength]    = '/0';    
   
        strcat(headerSend, (const char*)post);    
    }    
   
    //strcpy(req->headerSend, headerSend);    
    req->headerSend     = (char*) malloc( sizeof(char*) * strlen(headerSend));    
    strcpy(req->headerSend, (char*) headerSend );    
   
   
    MemBufferCreate(&headersBuffer );    
    chars = 0;    
    done = FALSE;    
   
    while(!done)    
    {    
        l = recv(sock,buffer,1,0);    
        if(l<0)    
            done=TRUE;    
   
        switch(*buffer)    
        {    
        case '/r':    
            break;    
        case '/n':    
            if(chars==0)    
                done = TRUE;    
            chars=0;    
            break;    
        default:    
            chars++;    
            break;    
        }    
   
        MemBufferAddByte(&headersBuffer,*buffer);    
    }    
   
    req->headerReceive  = (char*) headersBuffer.buffer;    
    *(headersBuffer.position) = 0;    
   
   
   
    MemBufferCreate(&messageBuffer);                            // Now read the HTTP body    
   
    do   
    {    
        l = recv(sock,buffer,sizeof(buffer)-1,0);    
        if(l<0)    
            break;    
        *(buffer+l)=0;    
        MemBufferAddBuffer(&messageBuffer, (unsigned char*)&buffer, l);    
    } while(l>0);    
    *messageBuffer.position = 0;    
    req->message = (char*) messageBuffer.buffer;    
    req->messageLength = (messageBuffer.position - messageBuffer.buffer);    
   
   
    closesocket(sock);                                          // Cleanup    
   
    return 0;    
}    
void ILowerLayer::Send(const boost::uint8_t* apData, size_t aNumBytes)
{
    LOG_BLOCK(LEV_COMM, SendString() << " " << toHex(apData, aNumBytes, true));
    this->_Send(apData, aNumBytes);
}
//*****************************************************************************
//
// This is the main loop that runs the application.
//
//*****************************************************************************
int
main(void)
{
    uint_fast32_t ui32LastTickCount;
    bool bLastSuspend;


    //
    // Enable lazy stacking for interrupt handlers.  This allows floating-point
    // instructions to be used within interrupt handlers, but at the expense of
    // extra stack usage.
    //
    ROM_FPULazyStackingEnable();

    //
    // Set the clocking to run from the PLL at 50MHz.
    //
    ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // Enable the GPIO port that is used for the on-board LED.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);

    //
    // Enable the GPIO pin for the Blue LED (PF2).
    //
    ROM_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3);

    //
    // Enable the UART.
    //
    ConfigureUART();
    UARTprintf("Keyboard device application\n");

    // Configure USB0DM & USB0DP (PD4 & PD5)
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    SysCtlGPIOAHBEnable(SYSCTL_PERIPH_GPIOD);
    ROM_GPIOPinTypeUSBAnalog(GPIO_PORTD_AHB_BASE, GPIO_PIN_4 | GPIO_PIN_5);

    //Configure USB0ID & USB0VBUS (PB0 & PB1)
//    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
//    ROM_GPIOPinTypeUSBAnalog(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1);


    //
    // Erratum workaround for silicon revision A1.  VBUS must have pull-down.
    //
    if(CLASS_IS_TM4C123 && REVISION_IS_A1)
    {
        HWREG(GPIO_PORTB_BASE + GPIO_O_PDR) |= GPIO_PIN_1;
    }


    //
    // Initialize the buttons driver
    //
    ButtonsInit();

    //
    // Not configured initially.
    //
    g_bConnected = false;
    g_bSuspended = false;
    bLastSuspend = false;

    //
    // Initialize the USB stack for device mode.
    //
    //USBStackModeSet(0, eUSBModeDevice, 0);
    USBStackModeSet(0, eUSBModeForceDevice, 0);
    //
    // Pass our device information to the USB HID device class driver,
    // initialize the USB
    // controller and connect the device to the bus.
    //
    USBDHIDKeyboardInit(0, &g_sKeyboardDevice);

    //
    // Set the system tick to fire 100 times per second.
    //
    ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / SYSTICKS_PER_SECOND);
    ROM_SysTickIntEnable();
    ROM_SysTickEnable();

    //
    // The main loop starts here.  We begin by waiting for a host connection
    // then drop into the main keyboard handling section.  If the host
    // disconnects, we return to the top and wait for a new connection.
    //
    while(1)
    {
        uint8_t ui8Buttons;
        uint8_t ui8ButtonsChanged;

        //
        // Tell the user what we are doing and provide some basic instructions.
        //
        UARTprintf("Waiting for host...\n");

        //
        // Wait here until USB device is connected to a host.
        //
        while(!g_bConnected)
        {
        }

        //
        // Update the status.
        //
        UARTprintf("Host connected...\n");

        //
        // Enter the idle state.
        //
        g_eKeyboardState = STATE_IDLE;

        //
        // Assume that the bus is not currently suspended if we have just been
        // configured.
        //
        bLastSuspend = false;

        //
        // Keep transferring characters from the UART to the USB host for as
        // long as we are connected to the host.
        //
        while(g_bConnected)
        {
            //
            // Remember the current time.
            //
            ui32LastTickCount = g_ui32SysTickCount;

            //
            // Has the suspend state changed since last time we checked?
            //
            if(bLastSuspend != g_bSuspended)
            {
                //
                // Yes - the state changed so update the display.
                //
                bLastSuspend = g_bSuspended;
                UARTprintf(bLastSuspend ? "Bus suspended...\n" :"Host connected...\n");
            }

            //
            // See if the button was just pressed.
            //
            ui8Buttons = ButtonsPoll(&ui8ButtonsChanged, 0);
            if(BUTTON_PRESSED(LEFT_BUTTON, ui8Buttons, ui8ButtonsChanged))
            {
                //
                // If the bus is suspended then resume it.  Otherwise, type
                // some "random" characters.
                //
                if(g_bSuspended)
                {
                    USBDHIDKeyboardRemoteWakeupRequest(
                                                   (void *)&g_sKeyboardDevice);
                }
                else
                {
                    SendString("Make the Switch to TI Microcontrollers!");
                }
            }

            //
            // Wait for at least 1 system tick to have gone by before we poll
            // the buttons again.
            //
            while(g_ui32SysTickCount == ui32LastTickCount)
            {

            }
        }

        //
        // Dropping out of the previous loop indicates that the host has
        // disconnected so go back and wait for reconnection.
        //

        if(g_bConnected == false)
                {
                    UARTprintf("Host disconnected...\n");
                }

    }
}
int main(void)
{
	//Calibração do sensor
	/*configPWM();
	setServoAngle(0);
	while(1){
	}*/
	double dt = 0.0;
	double curr_err = 0;
	float PID_Input = 0;
	float PID_Output = 0;
	int i_PID_Input = 0;
	int i_Output = 0;
	char c_PID_Input[4];
	char c_Output[4];
	char c_adc_value[4];
	float gain = -20.0;
	
	
	ADC_config();
	ADC_Start();
	USART_config();
	
	configPWM();
	setServoAngle(0);
	ConfigSerie_BT();
	pid_start();
	pid_timer_config();
	configMotorPWM(500);
	setMotorDirection(1);
	duty_cycle = 10;
	while(1)
	{
		
		if(mode == 1)
		{
			
			if(all_read == 1)
			{
				
				PID_Input = Centroid_Algorithm();
				curr_err = (3.5 - PID_Input);
				dt = TCNT5;
				dt = (dt*16)/1000000;
				
				pid_update(ptr, curr_err,dt);
				PID_Output = PID.control;
				itoa(i_Output, c_Output, 10);
				SendString((char*)"\n-------------------\n");
				SendString((char*)"\nSaída_PID 1: ");
				SendString(c_Output);
				
			
				PID_Output = PID_Output*gain;
				if(PID_Output > 75)
					PID_Output = 75;
				if(PID_Output < -75)
					PID_Output = -75;
			
				setServoAngle(PID_Output);
			
				i_PID_Input = (int) PID_Input;
				i_Output = (int) PID_Output;
				itoa(i_PID_Input, c_PID_Input ,10);
				itoa(i_Output, c_Output, 10);
				SendString((char*)"\nLeituras: "); 
				for(int i = 0; i < 8; i++)
					{
						itoa(adc_value[i], c_adc_value, 10); 
						SendString(c_adc_value);
						UsartSendByte(' ');
					}
				SendString((char*)"\nEntrada PID: "); 
				SendString(c_PID_Input); 
				SendString((char*)"\nSaída_PID 2: "); 
				SendString(c_Output); 
				all_read = 0; 
				ADMUX &= 0XE0; //Limpa ADMUX 
				ADMUX |= channel; //Selecciona o canal 0 
				ADCSRA |= (1<<ADSC); //Inicia conversão
			}
		}
		if(mode == 0)
		{
			//
		}

	}
}
//*****************************************************************************
//
// This is the main loop that runs the application.
//
//*****************************************************************************
int
main(void)
{
    unsigned long ulLastTickCount;
    tBoolean bLastSuspend;
    tRectangle sRect;
    tContext sContext;
    long lCenterX;

    //
    // Enable lazy stacking for interrupt handlers.  This allows floating-point
    // instructions to be used within interrupt handlers, but at the expense of
    // extra stack usage.
    //
    ROM_FPULazyStackingEnable();

    //
    // Set the clocking to run from the PLL at 50MHz.
    //
    ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // Configure the required pins for USB operation.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOG);
    ROM_GPIOPinConfigure(GPIO_PG4_USB0EPEN);
    ROM_GPIOPinTypeUSBDigital(GPIO_PORTG_BASE, GPIO_PIN_4);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOL);
    ROM_GPIOPinTypeUSBAnalog(GPIO_PORTL_BASE, GPIO_PIN_6 | GPIO_PIN_7);
    ROM_GPIOPinTypeUSBAnalog(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1);

    //
    // Erratum workaround for silicon revision A1.  VBUS must have pull-down.
    //
    if(CLASS_IS_BLIZZARD && REVISION_IS_A1)
    {
        HWREG(GPIO_PORTB_BASE + GPIO_O_PDR) |= GPIO_PIN_1;
    }

    //
    // Enable the GPIO that is used for the on-board LED.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOG);
    ROM_GPIOPinTypeGPIOOutput(GPIO_PORTG_BASE, GPIO_PIN_2);
    ROM_GPIOPinWrite(GPIO_PORTG_BASE, GPIO_PIN_2, 0);

    //
    // Initialize the buttons driver
    //
    ButtonsInit();

    //
    // Initialize the display driver.
    //
    CFAL96x64x16Init();

    //
    // Initialize the graphics context and find the middle X coordinate.
    //
    GrContextInit(&sContext, &g_sCFAL96x64x16);
    lCenterX = GrContextDpyWidthGet(&sContext) / 2;

    //
    // Fill the top part of the screen with blue to create the banner.
    //
    sRect.sXMin = 0;
    sRect.sYMin = 0;
    sRect.sXMax = GrContextDpyWidthGet(&sContext) - 1;
    sRect.sYMax = 9;
    GrContextForegroundSet(&sContext, ClrDarkBlue);
    GrRectFill(&sContext, &sRect);

    //
    // Change foreground for white text.
    //
    GrContextForegroundSet(&sContext, ClrWhite);

    //
    // Put the application name in the middle of the banner.
    //
    GrContextFontSet(&sContext, g_pFontFixed6x8);
    GrStringDrawCentered(&sContext, "usb-dev-keyboard", -1, lCenterX, 4, 0);

    //
    // Not configured initially.
    //
    g_bConnected = false;
    g_bSuspended = false;
    bLastSuspend = false;

    //
    // Initialize the USB stack for device mode.
    //
    USBStackModeSet(0, USB_MODE_DEVICE, 0);

    //
    // Pass our device information to the USB HID device class driver,
    // initialize the USB
    // controller and connect the device to the bus.
    //
    USBDHIDKeyboardInit(0, &g_sKeyboardDevice);

    //
    // Set the system tick to fire 100 times per second.
    //
    ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / SYSTICKS_PER_SECOND);
    ROM_SysTickIntEnable();
    ROM_SysTickEnable();

    //
    // The main loop starts here.  We begin by waiting for a host connection
    // then drop into the main keyboard handling section.  If the host
    // disconnects, we return to the top and wait for a new connection.
    //
    while(1)
    {
        unsigned char ucButtons;
        unsigned char ucButtonsChanged;

        //
        // Tell the user what we are doing and provide some basic instructions.
        //
        GrStringDrawCentered(&sContext, "    Waiting    ", -1, lCenterX, 22, 1);
        GrStringDrawCentered(&sContext, " for host ... ", -1, lCenterX, 32, 1);

        //
        // Wait here until USB device is connected to a host.
        //
        while(!g_bConnected)
        {
        }

        //
        // Update the status.
        //
        GrStringDrawCentered(&sContext, "     Host     ", -1, lCenterX, 22, 1);
        GrStringDrawCentered(&sContext, " connected ... ", -1, lCenterX, 32, 1);

        //
        // Enter the idle state.
        //
        g_eKeyboardState = STATE_IDLE;

        //
        // Assume that the bus is not currently suspended if we have just been
        // configured.
        //
        bLastSuspend = false;

        //
        // Keep transferring characters from the UART to the USB host for as
        // long as we are connected to the host.
        //
        while(g_bConnected)
        {
            //
            // Remember the current time.
            //
            ulLastTickCount = g_ulSysTickCount;

            //
            // Has the suspend state changed since last time we checked?
            //
            if(bLastSuspend != g_bSuspended)
            {
                //
                // Yes - the state changed so update the display.
                //
                bLastSuspend = g_bSuspended;
                if(bLastSuspend)
                {
                    GrStringDrawCentered(&sContext, "      Bus      ", -1,
                                         lCenterX, 22, 1);
                    GrStringDrawCentered(&sContext, " suspended ... ", -1,
                                         lCenterX, 32, 1);
                }
                else
                {
                    GrStringDrawCentered(&sContext, "     Host     ", -1,
                                         lCenterX, 22, 1);
                    GrStringDrawCentered(&sContext, " connected ... ",
                                         -1, lCenterX, 32, 1);
                }
            }

            //
            // See if the button was just pressed.
            //
            ucButtons = ButtonsPoll(&ucButtonsChanged, 0);
            if(BUTTON_PRESSED(SELECT_BUTTON, ucButtons, ucButtonsChanged))
            {
                //
                // If the bus is suspended then resume it.  Otherwise, type
                // some "random" characters.
                //
                if(g_bSuspended)
                {
                    USBDHIDKeyboardRemoteWakeupRequest(
                                                   (void *)&g_sKeyboardDevice);
                }
                else
                {
                    SendString("Make the Switch to TI Microcontrollers!");
                }
            }

            //
            // Wait for at least 1 system tick to have gone by before we poll
            // the buttons again.
            //
            while(g_ulSysTickCount == ulLastTickCount)
            {
            }
        }
    }
}
Beispiel #15
0
void displayPrompt(int defaultCmd) {
  int minutesLeft;
  char *cmdStr, goMailStr[50];
  struct Kommando *cmd;

  if(Servermem->say[nodnr]) {
    displaysay();
  }
  if((minutesLeft = isUserOutOfTime()) == -1) {
    return;
  }

  Servermem->idletime[nodnr] = time(NULL);
  Servermem->action[nodnr] = LASER;
  Servermem->varmote[nodnr] = mote2;
  switch(defaultCmd) {
  case CMD_NEXTCONF:
    if(Servermem->cfg.ar.nextmeet) {
      sendautorexx(Servermem->cfg.ar.nextmeet);
    }
    cmdStr = CATSTR(MSG_PROMPT_GO_TO_NEXT_FORUM);
    break;
  case CMD_NEXTTEXT:
    if(mote2 == MAILBOX_CONFID) {
      if(Servermem->cfg.ar.nextletter) {
        sendautorexx(Servermem->cfg.ar.nextletter);
      }
      cmdStr = CATSTR(MSG_PROMPT_READ_NEXT_MAIL);
    } else {
      if(Servermem->cfg.ar.nexttext) {
        sendautorexx(Servermem->cfg.ar.nexttext);
      }
      cmdStr = CATSTR(MSG_PROMPT_READ_NEXT_TEXT);
    }
    break;
  case CMD_NEXTREPLY:
    if(Servermem->cfg.ar.nextkom) {
      sendautorexx(Servermem->cfg.ar.nextkom);
    }
    cmdStr = CATSTR(MSG_PROMPT_READ_NEXT_COMMENT);
    break;
  case CMD_SEETIME:
    Servermem->action[nodnr] = INGET;
    if(Servermem->cfg.ar.setid) {
      sendautorexx(Servermem->cfg.ar.setid);
    }
    cmdStr = CATSTR(MSG_PROMPT_SEE_TIME);
    break;
  case CMD_GOMAIL:
    if(Servermem->cfg.ar.nextmeet) {
      sendautorexx(Servermem->cfg.ar.nextmeet);
    }
    sprintf(goMailStr, CATSTR(MSG_PROMPT_GO_TO_MAILBOX), Servermem->cfg.brevnamn);
    cmdStr = goMailStr;
    break;
  default:
    cmdStr = "*** Undefined default command ***";
  }
  if(minutesLeft > 4) {
    SendString("\r\n%s %s ", cmdStr, Servermem->inne[nodnr].prompt);
  } else {
    SendString("\r\n%s (%d) %s ", cmdStr, minutesLeft, Servermem->inne[nodnr].prompt);
  }

  if((cmd = getCommandToExecute(defaultCmd)) == NULL) {
    return;
  }
  executeCommand(cmd);
}
Beispiel #16
0
void Cmd_Reply(void) {
  struct Mote *conf;
  int isCorrect;

  if(argument[0]) {
    if(mote2 == -1) {
      brev_kommentera();
      return;
    }
    conf = getmotpek(mote2);
    if(conf->type == MOTE_ORGINAL) {
      org_kommentera();
      return;
    }
    if(conf->type == MOTE_FIDO) {
      if(!MayReplyConf(mote2, inloggad, &Servermem->inne[nodnr])) {
        SendString("\r\n\nDu får inte kommentera den texten!\r\n\n");
        return;
      }
      if(conf->status & KOMSKYDD) {
        if(GetYesOrNo("\r\n\n", "Vill du verkligen kommentera i ett kommentarsskyddat möte?",
                      NULL, NULL, "Ja", "Nej", "\r\n", FALSE, &isCorrect)) {
          return;
        }
        if(!isCorrect) {
          return;
        }
      }
      fido_skriv(TEXTTYPE_REPLY, atoi(argument));
      return;
    }
  }

  if(!senast_text_typ) {
    SendString("\n\n\rDu har inte läst någon text ännu.\n\r");
    return;
  }
  if(senast_text_typ == BREV) {
    brev_kommentera();
    return;
  }
  conf = getmotpek(senast_text_mote);
  if(!conf) {
    LogEvent(SYSTEM_LOG, ERROR,
             "Conference for last read text (confId = %d) does not exist.",
             senast_text_mote);
    DisplayInternalError();
    return;
  }
  if(!MayReplyConf(senast_text_mote, inloggad, &Servermem->inne[nodnr])) {
    SendString("\r\n\nDu får inte kommentera den texten!\r\n\n");
    return;
  }
  if(conf->status & KOMSKYDD) {
    if(GetYesOrNo("\r\n\n", "Vill du verkligen kommentera i ett kommentarsskyddat möte?",
                  NULL, NULL, "Ja", "Nej", "\r\n", FALSE, &isCorrect)) {
      return;
    }
    if(!isCorrect) {
      return;
    }
  }
  if(conf->type == MOTE_ORGINAL) {
    org_kommentera();
  } else if(conf->type == MOTE_FIDO) {
    fido_skriv(TEXTTYPE_REPLY, senast_text_nr);
  }
}