text:
Stepper Motor Button Press
I am having difficulties programming what should be a simple sketch that gets my stepper motor to run at one step per second indefinitely at the press of a button and then stops at the press of another button. I am using the Bounce2.h and accelstepper.h libraries and have been unable to figure out how to do it. Any help would be greatly appreciated, and as for hardware I am using a NEMA 23 High Torque Stepper Motor connected through a M542T Motor Driver powered by a Switching Power Supply and running on an Arduino UNO.
Attatched find my code, and thank you so much for the help!
#include <Bounce2.h>
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <AccelStepper.h>

AccelStepper stepper(1, 9, 8); // initiate stepper motor

//int buttonPresses = 0;
const byte ButtonPin = 10;
const byte LedPin = 13; // for debugging and visualization

Bounce button;

void setup() {
  Serial.begin(9600);
  button.attach(ButtonPin);
  pinMode(LedPin, OUTPUT);
  stepper.setSpeed(1);
}

void loop() {
  if (button.rose()) {
    stepper.runSpeed();
    digitalWrite(LedPin, HIGH);
    //    buttonPresses++; // count presses of button and print to monitor
    //    Serial.print("Number of Button ");
    //    Serial.print("Presses = ");
    //    Serial.println(buttonPresses);
  }
  else {
    button.update();
    digitalWrite(LedPin, LOW);
    if (button.fell()) {
      stepper.stop();
    }
  }
}

As of now, a button press runs the motor at 1 step/second, but a second press or any subsequent presses thereafter do nothing to stop the motor. Thanks so much!
!!EDIT!!
Upon adding a boolean buttonState and setting it to LOW in the setup and changing my void loop() code to look like:
void loop() {
  button.update();
  if (button.rose() == true && buttonState == LOW) {
    stepper.runSpeed();
    digitalWrite(LedPin, HIGH);
    buttonState = HIGH;
  }
  else {
    if (button.fell() == true && buttonState == HIGH) {
      stepper.stop();
      buttonState = LOW;
    }
  }
}

I know get a step every button press. Just thought it may help in answering.
EDIT 2
So I I tried pulling the runSpeed() out of the loop and adding                                                            if (buttonState = HIGH){stepper.runSpeed();}
but that now just runs the stepperMotor constantly and at variable speed and will not turn it off?
EDIT 3 and Working Code
Thank you Janw for the help. I realized my fault in calling the runSpeed function within the if statement. Further, I also needed to change button.fell() to button.rose() since button.fell() returns true when the button is released, so basically I was stopping the motor everytime I let go of the button. Here is the final, and working void loop() in case anyone runs into a similar problem in the future:
void loop() {
  button.update();
  if (button.rose() == true && buttonState == LOW) {
    digitalWrite(LedPin, HIGH);
    buttonState = HIGH;
  }
  else {
    if (button.rose() == true && buttonState == HIGH) {
      stepper.stop();
      buttonState = LOW;
    }
  }
  if (buttonState == HIGH) {
    stepper.setSpeed(1);
    stepper.runSpeed();
  }
}

You will probably get only 1 step each button press because your runSpeed() is within the if (button.rose() == true && buttonState == LOW)-statement.
The runSpeed() needs to be called every loop to check if the motor needs to step.
A simple way to change this is to set a boolean to true or false if you check your button and add something like this pseudocode:
if(motorRun == true) stepper.runSpeed();

check edits on initial question I have added some more!

You need == instead of =

Okay I'll try that and see if that does the trick! Thanks!


text:
Run multiple function with different argument/return structure by one function pointer
Edit:
I tried a simple code in Arduino IDE which should've done in the first place instead in doing it in a desktop compiler. Because the results are different by experiment. In the desktop C compiler, it's working and bypassing the code without much problems, just one or two warnings.
But in Arduino IDE, it's not acceptable and gives error.
This is the code:
// functions
void function1(uint8_t x, uint8_t y){
  int z = x + y;
  Serial.println("function1\n");
  Serial.println(z);
}
uint8_t function2(uint8_t x, uint8_t y){
    Serial.println("function2\n");
    return 1;
}

void (*fun_ptr)();

void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);
  fun_ptr = (void (*)())function2;
  int value;

  value = fun_ptr(1,2);

}

void loop() {
  // put your main code here, to run repeatedly:

}

Of course you get that warning, since fun_ptr is a pointer to a function without any parameters, while fun1() is a function with a uint8_t parameter. Though it is unclear to me, why you are doing this, since you want to implement your FSM with a switch case. What structure do you want to build with the function pointer? Please show it the the context of your FSM, then we can try give you a good answer

I edited the post.

Note that the only place you call fun_ptr(), you do not supply any argument. Thus it wouldn't even make sense for fun_ptr to reference a function that does expect arguments.

OK, I'm trying to fix the code for now and thanks for the note.

I figured that I can redesign the question from all over, is it a good idea or I better start a new question ?

the auto type, templates/macros, and "void pointers" can be your best friends in this case

yeah, the auto is a C++ type, I'm focusing on C, I don't know why I don't want to use C++ right now ! But what I think most the time is that I want to test everything I can do in C. I want to develop a task manager, now I figured out using array of function pointers + array of bool locks to each related number of function pointer. Managed in the task manager function.

I was able to return data from a void function pointer to a function that returns uint8_t, but my problem now is with a function that has multiple arguments.

It looks to me like you are trying to find the right answer to the wrong
question, typical of an XY problem. In the example you provide in
your own answer, you call the function pointer right after having set
its value. In this case, there is no use to the function pointer, as you
could directly call either read_chars() or write_chars().
Obviously, this is just because that example is excessively simplified.
In a more realistic use case, you would set the function pointer in one
part of the code, and call it in a completely different part. Assuming
the functions and the pointer are defined like this:
void (*fun_ptr)();

void read_chars(uint8_t address) {
    printf("address of array is 0x%.2x\n", address);
}

void write_chars(uint8_t row, uint8_t col, const char *str) {
    printf("[%d, %d]: %s\n", row, col, str);
}

One section of the program sets the pointer:
// Here we learn what action should be performed.
if (should_read()) {
    fun_ptr = (void(*)()) read_chars;
} else {  // should write
    fun_ptr = (void(*)()) write_chars;
}

and a different section calls it:
// Here we have to perform the action.
if (fun_ptr == (void(*)()) read_chars) {
    ((void(*)(uint8_t)) fun_ptr)(1);
} else if (fun_ptr == (void(*)()) write_chars) {
    ((void(*)(uint8_t, uint8_t, const char *)) fun_ptr)(
            1, 1, "messaage0");
}

Note that this second section must know what function it is calling
in order to pass the correct arguments. Hence the if...then test. Note
also that, in order to have valid C++, you must explicitly cast the
function pointer before calling it. This gets very clumsy, and it is a
lot more convenient to store this information (what function should be
called) in an enum rather than a function pointer:
enum {
    CALL_NONE, CALL_READ_CHARS, CALL_WRITE_CHARS
} what_to_call = CALL_NONE;

which would be used like this:
// Here we learn what action should be performed.
if (should_read()) {
    what_to_call = CALL_READ_CHARS;
} else {
    what_to_call = CALL_WRITE_CHARS;
}

// ...

// Here we have to perform the action.
if (what_to_call == CALL_READ_CHARS)
    read_chars(1);
else if (what_to_call == CALL_WRITE_CHARS)
    write_chars(1, 1, "messaage1");

That being said, it is often the case that when it is time to perform
the action, the part of the code responsible of doing so does not know
what arguments should be passed, and this information is more readily
available at the time when when learn what action should be performed.
This is a quite common situation, and a standard C idiom in this case is
to give the function a void * parameter that it will cast to the
appropriate type in order to retrieve the data it needs. For instance:
void (*fun_ptr)(void *);
void *fun_ptr_data;

void read_chars(void * data) {
    uint8_t address = * (uint8_t *) data;
    printf("address of array is 0x%.2x\n", address);
}

struct write_chars_data {
    uint8_t row;
    uint8_t col;
    const char *str;
};

void write_chars(void *data) {
    write_chars_data *d = (write_chars_data *) data;
    printf("[%d, %d]: %s\n", d->row, d->col, d->str);
}

Note that, since write_chars() needs to retrieve multiple parameters
from a single pointer, it uses a pointer to a struct.
Now, the part of the code that learns what should be done has the
responsibility of providing the data:
// Here we learn what action should be performed.
if (should_read()) {
    fun_ptr = read_chars;
    uint8_t *p = new uint8_t;
    *p = 1;
    fun_ptr_data = (void *) p;
} else {  // should write
    fun_ptr = write_chars;
    write_chars_data *p = new write_chars_data;
    p->row = 1;
    p->col = 1;
    p->str = "messaage2";
    fun_ptr_data = (void *) p;
}

The part of the code that has to perform the action now is very simple:
// Here we have to perform the action.
if (fun_ptr)
    fun_ptr(fun_ptr_data);

Note that this code snippet doesn't free the allocated memory. You will
have to figure out who will be responsible for that.
This pattern is quite common in libraries, where the client (the user of
the library) wants an action to be performed, but the library is
responsible for performing that action at the right time. The client
would then provide the library a pointer to a function that accomplishes
the action (called a “callback”), together with a generic pointer to the
data needed by the callback. The use of a generic void * pointer makes
sense, because the library cannot know what kind of data the callback
will need.
In your case, since you know what kind of data you may need, you could
use a pointer to an union instead of a generic pointer:
union fun_data {
    uint8_t address;  // for read_chars
    struct {          // for write_chars
        uint8_t row;
        uint8_t col;
        const char *str;
    };
};

void (*fun_ptr)(fun_data *);
fun_data *fun_ptr_data;

A more idiomatic C++ style would be to pack together the callback
function and its data into a “functor”, i.e. an object that can be
called like a function, and can also store the data it needs. You would
then use inheritance in order to create specific functor types while
calling a generic one.

@R1S8K: 1. You can have the callbacks return a number if you want, but that has to be done consistently: all the callbacks should return the same type, and the pointer should be consistent with their signature. You should not need to typecast when assigning or using the function pointer. 2. The issue with your answer is not that it doesn't work. It is that it is fragile and bad practice. Being illegal C++, it can very well work on one platform/compiler combination, and fail on the next one.

