text:
how can I stop my Arduino code after 1 second?
I want to send message NRF24L01 to NRF24L01. I want to see if I can send just one second. How can I stop code after 1 second?

study the example code that is included with the arduino IDE

You can use different ways:
Use setup only
Instead of putting code in the loop function,  put it in setup, which is only executed once (use a for loop to send around 1 second.
millis() excluding setup
It is better to use the millis function and compare it against the start of sending; when 1 second is reached, don't send anything or use an infinite while loop.
Use something like:
unsigned long time_start;

void setup()
{
    // Your normal code

    time_start = millis();
}

void setup()
{
    if (millis() - time_start >= 1000)
    {
        while(1) {};
    }

    // your normal code (which should not take many ms,
    // otherwise the above code is not reached.

millis() including saetup (Thanks to Edgar Bonnet):
 void loop()
 {
     if (millis() >= 1000)
     {
        while(1) {};
     }
 }

This will stop exactly after 1 s  after startup (excluding the setup). It will start counting after millis start counting, which is before the setup function.
Actually, in none of the above the Arduino 'stops', it just is doing endlessly nothing (well internally endlessly checking against the true condition which never changes).

Or even if (millis >= 1000) exit();.

@EdgarBonet Thanks, I added it to the answer.


text:
Receiving Multiple data on Arduino Serial
I am writing a very simple code in Arduino Nano, in which I am reading data that I send on Serial. Here is the code snippet.
int incomingByte ;

void setup() {
        Serial.begin(9600);
}

void loop() {

    if (Serial.available() > 0) {

            incomingByte = Serial.read();

            Serial.print("I received: ");
            Serial.println(incomingByte);
    }

}
When I send 'A' , I receive the following output:
I received: 65
I received: 13
I received: 10
What is wrong with the working of Serial Port here?

You send a string "A"
However, to denote the end, a carriage line (code 13) + line feed (code 10) is sent.
So what is sent is actually an 'A' character followed by a return.
This way you also know when a new line starts
Just strip off the return (13,10) items if you do not need them.
If you do not want to send the return, try sending 'A' (which is the character A, and not the string A.
Update
You can ignore them by:
     if ((incomingByte != 10 && (incomingByte != 13))
     {
        Serial.print("I received: ");
        Serial.println(incomingByte);
     }

If you only want printable characters, check if you can use the isprint function (isprint function
so it should look like
    if (isprint(incomingByte))
    {
        Serial.print("I received: ");
        Serial.println(incomingByte);
    }

can you please tell me how to strip return (13, 10)?

I added it initially accidentally to the wrong answer, now added it to my own.

nothing is wrong, it's to do with operator overloading and the print function trying to be helpful.
if you change this line:
int incomingByte ;

to this:
char incomingByte ;

it should display correctly
And the extra characters are because the software on the computer is sending line endings. these may be a linefeed with or without a carriage return. you could either just ignore them, or make use of them to create multi character commands (if you need them)

hi, thanks for your input , but when I change it to char I still receive following :I received: A
I received:
I received:

I don't want trailing carriage return and enter in my output, I simply need the character. How to trim ?

If you don't want any trailing carriage returns, just ignore them

@James Kent ... sorry for editing your answer (I moved it to my own answer). But still upvoted yours (for the inconvenience).

this is just because you are typing a letter i  the serial monitor ans in your code your are declaring it as a integer 'int' so you not need to worry about that just try the following code
int incomingByte ;

void setup() {
        Serial.begin(9600);
}

void loop() {

    if (Serial.available() > 0) {

            incomingByte = Serial.read();
            Serial.write(incomingByte);
    }
}

--------------------------------   OR    ---------------------------------------
char incomingByte ;

void setup() {
        Serial.begin(9600);
}

void loop() {

    if (Serial.available() > 0) {

            incomingByte = Serial.read();
            Serial.print(incomingByte);
    }
}

Both of the programs will work try that.......

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Joysitck with servo, LED array and buzzer
Does anybody know of a sketch that can turn a single servo 180 degrees clockwise/counterclockwise with the x axis of a joystick, light a bar graph LED with the Y axis, and sound a buzzer when the joystick button is depressed.

With such a specific set of requirements, why not write such a sketch yourself? It's the Arduino way.

We are a bit too new, we have learned each of the parts of the code but we are struggling with the servo control and putting them all together. Check out what we learned about doing lots of commands at once https://arduino.stackexchange.com/questions/48810/emergency-vehicle-make-two-leds-flash-with-buttons-and-a-passive-buzzer-change

Assuming you are new on Arduino: try to create a sketch separately for each component (you can download them mostly). Than if you feel each component works, combine them to get the functionality that you want.

That previous question has an accepted answer with a link to an article on how to multitask with an Arduino. It talks about a state machine. That would be the path to take to be able to handle multiple event triggers and responses.

Oi, @MichelKeijzers - Stop reading my answers before I finish typing them :)

@CodeGorilla Your answer was not posted before I made this remark (but I guess your remark is sarcastic) ... Good answer btw (I upvote it) :-)

Wow -1, harsh from somebody. I am like 11 years old - I am trying.

Michel - Yes it was sarcastic - you know me too well :).  @Jacob - I don't think the down vote was because of your age.  Your question looks like posting here is the first thing you tried, it looks like you didn't do any research, because you haven't mentioned any.  Also because your requirements are so specific most people who post on here would know that there is no chance of there being a sketch that does all that you need.  Your age on here is how long you have been a member and having read your other posts you are a mature 2 YO :)

You have a distinct set of requirements that you could turn into a sketch yourself.  I'm guessing you have never written a program before, in which case the problem really is you don't know how to do what you want to.
So, break the problem down into small chunks.  The less complex a problem the more likely you are to find a generic solution on the web that you can 'borrow'.

How do you turn a servo?
How do you read the position of a joystick?
How do you light a LED bar graph?
How do you sound a buzzer?

I'm pretty certain that you can find pages that tells you how to do each of those in separate sketches.  Once you have each of those working you need to merge the setup functions, making sure they don't over write each other and then tackle the loop functions (which will be more difficult).  BUT I know there are posts on here about how to merge two sketches into one.
I'm 99% certain you will not find a sketch that does what you want.  I'm 99% certain you will be able to coble together a solution that will do what you want if you break it down.
If you get stuck, post the code you have and explain your problem and people will help.
Good luck.

Thanks. We learned how to tackle the loop function bit last week which was cool. Here is the first code we wrote -
the one at the bottom is our best one. https://arduino.stackexchange.com/questions/48810/emergency-vehicle-make-two-leds-flash-with-buttons-and-a-passive-buzzer-change

Added an extra answer to your above post.  I think the answer could also be applied to this question too.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Need to read/send both values of a button push
I'm trying to use a float switch to receive alerts via Blynk when a water level drops, and when it rises again. The code I have been using has been working for when the float drops (button pressed) and I could get it to work when the water comes back up, but it gets stuck in a loop. I'm new to Arduino programming and I'm sure it's some simple error in the way I'm writing/modifying this code...
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;

char auth[] = "710a4af9b1d82412fa477705bf642c634";
char ssid[] = "SSID";
char pass[] = "PWD";
int flag=0;
void notifyOnButtonPress()
{
  int isButtonPressed = digitalRead(D1); //assignment here for pin
  if (isButtonPressed==1 && flag==0) {

    Blynk.notify("Alert : Water Level has dropped");
    flag=1;
  }
  else if (isButtonPressed==0 && flag==0)
      Blynk.notify("Alert : Water level has risen");
  {
    flag=0;
  }

}
void setup()
{
  // Debug console
  Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
  // Setup notification button on pin D1
  pinMode(D1,INPUT_PULLUP);
 timer.setInterval(16000L,notifyOnButtonPress);

}
void loop()
{
  Blynk.run();
  timer.run(); // Initiates BlynkTimer
}

I believe the problem is in function notifyOnButtonPress.

Is the float connected to a switch on pin D1 such that if the water level drops, lowering the float, the switch connected to pin D1 is turned on and it stays on until the water level rises sufficiently, lifting the float, so that the float turns off the switch connected to pin D1? So the flag variable indicates if a message has been issued that the switch is turned on, low water level, or turned off, high water level?

Correct. The pin is assigned to D1. The water level is normally high. When it drops, the float drops and sends the "on" signal to the board. It remains in this state for around 15 minutes or so, then the water ebbs back up and opens the loop again (switching off). I'm trying to use "Flag" to be able to determine the last state and reset after a cycle of ON/OFF essentially with this switch... or i guess OFF/ON/OFF and repeat.

It seems to me that the saved float level state needs to be initialized to what it's actual current level is rather than just starting it off as 0. That way conditions such as a power outage during which the float level has changed could be detected.
I also changed the text of your notifications, which may or may not be allowed, to more accurately describe the state of the system.
I haven't actually tested this so I would like feedback as to whether it works or not.
int floatSavedState = -1;      // initial float low state indicates not yet known

void notifyOnButtonPress()
{
  // pin D1 will be 1 if float has dropped due to low water level
  // pin D1 will be 0 if water level is high enough
  int floatLevelLow = digitalRead(D1);  // read the float low indicator pin

  if (floatLevelLow && floatLevelLow != floatSavedState) {
       // send notification if this is first time or if the float level has
       // changed since the last notification.
       Blynk.notify("Alert : Water Level low.");
       floatSavedState = floatLevelLow;
  } else if (floatLevelLow != floatSavedState)
     // send notification if this is first time or if the float level has
     // changed since the last notification.
     Blynk.notify("Alert : Water level high");
     floatSavedState = floatLevelLow;
  }
}

Or I suppose even simpler would be:
int floatSavedState = -1;      // initial float low state indicates not yet known

void notifyOnButtonPress()
{
  // pin D1 will be 1 if float has dropped due to low water level
  // pin D1 will be 0 if water level is high enough
  int floatLevelLow = digitalRead(D1);  // read the float low indicator pin

  if (floatLevelLow != floatSavedState) {
       // send notification if this is first time or if the float level has
       // changed since the last notification.
       if (floatLevelLow) {
           Blynk.notify("Alert : Water Level low.");
       } else {
           Blynk.notify("Alert : Water level high");
       }
       floatSavedState = floatLevelLow;
  }
}

Thank you. This gives me a single notification of "Water Level low" when powered up and float is in the HIGH position. Manually adjusting the float after has no effect. This holds true for both examples provided.

@gfuller40 look at your pinMode(D1,INPUT_PULLUP) call. I think that makes pin D1 to be an INPUT pin and is attaching a pullup resistor to it so that if the line attached to the pin is floating, the pin will be pulled up to a HIGH value. I am a bit hazy on it but I am wondering if you have a wiring and setup problem. My impression, which may be wrong, is that the pin will always be HIGH. Could you check the value of the digitalRead(D1) that it returns a value of 1 if the float is pushed down, water level low, and a value of 0 if the float is up, water level high?

Thank you, Richard. I'm only using D1 and GND. This works as it should when i only check to see if the float has dropped in my initial programming
int isButtonPressed = digitalRead(D1);
if (isButtonPressed==1 && flag==0) {
Serial.println("Resevoir Water is Low!");
Blynk.notify("Alert : Resevoir water is Low!");
flag=1;

}
else if (isButtonPressed==0)
{
flag=0;
}
)
but when I add to check the state again (high) is where I've been having trouble. I guess that's the only reason i have to believe it is set up correctly?

