Esempio n. 1
0
/*
  Fade from off to given color and back.
 */
void pulse(int w) {
  uint32_t c;
  //uint32_t c = Wheel(map(opt, 0, 1023, 0, 255)); 
  for(uint16_t j = 8; j <= getOpt(_pin_lev, 0, 255); j++) {
    if( checkButton() ){ return; };
    setBrightness(j);
    c = Wheel(map(opt, 0, 1023, 0, 255));
    for(uint16_t i = 0; i < numPixels(); i++) {
      setPixelColor(i, c);
    }
    show();
    delay(w);
  }
  delay(w*10+50);
  for(uint16_t j=getOpt(_pin_lev, 0, 255); j>8; j--) {
    if( checkButton() ){ return; };
    setBrightness(j);
    c = Wheel(map(opt, 0, 1023, 0, 255));
    for(uint16_t i = 0; i < numPixels(); i++) {
      setPixelColor(i, c);
    }
    show();
    delay(w);
  }
  delay(w*10+50);
}
BOOL AP_Win32Dialog_Columns::_onDeltaPos(NM_UPDOWN * pnmud)
{
	wchar_t buf[BUFSIZE];
	UT_Win32LocaleString str;
    
	switch( pnmud->hdr.idFrom )
	{
	case AP_RID_DIALOG_COLUMN_SPIN_NUMCOLUMNS:
		if( pnmud->iDelta < 0 )
		{
			setColumns( getColumns() + 1 );
		}
		else
		{
			if( getColumns() > 1 )
			{
				setColumns( getColumns() - 1 );
			}
		}
		SetDlgItemTextW(m_hDlg, AP_RID_DIALOG_COLUMN_EDIT_NUMCOLUMNS, _itow(getColumns(),buf,10));
		checkButton(AP_RID_DIALOG_COLUMN_RADIO_ONE, (getColumns()==1));
		checkButton(AP_RID_DIALOG_COLUMN_RADIO_TWO, (getColumns()==2));
		checkButton(AP_RID_DIALOG_COLUMN_RADIO_THREE, (getColumns()==3));
		return 1;

	case AP_RID_DIALOG_COLUMN_SPIN_SPACEAFTER:
		if( pnmud->iDelta < 0 )
		{
			incrementSpaceAfter( true );
		}
		else
		{
			incrementSpaceAfter( false );
		}
        str.fromUTF8 (getSpaceAfterString());
        SetDlgItemTextW(m_hDlg, AP_RID_DIALOG_COLUMN_EDIT_SPACEAFTER, str.c_str ());
		return 1;

	case AP_RID_DIALOG_COLUMN_SPIN_MAXSIZE:
		if( pnmud->iDelta < 0 )
		{
			incrementMaxHeight( true );
		}
		else
		{
			incrementMaxHeight( false );
		}
        str.fromUTF8 (getHeightString());
        SetDlgItemTextW(m_hDlg, AP_RID_DIALOG_COLUMN_EDIT_MAXSIZE, str.c_str ());
		return 1;

	default:
		return 0;
	}
}
Esempio n. 3
0
BOOL XAP_Win32Dialog_Zoom::_onInitDialog(HWND hWnd, WPARAM /*wParam*/, LPARAM /*lParam*/)
{		
	const XAP_StringSet* pSS = m_pApp->getStringSet();

	// Update the caption
	setDialogTitle(pSS->getValue(XAP_STRING_ID_DLG_Zoom_ZoomTitle));

	// localize controls
	_DSX(ZOOM_BTN_CLOSE,		DLG_Close);
	_DS(ZOOM_TEXT_ZOOMTO,		DLG_Zoom_RadioFrameCaption);
	_DS(ZOOM_RADIO_200,		DLG_Zoom_200);
	_DS(ZOOM_RADIO_100,		DLG_Zoom_100);
	_DS(ZOOM_RADIO_75,		DLG_Zoom_75);
	_DS(ZOOM_RADIO_WIDTH,		DLG_Zoom_PageWidth);
	_DS(ZOOM_RADIO_WHOLE,		DLG_Zoom_WholePage);
	_DS(ZOOM_RADIO_PCT,		DLG_Zoom_Percent);

	// set initial state
	checkButton(XAP_RID_DIALOG_ZOOM_RADIO_200 + m_zoomType);
	setControlInt(XAP_RID_DIALOG_ZOOM_EDIT_PCT, (UINT) m_zoomPercent);
	m_bEditPctEnabled = ((XAP_RID_DIALOG_ZOOM_RADIO_200 + m_zoomType) == XAP_RID_DIALOG_ZOOM_RADIO_PCT);
	enableControl(XAP_RID_DIALOG_ZOOM_EDIT_PCT ,m_bEditPctEnabled);
	
	SendMessageW(GetDlgItem(hWnd,XAP_RID_DIALOG_ZOOM_SPIN_PCT),UDM_SETRANGE,
				(WPARAM)0,(LPARAM)MAKELONG(XAP_DLG_ZOOM_MAXIMUM_ZOOM,XAP_DLG_ZOOM_MINIMUM_ZOOM));
		
	_updatePreviewZoomPercent(getZoomPercent());
	
	centerDialog();	
	
	return 1;							// 1 == we did not call SetFocus()
}
Esempio n. 4
0
void DateRangeSelectionWidget::Private::_k_anytimeClicked()
{
    checkButton( m_anytimeButton );
    setRange( DateRange() );

    emit q->rangeChanged( m_range );
}
Esempio n. 5
0
//Rainbow Program
void rainbowSingle() {
  setBrightness();
  //int wait = getOpt(_pin_opt, -20, 20);
  uint16_t i, j;
  for(j = 0; j < 256; j++) {

    // calculate wait based on volatile opt from interrupt
    int wait = (int) map(opt, 0, 1023, -100, 100);
    if( wait < 0 ) {
      // negative values make a huge apparent difference, so fake a larger spread
      // by having -100 to 100 instead of -20 to 100
      wait = floor( wait / 5 );
    }
    // kind of a hack to allow negative wait value to speed rainbow by
    // skipping colors, otherwise 0 would be fast as chip could process
    if(wait < 0 &&  j % ( -1 * wait ) != 0){
      continue; 
    }

    if( checkButton() ){ return; };
    for(i=0; i < numPixels(); i++) {
      setPixelColor(i, Wheel(j));
    }
    show();

    if(wait > 0){
      delay(wait);
    }

  }
}
QStringList MainWindow::checkElements(QDomElement element){
    QDomNode child = element.firstChild();
    QStringList errors;
    while (!child.isNull()) {
        QString tagName = child.toElement().tagName();
        if(tagName == "label") {
            errors << checkLabel(child.toElement());
        } else if (tagName == "line") {
            errors << checkLine(child.toElement());
        } else if (tagName == "button") {
            errors << checkButton(child.toElement());
        } else if (tagName == "lineEdit") {
            errors << checkLineEdit(child.toElement());
        } else if (tagName == "spinBox") {
            errors << checkSpinBox(child.toElement());
        } else if (tagName == "checkBox") {
            errors << checkCheckBox(child.toElement());
        } else if (tagName == "radioGroup") {
            errors << checkRadioGroup(child.toElement());
        } else if (tagName == "tweet") {
            errors << checkTweetWidget(child.toElement());
        } else if (tagName == "tabSet") {
            errors << checkTabLayout(child.toElement());
        } else if (tagName == "challongeMatch") {
            errors << checkChallongeWidget(child.toElement());
        } else if (tagName == "cli") {
            //errors << checkCLI(child.toElement());
        }
        child = child.nextSibling();
    }
    return errors;
}
BOOL EditBox::dispatch( HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch( msg )
        {
        case WM_INITDIALOG:

            initDlg( hDlg );
            return TRUE;

        case WM_COMMAND:

            switch( wParam )
                {
                case IDE_LOW:
                case IDE_MEDIUM:
                case IDE_HIGH:

                    checkButton( hDlg, wParam );
                    return TRUE;

                case IDOK:

                    okCmd( hDlg );
                    return TRUE;

                case IDCANCEL:

                    cancelCmd( hDlg );
                    return TRUE;
                }
        }

    return ModalDialog::dispatch( hDlg, msg, wParam, lParam );
}
void SmartMote::config(){
    AString conf;
    AStringList * param = NULL;
    bool flag;
    /*  se il bottone non è premuto                                             */
    if(!checkButton()){
        /*  ritorno                                                             */
        return;
    }
    /*  accendo l'uart                                                          */
    openUART();
    /*  inizializzo il modulo come AP                                           */
    if(!m_net.initialize(AESP07::APMode)){
        /*  se fallisce notifico l'errore                                       */
        error();
    }
    /*  setto il nome come SmartMote e password admin                           */
    if(!m_net.configureAP("SmartMote", "smartmote")){
        /*  se fallisce notifico l'errore                                       */
        error();        
    }
    /*  imposto l'ip a 192.168.1.1                                              */
    if(!m_net.setIp(AESP07::APMode, "192.168.1.1")){
        /*  se fallisce notifico l'errore                                       */
        error();        
    }
    /*  disabilito le connessioni multiple                                      */
    if(!m_net.setMultipleConnections(false)){
        /*  se fallisce notifico l'errore                                       */
        error();                
    }
    /*  apro il server sulla porta 8000                                         */
    if(!m_net.listen(8000)){
        /*  se fallisce notifico l'errore                                       */
        error();
    }
    /*  aspetto di ricevere la stringa                                          */
    while(conf.isEmpty()){
        
        m_net.waitForData(conf);
    }
    /*  prendo i parametri                                                      */
    param = conf.split(' ');
    /*  se la stringlist è allocata correttamente                               */
    if(param){
        saveSSID(param->at(0));
        saveKey(param->at(1));
        saveHost(param->at(2));
        RTCC.setHours(static_cast<uint32>(param->at(3).toInt32(flag)));
        RTCC.setMinutes(static_cast<uint32>(param->at(3).toInt32(flag)));
        RTCC.setSeconds(static_cast<uint32>(param->at(3).toInt32(flag)));
    }else{
        /*  altrimenti notifico l'errore                                        */
        error();
    }
    /*  spengo i led                                                            */
    turnOffRed();
    turnOffGreen();
}
Esempio n. 9
0
void volMeter(uint8_t startColor, uint8_t endColor){
  if( checkButton() ){ return; };
  uint8_t  i;
  uint16_t minLvl, maxLvl;
  int      n, height;

  n   = analogRead(_pin_mic);                        // Raw reading from mic 
  n   = abs(n - 512 - _dc_offset); // Center on zero
  n   = (n <= _noise) ? 0 : (n - _noise);             // Remove noise/hum
  lvl = ((lvl * 7) + n) >> 3;    // "Dampened" reading (else looks twitchy)

  // Calculate bar height based on dynamic min/max levels (fixed point):
  height = _top_offset * (lvl - minLvlAvg) / (long)(maxLvlAvg - minLvlAvg);

  if(height < 0L)       height = 0;      // Clip output
  else if(height > _top_offset) height = _top_offset;
  if(height > peak)     peak   = height; // Keep 'peak' dot at top

  // Color pixels based on rainbow gradient
  for(i=0; i<_led_per_grp; i++) {
    if(i >= height)               setPixelColor(i,   0,   0, 0);
    else setPixelColor(i,Wheel(map(i,0,_led_per_grp-1,startColor,endColor)));
    
  }

  // Draw peak dot  
  if(peak > 0 && peak <= _led_per_grp-1) setPixelColor(peak,Wheel(map(peak,0,_led_per_grp-1,startColor,endColor)));
  
   strip.show(); // Update strip

  // Every few frames, make the peak pixel drop by 1:
    if(++dotCount >= _fall_rate) { //fall rate 
      
      if(peak > 0) peak--;
      dotCount = 0;
    }

  vol[volCount] = n;                      // Save sample for dynamic leveling
  if(++volCount >= SAMPLES) volCount = 0; // Advance/rollover sample counter

  // Get volume range of prior frames
  minLvl = maxLvl = vol[0];
  for(i=1; i<SAMPLES; i++) {
    if(vol[i] < minLvl)      minLvl = vol[i];
    else if(vol[i] > maxLvl) maxLvl = vol[i];
  }
  // minLvl and maxLvl indicate the volume range over prior frames, used
  // for vertically scaling the output graph (so it looks interesting
  // regardless of volume level).  If they're too close together though
  // (e.g. at very low volume levels) the graph becomes super coarse
  // and 'jumpy'...so keep some minimum distance between them (this
  // also lets the graph go to zero when no sound is playing):
  if((maxLvl - minLvl) < _top_offset) maxLvl = minLvl + _top_offset;
  minLvlAvg = (minLvlAvg * 63 + minLvl) >> 6; // Dampen min/max levels
  maxLvlAvg = (maxLvlAvg * 63 + maxLvl) >> 6; // (fake rolling average)
} 
Esempio n. 10
0
//Rainbow Program
void rainbow() {
  int wait = getOpt(_pin_opt, 0, 255);
  uint16_t i, j;
  for(j = 0; j < 256; j++) {
    if( checkButton() ){ return; };
    for(i = 0; i < numPixels(); i++) {
      setPixelColor(i, Wheel((i + j) & 255));
    }
    show();
    delay(wait);
  }
}
Esempio n. 11
0
	void test()
	{
		for (unsigned x(0); x < buffer_.width(); x+=10) {
			for (unsigned y(0); y < buffer_.height(); y+=10) {
				movePointer(x, y);
				checkFocus(true);
				checkPointer(x, y);
			}
		}

		movePointer(-1, -1);
		checkFocus(false);

		movePointer(5, 5);
		checkFocus(true);

		inputKeySend(BTN_LEFT, 1);
		checkButton(BTN_LEFT, 1);

		inputKeySend(BTN_LEFT, 0);
		checkButton(BTN_LEFT, 0);

		inputKeySend(BTN_RIGHT, 1);
		checkButton(BTN_RIGHT, 1);

		inputKeySend(BTN_RIGHT, 0);
		checkButton(BTN_RIGHT, 0);

		inputKeySend(BTN_MIDDLE, 1);
		checkButton(BTN_MIDDLE, 1);

		inputKeySend(BTN_MIDDLE, 0);
		checkButton(BTN_MIDDLE, 0);
	}