I assume, that the fun_ptr points to the different service functions to do some kind of animation other other long running tasks on your display, thus you want to repeatedly call them in a structured way.
What you are currently doing will not really work. When you call a function, you need to provide its arguments. That's the same for a function pointer. You cannot call a function, that demands parameters, without any parameters. While you can still set a function pointer of type (void (*)(void*) to a function of type (void (*)(uint8_t)), the compiler warns so, because you still cannot call the function without any parameter. If you are trying to do so, you will still get an error of too few arguments to function ....
I see 2 ways to go from here:

You could overload your functions, so that a version without any parameters exists. Like this:
  void foo(uint8_t i){Serial.println(i);}
  void foo(){foo(10);}

With 10 being the value, with which the function should be called, when you provide no parameters. You can of course also use variables or function calls here, to actually get that value for the parameter i. Then you can use the pointer to call that function:
  void (* p)(void);
  p = &foo;
  p();

The assignment of the pointer will choose the version of the function without any parameters out of the overloaded pool of this function, since that matches the type of the pointer. Note, that I removed the * from the void parameter definition. I don't understand, what that would mean anyway (pointer to void?). The function pointer p() can now be called without any parameters, since it points to a function without any parameters.

You could ditch the function pointer and use a simple switch case statement with a state variable (which holds some identifier for the corresponding function), to call the correct service function. I won't go into detail here, since that is already basically, how an FSM can be programmed in C++, which is covered on this site and on the web numerous times.

If I were you, I probably would go with the first option, though that might also depend on the overall logic, that I currently don't really understand (too few information).

Re “pointer to void?”: A void * is commonly used as a generic pointer, i.e. a pointer to a data item of unknown type. See for example the interface of qsort().

Here's my latest work around:
I was searching for a work around. I got back to copy a method of casting a function pointer.
And changed my data structure of having 2 nested structs to one that contain everything which should serve my project well.
Here's my work:
task_manager.h
///////////////////////////////////////////////////////////////////////////
// enumerations
typedef enum {NOT_FINISHED,FINISHED,DONE}STATE;
// variables
typedef void (*f_ptr)(void *args);

// structs
typedef struct __attribute__((__packed__)) THREAD{
    uint8_t tsk_cnts, tsk_cntr;     // task information
    STATE   thrd_st;                  // thread flag states
    f_ptr   *tsk_fptr;
}THREAD;

main.c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "task_manager.h"

const unsigned char PIC[] = {9, 8, 7, 1, 2};

void function1(void){printf("function1\n");}
void function2(uint8_t i){printf("function2\nnumber = %d\n",i);}
void function3(uint8_t a, uint8_t b, const uint8_t *img){
    printf("function3\na#%d b#%d\narray[0] = %d\n",a,b,*(img+0));}
uint8_t function4(uint8_t i){printf("function4# return\n"); return i+=1;}

THREAD thread1;

uint8_t fn4_ret;

int main(){

    // set thread main info
    thread1.thrd_st = 0;
    thread1.tsk_cnts = 4;
    thread1.tsk_cntr = 0;

    // allocating memory for tasks
    thread1.tsk_fptr = malloc(4*sizeof(f_ptr));

    // store tasks addresses
    thread1.tsk_fptr[0] = (void(*)())function1;
    thread1.tsk_fptr[1] = (void(*)())function2;
    thread1.tsk_fptr[2] = (void(*)())function3;
    thread1.tsk_fptr[3] = (void(*)())function4;

    // call the functions
    ((void(*)())thread1.tsk_fptr[1])(9);
    ((void(*)())thread1.tsk_fptr[2])(1,2,PIC);
    fn4_ret = ((uint8_t(*)())thread1.tsk_fptr[3])(1);
    printf("\fn4_ret = %d\n",fn4_ret);

    return 0;
}

It compiled with me fine, passed what I want and returned the required data.

Even though that may work on some compiler/platform, it is illegal in C++. gcc says about the cast: error: invalid conversion from ‘void (*)()’ to ‘uint8_t (*)()’, and about the call through the pointer: error: too many arguments to function.

I edited my answer.
What you think ? It worked with me well. No problems.

source: Stack Exchange

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

sort: votes


text:
Is it necessary to set a function with always_inline attribution when the function would work maybe once?
I'm going through a library for the ILI9488 running by SPI and want to copy this library in my version.
In the beginning of the source file, there's a guard for the SPI_HAS_TRANSACTION that if the library would run in Arduino compiler then it would use the SPI functions, otherwise it should run from another platform SPI libraries.
Library link:
jaretburkett / ILI9488
This is the part of code I have questions about:
// If the SPI library has transaction support, these functions
// establish settings and protect from interference from other
// libraries.  Otherwise, they simply do nothing.
#ifdef SPI_HAS_TRANSACTION
static inline void spi_begin(void) __attribute__((always_inline));
static inline void spi_begin(void) {
#if defined (ARDUINO_ARCH_ARC32)
  // max speed!
  SPI.beginTransaction(SPISettings(16000000, MSBFIRST, SPI_MODE0));
#else
    // max speed!
  SPI.beginTransaction(SPISettings(24000000, MSBFIRST, SPI_MODE0));
#endif
}
static inline void spi_end(void) __attribute__((always_inline));
static inline void spi_end(void) {
  SPI.endTransaction();
}
#else
#define spi_begin()
#define spi_end()
#endif

My questions:

why the programmer first declare the function in source file not in header file ?
why to use always_inline attribution for a function that's is most the time used once in program file and it's not likely to be used many times during operating time ?
what does this define means ARDUINO_ARCH_ARC32 and where to find it ? I searched in all files in arduino folders and didn't find it. Is it dedicated for fast boards or the usual 16MHz arduino boards ?

Edit:
I want to add another question for the same library.
This function content:
void ILI9488::spiwrite(uint8_t c) {

  //Serial.print("0x"); Serial.print(c, HEX); Serial.print(", ");

  if (hwSPI) {
#if defined (__AVR__)
  #ifndef SPI_HAS_TRANSACTION
    uint8_t backupSPCR = SPCR;
    SPCR = mySPCR;
  #endif
    SPDR = c;
    while(!(SPSR & _BV(SPIF)));
  #ifndef SPI_HAS_TRANSACTION
    SPCR = backupSPCR;
  #endif
#else
    SPI.transfer(c);
#endif
  } else {
#if defined(ESP8266) || defined (ARDUINO_ARCH_ARC32)
    for(uint8_t bit = 0x80; bit; bit >>= 1) {
      if(c & bit) {
    digitalWrite(_mosi, HIGH);
      } else {
    digitalWrite(_mosi, LOW);
      }
      digitalWrite(_sclk, HIGH);
      digitalWrite(_sclk, LOW);
    }
#else
    // Fast SPI bitbang swiped from LPD8806 library
    for(uint8_t bit = 0x80; bit; bit >>= 1) {
      if(c & bit) {
    //digitalWrite(_mosi, HIGH);
    *mosiport |=  mosipinmask;
      } else {
    //digitalWrite(_mosi, LOW);
    *mosiport &= ~mosipinmask;
      }
      //digitalWrite(_sclk, HIGH);
      *clkport |=  clkpinmask;
      //digitalWrite(_sclk, LOW);
      *clkport &= ~clkpinmask;
    }
#endif
  }
}

what I understood from this is that the programmer wants the library to be more versatile to support AVR chips programmer by another IDE than Arduino, also supports ESP8266 and anything else should be handled by softSPI, actually pretty smart coding I guess.
My question here, is does #if defined (__AVR__) checks for either AVR/Arduino in general and when specifies SPI_HAS_TRANSACTION means Arduino SPI library specifically ? right ?

why the programmer first declare the function in source file not in header file ?

the declarion is for the inline attribute. the function should be used only in this cpp.

why to use always_inline attribution for a function that's is most the time used once in program file and it's not likely to be used many
times during operating time ?

there are 14 occurrences of transaction start and it is called before every SPI communication commands set in the library. see my answer about beginTransaction

what does this define means ARDUINO_ARCH_ARC32 and where to find it ? I searched in all files in arduino folders and didn't find it. Is it
dedicated for fast boards or the usual 16MHz arduino boards ?

the architecture define is generated by the builder from selected board's boards package folder name. ARC32 architecture is the Intel Arduino 101 boards package.
EDIT (answer to edited part of the question):

My question here, is does #if defined (__AVR__) checks for either
AVR/Arduino in general and when specifies SPI_HAS_TRANSACTION means
Arduino SPI library specifically ? right ?

__AVR__ is defined in avrlibc, the toolchain for AVR microcontrolers. Arduino uses avrlibc for AVR MCUs. It is not recommended to check __AVR__. The AVR family of MCU is now large with different peripherals so checking __AVR__ should be really restricted to CPU matters.
Every Arduino 'architecture' has its own SPI library. The transactions support was added later so not all implementations of the SPI library support transactions. To declare transactions availability in SPI library Arduino defined the SPI_HAS_TRANSACTION define.

Thank you for the links ! Really helpful. But I have a question, where the defines are located ? Also what speeds are related to ? like ARC32 has 16MHz so which other chips have 24MHz ?

other SPI libraries use max SPI speed of the architecture if higher is requested. the architecture (and board) defines are specified as -D option on compiler command line created by the arduino builder based on platform.txt entries as -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch}

first where to find platform.txt ? second, I understood that the defines are saved in platform.txt file and passed with -D option during compilation, so the compiler put things together in linker stage, right ?

I want to add another question in the main post, hope you check it.

