blinking LED's without a delay not working - arduino-uno

I have a problem with my arduino project. It's supposed to have two modes: normal and hazard. The switching between those two is handles by a visual studio form. The blinking leds for the normal mode work just fine but when I tried switching to the hazard mode they blink very dimly. In the hazard mode the red, yellow and blue leds have to blink at the same time. My code makes it so that only the red led is working properly. I'm guessing it has something to do with me using the other two in the normal mode.
void loop() {
unsigned long currentMillisYellow = millis();
unsigned long currentMillisBlue = millis();
unsigned long currentMillisRed = millis();
unsigned long currentMillisGreen = millis();
int steerAngle = map(analogRead(Potentiometer), 0, 1024, -100, 100);
//..........................................................normal state blinking
if (rightCounter > 0 && steerAngle > 0 && state == NormalState) {
if (currentMillisBlue - previousMillisBlue > blinkIntervalBlue) {
previousMillisBlue = currentMillisBlue;
ledBlueState = !ledBlueState;
digitalWrite(ledBlue, ledBlueState);
}
} else {
rightCounter = 0;
digitalWrite(ledBlue, LOW);
}
if (leftCounter > 0 && steerAngle < 0 && state == NormalState) {
if (currentMillisYellow - previousMillisYellow > blinkIntervalYellow) {
previousMillisYellow = currentMillisYellow;
ledYellowState = !ledYellowState;
digitalWrite(ledYellow, ledYellowState);
}
} else {
leftCounter = 0;
digitalWrite(ledYellow, LOW);
}
//..........................................................hazard state blinking
if (state == HazardState) { //why is the led brightness so low? (needs to be fixed)
if (currentMillisYellow - previousMillisYellow > blinkIntervalYellow) {
previousMillisYellow = currentMillisYellow;
ledYellowState = !ledYellowState;
digitalWrite(ledYellow, ledYellowState);
}
}
if (state == HazardState) {
if (currentMillisBlue - previousMillisBlue > blinkIntervalBlue) {
previousMillisBlue = currentMillisBlue;
ledBlueState = !ledBlueState;
digitalWrite(ledBlue, ledBlueState);
}
}
if (state == HazardState) {
if (currentMillisRed - previousMillisRed > blinkIntervalRed) {
previousMillisRed = currentMillisRed;
ledRedState = !ledRedState;
digitalWrite(ledRed, ledRedState);
}
}

Are your blinkIntervals long enough to produce an adequate delay so that the LED can be seen properly blinking? As I understand you are trying to blink them, namely turn them on then off for a short period. In that case, you might prefer to define ON and OFF intervals, as done in the second example code from this tutorial.
Additionally, as #Juraj said, your else block is turning them off and that could be the reason why you see the dim flashing.
I would define states instead of comparing the state inside the if conditional. Something like:
typedef enum {
NORMAL,
HAZARD
} Modes;
Modes state = NORMAL;
then, in your main loop:
if( state == NORMAL){
// execute LEDs blinking
} else if(state == HAZARD){
// execute LEDs blinking
}

Related

I want to create an object at a position where there is nothing, but there is something wrong

I'm making a game in Unity2D where are 4 roads that tanks drive on, tanks spawn in random positions, I want to make sure that a tank can't spawn in a position that another tank is already in. When I start the game the Unity Editor crashes I think there is a problem somewhere in the do while loop but I haven't found it, hoping I described it right.
Thanks.
{
public GameObject tank;
public float spawnTime = 1f;
float positionX;
float positionY;
private bool check;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("TankSpawn", 1f, spawnTime);
}
void TankSpawn()
{
do
{
int rndY = Random.Range(1, 5);
float rndX = Random.Range(20.5f, 35.0f);
if (rndY == 1)
{
positionY = -3.5f;
positionX = rndX;
}
else if (rndY == 2)
{
positionY = 0.5f;
positionX = rndX;
}
else if (rndY == 3)
{
positionY = 4.5f;
positionX = rndX;
}
else if (rndY == 4)
{
positionY = 8.5f;
positionX = rndX;
}
GameObject[] tanks = GameObject.FindGameObjectsWithTag("tank");
foreach (GameObject tank in tanks)
{
if (tank.transform.position.x == positionX && tank.transform.position.y == positionY)
{
check = false;
}
else
{
check = true;
}
}
} while (check != true);
Instantiate(tank, new Vector2(positionX, positionY), transform.rotation);
}
}```
Firstly the problem that is doing you in:
By default bool variables. like check, are false. The while loops when check is false. The only way for check to be set to true is thru the forloop if the generated coordinates don't match any tank positions. The problem with that is that if there are no tanks in the scene the forloop is never even started meaning that there is no way for check to become true, ergo your while loop keeps looping and hangs up your editor.
A quick solution would be to check the length of found tanks array and if it is zero set check to true.
if (tanks.Length == 0)
{
check = true;
}
Sidenotes:
There is name ambiguity between the tank in the forloop and the tank in the prefab. Its good practice to avoid that.
It is extremely hard to match two float values with == due to rounding. They might be extremely close, but are still different.
With your method tanks will still overlap. I would recommend to check if a position is truly free, by using Physics2D.OverlapBox or Physics2D.OverlapCircle
If a lot of tanks spawn there might not be any valid positions. You should think of a way to timeout or impose some other limit, else you'll get softlocked in the while loop again.

p5.play counter not working

I'm trying to write a program in which the end screen of the game only shows up after the last animation finishes. I'm using a counter that's implemented after each object is removed (which is only after it finishes its animation), and when that counter gets to zero, it should show the end screen. Unfortunately, from what I can tell, the counter statement isn't registering at all. I've inserted a print statement that isn't functioning.
var star;
var score;
var counter;
function setup() {
createCanvas(600,400);
score = 0;
counter = 20;
for (var s = 0; s < 20; s++) {
star = createSprite(random(width), random(height));
star.addAnimation("idle", idleAnim);
star.addAnimation("explode", explAnim);
star.changeAnimation("idle");
star.onMousePressed = function() {
this.changeAnimation("explode");
this.animation.looping = false;
score +=1
if (this.getAnimationLabel() == "explode" && this.animation.getFrame() == this.animation.getLastFrame()) {
this.remove();
counter -= 1;
print(counter);
}
}
}
}
function draw() {
if (score == 20 && counter == 0) {
background(255,222,51)
textSize(90);
fill(0)
text("YOU WIN!",95,225)
} else {
drawSprites();
}
}
You need to take a step back and debug your program. For example, are you sure the star.onMousePressed() function is firing? Are you sure the if statement is working the way you expected? Are you sure the player.dir() function is being called?
It sounds like your if statement is not being entered. can you find out the value of everything on that line? Which thing has a different value from what you expected?
Use console.log() statements, or use the JavaScript debugger, to answer all of the above. Figure out exactly which line of code is behaving differently from what you expected, and then isolate that problem in a MCVE. Good luck.

Joystick won't work using SDL

I'm building a simple game in SDL. I've been through countless tutorials and I've clearly missed something as it still ignoring my Joystick completely
In my constructor
SDL_JoystickEventState(SDL_ENABLE);
joystick = SDL_JoystickOpen(0);
In my update I'm calling a test to check I have actually initialized the joystick
if (SDL_NumJoysticks() <= 0)
{
done = true;
}
Here is my player update as well
void World::playerMovement()
{
SDL_Event event;
while (SDL_PollEvent (&event))
{
switch (event.type)
{
case SDL_QUIT:
done = true;
break;
case SDL_JOYAXISMOTION:
if ( ( event.jaxis.value < -3200 ) || (event.jaxis.value > 3200 ) )
{
test = true;
}
break;
}
}
}
Test is simply a bool which once true will mean my enemies start spawning. I also run a check in main
if (SDL_Init( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0)
{
fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
done = true;
}
When I run the game it loads as normal but no matter how much I move the joystick it won't set test to true.
I also tried using the following in the while poll event loop instead.
if (event.type == SDL_JOYAXISMOTION)
{
if(SDL_JoystickGetAxis(joystick, 1) > 0)
{
test = true;
}
}
Any idea's what I have missed?
I think emartel has the best answer to make sure SDL_joystick is working.
When does World::playerMovement() happen? The overall flow of your program is hard to determine from these snippets.
I'm happy to share with you my code for handling joysticks, which keeps track of: multiple joysticks, axes scaled [-1,1] with deadzone removed, and buttons held down.
http://www.raptor007.com/code/RaptorEngine_Joystick.zip
And here's a snippet of how that would be utilized as part of your main loop:
// FIXME: SDL needs to be initialized before we get here.
JoystickManager Joy;
Joy.Initialize();
double deadzone = 0.02;
// Main loop.
bool done = false;
while( ! done )
{
// Keep the list of joysticks up-to-date.
Joy.FindJoysticks();
// Handle all user input.
SDL_Event event;
while( SDL_PollEvent( &event ) )
{
// Let the JoystickManager track events relevant to it.
Joy.TrackEvent( &event );
// FIXME: Handle single-press events here (next target, etc).
// Don't handle button-held-down events like firing (see below).
if( event.type == SDL_QUIT )
done = true;
}
// Read joystick 0 analog axes.
double roll = Joy.Axis( 0, 0, deadzone );
double pitch = Joy.Axis( 0, 1, deadzone );
double yaw = Joy.Axis( 0, 3, deadzone );
double throttle = Joy.AxisScaled( 0, 2, 1., 0., 0., deadzone );
// Read joystick 0 buttons held down.
bool firing = Joy.ButtonDown( 0, 0 );
// FIXME: Update game objects and draw graphics.
}
I found a weird behaviour in SDL2:
If no events are put into the queue, try adding the following before the SDL_Init call:
SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS,"1");
Are you sure joystick points to a valid joystick?
You state that you're getting it in your Constructor... does that contructor happen to be called before you initialize SDL with SDL_INIT_JOYSTICK? This could happen if your player is a global variable.
Make sure that in order you:
Init the Joystick subsystem, either by adding it to your SDL_Init with | SDL_INIT_JOYSTICK or by calling SDL_InitSubSystem(SDL_INIT_JOYSTICK);
Check SDL_NumJoysticks() > 0
Get joystick 0: joystick = SDL_JoystickOpen(0);
Enable events: SDL_JoystickEventState(SDL_ENABLE);
Process your events with SDL_PollEvent
At the end of your program, close your joystick: SDL_JoystickClose(joystick);
Also, make sure the joystick is properly detected in Windows and reports its inputs properly.
Looks like your SDL isn't init proper.
replace
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK)
with
SDL_Init(SDL_INIT_EVERYTHING)
Is this SDL 1.2 or 2.0? In my case, on 2.0 SDL_PollEvent(&event) didn't actually put any data in the event struct. After that call, I had to use SDL_JoystickGetAxis(joystick_id, axis) and friends to get data.
So in your case, try to move the SDL_JoystickGetAxis call out of the if-test on event-type.
If you call SDL_NumJoysticks to get the number of controllers connected, then call SDL_JoystickOpen which returns a joystick identifier before your game loop then you will receive the SDL_JOYAXISMOTION events.
e.g.
int num_joy;
num_joy = SDL_NumJoysticks();
printf("%d joysticks found\n", num_joy);
for(int i = 0; i < num_joy; i++)
{
SDL_Joystick *joystick = SDL_JoystickOpen(i);
printf("Joystick name: %s\n", SDL_JoystickName(joystick));
}
SDL_Event event;
bool quit = false;
// Game loop
while(!quit)
{
// event loop
while(SDL_PollEvent(&event))
{
if (event.type == SDL_JOYAXISMOTION)
{
printf("Joystick______EVENT!\n");
}
// etc.....
See https://wiki.libsdl.org/SDL_JoystickName
I do not know how this can help you, but I do know that pygame supports joystick. And pygame is the python port of the SDL library. If everything fails, I guess you can always write that particular piece of code in python.

Is my programming logic correct here?

const char IsPressed = 1; // 1
const char WasHeldDown = 2; // 10
const char IsFirstPress = 4; // 100
char* keystates[256];
Class::CalculateKeyStates()
{
for(int i = 0; i < 256; ++i)
{
if(this->IsDown(i))
{
keystates[i] |= IsPressed; // turn on
if(keystates[i] & WasHeldDown)
{
//keystates[i] |= IsFirstPress;
keystates[i] &= ~IsFirstPress; // turn off
}
else
{
keystates[i] |= WasHeldDown + IsFirstPress; // Turn on
}
}
else
{
keystates[i] = 0; // Turn ALL off
}
}
}
This function would be a member function of a class, Class. The other member function, IsDown, will return a true if the key in question is down and false if not.
Can you see any way of further improving this function?
Thanks
EDIT:
I will expand a bit as to what is done why. This is a modification of an bit of code that works through an array keyStates (which was a struct of three bools) setting IsPressed to false for all of the keys. then again setting Ispressed to the value of this->IsDown and then a third time looping through checking if the key had been held, if it has then its no longer the first press so set that to false. if it was not held down, then set first press to true and was held to true as well, so next time it is flagged as having been held.
EDIT2:
Added some comments to code and corrected one line
Personally, I would define the key-states as disjoint states and write a simple state-machine, thus:
enum keystate
{
inactive,
firstPress,
active
};
keystate keystates[256];
Class::CalculateKeyStates()
{
for (int i = 0; i < 256; ++i)
{
keystate &k = keystates[i];
switch (k)
{
inactive:
k = (isDown(i)) ? firstPress : inactive;
break;
firstPress:
k = (isDown(i)) ? active : inactive;
break;
active:
k = (isDown(i)) ? active : inactive;
break;
}
}
}
This is easier to extend, and easier to read if it gets any more complex.
You are always setting IsFirstPress if the key is down, which might not be what you want.
I'm not sure what you want to achieve with IsFirstPress, as the keystate cannot remember any previous presses anyways. If you want to mark with this bit, that it's the first time you recognized the key being down, then your logic is wrong in the corresponding if statement.
keystates[i] & WasHeldDown evaluates to true if you already set the bit WasHeldDown earlier for this keystate.
In that case, what you may want to do is actually remove the IsFirstPress bit by xor-ing it: keystates[i] ^= IsFirstPress

Jump to listbox item by typing first few characters

I have a list of items (potentially large) from which the user must select one. I'd like to allow the user to type the first few letters of the desired item to jump to the correct place in the list. By default, each keypress jumps to the first item starting with that letter, so you can't type the first several letters. Is there any straightforward way to do this? Any CodeProject or other such example?
I've looked for hours, and found any number of samples for IAutocomplete, but that won't help here because I need to guarantee that the result is in the list.
The only way I can think to do this is to derive from CListBox, capture the keystrokes myself, find the item, run a timer so that new keystrokes after a sufficient pause will start a new search... since I'm not an MFC jock, this is daunting. Any tips much appreciated.
One clarifying note: my ultimate goal is actually to get this keyboard behavior for a ComboBox of DropDownList style (i.e. no edit box). The lack of an edit box rules out most autocomplete code, and the need for ComboBox functionality means I can't use CListCtrl by itself.
After much unnecessary pain, I've discovered that the real correct answer is simply to use LBS_SORT. Simply by specifying this style, the basic vanilla listbox supports the incremental search keyboard shortcut style I wanted. Without LBS_SORT (or CBS_SORT for a combobox), you get the irritating and almost-useless jump-to-first-letter-only behavior. I didn't try LBS_SORT because my list contents were added in sorted order anyway.
So the dozen or so hours of investigating custom controls, etc., all for naught because the Microsoft documentation makes no mention of this important behavioral difference in the description of LBS_SORT!!
Thanks to everyone who contributed.
I've implemented such a functionality in core Win32. Heres the code.
Somewhere in your message loop that processes the list box insert:
switch(message)
{
case WM_CHAR:
if(HandleListBoxKeyStrokes(hwnd, wParam) == FALSE)
return FALSE;
....
Heres the code (propably not fully complete):
/* ======================================================================== */
/* ======================================================================== */
#define RETURNr(a, b) // homegrown asserts
BOOLEAN HandleListBoxKeyStrokes(HWND hwnd, UINT theKey)
{
#define MAXCHARCACHEINTERVALL 600.0 // Max. milisecs time offset to consider as typed 'at once'
static char sgLastChars[255] = {'0'};
static double sgLastCharTime = 0.;
static HWND sgLasthwnd = NULL;
if(GetSecs() - sgLastCharTime > MAXCHARCACHEINTERVALL ||
sgLasthwnd != hwnd)
*sgLastChars = 0;
if(theKey == ' ' && *sgLastChars == 0)
return TRUE;
sgLastCharTime = GetSecs();
sgLasthwnd = hwnd;
AppendChar(sgLastChars, toupper(theKey));
if(strlen(sgLastChars) > 1)
{
LONG l = GetWindowLong(hwnd, GWL_STYLE);
Char255 tx;
GetClassName(hwnd, tx, sizeof(tx));
if( (! stricmp(tx, "Listbox") &&
! (l & (LBS_EXTENDEDSEL | LBS_MULTIPLESEL)) ) ||
(! stricmp(tx, "ComboBox") && // combo Box support
l & CBS_DROPDOWNLIST &&
! (l & (CBS_OWNERDRAWFIXED | CBS_OWNERDRAWVARIABLE)) ) )
{
long Count, l, BestMatch = - 1, BestMatchOff = 0;
long LBcmdSet[] = {LB_GETCOUNT, LB_GETTEXTLEN , LB_GETTEXT};
long CBcmdSet[] = {CB_GETCOUNT, CB_GETLBTEXTLEN, CB_GETLBTEXT};
long *cmdSet = (! stricmp(tx, "ComboBox")) ? CBcmdSet : LBcmdSet;
RETURNr((Count = SendMessage(hwnd, cmdSet[0], 0, 0)) != LB_ERR, 0);
for(int i = 0; i < Count; i++)
{
RETURNr((l = SendMessage(hwnd, cmdSet[1], i, 0)) != LB_ERR, TRUE);
RETURNr( l < sizeof(tx), TRUE);
RETURNr((l = SendMessage(hwnd, cmdSet[2], i, (LPARAM)&tx)) != LB_ERR, TRUE);
strupr(tx);
if(! strncmp(tx, sgLastChars, strlen(sgLastChars)))
{
SelListBoxAndNotify(hwnd, i);
return FALSE;
}
char *p;
if(p = strstr(tx, sgLastChars))
{
int off = p - tx;
if(BestMatch == -1 || off < BestMatchOff)
{
BestMatch = i;
BestMatchOff = off;
}
}
}
// If text not found at start of string see if it matches some part inside the string
if(BestMatch != -1)
SelListBoxAndNotify(hwnd, BestMatch);
// Nothing found - dont process
return FALSE;
}
}
return TRUE;
}
/* ======================================================================== */
/* ======================================================================== */
void SelListBoxAndNotify(HWND hwnd, int index)
{
// i am sorry here - this is some XVT-toolkit specific code.
// it has to be replaced with something similar for native Win32
WINDOW win = xvtwi_hwnd_to_window(hwnd);
WINDOW parent = xvt_vobj_get_parent(win);
xvt_list_set_sel(win, index, 1);
EVENT evt;
memset(&evt, 0, sizeof(evt));
evt.type = E_CONTROL;
evt.v.ctl.id = GetDlgCtrlID(hwnd);
evt.v.ctl.ci.v.lbox.dbl_click = FALSE;
xvt_win_dispatch_event(parent, &evt);
}
/* ======================================================================== */
/* ======================================================================== */
double GetSecs(void)
{
struct timeb timebuffer;
ftime(&timebuffer);
return (double)timebuffer.millitm +
((double)timebuffer.time * 1000.) - // Timezone needed for DbfGetToday
((double)timebuffer.timezone * 60. * 1000.);
}
/* ======================================================================== */
/* ======================================================================== */
char AppendChar(char *tx, char C)
{ int i;
i = strlen(tx);
tx[i ] = C;
tx[i + 1] = 0;
return(C);
}
Can you use a CListView CListCtrl instead? They work like that by default.

Resources