コード例 #1
0
ファイル: depthprobe.cpp プロジェクト: kosme/grbl0.8-Kosme
void depthProbe::button()
{
    readSerial(true);
    sendSerial("$\r");
    QString popochas = readSerial(false);
    QMessageBox(QMessageBox::Critical,"Interaction needed",popochas,QMessageBox::Ok).exec();
}
コード例 #2
0
void stk500service::setMode(char mode) {

    // Execute the 'm' command and switch modes
    char command[2] = {'m', mode};
    if (!writeVerifyRetry(command, sizeof(command))) {
        throw ProtocolException("Failed to switch SPM mode: No response");
    }

    // Read the address part; send 4 bytes to push it out
    quint32 address = 0;
    _handler->getPort()->write("\0\0\0\0" , 4);
    int recLen = readSerial((char*) &address, sizeof(address));
    if (recLen != (int) sizeof(address)) {
        // Could not get a full response for the switch mode command
        QString errorMessage = QString("Failed to switch SPM mode: Response too short\n"
                                       "Received: %1 bytes").arg(recLen+2);
        throw ProtocolException(errorMessage);
    }

    // Verify address is valid
    QString addrText = QString("0x%0").arg(QString::number(address*2, 16).toUpper());
    if (address == 0) {
        throw ProtocolException("Failed to switch SPM mode: Function not found. "
                                "Could not locate the firmware section "
                                "used to write to flash memory.\n\n"
                                "The firmware currently on the device does not support "
                                "service updates. Use an ISP programmer to upload the "
                                "right firmware to the device.");
    }

    // Debug: print address information
    qDebug() << "[Service] mode =" << mode << "; spm_addr =" << addrText;
}
コード例 #3
0
ファイル: uartsocket.c プロジェクト: pellepl/cnc_ctrl
static DWORD WINAPI pipeDataFrSe(LPVOID pVClient) {
	char *buf = malloc(PIPE_BUF_SIZE);
	ClientElem_t *pClient = (ClientElem_t *)pVClient;
	while (pClient->running) {
		int nBytesRead;
		if (!readSerial(pClient, &buf[0], PIPE_BUF_SIZE, &nBytesRead, 1000)) {
			DBG_PRINT("ERROR uartread pipe %ld, hdl %ld", GetLastError(), pClient->serialHdl);
			pClient->running = 0;
		} else if (nBytesRead > 0) {
			int wrIx = 0;
			int wrLen = 0;
			DBG_PRINT("SE-> put %i bytes in buf", nBytesRead);
			while (nBytesRead > 0 && wrLen >= 0 && pClient->running) {
				wrLen = rbWrite(&pClient->rbSeSo, &buf[wrIx], nBytesRead, 1000);
				nBytesRead -= wrLen;
				wrIx += wrLen;
			}
			if (wrLen < 0) {
				DBG_PRINT("ERROR uartwrbuf pipe");
				pClient->running = 0;
			}
		}
	}
	free(buf);
	DBG_PRINT("SE->X");
	return 0;
}
コード例 #4
0
	void Everything::run()
	{
		updateSensors();			//call each st::Sensor object to refresh data

		#ifndef DISABLE_SMARTTHINGS
			SmartThing.run();		//call the ST Shield Library to receive any data from the ST Hub
			updateNetworkState();	//call the ST Shield Library to update the current zigbee network status between the Shield and Hub
		#endif
		
		#if defined(ENABLE_SERIAL)
			readSerial();			//read data from the Arduino IDE Serial Monitor window (useful for debugging sometimes)
		#endif
		
		sendStrings();				//send any pending updates to ST Cloud
		
		#ifndef DISABLE_REFRESH		//Added new check to allow user to disable REFRESH feature - setting is in Constants.h)
		if ((bTimersPending == 0) && ((millis() - refLastMillis) >= long(Constants::DEV_REFRESH_INTERVAL) * 1000))  //DEV_REFRESH_INTERVAL is set in Constants.h
		{
			refLastMillis = millis();
			refreshDevices();	//call each st::Device object to refresh data (this is just a safeguard to ensure the state of the Arduino and the ST Cloud stay in synch should an event be missed)
		}
		#endif
		
		if(debug && millis()%60000==0 && millis()!=lastmillis)
		{
			lastmillis = millis();
			Serial.print(F("Everything: Free Ram = "));  
			Serial.println(freeRam());
		}
	}