I enhanced the answer. platform.txt is in boards package folder as it is installed by Arduino IDE (please don't ask a follow up question for this. it is a different topic).  you can read the Arduino platform documentation here https://arduino.github.io/arduino-cli/platform-specification/

thanks for the support

Here I am only addressing question number 2. The others have already
complete answers.
The choice to whether a function should be inlined or not is a
speed/size trade-off. There is a cost to calling a function. On AVR, for
example, the call instruction takes 4 CPU cycles, and ret takes
another 4. Inlining the function removes this cost. On the other hand,
you end up with as many copies of the function as places where it is
inlined, and this in turn costs flash memory.
The compiler is usually smart enough to make wise decision regarding
function inlining. In this case, it is not obvious what decision it
would make on its own. On the one hand, the function is used multiple
times in the code, which makes a good case against inlining it. On the
other hand, the body of the function is tiny: only setting up some
registers (the two parameters of SPIClass::beginTransaction(),
including the implicit this) and jumping to another function,
so the cost of inlining is small.
For this library, the programmer happened to have a strong opinion on
this matter, and he though inlining was really the best option. Also, he
did not thrust the compiler to make the good decision. This is the
reason why he used the gcc extension:
__attribute__((always_inline))

And no, it is not necessary, it is just an optimization choice.

Thank you so much for your answer, after some time; just now, I opened this thread and read your answer with more deep attention, and got your answer understood at a very good level. I learned that if I didn't use __attribute__((always_inline)) then the compiler would decide if the function is inlined or not. That's an important information I learned about inlining. Also, the inlined function should be small enough not to take a lot of flash space, big functions should be called normally.

The function is only used in the library, and not part of the "API" of that library. Kind of like a private function.

Both functions are both being called 14 times inside the source code of this library. But in the larger scheme of things, it doesn't add a lot. But why not add it and maybe save a few bytes, and a few clock cycles.

The ARDUINO_ARCH_ARC32 is for the Arduino 101 board (Intel Curie processor).

I'm replying to your answer points.

Yes, the programmer defined a guard with two functions; static inline void spi_begin(void) and static inline void spi_end(void) which include a call for SPI library.

How to save few bytes with inline ? I learned that it saves clock cycles but not space.

So actually, I don't have to use ARDUINO_ARCH_ARC32 when I'm using nano or uno boards ? right ?

It's been more than two months. I don't remember what this is about.

It's about the use of SPI begin function that is used in a library and put in inline mode.

I don't have time to dive into you question again, at the moment. So I'm not able to answer your followup. Sorry.

Thank you so much for your kind reply, you're right, it's been a lot of time for anyone other than me to remember what this topic is about, I'm sorry for my unbalanced follow-up question, I really should open a new thread.

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


text:
The need to use logic level converter
Why do we need level logic converter to have 5V or 3.3V?
Because in Arduino Uno/Mega (don't know about other boards), they already provide 5V and 3.3V for us to use.

please explain the context for your question?  (the reason for your question)

Is this about i2c?

Level logic converting for level shifting is different from powering a device.
Logic level is the state of a digital input/output. No voltage (or very little of it) is considered LOW.   Over the threshold voltage is HIGH. On a 3.3V system, if you set pin to HIGH, it has 3.3 V.  On a 5 V system, HIGH is 5 V.
A digital input pin reads HIGH once the threshold voltage is surpassed. If the input pin is for 3.3 V and doesn't have 5 V tolerance, feeding 5 V as HIGH could destroy it.  That is why you need level converter from 5 V to 3.3 V.
If the input pin is for 5 V and the threshold voltage is higher then 3.3 V,  3.3 V input will not be read as HIGH.  That is when you need level converter from 3.3 V to 5 V.
You must consult the 3.3 V device datasheet and check if the input pins are 5 V tolerant.   You should also check the digital pin threshold voltage on a 5 V device in case you want to communicate with it using 3.3 V.


text:
How much voltage and current can a Arduino uno digital input sink?
I am having a digital output of 24VDC and 0.5A from ABB IRC5 controller. I need to feed this digital output to the digital input of Arduino uno. How can I do that?

Do you want to sink the voltage, or detect it?

just to detect sir

Why are you asking about current then? That's like asking "how heavy an aircraft can I see in the sky with my telescope?". Just to detect it, you don't care about its weight. And to detect a voltage, you don't care about its current (unless the current is very very tiny).

One common misconceptions is that the current limit of a GPIO pin applies to inputs.  It does not.
The 40mA "maximum sink" is only applicable when the pin is set to OUTPUT and is driven LOW - at which point the pin is connected to ground through a MOSFET.

Read: What Exactly is a GPIO Pin?

However, when the pin is in INPUT mode it is high impedance.  This means that it neither sinks nor sources current (apart from a very tiny leakage current).  The only thing that matters is the voltage.  That must:

Never go higher than 0.3V above VCC (5.3V if powered from 5V)
Never go lower than -0.3V
Have logic levels that are within the thresholds of the input:

Below 0.3 × VCC for LOW
Above 0.6 × VCC for HIGH

You can connect the input to a signal that is 5V and 1,000,000 giga-amps and all will be well.
However, if you inadvertently set the pin to OUTPUT and drive it LOW there will instantly be smoke.  For this reason it is common to add a small inline resistor (maybe 100Ω-470Ω) in order to limit any current through the circuit should the pin ever be set to OUTPUT and LOW.
Another "However", though:  If you are using a voltage divider to reduce your incoming voltage to conform to the values above (as shown by @user43648 and suitable values given by @EdgarBonet) the inline resistor is pointless. The voltage divider itself will have a very high output impedance which massively limits the current. This impedance is like having a resistance equivalent to both the provided resistors in parallel inline with your input.

Which will be the better option for me to step down the voltage sir? plz dont mind sir, I am mechanical guy having very very little knowledge in this area.

@SriHarsha As long as you're not dealing with high frequencies a simple voltage divider will suffice. – Majenko

Can you please share a link regarding this sir? I wanna go through it

Regarding voltage dividers? https://en.wikipedia.org/wiki/Voltage_divider

The link was really very helpful. Thank you @Majenko. You earned +1.

As a complement to user43648's answer, it is worth noting that:

According to the datasheet, the 40 mA limit “is a stress rating
only and functional operation of the device [...] is not implied”
beyond the maximum tested current which is 20 mA.
The input voltage should be at least 3 V for the pin to be
guaranteed to read high.
When sensing voltage through a voltage divider, 10 kΩ is a
somewhat typical order of magnitude for the resistors.

Given the above, I would suggest using 47 kΩ for the top resistor
and 10 kΩ for the bottom one. This should give about 4.2 V on
the input pin, which is near the middle of the appropriate range for the
pin to read HIGH.

Sir, should we not bother about the current? What will the current output?I am a mechanical guy, I don't have any idea regarding these things... please kindly help...

You will read the high/low level of the pin with digitalRead().  The input current will be 1uA max, 0.000001A. Practically nothing.  pinLevel = digitalRead(inputPin);

In addition to the potential divider I would be tempted to strap the input pin to ground with a zener diode between 4V7 and 5V1 in case the lower resistor or its solder joints fail. even with a relatively high value series resistor 24V has plenty of potential to destroy the input pin if not the entire chip. The safest method though is use an opto-isolator and keep the nasty high voltages isolated from the delicate digital level components.


text:
error while uploading a code
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

avrdude: can't open input file C:\Users\PETER_~1\AppData\Local\Temp\arduino_build_223764/nyu_probe_activity1_code.ino.hex: No such file or directory
avrdude: read from file 'C:\Users\PETER_~1\AppData\Local\Temp\arduino_build_223764/nyu_probe_activity1_code.ino.hex' failed
An error occurred while uploading the sketch
Invalid library found in D:\programs\ArDuInO\arduino-1.8.5\libraries\OLED_Mono_I2C: D:\programs\ArDuInO\arduino-1.8.5\libraries\OLED_Mono_I2C
Invalid library found in D:\programs\ArDuInO\arduino-1.8.5\libraries\OLED_Mono_I2C: D:\programs\ArDuInO\arduino-1.8.5\libraries\OLED_Mono_I2C

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences. - have you tried?

Have you installed the Arduino IDE from the Windows appstore? If so, install the newest version from the official website instead, since the appstore Version is known to be faulty


text:
Can I avoid having a bootloader if I use ISP to flash to an arduino?
My Trinket Pro waits about 10 seconds upon booting before starting the program that I have loaded on it.
Can I avoid this delay and the bootloader taking up space if I flash my program directly to the Arduino with ArduinoISP?

Please read the other question linked above.

It looks like the Trinket Pro has an Atmega328P processor. You can change the fuses to not run the bootloader, in which case you don't need the space taken by it.
I have a hex uploader sketch which will upload a .hex file from an SD file directly to the chip, removing the need for a bootloader. Using ArduinoISP is another approach which will probably work. I'm not sure whether that fixes up the fuses for you.
If you just want to avoid the time (and not the space - the bootloader is probably only 512 bytes) you can use the sketch I linked to (without needing an SD card) to make fuse changes.
See Engbedded Atmel AVR® Fuse Calculator for fuse calculations. Basically you need to toggle the BOOTRST fuse (the low-order bit of the High fuse).

Thanks!
On the arduino I have, a Trinket Pro, the bootloader is 4kb, which is one reason why I wanted to get rid of it.

The sd-card thing is funny, much like a game cartridge :)

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


text:
Can't get ESP8266 working
I have received an ESP8266 (ESP-07) Wi-Fi module from DealExtreme (Link: http://bit.ly/2dFJdxE).
It is a 4-pin module with the following pins: RX, TX, VCC and GND.
The module has a switch so you can switch between the following modes: Program & UART. The module also has a RESET-button.
Here's a picture of my module:

I've connected the module to my Arduino Uno like this:
RX > RX,
TX > TX(TX>RX & RX > TX, like mentioned in manuals, results in no connection),
VCC > 3.3v (not using any level shifters because the module has on board level shifters),
GND > GND.
I found a lot of manuals to test the module, but apparantly I can't get my module working. I am using Windows with the Arduino IDE.
The boards mentioned on the manuals/tutorials also seem to differ from my module because most of the manuals are talking about a board that has 8-pins (with an extra GPO0, GPO2 CH_PD and RST pin).
I've tried to upload the BareMinimum sketch to the module, which only finishes uploading if I disconnect and reconnect the 3.3v input that's feeded to the ESP-board when the Arduino IDE says "Uploading...... " while the ESP-board is in Program-mode.
I have installed the ESP8266 library within the Arduino IDE and the Generic ESP8266 Module is selected.
Then when I open the serial monitor in the Arduino IDE, to test the AT commands (on different BAUD values), it does not respond (neither in Program-, nor in UART-mode).
Strange thing is when I keep the serial monitor on at 74880 BAUD (and UART-mode on the module) and I push the RESET button on the module, it gives the following message:
ets Jan  8 2013,rst cause:2, boot mode:(3,7)
ets_main.c

I've tried several things.  But none of them seem to work; like trying to flash new firmware (for example 'v0.9.5.2 AT Firmware.bin' and 'esp8266-2016-05-03-v1.8.bin') with esptool.py with the following command:
esptool.py -b 115200 -p COM3 write_flash 0 FIRMWARE.bin

It says that the writing is finished and no errors appear after running the esptool. This is what is printed + command that is used:
esptool.py -p com3 -b 115200 write_flash 0 firmware.bin
esptool.py v1.2-dev
Connecting...
Running Cesanta flasher stub...
Flash params set to 0x0000
Writing 520192 @ 0x0... 520192 (100 %)
Wrote 520192 bytes at 0x0 in 44.2 seconds (94.1 kbit/s)...
Leaving...
A strange thing is when I open the serial monitor in the Arduino IDE after that moment (without resetting the module/unplug from 3.3v or change to UART mode), it keeps printing the following at 115200 BAUD:
Fatal exception (28):
epc1=0x4000228b, epc2=0x00000000, epc3=0x00000000, excvaddr=0x000000b5, depc=0x00000000

I even tried it with the erase_flash before and 0x00000 instead of 0. Also tried to run the command with a variety of flash_sizes (with the command --flash_size=Xm).
Esptool looks like the only tool where I can flash new binaries successfully, tried some others that where on some manuals but without success.
When I run esptool.py -p flash_id
I get the following response:
Connecting...
Manufacturer: e0
Device: 4014
Who knows how to fix this problem so I can send AT commands to the module through the serial monitor in the Arduino IDE.
Thanks in regards (this is my first post so if some things are unclear, please let me know)
Edit: Note that I have to disconnect and reconnect the 3.3v to the module EVERY time to successfully run a command (like write_flash, flash_id et cetera). Also tried connecting it to 5v and using an external power supply next to the USB.

On DealExtreme  it says Working voltage: 4.5V - 5.5V. You are supposed to power it with 5V not 3.3V.

Sorry I didn't write it in my post, but already tried that + tried it using an extra power supply connected to the Arduino (besides USB). Makes no difference.

Seeing "ets Jan  8 2013,rst cause:2, boot mode:(3,7)": Good, your ESP is alive, and wired correctly for communication. "Fatal exception (28):" Good, you managed to set the ESP to non-program/normal mode. Only the software on it seems bad :) What you want to do is flash it with the Espressif AT firmware, and it should work as you expect it, responding to AT commands. DONT after that upload any sketches, cause it will replace the AT firmware. There's tutorials of uploading the AT firmware I think, I'm behind a firewall atm. so can't look for any for you :)

Thanks for your answer, tried different firmware packages from the Espressif website earlier but without any success.

Personally I think using an ESP as a interface for an Arduino is backwards and the Arduino ought to act as the interface to your devices for the much more powerful ESP.
I think you had a board that was configured to work as a interface between serial and Wifi, not as a normal board.  I'm pretty sure that you have now shagged it totally by trying to write programs to it.  However you might be able to recover it if you can find the original program and upload that to it.  You don't need the ability to program and ESP-8266 in the IDE to use this board, you can not upload sketches to it, you can't access the GPIOs.
I think you should just be able to slide the switch to "program" power the board up and type AT commands via a terminal emulator to set the board up and then power down, slide the switch back to UART and away it goes.  As to the Tx and Rx pins, that depends on weather its saying "this is the Rx pin" or "this is the Rx connection", you'll get it right second time :)
If you want a ESP8266 try AliExpress they cost between £1 and £2 and I've never had any problems, probably because they were made in China.

Have you had a look at this documentation I found another seller of your board offering this link.  I haven't downloaded it so virus scan it.
https://www.adrive.com/public/8SGB7d/FZ1727-Serial%20Wifi%20module.zip

Thanks for your answer. Think I should have been more careful before I blindly followed some online tutorials. New boards are on the way so I hope I have more luck with them, hehe. Giving up on this one now I guess, think it's firmware is screwed, tried any firmware package I found on the Internet.

@sschrijver - You could always unsolder the ESP board and put a new one on.

Or buy a more common/popular type of ESP8266 board. The "Sparkfun Thing" and "Adafruit Huzzah" are good if you want quality and customer support. They provider good tutorials as wel. Alternatively you could get a cheap, but common module like the NodeMCU or WeMos.

It may be that the type you have has extremely low memory, bad/unstable power circuitry, weird or specific upload mode or different bootloader. If you get one that is in the upload list, you'll have the right settings. And popular boards are proven to be working and if not, you'll find a lot of tutorials/support specific to your board/problem that may even be the same problem as yours (and how to fix it)

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


text:
Tried to fix ports on Mac OS X Yosemite. Now nothing works
I was having an issue very similar to this one:
Arduino compatible's serial port not showing Mac OSX
Basically I have a clone (VISduino) and it's made with a different USB chip so it needed a driver. Installing the driver didn't help.
http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html
Running:
 sudo nvram boot-args="kext-dev-mode=1"

didn't help. So I decided to delete Arduino and reinstall. Then I went through all of the steps again.
Well.... now nothing works. Before doing this I could use:

Adafruit metro
An uno clone
My genuine uno
lightBlue Bean
adafruit trinket and trinket pro
adafruit trinket pro via USB
digikey

I've reinstalled the drivers for these but NOTHING is working now. They were all working before. It just says Arduino Uno on COM1, or digikey on COM1 etc.

And of course my clone (vis duino) isn't working either.
How can I fix this?

The com ports just are not there.

That's clever - you've got your Mac to give you Windows device names...?!

what do you mean?

COM1 is what windows calls it.  I'd expect something like /dev/cu.modem-4d82f3a

well my mac is calling it com1 I posted a photo.

It's saying COM1 because you haven't (yet) selected a serial port to use.  This has nothing to do with the Arduino IDE - it's 100% to do with dodgy drivers.

Serial is greyed out. I tried deleting all Arduino files (except for my sketches which I put in another folder.) reinstalling and just trying to load blink on my  genuine uno.... same error.

Have you reviewed the questions shown as Linked or Related, in the right sidebar?  Eg,  “Arduino compatible's serial port not showing Mac OSX”, “No valid serial ports for Arduino UNO on Mac”, “Arduino compatible's serial port not showing Mac OSX”, “Arduino Nano no serial port for MacBook Air 2013”, and “Mac won't detect Serial Port for Leonardo”

Restarted for the 6th time and now it works WTF seriously.

Oh I did read all of those. It's working now but I have no idea why. Ugh.

I solved this issue by deleting all of the Arduino files and the Arduino app. I put my sketched folder aside but deleted all libraries.
Restarted the computer.
Installed Arduino fresh.
Restarted the computer.
Installed the drivers.
Ran the command.
Restarted the computer.
Restarted the computer.
Restarted the computer.
Then it worked.


text:
SD Card Info Unexpected
So I have just begun testing my Wireless SD Shield from Arduino with my Arduino UNO. Upon running my the basic CardInfo sketch, it uploads and displays data, but far more than expected. The SD Card is entirely empty, as in, if I plug it into my computer, there are no files on it. However, this is the Serial Monitor Output I receive:

The reason I have included screenshots rather than copy and pasting the output, is that if I try and copy and paste, it does not copy all of the Files Found on the card, it only copies the first 8 lines.
Any help would be greatly, appreciated!
This code does not compile for me and gives me an avrdude error which I believe is due in some part to the above pictures:
//Program by Jeremy Blum
//www.jeremyblum.com
//SD Card Demonstration
//Based on Example by Tom Igoe

#include <SD.h>

//Set by default for the SD Card Library
//MOSI = Pin 11
//MISO = Pin 12
//SCLK = PIN 13
//We always need to set the CS Pin
int CS_pin = 4;

void setup()
{
  Serial.begin(9600);
  Serial.println("Initializing Card");
  //CS Pin is an output
  pinMode(CS_pin, OUTPUT);

  if (!SD.begin(CS_pin))
  {
      Serial.println("Card Failure");
      return;
  }
  Serial.println("Card Ready");

}

void loop()
{
  String dataString = "Hello";

  //Open a file to write to
  //Only one file can be open at a time

  File dataFile = SD.open("log.txt", FILE_WRITE);
  if (dataFile)
  {
    dataFile.println(dataString);
    dataFile.close();
    Serial.println(dataString);
  }
  else
  {
    Serial.println("Couldn't open log file");
  }
  delay(5000);
}

Whereas, this code does:
#include <SD.h>         //SD Card Library
#include <Wire.h>       //I2C Library
#include <DallasTemperature.h>
#include <OneWire.h>

OneWire oneWire(2); // initiate pin connected to DS18B20
DallasTemperature sensors(&oneWire); // pass oneWire as parameter to Dallas Temp. library

//SPI SD Card Pins
  //MOSI = Pin 11
  //MISO = Pin 12
  //SCLK = PIN 13
  int CS_pin = 4;
//  int pow_pin = 8;

//Light Sensor Pins
  int light_pin = 0;

float refresh_rate = 500;  //Dataloger Refresh Rate
float id = 0;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  sensors.begin(); // initiate the sensors on the DS18B20
  Serial.println("Initializing Card");
  //CS Pin is an output
  pinMode(CS_pin, OUTPUT);

//  //SD Card will Draw Power from Pin 8, so set it high
//  pinMode(pow_pin, OUTPUT);
//  digitalWrite(pow_pin, HIGH);

  //Initialize Card
  if (!SD.begin(CS_pin))
  {
      Serial.println("Card Failure");
      return;
  }
  Serial.println("Card Ready");

  //Write Log File Header
  File logFile = SD.open("LOG.csv", FILE_WRITE);
  if (logFile)
  {
    logFile.println(", , , ,"); //Just a leading blank line, incase there was previous data
    String header = "ID, Light, Temp";
    logFile.println(header);
    logFile.close();
    Serial.println(header);
  }
  else
  {
    Serial.println("Couldn't open log file");
  }

}

