/**
 * Inititializes the DHT Sensor module.
 *
 * The positive supply for all DHT sensors can by supplied via a port. If the
 * "portPowerSwitch" parameter is not IOPORT_ID_NA, than it gives the IO
 * Port used to supply power to the DHT sensors.
 * If "powerSwitchInverted" is FALSE, this port is set to 1 to power DHT sensors.
 * If "powerSwitchInverted" is TRUE, this port is set to 0 to power DHT sensors.
 *
 * @param startupDelay Time to wait before first read. When a system has multiple DHT22 sensors,
 *            ensure each one has a different startup delay! Use 0 to use default value.
 *
 * @param portPowerSwitch The "Port ID" connected to the sensor pin of the DHT22.
 * Is a number from 0 to 41, also known as the "Netcruzer Port Name".
 * Use IOPORT_ID_NA is there is no power switch.
 *
 * @param powerSwitchInverted Indicates if the power switch is inverted (port set to
 * 0 to power sensors).
 *
 * @return Returns 0 if success, else error code.
 */
BYTE sensDht_init(WORD startupDelay, BYTE portPowerSwitch, BOOL powerSwitchInverted) {

    sens.flags.pwrSwtInverted = powerSwitchInverted;
    sens.bitadrPwrSwt = portGetLAT(portPowerSwitch);

    //Enable power switch
    if (sens.bitadrPwrSwt != BITADR_NA) {
        //Enable power
        if (powerSwitchInverted==TRUE)
            portWriteBitadr(sens.bitadrPwrSwt, 0);
        else
            portWriteBitadr(sens.bitadrPwrSwt, 1);

        //Configure port as output
        portConfig(portPowerSwitch, PTYPE_DOUT);
        //if (portConfig(portIdSens, PTYPE_DOUT) != 0) {
        //    DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, "\nERR: sensDht_addSensor() DOUT");
        //}
    }

    //Start reset delay - delay required before first read
    sens.sm = SM_SENSDHT_RESET_DELAY;

    if (startupDelay==0)
        startupDelay = SENS_DHT_STARTUP_READ_DELAY;
    sens.tmrDelay = tick16Get() + tick16ConvertFromMS(startupDelay);

    return 0;
}
/**
 * Configures IO Port (port of SBC) for the DHT Sensor as an input, with pull-up
 * resistor enabled.
 *
 * @param portIdSens The "Port ID" connected to the sensor pin of the DHT22. Is a
 *             number from 0 to 41, also known as the "Netcruzer Port Name".
 */
