Пример #1
0
/**
  \fn void close_port(HANDLE *fpCom)
   
  \brief close comm port
  
  \param[in] fpCom    handle to comm port

  close & release comm port. 
*/
void close_port(HANDLE *fpCom) {

/////////
// Win32
/////////
#if defined(WIN32)

  BOOL      fSuccess;

  if (*fpCom != NULL) {
    fSuccess = CloseHandle(*fpCom);
    if (!fSuccess) {
      setConsoleColor(PRM_COLOR_RED);
      *fpCom = NULL;
      fprintf(stderr, "\n\nerror in 'close_port': close port failed with code %d, exit!\n\n", (int) GetLastError());
      Exit(1, g_pauseOnExit);
    }
  }
  *fpCom = NULL;

#endif // WIN32


/////////
// Posix
/////////
#if defined(__APPLE__) || defined(__unix__) 

  if (*fpCom != 0) {
    if (close(*fpCom) != 0) {
      setConsoleColor(PRM_COLOR_RED);
      *fpCom = 0;
      fprintf(stderr, "\n\nerror in 'close_port': close port failed, exit!\n\n");
      Exit(1, g_pauseOnExit);
    }
  }
  *fpCom = 0;

#endif // __APPLE__ || __unix__

} // close_port
Пример #2
0
void initScoreBoard(Player * players, int nOfPlayers)
{
    int i;
    setConsoleColor(COLORDEF);
    system("cls");
    puts("SCOREBOARD : ");
    printf("%20s %10s\n", "NAME", "SCORE");
    for(i = 0; i < nOfPlayers; i++)
        printf("%20s %10i\n", players[i].name, players[i].points);
    puts("Press anything to continue");
    getch();
}
Пример #3
0
void asciitochar(){
    int userChoise = 0;
    char didExit = 'a';
    while(1){
        int c;

        system("cls");

        setConsoleColor(FOREGROUND_BLUE | FOREGROUND_INTENSITY);

        printf ("########################################\n");
        printf ("######  Welcome on ascii to char  ######\n");
        printf ("########################################\n");
        printf ("\n");
        fflush(stdout);

        printf ("########################################\n");
        printf ("# Press ascii and get it to char       #\n");
        printf ("# 1 : take a int ascii table 0 - 127   #\n");
        printf( "# 2 : validate                         #\n");
        printf ("########################################\n");
        printf ("\n");
        fflush(stdout);

        /* Restore original attributes */
        setConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);

        printf("Enter a int: ");
        c = mathInputInt();
        printf("Int value of %c = %d\n",c,c);

        printf ("Do you want to exit? (q) :");
        didExit = needToExit();
        if(didExit == 'q'){
            asciiHomeDisplay();
            userChoise = userInputInt(3);
            asciiHomeUse(userChoise);
        }
    }
}
Пример #4
0
void initConsole()
{
    int i, j;
    int status = 0;
    size_t nOfElements =0;
    char buffer[100];
    char settings[100];
    time_t t;
    srand((unsigned) time(&t));
    sprintf(settings,"mode con:cols=%i lines=%i", LENGTH, HEIGHT);
    system(settings);
    do
    {
        system("cls");
        puts("Please write the size of the array (1..23)");
        printf(" >> ");
        fgets(buffer, 100,stdin);
        status = sscanf(buffer, "%u", &nOfElements);
    }
    while(!status || nOfElements < 1 || nOfElements > 23);
    double arr[nOfElements];
    system("cls");
    setCursorPosition((LENGTH - (RIGHTBORDER))/2, 1);
    printf("Type 'help' for commands");
    clearZone(RIGHTBORDER, 0, LENGTH - 1, HEIGHT - 2, COLORWORKBACK);
    clearZone(0, BOTBORDER, LENGTH - 1, HEIGHT - 1, COLORWORKCOM);
    setConsoleColor(COLORWORKCOM);
    setCursorPosition(LENGTH/3, BOTBORDER);
    printf("Command's action :");
    setConsoleColor(COLORWORKBACK);
    setCursorPosition(RIGHTBORDER + (LENGTH - (RIGHTBORDER))/3, 0);
    printf("Array : ");
    initRandArray(arr, nOfElements, -10, 10);
    printArr(arr, nOfElements);
    setConsoleColor(COLORDEF);
    setCursorPosition(0, 1);
    getCommand(arr, nOfElements);
}
Пример #5
0
/**
  \fn uint32_t send_port(HANDLE fpCom, uint32_t lenTx, char *Tx)
   
  \brief send data via comm port
  
  \param[in] fpCom    handle to comm port
  \param[in] lenTx    number of bytes to send
  \param[in] Tx       array of bytes to send

  \return number of sent bytes
  
  send data via comm port. Use this function to facilitate serial communication
  on different platforms, e.g. Win32 and Posix.
  If g_UARTmode==1 (1-wire interface), read back LIN echo 
*/
uint32_t send_port(HANDLE fpCom, uint32_t lenTx, char *Tx) {

  // for reading back LIN echo 
  char      Rx[1000];
  uint32_t  lenRx;
  
  
/////////
// Win32
/////////
#ifdef WIN32

  DWORD   numChars;
  
  // send data & return number of sent bytes
  PurgeComm(fpCom, PURGE_RXABORT | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_TXCLEAR);
  WriteFile(fpCom, Tx, lenTx, &numChars, NULL);

#endif // WIN32


/////////
// Posix
/////////
#if defined(__APPLE__) || defined(__unix__) 

  uint32_t  numChars;
  
  // send data & return number of sent bytes
  numChars = write(fpCom, Tx, lenTx);

#endif // __APPLE__ || __unix__


  // for 1-wire interface, read back LIN echo and ignore
  if (g_UARTmode == 1) {
    lenRx = receive_port(fpCom, numChars, Rx);
    if (lenRx != numChars) {
      setConsoleColor(PRM_COLOR_RED);
      fprintf(stderr, "\n\nerror in 'send_port()': read 1-wire echo failed, exit!\n\n");
      Exit(1, g_pauseOnExit);
    }
    //fprintf(stderr,"received echo %dB 0x%02x\n", (int) lenRx, Rx[0]);
  }
  
  // return number of sent bytes
  return((uint32_t) numChars);

} // send_port
Пример #6
0
int main(void)
{
	InitConsole();
	Welcome();
	while (1) {
		GameMainLoop();
		ClearConsoleBuffer();
		setConsoleColor(FRED);
		DrawString((WIDTH - strlen("You are dead")) / 2, HEIGHT / 2, "You are dead");
		resetConsoleColor();
		RedrawConsole();
		while (!IsKeyPressed(VK_RETURN));
	}
	return 0;
}
Пример #7
0
void consoleFill(int rows, int columns)
{
    int i, curRow;
    for(i = 0, curRow = 0; curRow<rows; i++, curRow = (i/columns))
    {
        int left = curRow %2 ? 0 : 1;
        int curColumn = left ? (columns-1)-i%columns : i%columns;
        int curColorPos = abs( (curColumn - curRow) % 3);
        if(curRow > curColumn)
            curColorPos = 2 - abs( (curColumn - curRow - 2) % 3);
        setCursorPosition(curColumn, curRow);
        setConsoleColor(curColorPos);
        printf("*"); /* " " is more beautiful */
        Sleep(1);
    }
    setCursorPosition(0, 0);
}
Пример #8
0
void rawLogMessage(LogLevel c, const char *message) {
  static std::size_t lastHash = 0;
  static int timesRepeated = 0;
  std::size_t curHash =
      hash_bytes(message, std::strlen(message)) + (std::size_t)c;
  // bool repeatLast = false;
  if (curHash == lastHash) {
    // repeat last output
    ++timesRepeated;
    setConsoleColor(std::cerr, 8);
    rawRepeatLast(timesRepeated, message);
    setConsoleColor(std::cerr, 7);
  } else {
    lastHash = curHash;
    if (timesRepeated)
      rawDebugOutput(0, "\n");
    timesRepeated = 0;
  }

  if (c == LogLevel::Debug) {
    setConsoleColor(std::cerr, 8);
    rawDebugOutput(timesRepeated, "[DEBUG] ");
  } else if (c == LogLevel::Warning) {
    setConsoleColor(std::cerr, 14);
    rawDebugOutput(timesRepeated, "[WARN ] ");
    setConsoleColor(std::cerr, 7);
  } else if (c == LogLevel::Error) {
    setConsoleColor(std::cerr, 12);
    rawDebugOutput(timesRepeated, "[ERROR] ");
    setConsoleColor(std::cerr, 7);
  } else if (c == LogLevel::Fatal) {
    setConsoleColor(std::cerr, 12);
    rawDebugOutput(timesRepeated, "\n[FATAL] ");
  }
  rawDebugOutput(timesRepeated, message);
  rawDebugOutput(timesRepeated, "\n");
  setConsoleColor(std::cerr, 7);
}
void RenderSystem::forceClear()
{
    for (int y = 0; y < SCREEN_HEIGHT; y++)
    {
        for (int x = 0; x < SCREEN_WIDTH; x++)
        {
            m_backBuffer[y][x].symbol = 0;
            m_backBuffer[y][x].symbolColor = ConsoleColor_Grey;
            m_backBuffer[y][x].backgroundColor = ConsoleColor_Black;

            m_screenBuffer[y][x] = m_backBuffer[y][x];

            setConsoleCursor(x, y);
            setConsoleColor(m_screenBuffer[y][x].symbolColor, m_screenBuffer[y][x].backgroundColor);
            printf("%c", m_screenBuffer[y][x].symbol);
        }
    }
    setConsoleCursor(0, 0);

}
Пример #10
0
	void print() {
		if (val < 1)
			setConsoleColor(DARKBLUE);
		else if(val < 2)
			setConsoleColor(BLUE);
		else if (val < 3)
			setConsoleColor(DARKYELLOW);
		else if (val < 5)
			setConsoleColor(GREEN);
		else if (val < 6)
			setConsoleColor(DARKGREEN);
		else if (val < 7)
			setConsoleColor(GRAY);
		else if (val < 8)
			setConsoleColor(DARKGRAY);
		else if (val < 9)
			setConsoleColor(WHITE);

		std::cout << (char)219;//std::to_string(val);

		setDefaultConsoleColor();
	}
