0

I'm trying to made a program that turn on and turn off leds with an input and send the coordinates of joystick, but, in the loop, the arduino makes one at a time, and i want make this in the same time. How can i make that?

PRVS
  • 117
  • 4

2 Answers2

1

One way to do this is to use the millis() function.

millis() returns the current value of a timer that is incremented once per millisecond (hence the function name). You can compare the value of millis() at some past time with the current value to determine how many milliseconds have passed. By having multiple compare registers you can have multiple independent delays operating. (There is also micros() which increments at the 1 uS rate (with a "granularity" of 4uS on some processors).

This code is an example only. It MAY run but has not been tested and probably contains silly mistakes which do not affect its example purposes.

A function ToggleLED(n) is assumed which toggles the specified LED n from 1->0 or 0->1 as required.

LED1 will flash 200 mS on, 200 mS off, ...
LED2 will flash 333 mS on, 333 mS off, ...

The two loops are essentially independent.


unsigned long delay1; delay2;

void setup(){  

int FlashTime1 = 200; / LED 1 will have a 200 on 200 off cycle
int FlashTime2 = 333; / LED 2 will have a 333 on 333 off cycle

delay1 = millis() + FlashTime1;  / Init LED timers
delay2 = millis() + Flashtime2;  
}

void loop()  
{  
  if (millis() == delay1){ / Not until delay expired. 

    ToggleLED(1);
    delay1= millis() + FlashTime1; / Reinit flash timer}

  if (millis() == delay2){

       ToggleLED(2);
       delay2= millis() + FlashTime2;}


}
Gerben
  • 11,332
  • 3
  • 22
  • 34
Russell McMahon
  • 2,421
  • 11
  • 14
0

the loop is something like this:

loop() {
controlleds();
joystickevent();
}

but he runs, controlleds first, and joystickevent next, i want at the same time.

There are typically two ways to read a simple potentiometer joystick: Connect it in a voltage divider and measure the analog voltage; and connect it in an R-C circuit and measure the time for the capacitor to charge.

The first way is faster and you should not be able to notice the time difference between controlling the LEDs and reading the joystick.

The second way takes longer and you might be able to notice. If this is how your joystick controller works, you would need to separately start the joystick reading, continue to poll the buttons control the LEDs, and check whether the joystick reading is ready yet. The joystick routine must not delay, waiting for the measurement to finish.

JRobert
  • 15,407
  • 3
  • 24
  • 51