void sensDht_addSensor(BYTE portIdSens) {
    //Configure port as input, with pull-up resistors enabled
    if (portConfig(portIdSens, PTYPE_DIN | PCFG_DIN_PULLUP) != 0) {
        DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, "\nERR: sensDht_addSensor() DIN");
    }

    //Start reset delay - delay required before first read
    sens.sm = SM_SENSDHT_RESET_DELAY;
    sens.tmrDelay = tick16Get() + tick16ConvertFromMS(SENS_DHT_STARTUP_READ_DELAY);
}
Beispiel #3
0
void main_remi() {
	char buf[27] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm' ,'n', 'o', 'p' ,'q'
	,'r', 's','t','u','v','w','x','y','z',' '};
	// Setup STM32 system (clock, PLL and Flash configuration)
	SystemInit();





	Gpio *gpioA = STM32F103::getGpioA();
	// Set default port behavior
	GpioConfiguration portConfig(Gpio::AF_PUSH_PULL_OUTPUT | Gpio::OUTPUT_SPEED_50MHZ);
	gpioA->configure(portConfig);

	Uart *uart1 = STM32F103::getUart1();
	UartConfiguration uart1Config;
	uart1Config.baudrate 		= 9600;
	uart1Config.stopBit 		= Uart::UART_1_STOPBIT;
	uart1Config.parityEnable 	= Uart::UART_PARITY_DISABLE;
	uart1Config.wordLenght		= Uart::UART_WORD_LENGTH_8BIT;
	uart1->configure(uart1Config);

	//Uart *uart2 = STM32F103::getUart2();
	// Uart2 config

	// Tag each Uart with their respective source
	uart1->setTag(Peripheral::Controller);
	//uart2->setTag(Peripheral::Drive);

	// Configure blinking led
	GpioPinConfiguration ledPinConfig;
	ledPinConfig.pin = Gpio::GP_PUSH_PULL_OUTPUT | Gpio::OUTPUT_SPEED_50MHZ;
	gpioA->getPin(0)->configure(ledPinConfig);

	GpioPin *led = gpioA->getPin(0);

	// Blink led
	while(1) {
		led->setHigh();	// On
		for(uint32_t i=0; i<1000000; i++){
			uart1->poll();
		}

		uart1->write((char *)buf, 27);

		led->setLow();	// Off
		for(uint32_t i=0; i<1000000; i++){
			uart1->poll();
		}
	}
}
Beispiel #4
0
HeadTracker::HeadTracker()
: lastTimeStampMs(0)
, samplingRateHz(0)
, tc(0.7)
{
	// Try and open default path
	String defaultPath("/dev/tty.usbmodem1411");
	SerialPortConfig portConfig(115200,
								8, 
								SerialPortConfig::SERIALPORT_PARITY_NONE,
								SerialPortConfig::STOPBITS_1,
								SerialPortConfig::FLOWCONTROL_NONE);

	port = new SerialPort(defaultPath, portConfig);

	if(port->exists()) {
		stream = new SerialPortInputStream(port);
		stream->setNotify(SerialPortInputStream::NOTIFY_ON_CHAR, '\n');
		stream->addChangeListener(this);
	}
	else {
		// Warn user no head tracker is there
	}
}
Beispiel #5
0
//Function to Initialize PORTS
void LCD::portInit()
{
	portConfig();
}
Beispiel #6
0
void main_francois() {
	// Setup STM32 system (clock, PLL and Flash configuration)
	SystemInit();

	Gpio *gpioA = STM32F103::getGpioA();
	Gpio *gpioB = STM32F103::getGpioB();
	Gpio *gpioC = STM32F103::getGpioC();

	// Set default port behavior
	GpioConfiguration portConfig(Gpio::FLOATING_INPUT);
	gpioA->configure(portConfig);

	// Configure blinking led
	GpioPinConfiguration ledPinConfig;
	ledPinConfig.pin = Gpio::GP_PUSH_PULL_OUTPUT | Gpio::OUTPUT_SPEED_50MHZ;
	gpioA->getPin(0)->configure(ledPinConfig);

	GpioPin *led = gpioA->getPin(0);

	// Create the usb port
	Usb* usb = STM32F103::getUsb();

	// Create a new NES controller interface
	AFIO->MAPR |= AFIO_MAPR_SWJ_CFG_DISABLE;	// JTAG remap
	NesControllerInterface* nesInterface = new NesControllerInterface(gpioB->getPin(3), gpioB->getPin(4), gpioC->getPin(5));
	usb->addEventListener(nesInterface);

	usb->listenForDevice();

	while(!usb->deviceDetected());

	//debug
	// Blink led fast
	led->setHigh();	// On
	for(uint32_t i=0; i<100000; i++);
	led->setLow();	// Off
	for(uint32_t i=0; i<100000; i++);

	usb->enumerateDevice();

	// Blink led
	while(1) {

		//if(usb->deviceDetected()) {
			/*led->setHigh();	// On
			for(uint32_t i=0; i<100000; i++);
			led->setLow();	// Off
			for(uint32_t i=0; i<100000; i++);*/

			//if(!usb->deviceEnumerated()) {

				//debug
				// Blink led fast
				/*GPIOA->BSRR |= 0x01;	// On
				for(uint32_t i=0; i<100000; i++);
				GPIOA->BRR |= 0x01;	// Off
				for(uint32_t i=0; i<100000; i++);

				usb->enumerateDevice();*/
			//}
			//else {
				usb->serviceHid();
			//}
		//}

		/*
		led->setHigh();	// On
		for(uint32_t i=0; i<1000000; i++);

		led->setLow();	// Off
		for(uint32_t i=0; i<1000000; i++);
		*/

		// Simulate an external interrupt
		//EXTI->SWIER |= EXTI_SWIER_SWIER1;
	}
}
Beispiel #7
0
int main() {
	Gpio *gpio1 = LPC2478::getGpio1();

	// Set default port behavior
	GpioConfiguration portConfig(32, Gpio::INPUT);
	gpio1->configure(portConfig);

	// Configure blinking led
	GpioPinConfiguration *ledPinConfig = new GpioPinConfiguration();
	ledPinConfig->pin = Gpio::OUTPUT;
	gpio1->getPin(12)->configure(*ledPinConfig);

	GpioPin *led = gpio1->getPin(12);

	LCDConfiguration lcdConfig;
	lcdConfig.bufferBaseAddress = 0xA0000000;
	lcdConfig.height = 272;
	lcdConfig.width = 480;
	LCDControllerDriver* lcd = LPC2478::getLCD();
	lcd->configure(lcdConfig);

	// Set background
	lcd->setBackground(0x00FFFFFF);

	Debug::writeLine("Platform initialized");

	// USB debug section
	HostControllerDriver* hcd = LPC2478::getHCD();
	//hcd->init();
	Debug::writeLine("Please connect a USB device");
	IntEnable();

	UsbDevice* device;
	XboxControllerDriver* controller;
	while(1) {
		device = hcd->periodicTask();
		if(device != 0) {
			if(device->getDeviceDescriptor()->idVendor == 0x045e && device->getDeviceDescriptor()->idProduct == 0x0719) { // Xbox receiver
				MemoryPool* memoryPool = hcd->getMemoryPool();
				if(memoryPool != 0) {
					controller = new XboxControllerDriver(device, memoryPool);
					break;
				}
				else {
					Debug::writeLine("Not enough USB memory");
				}
			}
		}
		LPC2478::delay(100000);
	}

	Debug::writeLine("Xbox controller ready to use");
	LPC2478::delay(1000000);
	controller->query(XboxControllerDriver::CONTROLLER1);
	controller->query(XboxControllerDriver::CONTROLLER2);
	//controller->setLedState(XboxControllerDriver::Flashes_ON_1, XboxControllerDriver::CONTROLLER1);
	//controller->setRumbleState(0, 128, XboxControllerDriver::CONTROLLER1);
	//LPC2478::delay(100000);
	GamepadInputReport* gamepadStatus1 = controller->getStatus(XboxControllerDriver::CONTROLLER1);
	GamepadInputReport* gamepadStatus2 = controller->getStatus(XboxControllerDriver::CONTROLLER2);

	//while(1);

	/*while(1) {
		if(gamepadStatus->a) {
			led->setHigh();
		}
		else {
			led->setLow();
		}
	}*/

	DisplayHelper* displayHelper = new DisplayHelper(lcd);

	/*
	 * SD Card and file system section
	 *
	 * This is all C for now
	 */
	Debug::writeLine("Init Timer");
	TIMER0->TCR = 0;				/* Disable Timer */
	TIMER0->MR0 = 720000 - 1;		/* 72M / 100 = 720000 */
	TIMER0->MCR = 0x3;			/* Clear TC and Interrupt on MR0 match */
	TIMER0->TCR = 1;				/* Enable Timer */
	VICIntSelect &= ~(1 << TIMER0_INT); // IRQ Category (Not FIQ)
	VICIntEnable |= (1 << TIMER0_INT);

	IntEnable();

	FRESULT f_err_code;
	FATFS FATFS_Obj[1];

	f_err_code = f_mount(0, &FATFS_Obj[0]);

	if(f_err_code == 0) {
		Debug::writeLine("SD card mounted");
	}
	else {
		Debug::writeLine("Failed to mount SD card");
	}

	//------ Engine Test

	Engine* engine = new Engine();
	engine->start(gamepadStatus1, gamepadStatus2);

	//------------------




	Bitmap* bitmap = new Bitmap("0:mmx1.bmp");
	bitmap->load();
	if(bitmap->getData() != 0) {
		displayHelper->drawImage(100,50,bitmap->getData(),bitmap->getInfoHeader()->width,bitmap->getInfoHeader()->height);
	}

	AudioHelper* audioHelper = new AudioHelper(LPC2478::getDAC());
	Wave* wave = new Wave("0:intro.wav");
	wave->load();

	//LPC2478::getDAC()->setValue(32768);
	//DAC0->DACR = 32768;
	//while(1);

	if(wave->isLoaded()) {
		Debug::writeLine("Playing wave file");
		audioHelper->play(wave);
	}
	while(1);

	// Display megaman gif
	/*uint32_t* lcd_ptr = (uint32_t*)lcd->getBufferBase();
	uint32_t bufferLenght = 480*272;
	displayHelper->drawImage(50,50,(uint32_t*)&megaman_running[0][0],35,35);
	while(1) {
		for(uint8_t i=1;i<11; i++) {
			displayHelper->drawImage(0,0,(uint32_t*)&megaman_running[i][0],35,35);
			//LPC2478::delay(100000);
			for (uint32_t i=16800; i<bufferLenght; i++) {
				*(lcd_ptr++) = 0x00FFFFFF;
			}
		}
	}*/

	led->setLow();

	// Test sdram
#define SDRAM_BASE_ADDR *(volatile unsigned int*)0xA0000000

	/*unsigned int i;
	for (i = 0; i < 0x2000000; i+=sizeof(unsigned int))
	{
	*(unsigned int *)((unsigned int )&SDRAM_BASE_ADDR+i) = i;
	}

	for (i = 0; i < 0x2000000; i+=sizeof(unsigned int ))
	{
	if (*(unsigned int *)((unsigned int )&SDRAM_BASE_ADDR+i) != i)
	{
	  led->setHigh();
	  while(1);
	}
	}*/

	//while(1);
	//LPC2478::delay(1000000);

	// Blink led
	while(1) {
		led->setHigh();	// On
		//for(uint32_t i=0; i<100000; i++);
		LPC2478::delay(1000000);
		led->setLow();	// Off
		//for(uint32_t i=0; i<100000; i++);
		LPC2478::delay(1000000);
	}

}
Beispiel #8
0
int main() {

    // global interupt enable
    sei();

    // Start I2C
    i2c_init();

    // Start UART
    //UART_init();

    // start ADC
    ADC_init();

    // termistor on ADC channel 2
    ADC_channel(ADCCHANNEL);

    portConfig();

    // timer0 aprox. get data from RTC
    // timer1 for update 7 segment
    timer0start();

    // aprox. 4x per second
    timer1start();

    // read Epprom
    readDataFromEeprom();

    // read time from RTC
    getTime();

    while(1) {
        // if set is set for modify values PB1
        if (debounce(&PINB, PB1)) {
            changeStateCounter = 0;

            if (set) {
                timer1stop();

                switch (show) {
                case show_time:
                    if(set == set_second) {
                        minute++;
                        if (minute > 59) {
                            minute = 0;
                        }
                        write(minute, minute_RTC);
                    }
                    if(set == set_first) {
                        hour++;
                        if (hour > 23) {
                            hour = 0;
                        }
                        write(hour, hour_RTC);
                    }
                    break;

                case show_switch:
                    break;

                case show_date:
                    if(set == set_first) {
                        day++;
                        if (day > 31) {
                            day = 1;
                        }
                        write(day, day_RTC);
                    }
                    if(set == set_second) {
                        month++;
                        if (month > 12) {
                            month = 1;
                        }
                        write(month, month_RTC);
                    }
                    break;

                case show_year:
                    if(set == set_both) {
                        year++;
                        if (year > 99) {
                            year = 0;
                        }
                        write(year, year_RTC);
                    }
                    break;

                case show_onTime1:
                    if(set == set_first) {
                        on[0]++;
                        if (on[0] > 23) {
                            on[0] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)0, on[0]);
                    }
                    if(set == set_second) {
                        on[1]++;
                        if (on[1] > 59) {
                            on[1] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)1, on[1]);
                    }
                    if(set == set_both) {
                        if (dayStatus[0] == d_day) {
                            dayStatus[0] = d_night;
                        } else if (dayStatus[0] == d_night) {
                            dayStatus[0] = d_off;
                        } else {
                            dayStatus[0] = d_day;
                        }
                        eeprom_write_byte ((uint8_t*)STATUS_EEPROM_POS + 1, (uint8_t)dayStatus[0]);
                    }
                    break;

                case show_onTime2:
                    if(set == set_first) {
                        on[2]++;
                        if (on[2] > 23) {
                            on[2] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)2, on[2]);
                    }
                    if(set == set_second) {
                        on[3]++;
                        if (on[3] > 59) {
                            on[3] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)3, on[3]);
                    }
                    if(set == set_both) {
                        if (dayStatus[1] == d_day) {
                            dayStatus[1] = d_night;
                        } else if (dayStatus[1] == d_night) {
                            dayStatus[1] = d_off;
                        } else {
                            dayStatus[1] = d_day;
                        }
                        eeprom_write_byte ((uint8_t*)STATUS_EEPROM_POS + 2, (uint8_t)dayStatus[1]);
                    }
                    break;

                case show_onTime3:
                    if(set == set_first) {
                        on[4]++;
                        if (on[4] > 23) {
                            on[4] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)4, on[4]);
                    }
                    if(set == set_second) {
                        on[5]++;
                        if (on[5] > 59) {
                            on[5] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)5, on[5]);
                    }
                    if(set == set_both) {
                        if (dayStatus[2] == d_day) {
                            dayStatus[2] = d_night;
                        } else if (dayStatus[2] == d_night) {
                            dayStatus[2] = d_off;
                        } else {
                            dayStatus[2] = d_day;
                        }
                        eeprom_write_byte ((uint8_t*)STATUS_EEPROM_POS + 3, (uint8_t)dayStatus[2]);
                    }
                    break;

                case show_onTime4:
                    if(set == set_first) {
                        on[6]++;
                        if (on[6] > 23) {
                            on[6] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)6, on[6]);
                    }
                    if(set == set_second) {
                        on[7]++;
                        if (on[7] > 59) {
                            on[7] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)7, on[7]);
                    }
                    if(set == set_both) {
                        if (dayStatus[3] == d_day) {
                            dayStatus[3] = d_night;
                        } else if (dayStatus[3] == d_night) {
                            dayStatus[3] = d_off;
                        } else {
                            dayStatus[3] = d_day;
                        }
                        eeprom_write_byte ((uint8_t*)STATUS_EEPROM_POS + 4, (uint8_t)dayStatus[3]);
                    }
                    break;

                case show_onTime5:
                    if(set == set_first) {
                        on[8]++;
                        if (on[8] > 23) {
                            on[8] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)8, on[8]);
                    }
                    if(set == set_second) {
                        on[9]++;
                        if (on[9] > 59) {
                            on[9] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)9, on[9]);
                    }
                    if(set == set_both) {
                        if (dayStatus[4] == d_day) {
                            dayStatus[4] = d_night;
                        } else if (dayStatus[4] == d_night) {
                            dayStatus[4] = d_off;
                        } else {
                            dayStatus[4] = d_day;
                        }
                        eeprom_write_byte ((uint8_t*)STATUS_EEPROM_POS + 5, (uint8_t)dayStatus[4]);
                    }
                    break;

                case show_onTime6:
                    if(set == set_first) {
                        on[10]++;
                        if (on[10] > 23) {
                            on[10] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)10, on[10]);
                    }
                    if(set == set_second) {
                        on[11]++;
                        if (on[11] > 59) {
                            on[11] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)11, on[11]);
                    }
                    if(set == set_both) {
                        if (dayStatus[5] == d_day) {
                            dayStatus[5] = d_night;
                        } else if (dayStatus[5] == d_night) {
                            dayStatus[5] = d_off;
                        } else {
                            dayStatus[5] = d_day;
                        }
                        eeprom_write_byte ((uint8_t*)STATUS_EEPROM_POS + 6, (uint8_t)dayStatus[5]);
                    }
                    break;

                case show_co2on:
                    if(set == set_first) {
                        co2[0]++;
                        if (co2[0] > 23) {
                            co2[0] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)12, co2[0]);
                    }
                    if(set == set_second) {
                        co2[1]++;
                        if (co2[1] > 59) {
                            co2[1] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)13, co2[1]);
                    }
                    break;

                case show_co2off:
                    if(set == set_first) {
                        co2[2]++;
                        if (co2[2] > 23) {
                            co2[2] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)14, co2[2]);
                    }
                    if(set == set_second) {
                        co2[3]++;
                        if (co2[3] > 59) {
                            co2[3] = 0;
                        }
                        eeprom_write_byte ((uint8_t*)15, co2[3]);
                    }
                    break;

                }
                timer1start();

            } else {

                // this is place for change display
                // daytime, date, yer, set dates, etc.
                show++;
                if (show == show_end) {
                    show = show_time;
                }
            }
        }

        // button for change position for update PC3
        if (debounce(&PINC, PC3)) {
            changeStateCounter = 0;

            switch (show) {
            case show_time:
            case show_date:
            case show_co2on:
            case show_co2off:
                set++;
                if (set == set_both) {
                    set = set_none;
                }
                readDate();
                break;

            case show_onTime1:
            case show_onTime2:
            case show_onTime3:
            case show_onTime4:
            case show_onTime5:
            case show_onTime6:
                set++;
                if (set == set_end) {
                    set = set_none;
                }
                break;

            case show_year:
                if (set == set_both) {
                    set = set_none;
                } else {
                    set = set_both;
                }
                readYear();
                break;

            case show_switch:
                switchStatus++;
                eeprom_write_byte ((uint8_t*)STATUS_EEPROM_POS, switchStatus);
                if(switchStatus == switch_end) {
                    switchStatus = switch_off;
                }
                break;
            }
        }

        if (debounce(&PINB, PB0)) {
            changeStateCounter = 0;
            show = show_switch;
            switchStatus++;
            eeprom_write_byte ((uint8_t*)STATUS_EEPROM_POS, switchStatus);
            if (switchStatus == switch_end) {
                switchStatus = switch_off;
            }
        }

        //val = getTemperature();
        //sprintf (str, "value: %d.", val);
        //UART_puts(str);
        //UART_puts("\n");
        //_delay_ms(500);
    }
    return 0;
}
/**
 * Reads the temperature and humidity for a DHT11 or DHT22 sensor. After calling this
 * function, the temperature and humidity values can be retrieved with the sensDht_getXxx
 * functions.
 *
 * @param type Type of sensor, is a SENS_DHT_TYPE_XXX define, like SENS_DHT_TYPE_DHT22
 * for example.
 *
 * @param portIdSens The "Port ID" connected to the sensor pin of the DHT22. Is a
 *             number from 0 to 41, also known as the "Netcruzer Port Name".
 *
 * @return Returns 0 if success, else a SENS_DHT_ERROR(enum) error code.
 *      - 0 = Success
 */