void RenderSystem::flush()
{
    bool screenBufferModified = false;

    for (int y = 0; y < SCREEN_HEIGHT; y++)
    {
        for (int x = 0; x < SCREEN_WIDTH; x++)
        {
            if (m_backBuffer[y][x] != m_screenBuffer[y][x])
            {
                m_screenBuffer[y][x] = m_backBuffer[y][x];

                setConsoleCursor(x, y);
                setConsoleColor(m_screenBuffer[y][x].symbolColor, m_screenBuffer[y][x].backgroundColor);
                printf("%c", m_screenBuffer[y][x].symbol);
                screenBufferModified = true;
            }
        }
    }
    if (screenBufferModified)
    {
        setConsoleCursor(0, 0);
    }
}
Пример #12
0
void getCommand(double arr[], size_t size)
{
    char buffer[100];
    CONSOLE_SCREEN_BUFFER_INFO SBInfo;
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    GetConsoleScreenBufferInfo(hConsole, &SBInfo);
    if(SBInfo.dwCursorPosition.Y > BOTBORDER - 3)
    {
        clearZone(0, 1, RIGHTBORDER - 1, BOTBORDER - 2, COLORDEF);
        setCursorPosition(0, 1);
    }
    printf(" >> ");
    fgets(buffer, 100,stdin);
    if(!strcmp(buffer, "help\n"))
    {
        if(SBInfo.dwCursorPosition.Y > BOTBORDER - 20)
        {
            clearZone(0, 1, RIGHTBORDER - 1, BOTBORDER - 2, COLORDEF);
            setCursorPosition(0, 1);
        }
        puts(HELPINFO);
    }
    else if(!strcmp(buffer, "nullify\n"))
    {
        nullifyArr(arr, size);
        printArr(arr, size);
    }
    else if(strstr(buffer, "change"))
    {
        unsigned int index;
        int status;
        double value;
        printArr(arr, size);
        status = sscanf(buffer, "change %u %lf", &index, &value);
        if(status==2 && index < size)
        {
            changeNumByInd(arr, size, index, value);
            printArrEl(arr, size, index);
        }
        else
        {
            setConsoleColor(COLORERROR);
            puts("Inappropriate format");
            setConsoleColor(COLORDEF);
        }

    }
    else if(strstr(buffer, "random"))
    {
        double from, to;
        int status = sscanf(buffer, "random %lf %lf", &from, &to);
        if(status==2)
        {
            initRandArray(arr, size, from, to);
            printArr(arr, size);
        }
        else
        {
            setConsoleColor(COLORERROR);
            puts("Inappropriate format");
            setConsoleColor(COLORDEF);
        }
    }
    else if(!strcmp(buffer, "reverse\n"))
    {
        int i;
        reverseArr(arr, size);
        clearZone(RIGHTBORDER, 0, LENGTH - 1, 0, COLORSELECT);
        setConsoleColor(COLORSELECT);
        setCursorPosition(RIGHTBORDER + 1, 0);
        printf("REVERSED array : ");
        printArr(arr, size);
        setCursorPosition(0, SBInfo.dwCursorPosition.Y + 1);
        puts("Press anything to reverse back...");
        getch();
        setConsoleColor(COLORSELECT);
        clearZone(RIGHTBORDER, 0, LENGTH - 1, 0, COLORWORKBACK);
        setCursorPosition(RIGHTBORDER + (LENGTH - (RIGHTBORDER))/3, 0);
        setConsoleColor(COLORWORKBACK);
        printf("Array : ");
        clearZone(0, SBInfo.dwCursorPosition.Y + 1,RIGHTBORDER - 1, SBInfo.dwCursorPosition.Y + 1, COLORDEF);
        setCursorPosition(0, SBInfo.dwCursorPosition.Y + 1);
        reverseArr(arr, size);
        printArr(arr, size);
    }
    else if(!strcmp(buffer, "sum\n"))
    {
        double sum = findSum(arr, size);
        clearZone(0, BOTBORDER + 3, LENGTH - 1, BOTBORDER + 3, COLORWORKCOM);
        setCursorPosition(LENGTH/4, BOTBORDER + 3);
        setConsoleColor(COLORWORKCOM);
        printf("The sum of the array is : %.2f", sum);
        setConsoleColor(COLORDEF);
        setCursorPosition(0, SBInfo.dwCursorPosition.Y + 1);
    }
    else if(!strcmp(buffer, "nnegative\n"))
    {
        int nnegative = numOfNegElements(arr, size);
        clearZone(0, BOTBORDER + 3, LENGTH - 1, BOTBORDER + 3, COLORWORKCOM);
        setCursorPosition(LENGTH/4, BOTBORDER + 3);
        setConsoleColor(COLORWORKCOM);
        printf("The number of negative elements of the array is : %i", nnegative);
        setConsoleColor(COLORDEF);
        setCursorPosition(0, SBInfo.dwCursorPosition.Y + 1);
    }
    else if(strstr(buffer, "shift"))
    {
        unsigned int nSH;
        int status = sscanf(buffer, "shift %u", &nSH);
        if(status)
        {
            shiftArrR(arr, size, nSH);
            printArr(arr, size);
        }
        else
        {
            setConsoleColor(COLORERROR);
            puts("Inappropriate format");
            setConsoleColor(COLORDEF);
        }
    }
    else if(strstr(buffer, "cyclesh"))
    {
        unsigned int nSH;
        int status = sscanf(buffer, "cyclesh %u", &nSH);
        if(status)
        {
            cycleShiftArrR(arr, size, nSH);
            printArr(arr, size);
        }
        else
        {
            setConsoleColor(COLORERROR);
            puts("Inappropriate format");
            setConsoleColor(COLORDEF);
        }
    }
    else if(strstr(buffer, "powall"))
    {
        double power;
        int status = sscanf(buffer, "powall %lf", &power);
        if(status)
        {
            powEachElement(arr, size, power);
            printArr(arr, size);
        }
        else
        {
            setConsoleColor(COLORERROR);
            puts("Inappropriate format");
            setConsoleColor(COLORDEF);
        }
    }
    else if(!strcmp(buffer, "firstmin\n"))
    {
        int imin = getMinimumIndex(arr, size);
        printArr(arr, size);
        printArrEl(arr, size, imin);
        clearZone(0, BOTBORDER + 3, LENGTH - 1, BOTBORDER + 3, COLORWORKCOM);
        setCursorPosition(LENGTH/4, BOTBORDER + 3);
        setConsoleColor(COLORWORKCOM);
        printf("The index and value of first minimum element is : %i, %.2f", imin, arr[imin]);
        setConsoleColor(COLORDEF);
        setCursorPosition(0, SBInfo.dwCursorPosition.Y + 1);
    }
    else if(!strcmp(buffer, "swapmaxmin\n"))
    {
        int swap1, swap2;
        printArr(arr, size);
        swapLastMaxAndMin(arr, size, &swap1, &swap2);
        printArrEl(arr, size, swap1);
        printArrEl(arr, size, swap2);
    }
    else if(!strcmp(buffer, "exit\n"))
    {
        exit(EXIT_SUCCESS);
    }
    else
    {
        puts("Command not found. Check help");
    }
    getCommand(arr, size);
}
Пример #13
0
void initInterface(Player * players, int nOfPlayers)
{
    char name[100];
    char buff[100];
    int points;
    int level, curY = 0;
    int status = 0;
    system("mode con:cols=50 lines=50");
    system("cls");
    setFontSize(15, 20);
    if(nOfPlayers > 0)
        initScoreBoard(players, nOfPlayers);
    strcpy(name, "DEFAULT");
    system("cls");
    setCursorPosition(CONSOLESIZE/2 - 10,curY++);
    puts("Write your name:");
    setCursorPosition(CONSOLESIZE/2 - 15,curY++);
    fgets(buff, 100, stdin);
    buff[strlen(buff) - 1] = '\0';
    if(strlen(buff)>1)
        strcpy(name, buff);
    while(!status)
    {
        printf("Hi, %s, what level do you want to take? (0..9)\n", name);
        fgets(buff, 100, stdin);
        status = sscanf(buff, "%i", &level);
        if(!status || level>9 || level < 0)
        {
            status = 0;
            puts("Try again:");
            curY++;
        }
    }
    puts("Press anything to start...");
    getch();
    points = initSnake(level);
    curY = 0;
    setConsoleColor(COLORDEF);
    setCursorPosition(0,curY++);
    Player p;
    strcpy(p.name, name);
    p.points = points;
    addToScoreBoard(&p, &nOfPlayers);
    free(players);
    players = getScoreBoard(&nOfPlayers);
    while(1)
    {
        setConsoleColor(COLORDEF);
        system("cls");
        setCursorPosition(0,0);
        printf("HOORAY! You've got %i points. Type NO if you want to stop\n Type SCORE if you want to look through the scoreboard\nType anything else if you want to try again\n", points);
        fgets(buff, 100, stdin);
        if(!strcmp(buff, "NO\n"))
            break;
        else if(!strcmp(buff, "SCORE\n"))
            initScoreBoard(players, nOfPlayers);
        else
        {
            points = initSnake(level);
            p.points = points;
            addToScoreBoard(&p, &nOfPlayers);
            free(players);
            players = getScoreBoard(&nOfPlayers);
        }
    }
}
Пример #14
0
/**
  \fn void set_baudrate(HANDLE fpCom, uint32_t baudrate)
   
  \brief modify comm port baudrate
   
  \param[in] fpCom      handle to comm port
  \param[in] baudrate   new comm port speed in Baud

  set new baudrate for an already open comm port. Baudrate must be supported by PC driver.
*/
void set_baudrate(HANDLE fpCom, uint32_t baudrate) {
  
/////////
// Win32
/////////
#ifdef WIN32

  DCB       fDCB;
  BOOL      fSuccess;

  // get the current port configuration
  fSuccess = GetCommState(fpCom, &fDCB);
  if (!fSuccess) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'set_baudrate(%d)': get port attributes failed with code %d, exit!\n\n", (int) baudrate, (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }

  // change port settings
  fDCB.BaudRate = baudrate;     // set the baud rate (19200, 57600, 115200)
  fSuccess = SetCommState(fpCom, &fDCB);
  if (!fSuccess) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'set_baudrate(%d)': set port attributes failed with code %d, exit!\n\n", (int) baudrate, (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }

#endif // WIN32


/////////
// Posix
/////////
#if defined(__APPLE__) || defined(__unix__) 

  struct termios  toptions;
    
  // get attributes
  if (tcgetattr(fpCom, &toptions) < 0) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'set_baudrate(%d)': get port attributes failed, exit!\n\n", (int) baudrate);
    Exit(1, g_pauseOnExit);
  }

  // set baudrate
  speed_t brate = baudrate; // let you override switch below if needed
  switch(baudrate) {
#ifdef B4800
    case 4800:   brate=B4800;   break;
#endif
#ifdef B9600
    case 9600:   brate=B9600;   break;
#endif
#ifdef B14400
    case 14400:  brate=B14400;  break;
#endif
#ifdef B19200
    case 19200:  brate=B19200;  break;
#endif
#ifdef B28800
    case 28800:  brate=B28800;  break;
#endif
#ifdef B38400
    case 38400:  brate=B38400;  break;
#endif
#ifdef B57600
    case 57600:  brate=B57600;  break;
#endif
#ifdef B115200
    case 115200: brate=B115200; break;
#endif
#ifdef B230400
    case 230400: brate=B230400; break;
#endif
    default: 
      setConsoleColor(PRM_COLOR_RED);
      fprintf(stderr, "\n\nerror in 'set_baudrate()': unsupported baudrate %d Baud, exit!\n\n", (int) baudrate);
      Exit(1, g_pauseOnExit);
  }
  cfsetispeed(&toptions, brate);    // receive
  cfsetospeed(&toptions, brate);    // send

  // set term properties
  if( tcsetattr(fpCom, TCSANOW, &toptions) < 0) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'set_baudrate(%d)': set port attributes failed, exit!\n\n", (int) baudrate);
    Exit(1, g_pauseOnExit);
  }