@gfuller40 please update your posted question with a wiring schematic showing how you have things wired up. As part of that identify the actual components being used in the wiring. I am not sure what you mean by "only using D1 and GND" and how that wiring is done. You want to make sure that if the water level is low then the pin will definitely see a HIGH or 1 and if the water level is high then the pin will definitely see a LOW or 0. See https://playground.arduino.cc/CommonTopics/PullUpDownResistor or https://www.electronics-tutorials.ws/logic/pull-up-resistor.html

OK. I have a float switch (2 wires) one is connected to the GND pin on on the digital side of the MCU and the other is connected to D1 on the digital side as well. I just ran a test using a very simple function (void notifyOnButtonPress()
{
Serial.println(digitalRead(D1));
}) and I'm  only seeing a value of "1" on the serial monitor (both positions). That explains things.... do i need a 3 wire float or something? or just use two floats?

OK!!! I knohw what is going on... your code is fine, the serial monitor is registering correctly, it's the blynk notifications, it keeps sending them one after the other, is this an issue with the loop?

It has to be something going on here: void setup()
{
// Debug console
Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
// Setup notification button on pin D1
pinMode(D1,INPUT_PULLUP);
timer.setInterval(16000L,notifyOnButtonPress);
}
void loop()
{
Blynk.run();
timer.run(); // Initiates BlynkTimer
} Blynk keeps looping and saying the water level is high regardless of the position of the float.

@gfuller40 so I am not sure what your particular float switch looks like and how it operates so details about that would be good. Your Arduino sketch looks similar to the example from Blynk documentation. I really think it is your circuit. See this diagram that goes HIGH when button is pressed or LOW otherwise https://goo.gl/images/QWJftz because when button is pressed, pin is HIGH as power flows to pin and when button is released, pulldown resistor makes sure pin is LOW.

Richard - The code and wiring are fine. The serial monitor is outputting what it should and reflecting what the float switch is doing. The issue is that blynk is sending notifications every few seconds of it's current state when I'm only asking for a single notification of the float as the status of it changes

@gfuller40 is that notification every few seconds from your original code or is it from the code example I provided? Or both?

From the code you provided. I added your new code to the existing and the serial monitor reflects 100% what I'm doing with the float but notifications keep getting pushed.

Change
else if (isButtonPressed==0 && flag==0)
    Blynk.notify("Alert : Water level has risen");

to
else if ((isButtonPressed==0) && (flag==1))
{
    Blynk.notify("Alert : Water level has risen");
}

Otherwise, when flag == 1, it will never revert back to 0.
Also it's best to add brackets, and use parenthesis.
Also, change the variable name flag to something more meaningfull.

His brackets are also wrong. flag always gets set to 0.

Are you saying I should also get rid of this:
{
flag=0;
}

No you have to change it to flag==1
Also use brackets (I will add it in my answer)

Ok so this gets me stuck in a loop of water level LO and manually moving the float to HIGH has no effect.


text:
Burn bootloader to Arduino Uno using ARM-USB-OCD
I have ARM-USB-OCD created by OLIMEX. I am interested in can I use this to burn a bootloader to Arduino Uno. As I know Atmega 328P can be programmed using JTAG protocol which has also ARM-USB-ODC, so if it really can anyone give the circuit or something like this.
Here is my device (ARM-USB-ODC) manual.

Where did you get that information the Atmega328 supports JTAG? There is only the DebugWire interface. And as far as I remember, the AVR JTAG might be kinda incompatible with anything else. However the programmer is FTDI based, so it might be possible to use it as clasic serial programmer.

Atmega328P does not have JTAG pins.

Probably, but likely not easily
To program an AVR chip you likely want to use the AVR ISP protocol, which is not JTAG, but like JTAG is a synchronous serial protocol with a clock, a data line in each direction, and one additional control pin compared to the several mode/status pins of JTAG.
According to your link, the ARM-USB-OCD is based on an FT2232C USB interface chip.
avrdude documentation indicates that this is an interface it knows how to use, though it will likely take some study to figure out how.
The final question would be wiring - you'll need to figure out which JTAG-style signal names map to which FTDI functional pins, and how those should best be connected to AVR ISP pins in a way which avrdude can use.  Additionally, you'd have to make sure that any buffering between the FTDI chip and the pins is compatible with your needs, both in terms of data direction and voltage level.
Note that you can easily use any ATmega328-based Arduino as an ISP programmer for a same-voltage target - not really production worthy, but if you just need to move your project along today it's a handy option.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Servo start to turn like madman with simple if statement
I tried to write a simple program. Press button 1 servo goes to position 1, press button 2 servo goes to position 2.
But when I hook everything up my Servo goes full Crazy mode. It starts to jiggle back and forth like a madman. Even when I unhook the buttons.
What is the mistake I made? Any help is appreciated :D
Thanks in advance
/* Sweep
     by BARRAGAN <http://barraganstudio.com>
     This example code is in the public domain.

     modified 8 Nov 2013
     by Scott Fitzgerald
     http://www.arduino.cc/en/Tutorial/Sweep

    modified 5-12-2017
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int buttonState = 0;         // variable for reading the pushbutton status
int buttonState2 = 0;        // variable for reading the pushbutton status
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin2 = 5;    // the number of the pushbutton pin

void setup() {
  myservo.attach(9);         // attaches the servo on pin 9 to the servo object
  pinMode(buttonPin, INPUT);
  pinMode(buttonPin2, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2);
  if (buttonState == HIGH) {
    myservo.write(173);        // tell servo to go to position
    delay(25);                 // waits 25ms for the servo to reach the position
  }
  if (buttonState2 == HIGH) {
    myservo.write(97);         // tell servo to go to position
    delay(25);                 // waits 25ms for the servo to reach the position
  }
}

How did you connect the buttons to the Arduino? Schematic please.

added a picture

Please, connect the buttons to the ground and change the code:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int buttonState = 0;         // variable for reading the pushbutton status
int buttonState2 = 0;        // variable for reading the pushbutton status
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin2 = 5;    // the number of the pushbutton pin

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2);
  if (buttonState == LOW) {
    myservo.write(173);              // tell servo to go to position
    delay(300);                       // waits 25ms for the servo to reach the position
  }
  if (buttonState2 == LOW) {
    myservo.write(97);              // tell servo to go to position
    delay(300);                       // waits 25ms for the servo to reach the position
  }
}

Pull-up resistors get a high input level when the buttons are open. Otherwise, electromagnetic interference may occur.

Very cool it stopped randomly moving!. Now it goes to the 2 positons. Yet one of those positions it keeps "buzzing" like some of the gears are still turning but I dont see any rotation as result. The second Position is Silent and very nice :D Do you know how this buzzing can be removed?

Please try to increase the delay from 25 to 300.


text:
If I run a function in loop() or setup(), and the function doesn't work after some time, is there a way to escape the function and return to the code?
The hardware is an Arduino Uno, using the Arduino IDE.
As a simplest working example, say I have this code
(partially from Edgar Bonet's answer):
// Simulate an initialization that can hang. Connect pin 8 to ground if
// you want the function to ever return.
void initialize()
{
    pinMode(8, INPUT_PULLUP);
    while (digitalRead(8) == HIGH)
    ;  // wait
}

setup()
{
    initialize();             //Function I want to run

    Serial.begin(9600);       //Baud rate
    Serial.println("TEST 1"); //Test message
}

loop()
{
    Serial.println("TEST 2"); //Test message
    delay(1000);
}

if the initialize() function does not complete after some time, such as 2 secs.,
is there a way to ignore that function and continue with the rest of the code?

Not really.  But you could use a watchdog timer to give up and start over; and you can detect that this happened and maybe skip that function.  Or you can use a scheduler and have tasks take turns rather than run sequentially.  Generally though, even if you use one of these things, you should make your functions deterministically conclude and explicitly handle the situations that might cause operations to get stuck.

An infinite busy loop, like you have coded, is not a great idea.  Is there a reason you didn't try for(int l = 0; l < 20 && (digitalRead(8) == HIGH); ++l){Sleep(100);}?  Not a brilliant solution, but pretty fool proof.

@CodeGorilla That initialize function was only there to try make the question more specific, since this question was "put on hold as too broad". The actual function I use comes from a library I didn't write, and I wanted to avoid changing it since it was a bit hard to follow and had several inter-related dependent files.

In general, the right thing to do in such a situation is to fix the
initialize() function so that it always returns. If there is a timeout
to be handled, it should be handled within that function. This is likely
to be the easiest and cleanest solution.
However, if for whatever reason that is not feasible (maybe it comes
from a library that is too opaque to edit), then the idea suggested by
Michel Keijzers is a viable alternative:

[...] set up a timer interrupt and start it just before you initialize
  the device/component you want to initialize. When the timer interrupt
  triggers and the device is not initialized, behave the same like a
  timeout has occurred.

The issue with this is that you would want the ISR (interrupt service
routine) to return to the point where initialize() was called. This is
not trivial, but it can be done. Actually, and contrary to what my own
comment says, it can be handled without resorting to assembly hacks, by
using the setjmp “non-local goto” feature of the avr-libc. Here is a
proof of concept:
#include <setjmp.h>

jmp_buf env;

// Simulate an initialization that can hang. Connect pin 8 to ground if
// you want the function to ever return.
void initialize()
{
    pinMode(8, INPUT_PULLUP);
    while (digitalRead(8) == HIGH)
        ;  // wait
}

// This fires when the initialization times out.
ISR(TIMER1_OVF_vect)
{
    TIMSK1 = 0;       // disable timer interrupt
    longjmp(env, 1);  // go to where setjmp() was called
}

void setup()
{
    Serial.begin(9600);

    // Configure Timer 1 to fire an interrupt in about 4 seconds.
    TCCR1A = 0;           // reset timer
    TCCR1B = 0;
    TCNT1  = 0;
    TIFR1  = _BV(TOV1);   // clear interrupt flag
    TIMSK1 = _BV(TOIE1);  // enable timer overflow interrupt
    TCCR1B = _BV(CS10)    // clock at F_CPU / 1024
           | _BV(CS12);   // ditto

    // Attempt initialization.
    if (setjmp(env) == 0) {

        // This is the normal program flow.
        Serial.println("Attempting initialization.");
        initialize();
        TIMSK1 = 0;  // disable timer interrupt
        Serial.println("Initialization succeeded.");
    } else {

        // We get here through longjmp() in case of timeout.
        Serial.println("Initialization aborted on timeout.");
    }

    Serial.println("Moving on to the rest of the program.");
}

void loop(){}

If pin 8 is grounded, the initialization succeeds and the program prints
Attempting initialization.
Initialization succeeded.
Moving on to the rest of the program.

If pin 8 is left floating, the initialization hangs and the program
prints
Attempting initialization.
Initialization aborted on timeout.
Moving on to the rest of the program.

with a 4 second pause between the first and second lines.

I'm not sure if you should want this in the first place. Initialization normally should contain the necessary parts to start with.
If there is a device/component you want to initialize that is not able to initialize (because it is not present, or broken), check first if there is an intiialization function with a timeout and when the timeout is reached, set a boolean to denote the device has not been initialized.
If there is not a timeout function, you could try to set up a timer interrupt and start it just before you initialize the device/component you want to initialize. When the timer interrupt triggers and the device is not initialized, behave the same like a timeout has occurred.

About your timer interrupt suggestion: Ideally, the ISR should return to the caller of initialize(), but that would be quite tricky, and would probably have to handled in assembly. If you can manage to add to your answer some example code implementing the idea, it would be really great.

@EdgarBonet If it is problematic to have an ISR during initialize, why not create the initialization part that might fail in the loop() function and after initialization is finished use a while(true) to stay in that loop.

@EdgarBonet Btw, I never tried an ISR during initialization myself.

@EdgarBonet having an ISR "return to the caller" of a blocked function is approximately what a scheduler does.  What would be more realistic here is to have the ISR set a "timed out" flag and have whatever operation is spinning in a while() give up on seeing that.  Checking elapsed time via millis() is comparable, only instead of a boolean flag it's a numeric value updated by the Arduino core's timer ISR handler.


text:
When a pushbutton and sensor are in a certain state, do something for a certain period of time (15 seconds)
I have a sketch that contains code for an analog input (FSR sensor), a pushbutton, and 6 blinking LEDs.
Currently, the sketch is written to allow the LEDs to blink only when the button is pressed and there is sensor input.
Can someone help me write code to make the LEDs blink for a certain period of time once there is input from the analog sensor and while the button is pressed?  I am trying to make the LED blink for 15 seconds and then turnoff.
thank you!
/*
 6 Flashing LED Lights With A Pushbutton and FSR Sensor
*/