コード例 #5
0
ファイル: DVRPTRV3Controller.cpp プロジェクト: EA3HKB/OpenDV
bool CDVRPTRV3Controller::openModem()
{
	bool ret = false;

	switch (m_connection) {
		case CT_USB:
			ret = m_usb->open();
			break;
		case CT_NETWORK:
			ret = m_network->open();
			break;
		default:
			wxLogError(wxT("Invalid connection type: %d"), int(m_connection));
			break;
	}

	if (!ret)
		return false;

	ret = readSerial();
	if (!ret) {
		closeModem();
		return false;
	}

	ret = setConfig();
	if (!ret) {
		closeModem();
		return false;
	}

	return true;
}
コード例 #6
0
ファイル: depthprobe.cpp プロジェクト: kosme/grbl0.8-Kosme
double depthProbe::getRealZero(double X, double Y,bool reset)
{
    port.flush(port_nr);
    double Zpos=.5;
    QString comando;
    QString received = "";
    comando = "G00 X";
    comando.append(QString::number(X)).append(" Y").append(QString::number(Y)).append("\r");
    sendSerial(comando);
    port.flush(port_nr);
    pause(50);
    while(!received.contains("depth"))
    {
        Zpos-=0.02;
        comando = "G00 Z";
        comando.append(QString::number(Zpos)).append("\r");
        sendSerial(comando);
        pause(50);
        received = readSerial(false);
    }
    if(reset)
        port.Reset(port_nr);
    sendSerial("G00 Z01\r");
    pause(2000);
    return(Zpos);
}
コード例 #7
0
ファイル: URMSerial.cpp プロジェクト: Chief1/URM37
// Recieve distance from URM device
byte URMSerial::getMeasurement(int& value)
{
  if(!hasReading()) return NOTREADY;
  
  if(reqTimeout()) return TIMEOUT;
  

	// Read in data
	readSerial();

    // Validate the reading type
    switch(serialData[Header]) // Three types of command responses. 0x11 is a temperature, 0x22 Distance, 0x33 EEPROM
    {
     case COMMAND_DISTANCE:
        return processDistance(value);

     break;
     case COMMAND_TEMP:
        return processTemperature(value);
     break;
    }

    // Strange return result!
	distanceRequested = temperatureRequested = false; // This is a bug fix. If an error was returned (conrrupt byte array), reset distance measurements so we can re-request
    value = 0;
    return ERROR;
}
コード例 #8
0
//--------------------------
void threadedSerial::threadedFunction() 
{
	while( isThreadRunning() != 0 ){
		if( lock() ){
			haveInput[0] = 0;
			haveInput[1] = 0;
			haveInput[2] = 0;
			
			readSerial(); // this is the threaded serial polling call
            
            OSCtime = ofGetElapsedTimeMillis();
            if(OSCtime >= (OSCprevTime + OSCsendingInterval) ) {
                
                for(int i = 0; i < NUMOSCSENDERS; i++) {
                    if(senderActive[i]) {
                        if(i == resetID){
                            sendOSC( i, true );
                        }else{
                            sendOSC( i, false );
                        }
                    }
                }
                OSCprevTime = OSCtime;
            }
            
            usleep(500);	//mac sleeps in microseconds = 1/2 millisecond interval for serialThread
			unlock();
		}
	}
}
コード例 #9
0
bool CloudWatcherController::getCloudWatcherAnswer(char *buffer, int nBlocks) {
  int r = readSerial(buffer, nBlocks * BLOCK_SIZE);

  int valid = checkValidMessage(buffer, nBlocks);

  if (!valid) {
    return false;
  }

  return true;
}
コード例 #10
0
ファイル: URMSerial.cpp プロジェクト: Chief1/URM37
// Read data from EEPROM
byte URMSerial::read(byte command)
{
	byte ttlCOMMAND[3] = {COMMAND_EEPROMREAD,command,0};
	sendCommand(ttlCOMMAND);
	// Response should be immediate
	while(!hasReading());
	readSerial();

	// Return result
	return ttlCOMMAND[LowByte];
}
コード例 #11
0
ファイル: edfa.cpp プロジェクト: jhb123/SummerProject2016
bool edfa::setEmission(bool emission){
            qDebug() << "Set emission in EDFA object " << emission;
    if(emission){

        EDFAOn();
    }
    else{
        EDFAOff();
    }

    qDebug() << readSerial(); //Needed for some reason. Think it is to do with delays.

}
コード例 #12
0
ファイル: edfa.cpp プロジェクト: jhb123/SummerProject2016
float edfa::EDFAReadPh2(){
    QString message;

    if(ready){
        writeSerial("Ph 2\r\n");
        message=readSerial();
        if (message.contains("PDM2: ",Qt::CaseInsensitive)){
            message = stripString(message, "PDM2:");
        }
    }

    return message.toFloat();
}
コード例 #13
0
bool stk500service::writeVerify(const char* data, int dataLen) {
    // Write
    _handler->getPort()->write(data, dataLen);

    // Verify
    char* tmp = new char[dataLen];
    bool success = false;
    if (readSerial(tmp, dataLen) == dataLen) {
        success = (memcmp(data, tmp, dataLen) == 0);
    }
    delete[] tmp;
    return success;
}
コード例 #14
0
String SerialHandler::checkForCommand(){
	buffer += readSerial();
	if(buffer.length() > 0){
		String cmd = parseCommand();
		if(cmd.equals("")){
			Serial.print("Free RAM: ");
			Serial.println(freeRam());
			return NO_COMMAND;
		}else
			return cmd;
	}else{
		return NO_COMMAND;
	}
}
コード例 #15
0
ファイル: URMSerial.cpp プロジェクト: Chief1/URM37
// Send a request to the URM37
bool URMSerial::write(byte command, byte data)
{
 
	// WARNING. VERY DANGEROUS. You can set the wrong mode
	byte ttlCOMMAND[3] = {COMMAND_EEPROMWRITE,command,data};
	sendCommand(ttlCOMMAND);
	// Response should be immediate
	while(!hasReading());
	readSerial();
	
	// Return whether the command was echoed
	return  ttlCOMMAND[0] == serialData[0] 
		&&	ttlCOMMAND[1] == serialData[1] 
		&&	ttlCOMMAND[2] == serialData[2];
}
コード例 #16
0
ファイル: depthprobe.cpp プロジェクト: kosme/grbl0.8-Kosme
void depthProbe::getZero()
{
    port.flush(port_nr);
    double Zpos=0;
    QString comando,num;
    QString received = "";
    while(!received.contains("depth"))
    {
        comando="G00 Z";
        Zpos-=0.02;
        comando.append(num.setNum(Zpos)).append("\r");
        sendSerial(comando);
        pause(50);
        received = readSerial(false);
    }
    port.Reset(port_nr);
    sendSerial("G00 Z01\r");
    pause(100);
}
コード例 #17
0
ファイル: edfa.cpp プロジェクト: jhb123/SummerProject2016
bool edfa::replyCheck(){
    qDebug() << "In reply check";
    if(ready){
            qDebug() << "In reply check ready pass";
           serial->clear();
           serial->write("giberish\r\n"); //send some giberish to get FWC response.
           serial->waitForBytesWritten(10000);
           QString message = readSerial();
           qDebug() << message;
           if (message.contains("FWC",Qt::CaseInsensitive)){
           return true;
           }
           else{
               return replyCheck();
           }

    }
    return false;
}
コード例 #18
0
ファイル: application.cpp プロジェクト: palfrey/spark-proxy
char* readWord() {
    const unsigned int BUFLEN = 255;
    char* accumulated = (char*) malloc(BUFLEN);
    unsigned int location = 0;
    while (true) {
        if (Serial.available()) {
            char incoming = readSerial();
            if (incoming == '\n' || incoming == ';') {
                break;
            }
            accumulated[location] = incoming;
            location ++;
        }
        else {
            delay(2); // arbitrary
        }
    }
    accumulated[location] = '\0';
    return accumulated;
}
コード例 #19
0
void Serial::run(){
  size_t len;
  unsigned char buf[SERIAL_BUFFER_LENGTH];
  int used = 0;
  int frompos = 0;
  int topos = 0;

  if(verbose)
    std::cout << "starting rx" << std::endl;

  while(running) {
    len = readSerial(&buf[topos], SERIAL_BUFFER_LENGTH-topos);
    topos += len;
    len = topos-frompos;
    if(len > 0){
      do{
	if(verbose){
	  std::cout << "rx\t";
	  log(&buf[frompos], len);
	}
	if(callback){
	  used = callback->handle(&buf[frompos], len);
	}else{
	  used = len;
	}
	if(used == len)
	  frompos = topos = 0;
	else
	  frompos += used;
	len = topos-frompos;
      }while(used > 0 && len > 0);
    }
    if(topos >= SERIAL_BUFFER_LENGTH-1){
      std::cerr << "buffer overflow!" << std::endl;
      frompos = topos = 0;
    }
  }

  if(verbose)
    std::cout << "stopping rx" << std::endl;
}
コード例 #20
0
ファイル: sketch.cpp プロジェクト: Jones-S/physical-computing
void loop()
{
  readSerial(); // read the values available at the serial port
   
  Serial.print(firstValue); // debugging
  Serial.print("t");
  Serial.print(secondValue);
  Serial.print("t");
  Serial.print(thirdValue);
  Serial.print("t");
  //Serial.print(fourthValue); // add these lines if needed
  Serial.println(); // send a carriage return for debugging 

  if(firstValue > 250){
  	digitalWrite(LED, HIGH);
      
  } else {
  	digitalWrite(LED, LOW);
  }

}
コード例 #21
0
ファイル: depthprobe.cpp プロジェクト: kosme/grbl0.8-Kosme
double depthProbe::depthProbeZero()
{
    double half=2.56,level = 0;
    int i;
    QString received;
    sendSerial(QString("G00 Z").append(QString::number(level)).append("\r"));
    for(i=0;i<8;i++)
    {
        received=readSerial(true);
        half=half/2;
        if(received.contains("depth"))
        {
            level+=half;
        }
        else
        {
            level-=half;
        }
        sendSerial(QString("G00 Z").append(QString::number(level)).append("\r"));
    }
    return level;
}
コード例 #22
0
ファイル: edfa.cpp プロジェクト: jhb123/SummerProject2016
bool edfa::getEmission(){
    bool emission = false; //This needs to be made better so that the method will return something if no emission is found.
    QString message;

    if(ready){
        writeSerial("OM\r\n");
        message = readSerial();
        qDebug() << "get EDFA emission message " << message;
        if (message.contains("OM ",Qt::CaseInsensitive)){
            message = stripString(message, "OM");
            qDebug() << "message contains OM";
            qDebug() << "New message " << message;
        }
    }
    if(message == "O"){
        emission = false;
    }
    if(message == "2"){
        emission = true;
    }

return emission;
}
コード例 #23
0
Dolle_UserApp::Dolle_UserApp(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Dolle_UserApp)
{
    ui->setupUi(this);
    ui->tempLCD->display("-----");
    arduino = new QSerialPort(this);
        serialBuffer = "";
        parsed_data = "";
        temperature_value = 0.0;
        humidity_value = 0.0;
        open_value = "Unknown";


        bool arduino_is_available = true;
        //Declare the Arduino port according to Unix standards
        //For Windows systems the default port would be "COM3"
        QString arduino_uno_port_name = "/dev/ttyACM0";

         /*  Open and configure the arduino port if available
         */
        if(arduino_is_available){
            qDebug() << "Found the arduino port...\n";
            arduino->setPortName(arduino_uno_port_name);
            arduino->open(QSerialPort::ReadOnly);
            arduino->setBaudRate(QSerialPort::Baud9600);
            arduino->setDataBits(QSerialPort::Data8);
            arduino->setFlowControl(QSerialPort::NoFlowControl);
            arduino->setParity(QSerialPort::NoParity);
            arduino->setStopBits(QSerialPort::OneStop);
            QObject::connect(arduino, SIGNAL(readyRead()), this, SLOT(readSerial()));
        }else{
            qDebug() << "Couldn't find the correct port for the arduino.\n";
            QMessageBox::information(this, "Serial Port Error", "Couldn't open serial port to arduino.");
        }
    }