#endif // __APPLE__ || __unix__

} // set_baudrate
Пример #15
0
/**
  \fn void set_port_attribute(HANDLE fpCom, uint32_t baudrate, uint32_t timeout, uint8_t numBits, uint8_t parity, uint8_t numStop, uint8_t RTS, uint8_t DTR)
   
  \brief modify comm port settings
   
  \param[in] fpCom      handle to comm port
  \param[in] baudrate   comm port speed in Baud
  \param[in] timeout    timeout between chars in ms
  \param[in] numBits    number of data bits per byte
  \param[in] parity     parity control by HW
  \param[in] numStop    number of stop bits
  \param[in] RTS        Request To Send (required for some multimeter optocouplers)
  \param[in] DTR        Data Terminal Ready (required for some multimeter optocouplers)

  change attributes of an already open comm port.
*/
void set_port_attribute(HANDLE fpCom, uint32_t baudrate, uint32_t timeout, uint8_t numBits, uint8_t parity, uint8_t numStop, uint8_t RTS, uint8_t DTR) {
  
/////////
// Win32
/////////
#ifdef WIN32

  DCB           fDCB;
  BOOL          fSuccess;
  COMMTIMEOUTS  fTimeout;
  
  // reset COM port error buffer
  PurgeComm(fpCom, PURGE_RXABORT | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_TXCLEAR);
  
  // get the current port configuration
  fSuccess = GetCommState(fpCom, &fDCB);
  if (!fSuccess) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'set_port_attribute()': get port attributes failed with code %d, exit!\n\n", (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }

  // change port settings
  fDCB.BaudRate = baudrate;         // set the baud rate (19200, 57600, 115200)
  fDCB.ByteSize = numBits;          // number of data bits per byte
  if (parity) {
    fDCB.fParity = TRUE;            // Enable parity checking
    fDCB.Parity  = parity;          // 0-4=no,odd,even,mark,space
  }
  else {
    fDCB.fParity  = FALSE;          // disable parity checking
    fDCB.Parity   = NOPARITY;       // just to make sure
  }
  if (numStop == 1) 
    fDCB.StopBits = ONESTOPBIT;     // one stop bit
  else if (numStop == 2) 
    fDCB.StopBits = TWOSTOPBITS;    // two stop bit
  else
    fDCB.StopBits = ONE5STOPBITS;   // 1.5 stop bit
  fDCB.fRtsControl = (RTS != 0);    // RTS off(=0=-12V) or on(=1=+12V)
  fDCB.fDtrControl = (DTR != 0);    // DTR off(=0=-12V) or on(=1=+12V)

  // set new COM state
  fSuccess = SetCommState(fpCom, &fDCB);
  if (!fSuccess) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'set_port_attribute()': set port attributes failed with code %d, exit!\n\n", (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }


  // set timeouts for port to avoid hanging of program. For simplicity set all timeouts to same value.
  // For timeout=0 set values to query for buffer content
  if (timeout == 0)
    fTimeout.ReadIntervalTimeout        = MAXDWORD;    // --> no read timeout
  else
    fTimeout.ReadIntervalTimeout        = 0;           // max. ms between following read bytes (0=not used)
  fTimeout.ReadTotalTimeoutMultiplier   = 0;           // time per read byte (use contant timeout instead)
  fTimeout.ReadTotalTimeoutConstant     = timeout;     // total read timeout in ms
  fTimeout.WriteTotalTimeoutMultiplier  = 0;           // time per write byte (use contant timeout instead) 
  fTimeout.WriteTotalTimeoutConstant    = timeout;
  fSuccess = SetCommTimeouts(fpCom, &fTimeout);
  if (!fSuccess) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'set_port_attribute()': set port timeout failed with code %d, exit!\n\n", (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }

#endif // WIN32


/////////
// Posix
/////////
#if defined(__APPLE__) || defined(__unix__) 

  struct termios  toptions;
  int             status;
  
  
  // get attributes
  if (tcgetattr(fpCom, &toptions) < 0) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'set_port_attribute()': get port attributes failed, exit!\n\n");
    Exit(1, g_pauseOnExit);
  }
  
  // set baudrate
  speed_t brate = baudrate; // let you override switch below if needed
  switch(baudrate) {
#ifdef B4800
    case 4800:   brate=B4800;   break;
#endif
#ifdef B9600
    case 9600:   brate=B9600;   break;
#endif
#ifdef B14400
    case 14400:  brate=B14400;  break;
#endif
#ifdef B19200
    case 19200:  brate=B19200;  break;
#endif
#ifdef B28800
    case 28800:  brate=B28800;  break;
#endif
#ifdef B38400
    case 38400:  brate=B38400;  break;
#endif
#ifdef B57600
    case 57600:  brate=B57600;  break;
#endif
#ifdef B115200
    case 115200: brate=B115200; break;
#endif
#ifdef B230400
    case 230400: brate=B230400; break;
#endif
    default: 
      setConsoleColor(PRM_COLOR_RED);
      fprintf(stderr, "\n\nerror in 'set_port_attribute()': unsupported baudrate %d Baud, exit!\n\n", (int) baudrate);
      Exit(1, g_pauseOnExit);
  }
  cfsetispeed(&toptions, brate);    // receive
  cfsetospeed(&toptions, brate);    // send
  
  if (numBits == 7)
    toptions.c_cflag |=  CS7;       // 8 data bits
  else
    toptions.c_cflag |=  CS8;       // 8 data bits
  toptions.c_cflag &= ~PARENB;      // no parity
  //toptions.c_cflag |=  PARENB;    // with parity
  if (numStop == 1)
    toptions.c_cflag &= ~CSTOPB;    // one stop bit
  else
    toptions.c_cflag |= CSTOPB;     // two stop bit
  toptions.c_cflag &= ~CSIZE;       // clear data bits entry
  
  // disable flow control
  toptions.c_cflag &= ~CRTSCTS;
  toptions.c_cflag |= CREAD | CLOCAL;  // turn on READ & ignore ctrl lines
  toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
  
  // make raw
  toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
  toptions.c_oflag &= ~OPOST; // make raw
  
  // set timeout (see: http://unixwiz.net/techtips/termios-vmin-vtime.html)
  toptions.c_cc[VMIN]  = 255;
  toptions.c_cc[VTIME] = timeout/100;   // convert ms to 0.1s
  
  // set term properties
  if (tcsetattr(fpCom, TCSANOW, &toptions) < 0) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'set_port_attribute()': set port attributes failed, exit!\n\n");
    Exit(1, g_pauseOnExit);
  }
  
  
  // set static RTS and DTR status (required for some multimeter optocouplers)
  ioctl(fpCom, TIOCMGET, &status);
  if (RTS==1)
    status |= TIOCM_RTS;
  else
    status &= ~TIOCM_RTS;
  if (DTR==1)
    status |= TIOCM_DTR;
  else
    status &= ~TIOCM_DTR;
  if (ioctl(fpCom, TIOCMSET, &status)) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'set_port_attribute()': cannot set RTS status, exit!\n\n");
    Exit(1, g_pauseOnExit);
  }
  