void loop()
{
  //Check Light Level
  int light_level = analogRead(light_pin); //Write the value of the photoresistor to the serial monitor.

  //Read Temperature
  sensors.requestTemperatures(); // request the temperatures from the DS18B20, does not actually do anything simple sets it up
  float currentTemp; // initialize variable to store and hold current temperature readings
  currentTemp = sensors.getTempCByIndex(0); // go and get temperature in Celcius for the first temp probe, temperature probe 0 (could have more than one sensor here if wanted)

  Serial.print("Temperature = ");
  Serial.print(currentTemp); // prints actual temperature and starts new line
  Serial.print(" Celcius ");
  /* Serial.print((char)223); print degree symbol in LCD format */
//  Serial.println("C");

  //Create Data string for storing to SD card
  //We will use CSV Format
  String dataString = String(id) + ", " + String(light_level) + ", " + String(currentTemp);

  //Open a file to write to
  //Only one file can be open at a time
  File logFile = SD.open("LOG.csv", FILE_WRITE);
  if (logFile)
  {
    logFile.println(dataString);
    logFile.close();
    Serial.println(dataString);
  }
  else
  {
    Serial.println("Couldn't open log file");
  }

  //Increment ID number
  id++;

  delay(refresh_rate);
}

Both sketches are quite different, so I reccomend just looking at the intial void setup() part of each if you want to read through them.

