Arduino interruption (on pin change) I use the interrupt function to fill an array with values received from digitalRead().

 void setup() {
      Serial.begin(115200);
       attachInterrupt(0, test_func, CHANGE);
    }

    void test_func(){
      if(digitalRead(pin)==HIGH){
          test_array[x]=1;
        } else if(digitalRead(pin)==LOW){
          test_array[x]=0;
        }
         x=x+1;
    }

That problem is that when I print test_array there are values like: 111 or 000.

As I understand it, if I use the CHANGE option in the attachInterrupt() function, then the data sequence should always be 0101010101 without repeating.

The data changes quite fast since it comes from a radio module.

As a sort of prologue to this overly long answer...

This question got me deeply captivated with the problem of interrupt
latency, to the point of loosing sleep in counting cycles instead of
sheep. I am writing this response more for sharing my findings
than for just answering the question: most of this material may actually
not be at a level suitable for a proper answer. I hope it will be
useful, however, for readers that land here in search of solutions for
latency problems. The first few sections are expected to be useful to a
wide audience, including the original poster. Then, it gets hairy along
the way.

Clayton Mills already explained in his answer that there is some latency
in responding to interrupts. Here I will focus on quantifying the
latency (which is huge when using the Arduino libraries), and on the
means to minimize it. Most of what follows is specific to the hardware
of the Arduino Uno and similar boards.

Minimizing the interrupt latency on the Arduino

(or how to get from 99 down to 5 cycles)

I will use the original question as a working example, and restate the
problem in terms of interrupt latency. We have some external event that
triggers an interrupt (here: INT0 on pin change). We need to take some
action when the interrupt is triggered (here: read a digital input). The
problem is: there is some delay between the interrupt being triggered
and our taking the appropriate action. We call this delay "interrupt
latency". A long latency is detrimental in many situations. In this
particular example, the input signal may change during the delay, in
which case we get a faulty reading. There is nothing we can do to avoid
the delay: it is intrinsic to the way interrupts work. We can, however,
try to make it as short as possible, which should hopefully minimize the
bad consequences.

The first obvious thing we can do is take the time-critical action,
inside the interrupt handler, as soon as possible. This means calling
digitalRead() once (and only once) at the very beginning of the
handler. Here is the zeroth version of the program upon which we will
build:

#define INT_NUMBER 0
#define PIN_NUMBER 2    // interrupt 0 is on pin 2
#define MAX_COUNT  200

volatile uint8_t count_edges;  // count of signal edges
volatile uint8_t count_high;   // count of high levels

/* Interrupt handler. */
void read_pin()
{
    int pin_state = digitalRead(PIN_NUMBER);  // do this first!
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (pin_state == HIGH) count_high++;
}

void setup()
{
    Serial.begin(9600);
    attachInterrupt(INT_NUMBER, read_pin, CHANGE);
}

void loop()
{
    /* Wait for the interrupt handler to count MAX_COUNT edges. */
    while (count_edges < MAX_COUNT) { /* wait */ }

    /* Report result. */
    Serial.print("Counted ");
    Serial.print(count_high);
    Serial.print(" HIGH levels for ");
    Serial.print(count_edges);
    Serial.println(" edges");

    /* Count again. */
    count_high = 0;
    count_edges = 0;  // do this last to avoid race condition
}

I tested this program, and the subsequent versions, by sending it trains
of pulses of varying widths. There is enough spacing between the pulses
to ensure that no edge is missed: even if the falling edge is received
before the previous interrupt is done, the second interrupt request will
be put on hold and eventually serviced. If a pulse is shorter than the
interrupt latency, the program reads 0 on both edges. The reported
number of HIGH levels is then the percentage of correctly read pulses.

What happens when the interrupt is triggered?

Before trying to improve the code above, we will take a look at the
events that unfold right after the interrupt is triggered. The hardware
part of the story is told by the Atmel documentation. The software part,
by disassembling the binary.

Most of the time, the incoming interrupt is serviced right away. It may
happen, however, that the MCU (meaning "microcontroller") is in the
middle of some time-critical task, where interrupt servicing is
disabled. This is typically the case when it is already servicing
another interrupt. When this happens, the incoming interrupt request is
put on hold and serviced only when that time-critical section is done.
This situation is hard to avoid completely, because there are quite a
few of those critical sections in the Arduino core library (which I will
call "libcore" in the following). Fortunately, these sections are
short and run only every so often. Thus, most of the time, our interrupt
request will be serviced right away. In the following, I will assume
that we do not care about those few instances when this is not the case.

Then, our request is serviced immediately. This still involves a lot of
stuff that can take quite a while. First, there is a hardwired sequence.
The MCU will finish executing the current instruction. Fortunately, most
instructions are single-cycle, but some can take up to four cycles.
Then, the MCU clears an internal flag that disables further servicing of
interrupts. This is intended to prevent nested interrupts. Then, the PC
is saved into the stack. The stack is an area of RAM reserved for this
kind of temporary storage. The PC (meaning "Program Counter") is an
internal register holding the address of the next instruction the MCU is
about to execute. This is what allows the MCU to know what to do next,
and saving it is essential because it will have to be restored in order
for the main program to resume from where it was interrupted. The PC is
then loaded with a hardwired address specific to the request received,
and this is the end of the hardwired sequence, the rest being
software-controlled.

The MCU now executes the instruction from that hardwired address. This
instruction is called an "interrupt vector", and is generally a "jump"
instruction that will bring us to a special routine called an ISR
("Interrupt Service Routine"). In this case, the ISR is called
"__vector_1", a.k.a. "INT0_vect", which is a misnomer because it is
an ISR, not a vector. This particular ISR comes from libcore. Like any
ISR, it starts with a prologue that saves a bunch of internal CPU
registers on the stack. This will allow it to use those registers and,
when it is done, restore them to their previous values in order not to
disturb the main program. Then, it will look for the interrupt handler
that was registered with attachInterrupt(), and it will call that
handler, which is our read_pin() function above. Our function will
then call digitalRead() from libcore. digitalRead() will look into
some tables in order to map the Arduino port number to the hardware I/O
port it has to read and the associated bit number to test. It will also
check whether there is a PWM channel on that pin that would need to be
disabled. It will then read the I/O port... and we are done. Well, we
are not really done servicing the interrupt, but the time-critical task
(reading the I/O port) is done, and it is all that matters when we are
looking at latency.

Here is a short summary of all the above, together with the associated
delays in CPU cycles:

hardwired sequence: finish current instruction, prevent nested
interrupts, save PC, load address of vector (≥ 4 cycles)
execute interrupt vector: jump to ISR (3 cycles)
ISR prologue: save registers (32 cycles)
ISR main body: locate and call user-registered function (13 cycles)
read_pin: call digitalRead (5 cycles)
digitalRead: find the relevant port and bit to test (41 cycles)
digitalRead: read the I/O port (1 cycle)

We will assume the best case scenario, with 4 cycles for the
hardwired sequence. This gives us a total latency of 99 cycles, or
about 6.2 µs with a 16 MHz clock. In the following, I will
explore some tricks that can be used to lower this latency. They come
roughly in increasing order of complexity, but they all need us to
somehow dig into the internals of the MCU.

Use direct port access

The obvious first target for shortening the latency is digitalRead().
This function provides a nice abstraction to the MCU hardware, but it is
too inefficient for time-critical work. Getting rid of this one is
actually trivial: we just have to replace it with digitalReadFast(),
from the digitalwritefast
library. This cuts the latency almost by half at the cost of a small
download!

Well, that was too easy to be any fun, I will rather show you how to do
it the hard way. The purpose is to get us started into low-level stuff.
The method is called "direct port access" and is nicely documented on
the Arduino reference at the page on Port
Registers. At this
point, it is a good idea to download and take a look at the ATmega328P
datasheet.
This 650-page document may seem somewhat daunting at first look. It is,
however, well organised into sections specific to each of the MCU
peripherals and features. And we only need to check the sections
relevant to what we are doing. In this case, it is the section named
I/O ports. Here is a summary of what we learn from those readings:

The Arduino pin 2 is actually called PD2 (i.e. port D, bit 2) on the
AVR chip.
We get the whole port D at once by reading a special MCU register called
"PIND".
We then check bit number 2 by doing a bitwise logical and (the C ‘&’
operator) with 1 << 2.

So, here is our modified interrupt handler:

#define PIN_REG    PIND  // interrupt 0 is on AVR pin PD2
#define PIN_BIT    2

/* Interrupt handler. */
void read_pin()
{
    uint8_t sampled_pin = PIN_REG;            // do this first!
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (sampled_pin & (1 << PIN_BIT)) count_high++;
}

Now, our handler will read the I/O register as soon as it is called. The
latency is 53 CPU cycles. This simple trick saved us 46 cycles!

Write your own ISR

The next target for cycle-trimming is the INT0_vect ISR. This ISR is
needed for providing the functionality of attachInterrupt(): we can
change interrupt handlers at any time during program execution. However,
although nice to have, this is not really useful for our purpose. Thus,
instead of having the libcore's ISR locate and call our interrupt
handler, we will save a few cycles by replacing the ISR by our
handler.

This is not as hard as it sounds. ISRs can be written like normal
functions, we just have to be aware of their specific names, and define
them using a special ISR() macro from avr-libc. At this point it would
be good to have a look at the avr-libc's documentation on
interrupts,
and at the datasheet section named External Interrupts. Here is the
short summary:

We have to write a bit in a special hardware register called EICRA
(External Interrupt Control Register A) in order to configure the
interrupt to be triggered on any change of the pin value. This will be
done in setup().
We have to write a bit in another hardware register called EIMSK
(External Interrupt MaSK register) in order to enable the INT0
interrupt. This will also be done in setup().
We have to define the ISR with the syntax ISR(INT0_vect) { ... }.

Here is the code for the ISR and setup(), everything else is
unchanged:

/* Interrupt service routine for INT0. */
ISR(INT0_vect)
{
    uint8_t sampled_pin = PIN_REG;            // do this first!
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (sampled_pin & (1 << PIN_BIT)) count_high++;
}