#endif // __APPLE__ || __unix__

     
} // set_port_attribute
Пример #16
0
/**
  \fn void get_port_attribute(HANDLE fpCom, uint32_t *baudrate, uint32_t *timeout, uint8_t *numBits, uint8_t *parity, uint8_t *numStop, uint8_t *RTS, uint8_t *DTR)
   
  \brief get comm port settings
   
  \param[in]  fpCom      handle to comm port
  \param[out] baudrate   comm port speed in Baud
  \param[out] timeout    timeout between chars in ms
  \param[out] numBits    number of data bits per byte
  \param[out] parity     parity control by HW
  \param[out] numStop    number of stop bits
  \param[out] RTS        Request To Send (required for some multimeter optocouplers)
  \param[out] DTR        Data Terminal Ready (required for some multimeter optocouplers)

  get current attributes of an already open comm port.
*/
void get_port_attribute(HANDLE fpCom, uint32_t *baudrate, uint32_t *timeout, uint8_t *numBits, uint8_t *parity, uint8_t *numStop, uint8_t *RTS, uint8_t *DTR) {

/////////
// Win32
/////////
#ifdef WIN32

  DCB           fDCB;
  COMMTIMEOUTS  fTimeout;
  BOOL          fSuccess;

  // get the current port configuration
  fSuccess = GetCommState(fpCom, &fDCB);
  if (!fSuccess) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'get_port_attribute': GetCommState() failed with code %d, exit!\n\n", (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }

  // get port settings
  *baudrate = fDCB.BaudRate;        // baud rate (19200, 57600, 115200)
  *numBits  = fDCB.ByteSize;        // number of data bits per byte
  *parity   = fDCB.Parity;          // parity bit by HW
  *numStop  = fDCB.StopBits;        // number of stop bits
  if (fDCB.StopBits == ONESTOPBIT) 
    *numStop = 1;                      // 1 stop bit
  else if (fDCB.StopBits == TWOSTOPBITS) 
    *numStop = 2;                      // 2 stop bits
  else
    *numStop = 3;                      // 1.5 stop bits
  *RTS      = fDCB.fRtsControl;     // RTS off(=0=-12V) or on(=1=+12V)
  *DTR      = fDCB.fDtrControl;     // DTR off(=0=-12V) or on(=1=+12V)
  
  // get port timeout
  fSuccess = GetCommTimeouts(fpCom, &fTimeout);
  if (!fSuccess) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'get_port_attribute': GetCommTimeouts() failed with code %d, exit!\n\n", (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }
  *timeout = fTimeout.ReadTotalTimeoutConstant;       // this parameter fits also for timeout=0
  
#endif // WIN32


/////////
// Posix
/////////
#if defined(__APPLE__) || defined(__unix__) 

  struct termios  toptions;
  int             status;
  
  
  // get attributes
  if (tcgetattr(fpCom, &toptions) < 0) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'get_port_attribute': get port attributes failed, exit!\n\n");
    Exit(1, g_pauseOnExit);
  }
  
  
  // get baudrate
  speed_t brate = cfgetospeed(&toptions);
  switch (brate) {
#ifdef B4800
    case B4800:    *baudrate = 4800;    break;
#endif
#ifdef B9600
    case B9600:    *baudrate = 9600;    break;
#endif
#ifdef B14400
    case B14400:   *baudrate = 14400;   break;
#endif
#ifdef B19200
    case B19200:   *baudrate = 19200;   break;
#endif
#ifdef B28800
    case B28800:   *baudrate = 28800;   break;
#endif
#ifdef B38400
    case B38400:   *baudrate = 38400;   break;
#endif
#ifdef B57600
    case B57600:   *baudrate = 57600;   break;
#endif
#ifdef B115200
    case B115200:  *baudrate = 115200;  break;
#endif
#ifdef B230400
    case B230400:  *baudrate = 230400;  break;
#endif
    default: *baudrate = UINT32_MAX;
  } // switch (brate)
  
  
  // get timeout (see: http://unixwiz.net/techtips/termios-vmin-vtime.html)
  *timeout = toptions.c_cc[VTIME] * 100;   // convert 0.1s to ms
  
  
  // number of bits
  if (toptions.c_cflag & CS8)
    *numBits = 8;
  else
    *numBits = 7;
  
  
  // get parity
  if (toptions.c_cflag & PARENB)
    *parity = 1;
  else
    *parity = 0;
  
  
  // get number of stop bits
  if (toptions.c_cflag | CSTOPB)
    *numStop = 2;
  else
    *numStop = 1;
  

  // get static RTS and DTR status (required for some multimeter optocouplers)
  ioctl(fpCom, TIOCMGET, &status);
  if (status | TIOCM_RTS)
    *RTS = 1;
  else
    *RTS = 0;
  if (status | TIOCM_DTR)
    *DTR = 1;
  else
    *DTR = 0;