BYTE sensDht_read(BYTE type, BYTE portIdSens) {
    BYTE i;
    WORD w;
    WORD bitadrSens;
    BYTE err;
    WORD savedIpl;

    //Only continue if idle
    if (sens.sm != SM_SENSDHT_IDLE)
        return SENS_DHT_ERR_BUSY;

    if ((bitadrSens = portGetPIN(portIdSens)) == BITADR_NA) {
        DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, "\nsensDht_read() - invalid port!");
        return SENS_DHT_ERR_INVALID_PORT;
    }

    //Confirm port is high.
    if (portReadBitadr(bitadrSens) == 0) {
        DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, "\nsensDht_read() - port is low!");
        return SENS_DHT_ERR_PORT_LOW;
    }

    sens.flags.type = type;

    //Send start signal = 0v. Must be minimum 1ms for the DHT22, or 18ms for the DHT11 sensor
    portConfig(portIdSens, PTYPE_DOUT);
    portWriteBitadr(bitadrSens, 0);
#if (SENS_DHT_SUPPORT_DHT22 == 1)
    if (type==SENS_DHT_TYPE_DHT22) {
        nzDelayMs(2);
    }
#endif
#if (SENS_DHT_SUPPORT_DHT11 == 1)
    if (type==SENS_DHT_TYPE_DHT11) {
        nzDelayMs(20);
    }