Simply seeing an empty card on your computer, does not mean it's empty. Turn on 'Show hidden files' in Windows.
Besides that, many of these files are written to the SD card to make it usable. Without them the card is either corrupted or formatted.

Joy of tech... It's full file table, with old, deleted entries appearing as current files. You can nuke it with a quick or slow format, but the problem will return later. I don't know this shield, but there must be some problem with the code - it really shouldn't show deleted entries. Try another library, or google for problems with your current lib.

Not sure about quick format - but in any case, it shouldn't show old FAT. Please post your findings, I have some microsd modules in the mail.

So I ended up leaving it be, and simply ran a different sketch and it seems to be working fine so far. I believe it may have been some hidden files instaled by my Mac when I first tried to use it, and so hopefully it will not be an issue in the future.

mac's "hidden" files are prefixed with "." (dotfiles), that's not your bug.

hmm, then not sure why it seems to have worked?

can you post your broken and working code seperately?

Yup. I will add it as an edit to the above post.

They are Mac's OS X "Spotlight" hidden indexing files.  This answer shows how to turn it off.


text:
Button Relay Control
How can I fix this sketch to make it so that once the button is pressed, it performs some action for a certain amount of time and then returns back to a low state until it is pressed again. For example, I need to run a pump for 5 seconds when the button is pressed and then turn off automatically. And then, when I press the button again it will repeat, etc. I am not trying to use a relay module if it is not necessary. Here is my current sketch and a Lab View of the components:

#include <LiquidCrystal.h>
#include <SoftwareSerial.h>

int switchPin = 8;
int ledPin = 13;
int buttonPresses = 0;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean ledOn = false;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()
{
  Serial.begin(9600);
  pinMode(switchPin, INPUT);
  pinMode(ledPin, OUTPUT);
  lcd.begin(16, 2);
}

boolean debounce(boolean last) //just a debounce function
{
  boolean current = digitalRead(switchPin);
  if (last != current)
  {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
}

void loop()
{
  {currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    ledOn = !ledOn;

    buttonPresses++;
    lcd.clear();
    lcd.print("Number of Button ");
    lcd.setCursor(0,1);
    lcd.print("Presses = ");
    lcd.print(buttonPresses);
  }
   lastButton = currentButton;
   digitalWrite(ledPin, ledOn);
  }
}

THANK YOU!

This code should work. You will need to declare the following variables:

lastPress   // The last time the button was pressed
outputState  // The state of the timed output
outputPin  // The pin number for the timed output
PERIOD  // The amount of time that the outptu remains on

The code:
void loop()
{
    currentButton = debounce(lastButton);
    if (lastButton == LOW && currentButton == HIGH)
    {
        ledOn = !ledOn;

        buttonPresses++;
        lcd.clear();
        lcd.print("Number of Button ");
        lcd.setCursor(0,1);
        lcd.print("Presses = ");
        lcd.print(buttonPresses);

        outputState = HIGH;
        lastPress = millis();
    }

    if (outputState && ((millis() - lastPress) > PERIOD))
    {
        outputState = LOW;
    }

    digitalWrite(outputPin, outputState);

    lastButton = currentButton;
    digitalWrite(ledPin, ledOn);
}

A relay should be used to drive a pump etc.. The Arduino Uno can only drive 5V at maximum 20mA.

okay so I have tried what you mentioned and have been unable to get it to run? The variable lastPress would be akin to my variable lastButton, outputState to ledOn, and outputPin, to ledPin. I am unsure how I can declare the variable PERIOD to have a time dependent value.

PERIOD can be defined in two ways:
const int period = 3000;  // 3 seconds
or
#define PERIOD 3000  //3 seconds

The if statement I have added in my answer measures the time elapsed and compares if it is larger than the period variable. If it is it will turn the output off. More info: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay and here: https://www.arduino.cc/en/Reference/Millis

Appreciate all the help


text:
Issues with I2C and Wire.Available()
I am working on a project which requires communication from an Arduino Due (Master) and an FDC2214Q1 C to D IC (Slave), but there is some variability as to whether the code works or not depending on seemingly random variables.
I have narrowed the issue to the function I am using to read 2 bytes from the slave. The code is pretty standard, and is as follows:
// Read 2 byte from the FDC at 'address'
uint16_t FDC2214::read16FDC(uint16_t address) {

    uint16_t data;

    Wire.beginTransmission(_i2caddr);
    Wire.write(address);
    Wire.endTransmission(false); //restart
    Wire.requestFrom(_i2caddr, (uint8_t) 2);

    while (!Wire.available());
    data = Wire.read();
    data <<= 8;

    while (!Wire.available());
    data |= Wire.read();
    Wire.endTransmission(true); //end

    return data;
}

The code seems to get hung up sometimes on while (!Wire.available()) and if I simply remove that step, I never get the correct Device ID.
However, if I simply unplug the DUE and close the Serial Monitor and replug in and upload, it works. I just kind of upload and disconnect a few times and open and close the Serial Monitor and sometimes it works great, other times it gets hung up?
Any ideas what could be causing such and issue?
Code based on this library: https://github.com/zharijs/FDC2214/blob/master/src/FDC2214.cpp

Final code that has been working, removes need for While loop:
uint16_t FDC2214::read16FDC(uint16_t address) {

    uint16_t data;
        Wire.beginTransmission(_i2caddr); //queuing the slave address
        Wire.write(address); //queuing the register address/pointing regsiter
        byte busStatus = Wire.endTransmission(); //transmit all queued data and bring STOP condition on I2C Bus
        if(busStatus != 0x00)
        {
           Serial.print("Transmission Error....!");//transmissiion error wait here for ever
           while(1);
        }

        Wire.requestFrom(_i2caddr, (uint8_t) 2);     //this is looping code; when 2-byte has arrived, the loop terminates
        data = Wire.read();   //read the first byte from FIFO Buffer
        data = (data <<8)| Wire.read();   //16-bit data is formed
        Wire.endTransmission(true); //end
        return data;
}

how long are the wires? what value pullups are you using?

Currently do not have pull-ups as there is only one master/slave, but I realize maybe I should as a precaution. Will add some now, and let you know if that fixes anything. Thank you @dandavis

Hey @dandavis so I just added the pull-ups (1k) and it seemed they worked. But, sure enough, after a few sessions of opening and closing the Serial Monitor and unplugging/plugging the Arduino, I was able to reproduce the problem once again.

your code is not formatted properly ..... the two command lines after the while commands should not be indented ... the indentation implies that the two commands are inside the while loop .... they are not part of the while loop

@jsotola, this comment in no way helps me out, I understand how to format code, just thought it might be easier to emphasize the while loops I was referring to by tabing out the underlying code.

that is exactly what i am saying ... the tabbed code is NOT part of the while loop .... if you want to emphasize a section, then put in a blank line

Adafruit tells to avoid the Arduino Due. One of the reasons is the I2C bus. Can you use an other Arduino board? For example one of the MKR boards with a SAMD21 processor.
The Due has pullup resistors on the board for SDA and SCL which are too low in value. Sometimes the I2C bus with SDA and SCL works, but sometimes it does not work at all. Perhaps you are able to remove the pullup resistors at SDA and SCL from the board.
If possible use Wire1 with SDA1 and SCL1. Those have no pullup resistors at all, so you need to add 4k7 pullup resistors to 3.3V. When you use a library, you might have to change the library to use "Wire1" instead of "Wire".
You need to remove these, they are not doing something:
while (!Wire.available());    <- not doing something

Remove the Wire.endTransmission at the end.
Wire.endTransmission(true);   <- remove this
return data;

That library does not use the Wire library in a proper way.

The pullup resistors are 1k5 or sometimes 1k and are located in the upper-right corner, near pin 20 and 21. A value of 1k5 should be okay, when there are no other pullup resistors. When you board has 1k resistors, then I suggest to remove them.

Removing them is possible with a soldering iron and a big blob of solder. Check if the board is clean afterwards, for example with a magnifier. Avoid overheating your expensive Arduino Due board.
The I2C bus needs pullup resistors to work. A normal value is 4k7. Sometimes there are already 10k pullup resistors on a sensor module.
If the I2C has problems, start by using short seperate wires for SDA and SCL. When a cable is used for the I2C bus, then the cable is probably the problem and not the pullup resistors.

Thanks for the note, unfortunately I don't have any MKR boards, but I have some nanos that I can try out. I will swap to 4k7 pull ups as well, and remove the parts you have mentioned and give it a shot. I have read that the while(!Wire.available) is not necessary but figured it couldn't hurt (apparently it can). Will update either today or tomorrow the result of this! Thanks @Jot

Do not add extra 4k7 to SDA and SCL. There are already pullup resistors on the Due, which are too low in value. Adding 4k7 makes it worse. Only when using SDA1 and SCL1 requires to add (normal) pullup resistors.

