Ejemplo n.º 1
0
int main()
{
	int l = 1;
    uint8_t c[2];

	X.output();
	Y.output();
	Z.output();
	E.output();

	setleds(l);

	if (1) {
		UART * s = new UART(0, 9600);
		s->send((uint8_t *) "Start\n", 6);

		for(;;)
		{
    		for (int i = 0 ; ((i & (1 << 22)) == 0) && !g_LoopDummy ; i++)
    		{
    		}
    		c[0] = '0' + (l & 7);
    		c[1] = '\n';
			//s->send(c, 2);
			setleds(l++);
		}
	}
}
Ejemplo n.º 2
0
void ButEvent(int IntNo)
{
	if (IntNo == 0)
	{
		if (g_bUartState == false)
		{
			g_Uart.Enable();
			g_bUartState = true;
		}
		else
		{
			g_Uart.Disable();
			g_bUartState = false;
		}
	}
}
Ejemplo n.º 3
0
int main(void)
{
	char dutyCycle;
	UART uart;
	PWM pwm;
	uart.init();
	uart.println("*** QC-BLCD OS Startup Sequence ***");
	uart.println(" > UART initialized");
	pwm.init();
	uart.println(" > PWM initialized");

	uart.println("Startup Sequence successfull!");
	uart.println("Main program starts now");
	
	dutyCycle=0;
	

    while(42) {                       
               /*itoa(dutyCycle,msg,10);
			   println(msg);*/
			   pwm.setDutyCycle(dutyCycle);
			   dutyCycle++;
			   _delay_ms(200);

	}                        


}
Ejemplo n.º 4
0
void UartRxChedHandler(void * p_event_data, uint16_t event_size)
{
	uint8_t buff[128];

	int l = g_Uart.Rx(buff, 128);
	if (l > 0)
	{
		BleSrvcCharNotify(&g_UartBleSrvc, 0, buff, l);
	}
}
Ejemplo n.º 5
0
void uart_task(void *pvParameters)
{
	char buffer[128];
	char *p;
	uint8_t tmp;
	(void)pvParameters;

	// Enable nCTS
	uart2.handle_.Instance->CR3 |= (USART_CR3_CTSE);
	for (unsigned int i = 0; true; i++) {
		snprintf(buffer, sizeof(buffer), "{\"uart_task\": %d}\n", i);
		for (p = buffer; *p; p++) {
			uart2.rx(&tmp, 0);
			if (uart2.tx(*p, 250) != HAL_OK)
				break;
		}
		vTaskDelay(350 / portTICK_RATE_MS);
	}
}
Ejemplo n.º 6
0
namespace RODOS {
#endif

/*
 * nonblocking getc / getchar (from stdin)
 */
/****************************************************/

static UART uart0 ("uart0");

/** Returns -1 if no data, else char from getchar **/
int getcharNoWait() {
    char c;

	if (uart0.getcharNoWait(c)) return (unsigned char)c;
    else return -1;
}

bool isCharReady() {
    return uart0.isCharReady();
}

char* getsNoWait() {
	static char inBuffer[122];
	static int inBufferIndex = 0;

	while(1) { // terminated with returns

		int c= getcharNoWait();
		if(c < 0) return 0;

		if(c == '\n') { // end of string -> return
			inBuffer[inBufferIndex] = 0;
			inBufferIndex = 0;
			return inBuffer;
		}

		inBuffer[inBufferIndex] = c;
		if(inBufferIndex < 120) inBufferIndex++;
	}

}

void getUARTStats(XUartLite_Stats* stats) {
    uart0.getStats(stats);
}

void clearUARTStats() {
    uart0.clearStats();
}

#ifndef NO_RODOS_NAMESPACE
}
Ejemplo n.º 7
0
int main()
{
   UART uart;

   std::string outputString;
   int outData;
   uart.initUart();

   std::string RPM="010C\r";
   std::string Speed="010D\r";
   
   uart.sendLine("ATZ\r");
  
   sleep(5);

   outputString = uart.receiveLineString();
   std::cout << outputString << std::endl;

   uart.sendLine(RPM);


   outData = uart.receiveLineData("010C41 0C ", 5);

   std::cout << outData << std::endl;

}
Ejemplo n.º 8
0
int main(void)
{
  HAL *hal = HAL::get_HAL();
  UART *uart = hal->uart;
  
  uart->init((uint32_t)115200);
 
  const int TEST_DATA_SIZE = 3;
  uint8_t test_data[TEST_DATA_SIZE] = {'!', '1', ' '};
  uint8_t recv_buff[TEST_DATA_SIZE] = {};
  
  volatile bool testOk = false;
  while(1)
  {
    int msg_size = uart->write(test_data, TEST_DATA_SIZE);
    if (msg_size == TEST_DATA_SIZE)
    {
      hal->time->delay(1000);
      int recv_bytes = uart->read(recv_buff, TEST_DATA_SIZE);
      
      if (recv_bytes == TEST_DATA_SIZE)
      {
        int i;
        for(i = 0; i < TEST_DATA_SIZE; i++)
        {
          testOk = test_data[i] == recv_buff[i];
          recv_buff[i] = 0;
          
          if (!testOk) break;
        }
      }
    }
    if (!testOk)
    {//Fail catch
      while(1){}
    }
  }
  
}
Ejemplo n.º 9
0
void HardwareInit()
{
	g_Uart.Init(g_UartCfg);

	IOPinCfg(s_LedPins, s_NbLedPins);
	IOPinSet(BLUEIO_LED_BLUE_PORT, BLUEIO_LED_BLUE_PIN);
	IOPinSet(BLUEIO_LED_GREEN_PORT, BLUEIO_LED_GREEN_PIN);
	IOPinSet(BLUEIO_LED_RED_PORT, BLUEIO_LED_RED_PIN);

	IOPinCfg(s_ButPins, s_NbButPins);

	IOPinEnableInterrupt(0, APP_IRQ_PRIORITY_LOW, s_ButPins[0].PortNo, s_ButPins[0].PinNo, IOPINSENSE_LOW_TRANSITION, ButEvent);
}
Ejemplo n.º 10
0
int main()
{
    HardwareInit();

    g_Uart.printf("UART over BLE Demo\r\n");

    //g_Uart.Disable();

    BleAppInit((const BLEAPP_CFG *)&s_BleAppCfg, true);

    BleAppRun();

	return 0;
}
Ejemplo n.º 11
0
void ApplicationEntryPoint()
{
    BOOL result;
   
    RAM         RamTest    ( (UINT32*)RAMTestBase, (UINT32)RAMTestSize, (ENDIAN_TYPE)ENDIANESS, BUS_WIDTH );
    TimedEvents eventsTest;
    UART        usartTest  ( COMTestPort, 9600, USART_PARITY_NONE, 8, USART_STOP_BITS_ONE, USART_FLOW_NONE );
    GPIO        gpioTest   ( GPIOTestPin );   
    SPI         spiTest    ( SPIChipSelect, SPIModule, g_EEPROM_STM95x );
    Timers      timersTest ( DisplayInterval, TimerDuration );

    do
    {   
        result = RamTest.Execute   ( STREAM__OUT );       
        result = eventsTest.Execute( STREAM__OUT );
        result = usartTest.Execute ( STREAM__OUT );
        result = gpioTest.Execute  ( STREAM__OUT );
        result = spiTest.Execute   ( STREAM__OUT );
        result = timersTest.Execute( STREAM__OUT );

    } while(FALSE); // run only once!

    while(TRUE);
}
Ejemplo n.º 12
0
// must contain quick code only
void serialCommand(char *line) {
	// check uart1/wlan first
	if (strstr(line, "+CWLAP:(0")) {// == 0 && line[8] == '0') {
		// some pointer dangerous magic
		uint8_t apNameLength = strstr(line+11, "\"") - line - 11;
		if (apNameLength > 19) apNameLength = 19; // TODO: trim -> will result in connection error : redo datatypes
		if (data.freeAPCount < 5) {
			memset(data.freeAPList[data.freeAPCount], 0, 19);
			strncpy(data.freeAPList[data.freeAPCount], line+11, apNameLength);
			uart0.send("free ap: %s ", data.freeAPList[data.freeAPCount]);
			data.freeAPCount++;
		}
	}
	// check uart0/user commands first
	if (strcmp(line, "beep") == 0) beep();
	else if (strcmp(line, "shutdown") == 0) shutdown();
	else if (strcmp(line, "listwlan") == 0) wifi.listAP();
}
Ejemplo n.º 13
0
 int _write(int fd, uint8_t *buf, size_t buflen) {
     dbg.send((uint8_t *) buf, buflen);
     return buflen;
 }
Ejemplo n.º 14
0
void main_task(void *pvParameters)
{
	(void) pvParameters;

	vTaskDelay(500 / portTICK_RATE_MS);

	SPIMaster spi5(SPI5, SPI_BAUDRATEPRESCALER_32, 0x2000, {
				{MEMS_SPI_SCK_PIN,  GPIO_MODE_AF_PP, GPIO_PULLDOWN, GPIO_SPEED_MEDIUM, GPIO_AF5_SPI5},
				{MEMS_SPI_MISO_PIN, GPIO_MODE_AF_PP, GPIO_PULLDOWN, GPIO_SPEED_MEDIUM, GPIO_AF5_SPI5},
				{MEMS_SPI_MOSI_PIN, GPIO_MODE_AF_PP, GPIO_NOPULL,   GPIO_SPEED_MEDIUM, GPIO_AF5_SPI5},
			}, {
				{GYRO_CS_PIN,  GPIO_MODE_OUTPUT_PP, GPIO_PULLUP, GPIO_SPEED_MEDIUM, 0},
				{ACCEL_CS_PIN, GPIO_MODE_OUTPUT_PP, GPIO_PULLUP, GPIO_SPEED_MEDIUM, 0},
			});

	SPIMaster spi2(SPI2, SPI_BAUDRATEPRESCALER_32, 0x2000, {
					{EXT_MEMS_SPI_SCK_PIN,  GPIO_MODE_AF_PP, GPIO_PULLDOWN, GPIO_SPEED_MEDIUM, GPIO_AF5_SPI2},
					{EXT_MEMS_SPI_MISO_PIN, GPIO_MODE_AF_PP, GPIO_PULLDOWN, GPIO_SPEED_MEDIUM, GPIO_AF5_SPI2},
					{EXT_MEMS_SPI_MOSI_PIN, GPIO_MODE_AF_PP, GPIO_NOPULL,   GPIO_SPEED_MEDIUM, GPIO_AF5_SPI2},
				}, {
					{EXT_GYRO_CS_PIN,  GPIO_MODE_OUTPUT_PP, GPIO_PULLUP, GPIO_SPEED_MEDIUM, 0},
					{LPS25HB_PRESSURE_CS_PIN,  GPIO_MODE_OUTPUT_PP, GPIO_PULLUP, GPIO_SPEED_MEDIUM, 0},
					{BMP280_PRESSURE_CS_PIN,  GPIO_MODE_OUTPUT_PP, GPIO_PULLUP, GPIO_SPEED_MEDIUM, 0},
				});

	L3GD20 gyro(spi5, 0);
	LPS25HB lps25hb(spi2, 1);
	BMP280 bmp2(spi2, 2);
	LSM303D accel(spi5, 1);
	uint8_t gyro_wtm = 5;
	uint8_t acc_wtm = 8;
	TimeStamp console_update_time;
	TimeStamp sample_dt;
	TimeStamp led_toggle_ts;
	FlightControl flight_ctl;
	static bool print_to_console = false;
	LowPassFilter<Vector3f, float> gyro_lpf({0.5});
	LowPassFilter<Vector3f, float> acc_lpf_alt({0.9});
	LowPassFilter<Vector3f, float> acc_lpf_att({0.990});
	LowPassFilter<float, float> pressure_lpf({0.6});
	attitudetracker att;

	/*
	 * Apply the boot configuration from flash memory.
	 */
	dronestate_boot_config(*drone_state);

	L3GD20Reader gyro_reader(gyro, GYRO_INT2_PIN, gyro_align);
	LSM303Reader acc_reader(accel, ACC_INT2_PIN, acc_align);

	UartRpcServer rpcserver(*drone_state, configdata, acc_reader.mag_calibrator_);

	bmp2.set_oversamp_pressure(BMP280_OVERSAMP_16X);
	bmp2.set_work_mode(BMP280_ULTRA_HIGH_RESOLUTION_MODE);
	bmp2.set_filter(BMP280_FILTER_COEFF_OFF);

	Bmp280Reader bmp_reader(bmp2);

	HAL_NVIC_SetPriority(DMA1_Stream6_IRQn, 1, 1);
	HAL_NVIC_EnableIRQ (DMA1_Stream6_IRQn);
	HAL_NVIC_SetPriority(DMA1_Stream5_IRQn, 1, 0);
	HAL_NVIC_EnableIRQ (DMA1_Stream5_IRQn);

#ifndef ENABLE_UART_TASK
	uart2.uart_dmarx_start();
#endif

	printf("Priority Group: %lu\n", NVIC_GetPriorityGrouping());
	printf("SysTick_IRQn priority: %lu\n", NVIC_GetPriority(SysTick_IRQn) << __NVIC_PRIO_BITS);
	printf("configKERNEL_INTERRUPT_PRIORITY: %d\n", configKERNEL_INTERRUPT_PRIORITY);
	printf("configMAX_SYSCALL_INTERRUPT_PRIORITY: %d\n", configMAX_SYSCALL_INTERRUPT_PRIORITY);
	printf("LPS25HB Device id: %d\n", lps25hb.Get_DeviceID());
	vTaskDelay(500 / portTICK_RATE_MS);

	gyro_reader.init(gyro_wtm);
	gyro_reader.enable_int2(false);

	vTaskDelay(500 / portTICK_RATE_MS);

	acc_reader.init(acc_wtm);
	acc_reader.enable_int2(false);
	acc_reader.mag_calibrator_.set_bias(drone_state->mag_bias_);
	acc_reader.mag_calibrator_.set_scale_factor(drone_state->mag_scale_factor_);
	vTaskDelay(500 / portTICK_RATE_MS);

	printf("Calibrating...");

	gyro_reader.enable_int2(true);
	gyro_reader.calculate_static_bias_filtered(2400);
	printf(" Done!\n");
	flight_ctl.start_receiver();

	printf("Entering main loop...\n");
	gyro_reader.enable_int2(true);

	sample_dt.time_stamp();
	lps25hb.Set_FifoMode(LPS25HB_FIFO_STREAM_MODE);
	lps25hb.Set_FifoModeUse(LPS25HB_ENABLE);
	lps25hb.Set_Odr(LPS25HB_ODR_25HZ);
	lps25hb.Set_Bdu(LPS25HB_BDU_NO_UPDATE);
	LPS25HB_FIFOTypeDef_st fifo_config;
	memset(&fifo_config, 0, sizeof(fifo_config));
	lps25hb.Get_FifoConfig(&fifo_config);

#ifdef USE_LPS25HB
	float base_pressure = lps25hb.Get_PressureHpa();
	for (int i = 0; i < 100; i++) {
		while (lps25hb.Get_FifoStatus().FIFO_EMPTY)
			vTaskDelay(50 / portTICK_RATE_MS);
		base_pressure = pressure_lpf.do_filter(lps25hb.Get_PressureHpa());
	}
#endif

	bmp_reader.calibrate();

	// Infinite loop
	PerfCounter idle_time;
	while (1) {
		drone_state->iteration_++;
		if (drone_state->iteration_ % 120 == 0) {
			led1.toggle();
		}


		if (drone_state->iteration_ % 4 == 0) {
#ifdef USE_LPS25HB
			drone_state->temperature_ = lps25hb.Get_TemperatureCelsius();
			while (!lps25hb.Get_FifoStatus().FIFO_EMPTY) {
				drone_state->pressure_hpa_ = pressure_lpf.do_filter(lps25hb.Get_PressureHpa());
				float alt = (powf(base_pressure/drone_state->pressure_hpa_, 0.1902f) - 1.0f) * ((lps25hb.Get_TemperatureCelsius()) + 273.15f)/0.0065;
				drone_state->altitude_ = Distance::from_meters(alt);
			}
#else
			bmp_reader.pressure_filter_.set_alpha(drone_state->altitude_lpf_);
			drone_state->altitude_ = bmp_reader.get_altitude(true);
			drone_state->pressure_hpa_ = bmp_reader.get_pressure().hpa();
			drone_state->temperature_ = bmp_reader.get_temperature(false).celsius();
#endif
		}

		idle_time.begin_measure();
		gyro_reader.wait_for_data();
		idle_time.end_measure();
		drone_state->dt_ = sample_dt.elapsed();
		sample_dt.time_stamp();

		if (drone_state->base_throttle_ > 0.1)
			att.accelerometer_correction_speed(drone_state->accelerometer_correction_speed_);
		else
			att.accelerometer_correction_speed(3.0f);
		att.gyro_drift_pid(drone_state->gyro_drift_kp_, drone_state->gyro_drift_ki_, drone_state->gyro_drift_kd_);
		att.gyro_drift_leak_rate(drone_state->gyro_drift_leak_rate_);

		size_t fifosize = gyro_reader.size();
		for (size_t i = 0; i < fifosize; i++)
			   drone_state->gyro_raw_ = gyro_lpf.do_filter(gyro_reader.read_sample());
		if (drone_state->gyro_raw_.length_squared() > 0 && drone_state->dt_.microseconds() > 0) {
			   drone_state->gyro_ = (drone_state->gyro_raw_ - gyro_reader.bias()) * drone_state->gyro_factor_;
			   att.track_gyroscope(DEG2RAD(drone_state->gyro_) * 1.0f, drone_state->dt_.seconds_float());
		}

		fifosize = acc_reader.size();
		for (size_t i = 0; i < fifosize; i++) {
			Vector3f acc_sample = acc_reader.read_sample_acc();
			acc_lpf_att.do_filter(acc_sample);
			acc_lpf_alt.do_filter(acc_sample);
		}
		drone_state->accel_raw_ = acc_lpf_att.output();
		drone_state->accel_alt_ = acc_lpf_alt.output();
		drone_state->accel_ = (drone_state->accel_raw_ - drone_state->accelerometer_adjustment_).normalize();

#define ALLOW_ACCELEROMETER_OFF
#ifdef ALLOW_ACCELEROMETER_OFF
		if (drone_state->track_accelerometer_) {
			att.track_accelerometer(drone_state->accel_, drone_state->dt_.seconds_float());
		}
#else
		att.track_accelerometer(drone_state->accel_, drone_state->dt_.seconds_float());
#endif

#define REALTIME_DATA 0
#if REALTIME_DATA
		std::cout << drone_state->gyro_.transpose() << drone_state->accel_.transpose() << drone_state->pid_torque_.transpose();
		std::cout << drone_state->dt_.seconds_float() << std::endl;
#endif

		drone_state->mag_raw_ = acc_reader.read_sample_mag();
		drone_state->mag_ = drone_state->mag_raw_.normalize();
		if (drone_state->track_magnetometer_) {
			att.track_magnetometer(drone_state->mag_, drone_state->dt_.seconds_float());
		}

		drone_state->attitude_ = att.get_attitude();
		drone_state->gyro_drift_error_ = RAD2DEG(att.get_drift_error());

		flight_ctl.update_state(*drone_state);
		flight_ctl.send_throttle_to_motors();

		if (print_to_console && console_update_time.elapsed() > TimeSpan::from_milliseconds(300)) {

			Vector3f drift_err = att.get_drift_error();
			console_update_time.time_stamp();
			printf("Gyro      : %5.3f %5.3f %5.3f\n", drone_state->gyro_.at(0), drone_state->gyro_.at(1), drone_state->gyro_.at(2));
			printf("Drift Err : %5.3f %5.3f %5.3f\n", RAD2DEG(drift_err.at(0)), RAD2DEG(drift_err.at(1)), RAD2DEG(drift_err.at(2)));
			printf("Gyro Raw  : %5.3f %5.3f %5.3f\n", drone_state->gyro_raw_.at(0), drone_state->gyro_raw_.at(1), drone_state->gyro_raw_.at(2));
			printf("Accel     : %5.3f %5.3f %5.3f\n", drone_state->accel_.at(0), drone_state->accel_.at(1), drone_state->accel_.at(2));
			printf("Mag       : %5.3f %5.3f %5.3f\n", drone_state->mag_.at(0), drone_state->mag_.at(1), drone_state->mag_.at(2));
			printf("dT        : %lu uSec\n", (uint32_t)drone_state->dt_.microseconds());
			printf("Q         : %5.3f %5.3f %5.3f %5.3f\n\n", drone_state->attitude_.w, drone_state->attitude_.x, drone_state->attitude_.y,
					drone_state->attitude_.z);
#if 1
			printf("Motors    : %1.2f %1.2f %1.2f %1.2f\n", drone_state->motors_[0], drone_state->motors_[1],
								drone_state->motors_[2], drone_state->motors_[3]);
			printf("Throttle  : %1.2f\n", drone_state->base_throttle_);
		    printf("Armed     : %d\n", drone_state->motors_armed_);
			printf("Altitude  : %4.2f m\n", drone_state->altitude_.meters());
			printf("GPS       : Lon: %3.4f Lat: %3.4f Sat %lu Alt: %4.2f m\n",
					drone_state->longitude_.degrees(), drone_state->latitude_.degrees(),
					drone_state->satellite_count_, drone_state->gps_altitude_.meters());
			printf("Battery   : %2.1f V, %2.0f%%\n", drone_state->battery_voltage_.volts(), drone_state->battery_percentage_);
#endif
		}

#if 0
		if (led_toggle_ts.elapsed() > TimeSpan::from_seconds(1)) {
			led_toggle_ts.time_stamp();
			led0.toggle();
		}
#endif

#ifndef ENABLE_UART_TASK
		rpcserver.jsonrpc_request_handler(&uart2);
#endif
	}
}
Ejemplo n.º 15
0
Archivo: main.cpp Proyecto: I-SYST/EHAL
int main()
{
	bool res;

#ifdef DEMO_C
	res = UARTInit(&g_UartDev, &g_UartCfg);
#else
	res = g_Uart.Init(g_UartCfg);
#endif

	uint8_t d = 0xff;
    uint8_t val = 0;
    uint32_t errcnt = 0;
    uint32_t cnt = 0;
    auto t_start = std::chrono::high_resolution_clock::now();
    auto t_end = std::chrono::high_resolution_clock::now();
    
    std::chrono::duration<float> elapse = std::chrono::duration<float>(0);
    t_start = std::chrono::high_resolution_clock::now();

    time_t t;
    double e = 0.0;
    bool isOK = false;
//    do {
#ifdef DEMO_C
    while (UARTRx(&g_UartDev, &d, 1) <= 0);
#else
    while (g_Uart.Rx(&d, 1) <= 0);
#endif
    	if (val == d)
            isOK = true;
    	val = Prbs8(d);
 //   } while (!isOK);
    
	while(1)
	{
       // t_start = std::chrono::high_resolution_clock::now();
        t = time(NULL);
#ifdef DEMO_C
        while (UARTRx(&g_UartDev, &d, 1) <= 0);
#else
        while (g_Uart.Rx(&d, 1) <= 0);
#endif
		{
            e += difftime(time(NULL), t);
          //  t_end = std::chrono::high_resolution_clock::now();
            //elapse += std::chrono::duration<float>(t_end-t_start);
            cnt++;
            
			// If success send next code
           // printf("%x ", d);
            if (val != d)
            {
                errcnt++;
               // printf("PRBS %u errors %x %x\n", errcnt, val, d);
            }
            else if ((cnt & 0x7fff) == 0)
            {
                printf("PRBS rate %.3f B/s, err : %u\n", cnt / e, errcnt);
//                printf("PRBS rate %.3f B/s, err : %u\n", cnt / elapse.count(), errcnt);

            }
			val = Prbs8(d);
		}
	}
	return 0;
}
Ejemplo n.º 16
0
void clearUARTStats() {
    uart0.clearStats();
}
Ejemplo n.º 17
0
void getUARTStats(XUartLite_Stats* stats) {
    uart0.getStats(stats);
}
Ejemplo n.º 18
0
bool isCharReady() {
    return uart0.isCharReady();
}
Ejemplo n.º 19
0
/** Returns -1 if no data, else char from getchar **/
int getcharNoWait() {
    char c;

	if (uart0.getcharNoWait(c)) return (unsigned char)c;
    else return -1;
}
Ejemplo n.º 20
0
// main entry point, go ahead, have fun!
int main(void) {
	// hold the power button for 3 seconds or shutdown
	//_delay_ms(STARTUP_DELAY);
	// keep power pin High unless we want to shutdown
	powerControl = 1;

	// disable JTAG so we can use PF4,PF5,PF6,PF7 for ADC and GPIO
	MCUCSR |=(1<<JTD);MCUCSR |=(1<<JTD); // two times!!

	// init time RTC
	time.init(callback_timeSecond, callback_timeMinute);
	time.startInterval();

	// microcontroller features
	adc.init();	// needed by gp2y10 and more
	spi_init();	// needed by ILI9341
	i2c_init(); // needed by bmp180 and mics-vz-89t
	uart1.init(1, 9600, 1); // needed by esp8266 . Interrupts are hard on parsing, polling would be easier but blocking
	uart0.init(0, 9600, 1);
	// CONFIGURE INTERRUPT INT4  to count pulses from Geiger Counter
	EICRB |= (1<<ISC00) | (1<<ISC01); // Configure INT4 to trigger on RISING EDGE
	EIMSK |= (1<<INT4); // Configure INT4 to fire interrupts

	// CREATE Timer T1 PWM to drive inverter for regulated Geiger tube voltage
	inverter.initPWM();

	// init display
	lcd.init();
	lcd.setRotation(ILI9341::ROT0);
	//lcd.drawClear(BLACK);
	backlight(true);

	// init sensors
	bmp180.init();
	dust.init(&dustFlash, &adc, PF1);

	beep();
	// start UI

	// enter main menu
	// ## touchscreen calibration code
	/*while (1) {
		uint16_t x = 0, y = 0, z = 0;
				if (touch.read(&x, &y , &z)) {
					lcd.drawPixel(x,y, 2, RED);
				}
		lcd.drawStringF(0,0,2,WHITE, BLACK, "%4u %4u %4u", touch.readRawX(), touch.readRawY(), touch.readRawPressure());
	}*/

	// draw GUI first page with self check
	if (!gui.drawPage(PAGE_INIT))
		shutdown();


	_delay_ms(1000);
	gui.drawPage(PAGE_MAIN);
	// ## main code loop
	while (1) {
		// ## beep
		if (cmdBeep && !cmdAlarm && !isMuted) {
			beep();
			cmdBeep = false;
		}
		// ## read sensors
		// read inverter voltage, via 10M/47K resistive divider, connected to pin ADC2
		data.geiger_voltage = readTubeVoltage();
		inverter.adjustDutyCycle(data.geiger_voltage); // do nothing on failure, we can't reset
		// read battery
		data.battery_voltage = readBatVoltage();

		// turn backlight off when timeout is reached
		if (secTimeout > BACKLIGHT_TIMEOUT) {
			backlight(false);
			secTimeout = 0;
		}
		// ## draw titlebar and refresh data display
		if (cmdRefreshText) {
			// sensor BMP180
			bmp180.readAll(&data.bmp180_temp, &data.bmp180_pressure, &data.bmp180_altitude);
			dust.readDust(&data.gp2y10_dust);
			// sensor MICS-VZ-89T
			uint8_t reactivity = 0;
			// repeat until successful read with timeout?
			//int timeout = 10;
			//while (!vz89.read(&data.vz89_co2, &reactivity, &data.vz89_voc) && timeout) { _delay_ms(1500); timeout--; }
			vz89.read(&data.vz89_co2, &reactivity, &data.vz89_voc);
			// geiger readings
			//float dose = aux_CPM2uSVh((uint8_t)DEV_RAD_DETECTOR, geigerCPM);
			data.geiger_cpm = geigerCPM;

			data.time_hour = time.getHour();
			data.time_minute = time.getMin();
			data.time_second = time.getSec();

			data.setLimits(); // must be changed to proper OOP set/get for all fields
			gui.updateValues();

			// ## alarm condition
			if (geigerCPM >= GEIGER_CPM_ALARM) {
				// threshold to sound alarm reached
				cmdAlarm = ALARM_RADIATION;
			} else if (cmdAlarm) {
				// alarm should be turned off
				cmdAlarm = 0;
				speaker = 0;
			}

			cmdRefreshText = false;

		}
		// ## every minute we can dispatch data over serial or over WLAN to uradmonitor
		if (cmdSend) {
			char tmp[200];
			sprintf(tmp,"{\"data\":{ \"id\":\"%08lX\","
					"\"type\":\"%X\",\"detector\":\"%s\","
					"\"cpm\":%lu,\"temperature\":%.2f,\"uptime\": %lu,"
					"\"pressure\":%lu,\"dust\":%.2f,\"co2\":%.2f,\"voc\":%.2f,"
					"\"battery\":%.2f,\"tube\":%u}}",
					deviceID, DEV_MODEL, aux_detectorName(DEV_RAD_DETECTOR), geigerCPM, data.bmp180_temp, time.getTotalSec(),
					data.bmp180_pressure, data.gp2y10_dust,data.vz89_co2, data.vz89_voc, data.battery_voltage, data.geiger_voltage);
			data.serial_sent += strlen(tmp);
			uart0.send(tmp);

			// internet code here

			sprintf(tmp,"id=%08lX&ts=%ld&inv=%d&ind=%d&s1t=%2.2f&cpm=%ld&voc=%.2f&co2=%.2f",
								deviceID,
								time.getTotalSec(),
								data.geiger_voltage,
								data.geiger_duty,
								data.bmp180_temp,
								geigerCPM,
								data.vz89_voc, data.vz89_co2);

						wifi.sendData(tmp);
			cmdSend = false;
		}

		// ## act on the gui elements
		// read a new touch event only if we are done with previous: useful for handling confirmation "modal" "dialogs"
		if (uiResult == 0) {
			uiResult = gui.readTouchEvent();
			// reset backlight timeout on valid touch
			if (uiResult > 0) {
				secTimeout = 0;
				backlight(true);
				// if screen is pressed while alarm is on, stop alarm
				if (cmdAlarm) {
					cmdAlarm = false;
					speaker = 0;
				}
			}
		}
		// handle special cases: click on wlan AP buttons
		if (uiResult >= ID_BUTTON_WLAN_START && uiResult < ID_BUTTON_WLAN_STOP) {
			uint8_t ap_index = uiResult - ID_BUTTON_WLAN_START;
			// connect and return to main screen
			wifi.connectWiFi(data.freeAPList[ap_index], "");
			uiResult = 0;
			gui.drawPage(PAGE_MAIN);
		}
		// handle regular buttons
		switch (uiResult) {
			case  ID_BUTTON_SHUTDOWN: {
				uint16_t result = gui.showYesNoPopup("Are you sure?");
				if (result == ID_YES)
					shutdown();
				else if (result == ID_NO) {
					uiResult = 0;
					gui.drawPage(PAGE_MAIN);
				}
			} break;
			case ID_BUTTON_MEASURE: {
				uiResult = 0;
				gui.drawPage(PAGE_MEASURE);
			} break;
			case ID_BUTTON_MONITOR: {
				uiResult = 0;
				gui.drawPage(PAGE_MONITOR);
			} break;
			case ID_BUTTON_SETTINGS: {
				uiResult = 0;
				gui.drawPage(PAGE_SETTINGS);
			} break;
			case ID_BUTTON_BACK: {
				uiResult = 0;
				gui.drawPage(PAGE_MAIN);
			} break;
			case ID_BUTTON_MUTE: {
				isMuted = !isMuted;
				if (!isMuted) beep(); // test beep that sound is on
				uiResult = 0;
			} break;
			case ID_BUTTON_CALIBRATE: {
				uiResult = 0;
				gui.drawPage(PAGE_CALIBRATE);
			} break;
			case ID_BUTTON_WLAN: {
				// request list of WLAN APs
				data.freeAPCount = 0;
				//wifi.setMode();
				wifi.listAP();
				uiResult = 0;
				gui.drawPage(PAGE_WLAN);
			}
			break;
			// other commands that don't require a popup so we consume asap
			default:
				uiResult = 0;
		}

		//uint16_t x, y,z;
				//gui.getLastTouch(&x, &y, &z);
				//lcd.drawStringF(0,288, 2, RED, BLACK,"%u %d,%d   ", uiResult, x,y);

	}
}
Ejemplo n.º 21
0
void query()
{

   ////////////////////////////////////////////////
   extern int curSpeed;
   extern int curRPM;
   extern int initFuel, prevFuel, curFuel;
   extern int initDist, curDist;
   extern int curTemp;
   extern int leftDist, rightDist;

   //Time Globals
   extern time_t rawTime;
   extern struct tm *prevTime, *curTime;
   extern int timeOffset;
   extern bool forwardMode;



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

   int temp, count=0;
   UART uart;
   myI2C *sensorPtr0 = new myI2C();
   myI2C *sensorPtr1 = new myI2C();

   std::string RPM="010C\r";
   std::string Speed="010D\r";
   std::string Temperature="0105\r";
   std::string Fuel="012F\r";
   std::string Dist="0131\r";

   //   sensorPtr0->i2cSetAddress(DEVICE_ADDR0);
   //   sensorPtr1->i2cSetAddress(DEVICE_ADDR1);

   uart.initUart();

   uart.sendLine("ATZ\r");

   int fd = open( "/sys/class/gpio/gpio67/value", O_RDONLY | O_NONBLOCK );
   GIOChannel* channel = g_io_channel_unix_new( fd );
   GIOCondition cond = GIOCondition( G_IO_PRI );
   guint id = g_io_add_watch( channel, cond, onButtonEvent, 0 );


   usleep(5000000);



   //Get initial Distance
   //======================================
   uart.sendLine(Dist);
   temp=-1;
   while(temp==-1)
   {
      if ((temp=uart.receiveLineData("013141 31 ",5))!=-1)
      {
	 initDist=temp;
	 curDist=initDist;
      }
      usleep(500000);
   }
   //======================================

   //Get initial time
   //======================================
   time(&rawTime);
   prevTime=localtime(&rawTime);
   prevTime->tm_hour+=timeOffset;
   curTime=localtime(&rawTime);
   curTime->tm_hour+=timeOffset;
   if(prevTime->tm_hour<0)
   {
      prevTime->tm_hour+=24;
      curTime->tm_hour+=24;
   }
   //======================================

   //Get initial fuel level
   //======================================
   uart.sendLine(Fuel);
   temp=-1;
   while(temp==-1)
   {
      if ((temp=uart.receiveLineData("012F41 2F ",2))!=-1)
      {
	 initFuel=temp;
	 prevFuel=initFuel;
	 curFuel=initFuel;
      }
      usleep(500000);
   }
   //======================================

   //Query for Engine Temp
   //======================================
   uart.sendLine(Temperature);
   temp=-1;
   while(temp==-1)
   {
      if ((temp=uart.receiveLineData("010541 05 ",2))!=-1)
      {
	 curTemp=temp;
      }
      usleep(500000);
   }
   //======================================

   while(1)
   {
      //Forward Mode
      //======================================
      if(forwardMode)
      {

	 //Query for Speed
	 //======================================
	 uart.sendLine(Speed);
	 if ((temp=uart.receiveLineData("010D41 0D ",2))!=-1)
	 {
	    curSpeed=temp;
	 }
	 //======================================

	 usleep(500000);
	 //Query for RPM
	 //======================================
	 uart.sendLine(RPM);
	 if ((temp=uart.receiveLineData("010C41 0C ",5))!=-1)
	 {
	    curRPM=temp;
	 }
	 //======================================

	 //Get the time
	 //======================================
	 time(&rawTime);
	 curTime=localtime(&rawTime);
	 curTime->tm_hour+=timeOffset;
	 if(curTime->tm_hour < 0)
	 {
	    curTime->tm_hour+=24;
	 }
	 //======================================

	 usleep(500000);
	 //if it's been a minute, check fuel level and engine Temp
	 //======================================
	 if(count>99)
	 {
	    count=0;
	    prevTime=localtime(&rawTime);
	    prevTime->tm_hour+=timeOffset;
	    if(prevTime->tm_hour < 0)
	    {
	       prevTime->tm_hour+=24;
	    }
	    uart.sendLine(Fuel);
	    if ((temp=uart.receiveLineData("012F41 2F ",2))!=-1)
	    {
	       curFuel=temp;
	    }
	    usleep(500000);

	    //Query for Engine Temp
	    //======================================
	    if ((temp=uart.receiveLineData("010541 05 ",2))!=-1)
	    {
	       curTemp=temp;
	    }
	    //======================================
	    usleep(500000);
	 }
	 //======================================

	 //if the fuel level has changed,
	 //check distance
	 //======================================
	 if(prevFuel!=curFuel)
	 {
	    prevFuel=curFuel;
	    uart.sendLine(Dist);
	    if ((temp=uart.receiveLineData("013141 31 ",4))!=-1)
	    {
	       curDist=temp;
	    }
	    usleep(500000);
	 }

	 //if the speed is greater than 30MPH or 49 KPH
	 //check rear distance
	 //======================================
	 if(curSpeed > 49)
	 {
	    /*sensorPtr0->Send_I2C_Byte(0x00, 0x51);
	      usleep(68E3);
	      leftDist=sensorPtr0->Read_2I2C_Bytes(0x02);
	      sensorPtr1->Send_I2C_Byte(0x00, 0x51);
	      usleep(68E3);
	      rightDist=sensorPtr1->Read_2I2C_Bytes(0x02);*/
	 }
	 //======================================
      
      count++;

      }
      //======================================

      //Reverse Mode
      //======================================
      else
      {
	 usleep(1000000);
	 //Query reverse distance as much as possible
	 //======================================
	 /*sensorPtr0->Send_I2C_Byte(0x00, 0x51);
	   usleep(68E3);
	   leftDist=sensorPtr0->Read_2I2C_Bytes(0x02);
	   sensorPtr1->Send_I2C_Byte(0x00, 0x51);
	   usleep(68E3);
	   rightDist=sensorPtr1->Read_2I2C_Bytes(0x02);*/
	 //======================================

      }
   }
}
Ejemplo n.º 22
0
    void printk(const char* message_) { // boring and not flexible but mandatory =/
	UART com;
	VGA v;
	v.put(message_, COLOR_WHITE);
	com.send(message_);
    }