const int buttonPin = 8;
const int LedPin1 = 7;
const int LedPin2 = 6;
const int LedPin3 = 5;
const int LedPin4 = 4;
const int LedPin5 = 3;
const int LedPin6 = 2;

int buttonState = 0;
int SensorPin = A0;
int SensorPinReading;

void setup() {
  Serial.begin(9600);
  pinMode(LedPin1, OUTPUT);
  pinMode(LedPin2, OUTPUT);
  pinMode(LedPin3, OUTPUT);
  pinMode(LedPin4, OUTPUT);
  pinMode(LedPin5, OUTPUT);
  pinMode(LedPin6, OUTPUT);
  pinMode(buttonPin,INPUT);
  pinMode(SensorPin, INPUT);
}

void loop() {
  SensorPinReading = analogRead(SensorPin);
  Serial.print("Analog reading = ");
  Serial.print(SensorPinReading);

if (SensorPinReading < 10) {
  Serial.println(" - No Pressure");
} else if (SensorPinReading < 200) {
  Serial.println(" - Light Touch");
} else if (SensorPinReading < 500) {
  Serial.println(" - Light Squeeze");
} else if (SensorPinReading < 800) {
  Serial.println(" - Medium Squeeze");
} else {
  Serial.println(" - Big Squeeze");
}

  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH && SensorPinReading > 10)  {
  digitalWrite(LedPin1, HIGH);
  digitalWrite(LedPin2, HIGH);
  digitalWrite(LedPin3, HIGH);
  digitalWrite(LedPin4, HIGH);
  digitalWrite(LedPin5, HIGH);
  digitalWrite(LedPin6, HIGH);
  delay(600);
  digitalWrite(LedPin1, LOW);
  digitalWrite(LedPin2, LOW);
  digitalWrite(LedPin3, LOW);
  digitalWrite(LedPin4, LOW);
  digitalWrite(LedPin5, LOW);
  digitalWrite(LedPin6, LOW);
  delay(200);
  }
  else {
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }

}

Please edit your question (click "edit") and mark the code as code.  In the editing box, highlight the code and press ctrl-k. Or highlight the code and click the {} icon in the toolbar at the top of the editing box. To highlight text click-drag across it or use the arrow keys while holding the shift key.

The code shown below is to “make the LEDs blink like the previous sketch during the 15 seconds”.  The  previous sketch (that is, the code in the question) turns the LEDs on for 600 ms and off for 200.  The code below reverses the order – that is, does off for 200 and on for 600 – and repeats that pattern during the first 15 seconds after conditions being met.  The annoyingly complicated if statements in the code are to prevent retriggering; that is, to prevent another 15-second blink session immediately starting up if the trigger conditions are still present.  Your problem statement is not perfectly clear on how that should be handled.
// 6 Flashing LED Lights With A Pushbutton and FSR Sensor

enum { LedPin6=2, LedPin5, LedPin4, LedPin3, LedPin2, LedPin1 };
enum { buttonPin=8, SensorPin = A0};
enum { quantum=200, sessionLength=15000/quantum};

byte buttonState = 0;
byte SensorPinReading;
byte blinkLEDs=false, sessionDone=false;
unsigned long baseMilli;

void setLEDlevels(byte level) {
  digitalWrite(LedPin1, level);
  digitalWrite(LedPin2, level);
  digitalWrite(LedPin3, level);
  digitalWrite(LedPin4, level);
  digitalWrite(LedPin5, level);
  digitalWrite(LedPin6, level);
}

void setup() {
  Serial.begin(115200);
  pinMode(LedPin1, OUTPUT);
  pinMode(LedPin2, OUTPUT);
  pinMode(LedPin3, OUTPUT);
  pinMode(LedPin4, OUTPUT);
  pinMode(LedPin5, OUTPUT);
  pinMode(LedPin6, OUTPUT);
  pinMode(buttonPin,INPUT);
  pinMode(SensorPin, INPUT);
}

void loop() {
  SensorPinReading = analogRead(SensorPin);
  Serial.print("Analog reading = ");
  Serial.print(SensorPinReading);

  if (SensorPinReading < 10) {
    Serial.println(" - No Pressure");
  } else if (SensorPinReading < 200) {
    Serial.println(" - Light Touch");
  } else if (SensorPinReading < 500) {
    Serial.println(" - Light Squeeze");
  } else if (SensorPinReading < 800) {
    Serial.println(" - Medium Squeeze");
  } else {
    Serial.println(" - Big Squeeze");
  }

  buttonState = digitalRead(buttonPin);
  // Turn on 15-second blink session if conditions met
  if (buttonState == HIGH && SensorPinReading > 10)  {
    if (!blinkLEDs && !sessionDone) { // Is session eligible?
      blinkLEDs = true;
      sessionDone = false;
      baseMilli = millis();
    }
  } else {               // A condition failed.
    if (sessionDone)             // Has session finished?
      blinkLEDs = sessionDone = false; // Enable next session
  }

  if (blinkLEDs) {
    int age = (millis()-baseMilli)/quantum;
    setLEDlevels((age&3)>0);    // Off for 1 quantum, on for 3 quanta
    // See if blink session has run long enough
    if (age > sessionLength) {
      blinkLEDs = false;        // Stop blinking
      sessionDone = true;   // Prevent retrigger until conditions reset
      setLEDlevels(LOW);    // Turn off lights
    }
  }
}

The statement setLEDlevels((age&3)>0) calls setLEDlevels() with a parameter value of 0 or 1.  It will be 0 if age is a multiple of 4.  In binary, multiples of 4 have their lowest two bits clear.  It will be 1 if age is not a multiple of 4.  This will alternately turn the LEDs off for one quantum (200 ms) and then on for 3 quanta (600 ms).

Edit 1: To  “make the sensor read input while the button is not pressed, and then relay that input once the button is pressed so the LEDs immediately light up when it is pressed”, add a state variable (eg sensorPressed) to use in place of SensorPinReading > 10.  Whenever SensorPinReading is large enough (and any other necessary conditions are met), set sensorPressed.  When you start a blink session, reset sensorPressed (make it false).
Note, from your comment, you've added the following code near the end of loop():
if (buttonState == LOW && blinkLEDs == true) {
  blinkLEDs = false;
  sessionDone = true;
  setLEDlevels(LOW);
}

A minor issue with that code is it leaves sessionDone = true.  It is minor because the next pass through loop() usually will execute the else branch (of the if (buttonState == HIGH && SensorPinReading > 10) if-statement) which will go ahead and set sessionDone = false to enable the next blink session.  Assuming you want to shut down blinking whenever the button is low, what I would do instead of that little code block is this:
if (!buttonState) {
  blinkLEDs = sessionDone = false;
  setLEDlevels(LOW);
}