コード例 #24
0
ファイル: MePS2.cpp プロジェクト: bq/bitbloq-compiler
/**
 * \par Function
 *    readjoystick
 * \par Description
 *    This function is used to read the handle datas.
 * \param[in]
 *    None
 * \par Output
 *    None
 * \par Return
 *    Returns 0 if no data ready, 1 if data ready.
 * \par Others
 *    None
 */
boolean MePS2::readjoystick(void)
{
  boolean result = false;
  if(millis() - _lasttime > 200)
  {
    _isReady = false;
    _isStart=false;
    _prevc = 0x00;
    buffer[2] = buffer[4] = buffer[6] =buffer[8] =0x80;
    buffer[1] = buffer[3] = buffer[5] =buffer[7] =0x00;
  }
  readSerial();
  while(_isAvailable)
  {
    _lasttime = millis();
    unsigned char c = _serialRead & 0xff;
    if((c == 0x55) && (_isStart == false))
    {
      if(_prevc == 0xff)
      {
        _index=1;
        _isStart = true;
      }
    }
    else
    {
      _prevc = c;
      if(_isStart)
      {
        writeBuffer(_index,c);
      }
    }
    _index++;
    if((_isStart == false) && (_index > 12))
    {
      _index=0; 
      _isStart=false;
      buffer[2] = buffer[4] = buffer[6] =buffer[8] =0x80;
      buffer[1] = buffer[3] = buffer[5] =buffer[7] =0x00;
    }
    else if(_isStart && (_index > 9))
    {
      uint8_t checksum;
      checksum = buffer[2]+buffer[3]+buffer[4]+buffer[5]+buffer[6]+buffer[7]+buffer[8];
      if(checksum == buffer[9])
      {
        _isReady = true;
       	_isStart = false;
       	_index = 0;
       	result = true;
      }
      else
      {
        _isStart = false;
        _index = 0;
        _prevc = 0x00;
        _isStart=false;
        result = false;
      }
    }
    readSerial();
   }
   return result;
}
コード例 #25
0
ファイル: pprinterserial.cpp プロジェクト: darkjavi/apc
pPrinterSerial::pPrinterSerial(printerType ptype, QObject *parent) :
    pPrinter(ptype,parent), m_serial(this)
{
    connect(&m_serial,SIGNAL(readyRead()),this,SLOT(readSerial()));
}
コード例 #26
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow) {
    ui->setupUi(this);

    _serialPort = new QextSerialPort;
    connect(_serialPort, SIGNAL(readyRead()), this, SLOT(readSerial()));

    QStringList serialCommandList;
    serialCommandList
    << "node.restart"
    << "node.dsleep"
    << "node.info"
    << "node.chipid"
    << "node.flashid"
    << "node.heap"
    << "node.key"
    << "node.led"
    << "node.input"
    << "node.output"
    << "node.readvdd33"
    << "node.compile"
    << "node.setcpufreq"
    << "node.restore"
    << "file.remove"
    << "file.open"
    << "file.close"
    << "file.readline"
    << "file.writeline"
    << "file.read"
    << "file.write"
    << "file.flush"
    << "file.seek"
    << "file.list"
    << "file.format"
    << "file.rename"
    << "file.fsinfo"
    << "wifi.setmode"
    << "wifi.getmode"
    << "wifi.getchannel"
    << "wifi.setphymode"
    << "wifi.getphymode"
    << "wifi.startsmart"
    << "wifi.stopsmart"
    << "wifi.sleeptype"
    << "wifi.sta.getconfig"
    << "wifi.sta.config"
    << "wifi.sta.connect"
    << "wifi.sta.disconnect"
    << "wifi.sta.autoconnect"
    << "wifi.sta.getip"
    << "wifi.sta.setip"
    << "wifi.sta.getmac"
    << "wifi.sta.setmac"
    << "wifi.sta.getap"
    << "wifi.sta.status"
    << "wifi.sta.getbroadcast"
    << "wifi.sta.eventMonReg"
    << "wifi.sta.eventMonStart"
    << "wifi.sta.eventMonStop"
    << "wifi.ap.config"
    << "wifi.ap.getip"
    << "wifi.ap.setip"
    << "wifi.ap.getmac"
    << "wifi.ap.setmac"
    << "wifi.ap.getbroadcast"
    << "tmr.delay"
    << "tmr.now"
    << "tmr.alarm"
    << "tmr.stop"
    << "tmr.wdclr"
    << "tmr.time"
    << "gpio.mode"
    << "gpio.read"
    << "gpio.write"
    << "gpio.trig"
    << "pwm.setup"
    << "pwm.close"
    << "pwm.start"
    << "pwm.stop"
    << "pwm.setclock"
    << "pwm.getclock"
    << "pwm.setduty"
    << "pwm.getduty"
    << "net.createServer"
    << "net.createConnection"
    << "net.server:listen"
    << "net.server:close"
    << "net.socket:connect"
    << "net.socket:send"
    << "net.socket:on"
    << "net.socket:close"
    << "net.socket:dns"
    << "i2c.setup"
    << "i2c.start"
    << "i2c.stop"
    << "i2c.address"
    << "i2c.write"
    << "i2c.read"
    << "adc.read"
    << "adc.readvdd33"
    << "uart.setup"
    << "uart.on"
    << "uart.write"
    << "ow.setup"
    << "ow.reset"
    << "ow.skip"
    << "ow.select"
    << "ow.write"
    << "ow.write_bytes"
    << "ow.read"
    << "ow.read_bytes"
    << "ow.depower"
    << "ow.reset_search"
    << "ow.target_search"
    << "ow.search"
    << "ow.crc8"
    << "ow.check_crc16"
    << "ow.crc16"
    << "bit.bnot"
    << "bit.band"
    << "bit.bor"
    << "bit.bxor"
    << "bit.lshift"
    << "bit.rshift"
    << "bit.arshift"
    << "bit.bit"
    << "bit.set"
    << "bit.clear"
    << "bit.isset"
    << "bit.isclear"
    << "spi.setup"
    << "spi.send"
    << "spi.recv"
    << "mqtt.Client"
    << "mqtt.client:lwt"
    << "mqtt.client:connect"
    << "mqtt.client:close"
    << "mqtt.client:publish"
    << "mqtt.client:subscribe"
    << "mqtt.client:on"
    << "ws2812.writergb"
    << "cjson.encode"
    << "cjson.decode"
    << "crypto.hash"
    << "crypto.hmac"
    << "crypto.mask"
    << "crypto.toHex"
    << "crypto.toBase64"
    << "u8g.ssd1306_128x64_i2c"
    << "u8g.ssd1306_128x64_spi"
    << "u8g.pcd8544_84x48"
    << "u8g.disp:begin"
    << "u8g.disp:drawBitmap"
    << "u8g.disp:drawBox"
    << "u8g.disp:drawCircle"
    << "u8g.disp:drawDisc"
    << "u8g.disp:drawEllipse"
    << "u8g.disp:drawFilledEllipse"
    << "u8g.disp:drawFrame"
    << "u8g.disp:drawHLine"
    << "u8g.disp:drawLine"
    << "u8g.disp:drawPixel"
    << "u8g.disp:drawRBox"
    << "u8g.disp:drawRFrame"
    << "u8g.disp:drawStr"
    << "u8g.disp:drawStr90"
    << "u8g.disp:drawStr180"
    << "u8g.disp:drawStr270"
    << "u8g.disp:drawTriangle"
    << "u8g.disp:drawVLine"
    << "u8g.disp:drawXBM"
    << "u8g.disp:firstPage"
    << "u8g.disp:getColorIndex"
    << "u8g.disp:getFontAscent"
    << "u8g.disp:getFontDescent"
    << "u8g.disp:getFontLineSpacing"
    << "u8g.disp:getHeight"
    << "u8g.disp:getMode"
    << "u8g.disp:getWidth"
    << "u8g.disp:getStrWidth"
    << "u8g.disp:nextPage"
    << "u8g.disp:setColorIndex"
    << "u8g.disp:setDefaultBackgroundColor"
    << "u8g.disp:setDefaultForegroundColor"
    << "u8g.disp:setFont"
    << "u8g.disp:setFontLineSpacingFactor"
    << "u8g.disp:setFontPosBaseline"
    << "u8g.disp:setFontPosBottom"
    << "u8g.disp:setFontPosCenter"
    << "u8g.disp:setFontPosTop"
    << "u8g.disp:setFontRefHeightAll"
    << "u8g.disp:setFontRefHeightExtendedText"
    << "u8g.disp:setFontRefHeightText"
    << "u8g.disp:setRot90"
    << "u8g.disp:setRot180"
    << "u8g.disp:setRot270"
    << "u8g.disp:setScale2x2"
    << "u8g.disp:sleepOn"
    << "u8g.disp:sleepOff"
    << "u8g.disp:undoRotation"
    << "u8g.disp:undoScale"
    << "dht.read"
    << "dht.read11"
    << "dht.readxx";

    _serialCommandCompleter = new QCompleter(serialCommandList, this);
    ui->serialSendComboBox->lineEdit()->setCompleter(_serialCommandCompleter);

    addEditorWindow();
}
コード例 #27
0
ファイル: application.cpp プロジェクト: palfrey/spark-proxy
void loop () {
    if (!initialised && !connected && (lastCheck + 5000 < millis())) {
        if (WiFi.ready()) {
            connect("www.apple.com", 80);
            if (connected) {
                client.println("GET /library/test/success.html HTTP/1.1");
                client.println("Host: www.apple.com");
                client.println();
                const char *success = "Success";
                unsigned int successLocation = 0;
                while (true) {
                    if (client.available()) {
                        int chr = client.read();
                        if (success[successLocation] == chr) {
                            successLocation ++;
                            if (successLocation == strlen(success)) {
                                initialised = true;
                                Spark.connect();
                                Spark.function("digitalread", tinkerDigitalRead);
                                Spark.function("digitalwrite", tinkerDigitalWrite);
                                Spark.function("analogread", tinkerAnalogRead);
                                Spark.function("analogwrite", tinkerAnalogWrite);
                                client.stop();
                                break;
                            }
                        }
                        else {
                            successLocation = 0;
                        }
                    }
                    else {
                        delay(2);
                    }
                }
            }
        }
        else {
            return;
        }
    }

    if (Serial.available()) {
        if (connected) {
            int bytes = Serial.available();
            for (int i=0; i<bytes; i++) {
                client.write(readSerial());
            }
        }
        else {
            int cmd = readSerial();
            switch (cmd) {
                case 'i':
                    Serial.println("Ready");
                    break;
                case 'c': {
                    char* host;
                    char* stringPort;
                    readWord(); // junk space
                    host = readWord();
                    stringPort = readWord();
                    connect(host, atol(stringPort));
                    free(host);
                    free(stringPort);
                    break;
                }
                case 'w': {
                    char* ssid;
                    char* password;
                    readWord();
                    ssid = readWord();
                    password = readWord();
                    Serial.print("Wifi credentials set to SSID '");
                    Serial.print(ssid);
                    Serial.print("' and password '");
                    Serial.print(password);
                    Serial.println("'");
                    WiFi.setCredentials(ssid, password);
                    break;
                }
                default:
                    Serial.print("Don't know command: ");
                    Serial.write(cmd);
                    Serial.println();
                    break;
            }
        }
    }
    if (connected) {
        int bytes = client.available();
        for (int i=0; i<bytes; i++) {
            Serial.write(client.read());
        }
        
        if (!client.connected()) {
            Serial.println();
            Serial.println("Disconnecting");
            client.stop();
            connected = false;
        }
    }
}
コード例 #28
0
ファイル: main.c プロジェクト: microblinks/l-firmware
/**
 * Main program.
 */