Gotcha, I will remove them for the Due, but for testing on the Nano should I remove them as well? @Jot (also i have to run, but will update this ASAP tomorrow morning.)

The sensor is for 3.3v and the nano runs at 5v. I don't like that combination, unless you use a level shifter for sda and scl.

it was my understanding that the i2c on the Nano was 3.3V, but if it is not as you say, would it be possible to disable the internal pull ups and then simply use a 2k7 or 4k7 to 3.3V?

@JonathanA Nano: It is possible to turn off the internal pullup resistors after Wire.begin. The FDC2214 is damaged with a voltage above 5v and not at 3.6v as many sensors do. So with external pullup resistors of 4k7 to 3.3v, it might work for a test, but I still don't like it. Due: You need a soldering iron to remove the wrong pullup resistors. It is the smd component near pin 20 and 21.

I will spend my morning tomorrow on this. Will update you with what I find. However, on the Due I will try and remove the weak pull-ups and add my own externally. Will let you know! Thanks for your continued advice.

@JonathanA I have added a paragraph to avoid a cable. The onboard pullup resistors is a specific problem for the due, but there are many common problems for the i2c bus.

Thank you! I have posted the code that, for the moment, seems to have fixed my problem. I will, nonetheless, accept your answer as correct as it has been of great help! Thanks @Jot.

@JonathanA you still need to remove the line above the return (the last Wire.endTransmission). Read about it: https://www.arduino.cc/en/Reference/WireEndTransmission it should not be used after a call to Wire.requestFrom.

Let us continue this discussion in chat.


text:
Arduino Yun connection problems
I followed this guide and evertything works until I'm at chapter Configuring the onboard WiFi.
I can see the arduino as an AP.

And I can connect with it. However when entering the IP adress 192.168.240.1 or arduino.local it does not give me the login page.
When using the IP adress I get: the site is not accessable screen. Using arduino.local gives me a page that loads forever for a long time before giving me the exact same result.

I have looked on different forums for a solution. This one said that I should download bonjour and bonjour browser because they use the same port (port 5353). After installing the bonjour browser I should be seeing a connection called .arduino._tcp but I don't see that. In fact I often can't see any connection what so ever.

and sometimes I can see a few connections but none of those are the arduino.

I have tried to ping with the arduino on the adress 192.168.240.1 but all I got was a time out.
Pinging 192.168.240.1 with 32 bytes of data:
Request timed out.

Edit : I managed to get the bonjour browser to work all the time, by installing itunes. It also shows the arduino.

Have you confirmed that your computer has been given a correct IP address on the right subnet through DHCP?

Yes i have checked that. also i just tried to do it on another computer and it seems to work with that computer.

So this is a problem with your computer then, not the Yun. I suggest disabling all firewalls and antivirus products and trying again.

Please add a screenshot of WI-FI connection properties. You must be connected to the Arduino-Yun network and not WiFi-2.4-2348_EXT.

@AltAir i replaced the screenshot

@Majenko I disabled all firewalls and disabled my antivirus, still didn't manage to load the page

You have to find IP address of your Yùn on your local network.
What I do in this case:
- look on the Home router if you can see your Yùn and it's ip, or,
- there is a sketch in Arduino Ide / exemple / bridge / wifi status which can help you to get ip, or
-  open the Arduino Ide software, upload serialTerminal sketch and open serial monitor. It allows you to access the Linux part of the Yùn and type 'ifconfig' to get the IP from the Yùn.

Well as you can see on the last screenshot I made the ip is 192.168.240.1


text:
Would rewriting my code in C help reduce RAM usage?
So my program fails to run because there is not enough room for my variables as well as the Arduino Core and Stack. I can't find any more ways to optimize my program so I'm thinking about just rewriting it in C.
However, I'm not sure if that will actually help me. For example I know that in C my program will run faster because things like digitalWrite() and analogRead() have a bunch of "extras" that make it go slower, but I don't know if this will affect RAM.
So can any of the experts on here tell me if writing my code will help before I waste time doing so?
Here is my code:
#include <SoftwareSerial.h>
#include <avr/pgmspace.h>

#define FASTADC 1

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

SoftwareSerial mySerial(0,1) PROGMEM;

byte i;

byte pixelsArray1[128];   //Array to hold the values of the individual pixles.
byte pixelsArray2[128];   //Array to hold the values of the individual pixles.
byte pixelsArray3[128];   //Array to hold the values of the individual pixles.

void setup()
{
  #if FASTADC
   // set prescale to 16
   sbi(ADCSRA,ADPS2);
   cbi(ADCSRA,ADPS1);
   cbi(ADCSRA,ADPS0);
  #endif

  pinMode(1,OUTPUT);        //Setting the 1 pin to be used for output
  pinMode(0,OUTPUT);        //Setting the 0 pin to be used for output
  pinMode(A3,INPUT);        //Input for Camera 3
  pinMode(A2,INPUT);        //Input for Camera 2
  pinMode(A1,INPUT);        //Input for Camera 1

  mySerial.begin(9600);     //Setting the data transfer rate
}

Notes:

I'm programming on the ATtiny85
I'm running Windows 10
I've never programmed in Arduino before

What does your RAM usage currently look like?

The three arrays, SoftwareSerial, and byte variable use 432 of the total 512 bytes of RAM on the ATtiny. Leaving the remaining 128 for the Core and Stack which I'm assuming is not enough because when I upload the program it fails to run. However when I reduce the size of the arrays the program runs just fine.

Personally I would look at ditching SoftwareSerial and running the USI by hand, but have you tried the code on a larger device yet?

Yes it work just fine on my Mega. But doesn't SoftwareSerial not affect the memory in my code since I'm using PROGMEM to store it in flash? Also can you expand on what you mean by "running the USI by hand".

SoftwareSerial has a buffer that takes up RAM regardless of where the object itself is located. AVR307

The only time I'm using it is when I'm setting the data transfer rate. Is there another way that I can do this?

See the document I linked.

I don't think I'm going to be able to understand that document in the near future. Thank you though.

I see you never use mySerial in your code, however this allocates some buffers that may take a lot of your precious memory. For me you should just completely remove it from your code as I don't see its purpose, it would probably be a gain of more than 50 bytes SRAM.

The simplest approach to reducing RAM usage of the program shown is to get rid of the three 128-byte pixel arrays.  They are not needed for the program to function.
Instead of writing
pixelsArray1[i]=analogRead(A1)/4;
pixelsArray2[i]=analogRead(A2)/4;
pixelsArray3[i]=analogRead(A3)/4;

write
if (analogRead(A1)/4 == 0 && analogRead(A2)/4 == 0 && analogRead(A3)/4 == 0) ++foundZero;

where foundZero is initialized to zero before the loop.  After the loop, you say something like
while (foundZero--) {
  digitalWrite(1, HIGH);
  delay(2000);
  digitalWrite(1, LOW);
  delay(2000);
}

to toggle pin 1 as many times as there were three zero pixels.
Note, the timing of the if (...) ++foundZero; statement may differ from pixel to pixel because the && evaluation may short circuit.  If the timing matters, save data in temporary variables, or check if the sum of the three is zero, etc.

Thanks but eventually I will need all three arrays to do some calculations once the project nears completion. I need the three arrays and can't do without them.

If timing of reading pixels isn't critical, just do those other calculations online also.  If possible.  Or if your later processing needs some context but not the whole array, keep a dozen or two of pixels in a circular buffer.  Or just reread all the pixels when you need to work with them.

I don't believe that rewriting it in C is going to help you much: the framework is pretty tight already, and you'd only get the C library's versions of the various drivers' buffers etc.
I do think your only solution (apart from getting larger hardware!) is to 'optimise' the pixelArrays. To do that, could you consider the following questions:

What is the worst value resolution that you'll get away with? You're currently compressing each camera feeds' pixel to the range 0-255, to store them into their individual bytes. What about 0-31? (See why below)
Will you always be comparing each feed's individual pixels against the same pixel in another feed? If so, perhaps you could pack all three values into one 16-bit quantity:
X 11111 22222 33333
where each quintet of bits is that feed's value compressed down. The X is cute: before compressing, you could compare all three values with each other, or zero, or something, and if true set the X bit to 1. That then means that you can later test for that exact condition in the triple-pixel with a <0 check - the sign bit will be set, so the condition will be true.
Or, if compressing down to 0-31 is too extreme, what about storing a 'master' copy of the pixel, and then two (scaled) differences from there: 11111111 2222 3333 where the master 1 value is unscaled (other than /4), while the other values are from the following table:
0000 - Identical pixel value
0001 - Within +2
1111 - Within -2
0010 - Within +4
1110 - Within -4
0011 - Within +8
1101 - Within -8
0100 - Within +16
1100 - Within -16
0101 - Within +32
1011 - Within -32
0110 - Within +64
1010 - Within -64
0111 - Within +128
1001 - Within -128
1000 - More than ±128
Even more radical: could you do all the tests when you read the data (do you have time???), and then simply store a one-bit result for each pixel? Such a packed-bit array is VERY efficient - if you can boil down your decision to yes/no...

I'd be happy to help write (reasonably) efficient C code to implement the TriplePixel functions - or even attempt it in assembly...


text:
Parse JSON with arduino to turn on LED
Hi i'm trying to parse JSON resposne from webserver in my arduino in order to turn on and off a LED light. I'm using the wifi client repeating example to make a get request to my server:
http://arduino.cc/en/Tutorial/WiFiWebClientRepeating
Here is what I get printed back from the serial port
connecting...
HTTP/1.1 200 OK
Date: Sun, 06 Apr 2014 01:14:37 GMT
Server: Apache
X-Powered-By: PHP/5.5.10
Cache-Control: no-cache
X-Frame-Options: SAMEORIGIN
Set-Cookie: expires=Sun, 06-Apr-2014 03:14:37 GMT; Max-Age=7200; path=/; httponly
Connection: close
Transfer-Encoding: chunked
Content-Type: application/json

19
{"lightstatus":"on"}
0

How do i parse the JSON portion of this response only so that I can use it to control my LED?
Thanks

I'm aware of a few JSON parsing libraries for Arduino.

aJSON
Arduino JSON Parser
JSON Arduino