(The expression !buttonState has the same value as buttonState == LOW and is four syllables shorter.)
Note, the code perhaps can be made more clear by using a state machine to control what happens.  To do so, draw a diagram with nodes representing possible states – such as “idle” or “waiting for inputs”, “enabled”, “blinking”, “after blinking”.  Draw lines between states, each labeled with the condition that triggers the particular state transition.  State machines can be implemented using switch and case statements, or via an if–else sequence.

thank you so much! That is basically what I need, although I made one modification to your code...

if (buttonState == LOW && blinkLEDs == true)  {
blinkLEDs = false;
sessionDone = true;
setLEDlevels(LOW);                                                                                Thank you so much @jwpat7 ! Sorry about the unclear problem statement.  I added the above code at the end.  Now to complicate it a bit more.  I will explain best I can.  Is there any way to make the sensor read input while the button is not pressed, and then relay that input once the button is pressed so the LEDs immediately light up when it is pressed?  Either way thank you again!

@msquirrel, see edit 1

To “make the sensor read input while the button is not pressed, and then relay that input once the button is pressed so the LEDs immediately light up when it is pressed”... I changed the SensorPinReading to sensorPressed, but what type of statement would I use in the loop to meet the condition?  I tried similar if statements that did not work, and I'm unsure of how to set it up.

You still need to set SensorPinReading = analogRead(SensorPin) each pass thru loop.  Turn on sensorPressed whenever  SensorPinReading is high enough; turn sensorPressed off once you have used it to trigger a blink session.

Here below is modified code based on your requirement. There are some changes in your code and I also comment it out. I hope it will help you.
/*
 6 Flashing LED Lights With A Pushbutton and FSR Sensor
*/

const int buttonPin = 8;

const int LedPin1 = 7;
const int LedPin2 = 6;
const int LedPin3 = 5;
const int LedPin4 = 4;
const int LedPin5 = 3;
const int LedPin6 = 2;

const int kDelay = 1000; // Take one varible "kDelay" and value = 1000

int buttonState = 0;
int SensorPin = A0;
int SensorPinReading;

void setup()
{
  Serial.begin(9600);
  pinMode(LedPin1, OUTPUT);
  pinMode(LedPin2, OUTPUT);
  pinMode(LedPin3, OUTPUT);
  pinMode(LedPin4, OUTPUT);
  pinMode(LedPin5, OUTPUT);
  pinMode(LedPin6, OUTPUT);

  pinMode(buttonPin,INPUT_PULLUP); // Provide PULLUP
  pinMode(SensorPin, INPUT);
}

void loop()
{
  SensorPinReading = analogRead(SensorPin);
  Serial.print("Analog reading = ");
  Serial.print(SensorPinReading);

  if(SensorPinReading < 10)
  {
    Serial.println(" - No Pressure");
  }
  else if (SensorPinReading < 200)
  {
    Serial.println(" - Light Touch");
  }
  else if (SensorPinReading < 500)
  {
    Serial.println(" - Light Squeeze");
  }
  else if (SensorPinReading < 800)
  {
    Serial.println(" - Medium Squeeze");
  }
  else
  {
    Serial.println(" - Big Squeeze");
  }

  buttonState = digitalRead(buttonPin);

  if(buttonState == HIGH && SensorPinReading > 10)
  {
    digitalWrite(LedPin1, HIGH);
    digitalWrite(LedPin2, HIGH);
    digitalWrite(LedPin3, HIGH);
    digitalWrite(LedPin4, HIGH);
    digitalWrite(LedPin5, HIGH);
    digitalWrite(LedPin6, HIGH);
    delay(15 * kDelay);            // You need 15 Sec, multiply kDelay with 15
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }
  else
  {
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }
}

is there any way to make the LEDs blink like the previous sketch during the 15 seconds? @Hasan


text:
Proper use of * and & when passing objects in methods
Coming from C#, pointers are somewhat foreign although I am grasping the concept.
Is it proper to construct methods in the following manner and passing the object (as a parameter) constructed by reference? If not, then please answer how to do this properly.
Initialize the object
Adafruit_VS1053_FilePlayer musicPlayer =
    Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

Method: (use the * for pointer?)
boolean initializeMusicPlayer(Adafruit_VS1053_FilePlayer *mp, uint16_t baudRate) {

    musicPlayerSerialPort.begin(baudRate);
    // initialise the music player
    if (!mp->begin()) { // initialise the music player
        Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
        return false;
        //while (1);
    }
    Serial.println(F("VS1053 found"));

    mp->sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working

    if (!SD.begin(CARDCS)) {
        Serial.println(F("SD failed, or not present"));
        return false;
        //while (1);  // don't do anything more
    }
    Serial.println("SD OK!");
    // Set volume for left, right channels. lower numbers == louder volume!
    mp->setVolume(20, 20);

    if (!mp->useInterrupt(VS1053_FILEPLAYER_PIN_INT)) {
        Serial.println(F("DREQ pin is not an interrupt pin"));
        return false;
    }
    return true;
}

Call the method (Use the ampersand to pass the currently created one by reference?)
if(initializeMusicPlayer(&musicPlayer, 9600) == true) {
    tempString = tempString + "MusicPlayer initialized!";
    Serial.println(tempString);
    //when adding lcd, print the above to lcd and remove the serial print
}

The method you have implemented, passing by pointer, is one of the two normal methods, yes. The other is passing by reference and is specific to C++, not C.
Under the hood the end result is the same between the two methods, by the syntactic "sugar" is very different and the latter can be preferable for that reason alone.
Your method:
void function(whatever *ob) {
    ob->method();
}

function(&myObject);

The pass by reference method:
void function(whatever &ob) {
    ob.method();
}

function(myObject);

As you can see the need to convert the object into a pointer with & is now gone. That makes it much easier for people lacking in programming skills to use it since it hides the whole pointer mechanism from them.
Also, internally your function now treats ob as just another object using ., rather than a pointer to an object and needing to use ->.  Note that you can only use the reference operator in a function prototype, not a variable or anything like that - it's purely for passing objects and variables to functions.  If you want to then go and store the pointer in a variable you still then have to get the address:
void function(whatever &ob) {
    myObjectPointer = &ob;
}

As you see it gets confusing with the two different uses of &. Basically though: if it's in a function prototype, it's the pass by reference operator. If it's anywhere else, it's the get the address of operator (or a logical AND of course).
Storing the pointer can be useful if you want to then do other things later on with the same object, especially if you are yourself working with a class.  For instance, I often write code similar to the following:
class foo {
    private:
        bar *ob; // Pointer to other object of type "bar"
    public:
        foo(bar *inob) : ob(inob) {}
        foo(bar &inob) : ob(&inob) {}

        void something() {
            ob->doSomething();
        }

        void somethingElse() {
            ob->doSomethingElse();
            ob->evenMoreThings();
        }
};

You then have a choice of constructors:
bar myBar;
foo myFoo(myBar);

// ... later ...
myFoo.something();

or
bar myBar;
foo myFoo(&myBar);

// ... later ...
myFoo.something();

and the user doesn't have to remember which they need to use - whichever they try will work.

So what I have done is correct, although not necessarily the best method. My thought with the pointer, was since that player can be called dozens of times, I want it to call the same object every time. Is my code written properly for that intent?

Looks fine to me.  Although I tend to pass an object to the constructor and store it as a pointer in the class I am making, then access the object through that pointer - means you don't have to then keep passing the same object over and over again.

@Majenko...Thank you, one other item. Put the class in the projects header file?

It depends how you are going to use the class. If you want to use it in other places it can be worth turning it into a library - have a .h file with the class declaration in it, and a .cpp file with the actual class methods. If you don't want to split it into separate declaration and definition then you should keep it in your sketch. It can still be useful to split it even then though if you have multiple source files in your sketch that all want to use it.

I think it would be worth mentioning the important difference between a pointer and a reference: a pointer can be NULL (i.e. 0 meaning that it points to nothing) whereas a reference shall always refer to a real variable (although technically it is possible to trick the compiler but nobody would do that). Personally I always prefer using references if I don't want to allow NULL.


text:
using enums in functions
Given the following enums
enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
enum class CrossingZoneState: uint8_t {
    CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
    CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
};

Where RELAY_OFF = HIGH, HIGH is #define HIGH 0x1 which I assume is a C++/Arduino constant? because I didn't define it. And RELAY_ON = LOW, LOW is 0x0
in the following function I get the error that follows.
CrossingZoneState CheckEntrySensor(uint8_t esp) {
    //esp, short for entry sensor pin
    if (digitalRead(esp) == HIGH)
    {
        state = CrossingZoneState::CROSSINGZONE_CLEAR;
        return state;
    }
    else if (digitalRead(esp) == LOW)
    {
        state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
        return state;
    }
    // if the digital read errs, return the current state so it re-runs
    return state;
};

boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState relayState)    {

    int testInt = 0;
    if (relayState == RelayState::RELAY_OFF)
    {
        testInt = 1;
    }
    digitalWrite(relayNumber, relayState);
    if (digitalRead(relayNumber) == testInt) {
        return true;
    };
    return false;
};

I tried having RelayState be an enum class as well but was getting similar type errors. Here is the error from VS2015 with the code shown above.

Compiling debug version of 'ModelRRXingStateMachine' for 'Arduino/Genuino Uno'
  ModelRRXingStateMachine.ino:11:55: error: 'RelayState' has not been declared
  :boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState relayState)
  ModelRRXingStateMachine.ino:2:1: error: 'CrossingZoneState' does not name a type
  :CrossingZoneState CheckEntrySensor(byte esp)
  Error compiling project sources

I'm not a professional programmer and am new to C++, usually writing in C# or VB.Net so I'm not sure what the compiler is looking for here, both enums are declared and one is declared with a type. Also, the VS code editor is showing no errors, the errors shown above show up in the error window when I try to build.

is this all in the .ino? the sketch preprocessor may be reordering the declarations and mucking things up.

I am using Visual Studio Professional 2015 and the Visual Micro add-in for Arduino, not the Arduino IDE

and yes, all this code is from the .ino file

The IDE automatically puts forward declarations for methods at the top of the file, conveniently before any types you make get defined. The VS add-in might do it too so everything compiles the same. Moving the code to a separate .h file and including that file would stop it from reordering things if that were the problem.