void setup()
{
    Serial.begin(9600);
    EICRA = 1 << ISC00;  // sense any change on the INT0 pin
    EIMSK = 1 << INT0;   // enable INT0 interrupt
}

This comes with a free bonus: since this ISR is simpler than the one it
replaces, it needs less registers to do its job, then the
register-saving prologue is shorter. Now we are down to a latency of 20
cycles. Not bad considering that we started close to 100!

At this point I would say we are done. Mission accomplished. What
follows is only for those who are not afraid of getting their hands
dirty with some AVR assembly. Otherwise you can stop reading here, and
thank-you for getting so far.

Write a naked ISR

Still here? Good! For proceeding further, it would be helpful to have at
least some very basic idea of how assembly works, and to take a look at
the Inline Assembler
Cookbook
from the avr-libc documentation. At this point, our interrupt entry
sequence looks like this:

hardwired sequence (4 cycles)
interrupt vector: jump to ISR (3 cycles)
ISR prologue: save regs (12 cycles)
first thing in the ISR body: read the IO port (1 cycle)

If we want to do better, we have to move the reading of the port into
the prologue. The idea is the following: reading the PIND register will
clobber one CPU register, thus we need to save at least one register
before doing that, but the other registers can wait. We then need to
write a custom prologue that reads the I/O port right after saving the
first register. You have already seen in the avr-libc interrupt
documentation (you have read it, right?) that an ISR can be made
naked, in which case the compiler will emit no prologue or epilogue,
allowing us to write our own custom version.

The problem with this approach is that we will probably end up writing
the whole ISR in assembly. Not a big deal, but I would rather have the
compiler write those boring prologues and epilogues for me. So, here is
the dirty trick: we will split the ISR in two parts:

the first part will be a short assembly fragment that will

save a single register to the stack
read PIND into that register
store that value into a global variable
restore the register from the stack
jump to the second part

the second part will be regular C code with compiler-generated
prologue and epilogue

Our previous INT0 ISR is then replaced by this:

volatile uint8_t sampled_pin;    // this is now a global variable

/* Interrupt service routine for INT0. */
ISR(INT0_vect, ISR_NAKED)
{
    asm volatile(
    "    push r0                \n"  // save register r0
    "    in r0, %[pin]          \n"  // read PIND into r0
    "    sts sampled_pin, r0    \n"  // store r0 in a global
    "    pop r0                 \n"  // restore previous r0
    "    rjmp INT0_vect_part_2  \n"  // go to part 2
    :: [pin] "I" (_SFR_IO_ADDR(PIND)));
}

ISR(INT0_vect_part_2)
{
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (sampled_pin & (1 << PIN_BIT)) count_high++;
}

Here we are using the ISR() macro to have the compiler instrument
INT0_vect_part_2 with the required prologue and epilogue. The compiler
will complain that "‘INT0_vect_part_2’ appears to be a misspelled
signal handler", but the warning can be safely ignored. Now the ISR has
a single 2-cycle instruction before the actual port read, and the total
latency is only 10 cycles.

Use the GPIOR0 register

What if we could have a register reserved for this specific job? Then,
we would not need save anything before reading the port. We can actually
ask the compiler to bind a global variable to a
register.
This, however, would require us to recompile the whole Arduino core and
libc in order to make sure the register is always reserved. Not really
convenient. On the other hand, the ATmega328P happens to have three
registers that are not used by the compiler nor any library, and are
available for storing whatever we want. They are called GPIOR0, GPIOR1
and GPIOR2 (General Purpose I/O Registers). Although they are mapped
in the I/O address space of the MCU, these are actually not I/O
registers: they are just plain memory, like three bytes of RAM that
somehow got lost in a bus and ended up in the wrong address space. These
are not as capable as the internal CPU registers, and we cannot copy
PIND into one of these with the in instruction. GPIOR0 is interesting,
though, in that it is bit-addressable, just like PIND. This will allow
us to transfer the information without clobbering any internal CPU
register.

Here is the trick: we will make sure that GPIOR0 is initially zero (it
is actually cleared by hardware at boot time), then we will use the
sbic (Skip next instruction if some Bit in some I/o register is Clear)
and the sbi (Set to 1 some Bit in some I/o register) instructions as
follows:

sbic PIND, 2   ; skip the following if bit 2 of PIND is clear
sbi GPIOR0, 0  ; set to 1 bit 0 of GPIOR0

This way, GPIOR0 will end up being 0 or 1 depending on the bit we wanted
to read from PIND. The sbic instruction takes 1 or 2 cycles to execute
depending on whether the condition is false or true. Obviously, the PIND
bit is accessed on the first cycle. In this new version of the code, the
global variable sampled_pin is not useful anymore, since it is
basically replaced by GPIOR0:

/* Interrupt service routine for INT0. */
ISR(INT0_vect, ISR_NAKED)
{
    asm volatile(
    "    sbic %[pin], %[bit]    \n"
    "    sbi %[gpio], 0         \n"
    "    rjmp INT0_vect_part_2  \n"
    :: [pin]  "I" (_SFR_IO_ADDR(PIND)),
       [bit]  "I" (PIN_BIT),
       [gpio] "I" (_SFR_IO_ADDR(GPIOR0)));
}

ISR(INT0_vect_part_2)
{
    if (count_edges < MAX_COUNT) {
        count_edges++;
        if (GPIOR0) count_high++;
    }
    GPIOR0 = 0;
}

It should be noted that GPIOR0 has to always be reset in the ISR.

Now, the sampling of the PIND I/O register is the very first thing done
inside the ISR. Total latency is 8 cycles. This is about the best we can
do before getting stained with terribly sinful kludges. This is again a
good opportunity to stop reading...

Put the time-critical code in the vector table

For those still here, here is our current situation:

hardwired sequence (4 cycles)
interrupt vector: jump to ISR (3 cycles)
ISR body: read the IO port (on 1st cycle)

There is obviously little room for improvement. The only way we could
shorten the latency at this point is by replacing the interrupt vector
itself by our code. Be warned that this should be immensely distasteful
to anyone who values clean software design. But it is possible, and I
will show you how.

The layout of the ATmega328P vector table can be found in the datasheet,
section Interrupts, subsection Interrupt Vectors in ATmega328 and
ATmega328P. Or by disassembling any program for this chip. Here is how
it looks like. I am using avr-gcc and avr-libc's conventions (__init
is vector 0, addresses are in bytes) which are different from Atmel's.

address │ instruction     │ comment
────────┼─────────────────┼──────────────────────
 0x0000 │ jmp __init      │ reset vector
 0x0004 │ jmp __vector_1  │ a.k.a. INT0_vect
 0x0008 │ jmp __vector_2  │ a.k.a. INT1_vect
 0x000c │ jmp __vector_3  │ a.k.a. PCINT0_vect
  ...
 0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect

Each vector has a 4-byte slot, filled with a single jmp instruction.
This is a 32-bit instruction, unlike most AVR instructions which are
16-bit. But a 32-bit slot is too small to hold the first part of our
ISR: we can fit the sbic and sbi instructions, but not the rjmp.
If we do that, the vector table ends up looking like this:

address │ instruction     │ comment
────────┼─────────────────┼──────────────────────
 0x0000 │ jmp __init      │ reset vector
 0x0004 │ sbic PIND, 2    │ the first part...
 0x0006 │ sbi GPIOR0, 0   │ ...of our ISR
 0x0008 │ jmp __vector_2  │ a.k.a. INT1_vect
 0x000c │ jmp __vector_3  │ a.k.a. PCINT0_vect
  ...
 0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect

When INT0 fires, PIND will be read, the relevant bit will be copied into
GPIOR0, and then the execution will fall through to the next vector.
Then, the ISR for INT1 will be called, instead of the ISR for INT0. This
is creepy, but since we are not using INT1 anyway, we will just "hijack"
its vector for servicing INT0.

Now, we just have to write our own custom vector table to override the
default one. It turns out it is not so easy. The default vector table is
provided by the avr-libc distribution, in an object file called
crtm328p.o that is automatically linked with any program we build.
Unlike library code, object-file code is not meant to be overridden:
trying to do that will give a linker error about the table being defined
twice. This means we have to replace the whole crtm328p.o with our
custom version. One option is to download the full avr-libc source
code, do our
custom modifications in
gcrt1.S,
then build this as a custom libc.

Here I went for a lighter, alternative approach. I wrote a custom
crt.S, which is a simplified version of the original from avr-libc. It
lacks a few rarely used features, like the ability to define a "catch
all" ISR, or to be able to terminate the program (i.e. freeze the
Arduino) by calling exit(). Here is the code. I trimmed the repetitive
part of the vector table in order to minimize scrolling:

#include <avr/io.h>

.weak __heap_end
.set  __heap_end, 0

.macro vector name
    .weak \name
    .set \name, __vectors
    jmp \name
.endm

.section .vectors
__vectors:
    jmp __init
    sbic _SFR_IO_ADDR(PIND), 2   ; these 2 lines...
    sbi _SFR_IO_ADDR(GPIOR0), 0  ; ...replace vector_1
    vector __vector_2
    vector __vector_3
    [...and so forth until...]
    vector __vector_25

.section .init2
__init:
    clr r1
    out _SFR_IO_ADDR(SREG), r1
    ldi r28, lo8(RAMEND)
    ldi r29, hi8(RAMEND)
    out _SFR_IO_ADDR(SPL), r28
    out _SFR_IO_ADDR(SPH), r29

.section .init9
    jmp main

It can be compiled with the following command line:

avr-gcc -c -mmcu=atmega328p silly-crt.S

The sketch is identical to the previous one except that there is no
INT0_vect, and INT0_vect_part_2 is replaced by INT1_vect:

/* Interrupt service routine for INT1 hijacked to service INT0. */
ISR(INT1_vect)
{
    if (count_edges < MAX_COUNT) {
        count_edges++;
        if (GPIOR0) count_high++;
    }
    GPIOR0 = 0;
}

To compile the sketch, we need a custom compile command. If you have
followed so far, you probably know how to compile from the command line.
You have to explicitly request silly-crt.o to be linked to your program,
and add the -nostartfiles option to avoid linking in the original
crtm328p.o.

Now, the reading of the I/O port is the very first instruction executed
after the interrupt triggers. I tested this version by sending it short
pulses from another Arduino, and it can catch (although not reliably)
the high level of pulses as short as 5 cycles. There is nothing more we
can do to shorten the interrupt latency on this hardware.


Is my Arduino board defect? No matter what program I upload the pin 13 turns on and off 3 times and that's it Just trying to find out if my Arduino UNO R1 board is broken or not.

First of all, everything seems normal, Arduino board shows "on" (green) when I plug it on my computer, I also can verify and upload programs to my Arduino board. But, no matter what program I upload the pin 13 turns on and off 3 times and that's it. I'm checkin it by using a LED.
Eg. if I want to use another pin (ex. 7, 8, 12) it doesn't work, or even to write a program for turning on/off 9 times pin 13 doesn't work...

Note: I noticed that pin 8 turns the LED for less than a 1/2 a second.

I already tried to restart board by bridging the reset pin and also by pushing reset directly on the board, I also reinstalled Arduino Genuino Application. I thought to update Atmega8U2 firmware but accordingly to Arduino site I don't need to update since I have firmware rev. 0.01.

It would be also great not to have to buy a new Arduino UNO. Thanks for your help

Edit:
Here is how I'm trying to make pin 12 work

int ledPin = 12;

void setup()
{
    pinMode(ledPin, OUTPUT);
}

void loop()
{
    digitalWrite(ledPin, HIGH);
    delay(2000);
    digitalWrite(ledPin, LOW);
    delay(2000);
}

The best way to check if Arduino is working or not is to install Firmata. Here's the necessary steps:

1) Download Firmata application from the official website.

2) Connect Arduino to the computer

3) Open the Arduino IDE and burn the example Standard Firmata [File - Examples - Firmata - Standard Firmata]

4) Open the application, leaving the Arduino connected.

5) Chose the right serial port and debug every pin =D


Processing error with processing-arduino examples I have followed the instructions to run the Arduino processing examples but with no success.

Always import processing.serial.*; does not name a type. Which is perhaps a library (processing-arduino) related error.

My sketch is a sketch that comes with processing-arduino library.

I have searched for a long time with no solution. Any suggestion?

Errors:

arduino_output:28: error: 'import' does not name a type
arduino_output:30: error: 'import' does not name a type
arduino_output:32: error: 'Arduino' does not name a type
arduino_output:34: error: 'color' does not name a type
arduino_output:35: error: 'color' does not name a type
arduino_output:37: error: expected unqualified-id before '[' token
arduino_output.pde: In function 'void setup()':
arduino_output:42: error: 'size' was not declared in this scope
arduino_output:45: error: 'Arduino' was not declared in this scope
arduino_output:45: error: 'println' was not declared in this scope
arduino_output:50: error: 'arduino' was not declared in this scope
arduino_output:50: error: expected type-specifier before 'Arduino'
arduino_output:50: error: expected `;' before 'Arduino'
arduino_output:58: error: expected unqualified-id before numeric constant
arduino_output.pde: In function 'void draw()':
arduino_output:62: error: 'off' was not declared in this scope
arduino_output:62: error: 'background' was not declared in this scope
arduino_output:63: error: 'on' was not declared in this scope
arduino_output:63: error: 'stroke' was not declared in this scope
arduino_output:66: error: 'values' was not declared in this scope
arduino_output:66: error: 'Arduino' was not declared in this scope
arduino_output:66: error: expected unqualified-id before numeric constant
arduino_output:66: error: expected `)' before numeric constant
arduino_output:67: error: 'fill' was not declared in this scope
arduino_output:69: error: 'fill' was not declared in this scope
arduino_output:71: error: 'rect' was not declared in this scope
arduino_output.pde: In function 'void mousePressed()':
arduino_output:77: error: 'mouseX' was not declared in this scope
arduino_output:80: error: 'values' was not declared in this scope
arduino_output:80: error: 'Arduino' was not declared in this scope
arduino_output:80: error: expected unqualified-id before numeric constant
arduino_output:80: error: expected `)' before numeric constant
arduino_output:81: error: 'arduino' was not declared in this scope
arduino_output:81: error: expected unqualified-id before numeric constant
arduino_output:82: error: expected unqualified-id before numeric constant
arduino_output:82: error: expected `;' before numeric constant
arduino_output:84: error: 'arduino' was not declared in this scope
arduino_output:84: error: expected unqualified-id before numeric constant
arduino_output:85: error: expected unqualified-id before numeric constant
arduino_output:85: error: expected `;' before numeric constant

Note: I am testing this on OS X, so my paths may differ slightly from yours.

I have managed to reproduce your issue, by incorrectly copying the arduino directory, from the unzipped processing2-arduino.zip package, to the libraries directory under the Arduino directory in my home directory, thus

/Users/user/Documents/Arduino/libraries/arduino

Then opening the Arduino IDE and running the arduino_output example, via the menu, File -> Sketchbook -> Libraries -> Arduino -> arduino_output. When I hit the compile button, in the Arduino IDE, the compiler throws up the exact same errors that you describe in your question.

However this is not the correct usage of this package. This package is intended to be used in conjunction with the Processing application, not the Arduino IDE. You should download Processing and then follow the instructions again:

  Unzip the library and copy the "arduino" folder into the "libraries" sub-folder of your Processing Sketchbook. (You can find
  the location of your Sketchbook by opening the Processing Preferences.
  If you haven't made a "libraries" sub-folder, create one.)

Thus, on OS X, the path should now be

/Users/user/Documents/Processing/libraries/arduino

However, as usual, the documentation on the Arduino website leaves a lot to be desired. Pay careful attention to the following paragraph if you are running OS X or Linux:

  Note: if you run Linux, you need to change Arduino.jar into
  arduino.jar, because Linux is case sensitive and it does not work if
  you don't change this letter (Arduino.jar is in the folder "library"
  of this Processing Library).

So,

/Users/user/Documents/Arduino/libraries/arduino/library/Arduino.jar

becomes

/Users/user/Documents/Arduino/libraries/arduino/library/arduino.jar

Relaunch the Processing application. File -> Examples..., opens up a window, scroll down to Contributed Libraries, open that, open Arduino (Firmata), open the arduino_output example. Hit the Run button, and after compiling you should see the window below:

HTH.


Difficulties with raw string literals I have an application where I would like to include an external multiline script as a const in my sketch. As far as I understand from C++11, this should work:

raw_string_literal_test.ino

const char *script =
#include "script.txt"
;

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

}

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

}

script.txt

R"(Line 1
Line 2
Line 3
Line 4
Line 5
Line 6)"

script.txt is placed in the same folder as raw_string_literal_test.ino

However, upon clicking Verify (selected board is Arduino/Genuino Uno, Arduino version is 1.6.12 on Mac OS 10.11.6) I get the following error:

/Users/owner/Desktop/raw_string/raw_string.ino:2:22: fatal error: script.txt: No such file or directory
 #include "script.txt"
                      ^
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.

What am I doing incorrectly?

Unlike other more "normal" build systems, the Arduino IDE doesn't compile the files in the project directory.

Instead it loads all the files with certain extensions into the IDE, each in its own tab. When you press the compile button it then writes the contents of each of those tabs to files in a temporary build folder and then compiles there.

Because of that only files with certain extensions ever get placed in the build folder. Those include:

.pde and .ino for sketch files
.c and .cpp for C and C++ source
.h for headers
.S for assembly source.

There may be a few others as well but those are the main ones. Things like text files aren't considered source files and thus aren't ever seen by the IDE.


How can you check how long a timer interrupt really is? I'm trying to set a 33 ms interrupt on my Arduino Mega and I'm not sure if I a in fact getting that kind of delay time. Is there a way to check?

I've calculated that that I need 515.6 ticks to achive this kind of delay with a prescaler of 1024 and I've coded it up like so:

void setupInterupt()
{
  noInterrupts();
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2 = 0;
  OCR2A = PERIOD - 1;
  TIMSK2 = _BV(OCIE2A);
  TCCR2B |= _BV(CS12) | _BV(CS10); // prescale by 1024
  interrupts();
}

I followed the information on the Arduino Playground page and if my math is correct this interrupt should be going off every 33 milliseconds. I tried to test that using the millis(); method but it only returns the time that program was on.

It doesn't fire every 33 milliseconds. First, you missed setting the CSn1 bit necessary for a 1024 prescaler; second, It looks like you want CTC mode (where the timer resets at OCRnA) but you didn't set the WGM21 bit necessary for that mode. After that your problem is that timer2 is an 8 bit timer and so OCR2A cannot store 515, but you math is correct.

You can get the period you want on a 16-bit timer; on the arduino mega thats timers 1,3,4, and 5.

Anyway here is a simple sketch for finding the average interval between interrupts. It just keeps track of the total time elapsed and the number of times the interrupt fired; the ratio of these two is the average time per interrupt.

In this case, with a prescaler of 1024, OCRA = 0xFF, and CTC mode, it runs at an interrupt every 16.384 ms.

volatile uint16_t interruptCount;
volatile uint32_t start;

ISR(TIMER2_COMPA_vect){
    interruptCount++;
}

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

    noInterrupts();
    TCCR2A = _BV(WGM21);
    TCCR2B = _BV(CS22) | _BV(CS21) | _BV(CS20); // prescale by 1024
    OCR2A = 0xFF;
    TIMSK2 = _BV(OCIE2A);
    // start the timer
    interruptCount = 0;
    start = micros();
    interrupts();
}

void loop(){
    // read interrupt count into a local variable atomically
    noInterrupts();
    uint16_t localCount = interruptCount;
    interrupts();
    uint32_t time = micros() - start;

    // time elapsed
    Serial.print(time);
    Serial.print(" ");

    // number of times the interrupt handler fired
    Serial.print(localCount);
    Serial.print(" ");

    // average number of microseconds per interrupt
    Serial.print(time / localCount);
    Serial.println();

    delay(30);
}


Unable to read Arduino+ESP8266 full get Response Using below code I am able to invoke HTTP Get request, but I am not able to read full HTTP Response. Observing only output like( +IPD,0,141:HTTP/1.7. ). Please let me know how can I read full response?
Any Idea what is the issue?
#include <SoftwareSerial.h>

#define RX 2
#define TX 3
String WIFI_SSID = "xyz";       // Your WiFi ssid
String PASSWORD = "xys";         // Password

String HOST = "192.168.0.156";
String PATH = "/test";
String PORT = "8080";

int countTrueCommand;
int countTimeCommand;
boolean found = false;

SoftwareSerial esp8266(RX, TX);

void setup() {
  Serial.begin(9600);
  esp8266.begin(9600);
  esp8266.println("AT");
  Serial.println(esp8266.read());
  sendCommandToESP8266("AT", 5, "OK");
  sendCommandToESP8266("AT+CWMODE=1", 5, "OK");
  sendCommandToESP8266("AT+CWJAP=\"" + WIFI_SSID + "\",\"" + PASSWORD + "\"", 20, "OK");
}

void loop() {
  String postRequest = "GET " + PATH  + " HTTP/1.1\r\n" +
                       "Host: " + HOST + "\r\n" +
                       "Accept: *" + "/" + "*\r\n" +
                       "\r\n";

  sendCommandToESP8266("AT+CIPMUX=1", 5, "OK");
  sendCommandToESP8266("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
  String cipSend = "AT+CIPSEND=0," + String(postRequest.length());
  sendCommandToESP8266(cipSend, 4, ">");
  sendData(postRequest);
  readESP8266(8000);
  sendCommandToESP8266("AT+CIPCLOSE=0", 5, "OK");
}

void sendCommandToESP8266(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");
  while (countTimeCommand < (maxTime * 1))
  {
    esp8266.println(command);
    if (esp8266.find(readReplay))
    {
      found = true;
      break;
    }

    countTimeCommand++;
  }

  if (found == true)
  {
    Serial.println("Success");
    countTrueCommand++;
    countTimeCommand = 0;
  }

  if (found == false)
  {
    Serial.println("Fail");
    countTrueCommand = 0;
    countTimeCommand = 0;
  }

  found = false;
}

void sendData(String postRequest) {
  Serial.println(postRequest);
  esp8266.println(postRequest);
  delay(1500);
  countTrueCommand++;
}

void readESP8266(const int timeout)
{
  String reponse = "";
  long int time = millis();
  while( (time+timeout) > millis())
  {
    while(esp8266.available())
    {
      reponse+=esp8266.readString();
    }
  }
  Serial.print(reponse);
}

Output:
Success
1. at command => AT+CWMODE=1 Success
2. at command => AT+CWJAP="xyz","xys" Success
3. at command => AT+CIPMUX=1 Success
4. at command => AT+CIPSTART=0,"TCP","192.168.0.156",8080 Success
5. at command => AT+CIPSEND=0,56 Success
GET /test HTTP/1.1
Host: 192.168.0.156
Accept: */*

busy s...

Recv 56 bytes

SEND OK

+IPD,0,141:HTTP/1.7. at command => AT+CIPCLOSE=0 Success

Finally the HTTP Get request with Arduino Uno + ESP8266 Wifi shield which is working is below:
// This is a demo example using a public http server for testing both GET and POST requests
#include <Arduino.h>
#include <LiteESP8266Client.h>

#define PACKET_MTU 1500    // Standard network MTU is 1500 bytes

LiteESP8266 radio;

const char ssid[] PROGMEM = "xyz";    //change it to your wifi SSID
const char password[] PROGMEM = "abc";    //change it to your wifi password
const char host[] PROGMEM = "192.168.0.156";
const int port = 8080;

const char http_get_request[] PROGMEM = "GET /test HTTP/1.1\r\n";
const char http_useragent[] PROGMEM = "User-Agent: Arduino-stm32/0.1\r\n";
const char http_content_type_json[] PROGMEM = "Content-Type: application/json\r\n";
const char http_host[] PROGMEM = "Host: 192.168.0.156\r\n";
const char http_close_connection[] PROGMEM = "Connection: close\r\n\r\n";
const char http_content_length_header[] PROGMEM = "Content-Length: ";
const char success[] PROGMEM = "success";
const char failed[] PROGMEM = "failed";
const char CRLF[] PROGMEM = "\r\n";
const char error_data_null[] PROGMEM = "Error: data came back null.";

void setupStationMode() {
  Serial.print("Setup station mode... ");
  if (radio.set_station_mode()) {
    Serial.println("success");
  } else {
    Serial.println("failed");
  }
}

void joinAP() {
  Serial.print("Join AP ");
  Serial.print(ssid);
  Serial.print("... ");
  if (radio.connect_to_ap(ssid, password)) {
    Serial.println("Success");
  } else {
    Serial.println("Failed");
  }
}

void establishTcpConnect() {
  Serial.print("Establish TCP Connection... ");
  if (radio.connect_progmem(host, port)) {
    Serial.println( "Success");
  } else {
    Serial.println( "Failed");
  }
}

void getHttpPacket() {
  char *data;
  while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
    if (data) {
      Serial.println("Packet Received...");
      Serial.println(data);
    } else {
      Serial.println(error_data_null);
    }
  }
  free(data);
}

void httpGet() {
  Serial.println("Sending GET request... ");
  radio.send_progmem(http_get_request);
  radio.send_progmem(http_useragent);
  radio.send_progmem(http_host);
  radio.send_progmem(http_close_connection);
}
void setup() {
  delay(2000);
  radio.begin(9600,2,3);
  Serial.begin(9600);
  while (!Serial) {};

  setupStationMode();
  joinAP();
}

void loop() {
  establishTcpConnect();

  httpGet();
  getHttpPacket();
  }

Output:
Setup station mode... success
Join AP ⸮... Success
Establish TCP Connection... Success
Sending GET request...
Packet Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 27
Date: Fri, 07 Aug 2020 13:04:03 GMT
Connection: close

Greetings from Spring Boot!

But one issue I am facing is after few call the HTTP invocation is getting stopped probably memory being full. Will check this.


Why does an Arduino MEGA 2560 have different PORTS I'm currently looking at my Arduino MEGA 2560 board and was just wondering why there are different ports to it e.g. ANALOG IN, DIGITAL, Communication? in fact I've only seen this in some microcontrollers. Not many microcontrollers have ports dedicated to certain things. Is anyone able to give me an answer as to why there is different ports to the microcontroller? is it making it easier for the chip to handle etc. A detailed but not too detailed answer would be great!

Thats because Arduino has configured the Mega to do so. In microcontrollers you need to select what use will each pin have based on the availability. To make user interface easy arduino has done this based on what is commonly used by everyone. Even then some functions are still not disabled.

For example 50,51,52,53 are SPI pins on mega which use Pin change interrupt for working. Thus it not necessary we use them for SPI we can also use them for Pin change interrupt.

Similar is the case for pins 10,11,12,13. These PWM pins can also be used for Pin change interrupt but other PWM pins cannot.


Arduino nano 33 ble vs ble sense. Power consumption, etc After working with an Arduino Uno at work, I am looking to buy myself a board for some projects/experiments at home. The nano size seems like a great option, especially the one without soldered headers, as it is very flexible and easy to fit in projects with limited space. More specifically, I am interested in nano 33 ble and nano 33 ble sense.
My question is, apart from price does anyone know of any other disadvantages the sense board might have on comparison to the 33 ble?
Does it consume more power if the sensors are not used in a projects (just from being integrated in the board’s circuit)?
Also, does the light intensity sensor work like an LDR (photoresistor)? E.g. will I be able to do things like turn on LEDs automatically when it is dark, based on the sensor’s readings?

The official page for the Nano 33 BLE Sense mentions various things including the datasheet for the light sensor. That appears to be much more sophisticated than an LDR.
According to the sensor documentation (above):

Upon  power-up,  POR,  the  device  initializes  and  immedi-ately enters the low power SLEEP state. In this operational state  the  internal  oscillator  and  other  circuitry  are  not  active,  resulting  in  ultra-low  power  consumption.

You would have to read the documentation for the other devices to check these things. Personally I haven't used one, and Arduino claim it "is a completely new board". So, you may not find a lot of people that can answer those questions.
Keeping power consumption low is quite a complex field. You need to look at clock speeds, sleep states, peripheral power consumption and so on.


Arduino project - will this fit together? I'm about to order parts for my project and I'd like to avoid some rookie mistake I might've missed. I'll be using Arduino chip and a wifi module to host a very simple webpage and a battery to make this all portable. I've decided to use Arduino Mini Pro 8MHz because of 3.3V input voltage, same as ESP8266, also FT232RL to program the board and TPS73601 for my battery. This is where I have some doubts, the battery I've picked is Li-Ion from my old Samsung Galaxy S AFAIK when charged it supplies ~4.2V and nearly discharged ~2.7V so the regulator should work (?). Is using Li-Ion in any way different from regular AA or just +/- because I see 3 pins on the back of it? Except for charging of course I'll be using the phone for that. Thanks in advance for any suggestions.

From what you've provided everything seems to be compatible.

Concerning the battery, a quick look at the Arduino website shows:

  Input Voltage 3.35 -12 V (3.3V model)

Meaning the regulator will work as long as the battery provides voltage above 3.35 but since your battery's voltage drops as it gets depleted you might not get the battery life you'd expect :/. In other words: it'll work initially  until the voltage drops below 3.35V and then you would have to recharge it.

  Is using Li-Ion in any way different from regular AA

Yes and No.
No : both provide a stable DC source and both can be used in similar applications.

Yes: Li-Ion batteries can be recharged and have a longer life-span, and most importantly, Li-Ion batteries don't have a sharp voltage drop as they get depleted, unlike regular AA batteries. Which is a bonus for this project ( i guess :p )

  I see 3 pins on the back of it

There are only 2 pins that actually provide the power from the battery while the third is usually used to monitor temperature or battery life remaining.So you can use this battery by only connecting the power providing pins (usually indicated by + and - ) and safely ignore the third.

Gd Luck!


What is the advantage of a 3MP OV3660 sensor on the ESP32 M5Stack camera if it can only save upto 2MP images? I am making a self-contained stills camera and the ESP32-based modules seem well-suited to my project due to the easy incorporation of a TFT viewfinder screen and TF card slot in one package. I am not interested in saving video or web streaming.
I have worked with the TTGO ESP32 camera that uses the OV2640 2MP sensor and can save full 2MP UXGA (1600x1200) resolution stills (albeit with mandatory JPEG compression turned on - I have only managed to get 1.3 MP images without compression).
I see now there is a version of ESP32 camera that uses the OV3660 3MP sensor (called 'M5Stack Timer Camera'). However, the specs for that camera https://docs.m5stack.com/#/en/unit/timercam say it can save upto a maximum of UXGA - i.e. 2MP images.
So what is the advantage of having a 3MP sensor chip if you can only save 2 MP images? Or is there a way of saving the full 3MP sensor resolution (i.e. 2048 x 1536) stills from this camera?
Thanks

The limit isn't the camera - it's the memory.
At 3 megapixels you have 3145728 pixels. At 3 bytes per pixel (8 bits each of red green and blue) it requires 9437184 bytes to store the image. That's more than can fit into the 8MB PSRAM.
1600x1200 will probably be one of the standard resolutions that the specific camera in use can capture, and is probably the biggest size that is below 8MB in size for a single frame.
So, what advantage of having a 3 megapixel camera? Well, none to you, other than the cost. It's probably cheaper to use a newer 3 megapixel camera than an older 2 megapixel camera.

It is perfectly possible to run at the resolutions you desire though. This resolution is known as QXGA and is supported by the OV3660 driver in the ESP32 Camera library.  There are some caveats though:

You must use JPEG compression. Not only is this to make the image small enough to fit into PSRAM but also to make it possible to write the whole frame into PSRAM fast enough that you don't miss bits of the data.
You will not be able to "do" anything with the image other than send it to somewhere else (such as an SD card or a web server). There just isn't enough room to uncompress the image.


Wearable GPS Antenna I am using the Adafruit Fona 808 to make a wearable device. One of the main features is GPS but I cannot seem to find a suitable antenna for wearables. My question is: What is a good GPS antenna for a wearable project and should it be active or passive?
Thanks

I too thought whats wrong with a normal Antenna, but the answer is the problem is the human body.

There are manufacturers that make "fabric" antennas, but these tend to be Mil-Spec so are going to cost a fortune.  (http://www.pharad.com/gps-wearable-antenna.html)

I found this site that explains what the effect of the body is, and seems to make their own antenna.  http://www.pharad.com/gps-wearable-antenna.html

I think you might be better off looking for a high gain antenna and the choice of active or passive will probably be based on the interference you get from the body.


How to fix compilation error for tone() using same timer as other function I am trying to integrate tone() with the open source program for the Amped heart rate monitor. The error:

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `__vector_7'
sketch\PulseSensorAmped_Arduino_1dot4.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

The program comes in three files. PulseSensorAmped_Arduino_1dot4.cpp I don't think references any timers but references a function in another file with this code:
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED

This uses timer 2; but isn't the error for timer 1? The tone() reference page says that tone interferes with pins 3 and 11. Is there any way to fix this?
references:
https://www.arduino.cc/en/Reference/Tone
https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino

It looks like the Tone library uses Timer 2, and it looks like your other code also uses Timer 2, hence the error message. Vector 7 would be the TIMER2_COMPA_vect (Timer 2 compare "a").

Pins 3 and 11 are from Timer 2.

I wrote a small library that generates tones using the hardware PWM and not interrupts. You can read about it here.

Example code:

#include <TonePlayer.h>

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (220);  // 220 Hz
  delay (500);
  tone1.noTone ();

  tone1.tone (440);
  delay (500);
  tone1.noTone ();

  tone1.tone (880);
  delay (500);
  tone1.noTone ();
  }

void loop() { }

Library can be downloaded from http://www.gammon.com.au/Arduino/TonePlayer.zip

This uses Timer 1 (so that won't interfere with Timer 2) and no interrupts.


Which is a better? GPRS SIM800L or GPRS SIM900? I will implementate the GPRS technologity in my Arduino project, but before buy the module, I want to know which is a better. If GPRS SIM800L or GPRS SIM900? My needs are send JSON array through POST request.

Thanks and best regards.

SIM900 is older type. SIM800L has FM build it and it uses same AT cmds as SIM900.
Also, they are in same quadband. I guess both will work just fine.


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.

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.


Capacitive sensor switch I am trying to get relays to switch on or off based on if I touch a capacitive sensor, basically a light switch. For some reason, I get two readings that are high capacitive readings when I do a printout. I am not really sure why this is happening. I tried delays in case it was reading my touch too fast but with no luck.

The hardware is basically a 1M resistor between send and receive.

// capactitive sensing
#include <CapacitiveSensor.h>
CapacitiveSensor   cs_7_6 = CapacitiveSensor(7,6);
// 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil
const int numReadings = 5;
int index = 0;                  // the index of the current reading
int readings[numReadings];      // the readings from the analog input
int total = 0;                  // the running total
int average = 0;
int relay = A2;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;
boolean lightState = false;
// sound sample
const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;
//other
boolean isRelaysOn = false;

// capacitive sensor
void setup() {
  cs_7_6.set_CS_AutocaL_Millis(0xFFFFFFFF);
  // turn off autocalibrate on channel 1 - just as an example
  Serial.begin(9600);
  for (int thisReading = 0; thisReading < numReadings; thisReading++)
    readings[thisReading] = 0;
  // other
  pinMode(relay, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  turnRelayOff();
  Serial.begin(9600);
}

boolean state = false;
boolean lastState = true;
boolean lightTurnedItOff = false;

void loop() {
  Serial.println(capReading());
  if(capReading() >= 3000) {
    Serial.println("threadhold reached");
    lightState = !lightState;
    controlRelay();
  }
}

boolean isOn = false;

void controlRelay() {
  if(lightState == true && isOn == false) {
    turnRelayOn();
    //delay(1000);
  }
  if(lightState == false) {
    turnRelayOff();
    // delay(1000);
  }
}

void turnRelayOn() {
  int delayAmount = 100;
  digitalWrite(relay, LOW);
  delay(delayAmount);
  digitalWrite(relay2, LOW);
  delay(delayAmount);
  digitalWrite(relay3, LOW);
  delay(delayAmount);
  digitalWrite(relay4, LOW);
  delay(delayAmount);
  digitalWrite(relay4, HIGH);
  delay(delayAmount);
  digitalWrite(relay4, LOW);
  isOn =true;
}

void turnRelayOff() {
  digitalWrite(relay, HIGH);
  digitalWrite(relay2, HIGH);
  digitalWrite(relay3, HIGH);
  digitalWrite(relay4, HIGH);
  isOn = false;
}

int capReading () {
  // get average.
  total= total - readings[index];
  readings[index] =  cs_7_6.capacitiveSensor(30);
  total= total + readings[index];
  index++;
  if (index >= numReadings)
    index = 0;
  average = total / numReadings;
  delay(100);
  return average;
}

The output doesn't make much sense sometimes either, here are a few samples:

  11 16 21 22 32 61 74 threadhold reached 6191 threadhold reached 6167
  threadhold reached 30 15 11 12

  6 10 17 44 2144 3745 threadhold reached
  -475 threadhold reached
  -3129 22 10 12 13

  15 13 7 20 23 725 2726 2735
  -6373
  -3197 threadhold reached 4127 2714 54 40 43 34 24 27 31

In this line:

readings[index] =  cs_7_6.capacitiveSensor(30);

...you are assigning an "int" the value from a method of type "long".

Likely you will want to change all your types used to track the capacitance value, including the type of your "capReading" method, to "long".


Multiplex 7 segment during delay (external IC?) I am using some sensors with the arduino which take a second to receive the data from them. My guess is that there is a delay used somewhere in the library. During this time the multiplexed displays stop working as the rapidly changing grounds are temporarily paused and only one of the displays has the digit lit up. I could change the sensor I'm using (DHT11) to something I could AnalogRead, however I'm curious if there is an external IC for this which drives multiplexed displays with some sort of serial communication or I2C between the arduino and it. I could use a separate arduino(or ATTiny) and write some code for it to do this, but is there a class of chips which already do this? Something where you could pass bytes of the digits and the multiplex delay and it continues to multiplex until the next data is received.

I don't mind if in this time the digits are left in their last states similar to how it would operate if they were directly driven rather than multiplexed. If anyone has insight that would be great!

Perhaps a MAX7219 would do what you want.

  The MAX7219CNG+ is a 8-digit serially interfaced LED Display Driver for LED matrix displays.
  The MAX7219 is compact, serial input/output common-cathode display drivers that interface microprocessors (¦ÌPs) to 7-segment numeric LED displays of up to 8 digits, bar-graph displays or 64 individual LEDs.
  Included on-chip are a BCD code-B decoder, multiplex scan circuitry, segment and digit drivers and an 8x8 static RAM that stores each digit.
  Only one external resistor is required to set the segment current for all LEDs.
  A convenient 4-wire serial interface connects to all common ¦ÌPs.
  Individual digits may be addressed and updated without rewriting the entire display.
  The MAX7219 also allow the user to select code-B decoding or no-decode for each digit.


Problem with PWM interference I have a following code

  #include <Servo.h> //library for servo drive
  int MotorAPinA = 9;   //pin number for DC drive
  int MotorAPinB = 10;  //pin number for DC drive
  Servo myservo; //create object myservo, class servo from Servo library

void setup() {
  // put your setup code here, to run once:
  pinMode(MotorAPinA, OUTPUT);
  pinMode(MotorAPinB, OUTPUT);
  //myservo.attach(6); //pin number for servo output
  myservo.write(65);
}

void loop() {
  analogWrite(MotorAPinA, 240);
}

This very code works only partly.
If I comment line

myservo.attach(6)

then I got my DC drive working.
If I uncomment this line, my Servo goings crazy (effect looks like myservo.write(0) constantly), until I comment line

analogWrite(MotorAPinA, 240);

and then I got my servo working properly.
While myservo.attach(6) is uncommented, DC drive doesn't work (with uncommented analogWrite).

So, basically, I can have or PWM or Servo working simultaneously, but not both

Any ideas? Arduino Uno R3, Arduino 1.8.1.

Well, your PWM outputs are both on 16b Timer/Counter 1 and the servo is attached to the 8b Timer/Counter 0. So my guess is that 8bit counter has too low resolution for driving the servo and it uses Timer/Counter 1 in full 16b mode for better precision instead (PWM uses just 8bits from 16). Also Timer/Counter 0 is used for counting millis, so its settings can't be changed anyway.

For the confirmation you can either:

use pins 5 and 6 (TC0) or/and pins 3 and 11 (TC2) and for the servo use pin 9 or 10
You can read the values of TC1 configuration registers and according to the datasheet you can figure out what mode is currently used.

EDIT:
So on the Uno board is used Timer/Counter 1 for timing purposes:

  if(timer == _timer1) {
    TCCR1A = 0;             // normal counting mode
    TCCR1B = _BV(CS11);     // set prescaler of 8
    TCNT1 = 0;              // clear the timer count
    TIFR |= _BV(OCF1A);      // clear any pending interrupts;
    TIMSK |=  _BV(OCIE1A) ;  // enable the output compare interrupt
    timerAttach(TIMER1OUTCOMPAREA_INT, Timer1Service);
  }

So no PWM on the OC1A nor OC1B in normal mode and the channel A is taken by Servo.


Correct way of having loop end when required? I'm brand new to Arduinos. I'm currently trying to modify a script from here which at the moment, simply turns an LED on or off depending on which HTTP GET request it receives. However, I want to modify this to have the LED modulate on/off when presented with the On HTTP GET request and then simply turn off all together when presented with the Off HTTP GET request. However, I have two conflicting methods that I have found about how to achieve this; the first is:

int value = LOW;
    if (request.indexOf("/LED=ON") != -1)  {
      value = HIGH;
      do
      {
      digitalWrite(ledPin, HIGH);
      delay(3000);
      digitalWrite(ledPin, LOW);
      delay(5000);
      value = HIGH;
      } while (value = HIGH);
    }
    if (request.indexOf("/LED=OFF") != -1)  {
      digitalWrite(ledPin, LOW);
      value = LOW;
    }

Wheareas the other is:

  int value = LOW;
    if (request.indexOf("/LED=ON") != -1)  {
      value = HIGH;
      void loop() {
      digitalWrite(ledPin, HIGH);
      delay(3000);
      digitalWrite(ledPin, LOW);
      delay(5000);
      value = HIGH;
      }
    }
    if (request.indexOf("/LED=OFF") != -1)  {
      digitalWrite(ledPin, LOW);
      value = LOW;
    }

As you can see, the first uses do...while and the second uses loop(). I have a feeling that the first of the two scripts would be more suitable as it should cut out as soon as value is set to LOW (i.e. when requested to turn off)

However, I would really appreciate it if someone could look through the two scripts and tell me which of the two is the correct way to achieve this sort of cut off when the HTTP GET Off is requested (if either for them even is the correct way to do this!).

Thank you in advance for your help,

Kind regards,
Tom

As pointed out by Ignacio Vazquez-Abrams and jsotola, you need to use a
state machine, like the one from the Blink Without Delay
Arduino tutorial. Yours would be slightly more complicated because you
need a way to turn it on and off, and because you use different on and
off periods. Here is an example code that abstract the blinking logic
into three functions:

update_led() takes care of the blinking, and it has to be called
quite often in order to achieve a smooth blinking
start_blinking() and stop_blinking(), as their names suggest, are
used to turn the blinking state machine on and off.

const uint32_t ON_TIME  = 3000;
const uint32_t OFF_TIME = 5000;

bool led_blinking;     // are we blinking the LED?
bool led_on;           // is the LED currently on?
uint32_t last_toggle;  // last time it toggled while blinking

void update_led() {
    if (!led_blinking) return;
    uint32_t now = millis();
    if (led_on && now - last_toggle >= ON_TIME) {
        digitalWrite(ledPin, LOW);
        led_on = false;
        last_toggle = now;
    }
    if (!led_on && now - last_toggle >= OFF_TIME) {
        digitalWrite(ledPin, HIGH);
        led_on = true;
        last_toggle = now;
    }
}

void start_blinking() {
    digitalWrite(ledPin, HIGH);
    led_blinking = true;
    led_on = true;
    last_toggle = millis();
}

void stop_blinking() {
    digitalWrite(ledPin, LOW);
    led_blinking = false;
    led_on = false;
}

You then have to call these functions from loop() as follows:

void loop() {
    // Keep the LED blinking if necessary.
    update_led();
    ...
    if (request.indexOf("/LED=ON") != -1)  {
        start_blinking();
    }
    if (request.indexOf("/LED=OFF") != -1)  {
        stop_blinking();
    }
    ...
}

Edit, in response to jsotola’s comments:

When answering the question, I was initially tempted to make a
BlinkingLed class, with the functions as its public interface and the
variables private. I resisted the temptation on the grounds that, given
the apparent OP’s level of C++ knowledge, that could end up being well
over his head. Instead, I used documentation as an informal way of
separating the public from the private: you are only supposed to use
what is documented, i.e. the functions. You don't “take a shortcut in
your program and clear led_blinking directly”.

You could, of course, make the led_blinking variable part of the
public interface. That could even be a nice simplification, as you don't
need the start/stop function anymore. But then you loose control over
the initial phase of the blinking pattern. That may not be an issue, but
if you want the LED to turn on as soon as you set led_blinking to
true, then you have to do something like

void update_led() {
    uint32_t now = millis();
    if (!led_blinking) {
        digitalWrite(ledPin, LOW);
        led_on = false;
        last_toggle = now - OFF_TIME;  // fix initial phase
        return;
    }
    ...
}

Note that the subtraction can overflow, but that's not as issue because
it follows the rules of modular arithmetics.

I actually kind of like this option, with all the logic in a single
function. This way the variables led_on and last_toggle can be made
static local to the function, which provides true encapsulation without
a class. However, from a pedagogic point of view, I think my initial
proposal is easier to understand.


Replicating Tx and Rx LEDs In my application all of the Arduino Uno LEDs will be invisible inside an enclosure, so I wish to provide panel-mounted Tx and Rx LEDS just replicating their on-board counterparts. Is there a way to drive any of the digital outputs to replicate those LEDs? I seem to recall that the Tx and Rx LEDs are driven directly from the FTDI logic, does this preclude hacking their states and sending them to two digital outputs? How could this be done? I could de-solder the LEDs and hardwire the panel LEDS to their pads, but I think this should be a last resort.

The USB to serial and LEDs are done with the ATmega16U2 (the chip near the USB socket).

If you look closely you'll see there are 4 pad near the chip, JP2 in the schematic. You could solder some wire to it to connect your leds. You could then slightly modify the firmware running on the ATMega16u2, and upload it using DFU.

I did this on my arduino uno to break out the reset signal, so I could use my UNO to program an separate ATMega328 over serial.

In your case you could use the pads connected to PB4 and PB5 (as the original code uses PD4 and PD5), so the you only have to change DDRD and PORTD, to DDRB and PORTB in LED.h.


Can you current-limit Arduino 101 GPIO pins? A number of questions ask about max possible in/out current on a GPIO pin, that's not my question here. I'm asking if it's possible to set a maximum current limit on a GPIO pin, such that any attempts to draw more than that current would result in the Arduino entering a constant current mode e.g. reducing the pin voltage?

I've read this, this, this, and skimmed the Curie datasheet, but I don't see a feature like this mentioned anywhere.

The only half-answer I have seen is on the Ruggeduino website, which explains that they have added a fuse to each GPIO pin to avoid overcurrent draws due to short circuits.

For context - I have an external sensor that claims to be more reliable with a small amount of constant current. I didn't know if I could easily add that limitation (e.g. max 15mA at 3.3V) into the GPIO pin as a safety measure, so I went on a search to find out which has eventually led me here

No. I have never heard of a microcontroller with constant current or current limiting on the GPIO pins.

You may get a drive strength on the pins of an FPGA, but I have never seen such a thing on a microcontroller.

In general, if you have a need to reduce the voltage as the current increases you would just slip a resistor in the circuit. Or for more precise control using the GPIO pin to control a constant current source or constant current sink is the normal way of doing it.

GPIO pins are generally designed for communicating with other logic level devices. They require minimal current. Some microcontrollers provide a higher drive strength to work with larger fanouts (lots of devices connected to one pin, such as in SPI buses), but they are not intended for providing power to a device or giving control over their current.


String & Char concatenations A newbie in Arduino- and I'm trying to concatenate string and chars ( well in python it is quite different ).

I'm trying to post a MQTT message- constructed following format to the client.publish(outTopic, "["+outTopic+"]"+ msg)

while outTopic is a char* variable, and msg is char- but I get an error for such concatenation.

please your help

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// GPIOs on SONOFF board
int LED_SONOFF = 13;
int REL_SONOFF = 12;
int PIN_SW = 14;

const char* ssid = "HomeNetwork_2.4G";
const char* password = "pswd";
const char* mqtt_server = "192.168.2.113";

WiFiClient espClient;
PubSubClient client(espClient);

char msg[50];
const char* outTopic = "HomePi/Dvir/Messages";
const char* inTopic = "HomePi/Dvir/Windows/SONOFF";
const char* inTopic2 = "HomePi/Dvir/Windows/All";
const char* clientID = "Sonoff#1";
String m1, m2;

void start_wifi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void setup() {
  start_wifi(); // start wifi service
  Serial.begin(115200); // start serial service
  delay(10);

  // define sonoff gpios
  pinMode(LED_SONOFF, OUTPUT);
  pinMode(REL_SONOFF, OUTPUT);
  pinMode(PIN_SW, INPUT_PULLUP); // GPIO14 has a pullup resistor
  digitalWrite(LED_SONOFF,HIGH); // LED high is OFF
  digitalWrite(REL_SONOFF,LOW);

  // start mqtt
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void switch_on() {
  digitalWrite(REL_SONOFF,HIGH);
  digitalWrite(LED_SONOFF, LOW); // LED ON
  pub_mqtt("Switch ON");
}

void switch_off() {
  digitalWrite(REL_SONOFF,LOW);
  digitalWrite(LED_SONOFF, HIGH); // LED OFF
  pub_mqtt("Switch OFF");
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  if ((char)payload[0] == '1') {
    switch_on();
  }
  if ((char)payload[0] == '0') {
    switch_off();
    Serial.print("payload: ");
    Serial.println(payload[0]);
  }

}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      client.publish(outTopic, "Connected");

      client.subscribe(inTopic);
      m1="Subscribed to: "+inTopic;
      client.publish(outTopic, m1);
      if (inTopic2 !=""){
        client.subscribe(inTopic2);
        m2="Subscribed to: ";//+ String(inTopic2);
        client.publish(outTopic, m2);
      }

    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void pub_mqtt(char* msg) {
  client.publish(outTopic, msg);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  if (digitalRead(PIN_SW)==1) {
    if (digitalRead(REL_SONOFF)!=LOW) {
      switch_off();
    }
  }
  else if (digitalRead(PIN_SW)==0) {
    if (digitalRead(REL_SONOFF)!=HIGH){
      switch_on();
    }
  }
   delay(100);
}

You can't simply concatenate C strings like that. Instead you have to build them up into a new string.  For formatting like that the simplest way is with sprintf:

char outMessage[strlen(outTopic) + strlen(msg) + 3]; // Room for topic, message, [ and ] and terminating \0
sprintf(outMessage, "[%s]%s", outTopic, msg);
client.publish(outTopic, outMessage);

Another method is with strcpy and strcat:

char outMessage[strlen(outTopic) + strlen(msg) + 3]; // Room for topic, message, [ and ] and terminating \0
strcpy(outMessage, "[");
strcat(outMessage, outTopic);
strcat(outMessage, "]");
strcat(outMessage, msg);
client.publish(outTopic, outMessage);

You have to ensure that your "holding" string outMessage is big enough to hold everything you want to send, plus a terminating NULL character, otherwise your program will crash.

Another way of creating the "holding" variable is with alloca(). That allocates bytes on the stack for a variable - just like malloc() does on the heap, but doesn't require free()ing because it's on the stack and is reclaimed when the function exits:

char *outMessage = (char *)alloca(strlen(outTopic) + strlen(msg) + 3);


Arduino Control over the internet I am really interested in IoT (enthusiastic noob) and I would like to use the arduino board. Here are the steps according to me, with my queries:

User goes to example.com/arduino_switch
Interacts with an HTML form to toggle an action
Sends the data over the Internet (This is the part I have problem understanding)
Arduino receives the data point (how can we do this? polling a url or can we actively send it)
performs the action (easy to do for me)

Any and all help will be appreciated, even if its just pointing me to the right resources.

You have two choices:

The Arduino regularly communicates with an external web server, sending data and asking if there is anything to do. This is the way Mitsubishi heatpumps can be controlled from the web. The advantage is that your internet connection does not need to publish a web server. Drawback is that the communication is slow (being dependent on the polling interval), plus the need for a web server to talk to. For instance, to control your Mitsubishi heatpump, you need to create an account on one of their servers for the purpose.
The Arduino exposes a web interface that is then exposed to the internet. This needs configuration of your internet router and preferably a static IP address on the internet. Security is a problem, and I'm not sure that even the Due can do HTTPS plus some form of authentication. I used this method, but fronted my Arduino with an old laptop running Linux and Apache web server. The laptop does the authentication and HTTPS processing. Advantage is near real-time control; disadvantage is the amount of hardware and configuration required.


Solutions for displays? I am trying to find cheap options for displays about 3 x 6 inches to display time, weather, simple clip-art type images, and other marquee messages.  What are my best options to work with arduino if my goal is cost-cutting?

2" x 4" or greater in size
40 dpi minimum
readable from 15 feet in normal indoor conditions
everything else is unimportant to me at this point: RGB, pitch, power draw, etc.

One possible option would be these 8x8 pixel displays.

I got that from eBay for $8.50 (for the 4 modules).

They come pre-assembled, this is the back:

Notice the data direction. You can connect them together like this:

That one (3 lots of 4 modules) is 25.4 cm long (10 inches) and 3.2 cm high (about 1.25 inches).

That's 96 pixels (8 x 4 x 3) in 10 inches, which is a lot less than 40 DPI, but really, if you want to read them from 15 feet away, that is probably OK.

Note: These were single-colour only.

If you want 40 DPI x 6 inches that means you must want 240 pixels horizontally and 120 pixels vertically. That would be 240 / 8 modules horizontally (30 modules) and 120 / 8 vertically (15 modules). That's a total of 450 modules. Since they come in lots of four that would be 116 in total (rounded up). 116 x $8.50 = $US 986.

I don't know if that is what you have in mind by "cost cutting" but that is one option.

You would need to assemble them yourself, connect them together, supply power, and have a suitable driver. I have some code that drives those boards, although I certainly have not tested it with 450 of them at once.

As you can see those boards come with mounting holes on the back, and are designed to be physically adjacent to each other. Mounting 450 of them could be quite tedious. The LED modules on the front pull off to give access to the mounting holes, but it would be a long job.

You can get larger modules, as mentioned in another reply, I expect they would be more expensive, but you would of course get more pixels.

Example: 64x32 RGB LED Matrix - 4mm pitch. That one is 64x32 pixels for around $US 80.

You would probably need 4 of those horizontally (256 pixels) and 4 vertically (128 pixels). Thus, a total of 16 which would cost you around $US 1280. However for that at least you get RGB. Note that the Adafruit page mentions you cannot drive that many pixels with a Uno.


SPI: problems communicating with sensor using Arduino I have a sensor which I am trying to communicate with over SPI using an Arduino UNO. It is my first time using SPI and I'm experiencing some problems which I'm hoping are just due to some misunderstanding on my part. I have written a simple code to perform one basic operation: Turn on the sensor's fan. The Arduino is being powered through the 2.1 mm barrel jack by a 1.5 A DC adapter. The 5V, GND, MOSI, MISO, SS and SCK pins on the Arduino are connected to the corresponding pins on the sensor. The sensor receives power from the Arduino, drawing up to 250 mA (with the fan on).

The manufacturer provides a list of commands corresponding to each function of the sensor. To turn on the fan, the command list gives the following information:

Command_byte: 0x03
Bytes: 0x03, 0x00
Bytes_in: 0xF3, 0x03
Time_between_current_and_next_byte: 1.7ms, NA
Note: 1ms would be adequate delay between command byte and following byte

Based on my understanding of this, to turn on the fan, I need to send a command byte (0x03), then wait 1.7 ms and send another byte (0x00). My code for doing this is as follows:

#include <SPI.h>
const int chipSelectPin = 10;

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

  SPI.begin();
  pinMode(chipSelectPin, OUTPUT);
  SPI.setClockDivider(SPI_CLOCK_DIV32); //set clock to 500kHz
  SPI.setDataMode(SPI_MODE1);
  SPI.setBitOrder(MSBFIRST);
  delay(10000); // Let the sensor settle for 10 seconds

  digitalWrite(chipSelectPin, LOW);
  indata = SPI.transfer(0x03); //command byte for fan on
  Serial.println(indata);// value returned should be 0xF3
  delay(2);
  indata = SPI.transfer(0x00); //Turn on fan
  digitalWrite(chipSelectPin, HIGH);
  Serial.println(indata);// value returned should be 0x03
}

void loop() {}

When I send the command byte, the returned value (which gets printed to the terminal) is 243 which corresponds to the expected hex value of 0xF3. However, the second command does not turn on the fan and the second returned value is 231 which does not correspond to the expected hex value of 0x03.

I don't think it's a hardware issue because at least one of the returned values is correct and because the sensor does work when used with a different platform. I also experimented with different delays between bytes.

Change your chipSelectPin. Pin 10 is exclusively used by SPI library. See Arduino Uno description.

Similar issue has been discussed here.


How to detect water presence with only 2 wires I don't know if this question belong here or on electronics SE.

A manufacturer just sent me a personalize device which include an ESP-32 and a Water Sensor.

My problem is that I don't know how to retrieve the water sensor data (if there is water or not).
When I used my Arduino Nano and a Funduino Water Sensor, it was easy to retrieve the value because this sensor got 3 connectors (VCC, GND, Data), I just had to do a basic analogRead(DATA_PIN).

But now, as you can see on the diagram bellow, the water sensor is just composed of 2 wires. I presume that it will detect water when these two wires are going to be connected by water.

So, How to detect the presence of water in Arduino using only these 2 wires ?

What I tried :

Analog Read on the pin GPIO33
Digital Read on the pin GPIO33
Try to use TOUCH_PAD with this pin using touchAttachInterrupt(T8, callback, Threshold); but callback was never called
Contact the manufacturer (He said that it works perfectly, he used touch_pad for testing but never used Arduino IDE, only ESP-IDF that I really don't know)

simulate this circuit – Schematic created using CircuitLab

EDIT:

This image represent the back of the device with the sensor, inner wire is directly connected to GND and outer wire is connected to GPIO_33. This is all, there is not hidden connectors or something else.

Since all you have is 2 bare wires, the water simply forms a resistor between them.

You can use it as part of a resistive divider, with a fixed resistor between your analog input and +3.3V.  The resistance between the wires will change from infinite (dry) to something much lower (wet) and the reading you get from the ADC will depict that.

You will need to experiment with different resistances in order to get reasonable values, but start with 10kΩ, or 100kΩ.  If you use a very high resistance (in the order of 1MΩ or more) you may even be able to use it like a simple switch and connect it to a digital input.

Be warned, though, that this method will cause a small amount of electrolysis, causing one electrode to be eroded away and the other to gain extra material.  For this reason it can be good to connect the resistor to a GPIO pin instead of directly to +3.3V and switch the GPIO pin HIGH when you want to do a reading (to provide power) and LOW (or INPUT) when at other times (to remove power).  This will greatly increase the lifetime of your water sensor.


Dshot implementation on Arduino (ESC protocol) Does anyone one know if it's possible to implement Dshot on Arduino? I want to interface the Arduino with ESCs (electric speed controllers). These ESCs use Dshot,
 (https://oscarliang.com/dshot/) a digital protocol. From what I read online, you can make PWM follow a duty cycle. However, I want to change the duty cycle after each pulse and not just repeat the same duty cycle. I understand this requires DMA (direct memory access) but it's a bit over my head.

In short, I ended up creating a library capable to drive multiple DShot600 ESCs:
DShot-Arduino
It still need a lot more polish, but the bit-banging works really well.

SPI method

I tried the method @dannyf mentioned, which involved combining 3 SPI bytes to form 1 dShot bit and it actually works.

But there's a few problem with SPI:

It takes up the valuable SPI port, in theory you can still connect other SPI devices, but;
maximum 1 dShot ESC can be connected
During transmission of the packet, the CPU need to wait for the whole task, assume we are sending DShot300, each packet is about 54us long so CPU is halt for that amount of time. If you are doing this in 1000Hz, that is 5% CPU time.
The timing is not very accurate to the DShot protocol standard

e.g. for DShot300, each bit is

  1.25us High - 1.25us H/L - 0.83 Low

  for a 16MHz Arduino, 1.25us will be 20 CPU cycles which is not accurate to transmit with a SPI byte

I end up with the following codes to send a bit:

inline void dshot_0(){
  SPDR = 0xFF;
  NOP;
  while (!(SPSR & _BV(SPIF))) ;
  SPDR = 0x60;
  NOP;
  while (!(SPSR & _BV(SPIF))) ;
  SPDR = 0x00;
  NOP8;
  while (!(SPSR & _BV(SPIF))) ;
}

inline void dshot_1(){
  SPDR = 0xFF;
  NOP;
  while (!(SPSR & _BV(SPIF))) ;
  SPDR = 0xFF;
  NOP;
  while (!(SPSR & _BV(SPIF))) ;
  SPDR = 0xF0;
  NOP8;
  while (!(SPSR & _BV(SPIF))) ;
}

Above code is for DShot150, the SPI was set to 4Mbps, to adhere to the correct timing, I cannot transmit a full DShot byte as all on or all off, here's how the calculation done:

  4Mbit SPI, each bit 0.25us. Thus for 16M clock arduino:

  DShot 0 sequence: 10 bits of 1, 14 bits of 0
  DShot 1 sequence: 20 bits of 1, 4 bits of 0

Those NOPn are just macro for the number of NOPs. I avoided using SPI library code here since the overhead of making library call is quite a lot.

Pure software bit-banging

This is the method resulted in my library, since using hardware SPI won't give me any advantages of releasing CPU time, and doing some Math gives me that a DShot600 require total 27 CPU cycle on 16MHz UNO. Which the pattern is the following:

  10 Cycle High -> 10 Cycle H/L (depending on bit 1/0) -> 7 cycles low

Which gives total of 1.6875us per bit or 27us per packet. To allow the very tight timing those are coded in assembly.

Also by applying bit-masking the library is capable of driving at most 8 ESCs on the same hardware port (on UNO, Digital pin 0-7, PORTD).

Update cycle

One last note about DShot is during my test, I found it is quite strict on the update frequency. It must be updated at exact time interval and I found the slowest update frequency will be around 500Hz. To provide the correct timing for that, the library used Timer 1 and by default update in 1000Hz frequency.


OBD Connector to Arduino I bought an OBD connector from Sparkfun to try to connect to my vehicle via arduino.

I'm just beginning and am not sure if I can just connect the connector pics to the arduino directly, or if there is some other required hardware?

Does anyone know if I can connect directly and why or why not?

I briefly read up on this subject and I found out this:

It seems like there's a protocol called J1850. There's no native support on the Arduino for that, but you might be able to do something bit-banging if you can find the specifications for this protocol. If you do this, I'd advise accessing the registers directly and skipping the digitalRead() command.

There are a few protocols in use, so it is hard to know without knowing the car you drive to even tell what the car will send.

More on this topic...

Anyway, it seems like you need a chip to use with this. Sparkfun also sells a breakout board for the STN1110 OBD-II to UART chip (tutorial). I couldn't really find anything else besides this.

Anyway, you probably need another chip to do this work. The Arduino isn't meant to do all of these protocols, and the OBD isn't UART-compatible.


USB Communication between Arduino Nano and UHF Reader module I am working on a project that requires a UHF reader development kit that can communicate using either RS232 or by USB.  Via USB and a Serial terminal, I have been able to send commands to the reader as well as analyze its response.

My goal is to send these same commands to the reader, but through an Arduino Nano.  My first instinct was to use the RS232, converting the signal via a MAX232.  However, this is for a school project, and my advisor preferred I try to work with USB.  I am familiar with UART communication, and I've been under the assumption that USB operates using UART.

I had purchased a USB converter that gives me access to the pins, but it had two additional pins than I was not expecting: CTS and DTR.  I attempted to communicate despite these pins (just leaving them open, and connecting Rx, Tx, Vcc and GND as I normally would).  When plugged into the UHF reader, the device did power on (as it draws power from the USB connection), however, it did not receive the output signal from the Arduino Nano.

I know that my baud rate and other settings are correct, because, as I have said, communicating via USB and a Serial terminal gives me no problems.  My initial thought is that I need to properly connect the CTS and DTR pins, but immediately I could not find a good reference on how to do this, and I am not entirely convinced this is the issue.  My other thought was that perhaps I am writing out my HEX values wrong from the Arduino, using a line similar to the following, where "UHF_Reader" is defined by SoftwareSerial:

UHF_Reader.write(0xAA);

However, it appears to me from research that this is indeed the correct way to output HEX values via serial.

My final attempt to resolve this was to connect the micro-USB from the Nano to the USB of the reader, and then use Software Serial in conjunction with the USB converter to analyze the output on a Serial terminal, while powering the Nano via a 5V power supply.  However, since the reader draws power from the USB port, it did not even turn on when I attempted this (I am assuming that the Vcc can only be supplied from the USB end?).  Regardless, this attempt proved useless as well.

If anyone can offer any advice, or point me towards any references for something similar, I would much appreciate it!  I have spent a while on this, and I just can't figure out what the problem is.

For reference, the reader I am using is found here: UHF Reader

And the USB converter I am using is here: USB Converter

I've been under the assumption that USB operates using UART.

No. You have it backwards.  Devices can emulate a UART (known as CDC/ACM) over a USB connection as one of the many possible device profiles, but it is about as far from being a UART as an F1 car is from a Penny Farthing.

USB operates on a strict Master / Slave principle. That is, it has a single master device, called the Host, which coordinates all the devices on the bus and makes requests to them.  Everything you plug into a USB system is a Device and requires a Host to tell it what to do.

Neither the Nano, nor this adaptor you bought, are Hosts. They are just Devices. And Devices cannot talk to Devices. Only Hosts can talk to Devices.

Which means you need a Host in there somewhere. If you want it controlled by Arduino then you need a USB Host Shield (or something similar) which normally communicates over SPI.

If the device you are trying to talk to uses the CDC/ACM profile then you can use the USB Host Shield with it. If it uses a proprietary profile, like the CH340G or FT232, then getting it to work with the USB Host Shield will be much harder (maybe even impossible) unless you are intimate with the underlying protocol used.


Got Trouble with ESP8266 and Arduino Yun using REST control Sorry about my English.

I'm a new bie in program Arduino and interested in ESP8266. I'm trying to use ESP8266 control Arduino Yun using REST API.

Like you know, we using web browser as

http://<Arduino_Yún_Address>/arduino/<status>/<pin>/<value(optional)>

Example: http://<Arduino_Yún_Address>/arduino/digital/13/1

you bring pin 13 to high, by closing the relay and giving light to the LED,

while with: http://<Arduino_Yún_Address>/arduino/digital/13/0

the relay is opened and the LED is turned off

and I want to use ESP8266 to send command like using web browser and it didn't work.

After connect to Wifi access point and Server of Yun done, I've tried to send command like

GET /http://<Arduino_Yún_Address>/arduino/digital/13/1

Please give me some idea or move advices about this situation. Thanks for reading my topic.  :D

Here is my problem:

AT+CIPSTART="TCP","192.168.0.150",80

OK
Linked
AT+CIPSEND=58

> GET /http://192.168.0.150/arduino/digital/13/1 HTTP/1.0\n

wrong syntax

ERROR

The proper HTTP request should look like:

GET /arduino/digital/13/1 HTTP/1.0\r\n


Power source for Arduino uno, sparkfun usb shield and adafruit motor shield I'm having trouble powering my boards altogether. Right now, I'm using 8x AA batteries to power everything. Running my arduino with one shield runs fine, but not with both shields stacked on top of my arduino. I've even tried powering it with an extra 4x AA batteries on my motor shield, but it still won't run. The way it's stacked is; arduino uno board, usb host shield then motor shield.

Its a very bad idea to power everything from the same battery source. Most motors, especially ESP, generate large current spikes, rather than draw a small current throught. AA batteries are not designed for this.

You can get away with using AA batteries for micro-controllers, shields. However, keep motors on a sweater power supply. There are batteries for specific motor types, and these will typically have a high current rating. Of course, without a circuit diagram, I cannot go into details. I'll update my answer when you do.


Is there a 3.3V and 12V 18650 circuit? Is there an all in one circuit which regulates charging, protects and steps up/down an 18650 battery to 12V and 3.3V at the same time, so I can power a sensor and my ESP32?

I would suggest using a 12V controller, and then adding a 3.3V switching regulator using the 12V supply. That would be 2 off-the shelf components and you're done.