Esempio n. 1
0
void alarmSound(uint8_t reps){
	int rep = 0;
	for(rep = 0;rep < reps;rep++){
		int size = sizeof(melody) / sizeof(int);
		for(int thisNote = 0; thisNote < size; thisNote++){
			int noteDuration = 1000 / tempo[thisNote];
			buzz(melody[thisNote], noteDuration);
			int pauseBetweenNotes = noteDuration * 1.30;
			while(pauseBetweenNotes-- != 0)
				_delay_us(300);
			
			buzz(0, noteDuration);
		}
	}
}
Esempio n. 2
0
int main() {
  Word fizz("fizz");
  Word buzz("buzz");
  auto fizz_buzz = fizz + buzz;

  std::unordered_map<int, Word*> words;

  words[3] = words[6] = words[9] = words[12] = &fizz;
  words[5] = words[10] = &buzz;
  words[15] = &fizz_buzz;
  
  for(int penta_deca = 0; penta_deca < 7; ++penta_deca) {
    for(int i = 1; i <= 15; ++i) {
      auto word = words.find(i);

      if(word != words.end()) {
	std::cout << *word->second << std::endl;
      } else {
	std::cout << i + penta_deca * 15 << std::endl;
      }
    }
  }

  return 0;
}
Esempio n. 3
0
void gpio_handler(void)
{
    LED_ON(2);
    POMP_OUT_ON();
    app_timer_start(m_one_second_timer, POMP_ENABLE_TIME_MS);
    buzz();
}
int main(void)
{
	// set up port B

	DDRB  = _BV(DDB5);             // set port B pin 5 as output
	PORTB = ~(_BV(DDB5));          // set pullups on inputs

	set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // set sleep mode

	// set up interrupts 

	PCMSK1 |= _BV(PCINT12);        // enable PCI interrupt on PB4

	PCICR  |= _BV(PCIE1);          // enable pin change interrupt 1
	PCIFR  |= _BV(PCIF1);          // clear pin change interrupt flag 1

	sei();                         // enable interrupts

	// infinite loop to wait until button is pressed
	while (1) {
		sleep_mode();
		buzz();
	}
	return(1);
}
Esempio n. 5
0
int dobreathe(void)
{
	const struct attack *mattk;
	schar dx, dy, dz;

	if (Strangled) {
	    pline("You can't breathe.  Sorry.");
	    return 0;
	}
	if (u.uen < 15) {
	    pline("You don't have enough energy to breathe!");
	    return 0;
	}
	u.uen -= 15;
	iflags.botl = 1;

	if (!getdir(NULL, &dx, &dy, &dz))
	    return 0;

	mattk = attacktype_fordmg(youmonst.data, AT_BREA, AD_ANY);
	if (!mattk)
	    impossible("bad breath attack?");	/* mouthwash needed... */
	else
	    buzz((int) (20 + mattk->adtyp-1), (int)mattk->damn,
		u.ux, u.uy, dx, dy);
	return 1;
}
Esempio n. 6
0
int main(int argc, char **argv) {
	int freq, length;
	char *binary;
	char c;
	binary = *argv;
	if (argc < 2) {printf("Usage: %s <tone 0-21| freq 2000-250 | pause -millisec> [...]\n", binary); return 0;}
	if (!init_buzzer()) {printf("Run as Root\n"); return 0;}
	argv++;
	c = *(argv)[0];
	if (((c < 48) || (c > 58)) && (c != '-')) {printf("Usage: %s <tone 0-21| freq 2000-250| p -millisec> [...]\n", binary); return 0;}
	int x;
	for (x = 1; x < argc; x++) {
	c = *(argv)[0];
	if (((c < 48) || (c > 58)) && (c != '-')) {printf("Usage: %s <tone 0-21| freq 2000-250| p -millisec> [...]\n", binary); return 0;}
	if ((*argv[0] == '-') && (*(*argv+1) != 0)) {
		sscanf(*argv+1,"%d",&freq);
		wait(freq);
	}
	else {
		if (!( (*argv[0] < 48) || (*argv[0] > 58) )) sscanf(*argv,"%d",&freq);
		if (freq < 250) if (freq < NOTES) freq = progression[freq];
		else freq = 1550;
		buzz(freq);
	}
	argv++;
}

stop_buzzer();
return 1;
}
Esempio n. 7
0
void play_mario() {
  {
    for (int thisNote = 0; thisNote < 78; thisNote++) {
      // to calculate the note duration, take one second
      // divided by the note type.
      //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
      int noteDuration = 1000 / tempo[thisNote];
      buzz(BUZ_PIN, melody[thisNote], noteDuration);
      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well:
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);
      // stop the tone playing:
      buzz(BUZ_PIN, 0, noteDuration);
    }
  }
}
 // UpdateAsync allows the buzzer to buzz every 90 ms asynchronously
 void UpdateAsync() {
     if (soundAlarm) {
         unsigned long currentMillis = millis();
         if (currentMillis - lastMillis >= 90) {
             buzz(freq, 20);
             lastMillis = currentMillis;
         }
     }
 }