Esempio n. 12
0
LRESULT PublicHubsFrame::onClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) {
	if(!closed) {
		FavoriteManager::getInstance()->removeListener(this);
		closed = true;
		PostMessage(WM_CLOSE);
		return 0;
	} else {
		WinUtil::saveHeaderOrder(ctrlHubs, SettingsManager::PUBLICHUBSFRAME_ORDER,
			SettingsManager::PUBLICHUBSFRAME_WIDTHS, COLUMN_LAST, columnIndexes, columnSizes);
		
		checkButton(false);

		bHandled = FALSE;
		return 0;
	}
}
Esempio n. 13
0
int PortableTester::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QMainWindow::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: buttonPressed((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 1: UnHide(); break;
        case 2: checkButton(); break;
        default: ;
        }
        _id -= 3;
    }
    return _id;
}
Esempio n. 14
0
// ------------------- FilterWidget
FilterWidget::FilterWidget(QWidget *parent, LayoutMode lm)  :
    QWidget(parent),
    m_editor(new HintLineEdit(this)),
    m_button(new IconButton(m_editor)),
    m_buttonwidth(0)
{
    m_editor->setPlaceholderText(tr("Filter"));

    // Let the style determine minimum height for our widget
    QSize size(ICONBUTTON_SIZE + 6, ICONBUTTON_SIZE + 2);

    // Note KDE does not reserve space for the highlight color
    if (style()->inherits("OxygenStyle")) {
        size = size.expandedTo(QSize(24, 0));
    }

    // Make room for clear icon
    QMargins margins = m_editor->textMargins();
    if (layoutDirection() == Qt::LeftToRight)
        margins.setRight(size.width());
    else
        margins.setLeft(size.width());

    m_editor->setTextMargins(margins);

    QHBoxLayout *l = new QHBoxLayout(this);
    l->setMargin(0);
    l->setSpacing(0);
    if (lm == LayoutAlignRight)
        l->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum));

    l->addWidget(m_editor);

    // KDE has custom icons for this. Notice that icon namings are counter intuitive
    // If these icons are not avaiable we use the freedesktop standard name before
    // falling back to a bundled resource
    QIcon icon = QIcon::fromTheme(layoutDirection() == Qt::LeftToRight ?
                     QLatin1String("edit-clear-locationbar-rtl") :
                     QLatin1String("edit-clear-locationbar-ltr"),
                     QIcon::fromTheme("edit-clear", createIconSet(QLatin1String("cleartext.png"))));

    m_button->setIcon(icon);
    m_button->setToolTip(tr("Clear text"));
    connect(m_button, SIGNAL(clicked()), this, SLOT(reset()));
    connect(m_editor, SIGNAL(textChanged(QString)), this, SLOT(checkButton(QString)));
    connect(m_editor, SIGNAL(textEdited(QString)), this, SIGNAL(filterChanged(QString)));
}
void XAP_Win32Dialog_HTMLOptions::refreshStates()
{
	// determine which controls are available.
	enableControl(XAP_RID_DIALOG_HTMLOPTIONS_CHK_XML,can_set_Declare_XML());
	enableControl(XAP_RID_DIALOG_HTMLOPTIONS_CHK_AWML,can_set_Allow_AWML());
	enableControl(XAP_RID_DIALOG_HTMLOPTIONS_CHK_EMBEDCSS,can_set_Embed_CSS());
	enableControl(XAP_RID_DIALOG_HTMLOPTIONS_CHK_URLIMAGE,can_set_Embed_Images());
	enableControl(XAP_RID_DIALOG_HTMLOPTIONS_CHK_SPLITFILE,can_set_Split_Document());

	// set initial state
	checkButton(XAP_RID_DIALOG_HTMLOPTIONS_CHK_HTML4,get_HTML4());
	checkButton(XAP_RID_DIALOG_HTMLOPTIONS_CHK_PHP,get_PHTML()); 
	checkButton(XAP_RID_DIALOG_HTMLOPTIONS_CHK_XML,get_Declare_XML());
	checkButton(XAP_RID_DIALOG_HTMLOPTIONS_CHK_AWML,get_Allow_AWML());
	checkButton(XAP_RID_DIALOG_HTMLOPTIONS_CHK_EMBEDCSS,get_Embed_CSS());
	checkButton(XAP_RID_DIALOG_HTMLOPTIONS_CHK_URLIMAGE,get_Embed_Images());
	checkButton(XAP_RID_DIALOG_HTMLOPTIONS_CHK_PNGMATHML,get_MathML_Render_PNG());
	checkButton(XAP_RID_DIALOG_HTMLOPTIONS_CHK_SPLITFILE,get_Split_Document());
}
Esempio n. 16
0
int PortableTester::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QMainWindow::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: startFG(); break;
        case 1: buttonPressed((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 2: poweroff(); break;
        case 3: houseKeeping(); break;
        case 4: UnHide(); break;
        case 5: checkButton(); break;
        case 6: idleScreen(); break;
        case 7: slotAcceptUserLogin((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break;
        default: ;
        }
        _id -= 8;
    }
    return _id;
}
// --------- FancyLineEdit
FancyLineEdit::FancyLineEdit(QWidget *parent) :
    QLineEdit(parent),
    m_d(new FancyLineEditPrivate(this))
{
    // KDE has custom icons for this. Notice that icon namings are counter intuitive
    // If these icons are not avaiable we use the freedesktop standard name before
    // falling back to a bundled resource
    QIcon icon = QIcon::fromTheme(layoutDirection() == Qt::LeftToRight ?
                     QLatin1String("edit-clear-locationbar-rtl") :
                     QLatin1String("edit-clear-locationbar-ltr"),
                     QIcon::fromTheme("edit-clear", QIcon(QLatin1String(":/core/images/editclear.png"))));

    m_d->m_iconbutton->installEventFilter(m_d);
    m_d->m_iconbutton->setIcon(icon);

    ensurePolished();
    setSide(Left);

    connect(this, SIGNAL(textChanged(QString)), this, SLOT(checkButton(QString)));
    connect(m_d->m_iconbutton, SIGNAL(clicked()), this, SLOT(iconClicked()));
}
LRESULT WaitingUsersFrame::onClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
	if (!closed) {
		UploadManager::getInstance()->removeListener(this);

		closed = true;
		PostMessage(WM_CLOSE);
		return 0;
	} else {
		HTREEITEM userNode = ctrlQueued.GetRootItem();

		while (userNode) {
			delete reinterpret_cast<UserPtr *>(ctrlQueued.GetItemData(userNode));
			userNode = ctrlQueued.GetNextSiblingItem(userNode);
		}

		checkButton(false);
		frame = NULL;

		bHandled = FALSE;
		return 0;
	}
}
// ------------------- FilterWidget
FilterWidget::FilterWidget(QWidget *parent, LayoutMode lm)  :
    QWidget(parent),
    m_button(new QPushButton),
    m_editor(new HintLineEdit)
{
    m_editor->setHintText(tr("<Filter>"));
    QHBoxLayout *l = new QHBoxLayout(this);
    l->setMargin(0);
    l->setSpacing(0);

    if (lm == LayoutAlignRight)
        l->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum));

    l->addWidget(m_editor);

    m_button->setIcon(createIconSet(QLatin1String("resetproperty.png")));
    m_button->setIconSize(QSize(8, 8));
    m_button->setFlat(true);
    l->addWidget(m_button);

    connect(m_button, SIGNAL(clicked()), this, SLOT(reset()));
    connect(m_editor, SIGNAL(textChanged(QString)), this, SLOT(checkButton(QString)));
    connect(m_editor, SIGNAL(textEdited(QString)), this, SIGNAL(filterChanged(QString)));
}
Esempio n. 20
0
void doState(states_t command, SAMPLE* sptr)
{
    int tempi;
	
	switch(command) 
	{ 
			// ring buffer contents are initialized
			// next state determined by caller
		case S_INIT:
			currentSTATE = S_INIT;
			zeroMemory(sptr);
			break;
			
			// filling the ring buffer with samples
			// next state determined by caller
		case S_COLLECTING:
			currentSTATE = S_COLLECTING;
			//printf("\n=== Now recording!!  ===\n"); 
			//fflush(stdout);
			
			break;
			
			// simple playback of last NUM_PLAYBACK_SECONDS seconds
		case S_REWIND_10:
			currentSTATE = S_REWIND_10;
			greenLED = ON;
		    digitalWrite (LED_PIN,  ON) ;
		    
            // tell playback callback how many frames to play
			data.maxFrameIndex = totalFrames = 
			                                 NUM_PLAYBACK_SECONDS * SAMPLE_RATE;
			// reset playback count
			data.frameIndex = 0;
			
			// playback NUM_PLAYBACK_SECONDS
			// adjust pointers with mod RING_BUFFER_LEN arithmetic
			tempi = ringbufferWPTR - (data.maxFrameIndex * NUM_CHANNELS);
			if(tempi < 0)
				tempi += RING_BUFFER_LEN;
			
			ringbufferRPTR = tempi;
			
			playbackDirection = FWD;
			
			buttonPress = FALSE;
			buttonHold  = FALSE;
			
			// Playback recorded data.  ----------------------------------
			// advance state to playback
			currentSTATE = S_PLAYBACK;
			break;
			
			// rewind playback while button is held
			// playback from top of buffer but at faster sample rate
			// when button is release, advance state and playback at 
			// normal sample rate from where we released button
			// the FWD/REV i/o pin tells to go from the top of the buffer
			// in the REV speech direction or all the way from the start of the 
			// buffer (5 min back in time) in the FWD speech direction 
		case S_REWIND_PLAYBACK:
			currentSTATE = S_REWIND_PLAYBACK;
			
			//+++++++++++++++++++++++++++++++++++++++++++++++++++++
			greenLED = ON;
		    digitalWrite (LED_PIN,  ON) ;
		    
            // tell playback how many frames to play
            // say all of them but we will use the button
            // unpress to stop before this
			data.maxFrameIndex = totalFrames = 
			                                 NUM_SECONDS * SAMPLE_RATE - 4;
                                 
			// reset playback count
			data.frameIndex = 0;
			
			buttonPress = FALSE;
			buttonHold  = FALSE;
			
			if(digitalRead(DIRECTION_PIN) == 1)
            {
              // playback fast and in reverse from current write pointer			
			  playbackDirection = REV;
			  // start at buffer head
			  ringbufferRPTR = ringbufferWPTR;
			  // fast playback 4X speed
		      playback(32000); // stays here until rewind playback finished
		      // will return here when button is released
            }
            else
            {
            // playback fast and in forward direction 
            // from buffer start		
			playbackDirection = FWD;
			// all the way back 5 minutes in time
			tempi = 
			ringbufferWPTR - ( NUM_SECONDS * SAMPLE_RATE * NUM_CHANNELS - 4);
			if(tempi < 0)
				tempi += RING_BUFFER_LEN;
			
			ringbufferRPTR = tempi;
			
			// fast playback 2X speed
		    playback(16000); // stays here until rewind playback finished
		    // will return here when button is released

            }
									
			//+++++++++++++++++++++++++++++++++++++++++++++++++++++			
		    		    		    
		    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~	
		    // we are finished rewinding playback	  
		    // now do regular forward playback from read pointer which has 
		    // been going in the reverse direction
		    // (or forward direction depending on io pin)
		  
		    // how far did we go back?
			// we started at buffer head
			// ringbufferRPTR = ringbufferWPTR;
            // we held the button this many samples
            tempi = ringbufferWPTR - ringbufferRPTR;
			if(tempi < 0)
				tempi += RING_BUFFER_LEN;

            
            // tell playback how many frames to play
            // pointers are in samples
            // maxFrameIndex is in frames--duh!
			data.maxFrameIndex = totalFrames = tempi / NUM_CHANNELS;            		    
		    
			// reset playback count
			data.frameIndex = 0;
			
			// reset RPTR
			// playback NUM_PLAYBACK_SECONDS
			tempi = ringbufferWPTR - (data.maxFrameIndex * NUM_CHANNELS);
			if(tempi < 0)
				tempi += RING_BUFFER_LEN;
			
			ringbufferRPTR = tempi;
						
			playbackDirection = FWD;
			
			buttonPress = FALSE;
			buttonHold  = FALSE;
			
			// Playback recorded data.  ----------------------------------
			// advance state to playback
			currentSTATE = S_PLAYBACK;
		  

			break;
			
			// playback from top of buffer at normal sample rate
			// data.maxFrameIndex should be set
		case S_PLAYBACK:
			currentSTATE = S_PLAYBACK;
		    // playback from the top of the buffer
		    // will only run interrupts until playback finished
		    // state machine will not run until returns
		    playback(8000); // stays here until playback finished

			greenLED = OFF;
		    digitalWrite (LED_PIN,  OFF) ;

		    // will return here when all samples have been played
		    currentSTATE = S_STOP;
			break;
			
			// all stop--pointer rudder is amidship
			// ring buffer contents are preserved
			// to exit this state, power down.
			// todo(maybe?): to exit this state, five button presses?
			// how would I remember that? Add more buttons? Labels? ...
		case S_STOP:
			currentSTATE = S_STOP;
			
            // leave the S_STOP state (LED OFF) when button is pressed once 
            // (10 second rewind) or held pressed (rewind playback FWD or REV 
            // 4X/2X speed)
            // Not implemented-- re-enter S_COLLECTING and overwrite samples
            // with 5 button presses (?) or something... 
            // like another hardware switch
            			  
            if(digitalRead(REBOOT_PIN) == 0)
              {
                system("/home/pi/reboot.py");
              }

            
			tempi = checkButton();
			if(tempi == OFF)
			 break;

			if(tempi == 1)
			{
			   //printf("button press\n");
			   //fflush(stdout);
			   currentSTATE = S_REWIND_10;			   
			   break;
			 }
			 else
			 { // checkButton returned minus
			   //printf("button hold\n");
			   //fflush(stdout);
			   currentSTATE = S_REWIND_PLAYBACK;

			   //terminate = TRUE;
			   //printf("terminate\n");
			   //fflush(stdout);
			   break;
			}
			break;
			
		default:
			break;
	}
	
}
BOOL AP_Win32Dialog_Columns::_onCommand(HWND hWnd, WPARAM wParam, LPARAM /*lParam*/)
{
	WORD wNotifyCode = HIWORD(wParam);
	WORD wId = LOWORD(wParam);
	wchar_t buf[BUFSIZE];
    UT_Win32LocaleString str;
    
	switch (wId)
	{
	case IDCANCEL:						// also AP_RID_DIALOG_COLUMN_BTN_CANCEL
		m_answer = a_CANCEL;
		// fall through

	case IDOK:							// also AP_RID_DIALOG_COLUMN_BTN_OK
		EndDialog(hWnd,0);
		return 1;

	case AP_RID_DIALOG_COLUMN_RADIO_ONE:
		setColumns(1);
		checkButton(AP_RID_DIALOG_COLUMN_RADIO_TWO, false);
		checkButton(AP_RID_DIALOG_COLUMN_RADIO_THREE, false);
		SetDlgItemTextW(m_hDlg, AP_RID_DIALOG_COLUMN_EDIT_NUMCOLUMNS, _itow(getColumns(),buf,10));
		return 1;

	case AP_RID_DIALOG_COLUMN_RADIO_TWO:
		setColumns(2);
		checkButton(AP_RID_DIALOG_COLUMN_RADIO_ONE, false);
		checkButton(AP_RID_DIALOG_COLUMN_RADIO_THREE, false);
		SetDlgItemTextW(m_hDlg, AP_RID_DIALOG_COLUMN_EDIT_NUMCOLUMNS, _itow(getColumns(),buf,10));
		return 1;

	case AP_RID_DIALOG_COLUMN_RADIO_THREE:
		setColumns(3);
		checkButton(AP_RID_DIALOG_COLUMN_RADIO_ONE, false);
		checkButton(AP_RID_DIALOG_COLUMN_RADIO_TWO, false);
		SetDlgItemTextW(m_hDlg, AP_RID_DIALOG_COLUMN_EDIT_NUMCOLUMNS, _itow(getColumns(),buf,10));
		return 1;

	case AP_RID_DIALOG_COLUMN_CHECK_LINE_BETWEEN:
		setLineBetween( isChecked(AP_RID_DIALOG_COLUMN_CHECK_LINE_BETWEEN)==BST_CHECKED );
		return 1;

	case AP_RID_DIALOG_COLUMN_EDIT_NUMCOLUMNS:
		if( wNotifyCode == EN_KILLFOCUS )
		{
			GetDlgItemTextW( hWnd, wId, buf, BUFSIZE );
			if( _wtoi( buf ) > 0 && _wtoi(buf) != (signed) getColumns() )
			{
				setColumns( _wtoi(buf) );
			}
			SetDlgItemTextW(m_hDlg, wId, _itow(getColumns(),buf,10));
			checkButton(AP_RID_DIALOG_COLUMN_RADIO_ONE, (getColumns()==1));
			checkButton(AP_RID_DIALOG_COLUMN_RADIO_TWO, (getColumns()==2));
			checkButton(AP_RID_DIALOG_COLUMN_RADIO_THREE, (getColumns()==3));
		}
		return 1;

	case AP_RID_DIALOG_COLUMN_EDIT_SPACEAFTER:
		if( wNotifyCode == EN_KILLFOCUS )
		{
			GetDlgItemTextW( hWnd, wId, buf, BUFSIZE );
			str.fromLocale (buf);
			setSpaceAfter( str.utf8_str().utf8_str() );
			str.fromUTF8 (getSpaceAfterString ());
			SetDlgItemTextW(m_hDlg, wId, str.c_str ());
		}
		return 1;

	case AP_RID_DIALOG_COLUMN_EDIT_MAXSIZE:
		if( wNotifyCode == EN_KILLFOCUS )
		{
			GetDlgItemTextW( hWnd, wId, buf, BUFSIZE );
            str.fromLocale (buf);
			setMaxHeight( str.utf8_str().utf8_str() );
            str.fromUTF8 (getHeightString());
            SetDlgItemTextW(m_hDlg, wId, str.c_str ());
		}
		return 1;

	case AP_RID_DIALOG_COLUMN_CHECK_RTL_ORDER:
		setColumnOrder( (UT_uint32) (isChecked(AP_RID_DIALOG_COLUMN_CHECK_RTL_ORDER) == BST_CHECKED) );
		return 1;

	default:							// we did not handle this notification
		UT_DEBUGMSG(("WM_Command for id %ld\n",wId));
		return 0;						// return zero to let windows take care of it.
	}
}
BOOL AP_Win32Dialog_Columns::_onInitDialog(HWND hWnd, WPARAM /*wParam*/, LPARAM /*lParam*/)
{
	const XAP_StringSet* pSS = m_pApp->getStringSet();

	// Update the caption
	setDialogTitle(pSS->getValue(AP_STRING_ID_DLG_Column_ColumnTitle));

	/* Localise controls*/
	_DSX(COLUMN_BTN_OK,			DLG_OK);
	_DSX(COLUMN_BTN_CANCEL,			DLG_Cancel);
	_DS(COLUMN_GROUP1,			DLG_Column_Number);
	_DS(COLUMN_GROUP2,			DLG_Column_Preview);
	_DS(COLUMN_TEXT_ONE,			DLG_Column_One);
	_DS(COLUMN_TEXT_TWO,			DLG_Column_Two);
	_DS(COLUMN_TEXT_THREE,			DLG_Column_Three);
	_DS(COLUMN_CHECK_LINE_BETWEEN,		DLG_Column_Line_Between);
	_DS(COLUMN_TEXT_NUMCOLUMNS,		DLG_Column_Number_Cols);
	_DS(COLUMN_TEXT_SPACEAFTER,		DLG_Column_Space_After);
	_DS(COLUMN_TEXT_MAXSIZE,		DLG_Column_Size);
	_DS(COLUMN_CHECK_RTL_ORDER,		DLG_Column_RtlOrder);

	// Do Bitmaps
	RECT rect;
	GetClientRect(GetDlgItem(hWnd, AP_RID_DIALOG_COLUMN_RADIO_ONE), &rect);
	int iWidth = rect.right - rect.left;
	int iHeight = rect.bottom - rect.top;

	HBITMAP hBitmap;
	AP_Win32Toolbar_Icons Icons;
	COLORREF ColorRef = GetSysColor(COLOR_BTNFACE);
	UT_RGBColor Color(GetRValue(ColorRef), GetGValue(ColorRef), GetBValue(ColorRef));

	bool bFoundIcon = Icons.getBitmapForIcon(hWnd, iWidth, iHeight, &Color, "1COLUMN",
																&hBitmap);
	UT_return_val_if_fail (bFoundIcon, false);
	SendDlgItemMessageW(hWnd, AP_RID_DIALOG_COLUMN_RADIO_ONE, BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap);

	bFoundIcon = Icons.getBitmapForIcon(hWnd, iWidth, iHeight, &Color, "2COLUMN",
																&hBitmap);
	UT_return_val_if_fail (bFoundIcon, false);
	SendDlgItemMessageW(hWnd, AP_RID_DIALOG_COLUMN_RADIO_TWO, BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap);

	bFoundIcon = Icons.getBitmapForIcon(hWnd, iWidth, iHeight, &Color, "3COLUMN",
																&hBitmap);
	UT_return_val_if_fail (bFoundIcon, false);
	SendDlgItemMessageW(hWnd, AP_RID_DIALOG_COLUMN_RADIO_THREE, BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap);

	// set initial state
	wchar_t buf[BUFSIZE];
	checkButton(AP_RID_DIALOG_COLUMN_RADIO_ONE + getColumns() - 1, true);
	enableLineBetweenControl(getColumns() != 1);
	checkButton(AP_RID_DIALOG_COLUMN_CHECK_LINE_BETWEEN, getLineBetween());
	SetDlgItemTextW(m_hDlg, AP_RID_DIALOG_COLUMN_EDIT_NUMCOLUMNS, _itow( getColumns(),buf,10) );    
	setControlText(AP_RID_DIALOG_COLUMN_EDIT_SPACEAFTER, getSpaceAfterString());
	setControlText(AP_RID_DIALOG_COLUMN_EDIT_MAXSIZE, getHeightString());

	showControl( AP_RID_DIALOG_COLUMN_CHECK_RTL_ORDER, SW_NORMAL );
	checkButton(AP_RID_DIALOG_COLUMN_CHECK_RTL_ORDER, getColumnOrder()!=false);

	// Create a preview window.

	HWND hwndChild = GetDlgItem(hWnd, AP_RID_DIALOG_COLUMN_PREVIEW);

	m_pPreviewWidget = new XAP_Win32PreviewWidget(static_cast<XAP_Win32App *>(m_pApp),
													  hwndChild,
													  0);
	UT_uint32 w,h;
	m_pPreviewWidget->getWindowSize(&w,&h);
	//m_pPreviewWidget->init3dColors(m_wpreviewArea->style);
	m_pPreviewWidget->getGraphics()->init3dColors();
	_createPreviewFromGC(m_pPreviewWidget->getGraphics(), w, h);
	m_pPreviewWidget->setPreview(m_pColumnsPreview);
	
	centerDialog();	
	
	return 1;	// 1 == we did not call SetFocus()
}
Esempio n. 23
0
PortableTester::PortableTester(QWidget *parent) :
        QMainWindow(parent, Qt::FramelessWindowHint | Qt::WindowSystemMenuHint),
        ui(new Ui::PortableTester) {
    
    ui->setupUi(this);
/*    LoginDialog* loginDialog = new LoginDialog( this );
    connect(loginDialog,SIGNAL(acceptLogin(QString&,QString&,int&)),this,SLOT(slotAcceptUserLogin(QString&,QString&)));
    do{
        loginDialog->exec();
    }while(!m_nPassword);*/
    //qDebug()
            //<< "----------------------------PORTABLE TESTER STARTS----------------------------";
    
    //Set home Directory as Current Directory
    QDir::setCurrent("/home");
    
    //PT6 Application Interface Library
    QPluginLoader apploader1("libPTComponentsInterface.so", this);
    QObject *AppPlugin1 = apploader1.instance();
    IPT = qobject_cast<IPTComponentsInterface*> (AppPlugin1);
    
    //Application Card Interface Library
    QPluginLoader loaderApp("libPTApplicationcardInterface.so", this);
    IAppCard = qobject_cast<IApplicationCardInterface*> (loaderApp.instance());
    IAppCard->setDeviceName(SLOT0);
    IAppCard->enumerateAPPCard();
    
    //Backplane Interface Library
    QPluginLoader loader2("libBackPlaneInterface.so", this);
    IBackPlane = qobject_cast<IntefaceBackPlane*> (loader2.instance());
    IBackPlane->InitializeBpObject();
    
    //PSOC Interface Library
    QPluginLoader loader3("libPTPsocInterface2.so", this);
    IPsoc = qobject_cast<IPSOCCOMMUNICATION*> (loader3.instance());
    IPsoc->openSerial();
    objTimer = new QTimer(this);
    connect(objTimer, SIGNAL(timeout()), this, SLOT(checkButton()));
    
    //	idleTimer=new QTimer(this);
    //	connect(idleTimer, SIGNAL(timeout()),this,SLOT(idleScreen()));
    //	idleTimer->setInterval(23000);
    //	idleTimer->start();
    
    //QMax PT Interface Library
    QPluginLoader loader4("libQmaxPTInterface.so", this);
    IptLib = qobject_cast<IQmaxPTLibrary*> (loader4.instance());
    //GPIO Event Interface Library
    QPluginLoader loader5("libGPIOEventInterface.so", this);
    IGPIOEvent = qobject_cast<PTGPIOEventInterface*> (loader5.instance());
    //PT Keypad Interface Library
    QPluginLoader loader6("libPTKeyEventInterfaces.so", this);
    IPTKeyEvent = qobject_cast<PTEventInterface*> (loader6.instance());
    //GPIO PIN Interface Library for toggle touch and kill
    QPluginLoader loader7("libPTGPIOPinInterface.so", this);
    IGPIOPin = qobject_cast<InterfaceGPIOPins*> (loader7.instance());
//    //Hardware Identification Library
//    QPluginLoader loader8("libPTHWIDInterface.so", this);
//    IHWID = qobject_cast<IHWIDInterface*> (loader8.instance());
//
//    //Utility Panel Interface Library
//    QPluginLoader loader9("libUtilityPanel.so", this);
//    IUtility = qobject_cast<UtilityInterface*> (loader9.instance());
    

    IBackPlane->writeBackPlaneRegister(0x03, 0x14); // Initialize LCD Control
//    IptLib->InitPTLibrary("./PTUI.xml", "MainWindow");
    initialitation();
    IPTKeyEvent->InvokeGPIOEvent(this, "/dev/input/event2", "pt_kpp",&m_nPTKeyCode);
//    IGPIOEvent->InvokeGPIOEvent(this, "/dev/input/event3", "gpioshutdown", &m_nPTShutDown);//do not uncomment VI will not work properly
    
    //qDebug() << "PT win Id" << this->winId();
    isWindowOpen = false;
    
    msgBoxLive = false;
    /*
	QByteArray psocData;
        
	QMessageBox failure;
	IPsoc->writeSerial(0xff);
	IPsoc->writeSerial(0xff);
	psocData = IPsoc->readSerByte();
	if (psocData.endsWith("*?") == true) {
		qDebug() << "PSOC RESET DONE on 1st try";
	} else {
		IPsoc->writeSerial(0xff);
		psocData = IPsoc->readSerByte();
		if (psocData.endsWith("*?") == true) {
			qDebug() << "PSOC RESET DONE on 2nd try";
		} else {
			IPsoc->writeSerial(0xff);
			psocData = IPsoc->readSerByte();
			if (psocData.endsWith("*?") == true) {
				qDebug() << "PSOC RESET DONE on 3rd try";
			} else {
				failure.setText("PSOC RESET FAILURE");
				failure.exec();
			}
                        
		}
	}
        
	qDebug() << "RESET DATA:" << psocData;
*/
    
    QMessageBox testing;
    if (IAppCard->readAppCardCodeId() != 0x1982) {
        testing.setText("Check Appcard !!!");
        testing.exec();
    }
    if (IBackPlane->readBackPlaneCodeID() != 0x2704) {
        testing.setText("Check Backpanel !!!");
        testing.exec();
    }
    //	IAppCard->resetADC(1);
    dmmPlugin = viPlugin = fgPlugin = slPlugin = icmPlugin = false;
    m_bTouchFlag = true;
    
    //~~~~~~~~~~~Transparent OM Symbol Splash~~~~~~~~~~~
    /*	QPixmap pixmap(":/images/Tamil_ohm2.png");
	QSplashScreen splash(pixmap);
	splash.setMask(pixmap.mask());
	splash.show();
	splash.close();*/
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //~~~~~~~~~~~~~~Digital Clock~~~~~~~~~~~~~~~~~~~~~~~
    clock=new QDigitalClock(this);
    clock->setGeometry(620,0,170,30);
    clock->m_TextColor=QColor(255,255,255,255);
    clock->setFont(QFont("DejaVu Sans",14,50,false));
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    myID=0;
    //	 qInstallMsgHandler(customMessageHandler);
}
Esempio n. 24
0
int main(void)
{
	
	/*-----------------------
	Default PORT settings
	------------------------*/
	//portB is configured by display.h
	
	//portD: 0,1,5,6,7 = output, 2,3 = input (interrupts), 4 - unused
	DDRD = 0xE3;
	PORTD = 0x1C; // enable pull-up for unused pin and for interrupt pins
	
	//port C is only input port
	DDRC = 0x00;
	PORTC = 0xCB; //pull-up for btn 1-2, reset and unused pin,
	
	clearBit(OUTPUT,SF); //FAN is OFF
	
	/*-----------------------
	Restore data from eeprom
	------------------------*/	
	totalDistance = eeprom_read_dword(15);
	totalConsumedCapacity = eeprom_read_dword(25);
	LineMode = eeprom_read_byte(35);
	
	
	/*-------------------------------------------------------------
	TIMER1 configuration 
	generate of "servo" control PWM (1-2ms impulse, 20ms period)
	--------------------------------------------------------------*/
	//COM1A1 COM1A0 COM1B1 COM1B0 FOC1A FOC1B WGM11 WGM10
	TCCR1A = 0x00; //Normal port operation, OC1A/OC1B disconnected, normal mode
	
	//ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10
	TCCR1B = 0x0B; //CTC mode, prescaler = 64 (250 clk = 2ms, 2500 = 20ms)
	
	//compare register A - period 20ms
	OCR1A = 0x09C4;
	
	// compare register B - impulse 1-2ms (OCR1AL=0x7F-0xFF)
	OCR1B = 0x007F;//1ms
	
	/*-------------------------------------------------------------
	TIMER2 configuration 
	generate time for speed measuring - period 2ms
	-------------------------------------------------------------*/
	
	//compare register - 2ms period
	OCR2 = 250;
	
	//FOC2 WGM20 COM21 COM20 WGM21 CS22 CS21 CS20
	TCCR2 = 0x0C;//TCT mode, OC2 disconnected, prescaler = 64	
	
	/*-------------------------------------------------------------
	external interrupt configuration 
	0 - measure cycle time
	1 - OFF signal
	-------------------------------------------------------------*/
	
	//SE SM2 SM1 SM0 ISC11 ISC10 ISC01 ISC00 
	setBit(MCUCR,1);// both interrupts on falling edge
	setBit(MCUCR,3);
	
	//INT1 INT0 – – – – IVSEL IVCE
	setBit(GICR,7); // both external interrupts enabled
	setBit(GICR,6);		
		
	//OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 – TOIE0
	TIMSK = 0x98; //interrupts on compare match
	
	sei();//global interrupt enable	
	
	// display initialization

	displayPortsInit(); 
	_delay_ms(2);	
	displayFunctionSet(1,1,0);
	displayOnOffControl(1,0,0);
	displayClear();	
	
	displayEntryModeSet(1,0);
	displayCursorShift(0,1);	
	
	
	//show text for 2 seconds
	displayPausedCounter = 100;
	displayPaused = 1;
	
	displaySetAddressDDRAM(0x00);	
	displayWriteDataArray("simply  ");
	displaySetAddressDDRAM(0x40);	
	displayWriteDataArray("version ");
			
    while(1)
    {       
		_delay_ms(7);
		checkButton();
		displayRedraw();		
    }
}
Esempio n. 25
0
void checkAll(Xbox360Controller &cont)
{
  if (cont.isConnected())
  {
    cont.updateState();
    checkButton(cont, client, 0, "a");
    checkButton(cont, client, 1, "b");
    checkButton(cont, client, 2, "x");
    checkButton(cont, client, 3, "y");
    checkButton(cont, client, 4, "dpadup");
    checkButton(cont, client, 5, "dpaddown");
    checkButton(cont, client, 6, "dpadleft");
    checkButton(cont, client, 7, "dpadright");
    checkButton(cont, client, 8, "start");
    checkButton(cont, client, 9, "back");
    checkButton(cont, client, 10, "leftthumbbutton");
    checkButton(cont, client, 11, "rightthumbbutton");
    checkButton(cont, client, 12, "white");
    checkButton(cont, client, 13, "black");
    checkTrigger(cont, client, 0, "rightanalogtrigger");
    checkTrigger(cont, client, 1, "leftanalogtrigger");
    checkThumb(cont, client, 0, "leftthumbstickleft", "leftthumbstickright");
    checkThumb(cont, client, 1, "leftthumbstickdown", "leftthumbstickup");
    checkThumb(cont, client, 2, "rightthumbstickleft", "rightthumbstickright");
    checkThumb(cont, client, 3, "rightthumbstickdown", "rightthumbstickup");
  } 
}
Esempio n. 26
0
int main(int argc, char *argv[]) {

    buttonstates padButtons;
	snespad pads;
	pollButton = 1;
	pollPads = 1;
	doRun = 1;

	// check command line arguments
	if (argc > 1) {
		// argv[1]==1 poll controllers only
		// argv[1]==2 poll button only
		// argv[1]==3 poll controllers and button
		switch ( atoi(argv[argc-1]) ) {
			case 1:
				printf("[SNESDev-Rpi] Polling only controllers.\n");
				pollButton = 0;
				pollPads = 1;
			break;
			case 2:
				printf("[SNESDev-Rpi] Polling button only.\n");
				pollButton = 1;
				pollPads = 0;
			break;
			case 3:
				printf("[SNESDev-Rpi] Polling controllers and button.\n");
				pollButton = 1;
				pollPads = 1;
			break;
			default:
				return -1;
		}
    } else {
    	printf("[SNESDev-Rpi] Polling controllers and button.\n");
    }

    if (!bcm2835_init())
        return 1;

	// initialize button and LEDs
    bcm2835_gpio_fsel(BUTTONPIN,  BCM2835_GPIO_FSEL_INPT);

    /* initialize controller structures with GPIO pin assignments */

    // pin out used in SNESDev article on blog
	// pads.clock  = RPI_GPIO_P1_18;
	// pads.strobe = RPI_GPIO_P1_16;
	// pads.data1  = RPI_GPIO_P1_22;
	// pads.data2  = RPI_GPIO_P1_15;

    // pin out used pi gamecon GPIO driver
	pads.clock  = RPI_GPIO_P1_19;
	pads.strobe = RPI_GPIO_P1_23;
	pads.data1  = RPI_GPIO_P1_07;
	pads.data2  = RPI_GPIO_P1_05;

	/* set GPIO pins as input or output pins */
	initializePads( &pads );

	/* intialize virtual input device */
	if ((uinp_fd = setup_uinput_device()) < 0) {
		printf("[SNESDev-Rpi] Unable to find uinput device\n");
		return -1;
	}

	if (signal(SIGINT, sig_handler) == SIG_ERR)
  		printf("\n[SNESDev-Rpi] Cannot catch SIGINT\n");

	/* enter the main loop */
	while ( doRun ) {

		if (pollButton) {
			/* Check state of button. */
			checkButton(uinp_fd);
		}

		if (pollPads) {
			/* read states of the buttons */
			updateButtons(&pads, &padButtons);

			/* send an event (pressed or released) for each button */
			/* key events for first controller */
	        processPadBtn(padButtons.buttons1, SNES_A,     KEY_X,          uinp_fd);
	        processPadBtn(padButtons.buttons1, SNES_B,     KEY_Z,          uinp_fd);
	        processPadBtn(padButtons.buttons1, SNES_X,     KEY_S,          uinp_fd);
	        processPadBtn(padButtons.buttons1, SNES_Y,     KEY_A,          uinp_fd);
	        processPadBtn(padButtons.buttons1, SNES_L,     KEY_Q,          uinp_fd);
	        processPadBtn(padButtons.buttons1, SNES_R,     KEY_W,          uinp_fd);
	        processPadBtn(padButtons.buttons1, SNES_SELECT,KEY_RIGHTSHIFT, uinp_fd);
	        processPadBtn(padButtons.buttons1, SNES_START, KEY_ENTER,      uinp_fd);
	        processPadBtn(padButtons.buttons1, SNES_LEFT,  KEY_LEFT,       uinp_fd);
	        processPadBtn(padButtons.buttons1, SNES_RIGHT, KEY_RIGHT,      uinp_fd);
	        processPadBtn(padButtons.buttons1, SNES_UP,    KEY_UP,         uinp_fd);
	        processPadBtn(padButtons.buttons1, SNES_DOWN,  KEY_DOWN,       uinp_fd);

			// key events for second controller 
	        processPadBtn(padButtons.buttons2, SNES_A,     KEY_E, uinp_fd);
	        processPadBtn(padButtons.buttons2, SNES_B,     KEY_R, uinp_fd);
	        processPadBtn(padButtons.buttons2, SNES_X,     KEY_T, uinp_fd);
	        processPadBtn(padButtons.buttons2, SNES_Y,     KEY_Y, uinp_fd);
	        processPadBtn(padButtons.buttons2, SNES_L,     KEY_U, uinp_fd);
	        processPadBtn(padButtons.buttons2, SNES_R,     KEY_I, uinp_fd);
	        processPadBtn(padButtons.buttons2, SNES_SELECT,KEY_O, uinp_fd);
	        processPadBtn(padButtons.buttons2, SNES_START, KEY_P, uinp_fd);
	        processPadBtn(padButtons.buttons2, SNES_LEFT,  KEY_C, uinp_fd);
	        processPadBtn(padButtons.buttons2, SNES_RIGHT, KEY_B, uinp_fd);
	        processPadBtn(padButtons.buttons2, SNES_UP,    KEY_F, uinp_fd);
	        processPadBtn(padButtons.buttons2, SNES_DOWN,  KEY_V, uinp_fd);
		}

		/* wait for some time to keep the CPU load low */
		delay(FRAMEWAIT);
	}

	return 0;
}
Esempio n. 27
0
int main(void) {
    cpu_interval = 0;
    int mem_load;
    int display_mode = mode_CPU; 
    char tmp_value[20];
    mem_tot = mem_total()/1024;
    
    lcd_line("    RPi i2c test");
    lcd_line("    Copyright (C)");
    lcd_line("        2013");
    lcd_line("Jesper Stockenstrand");
    usleep(5000000);
    
    for(;;) {
        int cpu_l;
            
        switch (display_mode) {
        
            case mode_CPU:
                cpu_l = cpu_load();
                sprintf(tmp_value,"         %d%%",cpu_l);
                lcd_line("      CPU LOAD  ");
                lcd_line(tmp_value);
                lcd_line("   ");
                lcd_line(">CPU<[MEM][NET][UPT]"); 
                break;
                
            case mode_MEM:
                mem_load = (int)(((double)mem_used()/(double)mem_tot)*100);
                lcd_line("     MEM USAGE      ");
                sprintf(tmp_value,"       %d/%dMb",mem_used(),mem_tot);
                lcd_line(tmp_value);
                sprintf(tmp_value,"         %d%%",mem_load);
                lcd_line(tmp_value);
                lcd_line("[CPU]>MEM<[NET][UPT]");
                break;
                
            case mode_NET:
                lcd_line("    IP ADDRESS      ");
                sprintf(tmp_value,"    %s", net_address());
                lcd_line(tmp_value);
                lcd_line("      ");
                lcd_line("[CPU][MEM]>NET<[UPT]");
                break;
                
            case mode_UPT:
                lcd_line("       UP TIME      ");
                sprintf(tmp_value,"     %d sec",uptime());
                lcd_line(tmp_value);
                lcd_line("     ");
                lcd_line("[CPU][MEM][NET]>UPT<");
                break;
                
            default:
                display_mode = mode_CPU;
                
        }
        
        switch (checkButton()) {
        
            case 1:
                display_mode = mode_CPU;
                break;
                
            case 2:
                display_mode = mode_MEM;
                break;
                
            case 3:
                display_mode = mode_NET;
                break;
            
            case 4:
                display_mode = mode_UPT;
                break;
                
        } 

            
        usleep(10000);
    
    } 
    return(0);
}
Esempio n. 28
0
/*
  Rainbow Cycle Program - Equally distributed
 */