I've never used any of these but I did do some simple JSON parsing in a project I'm working on so I'll show you how I did that.
NOTE: I'm reading serial data using the software serial library. You'll need to change this code to work for you. This will only work on very simple JSON strings. It's very limited but if that's all you're parsing then it'll work.
Example of JSON response from server:
{"id":"TEST1","lat":"38.56050207","lng":"-121.42158374","total":"3","available":"2"}

First, only read data between curly braces.
String response = "";
bool begin = false;
while (SIM900.available() || !begin) {

    char in = SIM900.read();

    if (in == '{') {
        begin = true;
    }

    if (begin) response += (in);

    if (in == '}') {
        break;
    }

    delay(1);
}

This code reads data one byte at a time and once it gets an open brace, it starts saving it into response. When it gets a closing brace, it ends it. So here's a clear limitation, you can only have one set of opening/closing braces in your string.
Once I have the string, I use indexOf and substring to extract relevant information:
start = response.indexOf("id\":\"") + 5;
end = start + 5;
nodeId = response.substring(start, end);

This code sets start to the beginning of id":" + 5 characters in the string. It's +5 because that's how long id":" is. So start points to TEST1 in the JSON string. In my system, the ID is always going to be 5 characters long so end is start + 5. I then use substring to extract that.
Again, before anyone starts down voting me for this horrible solution: if you know exactly what you're working with, and understand the limitations of this code, then this is not a bad solution. It's a solution that gets the job done.

The JSON example you give does not look like "good" JSON, e.g. numeric values should normally not be quoted as strings.

+1 for the list of potentially usable libraries for JSON. I am surprised no library is based on a callback function approach, that would be called during parsing (much more efficient memory-wise).

At least you're conscious that your code sample is horrible:-) Of course it gets the job done, but it is not readable (by someone else qnd even by yourself in 6 months) and hence not maintainable.

@jfpoilpret I'm out of memory on the chip so I've had to cut corners in some places. At least it's heavily commented.

I understand; but I wonder if String usage does not make the memory situation worse (yes, String in Arduino is my pet peeve).

I think from the list of libraries you provided it would be nice to comment it's main features (eg: Arduino JSON Parser not using mallocs)

I have programmed a class that will receive char by char the JSON document. It only will store in memory a few bytes for known JSON structure using a state machine and the results you need. So you can query the class for the results you want and will process the JSON.
Its ideal for your purpose. I have used for connecting to a weather service that returns a json:
static const char* queries[] = { "list.0.deg", "list.0.weather.0.main"};
StreamJsonReader jsonreader(queries, 2); // 2 queries
while(char c  =  read()){
      jsonreader.process_char(c);
}

cout << jsonreader.results[0] << endl;
cout << jsonreader.results[1] << endl;

Check this blog post I just wrote: http://web.biicode.com/blog/big-json-on-arduino.
Source code is here in Biicode.

I wrote a parser for the PIC that has very low ram use because it works directly with char pointers and does not build a tree structure. If you ask to get item N of a list, it gives you an actual pointer into the direct JSON file right at the start of item N of the list. Then you can ask what type of object the pointer represents, etc. It's buggy and doesn't support floats and I think has a few other limitations(twas a long time ago) but it's all on github:https://github.com/EternityForest/OpenFortune-fortune-like-text-generator
You'll need to look in libfortune which is part of the C version.

I wrote a simple JSON-RPC library (on top of aJson) with example of how to turn a led on with JSON-RPC procedure call:

Code: https://github.com/cloud-rocket/arduino-json-rpc
Documentation: http://www.cloud-rocket.com/2014/03/serial-json-rpc-server-arduino/

Can you add some more information into your answer in case the link to the code/documentation changes...


text:
Arduino resets my MacBook Pro
Every time I connect the Arduino Uno to the Mac through USB port, the Mac restarts. Why is this happening? How can Arduino make such a sophisticated machine reset? This also happens with my ESP12E Node MCU.

Have you considered blaming the cable? The port?

Is the arduino connected to anything else or is the only connection to the computer? It's just as easy if not easier to make a sophisticated machine reset than a simple one.

Tried using different cable, cant really blame the port because my Mac is pretty new. This is happening ever since i upgraded to Sierra. The Arduino is not connected to anything.

@MilapJhumkhawala - If the Arduino is not connected to anything how is it reseting you mac? :)  Is the port you are using on the new Mac a port that can be used with an Arduino (USB2)?
It sounds like an OS problem (if that is what sierra is) Could you try your Arduino on a real computer?

I hope "real computer" isn't meant to start a flame war. We're big boys and girls in this space who use Unix/Linux, Windows, or MacOS on manufactured/purchased or home-built hardware according to what suits our own needs and wants. No one has to change hardware or OS to successfully develop embedded software for Arduino or something else....

... I can confirm that Apple hardware and operating systems support Arduino development absolutely as well as do Unix-oid or various flavors of Windows OSes on appropriate hardware. I made a living writing embedded systems with Digital, Data General, IBM, and Dell computers with Digital, Data General, and Microsoft (from DOS onward) operating systems and continue to develop with Apple hardware and operating systems, right up to Sierra including the Sierra betas. They all work. Use what works for you.

It is almost certainly a device-driver issue. Since Arduinos are probably a little way down the pecking order for things that Apple is interested in, they probably don't test as extensively as (say) printers.

How can Arduino make such a sophisticated machine reset?

Device drivers would operate with elevated privileges, because they need to control, well, devices, like hard disks, printers, etc. If one has a programming error (like dereferencing a NULL pointer) then it could crash the whole operating system.

I suggest you look at this page: IDE 1.6.12 released with Sierra support and more
It says there:

A new version of the Arduino IDE (1.6.12) supporting OSX Sierra is available for download! All OSX users updating to Sierra are invited to also update the IDE to avoid crashes when uploading sketches.

This may or may not help. They seem to be suggesting that the IDE crashes rather than the Mac, but it could be worth trying.

There are some posts on macOS Sierra Usb Serial Crash which seem relevant:

I need to use a arduino nano and my Mac with mac os sierra is rebooted when i plug in the arduino

It sounds like the CH340 chip set used on clone Arduinos is causing this.
A suggested new device driver fix is at ch340g-ch34g-ch34x-mac-os-x-driver

It's generally not "Arduinos" as such. Mainstream Arduinos with FTDI USB to serial chips or ATmegaXXu[24] microcontrollers are supported by drivers shipping with the OS, and those tend to be tested and work.
The problem tends to be with clones using CH340 based USB to serial chips, which are supported by vendor drivers of dubious reliability (though there are quite reliable third party drivers for them).

i have had the same problem and found that the CH340 driver was at fault.  With the Arduino MEGA clone attached to the computer, it would throw a kernal panic at startup, then keep restarting over and over.
With the clone unhooked, the computer started normally.  Therefore the driver when trying to load at startup was cauing a panic.
I went back to the web site and found an “updated” driver that solved the panic problem.  It starts and runs OK, BUT -

Every print command prints twice. A simple “Hello World” prints twice.

I don't have a solution for the double print.

The program would compile, but never load in to the clone.  When I switched the USB cable from a 6ft one to the included 1 ft blue one, it worked.

My MacOS is High Sierra 10.13.4 the simple solution is :

Download CH341SER_MAC.zip from here
https://github.com/awangga/NFCReader/raw/master/driver/CH341SER_MAC.zip
remove old driver, please open terminal and run command:
rm -rf /System/Library/Extensions/usbserial.kext
rm -rf /Library/Extensions/usbserial.kext
Unzip CH341SER_MAC and install CH34x_Install_V1.4.pkg then restart MAC,
after rebooting login to your MAC and open terminal,
Conect arduino into your Mac and Look at your serial folder :
ls /dev/
You can access your Arduino on /dev/cu.wchusbserialfa130 or /dev/tty.wchusbserialfa130 or just type : ls /dev/cu. then
tab twice.


text:
Adding button which resets to top of void
I'm quite new to Arduino and the programming of the board, but I wanted to have a go at making a traffic light based on an example I found online.
The example supplied a simple layout which I roughly copied with the components I had.

I then created the following code to mimic the traffic lights of my local area.
int red = 13;   int yellow = 12;   int green = 11;

void setup(){
    pinMode(red,OUTPUT);
    pinMode(yellow,OUTPUT);
    pinMode(green,OUTPUT);
}

void loop(){
    changeLights();
}

void changeLights(){
    // red on, other off for 3 seconds
    digitalWrite(green,LOW);
    digitalWrite(yellow,LOW);
    digitalWrite(red,HIGH);
    delay(3000);

    // red on, amber on,green off for 3 seconds
    digitalWrite(green,LOW);
    digitalWrite(yellow,HIGH);
    digitalWrite(red,HIGH);
    delay(3000);

    // red off, amber off,green on for 3 seconds
    digitalWrite(green,HIGH);
    digitalWrite(yellow,LOW);
    digitalWrite(red,LOW);
    delay(3000);

    // red off, amber on,green on for 3 seconds
    digitalWrite(green,HIGH);
    digitalWrite(yellow,HIGH);
    digitalWrite(red,LOW);
    delay(3000);
}

What I'm wanting to achieve next is a button which resets the code back to the top of void changeLights.
I assume I would be able to do this using a push-to-make switch, but I'm not sure how to incorporate it into my circuit or if it is even possible to reset using this.

Jumping to the top of changeLights() is not the best idea. Wouldn't you like to have an interupt service routine that clears all leds and then returns to the loop() function?

I'm not sure what the best practice is, But now is the best time to learn. Point me in the right direction please.

The reset button already does more or less what you want. If you do not want to reset the whole program, start by removing the call to delay() as in the blink without delay Arduino example. Then you will be able to poll a button in parallel. BTW, you will drive the motorists crazy if green is lit for only three seconds.

As currently written, your changeLights() function, which is repeatedly called over and over again by the Arduino loop() function, runs a timed sequence of lights.

Red light is on for 3000 ms
Amber is on for 3000 ms
Green is on for 3000 ms

This sequence could also be implemented using a state machine, but as it is right now, it's just a simple sequence of operations.
So now you have a new feature request (heh, this happens all the time in pro software development):