Esempio n. 9
0
int main(int argc, char* argv[])
{
    int num, i;
    if (argc <= 1) exit(0);
    num = atoi(argv[1]);
    for (i=1; i <= num; i++) {
        if (fizz(i) && buzz(i)) {
            printf("FizzBuzz\n");
        } else if (fizz(i)) {
            printf("Fizz\n");
        } else if (buzz(i)) {
            printf("Buzz\n");
        } else {
            printf("%d\n", i);
        }
    }
    return 0;
}
Esempio n. 10
0
std::string FizzBuzz::answer(int number)
{
	std::stringstream answer;
	
	answer << fizz(number) << buzz(number);
	if (answer.str() == "")
		answer << number;

	return answer.str();
}
Esempio n. 11
0
/* this "calibrates" the buzz loop to determine buzzmax */
void initbuzz()
{
	long t0, t1;

	buzzmax = 1000000;
	sginap(10);	/* sleep for 10/100 of a second */
	t0 = getltime();
	buzz();
	t1 = getltime();
	buzzmax = TIMESLICE*(100.0*1000000.0)/(t1-t0);
}
Esempio n. 12
0
void playBell(int* IDbell,int* IDbuzzer,unsigned char delay,int *fd){
	printf ("on \n");
	setChannelState(*IDbell,1);
	/*wait(1,&fd);*/

	/*buzzo*/
	buzz(IDbuzzer);

	printf ("off \n");
	setChannelState(*IDbell,0);
	wait(delay,fd);
}
Esempio n. 13
0
void alarmSound(uint8_t reps){
	int rep = 0;
	for(rep = 0;rep < reps;rep++){
		int size = sizeof(melody) / sizeof(int);
    		for (int thisNote = 0; thisNote < size; thisNote++) {
 			// to calculate the note duration, take one second
      			// divided by the note type.
      			//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
     		 	int noteDuration = 1000 / tempo[thisNote];
 
	      		buzz(melody[thisNote], noteDuration);
	 
	      		// to distinguish the notes, set a minimum time between them.
	      		// the note's duration + 30% seems to work well:
	      		int pauseBetweenNotes = noteDuration * 1.30;
	      		while(pauseBetweenNotes-- != 0)
				_delay_us(300);
			
	 
	     	 	// stop the tone playing:
	      		buzz(0, noteDuration);
	    	}
	}		
}
Esempio n. 14
0
int
breamq(struct monst *mtmp, int xdef, int ydef, const struct attack *mattk)
{
    /* if new breath types are added, change AD_ACID to max type */
    int typ = (mattk->adtyp == AD_RBRE) ? rnd(AD_ACID) : mattk->adtyp;

    boolean youdef = u.ux == xdef && u.uy == ydef;

    if (!youdef && distmin(mtmp->mx, mtmp->my, xdef, ydef) < 3)
        return 0;

    boolean linedup = qlined_up(mtmp, xdef, ydef, TRUE, FALSE);

    if (linedup) {
        if (mtmp->mcan) {
            if (canhear()) {
                if (mon_visible(mtmp))
                    pline("%s coughs.", Monnam(mtmp));
                else
                    You_hear("a cough.");
            }
            return 0;
        }
        if (!mtmp->mspec_used && rn2(3)) {
            if ((typ >= AD_MAGM) && (typ <= AD_ACID)) {
                if (mon_visible(mtmp)) {
                    pline("%s breathes %s!", Monnam(mtmp), breathwep[typ - 1]);
                    action_interrupted();
                }
                buzz((int)(-20 - (typ - 1)), (int)mattk->damn, mtmp->mx,
                     mtmp->my, sgn(tbx), sgn(tby), 0);
                /* breath runs out sometimes. Also, give monster some cunning;
                   don't breath if the target fell asleep. */
                if (!rn2(3))
                    mtmp->mspec_used = 10 + rn2(20);
                boolean sleeping = youdef ? u_helpless(hm_asleep) :
                    MON_AT(level, xdef, ydef) ?
                    m_at(level, xdef, ydef)->msleeping : FALSE;
                if (typ == AD_SLEE && sleeping)
                    mtmp->mspec_used += rnd(20);
            } else
                impossible("Breath weapon %d used", typ - 1);
        }
    }
    return 1;
}
Esempio n. 15
0
void check_display_debug (void)
{
	//Check for keypad combination held
	if (keypad_get_key() == 0x01) 
	{
		buzz(10);
		for (i = 0; i < 200; i++) 
		{
			if (keypad_get_key() == KEY_TICK) 
			{
				lcd_debug_display();
				break;
			}
			//20 ms delay. Waits in loop for 4 Seconds
			os_dly_wait(2);
		}
	}
}
Esempio n. 16
0
int main(void){

	const unsigned short MainCycle = 60;
	Init(MainCycle);

		for( ; ; ) {

		       // step(,);
		        left = ADRead(0);
                right = ADRead(1);

                	if(left>600){
                		LED(2);
                		Wait(200);
                		turn(32760,32760,50);  //	軌道修正 ~ 右 10k,10k ,persist = 100ms
                	}


                	if(right>600){
                		LED(1);
                		Wait(200);
                		turn(-32760,-32760,50);   //軌道修正  ~ 左 -10k, -10k
                	}


                	if(right > 600 && left > 600){
                		break;
                	}


                	else{
                          step(30,0);
                          buzz(0,30,0);
			       	  }

    LED(0);
		     }



		return 0;
}
int main()
{
  for (int i = 0; i <= 100; i++) {
    printf("(%i)\n", i);
    int found_matches = 0;
    int number_of_threes = given_number_includes_digit(i, 3);
    if (number_of_threes) {
      times(number_of_threes, fizz);
      found_matches = 1;
    }
    if (i % 3 == 0) {
      fizz();
      printf("\n");
      found_matches = 1;
    }
    int number_of_fives = given_number_includes_digit(i, 5);
    if (number_of_fives) {
      times(number_of_fives, buzz);
      found_matches = 1;
    }
    if (i % 5 == 0) {
      buzz();
      printf("\n");
      found_matches = 1;
    }
    int number_of_sevens = given_number_includes_digit(i, 7);
    if (number_of_sevens) {
      times(number_of_sevens, woof);
      found_matches = 1;
    }
    if (i % 7 == 0) {
      woof();
      printf("\n");
      found_matches = 1;
    }
    if (!found_matches) {
      printf("%i \n", i);
    }
  }
  return 0;
}
Esempio n. 18
0
/* monster uses spell (ranged) */
int buzzmu(struct monst *mtmp, const struct attack  *mattk)
{
	/* don't print constant stream of curse messages for 'normal'
	   spellcasting monsters at range */
	if (mattk->adtyp > AD_SPC2)
	    return 0;

	if (mtmp->mcan) {
	    cursetxt(mtmp, FALSE);
	    return 0;
	}
	if (lined_up(mtmp) && rn2(3)) {
	    nomul(0, NULL);
	    if (mattk->adtyp && (mattk->adtyp < 11)) { /* no cf unsigned >0 */
		if (canseemon(mtmp))
		    pline("%s zaps you with a %s!", Monnam(mtmp),
			  flash_types[ad_to_typ(mattk->adtyp)]);
		buzz(-ad_to_typ(mattk->adtyp), (int)mattk->damn,
		     mtmp->mx, mtmp->my, sgn(tbx), sgn(tby));
	    }
	}
	return 1;
}
Esempio n. 19
0
int dobreathe(void) {
    const struct attack *mattk;

    if (Strangled) {
        You_cant("breathe.  Sorry.");
        return(0);
    }
    if (u.uen < 15) {
        You("don't have enough energy to breathe!");
        return (0);
    }
    u.uen -= 15;

    if (!getdir((char *)0))
        return (0);

    mattk = attacktype_fordmg(youmonst.data, AT_BREA, AD_ANY);
    if (!mattk)
        impossible("bad breath attack?"); /* mouthwash needed... */
    else
        buzz((int)(20 + mattk->adtyp - 1), (int)mattk->damn, u.ux, u.uy, u.delta.x, u.delta.y);
    return (1);
}
Esempio n. 20
0
void inrange(struct monst *mtmp)
{
    schar tx;
    schar ty;

    /* Spit fire only when both in a room or both in a corridor */
    if(inroom(u.ux, u.uy) != inroom(mtmp->mx, mtmp->my)) {
        return;
    }

    tx = u.ux - mtmp->mx;
    ty = u.uy - mtmp->my;

    if(((tx == 0) && (abs(ty) < 8))
       || ((ty == 0) && (abs(tx) < 8)) 
       || ((abs(tx) == abs(ty)) && (abs(tx) < 8))) {
        /* Spit fire in the direction of @ (not necessarily hitting) */
        buzz(-1, mtmp->mx, mtmp->my, sgn(tx), sgn(ty));

        if(u.uhp < 1) {
            done_in_by(mtmp);
        }
    }
}
Esempio n. 21
0
void main()
{
	short val;
	int menu, pres;
	float p, mx, my;

	curmass = 0.5;
	curdrag = 0.15;
	prefsize(800,640);
	initbuzz();
	winopen("dynadraw");
	glcompat(GLC_OLDPOLYGON,1);
	subpixel(1);
	shademodel(FLAT);
	gconfig();
	qdevice(LEFTMOUSE);
	qdevice(MIDDLEMOUSE);
	qdevice(MENUBUTTON);
	qdevice(RIGHTSHIFTKEY); 
	qdevice(UPARROWKEY); 
	qdevice(DOWNARROWKEY); 
	qdevice(RIGHTSHIFTKEY); 
	makeframe();
	menu = defpup("dynadraw %t|toggle line style|save PostScript");
	width = initwidth;
	mouse.fixedangle = 1;
	while(1) {
		switch(qread(&val)) {
		case REDRAW:
			makeframe();
			break;
		case MIDDLEMOUSE:
			if(val) 
				clearscreen();
			break;
		case UPARROWKEY:
			if(val) 
				initwidth *= 1.414213;
			width = initwidth;
			break;
		case DOWNARROWKEY:
			if(val) 
				initwidth /= 1.414213;
			width = initwidth;
			break;
		case MENUBUTTON:
			if(val) {
				switch(dopup(menu)) {
				case 1: 
					mouse.fixedangle = 1-mouse.fixedangle;
					break;
				case 2: 
					savepolys();
					break;
				}
			}
			break;
		case LEFTMOUSE:
			if(val) {
				my = getmousey();
				if(my>0*SLIDERHIGH && my<2*SLIDERHIGH) {
					if(my>SLIDERHIGH) {
						while(getbutton(LEFTMOUSE)) {
							p = paramval();
							if(p != curmass) {
								curmass = p;
								showsettings();
							}
						}
					} else {
						while(getbutton(LEFTMOUSE)) {
							p = paramval();
							if(p != curdrag) {
								curdrag = p;
								showsettings();
							}
						}
					}
				} else {
					mx = 1.25*fgetmousex();
					my = fgetmousey();
					filtersetpos(&mouse,mx,my);
					odelx = 0.0;
					odely = 0.0;
					while(getbutton(LEFTMOUSE)) {
						mx = 1.25*fgetmousex();
						my = fgetmousey();
						if(filterapply(&mouse,mx,my)) {
							drawsegment(&mouse);
							color(0);
							buzz();
						}
					}
				}
			}
			break;
		}
	}
}
Esempio n. 22
0
void buzzerSound(uint8_t reps){
	int rep = 0;
	for(rep = 0;rep < reps;rep++){
		buzz(NOTE_C1, 10000);
	}
}
Esempio n. 23
0
int main()
{
	// PICTURE
	Tester 	*tester = new Tester("Picture");
	Picture p;

	tester->test(p.data, std::string(""),
		"constructor without filename make an empty string");

	p.getPictureFromFile(std::string("file.test"));
	tester->test(p.data, std::string("this is a test\ncool"),
		"when a correct filename is provided, it correctly reads the file");

	p.getPictureFromFile(std::string("notExistingFile.test"));
	tester->test(p.data, std::string("ERROR"),
		"when there is an error, the string is set to ERROR");

	delete tester;
	// PICTURE

	// TOY
	tester = new Tester("Toy");
	Toy		t;

	tester->test(t.getType(), Toy::BASIC_TOY,
		"default constructor set the type to BASIC_TOY");
	tester->test(t.getName(), std::string("toy"),
		"default constructor set the name to toy");
	tester->test(t.getAscii(), std::string(""),
		"default constructor set the ascii to ''");

	Toy 	t2(Toy::ALIEN, std::string("E.T"), std::string("file.test"));

	tester->test(t2.getType(), Toy::ALIEN,
		"constructor set the type correctly");
	tester->test(t2.getName(), std::string("E.T"),
		"constructor set the name correctly");
	tester->test(t2.getAscii(), std::string("this is a test\ncool"),
		"constructor set the ascii correctly");

	t = t2;

	tester->test(t.getType(), t2.getType() ,
		"operator= set the type correctly");
	tester->test(t.getName(), t2.getName(),
		"operator= set the name correctly");
	tester->test(t.getAscii(), t2.getAscii(),
		"operator= set the ascii correctly");

	delete tester;
	// TOY

	// BUZZ + WOODY
	tester = new Tester("Buzz and Woody");

	Buzz 	buzz(std::string("foo"));
	Woody 	woody(std::string("bar"), std::string("file.test"));

	tester->test(buzz.getType(), Toy::BUZZ,
		"Buzz constructor (no file) set the type correctly");
	tester->test(buzz.getName(), std::string("foo"),
		"Buzz constructor (no file) set the name correctly");
	tester->test(buzz.getAscii(), std::string("Buzz !!!"),
		"Buzz constructor (no file) set the ascii correctly");	

	tester->test(woody.getType(), Toy::WOODY,
		"Woody constructor set the type correctly");
	tester->test(woody.getName(), std::string("bar"),
		"Woody constructor set the name correctly");
	tester->test(woody.getAscii(), std::string("this is a test\ncool"),
		"Woody constructor set the ascii correctly");


	tester->warn("The following tests cannot be unit tested, please check by hand");
	t.speak("I cannot unit test this... Does it work ? (toy)");
	buzz.speak("I cannot unit test this... Does it work ? (buzz)");
	woody.speak("I cannot unit test this... Does it work ? (woody)");

	delete tester;
	// BUZZ + WOODY

	// OPERATOR<<
	tester = new Tester("operator<<");

	t << "woohoo";

	tester->test(t.getAscii(), std::string("woohoo"),
		"operator<< with TOY and STRING");

	tester->warn("The following test cannot be unit tested, please check by hand");
	std::cout << t;

	delete tester;
	// OPERATOR<<

	return 0;
}
Esempio n. 24
0
int
dozap(void)
{
	struct obj *obj;
	xchar zx,zy;

	obj = getobj("/", "zap");
	if(!obj) return(0);
	if(obj->spe < 0 || (obj->spe == 0 && rn2(121))) {
		pline("Nothing Happens.");
		return(1);
	}
	if(obj->spe == 0)
		pline("You wrest one more spell from the worn-out wand.");
	if(!(objects[obj->otyp].bits & NODIR) && !getdir(1))
		return(1);	/* make him pay for knowing !NODIR */
	obj->spe--;
	if(objects[obj->otyp].bits & IMMEDIATE) {
		if(u.uswallow)
			bhitm(u.ustuck, obj);
		else if(u.dz) {
			if(u.dz > 0) {
				struct obj *otmp = o_at(u.ux, u.uy);
				if(otmp)
					bhito(otmp, obj);
			}
		} else
			bhit(u.dx,u.dy,rn1(8,6),0,bhitm,bhito,obj);
	} else {
	    switch(obj->otyp){
		case WAN_LIGHT:
			litroom(TRUE);
			break;
		case WAN_SECRET_DOOR_DETECTION:
			if(!findit()) return(1);
			break;
		case WAN_CREATE_MONSTER:
			{ int cnt = 1;
			if(!rn2(23)) cnt += rn2(7) + 1;
			while(cnt--)
			    makemon(NULL, u.ux, u.uy);
			}
			break;
		case WAN_WISHING:
			{ char buf[BUFSZ];
			  struct obj *otmp;
		      if(u.uluck + rn2(5) < 0) {
			pline("Unfortunately, nothing happens.");
			break;
		      }
		      pline("You may wish for an object. What do you want? ");
		      getlin(buf);
		      if(buf[0] == '\033') buf[0] = 0;
		      otmp = readobjnam(buf);
		      otmp = addinv(otmp);
		      prinv(otmp);
		      break;
			}
		case WAN_DIGGING:
			/* Original effect (approximately):
			 * from CORR: dig until we pierce a wall
			 * from ROOM: piece wall and dig until we reach
			 * an ACCESSIBLE place.
			 * Currently: dig for digdepth positions;
			 * also down on request of Lennart Augustsson.
			 */
			{ struct rm *room;
			  int digdepth;
			if(u.uswallow) {
				struct monst *mtmp = u.ustuck;

				pline("You pierce %s's stomach wall!",
					monnam(mtmp));
				mtmp->mhp = 1;	/* almost dead */
				unstuck(mtmp);
				mnexto(mtmp);
				break;
			}
			if(u.dz) {
			    if(u.dz < 0) {
				pline("You loosen a rock from the ceiling.");
				pline("It falls on your head!");
				losehp(1, "falling rock");
				mksobj_at(ROCK, u.ux, u.uy);
				fobj->quan = 1;
				stackobj(fobj);
				if(Invisible) newsym(u.ux, u.uy);
			    } else {
				dighole();
			    }
			    break;
			}
			zx = u.ux+u.dx;
			zy = u.uy+u.dy;
			digdepth = 8 + rn2(18);
			Tmp_at(-1, '*');	/* open call */
			while(--digdepth >= 0) {
				if(!isok(zx,zy)) break;
				room = &levl[zx][zy];
				Tmp_at(zx,zy);
				if(!xdnstair){
					if(zx < 3 || zx > COLNO-3 ||
					    zy < 3 || zy > ROWNO-3)
						break;
					if(room->typ == HWALL ||
					    room->typ == VWALL){
						room->typ = ROOM;
						break;
					}
				} else
				if(room->typ == HWALL || room->typ == VWALL ||
				   room->typ == SDOOR || room->typ == LDOOR){
					room->typ = DOOR;
					digdepth -= 2;
				} else
				if(room->typ == SCORR || !room->typ) {
					room->typ = CORR;
					digdepth--;
				}
				mnewsym(zx,zy);
				zx += u.dx;
				zy += u.dy;
			}
			mnewsym(zx,zy);	/* not always necessary */
			Tmp_at(-1,-1);	/* closing call */
			break;
			}
		default:
			buzz((int) obj->otyp - WAN_MAGIC_MISSILE,
				u.ux, u.uy, u.dx, u.dy);
			break;
		}
	}
	return(1);
}
Esempio n. 25
0
int robot_begin()
{
  int ret = SUCCESS;
  int ivalue = 0;
  
  ret = motor_begin(); 
  if (ret != SUCCESS) return ret;

  Serial.println("Begin Robot Init");
  Serial.println("****************");
  
  lcd.clear();
  lcd.print("Begin Robot Init");
   
  pinMode(Led_Green, OUTPUT);      // set the pin as output
  blink(Led_Green); 
  pinMode(Led_Red, OUTPUT);      // set the pin as output
  blink(Led_Red);  
  pinMode(Led_Blue, OUTPUT);     // set the pin as output
  blink(Led_Blue);
  Serial.println("Init Leds OK");
    
  // initialize the buzzer
  pinMode(buzzPin, OUTPUT); 
  buzz(3);       
  Serial.println("Init Buzzer OK");
   
  // initialize the Tilt&Pan servos  
  TiltPan_begin(HSERVO_Pin, VSERVO_Pin);
  Serial.println("Init Tilt&Pan servos OK");

  // initialize the camera
  Serial.println(" ");
  Serial.println("Begin Init Camera...");
  ret=JPEGCamera.begin();
  if (ret != SUCCESS)
  {  
        Serial.print("Error Init Camera, error: ");
        Serial.println(ret);
        lcd.setCursor(0,1); 
        lcd.print("Init Camera KO  ");
  }        
  else
  {
        Serial.println("Init Camera OK");
        lcd.setCursor(0,1); 
        lcd.print("Init Camera OK  ");
  } 
  delay(5*1000);lcd.clear();    
  
  // initialize the SD-Card    
  ret = initSDCard();
  if (ret != SUCCESS)
  {  
        Serial.print("Error Init SD-Card, error: ");
        Serial.println(ret);
        lcd.print("Init SD-Card KO ");
  }                                                                    
  else
  {
        Serial.println("Init SD-Card OK");
        lcd.print("Init SD-Card OK ");
  }
    
  // get infos from SD-Card  
  ret=infoSDCard();
  if (ret < 0)
  {  
        Serial.print("Error Infos SD-Card, error: ");
        Serial.println(ret);
        lcd.setCursor(0,1); 
        lcd.print("Err Infos SDCard");
  }
  else
  {
        no_picture = ret+1;
        Serial.print("no_picture starts at: ");
        Serial.println(no_picture);
        lcd.setCursor(0,1); 
        lcd.print("Num picture:");lcd.print(no_picture);
  }   
  delay(5*1000);lcd.clear();  
    
    
  // initialize the brightness sensor   
  TEMT6000.TEMT6000_init(TEMT6000_Pin); // initialize the pin connected to the sensor
  Serial.println("Init Brightness sensor OK");
  
  ivalue = TEMT6000.TEMT6000_getLight();
  Serial.print("Value between 0 (dark) and 1023 (bright): ");
  Serial.println(ivalue); 
  lcd.print("Lux:");lcd.print(ivalue);lcd.printByte(lcd_pipe);
  
  // initialize the temperature sensor   
  TMP102.TMP102_init();
  Serial.println("Init Temperature sensor OK");
  
  double temperature = TMP102.TMP102_read();
  ivalue = (int)(100.0 * temperature);
  Serial.print("Temperature: ");
  Serial.println(ivalue); 
  lcd.print("T:");lcd.print(ivalue);lcd.printByte(lcd_celcius);lcd.printByte(lcd_pipe);   
  
  // initialize the electret micro   
  //Micro.Micro_init(MICRO_Pin); // initialize the pin connected to the micro
  //Serial.println("Init Micro OK");

  // initialize the motion sensor
  pinMode(MOTION_PIN, INPUT);
  Serial.println("Init Motion sensor OK");

  // initialize the IOT Serial 1 
  IOTSerial.IOTSbegin(1); // initialize the IOT Serial 1 to communicate with IOT WIFClient ESP8266
  Serial.println ("Init IOT Serial 1 to communicate with IOT WIFClient ESP8266 OK");
  
  // initialize the IOT Serial 2, interrupt setting
  IOTSerial.IOTSbegin(2); // initialize the IOT Serial 2 to communicate with IOT WIFServer ESP8266
  Serial.println ("Init IOT Serial 2 to communicate with IOT WIFServer ESP8266 OK");
  pinMode(IOT_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(IOT_PIN), IntrIOT, RISING);         // set IOT interrupt
 
  interrupts(); // enable all interrupts
  Serial.print("Init Interrupts OK, IntIOT: "); Serial.println(IntIOT);
  
  lcd.setCursor(0,1); 
  lcd.print("End   Robot Init");
  delay(5*1000);lcd.clear();  
 
  Serial.println("End Robot Init");
  Serial.println("**************");
  Serial.println("");
 
  return SUCCESS;
  
} 
Esempio n. 26
0
void TurnOnbeep1(){
	buzz(4, 2500, 2000); // buzz the buzzer on pin 4 at 2500Hz for 100 milliseconds
}
Esempio n. 27
0
/* when attacking "priest" in his temple */
void
ghod_hitsu(struct monst *priest)
{
    int x, y, ax, ay, roomno = (int)temple_occupied(u.urooms);
    struct mkroom *troom;

    if (!roomno || !has_shrine(priest))
        return;

    ax = x = CONST_EPRI(priest)->shrpos.x;
    ay = y = CONST_EPRI(priest)->shrpos.y;
    troom = &level->rooms[roomno - ROOMOFFSET];

    if ((u.ux == x && u.uy == y) || !linedup(u.ux, u.uy, x, y)) {
        if (IS_DOOR(level->locations[u.ux][u.uy].typ)) {

            if (u.ux == troom->lx - 1) {
                x = troom->hx;
                y = u.uy;
            } else if (u.ux == troom->hx + 1) {
                x = troom->lx;
                y = u.uy;
            } else if (u.uy == troom->ly - 1) {
                x = u.ux;
                y = troom->hy;
            } else if (u.uy == troom->hy + 1) {
                x = u.ux;
                y = troom->ly;
            }
        } else {
            switch (rn2(4)) {
            case 0:
                x = u.ux;
                y = troom->ly;
                break;
            case 1:
                x = u.ux;
                y = troom->hy;
                break;
            case 2:
                x = troom->lx;
                y = u.uy;
                break;
            default:
                x = troom->hx;
                y = u.uy;
                break;
            }
        }
        if (!linedup(u.ux, u.uy, x, y))
            return;
    }

    switch (rn2(3)) {
    case 0:
        pline("%s roars in anger:  \"Thou shalt suffer!\"", a_gname_at(ax, ay));
        break;
    case 1:
        pline("%s voice booms:  \"How darest thou harm my servant!\"",
              s_suffix(a_gname_at(ax, ay)));
        break;
    default:
        pline("%s roars:  \"Thou dost profane my shrine!\"",
              a_gname_at(ax, ay));
        break;
    }

    /* bolt of lightning */
    buzz(-10 - (AD_ELEC - 1), 6, x, y, sgn(tbx), sgn(tby), 0);
}
Esempio n. 28
0
void
inrange(struct monst *mtmp)
{
	schar tx,ty;

	/* do nothing if cancelled (but make '1' say something) */
	if(mtmp->data->mlet != '1' && mtmp->mcan)
		return;

	/* spit fire only when both in a room or both in a corridor */
	if(inroom(u.ux,u.uy) != inroom(mtmp->mx,mtmp->my)) return;
	tx = u.ux - mtmp->mx;
	ty = u.uy - mtmp->my;
	if((!tx && abs(ty) < BOLT_LIM) || (!ty && abs(tx) < BOLT_LIM)
	    || (abs(tx) == abs(ty) && abs(tx) < BOLT_LIM)){
	    switch(mtmp->data->mlet) {
	    case 'D':
		/* spit fire in the direction of @ (not nec. hitting) */
		buzz(-1,mtmp->mx,mtmp->my,sgn(tx),sgn(ty));
		break;
	    case '1':
		if(rn2(WIZSHOT)) break;
		/* if you zapped wizard with wand of cancellation,
		he has to shake off the effects before he can throw
		spells successfully.  1/2 the time they fail anyway */
		if(mtmp->mcan || rn2(2)) {
		    if(canseemon(mtmp))
			pline("%s makes a gesture, then curses.",
			    Monnam(mtmp));
		    else
			pline("You hear mumbled cursing.");
		    if(!rn2(3)) {
			mtmp->mspeed = 0;
			mtmp->minvis = 0;
		    }
		    if(!rn2(3))
			mtmp->mcan = 0;
		} else {
		    if(canseemon(mtmp)){
			if(!rn2(6) && !Invis) {
			    pline("%s hypnotizes you.", Monnam(mtmp));
			    nomul(rn2(3) + 3);
			    break;
			} else
			    pline("%s chants an incantation.",
				Monnam(mtmp));
		    } else
			    pline("You hear a mumbled incantation.");
		    switch(rn2(Invis ? 5 : 6)) {
		    case 0:
			/* create a nasty monster from a deep level */
			/* (for the moment, 'nasty' is not implemented) */
			(void) makemon((struct permonst *)0, u.ux, u.uy);
			break;
		    case 1:
			pline("\"Destroy the thief, my pets!\"");
			aggravate();	/* aggravate all the monsters */
			/* fall into next case */
		    case 2:
			if (flags.no_of_wizards == 1 && rnd(5) == 0)
			    /* if only 1 wizard, clone himself */
			    clonewiz(mtmp);
			break;
		    case 3:
			if(mtmp->mspeed == MSLOW)
				mtmp->mspeed = 0;
			else
				mtmp->mspeed = MFAST;
			break;
		    case 4:
			mtmp->minvis = 1;
			break;
		    case 5:
			/* Only if not Invisible */
			pline("You hear a clap of thunder!");
			/* shoot a bolt of fire or cold, or a sleep ray */
			buzz(-rnd(3),mtmp->mx,mtmp->my,sgn(tx),sgn(ty));
			break;
		    }
		}
	    }
	    if(u.uhp < 1) done_in_by(mtmp);
	}
}
Esempio n. 29
0
int robot_command (uint16_t *cmd, uint16_t *resp, uint8_t *resplen)
{    
 unsigned long start = 0;
 uint8_t infolen = 0;
 int checkdir;
 int motor_state_save;
 int error = -1;
 int ret = SUCCESS;
 
 lcd.clear();     // clear LCD
 reset_leds();    // turn off all leds
 digitalWrite(Led_Blue, HIGH);  // turn on led blue
 
 switch (cmd[0]) {
 
 case CMD_STOP:
     Serial.println("CMD_STOP");
     lcd.print("STOP"); 
     
     stop();
     motor_state = STATE_STOP;
     *resplen = 0;
     break; 
  
 case CMD_START:
     if (cmd[1] == 0)
     {  
           Serial.println("CMD_START");
           lcd.print("START"); 
           
           start_forward();
     }
     else
     {       
           Serial.print("CMD_START_TEST motor: "); Serial.println((int)cmd[1]);
           lcd.print("START motor: "); lcd.print((int)cmd[1]); 
           
           start_forward_test(cmd[1]);           
     }                      
     motor_state = STATE_GO;
     *resplen = 0;
     break; 
 
 case CMD_CHECK_AROUND:
     Serial.println("CMD_CHECK_AROUND");
     lcd.print("CHECK AROUND");
    
     checkdir = check_around();
     
     lcd.setCursor(0,1); 
     if      (checkdir == DIRECTION_LEFT)  lcd.print("LEFT");
     else if (checkdir == DIRECTION_RIGHT) lcd.print("RIGHT");
     else if (checkdir == OBSTACLE_LEFT)   lcd.print("OBSTACLE LEFT");
     else if (checkdir == OBSTACLE_RIGHT)  lcd.print("OBSTACLE RIGHT");
     else if (checkdir == OBSTACLE)        lcd.print("OBSTACLE");
     else                                  lcd.print("?");

     resp[0] = checkdir;
     *resplen = 0+1;
     break;
     
 case CMD_MOVE_TILT_PAN:    
     Serial.print("CMD_MOVE_TILT_PAN: "); Serial.print((int)cmd[1]);Serial.print((int)cmd[2]);Serial.print((int)cmd[3]);Serial.println((int)cmd[4]);    
     if (cmd[2] == 0) HPos = (int)cmd[1] + 90; else HPos = 90 - (int)cmd[1]; 
     if (cmd[4] == 0) VPos = (int)cmd[3] + 90; else VPos = 90 - (int)cmd[3]; 
     Serial.print("CMD_MOVE_TILT_PAN, HPos VPos: "); Serial.print(HPos);Serial.println(VPos);   
     lcd.print("MOVE TILT&PAN");
     lcd.setCursor(0,1); 
     lcd.print("X: ");
     lcd.print(HPos);
     lcd.print(" Y: ");
     lcd.print(VPos);
     
     TiltPan_move(HPos, VPos);
    
     *resplen = 0;
     break; 
                    
 case CMD_TURN:
       if (cmd[1] == 180)
     {       
           Serial.print("CMD_TURN_BACK");
           lcd.print("TURN BACK ");  
         
           ret = turnback (10);  // 10s max
           if (ret != SUCCESS){
           	  Serial.print("turnback error"); Serial.println(ret);
           	  lcd.setCursor(0,1); 
           	  lcd.print("turnback error: "); lcd.print(ret);
           	  error = 1;
           }
     }       
     else if (motor_state == STATE_GO)
     { 
           Serial.print("CMD_TURN, alpha: "); Serial.print((cmd[2] != 1) ? ('+'):('-')); Serial.println((int)cmd[1]); 
           lcd.print("TURN"); lcd.print((cmd[2] != 1) ? ('+'):('-')); lcd.print((int)cmd[1]);lcd.print((char)223); //degree   
         
           ret = turn ((double)((cmd[2] != 1) ? (cmd[1]):(-cmd[1])), 5);  // 5s max        
           if (ret != SUCCESS){
           	  Serial.print("turn error"); Serial.println(ret);
           	  lcd.setCursor(0,1); 
           	  lcd.print(" turn error: "); lcd.print(ret);
           	  error = 1;
           }           
    }
    
    *resplen = 0;
    break;        
     
     
 case CMD_INFOS: 
     Serial.println("CMD_INFOS");

     ret = infos (resp, &infolen);
       
     if (resp[MOTOR_STATE] == STATE_GO) {
         lcd.print("RUNING");
     }    
     else
     {
         lcd.print("STOPPED");
     }
     lcd.setCursor(0,1);   
     lcd.print((int)resp[TEMPERATURE]); lcd.print((byte)lcd_celcius);lcd.write(lcd_pipe);   
     lcd.print((int)resp[DISTANCE]); lcd.print("cm");lcd.write(lcd_pipe); 
     lcd.print((int)resp[DIRECTION]); lcd.print((char)223); //degree    
 
     *resplen = infolen;
     break;
      
 case CMD_PICTURE: 
     Serial.print("CMD_PICTURE, no_picture: ");
     no_picture++;
     Serial.println(no_picture);
     lcd.print("PICTURE ");
     
     motor_state_save = motor_state;
     if (motor_state == STATE_GO) {
        Serial.println("Stop"); 
        stop();
        motor_state = STATE_STOP;
      }
   
     ret = JPEGCamera.makePicture (no_picture);
     if (ret == SUCCESS)
     { 
        lcd.setCursor(0,1);
        lcd.print("picture: "); lcd.print(no_picture);
     }
     else
     {
        Serial.print("makePicture error: "); Serial.println(ret);
        lcd.setCursor(0,1); 
        lcd.print("error: "); lcd.print(ret);       
        error = 1;
     }
       
     if (motor_state_save == STATE_GO) {          
        Serial.println("Start");
        start_forward();                     
        motor_state = STATE_GO;
     }
        
     // byte 0: picture number
     resp[0] = no_picture;
     *resplen = 0+1;    
     break;

 case CMD_ALERT: 
     Serial.println("CMD_ALERT");
     lcd.print("Alert"); 
    
     blink(Led_Blue);  
     buzz(5); 
     
     // If motor_state == STATE_GO => Stop           
     if (motor_state == STATE_GO) {
        Serial.println("Stop"); 
        stop();
        motor_state = STATE_STOP;
     }
   
     // Make 3 pictures left, front and right
     if ((HPos != 90) || (VPos !=90))
     { 
        HPos = 90;
        VPos = 90;
        TiltPan_move(HPos, VPos);
     }
     
     Serial.print("makePicture, no_picture: ");
     no_picture++;
     Serial.println(no_picture);
     lcd.print("PICTURE ");
     
     ret = JPEGCamera.makePicture (no_picture);
     if (ret == SUCCESS)
     { 
        lcd.setCursor(0,1);
        lcd.print("picture: "); lcd.print(no_picture);
     }
     else
     {
        Serial.print("makePicture error: "); Serial.println(ret);
        lcd.setCursor(0,1); 
        lcd.print("error: "); lcd.print(ret);       
        error = 1;
     }
             
     if (ret == SUCCESS)
     { 
        HPos = 0;
        VPos = 90;
        TiltPan_move(HPos, VPos);

        Serial.print("makePicture, no_picture: ");
        no_picture++;
        Serial.println(no_picture);
        lcd.print("PICTURE ");
        
        ret = JPEGCamera.makePicture (no_picture);

        lcd.setCursor(0,1);
        lcd.print("picture: "); lcd.print(no_picture);
     }
     else
     {
        Serial.print("makePicture error: "); Serial.println(ret);
        lcd.setCursor(0,1); 
        lcd.print("error: "); lcd.print(ret);       
        error = 1;
     }
      
     if (ret == SUCCESS)
     { 
        HPos = 180;
        VPos = 90;
        TiltPan_move(HPos, VPos);
     
        Serial.print("makePicture, no_picture: ");
        no_picture++;
        Serial.println(no_picture);
        lcd.print("PICTURE ");
        
        ret = JPEGCamera.makePicture (no_picture);

        lcd.setCursor(0,1);
        lcd.print("picture: "); lcd.print(no_picture);
     }
     else
     {
        Serial.print("makePicture error: "); Serial.println(ret);
        lcd.setCursor(0,1); 
        lcd.print("error: "); lcd.print(ret);       
        error = 1;
     }

     // byte 0: last picture number
     resp[0] = no_picture;
     *resplen = 0+1;
          
     HPos = 90;
     VPos = 90;
     TiltPan_move(HPos, VPos);
              
     break; 
     
 case CMD_CHECK: 
     Serial.println("CMD_CHECK");
     lcd.print("Check"); 
        
     alert_status = check();
     
     if (alert_status != SUCCESS) {
           Serial.print("Alert detected: ");Serial.println(alert_status);
           lcd.setCursor(0,1); 
           lcd.print("Alert: "); lcd.print(alert_status);                
     }
     else
     {
           Serial.print("No alert detected: ");
           lcd.setCursor(0,1); 
           lcd.print(" No Alert");               
     } 
  
     // byte 0: alert
     resp[0] = alert_status;
     *resplen = 0+1;
     break; 
  
 case CMD_GO: 
     Serial.print("CMD_GO, nb seconds: "); Serial.print((int)cmd[1]);
     lcd.print("GO ");lcd.print((int)cmd[1]);lcd.print("secs");
     
     if (motor_state != STATE_GO)
     {  
           Serial.println("start_forward");
           start_forward();
           motor_state = STATE_GO;
     }
     
     error = -1;
     GOtimeout = (unsigned long)cmd[1];
     start = millis();
     while((millis() - start < GOtimeout*1000) && (error == -1)) {
          ret = go(GOtimeout);  
     
          if ((ret != SUCCESS) && (ret != OBSTACLE) && (ret != OBSTACLE_LEFT) && (ret != OBSTACLE_RIGHT))
          {
              stop();
              motor_state = STATE_STOP;
     	      error = 1;
     	                   
              Serial.print("CMD_GO error: "); Serial.println(ret);
              Serial.println("Stop");              
              lcd.setCursor(0,1); 
              lcd.print("error: "); lcd.print(ret);                

          }
          else if ((ret == OBSTACLE) || (ret == OBSTACLE_LEFT) || (ret == OBSTACLE_RIGHT))
          {
              stop();
              motor_state = STATE_STOP;
              
              buzz(3);
              blink(Led_Red);     
              Serial.print("CMD_GO Obstacle: ");Serial.println(ret);
              Serial.println("Stop");
              lcd.setCursor(0,1); 
              if (ret == OBSTACLE_LEFT)        lcd.print("OBSTACLE LEFT");
              else if (ret == OBSTACLE_RIGHT)  lcd.print("OBSTACLE RIGHT");
              else if (ret == OBSTACLE)        lcd.print("OBSTACLE");
              else 

                              
              ret = SUCCESS;            
              checkdir = check_around();
         
              Serial.print("check_around, direction: "); Serial.println(checkdir);
              lcd.clear();
              lcd.print("check around");
              lcd.setCursor(0,1); 
              if      (checkdir == DIRECTION_LEFT)  lcd.print("LEFT");
              else if (checkdir == DIRECTION_RIGHT) lcd.print("RIGHT");
              else if (checkdir == OBSTACLE_LEFT)   lcd.print("OBSTACLE LEFT");
              else if (checkdir == OBSTACLE_RIGHT)  lcd.print("OBSTACLE RIGHT");
              else if (checkdir == OBSTACLE)        lcd.print("OBSTACLE");
              else                             lcd.print("?");;
         
              if (checkdir == DIRECTION_LEFT) {
                   start_forward();
                   motor_state = STATE_GO;
                   ret = turn (-45,  5); // turn  -45 degrees during 5s max
                   if (ret != SUCCESS)
                   {
                      stop();
                      motor_state = STATE_STOP;                   	  
                   	  error = 1;
                   	                     	  
                   	  Serial.print("turn error: "); Serial.println(ret);
                      Serial.println("Stop");                                         	  
                   	  lcd.clear();                   	  
                   	  lcd.print("turn left");
                   	  lcd.setCursor(0,1);
                   	  lcd.print("error: "); lcd.print(ret); 
                   }
                   else
                   {
                      lcd.clear();                   	  
                   	  lcd.print("turn left OK");                  	
                   }
              }
              else if (checkdir == DIRECTION_RIGHT) {
                   start_forward();
                   motor_state = STATE_GO;
                   ret = turn (+45,  5); // turn  +45 degrees during 5s max
                   if (ret != SUCCESS)
                   {
                   	  stop();
                      motor_state = STATE_STOP;  
                   	  error = 1;
                   	                     	 
                   	  Serial.print("turn error: "); Serial.println(ret);
                   	  Serial.println("Stop"); 
                   	  lcd.clear();                   	  
                   	  lcd.print("turn right");
                   	  lcd.setCursor(0,1);
                   	  lcd.print("error: "); lcd.print(ret); 
                   }
                   else
                   {
                      lcd.clear();                   	  
                   	  lcd.print("turn right OK");                  	
                   }                  
              }
              else 
              {
              	   buzz(3);
                   blink(Led_Red);
              	   motor_state = STATE_GO;
              	   ret = turnback (10); // turn back during 10s max
                   if (ret != SUCCESS)
                   {
                      stop();
                      motor_state = STATE_STOP;
                      error = 1; 
                      
                      Serial.print("turnback error"); Serial.println(ret);
                   	  Serial.println("Stop");
                   	  lcd.clear();                   	  
                   	  lcd.print("turnback");
                   	  lcd.setCursor(0,1);
                   	  lcd.print("error: "); lcd.print(ret);                    	                                           	  
                   }
                   else
                   {
                      lcd.clear();                   	  
                   	  lcd.print("turnback OK");                  	
                   }                   
              }                 
          }
          else
          {
              	   Serial.println("GO OK");
              	   lcd.clear();                   	  
                   lcd.print("GO OK");
                   error = 0;
          }           
     } // end while
     
     ret = infos (resp, &infolen);
              
     if (error == 0) {
         if (resp[MOTOR_STATE] == STATE_GO) {
            lcd.print("RUNNING");
          }    
         else
         {
             lcd.print("STOPPED");
         }
         lcd.setCursor(0,1);   
         lcd.print((int)resp[TEMPERATURE]); lcd.print((byte)lcd_celcius);lcd.write(lcd_pipe);   
         lcd.print((int)resp[DISTANCE]); lcd.print("cm");lcd.write(lcd_pipe);
         lcd.print((int)resp[DIRECTION]); lcd.print((char)223); //degree   
     } 
     
     *resplen = infolen;      
     break;
 
 case CMD_PI: 
     Serial.print("CMD_PI activated, type: "); Serial.print((int)cmd[1]);  Serial.print(" - freq: ");Serial.println((int)cmd[2]);
     lcd.print("PI activated ");lcd.print((int)cmd[1]);
 
     PI_activated = (int)cmd[1];
     if (PI_activated <> PI_NO_COMM) PI_freqInfos = (int)cmd[2]* 1000;
        
     Serial.print("PI_activated: "); Serial.println(PI_activated);
     Serial.print("PI_freqInfos: ");Serial.println(PI_freqInfos);
  
     
    *resplen = 0;     
     break;
          
 default:
    Serial.println("invalid command");
    lcd.print("invalid command");
    
    *resplen = 0;      
    break;                     
 
 } //end switch
    
    
 if (error == 1) {
    blink(Led_Red);
    blink(Led_Red);
    buzz(7);
    *resplen = 0; 
 }
                        
 reset_leds();    // turn off all leds
 return ret;
}
Esempio n. 30
0
/**
  * @brief  Task which handles all UI including keypad, LCD and all user power outputs.
	* 				Responds to events caused by other tasks and ISRs
  * @param  None
  * @retval Should never exit
  */