void rainbowCycle() {
  setBrightness();
  uint16_t i, j;
  int j2;
  for(j=0; j<256; j++) { // cycle all wheel colors

    // calculate wait based on volatile opt from interrupt

    // This includes a very hacky way to have the color direction reverse
    // while maintaining the old "negative wait" convention to skip colors.
    // As it stands, we don't invert j2 till it reaches 0 otherwise colors would
    // suddenly change, but the direction may reverse a bit late (speeds up 
    // before reversing).
    int wait = (int) map(opt, 0, 1023, -200, 200);
    if( wait < 0 ) {
      if( j2 > 0 || j == 1 ){
        j2 = j;
      } else {
        j2 = -j;
      }
      wait = wait + 100;
    } else {
      if( j2 < 0 || j == 1 ){
        j2 = -j;
      } else {
        j2 = j;
      }
      wait = -wait + 100;
    }
    if( wait < 0 ) {
      // negative values make a huge apparent difference, so fake a larger spread
      // by having -100 to 100 instead of -20 to 100
      wait = floor( wait / 5 );
    }
    // kind of a hack to allow negative wait value to speed rainbow by
    // skipping colors, otherwise 0 would be fast as chip could process
    if(wait < 0 &&  j % ( -1 * wait ) != 0){
      continue; 
    }

    if( checkButton() ){ return; };
    for(i = 0; i < numPixels(); i++) {
      setPixelColor(
        i,
        Wheel(
          // i*256/numPixels() is like mapping i in 0...numPixels() to 0..256
          // 
          // + j & 255 ensures we change color each time we visit given pixel
          // while not running over 255
          // 
          // casting to uint32_t lets us handle strips longer than 256 pixels
          // since that would result in number larger than 32K, causing wraparound
          // to negative number
          ( (uint8_t) ( (uint32_t) i * 256 / numPixels()) + j2) & 255
        )
      );
    }
    show();

    if(wait > 0){
      delay(wait);
    }

  }
}
void loop()
{
	if (timing) {
		timerTime += millis() - lastTime;
		lastTime = millis();
	}

	if (state == WAITING || state == TIMER_COUNTDOWN) {
		if (state == WAITING && timing) disableTiming();
		if (readRFID()) {
			//Serial.print("RFID: ");
			//Serial.println(rfidNum);

			convertRFID();
			if (serverRequest()) {
				state = SERVER_WAIT;
				enableTiming();
			}
			else state = WAITING;
		}
	}
	else if (state == SERVER_WAIT){
		//Serial.println(timerTime);
		if (timerTime < TIMEOUT) {
			if (readServerResponse()) {
				disableTiming();
				parseResponse();
				if (authorized) {
					state = TIMER_COUNTDOWN;
					turnOn();
				}
				else state = DENIED;
			}
		}
		else {
			state = WAITING;
		}
	}
	else if (state == DENIED) {
		Serial.println("DENIED");
		state = WAITING;
	}

	if (state == TIMER_COUNTDOWN && timing && currentOn()) {
		disableTiming();
	}
	else if (state == TIMER_COUNTDOWN && (!timing && !currentOn())) {
		enableTiming();
	}

	if (state == TIMER_COUNTDOWN) {
		if ((timing && (timerTime > authorizedTime)) || checkButton()) {
			state = WAITING;
			disableTiming();
			turnOff();
		}
	}

	/*if (timerTime > 0)
		Serial.println(timerTime);*/
}