#endif // __APPLE__ || __unix__
     
} // get_port_attribute
Пример #17
0
void setDefConsoleColor(void)
{
	setConsoleColor(DEF_COLOR);
}
Пример #18
0
/**
  \fn void list_ports(void)
   
  \brief print list all available comm ports
   
  print list of all available COM ports. I don't know how to do this in
  a better way than to actually try and open each of them...
*/
void list_ports(void) {
  
/////////
// Win32
/////////
#if defined(WIN32)

  HANDLE        fpCom = NULL;
  uint16_t      i, j;
  char          port_tmp[100];
    
  // loop 1..255 over ports and list each available
  j=1;
  for (i=1; i<=255; i++) {

    // required to allow COM ports >COM9
    sprintf(port_tmp,"\\\\.\\COM%d", i);    
  
    // try to open COM-port
    fpCom = CreateFile(port_tmp,
      GENERIC_READ | GENERIC_WRITE,  // both read & write
      0,    // must be opened with exclusive-access
      NULL, // no security attributes
      OPEN_EXISTING, // must use OPEN_EXISTING
      0,    // not overlapped I/O
      NULL  // hTemplate must be NULL for comm devices
    );
    if (fpCom != INVALID_HANDLE_VALUE) {
      if (j!=1) printf(", ");
      printf("COM%d", i);
      CloseHandle(fpCom);
      j++;
    }
  }
  
#endif // WIN32


/////////
// Posix
/////////
#if defined(__APPLE__) || defined(__unix__) 

  // list all /dev/tty.usbserial-* (see http://bytes.com/groups/net-vc/545618-list-files-current-directory)
  uint16_t        i;
  struct dirent   *ent;
  DIR             *dir = opendir("/dev");
  if(dir) {
    i = 1;
    while((ent = readdir(dir)) != NULL) {
      
      // FTDI FT232 based USB-RS232 adapter (MacOS X)
      if (strstr(ent->d_name, "tty.usbserial")) {
        if (i!=1) printf(", ");
        printf("/dev/%s", ent->d_name);
        i++;
      }

      // Prolific PL2303 based USB-RS232 adapter
      if (strstr(ent->d_name, "tty.PL2303")) {
        if (i!=1) printf(", ");
        printf("/dev/%s", ent->d_name);
        i++;
      }
      
      // FTDI FT232 based USB-RS232 adapter (Ubuntu)
      if (strstr(ent->d_name, "ttyUSB")) {
        if (i!=1) printf(", ");
        printf("/dev/%s", ent->d_name);
        i++;
      }

      // direct UART under Raspberry Pi / Raspbian
      if (strstr(ent->d_name, "ttyAMA")) {
        if (i!=1) printf(", ");
        printf("/dev/%s", ent->d_name);
        i++;
      }

    }
  }
  else {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "cannot list, see /dev/tty*");
  }
  fflush(stdout);