#endif
    //Disable all interrupts lower than system tick. This will NOT disable the system tick!
    //Do this AFTER 2 or 20mS delay above, and before ending start signal below!
    NZ_SET_AND_SAVE_CPU_IPL(savedIpl, nzINT_PRIORITY_TICK-1);

    //End start signal
    portWriteBitadr(bitadrSens, 1);
    portConfig(portIdSens, PTYPE_DIN | PCFG_DIN_PULLUP);

    // Wait for LOW responce from sensor = low pulse 80uS. Is sent 20-40uS after our start signal
    if (sensDht_waitForPin(0, bitadrSens, 100) == 0) {
        NZ_RESTORE_CPU_IPL(savedIpl);   //Restore interrupts

        //Toggle power - turn power off
        portWriteBitadr(sens.bitadrPwrSwt, (sens.flags.pwrSwtInverted==TRUE)?1:0);

        sens.sm = SM_SENSDHT_POWERUP_RESET;
        sens.tmrDelay = tick16Get() + tick16ConvertFromMS(SENS_DHT_POWER_RST_TIME);
        
        DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, "\nDHT(");
        DEBUG_PUT_BYTE(DEBUG_LEVEL_WARNING, portIdSens);
        DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, ") no responce");

        err=SENS_DHT_ERR_NO_RESPONCE;   //Error, no responce received from sensor!
        goto DHT22_SENS_READ_ERROR;
    }

//    DEBUG_PUT_STR(DEBUG_LEVEL_INFO, "\nDHT Rcv: ");

    //Read 40 bits from sensor
    for(i=0; i<41; i++) {
        //Wait for sensor pin to go high. Will stay high 26-28uS for 0, and 70uS for 1
        if (sensDht_waitForPin(1, bitadrSens, 100) == 0) {
            DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, "\nDHT Err3");
            err=SENS_DHT_ERR_PORT_LOW;      //Error, DHT sensor holding bus low
            goto DHT22_SENS_READ_ERROR;
        }

        //First high-low pulse is responce from sensor. Is responce to our "Start" pulse. NOT first bit!
        if (i!=0) {
            BOOL bit;
            //Delay 50uS and measure pin. For low, pin stays high 26-28us, and for high 70uS.
            //So, after 50uS should the right time to measure pin
            nzDelayUs(SENS_DHT_RD_DLY);

            bit = portReadBitadr(bitadrSens);

            sens.data[(i-1)/8] <<= 1;
            sens.data[(i-1)/8] |= (bit==0)?0:0x01;

//            DEBUG_PUT_BYTE(DEBUG_LEVEL_INFO, portReadBitadr(bitadrSens));
//            DEBUG_PUT_CHAR(DEBUG_LEVEL_INFO, ',');
        }

        //Wait for low pulse from slave
        if (sensDht_waitForPin(0, bitadrSens, 100) == 0) {
            DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, "\nDHT Err4");
            err=SENS_DHT_ERR_NO_RESPONCE;   //Error, no responce from DHT sensor
            goto DHT22_SENS_READ_ERROR;
        }
    }

    //Check CRC
    w = 0;
    for (i=0; i<4; i++) {
        w += sens.data[i];
    }
    //Check for CRC Error
    if (sens.data[4] != (w&0xff)) {
        DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, "\nDHT CRC Error!");
        DEBUG_PUT_HEXBYTE(DEBUG_LEVEL_WARNING, sens.data[4]);
        DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, "!=");
        DEBUG_PUT_HEXBYTE(DEBUG_LEVEL_WARNING, w&0xff);
        err=SENS_DHT_ERR_CRC;       //CRC Error
        goto DHT22_SENS_READ_ERROR;
    }

//    DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, "\nDHT =");
//    DEBUG_PUT_HEXBYTE(DEBUG_LEVEL_WARNING, sens.data[0]);
//    DEBUG_PUT_HEXBYTE(DEBUG_LEVEL_WARNING, sens.data[1]);
//    DEBUG_PUT_HEXBYTE(DEBUG_LEVEL_WARNING, sens.data[2]);
//    DEBUG_PUT_HEXBYTE(DEBUG_LEVEL_WARNING, sens.data[3]);
//    DEBUG_PUT_HEXBYTE(DEBUG_LEVEL_WARNING, sens.data[4]);


    //Save data to sens.data[]
#if (SENS_DHT_SUPPORT_DHT22 == 1)
    if (type==SENS_DHT_TYPE_DHT22) {
        //Swap bytes 1&2 and 2&3
        i = sens.data[0];
        sens.data[0] = sens.data[1];
        sens.data[1] = i;
        i = sens.data[2];
        sens.data[2] = sens.data[3];
        sens.data[3] = i;
    }
#endif
#if (SENS_DHT_SUPPORT_DHT11 == 1)
    //if (type==SENS_DHT_TYPE_DHT11) {
        //No swapping of data required for the DHT11
    //}
#endif

    //After all bits are sent, bus is released by sensor, and goes high
    if (sensDht_waitForPin(1, bitadrSens, 100) == 0) {
        DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, "\nDHT Err5");
        err=SENS_DHT_ERR_PORT_LOW;  //Error, DHT sensor holding bus low
        goto DHT22_SENS_READ_ERROR;
    }

    NZ_RESTORE_CPU_IPL(savedIpl);   //Restore interrupts

//    DEBUG_PUT_STR(DEBUG_LEVEL_WARNING, "\nDHT =");
//    DEBUG_PUT_HEXBYTE(DEBUG_LEVEL_WARNING, sens.data[0]);
//    DEBUG_PUT_HEXBYTE(DEBUG_LEVEL_WARNING, sens.data[1]);
//    DEBUG_PUT_HEXBYTE(DEBUG_LEVEL_WARNING, sens.data[2]);
//    DEBUG_PUT_HEXBYTE(DEBUG_LEVEL_WARNING, sens.data[3]);
//    DEBUG_PUT_HEXBYTE(DEBUG_LEVEL_WARNING, sens.data[4]);

    sens.flags.error = 0;
    return 0;   //Success

    //ERROR! Set error flag, delay 2ms
DHT22_SENS_READ_ERROR:
    NZ_RESTORE_CPU_IPL(savedIpl);   //Restore interrupts
    //Ensure pin is input (high impedance)
    portConfigDir(portIdSens, 1);   //Configure port as input
    //nzDelayMs(2);
    sens.flags.error = 1;   //Error
    return err;
}