Ejemplo n.º 23
0
void UartTxSrvcCallback(BLESRVC *pBlueIOSvc, uint8_t *pData, int Offset, int Len)
{
	g_Uart.Tx(pData, Len);
}
Ejemplo n.º 24
0
int main()
{
	g_Uart.Init(s_UartCfg);

	// Retarget printf to UART
	UARTRetargetEnable(g_Uart, STDOUT_FILENO);
	UARTRetargetEnable(g_Uart, STDIN_FILENO);

	printf("Flash Memory Demo\r\n");
	getchar();

	g_Spi.Init(s_SpiCfg);

    IOPinConfig(FLASH_HOLD_PORT, FLASH_HOLD_PIN, FLASH_HOLD_PINOP, IOPINDIR_OUTPUT, IOPINRES_PULLUP, IOPINTYPE_NORMAL);

	g_FlashDiskIO.Init(s_FlashDiskCfg, &g_Spi, &g_FlashCache, 1);

	uint8_t buff[512];
	uint8_t tmp[512];
	uint16_t *p = (uint16_t*)buff;

	memset(tmp, 0, 512);
	for (int i = 0; i < 256; i++)
	{
		p[i] = i;
	}


	printf("Erasing... Please wait\r\n");

	// Ease could take a few minutes
	g_FlashDiskIO.Erase();

	printf("Writing 2KB data...\r\n");

	g_FlashDiskIO.SectWrite(0, buff);
	g_FlashDiskIO.SectWrite(2, buff);
	g_FlashDiskIO.SectWrite(4, buff);
	g_FlashDiskIO.SectWrite(8, buff);

	printf("Validate readback...\r\n");

	g_FlashDiskIO.SectRead(0, tmp);

	if (memcmp(buff, tmp, 512) != 0)
	{
		printf("Sector 0 verify failed\r\n");
	}
	else
	{
		printf("Sector 0 verify success\r\n");
	}

	memset(tmp, 0, 512);
	g_FlashDiskIO.SectRead(2, tmp);
	if (memcmp(buff, tmp, 512) != 0)
	{
		printf("Sector 2 verify failed\r\n");
	}
	else
	{
		printf("Sector 2 verify success\r\n");
	}

	memset(tmp, 0, 512);
	g_FlashDiskIO.SectRead(4, tmp);
	if (memcmp(buff, tmp, 512) != 0)
	{
		printf("Sector 4 verify failed\r\n");
	}
	else
	{
		printf("Sector 4 verify success\r\n");
	}

	memset(tmp, 0, 512);
	g_FlashDiskIO.SectRead(8, tmp);
	if (memcmp(buff, tmp, 512) != 0)
	{
		printf("Sector 8 verify failed\r\n");
	}
	else
	{
		printf("Sector 8 verify success\r\n");
	}

}
Ejemplo n.º 25
0
int main()
{
	bool res;
char *data = "nRF UART Hello World\r\n";
	uint8_t buff[20];

/*	nrf_gpio_cfg_output(9);
	while (1)
	{
		nrf_gpio_pin_toggle(9);
		usDelay(1000);
	}*/
	//NRF_MPU->PERR0 &= ~(1 << 2);
	//uart_init();
	//simple_uart_config(UART_RTS_PIN, UART_TX_PIN, UART_CTS_PIN, UART_RX_PIN, false);

#ifdef C_CODE
	res = UARTInit(&g_UartDev, &g_UartCfg);
	UARTprintf(&g_UartDev, data);
#else
	res = g_Uart.Init(g_UartCfg);
	g_Uart.printf(data);dfg
#endif
//    nrf_drv_gpiote_in_config_t cts_config = GPIOTE_CONFIG_IN_SENSE_TOGGLE(false);
//    nrf_drv_gpiote_in_init(p_comm_params->cts_pin_no, &cts_config, gpiote_uart_event_handler);

	//for (int i = 0; i < 20; i++)
	//	simple_uart_put(data[i]);
	//simple_uart_putstring((const uint8_t*)data);

	while(1) {
		uint8_t d;
		//usDelay(1000);
		//d = simple_uart_get();
		//simple_uart_put(d);
#ifndef TEST_INTERRUPT
		if (UARTRx(&g_UartDev, &d, 1) > 0)
		{
			UARTTx(&g_UartDev, &d, 1);
		//	UARTTx(&g_UartDev, (uint8_t*)data, 22);
			//usDelay(1000);
		}
#else
		int cnt = UARTRx(&g_UartDev, buff, 20);
		if (cnt > 0)
		{
			uint8_t *p = buff;
			while (cnt > 0)
			{
				int l = UARTTx(&g_UartDev, p, cnt);
				cnt -= l;
				p += l;
			}
		//	UARTTx(&g_UartDev, (uint8_t*)data, 22);
			//usDelay(1000);
		}

#endif
		//__WFI();
	}
	return 0;
}