int main()
{   
    uchar i, errorCode;
    uint8_t oldRunning = 0, running;

    /* Disable the watchdog */
    MCUSR = 0;
    wdt_disable();

    /* Read the serial number from flash */
    readSerial();
  
    /* Read the flash checksum from EEPROM */
    readFlashChecksum();

    /* Initialize USB and enable global interrupts */
    initUSB();

    /* First initialize the PWM so all LEDs are off. */
    pwmInit(prescalingIndex);
    pwmSet(CHANNEL0, 0, 0);
    pwmSet(CHANNEL1, 0, 0);
    pwmSet(CHANNEL2, 0, 0);
    pwmSet(CHANNEL3, 0, 0);
    pwmSet(CHANNEL4, 0, 0);
    pwmSet(CHANNEL5, 0, 0);

    /* Initialize the blinks memory from eeprom */
    eeprom_busy_wait();
    eeprom_read_block(memory, (uint8_t*) 1, BLINKS_MEM_SIZE);

    /* Make sure bits 7 is cleared and bit 6 is set */
    memory[0] &= 0x7f;
    memory[0] |= 0x40;

    /* Initialize blinks */
    blinksScript.data = BLINKS_SCRIPT(memory);
    blinksScript.size = BLINKS_SCRIPT_SIZE;
    errorCode = 1;

    /* Infinite program loop */
    i = 0;
    uint16_t shutdown = 0;
    while ((memory[0] & 0x40) || (--shutdown))
    {
        /* Re-init PWM if needed */
        if (prescalingIndex != getPrescalingIndex())
        {
            prescalingIndex = getPrescalingIndex();
            pwmInit(prescalingIndex);
        }
        
        /* Process USB events */
        usbPoll();

        /* Execute special commands */
        switch (command)
        {
            case CMD_SAVE:
                eeprom_busy_wait();
                eeprom_write_block(memory, (uint8_t*) 1, BLINKS_MEM_SIZE);
                break;
        }
        command = 0;

        /* Reset script when running flag has changed or an error occurred */
        running = BLINKS_FLAGS(memory) & BLINKS_FLAG_RUNNING;
        if (running != oldRunning || errorCode)
        {
            errorCode = blinksReset(blinksScript);
            oldRunning = running;
        }

        /* Execute next step in program when program is running an no error
           occurred. */
        if (running && !errorCode)
            errorCode = blinksStep(blinksScript);
        
        /* Apply channel values */
        if (!errorCode)
        {
            unsigned char outputs = blinksCountOutputs(blinksScript);
            unsigned char invert = isInverted();
            if (outputs > 0) pwmSet(CHANNEL0, blinksGetOutput(blinksScript, 0), invert);
            if (outputs > 1) pwmSet(CHANNEL1, blinksGetOutput(blinksScript, 1), invert);
            if (outputs > 2) pwmSet(CHANNEL2, blinksGetOutput(blinksScript, 2), invert);
            if (outputs > 3) pwmSet(CHANNEL3, blinksGetOutput(blinksScript, 3), invert);
            if (outputs > 4) pwmSet(CHANNEL4, blinksGetOutput(blinksScript, 4), invert);
            if (outputs > 5) pwmSet(CHANNEL5, blinksGetOutput(blinksScript, 5), invert);
        }

        /* When this loop has been executed for 100 times then
           mark the flash as OK */
        if ((flashChecksum != FLASH_CHECKSUM) && (i < 100))
        {
            i++;
            if (i == 100)
            {
                flashChecksum = FLASH_CHECKSUM;
                writeFlashChecksum();
            }
        }
    }

    enterBootloader();

    return 0;
}
コード例 #29
0
ファイル: modeegdriver.c プロジェクト: BCI-AR/NeuroServer
int main(int argc, char **argv)
{
    char responseBuf[MAXLEN];
    int i;
    int retval;
    ser_t serport;
    char EDFPacket[MAXHEADERLEN];
    int EDFLen = MAXHEADERLEN;
    /// buffer for reading from serial port
    char smallbuf[PROTOWINDOW];
    char *hostname = NULL;
    char *deviceName = NULL;
    /// DEFAULTHOST;
    unsigned short portno = 0;
    ///  DEFAULTPORT;
    struct timeval when;

    rprintf("ModEEG Driver v. %s-%s\n", VERSION, OSTYPESTR);

    rinitNetworking();
    /// process command line inputs
    for (i = 1; argv[i]; ++i) {
        if (argv[i][0] == '-' && argv[i][1] == 'h') {
            printHelp();
            exit(0);
        }
        if (argv[i][0] == '-' && argv[i][1] == 'd') {
            if (argv[i+1] == NULL) {
                rprintf("Bad devicename option: %s\nExpected device name as next argument.\n", argv[i]);
                exit(1);
            }
            deviceName = argv[i+1];
            i += 1;
            continue;
        }
        if (hostname == NULL) {
            hostname = argv[i];
            continue;
        }
        if (portno == 0) {
            portno = atoi(argv[i]);
            continue;
        }
    }
    if (deviceName == NULL)
        deviceName = DEFAULTDEVICE;
    if (portno == 0)
        portno = DEFAULTPORT;
    if (hostname == NULL)
        hostname = DEFAULTHOST;

    makeREDFConfig(&current, &modEEGCfg);
    writeEDFString(&current, EDFPacket, &EDFLen);


    sock_fd = rsocket();
    if (sock_fd < 0) {
        perror("socket");
        rexit(1);
    }
    setblocking(sock_fd);

    rprintf("Attempting to connect to nsd at %s:%d\n", hostname, portno);
    retval = rconnectName(sock_fd, hostname, portno);
    if (retval != 0) {
        rprintf("connect error\n");
        rexit(1);
    }
    rprintf("Socket connected.\n");
    fflush(stdout);

    serport = openSerialPort(deviceName,57600);
    rprintf("Serial port %s opened.\n", deviceName);

    writeString(sock_fd, "eeg\n", &ob);
    mGetOK(sock_fd, &ib);
    writeString(sock_fd, "setheader ", &ob);
    writeBytes(sock_fd, EDFPacket, EDFLen, &ob);
    writeString(sock_fd, "\n", &ob);
    mGetOK(sock_fd, &ib);
    updateMaxFd(sock_fd);
#ifndef __MINGW32__
    updateMaxFd(serport);
#endif
    when.tv_usec = (1000000L / modEEGCfg.chan[0].sampleCount);
    rprintf("Polling at %d Hertz or %d usec\n", modEEGCfg.chan[0].sampleCount, when.tv_usec);
    for (;;) {
        int i, readSerBytes;
        int retval;
        fd_set toread;
        when.tv_sec = 0;
        when.tv_usec = (1000000L / modEEGCfg.chan[0].sampleCount);
        FD_ZERO(&toread);
        FD_SET(sock_fd, &toread);
#ifndef __MINGW32__
        FD_SET(serport, &toread);
#endif
        retval = rselect_timed(max_fd, &toread, NULL, NULL, &when);
        readSerBytes = readSerial(serport, smallbuf, PROTOWINDOW);
        if (readSerBytes < 0) {
            rprintf("Serial error.\n");
        }
        if (readSerBytes > 0) {
            for (i = 0; i < readSerBytes; ++i)
                eatCharacter(smallbuf[i]);
        }
        if (FD_ISSET(sock_fd, &toread)) {
            my_read(sock_fd, responseBuf, MAXLEN, &ib);
        }
        if (isEOF(sock_fd, &ib)) {
            rprintf("Server died, exitting.\n");
            exit(0);
        }
    }

    return 0;
}
コード例 #30
0
void stk500service::flushData() {
    char tmp[512];
    memset(tmp, 0, sizeof(tmp));
    _handler->getPort()->write(tmp, sizeof(tmp));
    readSerial(tmp, sizeof(tmp));
}