The solution was to move the enum declarations to a header file, due to the fact this was a VM add-in issue which will be resolved once they've implemented arduino version 1.6.8.
Adding this code to a header file and removing it from the main file resolved the issues and the code builds and runs.
// ModelRRCrossing.h

#ifndef _MODELRRCROSSING_h
#define _MODELRRCROSSING_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif
#pragma once
// Arduino Digital I/O pin numbers for MEGA
//note: digital pins 30-45
//MEGA is a MUST for this project
enum {
    Relay1 = 30, Relay2 = 31, Relay3 = 32, Relay4 = 33, Relay5 = 34, Relay6 = 35,
    Relay7 = 36, Relay8 = 37, Relay9 = 38, Relay10 = 39, Relay11 = 40,
    Relay12 = 41, Relay13 = 42, Relay14 = 43, Relay15 = 44, Relay16 = 45
};

enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
enum class CrossingZoneState : uint8_t {
    CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
    CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
};

#endif

For one thing, you are using the variable state without defining it. Moreover, you have not declared the functions CheckEntrySensor() and throwRelayAndCheckStatus() . When you define a function without first declaring it, the arduino preprocessor builds its own declarations, but often does so in a defective way. This is one of the idiosyncracies of the arduino environment versus a plain C++ compiler.
The following compiles:
enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
typedef enum RelayState RelayState_t ;

enum CrossingZoneState {
    CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
    CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
};
typedef enum CrossingZoneState CrossingZoneState_t ;

CrossingZoneState_t CheckEntrySensor(uint8_t esp) ;
boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState_t relayState) ;

CrossingZoneState_t CheckEntrySensor(uint8_t esp)
{
  CrossingZoneState_t state ;
    //esp, short for entry sensor pin
    if (digitalRead(esp) == HIGH)
    {
        state = /*CrossingZoneState_t::*/CROSSINGZONE_CLEAR;
        return state;
    }
    else if (digitalRead(esp) == LOW)
    {
        state = /*CrossingZoneState::*/CROSSINGZONE_OCCUPIED;
        return state;
    }
    // if the digital read errs, return the current state so it re-runs
    return state;
}

boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState_t relayState)    {

    int testInt = 0;
    if (relayState == /*RelayState::*/RELAY_OFF)
    {
        testInt = 1;
    }
    digitalWrite(relayNumber, relayState);
    if (digitalRead(relayNumber) == testInt) {
        return true;
    };
    return false;
}

Or, if you want to avoid the use of typedef, you can use the following:
enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
enum CrossingZoneState: uint8_t {
    CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
    CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
};

enum CrossingZoneState CheckEntrySensor(uint8_t esp) ;
boolean throwRelayAndCheckStatus(uint8_t relayNumber, enum RelayState relayState) ;

enum CrossingZoneState CheckEntrySensor(uint8_t esp) {
    enum CrossingZoneState state ;
    //esp, short for entry sensor pin
    if (digitalRead(esp) == HIGH)
    {
        state = CROSSINGZONE_CLEAR;
        return state;
    }
    else if (digitalRead(esp) == LOW)
    {
        state = CROSSINGZONE_OCCUPIED;
        return state;
    }
    // if the digital read errs, return the current state so it re-runs
    return state;
}

boolean throwRelayAndCheckStatus(uint8_t relayNumber, enum RelayState relayState)    {

    int testInt = 0;
    if (relayState == RELAY_OFF)
    {
        testInt = 1;
    }
    digitalWrite(relayNumber, relayState);
    if (digitalRead(relayNumber) == testInt) {
        return true;
    };
    return false;
}

It is good that you are able to get the code to compile, but seems this is a Q&A site and a few months/years from now other inexperienced ones my become lazy(Ctrl+c Ctrl+v) and not gain any understanding about the cause or solution to there problems. Could you thus elaborate on why it compiled and also maybe mentions of general use of enums in this way.

Type def is a C structure and is not standard in C++11 and forward and is not recommended for enums any longer.

A lot of code compiles, that doesn't make it right or effective

@RSM: You are right.

a) In function CheckEntrySensor(), the variable state was used without being defined.

b) The functions were used without a declaration.

You can edit stuff like that into the answer

If you don't want to use typedef, you can omit the typedef declarations and replace all instances of xxx_t with enum xxx . I guess in C++11 it would be sufficient to use xxx (without enum), but, to my knowledge, arduino is NOT C++11.

@dinotom : true, the fact that some code compiles doesn't make it right or effective. However it is always better than code that does not compile at all, regardless of its writer's rep on SO.

@Alphonsos_Pangas...state is declared, just not shown in the snippets I posted, so that wasn't the issue. See my answer below as this was Visual Micro add-in specific issue, solved with their assistance.

authors: Владимир Шамов


text:
How to declare a pointer for arduino neopixels library so I can set it up in the setup function with dynamic variables?
I am using NeoPixel strips, and I want to be able to declare a pointer to them, but not initialize them until the setup function (because they will initialize with certain variables only made available in setup).
For simpler data types, I am just doing:
int totalNumColors = 4; //number of colors user can cycle through`
uint32_t* colorArray = new uint32_t[totalNumColors];
void setup() {
  for (int i=0;i<totalNumColors;i++){
    colorArray[i] = totalColorArray[i];
  }
}