hardware will include a momentary switch to ground
when the switch is pressed, the changeLights() sequence will skip to the next Red light
we might also want to do other kinds of sequence change, not just reset

The simplest way to code this would be to use digitalRead() to test whether the switch is pressed. You could test just after each of the delay(3000) calls. Technically this would work, but it would only sense the switch state just at the instant that digitalRead() is called. So for most of your 9-second sequence, it will ignore the switch, and only briefly test. The user will have to hold the button for 3 seconds to be sure the program senses the switch press.
There are some better ways to make this work. The delay(3000) actually makes the program do nothing else but watch the clock for the full delay interval, it doesn't do anything else during this time. So instead of delay(3000) you could use a for loop, and test whether the button has been pressed.
// Spend 3 seconds waiting; exit the function if BUTTON1 is pressed.
for(int count = 300; count > 0; count--) {
    delay(10); // test the button every 10 ms
    if (digitalRead(BUTTON1) == LOW) {
        return; // skip out of the changeLights() function
    }
}

(Just saw Edgar Bonet's comment about the blink without delay Ardino example, which is another valid way to do the same thing. You could also use the millis() function and calculate the time when the next state transition should happen.)
Since this is an educational example, it's worth looking into how you would implement this as a state machine. (The traffic lights controller is often used as an introduction to state machines.) There's two types of state machines, Mealy and Moore, the difference is that one kind the outputs are determined only by the internal state, and the other kind, the outputs are a function of the internal state and the inputs.
A simple traffic light controller state machine might look like this:

state 0: initialize; next state=1
state 1: Red light on, timer=5 seconds, next state=2
state 2: Green light on, timer=3 seconds, next state=3
state 3: Amber light on, timer=1 seconds, next state=1

Use a timing countdown like in the example above, and when the countdown reaches 0, advance to the next state.
const int S0_INIT = 0; // state 0: initialize
const int S1_RED = 1; // state 1: Red light on
const int S2_GREEN = 2; // state 2: Green light on
const int S3_AMBER = 3; // state 3: Amber light on
int state = S0_INIT;
int stateTimer = 0;
// void setup() not shown; configures input and output pins by pinMode(...)
void loop()
{
    if (stateTimer < 0) { stateTimer = 0; state = S0_INIT; return; }
    if (stateTimer > 0) {
        stateTimer = stateTimer - 1;
        delay(10); // 10 ms interval
        return;
    }
    switch(state) {
    case S0_INIT: // state 0: initialize; next state=1
        stateTimer = 0;
        state = S1_RED;
        break;
    case S1_RED: // state 1: Red light on, timer=5 seconds, next state=2
        // digitalWrite(... etc.) Red light on
        stateTimer = 500;
        state = S2_GREEN;
        break;
    case S2_GREEN: // state 2: Green light on, timer=3 seconds, next state=3
        // digitalWrite(... etc.) Green light on
        stateTimer = 300;
        state = S3_AMBER;
        break;
    case S3_AMBER: // state 3: Amber light on, timer=1 seconds, next state=1
        // digitalWrite(... etc.) Amber light on
        stateTimer = 100;
        state = S1_RED;
        break;
    }
}

A more advanced traffic light controller (that responds to input) might look like this:

state 0: initialize; next state=1
state 1: Red light on, next state=2 (unless SWITCH1=HIGH, next state=4)
state 2: Green light on, next state=3 (unless SWITCH1=HIGH, next state=4)
state 3: Amber light on, next state=1 (unless SWITCH1=HIGH, next state=4)
state 4: Red light on, next state=5 (unless SWITCH1=LOW, next state=2)
state 5: no lights on, next state=4 (unless SWITCH1=LOW, next state=2)

An external input SWITCH1 switches this traffic controller between Red-Amber-Green sequence (states 1-2-3) and flashing-Red sequence (states 4-5). Adding constants for S4_BLINKING_RED=4 and S5_BLINKING_RED=5 and replacing the switch(state):
    switch(state) {
    case S0_INIT:
        stateTimer = 0;
        state = S1_RED;
        break;
    case S1_RED:
        // digitalWrite(... etc.) Red light on
        stateTimer = 500;
        state = S2_GREEN;
        if (digitalRead(SWITCH1) == HIGH) {
            state = S4_BLINKING_RED;
        }
        break;
    case S2_GREEN:
        // digitalWrite(... etc.) Green light on
        stateTimer = 300;
        state = S3_AMBER;
        if (digitalRead(SWITCH1) == HIGH) {
            state = S4_BLINKING_RED;
        }
        break;
    case S3_AMBER:
        // digitalWrite(... etc.) Amber light on
        stateTimer = 100;
        state = S1_RED;
        if (digitalRead(SWITCH1) == HIGH) {
            state = S4_BLINKING_RED;
        }
        break;
    case S4_BLINKING_RED:
        // digitalWrite(... etc.) Red light on
        stateTimer = 50;
        state = S5_BLINKING_RED;
        if (digitalRead(SWITCH1) == LOW) {
            state = S2_GREEN;
        }
        break;
    case S5_BLINKING_RED:
        // digitalWrite(... etc.) no lights on
        stateTimer = 50;
        state = S4_BLINKING_RED;
        if (digitalRead(SWITCH1) == LOW) {
            state = S2_GREEN;
        }
        break;
    }

(Remember to define the SWITCH1 pin, and configure pinMode(SWITCH1 ) in setup().)
Of course a real traffic light controller has more lights, say Northbound-Red, Northbound-Amber, Northbound-Green, Westbound-Red, Westbound-Amber, Westbound-Green, etc. Not to mention left turn arrows and maybe even "vehicle present" sensors. For a smart traffic light controller like that, the state is named by what traffic flow is authorized during that state:

state 1: northbound-southbound traffic green, 5 seconds, next state 2
state 2: northbound-southbound traffic amber, 2 seconds, next state 3
state 3: all lights red, 0.5 second, next state 4 (unless no vehicles waiting west-east lanes, then next state 6)
state 4: westbound-eastbound traffic green, 5 seconds, next state 5
state 5: westbound-eastbound traffic amber, 2 seconds, next state 6
state 6: all lights red, 0.5 second, next state 7 (unless no vehicles waiting N-W nor S-E left turn bays, then next state 9)
state 7: north-to-west left turn and south-to-east left turn green, 3 seconds, next state 8
state 8: north-to-west left turn and south-to-east left turn amber, 2 seconds, next state 9
state 9: all lights red, 0.5 second, next state 10 (unless no vehicles waiting W-S nor E-N left turn bays, then next state 12)
state 10: west-to-south left turn and east-to-north left turn green, 3 seconds, next state 11
state 11: west-to-south left turn and east-to-north left turn amber, 2 seconds, next state 1
state 12: all lights red, 0.5 second, next state 1 (unless no vehicles waiting north-south lanes, then next state 3)

The power of using state machines is that they all use the same basic "engine", just with more states, more outputs, more inputs. If the traffic engineer wants to adjust the timing to improve the flow of traffic, that only requires adjusting some of the data, which is much lower risk than rewriting code.  ... and of course state machines apply to more than just traffic lights, it's a very generally useful design technique.

Agreed, a state machine allow for much more complex situations, while still being readable.

MarkU provided a pretty thorough answer with all the whys and hows of
state machines. This is definitely the way to go, and I encourage you to
read that answer very carefully.
I wrote a comment to your question where I suggest dropping delay() in
order for your loop to never block and your program to be responsive to
user input. Now I am writing this answer only to show you how to combine
both ideas, i.e. implement a state machine without delays. I do not
think this code needs any explanation besides those in MarkU's
answer and in the Blink
without delay
Arduino example.
// Pinout.
const int red = 13, yellow = 12, green = 11, reset = 10;

void setup() {
    pinMode(red,    OUTPUT);
    pinMode(yellow, OUTPUT);
    pinMode(green,  OUTPUT);
    pinMode(reset,  INPUT_PULLUP);  // use internal pull-up
}

void loop() {
    static enum { INIT, RED, RED_AMBER, GREEN, GREEN_AMBER } state = INIT;
    static uint32_t duration;
    static uint32_t last_change;
    uint32_t now = millis();

    // Sense the reset button.
    if (digitalRead(reset) == LOW)
        state = INIT;

    // Wait at this state for the specified duration.
    if (state != INIT && now - last_change < duration)
        return;

    // Switch to next state.
    switch (state) {
        case INIT:
        case GREEN_AMBER:
            state = RED;
            duration = 3000;
            digitalWrite(green,  LOW);
            digitalWrite(yellow, LOW);
            digitalWrite(red,    HIGH);
            break;
        case RED:
            state = RED_AMBER;
            duration = 3000;
            digitalWrite(green,  LOW);
            digitalWrite(yellow, HIGH);
            digitalWrite(red,    HIGH);
            break;
        case RED_AMBER:
            state = GREEN;
            duration = 3000;
            digitalWrite(green,  HIGH);
            digitalWrite(yellow, LOW);
            digitalWrite(red,    LOW);
            break;
        case GREEN:
            state = GREEN_AMBER;
            duration = 3000;
            digitalWrite(green,  HIGH);
            digitalWrite(yellow, HIGH);
            digitalWrite(red,    LOW);
            break;
    }
    last_change = now;
}

I would normally have declared duration as a static const. I kept it
non-const only to follow MarkU's steps and make it easy to have
different durations for different states (really, the green light should
last longer...).

Very good! I would make pinMode(reset,  INPUT_PULLUP); to save having to have an external pull-up resistor.

@NickGammon: Good point! I edited the answer to follow your suggestion.

The best way to handle this problem is using a state machine, as shown in all the other answers. In fact, this IS the classical problem to learn how to use and implement state machines.
I just wanted to add the "fast" solution to your problem, which will enable you to do what you want without changing your code too much:
void changeLights(){
    unsigned long startTime;

    // red on, other off for 3 seconds
    digitalWrite(green,LOW);
    digitalWrite(yellow,LOW);
    digitalWrite(red,HIGH);
    startTime = millis();
    while ((millis() - startTime) < 3000)
    { // Wait for 3 seconds while checking for the button
        if (digitalRead(buttonPin) == HIGH)
            return; // Just exit this function; the loop will start again
    }

    [ repeat for the other colors ]
}