#endif // __APPLE__ || __unix__

} // list_ports
Пример #19
0
/**
  \fn HANDLE init_port(const char *port, uint32_t baudrate, uint32_t timeout, uint8_t numBits, uint8_t parity, uint8_t numStop, uint8_t RTS, uint8_t DTR)
   
  \brief open comm port
   
  \param[in] port       name of port as string
  \param[in] baudrate   comm port speed in Baud
  \param[in] timeout    timeout between chars in ms
  \param[in] numBits    number of data bits per byte
  \param[in] parity     parity control by HW (0=none, 1=odd, 2=even)
  \param[in] numStop    number of stop bits (1=1; 2=2; other=1.5)
  \param[in] RTS        Request To Send (required for some multimeter optocouplers)
  \param[in] DTR        Data Terminal Ready (required for some multimeter optocouplers)

  \return           handle to comm port
  
  open comm port for communication, set properties (baudrate, timeout,...). 
  Note: baudrate must be supported by COM port driver. 
*/
HANDLE init_port(const char *port, uint32_t baudrate, uint32_t timeout, uint8_t numBits, uint8_t parity, uint8_t numStop, uint8_t RTS, uint8_t DTR) {

  
/////////
// Win32
/////////
#if defined(WIN32)

  char          port_tmp[100];
  HANDLE        fpCom = NULL;
  DCB           fDCB;
  BOOL          fSuccess;
  COMMTIMEOUTS  fTimeout;
    
  // required to allow COM ports >COM9
  sprintf(port_tmp,"\\\\.\\%s", port);    
  
  // create handle to COM-port
  fpCom = CreateFile(port_tmp,
    GENERIC_READ | GENERIC_WRITE,  // both read & write
    0,    // must be opened with exclusive-access
    NULL, // no security attributes
    OPEN_EXISTING, // must use OPEN_EXISTING
    0,    // not overlapped I/O
    NULL  // hTemplate must be NULL for comm devices
  );
  if (fpCom == INVALID_HANDLE_VALUE) {
    setConsoleColor(PRM_COLOR_RED);
    fpCom = NULL;
    fprintf(stderr, "\n\nerror in 'init_port(%s)': open port failed with code %d, exit!\n\n", port, (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }

  // reset COM port error buffer
  PurgeComm(fpCom, PURGE_RXABORT | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_TXCLEAR);
  
  // get the current port configuration
  fSuccess = GetCommState(fpCom, &fDCB);
  if (!fSuccess) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'init_port(%s)': get port attributes failed with code %d, exit!\n\n", port, (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }

  // change port settings
  fDCB.BaudRate = baudrate;         // set the baud rate (19200, 57600, 115200)
  fDCB.ByteSize = numBits;          // number of data bits per byte
  if (parity) {
    fDCB.fParity = TRUE;            // Enable parity checking
    fDCB.Parity  = parity;          // 0-4=no,odd,even,mark,space
  }
  else {
    fDCB.fParity  = FALSE;          // disable parity checking
    fDCB.Parity   = NOPARITY;       // just to make sure
  }
  if (numStop == 1) 
    fDCB.StopBits = ONESTOPBIT;     // one stop bit
  else if (numStop == 2) 
    fDCB.StopBits = TWOSTOPBITS;    // two stop bit
  else
    fDCB.StopBits = ONE5STOPBITS;   // 1.5 stop bit
  fDCB.fRtsControl = (RTS != 0);    // RTS off(=0=-12V) or on(=1=+12V)
  fDCB.fDtrControl = (DTR != 0);    // DTR off(=0=-12V) or on(=1=+12V)

  // set new COM state
  fSuccess = SetCommState(fpCom, &fDCB);
  if (!fSuccess) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'init_port(%s)': set port attributes failed with code %d, exit!\n\n", port, (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }


  // set timeouts for port to avoid hanging of program. For simplicity set all timeouts to same value.
  // For timeout=0 set values to query for buffer content
  if (timeout == 0)
    fTimeout.ReadIntervalTimeout        = MAXDWORD;    // --> no read timeout
  else
    fTimeout.ReadIntervalTimeout        = 0;           // max. ms between following read bytes (0=not used)
  fTimeout.ReadTotalTimeoutMultiplier   = 0;           // time per read byte (use contant timeout instead)
  fTimeout.ReadTotalTimeoutConstant     = timeout;     // total read timeout in ms
  fTimeout.WriteTotalTimeoutMultiplier  = 0;           // time per write byte (use contant timeout instead) 
  fTimeout.WriteTotalTimeoutConstant    = timeout;
  fSuccess = SetCommTimeouts(fpCom, &fTimeout);
  if (!fSuccess) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'init_port(%s)': set port timeout failed with code %d, exit!\n\n", port, (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }

  // return hande
  return(fpCom);

#endif // WIN32


/////////
// Posix
/////////
#if defined(__APPLE__) || defined(__unix__) 

  HANDLE          fpCom;
  struct termios  toptions;
  int             status;

  // open port
  fpCom = open(port, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
  if (fpCom == -1) {
    setConsoleColor(PRM_COLOR_RED);
    fpCom = 0;
    fprintf(stderr, "\n\nerror in 'init_port(%s)': open port failed, exit!\n\n", port);
    Exit(1, g_pauseOnExit);
  }
  //fcntl(fpCom, F_SETFL, O_RDWR);    // makes communication VERY slow -> skip
  
  // get attributes
  if (tcgetattr(fpCom, &toptions) < 0) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'init_port(%s)': get port attributes failed, exit!\n\n", port);
    Exit(1, g_pauseOnExit);
  }

  // set baudrate
  speed_t brate = baudrate; // let you override switch below if needed
  switch(baudrate) {
#ifdef B4800
    case 4800:   brate=B4800;   break;
#endif
#ifdef B9600
    case 9600:   brate=B9600;   break;
#endif
#ifdef B14400
    case 14400:  brate=B14400;  break;
#endif
#ifdef B19200
    case 19200:  brate=B19200;  break;
#endif
#ifdef B28800
    case 28800:  brate=B28800;  break;
#endif
#ifdef B38400
    case 38400:  brate=B38400;  break;
#endif
#ifdef B57600
    case 57600:  brate=B57600;  break;
#endif
#ifdef B115200
    case 115200: brate=B115200; break;
#endif
#ifdef B230400
    case 230400: brate=B230400; break;
#endif
    default: 
      setConsoleColor(PRM_COLOR_RED);
      fprintf(stderr, "\n\nerror in 'init_port(%s)': unsupported baudrate %d Baud, exit!\n\n", port, (int) baudrate);
      Exit(1, g_pauseOnExit);
  }
  cfmakeraw(&toptions);
  cfsetispeed(&toptions, brate);    // receive
  cfsetospeed(&toptions, brate);    // send

  if (numBits == 7)
    toptions.c_cflag |=  CS7;       // 8 data bits
  else
    toptions.c_cflag |=  CS8;       // 8 data bits
  if (parity == 0)
    toptions.c_cflag &= ~PARENB;    // 0=no parity
  else if (parity==1) {             // 1=odd parity
    toptions.c_cflag |=  PARENB;
    toptions.c_cflag |=  PARODD;
  }
  else if (parity==2) {             // even parity
    toptions.c_cflag |=  PARENB;
    toptions.c_cflag &=  ~PARODD;
  }
  if (numStop == 1) 
    toptions.c_cflag &= ~CSTOPB;    // one stop bit
  else
    toptions.c_cflag |= CSTOPB;     // two stop bit
  //toptions.c_cflag &= ~CSIZE;       // xxx clear data bits entry. Doesn't work on RasPi -> skip

  // disable flow control
  toptions.c_cflag &= ~CRTSCTS;
  toptions.c_cflag |= CREAD | CLOCAL;  // turn on READ & ignore ctrl lines
  toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl

  // make raw
  toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
  toptions.c_oflag &= ~OPOST; // make raw
  
  // set timeout (see: http://unixwiz.net/techtips/termios-vmin-vtime.html)
  toptions.c_cc[VMIN]  = 255;
  toptions.c_cc[VTIME] = timeout/100;   // convert ms to 0.1s

  // set term properties
  if (tcsetattr(fpCom, TCSANOW | TCSAFLUSH, &toptions) < 0) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'init_port(%s)': set port attributes failed, exit!\n\n", port);
    Exit(1, g_pauseOnExit);
  }

  // set static RTS and DTR status (required for some multimeter optocouplers)
  ioctl(fpCom, TIOCMGET, &status);
  if (RTS==1)
    status |= TIOCM_RTS;
  else
    status &= ~TIOCM_RTS;
  if (DTR==1)
    status |= TIOCM_DTR;
  else
    status &= ~TIOCM_DTR;
  if (ioctl(fpCom, TIOCMSET, &status)) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'init_port(%s)': cannot set RTS status, exit!\n\n", port);
    Exit(1, g_pauseOnExit);
  }

  // wait 10ms
  usleep(10000);
  
  // return comm port handle
  return fpCom;

#endif // __APPLE__ || __unix__

} // init_port
Пример #20
0
void basicRealCalc()
{
    int userChoise = 0;
    int flag = 1;
    float result = 0;
    float tempResult = 0;
    char operatorCalc = 'a';

    system("cls");

    setConsoleColor(FOREGROUND_BLUE | FOREGROUND_INTENSITY);
        //textcolor(BRIGHT, RED, BLACK);

        printf ("########################################\n");
        printf ("#### Welcome on calculator for float ###\n");
        printf ("########################################\n");
        printf ("\n");
        fflush(stdout);

        printf ("########################################\n");
        printf ("# Calc is done sequencialy             #\n");
        printf ("# 1 : enter your number                #\n");
        printf( "# 2 : enter your operator              #\n");
        printf ("# 3 : repeat                           #\n");
        printf ("# 4 : q to quit                        #\n");
        printf ("########################################\n");
        printf ("\n");
        fflush(stdout);

        /* Restore original attributes */
        setConsoleColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);

    result = mathInputFloat();

    while(flag){

        tempResult = result;
        operatorCalc = mathInputChar();
        result = mathInputFloat();

        //Print calc to see steps
            if(operatorCalc == '+'){
                printf("=> %d + %d = ", tempResult, result);
                result = tempResult + result;
            }else if(operatorCalc == '-'){
                printf("=> %d - %d = ", tempResult, result);
                result = tempResult - result;
            }else if(operatorCalc == 'x'){
                printf("=> %d x %d = ", tempResult, result);
                result = tempResult * result;
            }else if(operatorCalc == '/'){
                printf("=> %d / %d = ", tempResult, result);
                result = tempResult / result;
            }else if(operatorCalc == 'q'){
                calculatorHomeDisplay();
                userChoise = userInputInt(3);
                calculatorHomeUse(userChoise);
            }
        printf("%f\n", result);
    }
}
Пример #21
0
/**
  \fn uint32_t receive_port(HANDLE fpCom, uint32_t lenRx, char *Rx)
   
  \brief receive data via comm port
  
  \param[in]  fpCom   handle to comm port
  \param[in]  lenRx   number of bytes to receive
  \param[out] Rx      array containing bytes received
  
  \return number of received bytes
  
  receive data via comm port. Use this function to facilitate serial communication
  on different platforms, e.g. Win32 and Posix
  If g_UARTmode==2 (UART reply mode with 2-wire interface), reply each byte from STM8 -> SLOW
*/
uint32_t receive_port(HANDLE fpCom, uint32_t lenRx, char *Rx) {

  
/////////
// Win32
/////////
#ifdef WIN32

  DWORD     numChars, numTmp;
  uint32_t  i, numRx;
  
  // for UART reply mode with 2-wire interface echo each received bytes -> SLOW
  if (g_UARTmode==2) {
    
    // echo each byte as it is received
    numChars = 0;
    for (i=0; i<lenRx; i++) {
      ReadFile(fpCom, Rx+i, 1, &numTmp, NULL);
      if (numTmp == 1) {
        numChars++;
        send_port(fpCom, 1, Rx+i);
      }
      else
        break;
    } // loop i
  
  } // g_UARTmode==2
  
  
  // UART duplex mode or 1-wire interface -> receive all bytes in single block -> fast
  else {
    ReadFile(fpCom, Rx, lenRx, &numChars, NULL);
  }
  
  // return number of bytes received
  return((uint32_t) numChars);

#endif // WIN32


/////////
// Posix
/////////
#if defined(__APPLE__) || defined(__unix__) 

  char            *dest = Rx;
  uint32_t        remaining = lenRx, got = 0, received = 0;
  struct          timeval tv;
  fd_set          fdr;
  struct termios  toptions;
  uint32_t        timeout;
  
  // get terminal attributes
  if (tcgetattr(fpCom, &toptions) < 0) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'receive_port': get port attributes failed, exit!\n\n");
    Exit(1, g_pauseOnExit);
  }
  
  // get terminal timeout (see: http://unixwiz.net/techtips/termios-vmin-vtime.html)
  timeout = toptions.c_cc[VTIME] * 100;        // convert 0.1s to ms
  
  // while there are bytes left to read...
  while (remaining != 0) {
   
    // reinit timeval structure each time through loop
    tv.tv_sec  = (timeout / 1000L);
    tv.tv_usec = (timeout % 1000L) * 1000L;

    // wait for data to come in using select
    FD_ZERO(&fdr);
    FD_SET(fpCom, &fdr);
    if (select(fpCom + 1, &fdr, NULL, NULL, &tv) != 1) {
      return(received);
    }

    // read a response, we know there's data waiting
    got = read(fpCom, dest, remaining);
    
    // handle errors. retry on EAGAIN, fail on anything else, ignore if no bytes read
    if (got == -1) {
      if (errno == EAGAIN)
        continue;
      else
        return(received);
    } 
    else if (got > 0) {
      
      // for UART reply mode with 2-wire interface echo each byte
      if (g_UARTmode==2) {
        //fprintf(stderr,"sent echo %dB 0x%02x\n", (int) lenRx, Rx[0]);
        send_port(fpCom, 1, dest);
      }
      
      // figure out how many bytes are left and increment dest pointer through buffer
      dest += got;
      remaining -= got;
      received += got;
      
    } // received bytes

  } // while (remaining != 0)

  // return number of received bytes
  return(received);
  