How do I do this for NeoPixel strip intializers? I tried:
Adafruit_NeoPixel* pixels = new Adafruit_Neopixel;`

but I get the error:
expected type-specifier before 'adafruit neopixel'

I am trying to wrap my head around using pointers for Neopixels -- I am not a C expert but trying to learn as I go. I went over some documentation (read some sites, watched some YouTube videos) and understand the basics of pointers and I am able to use then in more basic ways. But I am confused how you use pointers when setting up Neopixels. Would you mind sharing some of your code so I can get an idea how the Neopixels are setup and how you are using them? I would greatly appreciate it. David

You can assign the pointer to NULL, and in the setup function give it a value. Note you have to add () for the arguments, even if there are none like in this case. Also you have to include the library (but probably you did but not added in your question).
#include "Adafruit_NeoPixel.h"

Adafruit_NeoPixel* pixels = NULL;

void setup()
{
  pixels = new Adafruit_NeoPixel();
}

I did include the library, but thanks, yes - this is exactly what I was looking to do.

Good luck with your project.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Calling external function from a class function
I'll try to explain my need:

I have a generic library I created, called myIOT.h.
This class have a pre-configured  MQTT and wifi setup.
Inside this library there is a mqtt_callback function, for all generic commands, such as boot_time and connection_status.
BUT, this library serves in several of my iot device's code, that each one has a few more mqtt commands, that is tailored just for s specific device, and I looking for a way that iot.mqtt_callback(ext_mqtt_func) will get as parameter a local ( which belong to the sketch and not to the library ), that will have the additional code needed.

I'll try to explain more clearly:
void myIOT::mqtt_callback(ext_mqtt_func){
if (a == true ) {
do something

};

else {

ext_mqtt_func()); // calling another fucntion that belongs to sketch and not library

}

Note that it is better to use if (a) than comparing a boolean with true or false. If you name a better so it is clear it is a boolean it is better maintainable.

@MichelKeijzers it is a string compare function to set a MQTT comman

Yes, you can do it.
You pass function pointer as function parameter.
See this stackoverflow question:
https://stackoverflow.com/questions/2582161/c-function-pointer-as-parameter

thank you, it works great. Since it have to a string using a MQTT, this ext_fuct needs as well to pass this string - and the explanation above is for a no-arg function, so I did upgrade it to be  typedef void (*cb_func)(char msg1[50]) that passes its string ( and it works great ), but I would rather pass it as a pointer to that string ( which fails )


text:
I can't seem to receive data to the ArduinoStudio serial monitor on ubuntu 14.04
I'm using the Arduino Starter Kit so I have a Uno R3 and going through the examples I'm trying to read temperature data from my controller in Arduino Studio.
In essence my problem can be reduced down to
void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.print("stuff");
}

Which I'd expect to keep printing "stuff" on the serial monitor.
(In practice I'm running this exact code but all the temperature-reading going on feels irrelevant to my problem, I'm simply mentioning it because I can observe that mye LEDs light up when the temperature rises so I know the code is uploaded and running on the Duo).
I'm not seeing any errors in the studio console, and if I connect using gtkterm or screen I can see data being sent so the problem seems to be isolated to the AndroidStudio serial monitor itself.
I'm running Ubuntu 14.04 and I've connected via USB on /dev/ttyACM3.
I tried running

stty -F /dev/ttyACM3 cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

as suggested here and I also tried with baud 115200, taking care to also change the value in my setup function.
I also ran

chmod a+rw /dev/ttyACM3

But I'm still not seeing any errors or output. How do I proceed to debug this issue?
Running ls -l /dev/ttyACM* gives

crw-rw---- 1 root dialout 166, 0 feb.  20 14:22 /dev/ttyACM0
crw-rw---- 1 root dialout 166, 1 feb.  20 14:22 /dev/ttyACM1
crw-rw---- 1 root dialout 166, 2 feb.  20 14:22 /dev/ttyACM2
crw-rw-rw- 1 root dialout 166, 3 feb.  20 14:30 /dev/ttyACM3

Test GtkTerm or PuTTY.

@MikaelPatel Thanks, that should help me isolate the problem at least :)

What's the output of "ls -l /dev/ttyACM*"?

@Avamander I've edited that into the question, along with what I'm getting from gtkterm

If it matters, my user is in the dialout group

Try putting the string "stuff" into double quotes instead of single quotes.

@Avamander Oh.. yeah.. double quotes. That's embarassing. It's still not showing in the IDE but now I get sensible data with both screen and gtkterm. Oh my... I guess the problem with the AndroidStudio still persists but since it's working with the terminal I guess I should go see if they have an issue tracker somehere. Thanks, if there's a close-reason here for a problem that can no longer be reproduced or a simple typographical error I guess it won't be misplaced here.

Android Studio issue? Have you solved your issue you mentioned in the question or not?

It's not solved as I still don't see any data in the serial monitor but I've isolated the problem after fixing the quotes and using gtkterm to confirm that the Arduino is indeed sending data. I'm still diggin into why the IDE doesn't show it but I suspect it's not an error I've done but rather an issue with the software itself.

Edited to clarify that the issue has been narrowed down by the help received in comments.

What version of the IDE are you using? Also, can you add the output of an lsusb?

Are you 100% sure that your arduino is seen on your computer as /dev/ttyACM3 ?
if you unpug the arduino, run "sudo dmesg -C", plug the arduino and then issue "dmesg" what do you get back ?
My Arduino nano clone (with ch340) shows up as /dev/ttyUSB0.

@louigi600 I don't own either the arduino itself or the computer I was using any more, but if someone else has the same issue I encourage them to try that and provide information.

this is how my ch340 based nano clone is seen on my linux pc:
[14429.560354] usb 1-2.2: ch341-uart converter now attached to ttyUSB0
I don't have any genuine arduino products but I suspect you may have been looking at the wrong device file

What serial port are you running on?

I'm voting to close this old unresolved question because the asker reports in comments that  "I don't own either the arduino itself or the computer I was using any more" which means that it will be impossible to ever conclusively resolve this issue.

By default, on a linux system without specific
udev binding rules to rename the device into something non standard, the FTDI driver should map the usb to serial port on /dev/ttyUSB* and not to /dev/ttbACM*. I suspect that you were just looking in the wrong place.
I think it defaults to /dev/ttyUSB* for any usb to serial dongle:
usb-serial.c:   usb_serial_tty_driver->name = "ttyUSB";

In order to make sure you're looking in the correct device file run "sudo dmesg -C" priot to plugging in the Arduino, and subsequently just 'sudo dmesg" to see where teh usb to serial converter was attached. You should see a message much like this:
ch341-uart converter now attached to ttyUSB0
where the ch341-uart is replaced by what your arduino has (most likely FT232'ish)

This is probably not applicable.  The post claims to be using an Uno R3, which does not have an FTDI but rather has a custom USB serial implementation in an ATmega16u2 which will map as a ttyACM device  not a ttyUSB one - that only happen on boards using other USB serial solutions, like older Arduinos and assorted clones and compatibles.

Ok but still doing the dmesg thing will tell you which is the correct device that linux is assigning to the arduino .... it won't show ch340 or FT* .... but it will still report what's the assigned character special file in /dev .


text:
Powering an USB to Serial from USB
I am creating a PCB which is a modification of the Arduino on a breadboard. I am intending to buy an USB to Serial breakout from Adafruit so that I can upload my sketches to the atmega 328 I'll be using.
However, in order to reduce power consumption (later I want to run my circuit by using some AA batteries), I would like to turn off the USB to Serial breakout. I thought originally about adding a SPST switch to disconnect it when not using it, but I wonder if it is possible to power it from the USB (whenever I connect something) instead of having to connect its VCC header to the circuit's 5v power.
Is it possible to do that? Or is there any other way I to accomplish this that I'm not thinking of?
UPDATE: For clarity sake, I will explain my design choices: I want this circuit to power some peristaltic pumps that work on 12V. Thus, I'm providing 12V for the pumps and using a regulator to lower the voltage to the circuit. I don't see this is a huge problem for power consumption because the circuit will be in low-power 98% of the time, only waking up one minute per hour. Sometimes, it will run on batteries, which is the reason I wanna eliminate the USB-to-Serial. However, when connected to a power adaptor, I want the USB to be available.
All the best,
Francis

Why not make it so you can plug in the usb-to-serial, only when you need it? Add some female headers to the breakout, and some male headers to your board. PS if you want good battery life using the 7805 regulator isn't the best.

@CurtJ.Sampson: Thanks. Do I really need the DTR? On the breadboard link above, they are not using it.

@Gerben: That is a very good idea, actually! Simple and nice. My only concern is that the board will get a bit "taller" than it should be, and it will be harder in case I make a custom case to it. But it is definitely worth considering! As for the 7805, you are right, and I considered it, but the circuit will run on LowPower mode most of the time, so I guess it won't make that difference.

The 7805 has a quiescent current of around 5mA. So that alone will drain an AA in around 20 days. As for the headers. There are also right angled headers. So you can plug in the module from the side.

@francisaugusto: You need DTR only if you want to have the PC auto-reset the Arduino when uploading sketches. If you don't mind having to push the reset button manually when you do this, you can leave off DTR.

This is a good, specific question about how to do a particular thing. However, you mention that your general aim is to reduce power consumption and, in a comment below, that you're supplying 12 V power to the Arduino side of the system. This changes things a lot, and rather than try to deal with that here I suggest you ask another question, giving more details about the whole system (including everything connected to it, and ask the general question about how you can reduce its power consumption.

You might be overthinking this. As Gerben points out in the comments, you might want to consider pluging in the USB to Serial breakout board only when required, instead of making it a permanent part of your prototype.
I do this myself in two ways, depending of what I need.
Option 1:
When I foresee a lot of debbuging through the Serial Monitor, I use a permanent pin header so I can attach and dettach the breakout board easily.
In this case I use a right angle pin header so as to keep a low profile. Like in this Arduino Pro Mini:

Option 2:
When I just need to upload the sketch to the Arduino and I know that I won't be using the breakout board from that moment on, I don't solder the pin header in place.
Instead, I've modified another breakout board using pogo pins (spring test probes):

This modified board is what I use to upload the code to the Arduino without any pin header whatsoever. Something like this (I've taken the picture just for illustrative purposes):

Thanks Enric! Those are very good ideas. I think I will do something on those lines, but I still think that maybe using a button to turn the usb on and off can be a better alternative. That, or running the usb chip by, well, using usb power.

Using separate power supplies at the same time for different parts of your system is a bad, bad idea; you never want two separate power supplies potentially pushing current at each other. Using separate +5V power sources for different chips but sharing a common ground across the device and connecting just data lines is problematic, too; as far as I know it's not trivial to do safely. Unless you really know what you're doing, full isolation between separately powered components is the way to go.
The two parts of the system we're talking about here, the USB-Serial converter and the rest of the system, exchange digital data only, and that at only three points, all of which are unidirectional: serial TX, serial RX and DTR. (DTR, when pulled low by the PC, resets the Arduino). Therefore if we can isolate these links not to exchange current when they communicate, we can separately power the devices on each side of this isolation barrier.
This is actually a common problem in things like power supplies (where we want data from the high-voltage side sent to the low-voltage side but don't want the risk that someone touching the low-voltage side could get electrocuted) and motor control boards (where the motors often use a separate power supply from the controller logic to reduce noise passed into the controller logic). One common solution is to use opto-isolators (also called optocouplers). Typically these use an LED and a sensor looking at it from across a gap; when the LED is lit up by one side, the other side sees it and generates a current.
The 6N137 (as used in this answer) or similar chip should work for this: 10 MHz is plenty of bandwith to run a 115,200 baud serial link. Each opto-coupler would be powered by the receiving side (Arduino for its RX and DTR, USB-serial for Arduino's TX) and on the other side you'd connect data to the VF+ pin and ground to the VF- pin. As per note 1 on page 4, you'll need caps at the power supply inputs, and you'll have to add inverters as well if you use this particular opto-isolator, since it inverts the signal; a 74HC04 will give you six of those. If you want to save a dollar, you could not bother to connect the DTR line and just reset the Arduino manually when you want to upload a program, if that's not too inconvenient.
Consumer warning here: I've not actually built this circuit (though I'd like to give it a try one day), so there could be something I'm missing here. (Hopefully someone more expert than me will speak up if that's the case.)
If you're going to be spending any significant amount of time connected to USB power and your whole system can run on less than 500 mA (the limit of the USB supply from many PCs), you may want to consider powering the entire system from USB while it's connected. This can be done in a way similar to how the Arduino Uno board disconnects USB power when receiving power on Vin: switch it with a comparator and a MOSFET.

Thanks a lot! I will have that in mind. It seems to be that the best option so far is to just put an SPST button on the circuit to turn the board on and off. But I got curious: how do I get power from USB using the adapter I'm planning to use?

That is not easy to do. You could try diodes and mosfets as switches, but one way or the other, there will probably some leakage current. The 6N137 requires power for the receiving signal.
Other common optocouplers might have leakage current in the nA range for the transistor output. That might be possible. Connect the GNDs. The RX and TX via optocouplers. DTR to RESET with 100nF as usual. Maybe you don't need extra inverters when the transistor outputs are used as emitter followers.
Could you make your project with the ATmega328P without the usb-to-serial module ? The Arduino Pro Mini does not have a usb-to-serial either.
Now that I mention the Arduino Pro Mini: Instead of making an Arduino compatible circuit with a ATmega328P, you could also buy a Arduino Pro Mini 8MHz, and remove the voltage regulator and the power led. Then you have the same thing.
That breadboard Arduino tutorial has +5V connected to AREF. Please don't do that. Keep AREF open, or connect a capacitor of 100nF to it to reduce some noise for analogRead.
In the deepest sleep mode, the ATmega328P can run more than a year on three AA batteries. The timer of the WatchDog can be used to wake up.
The voltage of the three AA batteries is directly connected to the VCC of the ATmega328P, without voltage regulator.
A very good tutorial about power saving is this: Nick Gammon about power saving

Thanks @jot! Answering your questions: Yes, I do need the USB-to-serial to be connected, as I'll change the sketches sometimes, and, when connected to power, I want to be able to transfer data from the sensors to a connected RaspPi. When on battery, I want it to be disconnected, and that's why I ask. Since there's some voltage on the USB cable, I wish I could use it instead of the circuit's. My project will use 12V (8AA batteries), so that's why I need the regulator. I will power other connected stuff that requires 12V (before the Voltage Regulator, of course).

As for the AREF, I will do very simple and quick reading. Other than the noise, will it be a problem to connect the 5V to it?

You should have mentioned the 12 V thing in your main post! You definitely want to avoid using the on-board regulator if you're concerned about running for a long time on batteries. That's throwing away far more power than a powered-but-quiescent USB/Serial chip would.

francisaugusto When the internal voltage reference is selected with AREF connected 5V, it will cause an internal shortcut. It's just wrong, don't do it. @CurtJ.Sampson You are so right, powering a ATmega chip with 12V is not low power, and makes this whole question and all answers trivial.

Have a look at this one: https://www.pololu.com/product/2843 It has 200µA quiescent current. I'm not saying that it is a good solution, because we have no know the whole circuit and its function, because everything has changed now that 12V is used.

@CurtJ.Sampson and Jot: I updated the question with a better description. As I explain there, I assume that because I will be running the circuit in lowpower mode 98% of the time, the voltage regulator won't be a big deal.


text:
Using Lego temperature sensor with Arduino
I have Arduino mega and Lego temperature sensor which I would like to connect to the Arduino. I'm trying to use a I2C connection between them, with no luck. I connected the sensor and Arduino referring to the picture below:
I'm using the Wire library for transmitting data. This is my code currently:
#include < Wire.h >
byte ADDRESS=0x98;
byte CONFIG=0x01;
void setup(){
  Serial.begin(9600);
  Wire.begin();
  Wire.beginTransmission(ADDRESS);
  Wire.write(CONFIG);
  Wire.endTransmission();
  delay(100);
}
void loop(){
  Wire.beginTransmission(ADDRESS);
  Wire.write(CONFIG);
 Wire.endTransmission();
  Wire.requestFrom(ADDRESS,2);
  delay(100);
  int avail=Wire.available();
  Serial.println(avail);
  delay(100);
}

I found the config and address values from RobotC drivers for the same sensor. But all I get is zeros. Is there any way i could check for a defect sensor? Is my code correct?

Start with a i2c scanner : http://playground.arduino.cc/Main/I2cScanner

Looks like this is the datasheet for the actual sensor http://www.ti.com/lit/ds/symlink/tmp275.pdf. Reading that and cross referencing with the header file you liked to, should explain how to communicate with it.

I2C scanner helped me to use the correct address, which was different from the one in drivers. Now my sensor is working. Thank you, Jot!

I managed to get it work with the following code:
float getTemp(){
    #define ADDRESS 0x4C
    #define CONFIG 0x00
    float temp;
    Wire.beginTransmission(ADDRESS);
    Wire.write(CONFIG);
    Wire.endTransmission();
    delay(50);
    Wire.requestFrom(ADDRESS,2);
    temp=Wire.read();
    if(Wire.read()==128){
        temp+=0.5;
    }
    return temp;
}

And connect the green wire to 3.3V, not to the 5V.


text:
Activating a defined macro in a class from main.cpp
Sorry if this question been asked. I'm trying to activate certain function in a class using a macro defined in the class from main.cpp. I'm using jrowberg MPU6050 library if that matters.
main.cpp
#include "gyro.h"
gyro gyro(Serial);
#define OUTPUT_READABLE_EULER

void setup(){
...
}
void loop(){
...
}

gyro.cpp
  #include "gyro.h"
  #ifdef OUTPUT_READABLE_EULER
      // display Euler angles in degrees
      mpu.dmpGetQuaternion(&q, fifoBuffer);
      mpu.dmpGetEuler(euler, &q);
      serial_.print("euler\t");
      serial_.print(euler[0] * 180/M_PI);
      serial_.print("\t");
      serial_.print(euler[1] * 180/M_PI);
      serial_.print("\t");
      serial_.println(euler[2] * 180/M_PI);
  #endif

If I define OUTPUT_READABLE_EULER in gyro.h, it works. But I want to do it from main.cpp.

Try putting the define before you include the file.

You cannot not, but also you should not try to define a macro in a cpp file and use it in another cpp file.
Instead, you have to define it in a h (header) file, which is included in both cpp files.
Why would you define it in main.cpp or main.h anyway if you don't use it in those files?
You have mainly three options:

Define it in gyro.h so you include it in gyro.cpp where you use it. You can later use it in other files as well.
Define it in gyro.cpp so you can use it only in that file. This prevents the macro being used in other files (which can be safer).
Define it in a separate file, e.g. euler.h and include this header file everywhere you need it.

See also Juraj's comments below.

this applies if the define should by in a source file. this kind of defines is usually set on compiler command line as -D. the Arduino IDE doesn't have -D define configuration for a project.

@Juraj in that case it could be an option to create a specific header file with those macros (one in this case) and include them in every file.

yes. it is the way if the macro should be used only in the sketch's files (project). inconvenient is it for libraries. then the user must go to library folder and a modifiy a file there, but then it applies for all projects. if the setting is boards specific or one has a customized board definition for a project, then -D can be set in boards.local.txt as build.extra_flags. for example in Eclipse -D can be set in project's settings

@Juraj Thanks for that additional info. However, that doesn't work in the IDE I guess ?(as the Arduino IDE is not eclipse based)


text:
Dynamic allocation/ Pointer to Pointer to update an Array containing parameter
topicArray defined as follows:
const char* msgTopic = "Home/Messages";
const char* groupTopic = "Home/All";
char* deviceName = deviceTopic;
const char* topicArry[2] = {deviceTopic, groupTopic};

But deviceTopic can be changed during code run, and I wish that topicArray containg deviceTopic will have the correct value after deviceTopic has changed.
What is the right way doing so ?

don't make the array 'constant' with const and you can change the values (pointers) it contains

@Juraj I did remove const ouf of array and all other variable, but still array is not changed

do you change it?

as said " I did remove const"

to be able to set the value topicArray[0] = "something"

You may try something like this:
const char* topicArry[2] = {NULL, groupTopic};
const char** const pDeviceTopic = &topicArry[0];
#define deviceTopic (*pDeviceTopic)

Arguably not very elegant, but now when you assign, e.g.
deviceTopic = msgTopic;

you are actually writing into topicArry[0].


text:
How to use parameteric function arguments
I have a function defined as follows:
void turn_leds_on(int col_indx, int bright_1 = BRIGHTNESS, int del_1 = 5, bool dir_1 = true )
This function is called using MQTT from user to define led's properties, which only first is mandatory ( has no default value ) - MQTT format is : 1,50,40,0, but can be 1,10.
Now, to implements this - I read MQTT message and store os into parameters as follows:
splitter(incoming_msg, 4, parameters); // read 4 parameters

when it defined as:
    void splitter(char *inputstr, int x, char *output[]) {
  char * pch;
  char *pnts[x];
  int i = 0;

  pch = strtok (inputstr, " ,.-");
  while (pch != NULL)
  {
    output[i] = pch;
    pch = strtok (NULL, " ,.-");
    i++;
  }
}

The problem starts when the user enters only 2 parameters and when passing parameters into :
if ( atoi(parameters[0]) <= tot_colors - 1 && isDigit(*parameters[0])) { // color num
      if (atoi(parameters[1]) <= 100 && isDigit(*parameters[1])) { //brightness
        if (atoi(parameters[2]) <= 100 && isDigit(*parameters[2])) { //delay between leds
          if (atoi(parameters[3]) <= 1 && isDigit(*parameters[3])) { //direction
            turn_leds_on(atoi(parameters[0]), atoi(parameters[1]), atoi(parameters[2]), atoi(parameters[3]));

So the question is: how to pass arguments, and on the other hand when they are not given, to use their default values as defined inside the function?

https://en.cppreference.com/w/cpp/utility/variadic

Hint: Use sscanf and let it scan, convert and check number of parameters.

turn_leds_on(3); will be compiled as turn_leds_on(3, BRIGHTNESS, 5, true);

@Juraj - that is correct, and not what i'm trying to change, but how it when parameters[i] is not given

you can do nothing if don't know the count of items filled in the array

@Juraj - I know they are 4, but is there a way to define parameters[i]=NULL, that when it is entered to the function, and not be an actual value, the defualt arguments will be considered

yes a pointer to char array can be NULL

So I checked, but default arguments were not used.


text:
Help What am I doing wrong? Matrix Led
I'm new and im trying out the Matrix LED
heres my code
#include <LedControl.h>

LedControl lc = LedControl(12, 11, 10, 1);

unsigned long delayime = 100;

void setup()
{
  lc.shutdown(0, false);
  lc.setIntensity(0, 8);
  lc.clearDisplay(0);
}

void writeArduinoOnMatrix()
{
  byte H[10] = {8, 8, B01100110, B01100110, B01100110, B01111110, B01111110, B01100110, B01100110, B01100110};
  byte E[10] = {8, 8, B01111110, B01111110, B01100000, B01111110, B01111110, B01100000, B01111110, B01111110};
  byte L[10] = {8, 8, B01100000, B01100000, B01100000, B01100000, B01100000, B01100000, B01111110, B01111110};
  byte O[10] = {8, 8, B01100000, B01100000, B01100000, B01100000, B01100000, B01100000, B01111110, B01111110};

  lc.setRow(0, 0, H[0]);
}

I keep on getting this error no matter what.
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Uno.
Help What am I doing wrong?

Welcome to Arduino SE! Can you post the complete code, with thevoid loop{...} function? Also post the complete error as Michel has requested below.

Unfortunately I think you are missing the actual error message and have just copied the result.  I suspect if you scroll back up through the output it will say loop is missing.
All Arduino sketches (well almost all) have to have setup() and loop() functions.  The underlying 'stuff' will call setup() once and loop() repeatedly.
I hate global variables, but in this case I would be tempted to move those arrays out of the function and make the constant global values.  That way they will be in memory as the Arduino boots and you won't have to waste processor cycles setting them up.
It may be a silly question, but are you using the right hardware?  This might help check that http://playground.arduino.cc/Main/LedControl

ok, yes I'm using the right hardware and the code...

I am using the right hardware, screw the code i made a new one can u check it for me?
#include <LedControl.h>
int DIN = 12;
int CS = 11;
int CLK = 10;
byte H[8]= {(0x66,0x66,0x66,0x7e,0x7e,0x66,0x66,0x66)};
byte E[8]= {(0x7e,0x7e,0x60,0x7e,0x7e,0x60,0x7e,0x7e)};
byte L[8]= {(0x60,0x60,0x60,0x60,0x60,0x60,0x7e,0x7e)};
byte O[8]= {(0x7e,0xff,0xc3,0xc3,0xc3,0xc3,0xff,0x7e)};
LedControl lc=LedControl(DIN,CLK,CS,0);
void setup() {
// put your setup code here, to run once:
lc.shutdown(0,false);
lc.setIntensity(0,15);
lc.clearDisplay(0);
}
Would this work?

A ld error normally means a link error, i.e. you call a function that is not defined.
Are you sure it is the complete error? That it does not show which function you miss?
Also, I notice:

function writeArduinoOnMatrix never seems to be called, or you didn't post the full code?
In writeArduinOnMatrix, you declare 4 arrays, but you use only one (H).
Typo in: unsigned long delayime = 100;  ... this should be delayTime

If the posted code is complete, then it is missing the loop() function, which might explain calling of an undefined function, as the rest of the runtime should call loop() after setup().


text:
Current consumption of a buzzer
I want to use the buzzer KPEG2000 in my Arduino application. I would like to know if a GPIO can directly drive this buzzer, without destroy the uC (a GPIO can deliver 40 mA max). In the datasheet, we can find the current consumption under 12 volts (40 mA), but if I decrease the driving voltage to 5V, will this buzzer use more or less then 40 mA ?
https://docs-emea.rs-online.com/webdocs/07a8/0900766b807a8e16.pdf
I already tried to make this buzzer work on an Arduino, and it works. But I would like to know if plugging this buzzer directly to the Arduino will not destroy it.

In the datasheet I read 14 mA @ 12V, which is below the recommended current of a GPIO pin of 20 mA.
Note that 40 mA for a GPIO pin is the max current, recommended is 20 mA. But 14 mA is way less.
To see if it changes for 5V, try connect it without an MCU (directly to a 5 V adapter/USB/breadboard power) and measure the current using a multimeter.
In case it uses more than 20 mA @ 5V, than use a transistor/mosfet to drive the buzzer.
In case you want to have the buzzer at full power, connect a VCC 5V power rail pin to a boost converter, which is controlled by a transistor/mosfet controlled by a GPIO pin.
Thus
Arduino VCC 5V -> Boos converter to 12 V -> Transistor/Mosfet -> Buzzer -> GND
                                                 ^
                                           Arduino GPIO pin

Point of clarification: You shouldn’t use a boost converter on a GPIO pin, only on a 5V supply rail. Boosting voltage takes a lot of current. >2.4x more.

@Duncan Yes I meant that (after a transistor), I will make it more clear.

Yeah, I assumed that's what you meant, but remember that lots of newbies read these boards.

@DuncanC True indeed, thanks for the notification.

If this is a piezo buzzer they typically work over a wide range of voltages and use very little current. I've seen them with specs for an input voltage ranging from 3 to 18v.
You could likely drive a piezo buzzer directly from a GPIO line without problems.


text:
How to connect a a three state switch (ON-OFF-ON) to arduino?
I have created a car that can detect obstacle and change its direction, but now I want to add a bluetooth module to control it and I want to switch between the two circuits using a three state switch (ON-OFF-ON), so how can I do that and how can I upload two different codes on the arduino.
Here is a fritzing diagram, (the pins for the bluetooth will be changed).
Sensor:

Bluetooth:

And here is the code for the sensor:
   #define echopin  8 // echo pin
   #define trigpin 9 // Trigger pin

   int maximumRange = 30;
   long duration, distance;

    void setup() {
        Serial.begin (9600);
        pinMode (trigpin, OUTPUT);
        pinMode (echopin, INPUT );
        pinMode (4, OUTPUT);
        pinMode (5, OUTPUT);
        pinMode (13, OUTPUT);
        pinMode (6, OUTPUT);
        pinMode (7, OUTPUT);
    }

    void loop ()
    {
        digitalWrite(trigpin,LOW);
        delayMicroseconds(2);

        digitalWrite(trigpin,HIGH);
        delayMicroseconds(10);

        duration=pulseIn (echopin,HIGH);

        distance= duration/58.2;
        delay (50);
        Serial.println(distance);
    }

        if (distance >= 30 ){
            digitalWrite(4,HIGH);
            digitalWrite(5,HIGH);
            digitalWrite(6,LOW);
            digitalWrite(7,LOW);
            delay (200);
        }
        else if (distance >=15 && distance <= 25) {
            digitalWrite (4,HIGH);
            digitalWrite (5,LOW);
            digitalWrite (6,LOW);
            digitalWrite (7,LOW);
            delay (1000);
        }
        else if (distance < 15){
            digitalWrite (4, LOW);
            digitalWrite (5, LOW);
            digitalWrite (6,HIGH);
            digitalWrite (7,HIGH);
            delay (1000);
            digitalWrite (4,LOW);
            digitalWrite (5,HIGH);
            digitalWrite (6,LOW);
            digitalWrite (7, LOW);
            delay (1000);
        }
    }

Please write in the most details and write any code as I am still a beginner.

Stackexchange is not a free coding service. The questions and answers should be useful to more than one user. You did the first steps right and supplied schematics and code. But you cannot expect to get your code written here.

As stated by st2000, it's not common practice to have two separate programs running on one microcontroller.
The solution is simple, use the switch to "switch between" behavior.
if(switch is on){
  //Automatic
}else{
  //Bluetooth
}

You should also use functions, to make your code more readable.
This might work:
#define echopin  8 // echo pin
#define trigpin 9 // Trigger pin
#define switchPin 10

int maximumRange = 30;
long duration, distance;

void setup() {
  Serial.begin (9600);
  pinMode (trigpin, OUTPUT);
  pinMode (echopin, INPUT );
  pinMode (4, OUTPUT);
  pinMode (5, OUTPUT);
  pinMode (13, OUTPUT);
  pinMode (6, OUTPUT);
  pinMode (7, OUTPUT);

  pinMode(switchPin, INPUT_PULLUP);
}

void loop ()
{
  if (digitalRead(switchPin)) { //If the switch is pressed.
    automaticLoop();          //Do the automatic control.
  } else {                   //If not pressed.
    bluetoothLoop();          //Do the bluetooth control.
  }
}

void measureDistance() {
  digitalWrite(trigpin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigpin, HIGH);
  delayMicroseconds(10);

  duration = pulseIn (echopin, HIGH);

  distance = duration / 58.2;
  delay (50);
  Serial.print("Distance is: ");
  Serial.println(distance);
}

void automaticLoop() {
  measureDistance();

  if (distance >= 30 ) {
    digitalWrite(4, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    delay (200);
  }

  else if (distance >= 15 && distance <= 25) {
    digitalWrite (4, HIGH);
    digitalWrite (5, LOW);
    digitalWrite (6, LOW);
    digitalWrite (7, LOW);
    delay (1000);
  }
  else if (distance < 15) {
    digitalWrite (4, LOW);
    digitalWrite (5, LOW);
    digitalWrite (6, HIGH);
    digitalWrite (7, HIGH);
    delay (1000);
    digitalWrite (4, LOW);
    digitalWrite (5, HIGH);
    digitalWrite (6, LOW);
    digitalWrite (7, LOW);
    delay (1000);
  }
}

void bluetoothLoop() {
  //Code for bluetooth.
}

While a simple concept, having 2 different selectable programs (sketches) in 1 Arduino is not the way the Arduino paradigm works.
Most Arduinos contain an Atmel processor.  This processor contains a boot loader program.  This program only knows how to deal with 1 other program (the sketch).  In order to switch between 2 different programs (sketches) you would have to re-write this boot loader.
But you still have to deal with the creation of the 2nd program.  In order to do this you need to change the SDK used to create the 2nd program (sketch).  Specifically, you need to link the 2nd program (sketch) so that it can operate out of a different location in the Atmel processor's memory.
It would be far easier to combine the two programs (sketches) into a single program (sketch).  Then use your switch to change the program's (sketch's) behavior.

The question ends with: I am still a beginner., I believe your answer is unnecessarily "technical".

I'm trying to give you some more general advice.
How to combine two Arduino sketches into one
There is no general rule, how to do this. But there are some common problems to solve.

Code has to be merged for setup and loop independently
You can have only one setup() and one loop() when finished.
If there are variables with same names in both sketches, you have to rename those in one of them.
If you operate with delays, be aware, that delays sum up and retard processing of your loop accordingly.
Having your code merged in most cases you need additional variables to transfer information from one code part to another.

How to use two different hardware setups with one Arduino
There are some general rules, too:

Except for some meticulously and intricately designed electronics, you can use each port only once. You have to move hardware to another port if they are conflicting.
If you run out of ports, you may have to use port expanders or some logic circuitry to gain more inputs and outputs
Check if your hardware does not overload your arduino power supply. some shields and modules can easily suck up the available power.

authors: Максим Парфёнов


text:
Interruption triggered twice when set to FALLING
I have a simple sketch with a button that triggers an interruption set to happen when the button pin goes from HIGH to LOW. It has debouncing so no repetitions happen when the button is pressed, but sometimes when releasing the button the interruption also fires. Why would that be? Shouldn't the debouncing take care of any micro-rising during the release of the button?
volatile int contador = 0;
int n = contador;

long t = 0;
void setup() {

    pinMode(2, INPUT_PULLUP);
    attachInterrupt( 0, incrementaContador, FALLING);
}

void loop() {
    if (n != contador) {
        n = contador;
    }
}

void incrementaContador() {

    if ( millis() > (t + 50) ) {
        contador++ ;
        t = millis();
    }
}

This same code works correctly when set to LOW instead of FALLING.

Shouldn't the debouncing take care of any micro-rising during the release of the button? - That depends on the debouncing. Schematic please?

Also if you think that "if" in your ISR is good debouncing you're sorely mistaken.

Think about what happens. You press the button, and the ISR triggers on each bounce. It counts once because all the bouncing happens within 50ms. Then, say 100ms later, you release the button. Again bouncing happens, and the ISR triggers on each bounce, and one of them within a 50ms window gets counted. You have no distinction between rising bounce and falling bounce. It's all up-down-up-down-up. The real thing you should be looking for is the final position that hasn't changed for a while.

Thank you for the reply @Majenko. The schematic is just a button attached to pin 2 and ground. I forgot to mention that this code works perfectly when the interruption is set to trigger on LOW instead of FALLING. I checked to see if incrementing the delay in the ISR would help and with 500ms it debounces also the releasing of the button. But why the difference between the two modes. Does FALLING also trigger when 0v is not reached?

This question seems to have been abandoned.

but sometimes when releasing the button the interruption also fires

Yes, well when you release the button it may also bounce. In other words OFF/ON/OFF so that will count as a press. A capacitor over the switch might be better.
Example: