Пример #1
0
/* Leave pin off for time (given in microseconds) */
void IRsend::space(int time) {
  // Sends an IR space for the specified number of microseconds.
  // A space is no output, so the PWM output is disabled.
  digitalWrite(IRpin, LOW);
  if (time > 0) delayMicroseconds(time);
}
void pwmSetRangeWPi (unsigned int range)
{
  *(pwm + PWM0_RANGE) = range ; delayMicroseconds (10) ;
  *(pwm + PWM1_RANGE) = range ; delayMicroseconds (10) ;
}
Пример #3
0
void LiquidCrystal::home()
{
  command(LCD_RETURNHOME);  // set cursor position to zero
  delayMicroseconds(2000);  // this command takes a long time!
}
Пример #4
0
void LCD::home()
{
   command(LCD_RETURNHOME);             // set cursor position to zero
   delayMicroseconds(HOME_CLEAR_EXEC);  // This command is time consuming
}
Пример #5
0
void initMPU6000(void)
{
    ///////////////////////////////////

    GPIO_ResetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);
    spiTransfer(MPU6000_SPI, MPU6000_PWR_MGMT_1);          // Device Reset
    spiTransfer(MPU6000_SPI, BIT_H_RESET);
    GPIO_SetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);

    delay(150);

    GPIO_ResetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);
    spiTransfer(MPU6000_SPI, MPU6000_PWR_MGMT_1);          // Clock Source PPL with Z axis gyro reference
    spiTransfer(MPU6000_SPI, MPU_CLK_SEL_PLLGYROZ);
    GPIO_SetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);

    delayMicroseconds(1);

    GPIO_ResetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);
    spiTransfer(MPU6000_SPI, MPU6000_USER_CTRL);           // Disable Primary I2C Interface
    spiTransfer(MPU6000_SPI, BIT_I2C_IF_DIS);
    GPIO_SetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);

    delayMicroseconds(1);

    GPIO_ResetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);
    spiTransfer(MPU6000_SPI, MPU6000_PWR_MGMT_2);
    spiTransfer(MPU6000_SPI, 0x00);
    GPIO_SetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);

    delayMicroseconds(1);

    GPIO_ResetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);
    spiTransfer(MPU6000_SPI, MPU6000_SMPLRT_DIV);          // Accel Sample Rate 1000 Hz, Gyro Sample Rate 8000 Hz
    spiTransfer(MPU6000_SPI, 0x00);
    GPIO_SetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);

    delayMicroseconds(1);

    GPIO_ResetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);
    spiTransfer(MPU6000_SPI, MPU6000_CONFIG);              // Accel and Gyro DLPF Setting
    spiTransfer(MPU6000_SPI, eepromConfig.dlpfSetting);
    GPIO_SetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);

    delayMicroseconds(1);

    GPIO_ResetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);
    spiTransfer(MPU6000_SPI, MPU6000_ACCEL_CONFIG);        // Accel +/- 4 G Full Scale
    spiTransfer(MPU6000_SPI, BITS_FS_4G);
    GPIO_SetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);

    delayMicroseconds(1);

    GPIO_ResetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);
    spiTransfer(MPU6000_SPI, MPU6000_GYRO_CONFIG);         // Gyro +/- 1000 DPS Full Scale
    spiTransfer(MPU6000_SPI, BITS_FS_1000DPS);
    GPIO_SetBits(MPU6000_CS_GPIO, MPU6000_CS_PIN);

    ///////////////////////////////////

    setSPIdivisor(MPU6000_SPI, 2);                         // 21 MHz SPI clock (within 20 +/- 10%)

    ///////////////////////////////////

    delay(100);

    computeMPU6000RTData();
}
void NewRemoteTransmitter::_sendStopPulse() {
	digitalWrite(_pin, HIGH);
	delayMicroseconds(_periodusec);
	digitalWrite(_pin, LOW);
	delayMicroseconds(_periodusec * 40);
}
Пример #7
0
void Modbus_WaitForReply(void)
{
#define MODBUS_TIMEOUT	1000	// millis
	mb_state = RECEIVING_DATA;
	buffer = 0;
	timeout = millis();	// wait up to one second for reply
//	if ( (*ModbusPort).available() ) // is there something to check?
	while ( (millis()-timeout)<MODBUS_TIMEOUT && mb_state==RECEIVING_DATA )
	{
		while ( ec_client.available() )
		{
			WDG_RST;  // avoid reset
			// The maximum number of bytes is limited to the serial buffer size of BUFFER_SIZE.
			// If more bytes is received than BUFFER_SIZE, the overflow flag will be set and
			// the serial buffer will be flushed as long as the slave is still responding.
			uint8_t mb_data = ec_client.read();
			//Serial.println(mb_data,HEX);	// debug
			if ( mb_state==RECEIVING_DATA )	{
				if ( buffer==0 && mb_data==0 )	continue;	// workaround for leading '0'
				// read and check data byte
				if ( buffer>=BUFFER_SIZE )
					ProcessError(BUFFER_OVERFLOW);	// buffer size overflow
				else if ( buffer==0 && mb_data!=frame[0] )
					ProcessError(WRONG_ID);	// wrong slave ID
				else if ( buffer==1 && (mb_data!=frame[1] || (0x80&frame[1])) )
					ProcessError(WRONG_FUNCTION);	// wrong function code
				else if ( buffer==2 && mb_data!=2*frame[5] )
					ProcessError(WRONG_DATA_LEN);	// wrong data lenght
			}
			if ( mb_state==RECEIVING_DATA )	// store data byte only if no error detected so far
			{
				frame[buffer++] = mb_data;  // store data and increment index
				 // check frame length and CRC
				if ( buffer>2 && (frame[2]+5)==buffer )	// last byte of frame received
				{
					*(uint16_t *)&frame[buffer] = *(uint16_t *)&frame[buffer-2];	// save received CRC
					CalculateCRC(buffer-2);	// overwrite received CRC with calculated value in the frame buffer
					if ( *(uint16_t *)&frame[buffer] != *(uint16_t *)&frame[buffer-2] )
						ProcessError(WRONG_CRC);	// wrong CRCs
					else
						ProcessSuccess();	// complete and correct reply frame received
				}
			}
			// insert inter character time out if no new data received yet
			if ( !ec_client.available() )
				delayMicroseconds(T1_5);
		}

		////////// END OF FRAME RECPTION //////////
		WDG_RST;  // avoid reset

		// The minimum buffer size from a slave can be an exception response of 5 bytes.
		// If the buffer was partially filled set a frame_error.
		if ( buffer>0 )
			ProcessError(WRONG_FRAME_LEN);	// too few bytes received
	}
	WDG_RST;  // avoid reset
	if ( buffer==0 )
		ProcessError(REPLY_TIMEOUT);	// timeout error, no data received
	startDelay = millis(); // starting delay
}
Пример #8
0
static int16_t ucg_com_arduino_illi9325_SW_SPI(ucg_t *ucg, int16_t msg, uint16_t arg, uint8_t *data)
{

  switch(msg)
  {
    case UCG_COM_MSG_POWER_UP:
      /* "data" is a pointer to ucg_com_info_t structure with the following information: */
      /*	((ucg_com_info_t *)data)->serial_clk_speed value in nanoseconds */
      /*	((ucg_com_info_t *)data)->parallel_clk_speed value in nanoseconds */

#ifdef __AVR__
      ucg_com_arduino_init_shift_out(ucg->pin_list[UCG_PIN_SDA], ucg->pin_list[UCG_PIN_SCL]);
#endif
    
      /* setup pins */
      pinMode(ucg->pin_list[UCG_PIN_CD], OUTPUT);
      pinMode(ucg->pin_list[UCG_PIN_SDA], OUTPUT);
      pinMode(ucg->pin_list[UCG_PIN_SCL], OUTPUT);
      if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
	pinMode(ucg->pin_list[UCG_PIN_CS], OUTPUT);
      if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
	pinMode(ucg->pin_list[UCG_PIN_RST], OUTPUT);

      digitalWriteFast(ucg->pin_list[UCG_PIN_CD], 1);
      digitalWriteFast(ucg->pin_list[UCG_PIN_SDA], 1);
      digitalWriteFast(ucg->pin_list[UCG_PIN_SCL], 0);
      if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
	digitalWriteFast(ucg->pin_list[UCG_PIN_CS], 1);
      if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
	digitalWriteFast(ucg->pin_list[UCG_PIN_RST], 1);

      break;
    case UCG_COM_MSG_POWER_DOWN:
      break;
    case UCG_COM_MSG_DELAY:
      delayMicroseconds(arg);
      break;
    case UCG_COM_MSG_CHANGE_RESET_LINE:
      if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
	digitalWriteFast(ucg->pin_list[UCG_PIN_RST], arg);
      break;
      
    case UCG_COM_MSG_CHANGE_CS_LINE:
#ifdef __AVR__
      ucg_com_arduino_init_shift_out(ucg->pin_list[UCG_PIN_SDA], ucg->pin_list[UCG_PIN_SCL]);
#endif    
      if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
	digitalWriteFast(ucg->pin_list[UCG_PIN_CS], arg);      
      break;
      
    case UCG_COM_MSG_CHANGE_CD_LINE:
      if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
      {
	digitalWriteFast(ucg->pin_list[UCG_PIN_CS], 1);      
	digitalWriteFast(ucg->pin_list[UCG_PIN_CS], 0);      
      }

      if ( ucg->com_status & UCG_COM_STATUS_MASK_CD )
	ucg_com_arduino_send_generic_SW_SPI(ucg, 0x072);
      else
	ucg_com_arduino_send_generic_SW_SPI(ucg, 0x070);      
	
      break;
      
    case UCG_COM_MSG_SEND_BYTE:
      ucg_com_arduino_send_generic_SW_SPI(ucg, arg);
      break;
    case UCG_COM_MSG_REPEAT_1_BYTE:
      while( arg > 0 ) {
	ucg_com_arduino_send_generic_SW_SPI(ucg, data[0]);
	arg--;
      }
      break;
    case UCG_COM_MSG_REPEAT_2_BYTES:
      while( arg > 0 ) {
	ucg_com_arduino_send_generic_SW_SPI(ucg, data[0]);
	ucg_com_arduino_send_generic_SW_SPI(ucg, data[1]);
	arg--;
      }
      break;
    case UCG_COM_MSG_REPEAT_3_BYTES:
      while( arg > 0 ) {
	ucg_com_arduino_send_generic_SW_SPI(ucg, data[0]);
	ucg_com_arduino_send_generic_SW_SPI(ucg, data[1]);
	ucg_com_arduino_send_generic_SW_SPI(ucg, data[2]);
	arg--;
      }
      break;
    case UCG_COM_MSG_SEND_STR:
      while( arg > 0 ) {
	ucg_com_arduino_send_generic_SW_SPI(ucg, *data++);
	arg--;
      }
      break;
    case UCG_COM_MSG_SEND_CD_DATA_SEQUENCE:
      while(arg > 0)
      {
	if ( *data != 0 )
	{
	  if ( *data == 1 )
	  {
	    if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
	    {
	      digitalWriteFast(ucg->pin_list[UCG_PIN_CS], 1);      
	      digitalWriteFast(ucg->pin_list[UCG_PIN_CS], 0);      
	    }
	    ucg_com_arduino_send_generic_SW_SPI(ucg, 0x070);
	  }
	  else
	  {
	    if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
	    {
	      digitalWriteFast(ucg->pin_list[UCG_PIN_CS], 1);      
	      digitalWriteFast(ucg->pin_list[UCG_PIN_CS], 0);      
	    }
	    ucg_com_arduino_send_generic_SW_SPI(ucg, 0x072);
	  }
	}
	data++;
	ucg_com_arduino_send_generic_SW_SPI(ucg, *data);
	data++;
	arg--;
      }
      break;
  }
  return 1;
}
Пример #9
0
static int16_t ucg_com_arduino_3wire_9bit_SW_SPI(ucg_t *ucg, int16_t msg, uint16_t arg, uint8_t *data)
{

  switch(msg)
  {
    case UCG_COM_MSG_POWER_UP:
      /* "data" is a pointer to ucg_com_info_t structure with the following information: */
      /*	((ucg_com_info_t *)data)->serial_clk_speed value in nanoseconds */
      /*	((ucg_com_info_t *)data)->parallel_clk_speed value in nanoseconds */
      
      /* setup pins */
      pinMode(ucg->pin_list[UCG_PIN_SDA], OUTPUT);
      pinMode(ucg->pin_list[UCG_PIN_SCL], OUTPUT);
      if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
	pinMode(ucg->pin_list[UCG_PIN_CS], OUTPUT);
      if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
	pinMode(ucg->pin_list[UCG_PIN_RST], OUTPUT);

      digitalWriteFast(ucg->pin_list[UCG_PIN_SDA], 1);
      digitalWriteFast(ucg->pin_list[UCG_PIN_SCL], 0);
      if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
	digitalWriteFast(ucg->pin_list[UCG_PIN_CS], 1);
      if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
	digitalWriteFast(ucg->pin_list[UCG_PIN_RST], 1);

      break;
    case UCG_COM_MSG_POWER_DOWN:
      break;
    case UCG_COM_MSG_DELAY:
      delayMicroseconds(arg);
      break;
    case UCG_COM_MSG_CHANGE_RESET_LINE:
      if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
	digitalWriteFast(ucg->pin_list[UCG_PIN_RST], arg);
      break;
    case UCG_COM_MSG_CHANGE_CS_LINE:
      if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
	digitalWriteFast(ucg->pin_list[UCG_PIN_CS], arg);
      break;
    case UCG_COM_MSG_CHANGE_CD_LINE:
      /* ignored, there is not CD line */
      break;
    case UCG_COM_MSG_SEND_BYTE:
      ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, arg);
      break;
    case UCG_COM_MSG_REPEAT_1_BYTE:
      while( arg > 0 ) {
	ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[0]);
	arg--;
      }
      break;
    case UCG_COM_MSG_REPEAT_2_BYTES:
      while( arg > 0 ) {
	ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[0]);
	ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[1]);
	arg--;
      }
      break;
    case UCG_COM_MSG_REPEAT_3_BYTES:
      while( arg > 0 ) {
	ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[0]);
	ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[1]);
	ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[2]);
	arg--;
      }
      break;
    case UCG_COM_MSG_SEND_STR:
      while( arg > 0 ) {
	ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, *data++);
	arg--;
      }
      break;
    case UCG_COM_MSG_SEND_CD_DATA_SEQUENCE:
      {
	uint8_t last_cd = ucg->com_status &UCG_COM_STATUS_MASK_CD;
	while(arg > 0)
	{
	  if ( *data != 0 )
	  {
	    if ( *data == 1 )
	    {
	      last_cd = 0;
	    }
	    else
	    {
	      last_cd = 1;
	    }
	  }
	  data++;
	  ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, last_cd, *data); 
	  data++;
	  arg--;
	}
      }
      break;
  }
  return 1;
}
void HD7279A::sendCmdAndData(unsigned char cmd, unsigned char data) {
	delayMicroseconds(50);
	sendRawData(cmd);
	delayMicroseconds(20);
	sendRawData(data);
}
Пример #11
0
void delay(uint32_t ms)
{
    while (ms--)
        delayMicroseconds(1000);
}
void HD7279A::sendCmd(unsigned char cmd) {
	digitalWrite(clkPin, 0);
	delayMicroseconds(50);
	sendRawData(cmd);
}
Пример #13
0
uint8_t OS_SoftSPIClass::transfer(uint8_t _data) {
  uint8_t index;
  uint8_t shiftIn;
  uint8_t shiftOut;
  int reg;

  //
  // SPI implements a virtual ring that exchanges a byte
  // (or other sized word) from the master to the slave a
  // single bit at a time.
  //
  // Note: some chips may exchange a word of different
  // bit size. For example some A/D chips will transfer
  // 12 bits for their samples. See the chip programming
  // data sheet. This class may need to be updated to exchange
  // larger bit sizes as it currently uses the default 8.
  //
  // If you do this, create a transfer12() or other function
  // since its likely the chip will require a mixture of
  // byte commands and 12 bit readings depending on the
  // chip.
  //
  // A Chip Select (CS) line is set to LOW to enable a chip
  // before communication is started. By default HIGH deselects
  // the chip. Only one chip may be selected at a time
  // to allow for multi-drop support.
  //
  // The Chip Select (CS) is the responsibility of the caller/user
  // of this class, including waiting any chip specific wait
  // times. For example a humidity sensor requires some number
  // of milliseconds once its CS is asserted before data
  // may be transfered using this function.
  //
  // The SCK line clocks the data in and out. Its IDLE value
  // depends on the Clock Polarity (CPOL) value.
  // CPOL=0 clock is IDLE low
  // CPOL=1 clock is IDLE high
  //
  // A bit is sampled at either the assertion, or de-assertion
  // of the SCK signal depending on the configured Clock Phase
  //(CPHA). In either case, the data must be stable at the time
  // it is sampled.
  //
  // Both devices expect a whole, word to be exchanged per transfer,
  // so 8 SCLK transitions are expected for a byte transfer sequence.
  //
  // Since this is a data exchange between the master and the slave,
  // the send/write data is shifted out of the MOSI (Master Out Slave In)
  // port at the same time the receive/read data is shifted in from the
  // MISO (Master In Slave Out) port.
  //
  // Whether the Most Significant Bit (MSB) or the Least Significant Bit
  // (LSB) is transferred first depends on the configured bit order
  // in setBitOrder().
  //
  // There is always a received word from the slave device when a word is
  // sent as the serial ring protocol demands it. This function will always
  // return that value, but the caller may not use it depending on the device
  // and its protocol. In many device sequences there a series of commands
  // which act in one direction, and responses, reads which return meanful
  // data.
  //
  // For example, many devices internally implement a "virtual register file"
  // similar to a set of I/O ports. Commands typically look like:
  //
  // Register Read:
  //
  // transfer(READ_REGISTER_COMMAND);
  // regValue = transfer(REGISTER_NUMBER);
  //
  // Register Write:
  //
  // transfer(WRITE_REGISTER_COMMAND);
  // transfer(REGISTER_NUMBER);
  // transfer(data_value);
  //

  // The caller controls CSN select, so issue its delay here if set
  delayMicroseconds(m_csnDelay);

  shiftIn = 0;
  shiftOut = _data;

  if (m_lsbFirst) {

    for(index = 0; index < 8; index++) {

      shiftIn >>= 1;

      // Send the bit
      if (shiftOut & 0x01) {
	reg = HIGH;
      }
      else {
        reg = LOW;
      }

      //
      // Write the output bit to the slave
      //
      // Note: We hold the data stable for the
      // entire SCK transition from ASSERT to
      // IDLE. This allows either clock phase
      // configured to work since the data is stable
      // for both rising edge and falling edge.
      //
      // In addition we read the slave value while the
      // SCK is ASSERTed which works for either
      // polarity.
      //
      digitalWrite(m_mosi, reg);

      // Delay our MOSI setup time for the slave
      delayMicroseconds(m_mosiDelay);

      //clock it
      digitalWrite(m_sck, m_sckAssert);

      // Delay our MISO valid time for the slave to respond
      // before we sample it
      delayMicroseconds(m_misoDelay);

      // Read the input bit from the slave
      reg = digitalRead(m_miso);

      //
      // We clock as fast as possible.
      // Could insert a delay before the next
      // digitalWrite to slow down the clock if
      // required.
      //
      digitalWrite(m_sck, m_sckIdle);

      if (reg != LOW) {
	 shiftIn |= 0x80;
      }
      else {
	 shiftIn &= 0xFE;
      }

      shiftOut >>= 1;
    }
  }
  else {

    // MSB First
    for(index = 0; index < 8; index++) {
Пример #14
0
void jshDelayMicroseconds(int microsec) {
  delayMicroseconds(microsec);
}
Пример #15
0
int main(int argc, const char* argv[])
{
	int result = 1;
	// run this program in background when not in Debug mode
#ifndef DEBUG
	{
		pid_t pid, sid;
		pid = fork();
		if (pid < 0)
		{
			exit(EXIT_FAILURE);
		}
		if (pid > 0)
		{
			exit(EXIT_SUCCESS);
		}
		
		// change file mode mask
		umask(0);
		// open logs,,, but I did not record any logs
		
		// create SID for child process
		sid = setsid();
		if (sid < 0)
		{
			exit(EXIT_FAILURE);
		}
		
		close(STDIN_FILENO);
		close(STDOUT_FILENO);
		//close(STDERR_FILENO);
	}
#endif	
	signal(SIGINT, break_program);
	
	// First to setup wiringPi
	if (wiringPiSetup() < 0)
	{
		fprintf(stderr, "Unable to setup wiringPi: %s \n", strerror(errno));
		return 1;	//exit(1);
	}
	pinMode(TRIG_GPIO_PIN, OUTPUT);
	pinMode(ECHO_GPIO_PIN, INPUT);
	pullUpDnControl(ECHO_GPIO_PIN, PUD_DOWN);

	if (wiringPiISR (ECHO_GPIO_PIN, INT_EDGE_BOTH, &myInterrupt) < 0)
	{
		fprintf (stderr, "Unable to setup ISR: %s\n", strerror (errno)) ;
		return 1 ;
	}


	
	loopingStatus = 1;
#ifdef DEBUG
	printf("All initialized...\n");
#endif
	while(loopingStatus)
	{
#ifdef DEBUG
	printf("waiting for signal...\n");
#endif
		digitalWrite(TRIG_GPIO_PIN, LOW);
		delayMicroseconds(10);
		digitalWrite(TRIG_GPIO_PIN, HIGH);
		usleep(10);
		digitalWrite(TRIG_GPIO_PIN, LOW);
		sleep(5);
	}
	
	return 0;
}
Пример #16
0
/********** high level commands, for the user! */
void st7032_clear()
{
  st7032_command(LCD_CLEARDISPLAY);  // clear display, set cursor position to zero
  delayMicroseconds(2000);  // this command takes a long time!
}
void NewRemoteTransmitter::_sendStartPulse(){
	digitalWrite(_pin, HIGH);
	delayMicroseconds(_periodusec);
	digitalWrite(_pin, LOW);
	delayMicroseconds(_periodusec * 10 + (_periodusec >> 1)); // Actually 10.5T insteat of 10.44T. Close enough.
}
Пример #18
0
void st7032_home()
{
  st7032_command(LCD_RETURNHOME);  // set cursor position to zero
  delayMicroseconds(2000);  // this command takes a long time!
}
Пример #19
0
// * Receiving the lenght of bytes from Serial port
void HerkulexClass::readData(int size)
{
	int i = 0;
    int beginsave=0;
    int Time_Counter=0;
    switch (port)
	{
	case SSerial:

        while((SwSerial.available() < size) & (Time_Counter < TIME_OUT)){
        		Time_Counter++;
        		delayMicroseconds(1000);  //wait 1 millisecond for 10 times
		}
        	
		while (SwSerial.available() > 0){
			byte inchar = (byte)SwSerial.read();
			if ( (inchar == 0xFF) & ((byte)SwSerial.peek() == 0xFF) ){
					beginsave=1; 
					i=0; 				 // if found new header, begin again
			}
			if (beginsave==1 && i<size) {
				   dataEx[i] = inchar;
				   i++;
			}
		}
		SwSerial.flush();
		break;
	
	#if defined (__AVR_ATmega1280__) || defined (__AVR_ATmega128__) || defined (__AVR_ATmega2560__)
	case HSerial1:
		while((Serial1.available() < size) & (Time_Counter < TIME_OUT)){
        		Time_Counter++;
        		delayMicroseconds(1000);
		}      	
		while (Serial1.available() > 0){
      		byte inchar = (byte)Serial1.read();
			//printHexByte(inchar);
        	if ( (inchar == 0xFF) & ((byte)Serial1.peek() == 0xFF) ){
						beginsave=1;
						i=0; 						
             }
            if (beginsave==1 && i<size) {
                       dataEx[i] = inchar;
                       i++;
			}
		}
		break;
	
	case HSerial2:
	    while((Serial2.available() < size) & (Time_Counter < TIME_OUT)){
        		Time_Counter++;
        		delayMicroseconds(1000);
		}
        	
		while (Serial2.available() > 0){
			byte inchar = (byte)Serial2.read();
			if ( (inchar == 0xFF) & ((byte)Serial2.peek() == 0xFF) ){
					beginsave=1;
					i=0; 					
			}
			if (beginsave==1 && i<size) {
				   dataEx[i] = inchar;
				   i++;
			}
		}
		break;

	case HSerial3:
		while((Serial3.available() < size) & (Time_Counter < TIME_OUT)){
			Time_Counter++;
			delayMicroseconds(1000);
		}
		
		while (Serial3.available() > 0){
			byte inchar = (byte)Serial3.read();
			if ( (inchar == 0xFF) & ((byte)Serial3.peek() == 0xFF) ){
					beginsave=1;
					i=0; 
			}
			if (beginsave==1 && i<size) {
				   dataEx[i] = inchar;
				   i++;
			}
		}
		break;
	#endif
	}
}
Пример #20
0
void MyTM1637::bitDelay(void)
{
	delayMicroseconds(50);
}
Пример #21
0
// Common LCD Commands
// ---------------------------------------------------------------------------
void LCD::clear()
{
   command(LCD_CLEARDISPLAY);             // clear display, set cursor position to zero
   delayMicroseconds(HOME_CLEAR_EXEC);    // this command is time consuming
}
Пример #22
0
boolean DHT::read(void) {
  uint8_t laststate = HIGH;
  uint8_t counter = 0;
  uint8_t j = 0, i;
  unsigned long currenttime;

  // pull the pin high and wait 250 milliseconds
  digitalWrite(_pin, HIGH);
  delay(250);

  currenttime = millis();
  if (currenttime < _lastreadtime) {
    // ie there was a rollover
    _lastreadtime = 0;
  }
  if (!firstreading && ((currenttime - _lastreadtime) < 2000)) {
    return true; // return last correct measurement
    //delay(2000 - (currenttime - _lastreadtime));
  }
  firstreading = false;
  /*
Serial.print("Currtime: "); Serial.print(currenttime);
Serial.print(" Lasttime: "); Serial.print(_lastreadtime);
*/
  _lastreadtime = millis();

  data[0] = data[1] = data[2] = data[3] = data[4] = 0;
  
  // now pull it low for ~20 milliseconds
  pinMode(_pin, OUTPUT);
  digitalWrite(_pin, LOW);
  delay(20);
  cli();
  digitalWrite(_pin, HIGH);
  delayMicroseconds(40);
  pinMode(_pin, INPUT);

  // read in timings
  for ( i=0; i< MAXTIMINGS; i++) {
    counter = 0;
    while (digitalRead(_pin) == laststate) {
      counter++;
      delayMicroseconds(1);
      if (counter == 255) {
        break;
      }
    }
    laststate = digitalRead(_pin);

    if (counter == 255) break;

    // ignore first 3 transitions
    if ((i >= 4) && (i%2 == 0)) {
      // shove each bit into the storage bytes
      data[j/8] <<= 1;
      if (counter > _count)
        data[j/8] |= 1;
      j++;
    }

  }

  sei();
  
  /*
Serial.println(j, DEC);
Serial.print(data[0], HEX); Serial.print(", ");
Serial.print(data[1], HEX); Serial.print(", ");
Serial.print(data[2], HEX); Serial.print(", ");
Serial.print(data[3], HEX); Serial.print(", ");
Serial.print(data[4], HEX); Serial.print(" =? ");
Serial.println(data[0] + data[1] + data[2] + data[3], HEX);
*/

  // check we read 40 bits and that the checksum matches
  if ((j >= 40) &&
      (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) {
    return true;
  }
  

  return false;

}
Пример #23
0
// PUBLIC METHODS
// ---------------------------------------------------------------------------
// When the display powers up, it is configured as follows:
//
// 1. Display clear
// 2. Function set: 
//    DL = 1; 8-bit interface data 
//    N = 0; 1-line display 
//    F = 0; 5x8 dot character font 
// 3. Display on/off control: 
//    D = 0; Display off 
//    C = 0; Cursor off 
//    B = 0; Blinking off 
// 4. Entry mode set: 
//    I/D = 1; Increment by 1 
//    S = 0; No shift 
//
// Note, however, that resetting the Arduino doesn't reset the LCD, so we
// can't assume that its in that state when a sketch starts (and the
// LiquidCrystal constructor is called).
// A call to begin() will reinitialize the LCD.
//
void LCD::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) 
{
   if (lines > 1) 
   {
      _displayfunction |= LCD_2LINE;
   }
   _numlines = lines;
   _cols = cols;
   
   // for some 1 line displays you can select a 10 pixel high font
   // ------------------------------------------------------------
   if ((dotsize != LCD_5x8DOTS) && (lines == 1)) 
   {
      _displayfunction |= LCD_5x10DOTS;
   }
   
   // SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION!
   // according to datasheet, we need at least 40ms after power rises above 2.7V
   // before sending commands. Arduino can turn on way before 4.5V so we'll wait 
   // 50
   // ---------------------------------------------------------------------------
   delay (100); // 100ms delay
   
   //put the LCD into 4 bit or 8 bit mode
   // -------------------------------------
   if (! (_displayfunction & LCD_8BITMODE)) 
   {
      // this is according to the hitachi HD44780 datasheet
      // figure 24, pg 46
      
      // we start in 8bit mode, try to set 4 bit mode
      send(0x03, FOUR_BITS);
      delayMicroseconds(4500); // wait min 4.1ms
      
      // second try
      send ( 0x03, FOUR_BITS );
      delayMicroseconds(4500); // wait min 4.1ms
      
      // third go!
      send( 0x03, FOUR_BITS );
      delayMicroseconds(150);
      
      // finally, set to 4-bit interface
      send ( 0x02, FOUR_BITS ); 
   } 
   else 
   {
      // this is according to the hitachi HD44780 datasheet
      // page 45 figure 23
      
      // Send function set command sequence
      command(LCD_FUNCTIONSET | _displayfunction);
      delayMicroseconds(4500);  // wait more than 4.1ms
      
      // second try
      command(LCD_FUNCTIONSET | _displayfunction);
      delayMicroseconds(150);
      
      // third go
      command(LCD_FUNCTIONSET | _displayfunction);
   }
   
   // finally, set # lines, font size, etc.
   command(LCD_FUNCTIONSET | _displayfunction);  
   
   // turn the display on with no cursor or blinking default
   _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF;  
   display();
   
   // clear the LCD
   clear();
   
   // Initialize to default text direction (for romance languages)
   _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT;
   // set the entry mode
   command(LCD_ENTRYMODESET | _displaymode);

   backlight();

}
Пример #24
0
uint8_t PSX64::config_gamepad(uint8_t clk, uint8_t cmd, uint8_t att, uint8_t dat, bool pressures, bool rumble) {

   uint8_t temp[sizeof(type_read)];
  
 _clk_mask = maskToBitNum(digitalPinToBitMask(clk));
 _clk_oreg = portOutputRegister(digitalPinToPort(clk));
 _cmd_mask = maskToBitNum(digitalPinToBitMask(cmd));
 _cmd_oreg = portOutputRegister(digitalPinToPort(cmd));
 _att_mask = maskToBitNum(digitalPinToBitMask(att));
 _att_oreg = portOutputRegister(digitalPinToPort(att));
 _dat_mask = maskToBitNum(digitalPinToBitMask(dat));
 _dat_ireg = portInputRegister(digitalPinToPort(dat));
  

  pinMode(clk, OUTPUT); //configure ports
  pinMode(att, OUTPUT);
  pinMode(cmd, OUTPUT);
  pinMode(dat, INPUT);

  digitalWrite(dat, HIGH); //enable pull-up 
    
   SET(*_cmd_oreg,_cmd_mask); // SET(*_cmd_oreg,_cmd_mask);
   SET(*_clk_oreg,_clk_mask);
   
   //new error checking. First, read gamepad a few times to see if it's talking
   read_gamepad();
   read_gamepad();
   
   //see if it talked
   if(PS2data[1] != 0x41 && PS2data[1] != 0x73 && PS2data[1] != 0x79){ //see if mode came back. If still anything but 41, 73 or 79, then it's not talking
      #ifdef PSX64_DEBUG
		Serial.println("Controller mode not matched or no controller found");
		Serial.print("Expected 0x41 or 0x73, got ");
		Serial.println(PS2data[1], HEX);
	  #endif
	 
	 return 1; //return error code 1
	}
  
  //try setting mode, increasing delays if need be. 
  read_delay = 1;
  
  for(int y = 0; y <= 10; y++)
  {
   sendCommandString(enter_config, sizeof(enter_config)); //start config run
   
   //read type
   	delayMicroseconds(CTRL_BYTE_DELAY);

	SET(*_cmd_oreg,_cmd_mask);
    SET(*_clk_oreg,_clk_mask);
    CLR(*_att_oreg,_att_mask); // low enable joystick
	
    delayMicroseconds(CTRL_BYTE_DELAY);

    for (int i = 0; i<9; i++) {
	  temp[i] = _gamepad_shiftinout(type_read[i]);
    }

	SET(*_att_oreg,_att_mask); // HI disable joystick
	
	controller_type = temp[3];
   
   sendCommandString(set_mode, sizeof(set_mode));
   if(rumble){ sendCommandString(enable_rumble, sizeof(enable_rumble)); en_Rumble = true; }
   if(pressures){ sendCommandString(set_bytes_large, sizeof(set_bytes_large)); en_Pressures = true; }
   sendCommandString(exit_config, sizeof(exit_config));
   
   read_gamepad();
   
   if(pressures){
	if(PS2data[1] == 0x79)
		break;
	if(PS2data[1] == 0x73)
		return 3;
   }
   
    if(PS2data[1] == 0x73)
      break;
      
    if(y == 10){
		#ifdef PSX64_DEBUG
		Serial.println("Controller not accepting commands");
		Serial.print("mode stil set at");
		Serial.println(PS2data[1], HEX);
		#endif
      return 2; //exit function with error
	  }
    
    read_delay += 1; //add 1ms to read_delay
  }
   
 return 0; //no error if here
}
void pinModeGpio (int pin, int mode)
{
//  register int barrier ;

  int fSel, shift, alt ;

  pin &= 63 ;

  fSel    = gpioToGPFSEL [pin] ;
  shift   = gpioToShift  [pin] ;

  /**/ if (mode == INPUT)
    *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) ; // Sets bits to zero = input
  else if (mode == OUTPUT)
    *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (1 << shift) ;
  else if (mode == PWM_OUTPUT)
  {
    if ((alt = gpioToPwmALT [pin]) == 0)	// Not a PWM pin
      return ;

// Set pin to PWM mode

    *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;

    delayMicroseconds (110) ;				// See comments in pwmSetClockWPi
    *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;

//  Page 107 of the BCM Peripherals manual talks about the GPIO clocks,
//	but I'm assuming (hoping!) that this applies to other clocks too.

    *(pwm + PWM_CONTROL) = 0 ;				// Stop PWM

    *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x01 ;	// Stop PWM Clock
    delayMicroseconds (110) ;				// See comments in pwmSetClockWPi

    while ((*(clk + PWMCLK_CNTL) & 0x80) != 0)		// Wait for clock to be !BUSY
      delayMicroseconds (1) ;

    *(clk + PWMCLK_DIV)  = BCM_PASSWORD | (32 << 12) ;	// set pwm div to 32 (19.2/32 = 600KHz)
    *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x11 ;	// enable clk

    delayMicroseconds (110) ;				// See comments in pwmSetClockWPi

// Default range register of 1024

    *(pwm + PWM0_RANGE) = 1024 ; delayMicroseconds (10) ;
    *(pwm + PWM1_RANGE) = 1024 ; delayMicroseconds (10) ;
    *(pwm + PWM0_DATA)  =    0 ; delayMicroseconds (10) ;
    *(pwm + PWM1_DATA)  =    0 ; delayMicroseconds (10) ;

// Enable PWMs in balanced mode (default)

    *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE ;

    delay (100) ;
  }


// When we change mode of any pin, we remove the pull up/downs
//	Or we used to... Hm. Commented out now because for some wieird reason,
//	it seems to block subsequent attempts to set the pull up/downs and I've
//	not quite gotten to the bottom of why this happens
//	The down-side is that the pull up/downs are rememberd in the SoC between
//	power cycles, so it's going to be a good idea to explicitly set them in
//	any new code.
//
//  pullUpDnControl (pin, PUD_OFF) ;

}
Пример #26
0
void *ChangeTHRepresentation (void *param)
{
    (void)param;
    OCStackResult result = OC_STACK_ERROR;
    modCounter += 1;
    if (modCounter % 10 ==
        0) // Matching the timing that the Linux Sample Server App uses for the same functionality.
    {

        byte dht11_dat[5];
        byte i;// start condition

        digitalWrite(dht11_pin, LOW);
        delay(18);
        digitalWrite(dht11_pin, HIGH);
        delayMicroseconds(1);
        pinMode(dht11_pin, INPUT);
        delayMicroseconds(40);

        if (digitalRead(dht11_pin))
        {
            Serial.println("dht11 start condition 1 not met"); // wait for DHT response signal: LOW
            delay(1000);
            return NULL;
        }
        delayMicroseconds(80);
        if (!digitalRead(dht11_pin))
        {
            Serial.println("dht11 start condition 2 not met");  //wair for second response signal:HIGH
            return NULL;
        }

        delayMicroseconds(80);// now ready for data reception
        for (i = 0; i < 5; i++)
        {
            dht11_dat[i] = read_dht11_dat();
        }  //recieved 40 bits data. Details are described in datasheet

        pinMode(dht11_pin, OUTPUT);
        digitalWrite(dht11_pin, HIGH);
        byte dht11_check_sum = dht11_dat[0] + dht11_dat[2]; // check check_sum
        if (dht11_dat[4] != dht11_check_sum)
        {
            Serial.println("DHT11 checksum error");
        }
        Serial.print("Current humdity = ");
        Serial.print(dht11_dat[0], DEC);
        Serial.print("%  ");
        Serial.print("temperature = ");
        Serial.print(dht11_dat[2], DEC);
        Serial.println("C  ");

        TH.m_humid = dht11_dat[0];
        TH.m_temp = dht11_dat[2];

        if (g_THUnderObservation)
        {
            OC_LOG_V(INFO, TAG, " =====> Notifying stack of new humid level %d\n", TH.m_humid);
            OC_LOG_V(INFO, TAG, " =====> Notifying stack of new temp level %d\n", TH.m_temp);

            result = OCNotifyAllObservers (TH.m_handle, OC_NA_QOS);

            if (OC_STACK_NO_OBSERVERS == result)
            {
                g_THUnderObservation = 0;
            }
        }
    }
    return NULL;
}
Пример #27
0
/********** high level commands, for the user! */
void LiquidCrystal::clear()
{
  command(LCD_CLEARDISPLAY);  // clear display, set cursor position to zero
  delayMicroseconds(2000);  // this command takes a long time!
}
Пример #28
0
static int16_t ucg_com_esp8266_hw_spi(ucg_t *ucg, int16_t msg, uint16_t arg, uint8_t *data)
{
  switch(msg)
  {
    case UCG_COM_MSG_POWER_UP:
        /* "data" is a pointer to ucg_com_info_t structure with the following information: */
        /*	((ucg_com_info_t *)data)->serial_clk_speed value in nanoseconds */
        /*	((ucg_com_info_t *)data)->parallel_clk_speed value in nanoseconds */
      
        /* setup pins */
    
        // we assume that the SPI interface was already initialized
        // just care for the /CS and D/C pins
        //platform_gpio_write( ucg->pin_list[0], value );

        if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
            platform_gpio_mode( ucg->pin_list[UCG_PIN_RST], PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_FLOAT );
        platform_gpio_mode( ucg->pin_list[UCG_PIN_CD], PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_FLOAT );
      
        if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
            platform_gpio_mode( ucg->pin_list[UCG_PIN_CS], PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_FLOAT );
      
        break;

    case UCG_COM_MSG_POWER_DOWN:
        break;

    case UCG_COM_MSG_DELAY:
        delayMicroseconds(arg);
        break;

    case UCG_COM_MSG_CHANGE_RESET_LINE:
        if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
            platform_gpio_write( ucg->pin_list[UCG_PIN_RST], arg );
        break;

    case UCG_COM_MSG_CHANGE_CS_LINE:
        if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
            platform_gpio_write( ucg->pin_list[UCG_PIN_CS], arg );
        break;

    case UCG_COM_MSG_CHANGE_CD_LINE:
        platform_gpio_write( ucg->pin_list[UCG_PIN_CD], arg );
        break;

    case UCG_COM_MSG_SEND_BYTE:
        platform_spi_send( 1, 8, arg );
        break;

    case UCG_COM_MSG_REPEAT_1_BYTE:
        while( arg > 0 ) {
            platform_spi_send( 1, 8, data[0] );
            arg--;
        }
        break;

    case UCG_COM_MSG_REPEAT_2_BYTES:
        while( arg > 0 ) {
            platform_spi_send( 1, 8, data[0] );
            platform_spi_send( 1, 8, data[1] );
            arg--;
        }
        break;

    case UCG_COM_MSG_REPEAT_3_BYTES:
        while( arg > 0 ) {
            platform_spi_send( 1, 8, data[0] );
            platform_spi_send( 1, 8, data[1] );
            platform_spi_send( 1, 8, data[2] );
            arg--;
        }
        break;

    case UCG_COM_MSG_SEND_STR:
        while( arg > 0 ) {
            platform_spi_send( 1, 8, *data++ );
            arg--;
        }
        break;

    case UCG_COM_MSG_SEND_CD_DATA_SEQUENCE:
        while(arg > 0)
        {
            if ( *data != 0 )
            {
                /* set the data line directly, ignore the setting from UCG_CFG_CD */
                if ( *data == 1 )
                {
                    platform_gpio_write( ucg->pin_list[UCG_PIN_CD], 0 );
                }
                else
                {
                    platform_gpio_write( ucg->pin_list[UCG_PIN_CD], 1 );
                }
            }
            data++;
            platform_spi_send( 1, 8, *data );
            data++;
            arg--;
        }
        break;
  }
  return 1;
}
Пример #29
0
void LiquidCrystal::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) {
  if (lines > 1) {
    _displayfunction |= LCD_2LINE;
  }
  _numlines = lines;
  _currline = 0;

  // for some 1 line displays you can select a 10 pixel high font
  if ((dotsize != 0) && (lines == 1)) {
    _displayfunction |= LCD_5x10DOTS;
  }

  // SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION!
  // according to datasheet, we need at least 40ms after power rises above 2.7V
  // before sending commands. Arduino can turn on way befer 4.5V so we'll wait 50
  delayMicroseconds(50000); 
  // Now we pull both RS and R/W low to begin commands
  digitalWrite(_rs_pin, LOW);
  digitalWrite(_enable_pin, LOW);
  if (_rw_pin != 255) { 
    digitalWrite(_rw_pin, LOW);
  }
  
  //put the LCD into 4 bit or 8 bit mode
  if (! (_displayfunction & LCD_8BITMODE)) {
    // this is according to the hitachi HD44780 datasheet
    // figure 24, pg 46

    // we start in 8bit mode, try to set 4 bit mode
    write4bits(0x03);
    delayMicroseconds(4500); // wait min 4.1ms

    // second try
    write4bits(0x03);
    delayMicroseconds(4500); // wait min 4.1ms
    
    // third go!
    write4bits(0x03); 
    delayMicroseconds(150);

    // finally, set to 4-bit interface
    write4bits(0x02); 
  } else {
    // this is according to the hitachi HD44780 datasheet
    // page 45 figure 23

    // Send function set command sequence
    command(LCD_FUNCTIONSET | _displayfunction);
    delayMicroseconds(4500);  // wait more than 4.1ms

    // second try
    command(LCD_FUNCTIONSET | _displayfunction);
    delayMicroseconds(150);

    // third go
    command(LCD_FUNCTIONSET | _displayfunction);
  }

  // finally, set # lines, font size, etc.
  command(LCD_FUNCTIONSET | _displayfunction);  

  // turn the display on with no cursor or blinking default
  _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF;  
  display();

  // clear it off
  clear();

  // Initialize to default text direction (for romance languages)
  _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT;
  // set the entry mode
  command(LCD_ENTRYMODESET | _displaymode);

}
Пример #30
0
int ROTankWire::I2C_ClearBus() {
#if defined(TWCR) && defined(TWEN)
    TWCR &= ~(_BV(TWEN)); //Disable the Atmel 2-Wire interface so we can control the SDA and SCL pins directly
#endif

    pinMode(SDA, INPUT_PULLUP); // Make SDA (data) and SCL (clock) pins Inputs with pullup.
    pinMode(SCL, INPUT_PULLUP);

    delay(2500);  // Wait 2.5 secs. This is strictly only necessary on the first power
    // up of the DS3231 module to allow it to initialize properly,
    // but is also assists in reliable programming of FioV3 boards as it gives the
    // IDE a chance to start uploaded the program
    // before existing sketch confuses the IDE by sending Serial data.

    boolean SCL_LOW = (digitalRead(SCL) == LOW); // Check is SCL is Low.
    if (SCL_LOW) { //If it is held low Arduno cannot become the I2C master.
        return 1; //I2C bus error. Could not clear SCL clock line held low
    }

    boolean SDA_LOW = (digitalRead(SDA) == LOW);  // vi. Check SDA input.
    int clockCount = 20; // > 2x9 clock

    while (SDA_LOW && (clockCount > 0)) { //  vii. If SDA is Low,
        clockCount--;
        // Note: I2C bus is open collector so do NOT drive SCL or SDA high.
        pinMode(SCL, INPUT); // release SCL pullup so that when made output it will be LOW
        pinMode(SCL, OUTPUT); // then clock SCL Low
        delayMicroseconds(10); //  for >5uS
        pinMode(SCL, INPUT); // release SCL LOW
        pinMode(SCL, INPUT_PULLUP); // turn on pullup resistors again
        // do not force high as slave may be holding it low for clock stretching.
        delayMicroseconds(10); //  for >5uS
        // The >5uS is so that even the slowest I2C devices are handled.
        SCL_LOW = (digitalRead(SCL) == LOW); // Check if SCL is Low.
        int counter = 20;
        while (SCL_LOW && (counter > 0)) {  //  loop waiting for SCL to become High only wait 2sec.
            counter--;
            delay(100);
            SCL_LOW = (digitalRead(SCL) == LOW);
        }
        if (SCL_LOW) { // still low after 2 sec error
            return 2; // I2C bus error. Could not clear. SCL clock line held low by slave clock stretch for >2sec
        }
        SDA_LOW = (digitalRead(SDA) == LOW); //   and check SDA input again and loop
    }
    if (SDA_LOW) { // still low
        return 3; // I2C bus error. Could not clear. SDA data line held low
    }

    // else pull SDA line low for Start or Repeated Start
    pinMode(SDA, INPUT); // remove pullup.
    pinMode(SDA, OUTPUT);  // and then make it LOW i.e. send an I2C Start or Repeated start control.
    // When there is only one I2C master a Start or Repeat Start has the same function as a Stop and clears the bus.
    /// A Repeat Start is a Start occurring after a Start with no intervening Stop.
    delayMicroseconds(10); // wait >5uS
    pinMode(SDA, INPUT); // remove output low
    pinMode(SDA, INPUT_PULLUP); // and make SDA high i.e. send I2C STOP control.
    delayMicroseconds(10); // x. wait >5uS
    pinMode(SDA, INPUT); // and reset pins as tri-state inputs which is the default state on reset
    pinMode(SCL, INPUT);
    return 0; // all ok
}