#endif // __APPLE__ || __unix__

} // receive_port
Пример #22
0
/**
   \fn int main(int argc, char *argv[])
   
   \brief main routine
   
   \param argc      number of commandline arguments + 1
   \param argv      string array containing commandline arguments (argv[0] contains name of executable)
   
   \return dummy return code (not used)
   
   Main routine for import, programming, and check routines
*/
int main(int argc, char ** argv) {
 
  char      *appname;             // name of application without path
  char      portname[STRLEN];     // name of communication port
  int       baudrate;             // communication baudrate [Baud]
  uint8_t   resetSTM8;            // 0=no reset; 1=HW reset via DTR (RS232/USB) or GPIO18 (Raspi); 2=SW reset by sending 0x55+0xAA
  uint8_t   enableBSL;            // don't enable ROM bootloader after upload (caution!)
  uint8_t   jumpFlash;            // jump to flash after upload
  uint8_t   pauseOnLaunch;        // prompt for <return> prior to upload
  int       flashsize;            // size of flash (kB) for w/e routines
  uint8_t   versBSL;              // BSL version for w/e routines
  char      hexfile[STRLEN];      // name of file to flash
  HANDLE    ptrPort;              // handle to communication port
  char      buf[BUFSIZE];         // buffer for hexfiles
  char      image[BUFSIZE];       // memory image buffer
  uint32_t  imageStart;           // starting address of image
  uint32_t  numBytes;             // number of bytes in image
  char      *ptr=NULL;            // pointer to memory
  int       i, j;                 // generic variables  
  //char      Tx[100], Rx[100];     // debug: buffer for tests
  

  // initialize global variables
  g_pauseOnExit = 1;            // wait for <return> before terminating
  g_UARTmode    = 0;            // 2-wire interface with UART duplex mode
  verbose       = false;        // verbose output when requested only
  
  // initialize default arguments
  portname[0] = '\0';           // no default port name
  baudrate   = 230400;          // default baudrate
  resetSTM8  = 0;               // don't automatically reset STM8
  jumpFlash  = 1;               // jump to flash after uploade
  pauseOnLaunch = 1;            // prompt for return prior to upload
  enableBSL  = 1;               // enable bootloader after upload
  hexfile[0] = '\0';            // no default hexfile
  
  // for debugging only
  //sprintf(portname, "/dev/tty.usbserial-A4009I0O");

  // required for strncpy()
  portname[STRLEN-1]  = '\0';
  hexfile[STRLEN-1]   = '\0';
    
    
  // reset console color (needs to be called once for Win32)      
  setConsoleColor(PRM_COLOR_DEFAULT);


  ////////
  // parse commandline arguments
  ////////
  for (i=1; i<argc; i++) {
    
    // debug: print argument
    //printf("arg %d: '%s'\n", (int) i, argv[i]);
    
    // name of communication port
    if (!strcmp(argv[i], "-p"))
      strncpy(portname, argv[++i], STRLEN-1);

    // communication baudrate
    else if (!strcmp(argv[i], "-b"))
      sscanf(argv[++i],"%d",&baudrate);

    // UART mode: 0=duplex, 1=1-wire reply, 2=2-wire reply (default: duplex)\n");
    else if (!strcmp(argv[i], "-u")) {
      sscanf(argv[++i], "%d", &j);
      g_UARTmode = j;
    }

    // name of hexfile
    else if (!strcmp(argv[i], "-f"))
      strncpy(hexfile, argv[++i], STRLEN-1);

    // HW reset STM8 via DTR line (RS232/USB) or GPIO18 (Raspi only)
    else if (!strcmp(argv[i], "-r")) {
      sscanf(argv[++i], "%d", &j);
      resetSTM8 = j;
    }
    
    // don't enable ROM bootloader after upload (caution!)
    else if (!strcmp(argv[i], "-x"))
      enableBSL = 0;

    // don't jump to address after upload
    else if (!strcmp(argv[i], "-j"))
      jumpFlash = 0;

    // don't prompt for <return> prior to upload
    else if (!strcmp(argv[i], "-Q"))
      pauseOnLaunch = 0;

    // don't prompt for <return> prior to exit
    else if (!strcmp(argv[i], "-q"))
      g_pauseOnExit = 0;

    // verbose output
    else if (!strcmp(argv[i], "-v"))
      verbose = true;

    // else print list of commandline arguments and language commands
    else {
      if (strrchr(argv[0],'\\'))
        appname = strrchr(argv[0],'\\')+1;         // windows
      else if (strrchr(argv[0],'/'))
        appname = strrchr(argv[0],'/')+1;          // Posix
      else
        appname = argv[0];
      printf("\n");
      printf("usage: %s [-h] [-p port] [-b rate] [-u mode] [-f file] [-r ch] [-x] [-j] [-Q] [-q] [-v]\n\n", appname);
      printf("  -h        print this help\n");
      printf("  -p port   name of communication port (default: list all ports and query)\n");
      printf("  -b rate   communication baudrate in Baud (default: 230400)\n");
      printf("  -u mode   UART mode: 0=duplex, 1=1-wire reply, 2=2-wire reply (default: duplex)\n");
      printf("  -f file   name of s19 or intel-hex file to flash (default: none)\n");
      #ifdef __ARMEL__
        printf("  -r ch     reset STM8: 1=DTR line (RS232), 2=send 'Re5eT!' @ 115.2kBaud, 3=GPIO18 pin (Raspi) (default: no reset)\n");
      #else
        printf("  -r ch     reset STM8: 1=DTR line (RS232), 2=send 'Re5eT!' @ 115.2kBaud (default: no reset)\n");
      #endif
      printf("  -x        don't enable ROM bootloader after upload (default: enable)\n");
      printf("  -j        don't jump to flash after upload (default: jump to flash)\n");
      printf("  -Q        don't prompt for <return> prior to upload (default: prompt)\n");
      printf("  -q        don't prompt for <return> prior to exit (default: prompt)\n");
      printf("  -v        verbose output\n");
      printf("\n");
      Exit(0, 0);
    }

  } // process commandline arguments
  
  

  ////////
  // print app name & version, and change console title
  ////////
  get_app_name(argv[0], VERSION, buf);
  printf("\n%s\n", buf);
  setConsoleTitle(buf);  
  
  
  ////////
  // if no port name is given, list all available ports and query
  ////////
  if (strlen(portname) == 0) {
    printf("  enter comm port name ( ");
    list_ports();
    printf(" ): ");
    scanf("%s", portname);
    getchar();
  } // if no comm port name

  // If specified import hexfile - do it early here to be able to report file read errors before others
  if (strlen(hexfile)>0) {
    const char *shortname = strrchr(hexfile, '/');
    if (!shortname)
      shortname = hexfile;

    // convert to memory image, depending on file type
    const char *dot = strrchr (hexfile, '.');
    if (dot && !strcmp(dot, ".s19")) {
      if (verbose)
        printf("  Loading Motorola S-record file %s …\n", shortname);
      load_hexfile(hexfile, buf, BUFSIZE);
      convert_s19(buf, &imageStart, &numBytes, image);
      }
    else if (dot && (!strcmp(dot, ".hex") || !strcmp(dot, ".ihx"))) {
      if (verbose)
        printf("  Loading Intel hex file %s …\n", shortname);
      load_hexfile(hexfile, buf, BUFSIZE);
      convert_hex(buf, &imageStart, &numBytes, image);
    }
    else {
      if (verbose)
        printf("  Loading binary file %s …\n", shortname);
      load_binfile(hexfile, image, &imageStart, &numBytes, BUFSIZE);
    }
  }

  ////////
  // put STM8 into bootloader mode
  ////////
  if (pauseOnLaunch) {
    printf("  activate STM8 bootloader and press <return>");
    fflush(stdout);
    fflush(stdin);
    getchar();
  }

  ////////
  // open port with given properties
  ////////
  printf("  open port '%s' with %gkBaud ... ", portname, (float) baudrate / 1000.0);
  fflush(stdout);
  if (g_UARTmode == 0)
    ptrPort = init_port(portname, baudrate, 1000, 8, 2, 1, 0, 0);   // use even parity
  else
    ptrPort = init_port(portname, baudrate, 1000, 8, 0, 1, 0, 0);   // use no parity
  printf("ok\n");
  fflush(stdout);
  
 
  // debug: communication test (echo+1 test-SW on STM8)
  /*
  printf("open: %d\n", ptrPort);
  for (i=0; i<254; i++) {
    Tx[0] = i;
    send_port(ptrPort, 1, Tx);
    receive_port(ptrPort, 1, Rx);
	printf("%d  %d\n", (int) Tx[0], (int) Rx[0]);
  }
  printf("done\n");
  Exit(1,0);
  */
  

  ////////
  // communicate with STM8 bootloader
  ////////

  // HW reset STM8 using DTR line (USB/RS232)
  if (resetSTM8 == 1) {
    printf("  reset via DTR ... ");
    pulse_DTR(ptrPort, 10);
    printf("done\n");
    SLEEP(5);                       // allow BSL to initialize
  }
  
  // SW reset STM8 via command 'Re5eT!' at 115.2kBaud (requires respective STM8 SW)
  else if (resetSTM8 == 2) {
    set_baudrate(ptrPort, 115200);    // expect STM8 SW to receive at 115.2kBaud
    printf("  reset via UART command ... ");
    sprintf(buf, "Re5eT!");           // reset command (same as in STM8 SW!)
    for (i=0; i<6; i++) {
      send_port(ptrPort, 1, buf+i);   // send reset command bytewise to account for slow handling
      SLEEP(10);
    }
    printf("done\n");
    set_baudrate(ptrPort, baudrate);  // restore specified baudrate
  }
  
  // HW reset STM8 using GPIO18 pin (only Raspberry Pi!)
  #ifdef __ARMEL__
    else if (resetSTM8 == 3) {
      printf("  reset via GPIO18 ... ");
      pulse_GPIO(18, 10);
      printf("done\n");
      SLEEP(5);                       // allow BSL to initialize
    }
  #endif // __ARMEL__
  
  // synchronize baudrate
  bsl_sync(ptrPort);
  
  // get bootloader info for selecting flash w/e routines
  bsl_getInfo(ptrPort, &flashsize, &versBSL);

  // select device dependent flash routines for upload
  if ((flashsize==32) && (versBSL==0x10)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_32K_ver_1_0_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_32K_ver_1_0_s19_len]=0;
  }
  else if ((flashsize==32) && (versBSL==0x12)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_32K_ver_1_2_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_32K_ver_1_2_s19_len]=0;
  }
  else if ((flashsize==32) && (versBSL==0x13)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_32K_ver_1_3_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_32K_ver_1_3_s19_len]=0;
  }
  else if ((flashsize==32) && (versBSL==0x14)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_32K_ver_1_4_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_32K_ver_1_4_s19_len]=0;
  }
  else if ((flashsize==128) && (versBSL==0x20)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_128K_ver_2_0_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_128K_ver_2_0_s19_len]=0;
  }
  else if ((flashsize==128) && (versBSL==0x21)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_128K_ver_2_1_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_128K_ver_2_1_s19_len]=0;
  }
  else if ((flashsize==128) && (versBSL==0x22)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_128K_ver_2_2_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_128K_ver_2_2_s19_len]=0;
  }
  else if ((flashsize==128) && (versBSL==0x24)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_128K_ver_2_4_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_128K_ver_2_4_s19_len]=0;
  }
  else if ((flashsize==256) && (versBSL==0x10)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_256K_ver_1_0_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_256K_ver_1_0_s19_len]=0;
  }
  else {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror: unsupported device, exit!\n\n");
    Exit(1, g_pauseOnExit);
  }

  {
    char      ramImage[8192];
    uint32_t  ramImageStart;
    uint32_t  numRamBytes;

    convert_s19(ptr, &ramImageStart, &numRamBytes, ramImage);

    if (verbose)
      printf("Uploading RAM routines\n");
    bsl_memWrite(ptrPort, ramImageStart, numRamBytes, ramImage, 0);
  }

  // if specified upload hexfile
  if (strlen(hexfile)>0)
    bsl_memWrite(ptrPort, imageStart, numBytes, image, 1);
  
  // memory read
  //imageStart = 0x8000;  numBytes = 128*1024;   // complete 128kB flash
  //imageStart = 0x00A0;  numBytes = 352;        // RAM
  //bsl_memRead(ptrPort, imageStart, numBytes, image);
  
  
  // enable ROM bootloader after upload (option bytes always on same address)
  if (enableBSL==1) {
    printf("  activate bootloader ... ");
    bsl_memWrite(ptrPort, 0x487E, 2, (char*)"\x55\xAA", 0);
    printf("done\n");
  }
  
  // jump to flash start address after upload (reset vector always on same address)
  if (jumpFlash)
    bsl_jumpTo(ptrPort, 0x8000);
  
  
  ////////
  // clean up and exit
  ////////
  close_port(&ptrPort);
  if (verbose)
    printf("done with program\n");
  Exit(0, g_pauseOnExit);
  
  // avoid compiler warnings
  return(0);
  
} // main