__task void ui (void)
{
	uint16_t event_flag = 0;
	uint8_t key;
	int i;
	uint64_t entry_code = 0;
	
	lcd_init();
	keypad_init();
	
	lcd_backlight(1);
	
	buzzer_init();
	
	pwr_sw_init();
	
	usb_outputs_init();
	dc_outputs_init();

	
	lcd_clear();
	lcd_write_string("    e.quinox    ");
	lcd_goto_XY(0,1);
	lcd_write_string("    izuba.box   ");
	

	//2 second timeout
	os_dly_wait(200);
	
	if ( get_unlock_days () >= 0 )
	{
		ui_state = STATE_NORM;
	}
	
	if( local_ee_data.lvdc_flag == 1 )
	{
		ui_state = STATE_LVDC;
	}
	
	reset_display();
	reset_outputs();
	
	while(1)
	{
		//Wait for any task event or timeout after 1 second
		if ( os_evt_wait_or(0xFFFF, 100) == OS_R_EVT )
		{
			//Find which event 
			event_flag = os_evt_get();
			
			if ( event_flag & UI_BOX_SETUP )
			{
				ui_state = STATE_SETUP;
				lcd_clear();
				reset_display();
				reset_outputs();
			}
			
			if ( (event_flag & UI_LVDC) )
			{
				if ( (ui_state != STATE_LVDC) && (ui_state != STATE_OFF) )
				{
					ui_state = STATE_LVDC;
					local_ee_data.lvdc_flag = 1;
					update_lvdc(1);
					//Turn off outputs
					reset_outputs();
					lcd_power(1);
					lcd_clear();
					lcd_write_string_XY(0, 0, "  Battery Empty ");
					lcd_write_string_XY(0, 1, "  Turning Off   ");

					//Delay and Buzz
					//20 Seconds
					for ( i = 0; i < 5; i++)
					{
						buzz(1);
						//4 second wait
						os_dly_wait(400);
					}
					
					//Turn off Screen
					lcd_power(0);
					
				}
				
			}
			
			if ( event_flag & UI_PWR_SW )
			{
				if ( ui_state != STATE_OFF)
				{
					//Turn off all outputs and UI devices
					//Wait only for UI_PWR_SW tasks
					lcd_power(0);
								
					ui_state = STATE_OFF;
					reset_outputs();
				}
				else
				{
					//Re-init LCD
					lcd_clear();
					lcd_power(1);
					
					check_display_debug();
					
					lcd_splash_screen(2);
					
					if(get_soc() >= CHARGED)
					{
						local_ee_data.lvdc_flag = 0;
						update_lvdc(0);
					}

					if(local_ee_data.lvdc_flag == 1)
					{
						ui_state = STATE_LVDC;
					}
					
					if(ui_state != STATE_LVDC)
					{
						if (get_unlock_days () >= 0 )
							ui_state = STATE_NORM;
						else
							ui_state = STATE_AWAIT_PAYMENT;
					}
					
					reset_outputs();
					reset_display();
				}
				
				//1 second delay
				os_dly_wait(100);
				EXTI_ClearITPendingBit(EXTI_Line0);
			}
			
			if ( event_flag & UI_EVT_USB_OC )
			{
				os_dly_wait(100);
                           
				if(EXTI_GetITStatus(EXTI_Line5) != RESET || EXTI_GetITStatus(EXTI_Line6) != RESET)
				{

					if(EXTI_GetITStatus(EXTI_Line5) != RESET)
						USB1_DISABLE();

					if(EXTI_GetITStatus(EXTI_Line6) != RESET)
						USB2_DISABLE();

					lcd_clear();
					lcd_write_string_XY(0, 0, "       USB      ");
					lcd_write_string_XY(0, 1, "      error!    ");
					//2s wait
					os_dly_wait(200);
					reset_display();
				}
			}

		
			if ( event_flag & (UI_EVT_KEYPAD_1 | UI_EVT_KEYPAD_2 | UI_EVT_KEYPAD_3) )
			{
				if ( (ui_state == STATE_AWAIT_PAYMENT) || (ui_state == STATE_NORM) || (ui_state == STATE_SETUP) )
				{
					//Read which key is pressed
					i = 0;
					do
					{
						key = keypad_get_key();		
						i++;
						os_dly_wait(1);
						if ( i > 20)
							break;
					} while (key == KEY_NONE);
					
					if (key != KEY_NONE)
					{					
						lcd_backlight(1);
						buzz(1);
					}
					
					if (ui_state == STATE_SETUP)
					{
						//If 5 digits and tick then set box_id
						if (key == KEY_CROSS) {
							//'X' Pressed
							//LCDWriteString("x");
							display_str[0] = '\0';
							digit_count = 0;
							local_ee_data.box_id = 0;
							reset_display();
						} else if (key == KEY_NONE) {
							//Do nothing
						} else if ( key == KEY_TICK ) {
							if(digit_count == 5){
								os_dly_wait(50);
								
								//Send message to payment control task
								os_evt_set(PC_SET_BOX_ID, payment_control_t);
								
								ui_state = STATE_AWAIT_PAYMENT;
								display_str[0] = '\0';
								digit_count = 0;
								reset_display();
								reset_outputs();
							}
							}else{
								if(digit_count <5){
									//Add the keypad value to the box id
									display_str[0] = '\0';
									local_ee_data.box_id = (local_ee_data.box_id * 10) + key;
									utoa_b(display_str, local_ee_data.box_id, 10, digit_count);
									lcd_write_string_XY(7, 0, display_str);
									lcd_goto_XY((8 + digit_count), 0);
									reset_display();
								}
								else { // do nothing
								}
								digit_count++;
						}
					}
					else if (ui_state == STATE_AWAIT_PAYMENT)
					{
						if (key == KEY_CROSS) {
							//'X' Pressed
							//LCDWriteString("x");
							display_str[0] = '\0';
							digit_count = 0;
							entry_code = 0;
							lcd_write_string_XY(6, 0, "__________");
							lcd_goto_XY(6, 0);
							//key = KEY_NONE;
							
						} else if (key == KEY_TICK) {
							//Tick Pressed
							//LCDWriteString("./");
						} else if (key == KEY_NONE) {
							//Tick Pressed
							//LCDWriteString("./");
						} else {
							//Add the keypad to the entry code
							entry_code = (entry_code * 10) + key;
							
							//Make the 
							display_str[0] = '\0';
							utoa_b(display_str, entry_code, 10, digit_count);
							lcd_write_string_XY(6, 0, display_str);
							lcd_goto_XY((7 + digit_count), 0);

							if (digit_count++ == 9) {
								os_dly_wait(50);
								
								//Send code to payment control task
								// but send (uint32_t)entry_code							
								if ( check_unlock_code((uint32_t)entry_code))
								{
									TRACE_INFO("2,1,%s\n", display_str);
									ui_state = STATE_NORM;
									// Edited Code
									lcd_clear();
									lcd_write_string_XY(0, 0, "      Valid      ");
									lcd_write_string_XY(0, 1, "      code!    ");
									entry_code = 0;
									digit_count = 0;
									display_str[0] = '\0';
									//2s wait
									os_dly_wait(200);
									// End of Edit
									reset_display();
									reset_outputs();
								}
								else
								{							
									TRACE_INFO("2,0,%s\n", display_str);
									// Edited Code
									lcd_clear();
									lcd_write_string_XY(0, 0, "      Wrong      ");
									lcd_write_string_XY(0, 1, "      code!    ");
									//2s wait
									os_dly_wait(200);
									// End of Edit
									
									entry_code = 0;
									digit_count = 0;
									display_str[0] = '\0';
									reset_display();
									reset_outputs();
								}
							}
						}
					}
					else
					{											
						switch (key)
						{
							case KEY_NONE:
								//No Action
								break;
							//Special Key Cases
							case KEY_TICK:
								TRACE_DEBUG("Key: ./ \n");
								break;
							case KEY_CROSS:
								TRACE_DEBUG("Key: X \n");
								break;
							default:
								//Print the key number
								TRACE_DEBUG("Key: %i \n", key);			
						}
					}
					
					//Wait for release of key (with time-out)
					i = 0;
					while( keypad_get_key() != KEY_NONE )
					{
						i++;
						os_dly_wait(1);
						if ( i > 20)
							break;
					}			
				}					
			}
			
			if(local_ee_data.lvdc_flag == 0)
			{
				if ( event_flag & UI_PAYMENT_INVALID )
				{
					ui_state = STATE_AWAIT_PAYMENT;
					lcd_clear();
					reset_display();
					reset_outputs();
				}
			}
			
			if(local_ee_data.lvdc_flag == 1)
			{
				lcd_clear();
				lcd_write_string_XY(0, 0, "  Battery Low   ");
				lcd_batt_level( get_soc(), get_charging_rate() );
				
				if(get_soc() >= CHARGED)
				{
					local_ee_data.lvdc_flag = 0;
					update_lvdc(0);
				}
			}
			//clear event flags
			os_evt_clr(event_flag, ui_t);
			
		}
		
		/* Debugging Info on LCD
	  sprintf(str, "P=%.2f", get_adc_voltage(ADC_SOL_V)*get_adc_voltage(ADC_SOL_I));
 		lcd_goto_XY(0,0);
 		lcd_write_string(str);
 		
 		str[0] = NULL;
 		
 		sprintf(str, "T=%.2f", get_adc_voltage(ADC_TEMP));
 		lcd_goto_XY(8,0);
 		lcd_write_string(str);
 		
 		str[0] = NULL;
 		
 		sprintf(str, "V=%.2f", get_adc_voltage(ADC_BATT_V));
 		lcd_goto_XY(0,1);
 		lcd_write_string(str);
		
 		str[0] = NULL;
 		
 		sprintf(str, "I=%.2f", get_adc_voltage(ADC_BATT_I));
 		lcd_goto_XY(8,1);
 		lcd_write_string(str);
 		
 		str[0] = NULL;
*/
		//Update battery levels, days remaining and if normal state then time/date
		
		if(local_ee_data.lvdc_flag == 1)
		{
			lcd_write_string_XY(0, 0, "  Battery Low   ");
			lcd_batt_level( get_soc(), get_charging_rate() );
				
			if(get_soc() >= CHARGED)
			{
				local_ee_data.lvdc_flag = 0;
				update_lvdc(0);
				
				if(get_unlock_days () >= 0 )
				{
					ui_state = STATE_NORM;
				}
				else
				{
					ui_state = STATE_AWAIT_PAYMENT;
				}
				
				reset_display();
				reset_outputs();
				
			}
		}
		
		if ( (ui_state == STATE_NORM) || (ui_state == STATE_AWAIT_PAYMENT) )
		{
			lcd_batt_level( get_soc(), get_charging_rate() );
		}
		
		if (ui_state == STATE_NORM)
		{
			//Update remaining days
			if(local_ee_data.full_unlock == EE_FULL_UNLOCK_CODE){
				lcd_write_string_XY(0, 1, "        Unlocked");
				lcd_batt_level( get_soc(), get_charging_rate() );
			}
			else{
				lcd_write_string_XY(0, 1, "            days");
				lcd_write_int_XY(10, 1, get_unlock_days() );
				lcd_batt_level( get_soc(), get_charging_rate() );
			}			
		}

	}
}