text:
Stepper wait for X seconds in a loop with millis (not delay)
In the code below I would like the stepper to bounce back and forward between two limit switches and while it is doing this it should turn and than wait for e.g. 1 second.
I thought I could achieve this with the if ((unsigned long)(currentMillis - previousMillis) >= interval) part, but it doesn't work.It won't turn. Any help would be great. Thank you.
// defines pins numbers
const int stepPin = 5;
const int dirPin = 4;
const int enPin = 12;
const int homeSwitchPin = 9;
const int homeSwitchPin2 = 11;

unsigned long interval=1000; // the time we need to wait
unsigned long previousMillis=0; // millis() returns an unsigned long.

void setup() {

   Serial.begin(9600);

  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
  pinMode(homeSwitchPin , INPUT);
  pinMode(homeSwitchPin2 , INPUT);
  pinMode(enPin,OUTPUT);
  digitalWrite(enPin,LOW);

  // Set Dir to Home switch
  digitalWrite(dirPin,LOW); // Enables the motor to move in a particular direction

}
void loop() {

    int homeSw = digitalRead( homeSwitchPin);
    int homeSw2 = digitalRead( homeSwitchPin2);

    if( homeSw == HIGH && (digitalRead(dirPin) == LOW) ){
        unsigned long currentMillis = millis();

        if ((unsigned long)(currentMillis - previousMillis) >= interval) {
        motorStep(1);
        previousMillis = millis();
        }
    }
    else if( homeSw == LOW && (digitalRead(dirPin) == LOW) ){
          digitalWrite(dirPin,HIGH);
          delay(2000);
    }

    if( homeSw2 == HIGH && (digitalRead(dirPin) == HIGH)){

        motorStep(1);
        // motorStep(32000);
        //digitalWrite(dirPin,LOW);

        //delay(2000);
    }
    else if( homeSw2 == LOW && (digitalRead(dirPin) == HIGH) ){
          digitalWrite(dirPin,LOW);
          delay(2000);
    }

}
void motorStep( int MAX){

   for(int x = 0; x < MAX; x++) {
        digitalWrite(stepPin,HIGH);
        delayMicroseconds(100);
        digitalWrite(stepPin,LOW);
        delayMicroseconds(100);
      }
}

Do the home switch pins have pull-up resistors on them? Your current code only makes the motor move one single step every second. So it's hardly moving. Are you sure it's not moving very slowly?

how many times do you want the motor to bounce back and forward between waits? ...... your description is unclear

Endless bounce back and forward, within that it should do other routines. @gerben maybe, but my question is how I can change that so it moves according to my routine. I need additional routines and therefore it would be great to know how to set this up. Thanks.

Have you tried spamming your code with print()s to determine if you are actually hitting the contents of the if() statement?

I asked two questions and you answer maybe. After reading your question 4 more times, it seem like you don't even need this if statement at all, and only change the delay(2000) to delay(1000) for your 1 second delay. And pinMode(homeSwitchPin , INPUT); to pinMode(homeSwitchPin , INPUT_PULLUP); to enable the pullup resistor.

I would like to solve this with millis() because I might have to integrate more than one stepper and for this using millis() is recommended even by Arduino. This is an excellent example of something I would call, in the lack of a better word, "best practices algorithms". I understand most of the lower level function, but lack the knowledge for these higher level algorithms and how they should be used. I would like to know where I can learn these most needed higher level algorithms for Arduino. Apart from asking on these forums.


text:
Run Stepper with A4988 driver in highest resolution
I have a Bipolar Stepper Motor (12V, 350mA, 28oz-in NEMA-17) and would like to run it in the highest resolution (Sixteenth Step) with the A4988 Driver. According to multiple sources I read I need to "put 5V" to the MS 1,2,3 pins. What does this mean/How can I achieve this ?
Do I need to hook up the MS 1,2,3 to the digital pins of the Arduino and write Digital High. Or do I need to hook all of them to 5V together ? And should the code look like this ? Is this safe/good pratice ?
int MS1Pin = 8;                 // Set MS Pins
int MS2Pin = 9;
int MS3Pin = 10;

void setup()
{
  pinMode(MS1Pin, OUTPUT);      // sets the digital pin as output
  pinMode(MS2Pin, OUTPUT);      // sets the digital pin as output
  pinMode(MS3Pin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(MS3Pin, HIGH);
  digitalWrite(MS2Pin, HIGH);
  digitalWrite(MS1Pin, HIGH);
<<MY CODE here>>

}

Sorry for these beginner questions, I just don't want to fry the Chip and this to work.
Thank you.

You can drive the MS pins from the Arduino if you want, but there is no need.  You can just hook them all up to 5V.
Have you seen this page, there seems to be load of details that you might find relevant.
https://www.pololu.com/product/1182

source: Stack Exchange

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

sort: votes


text:
Arduino (Or Raspberry Pi) As HID Device
I have an Arduino Uno and A Raspberry Pi B+. I was wandering how I could use either as a Programbel HID Device (EX: https://srlabs.de/badusb/). The Reason I ask under the arduino section is I want to preferably use it. If not I can use either.

The Arduino question has already been asked and answered.  As for the pi, it is theoretically possible with a model A or zero to operate the USB as a device rather than host, though I'm not sure anyone has ever done so.  But with models such as the B+ having multiple USB connectors, an onboard USB hub gets in the way of operating in device mode.

The Uno cannot be used as a HID device through the on board USB. You might be able to use the V-USB Library to be a HID device using the digital IO pins. See this tutorial.
There are several arduino compatible boards that do can act as a HID device natively. Most boards built around the ATMega32u4 can be a HID device.  For example the Arduino Micro
See this question about the Raspberry Pi.

I would share our experience with V-USB. For educational purposes, we had the opportunity to use like 15+ Arduinos with V-USB (Adafruit Trinket). At the moment, only two of them works well. There are various issues with newer motherboards, Windows 10, and mystic enumeration problems. I strongly recommend going for 32u4, such as Arduuno Leonardo or Arduino Micro (or any similar product with 32u4)

This answer is not correct in saying that it is not possible with the stock hardware.  The Uno's USB interface is provided by a reprogrammable ATmega8u2 or 16u2, and there are writeups online of how to program that to be an HID device.  Granted, there is the subsequent difficulty of the USB-serial channel not then being available to program the Arduino, though a dual-mode firmware is conceivably possible, if perhaps challenging to use with OSX hosts.

http://arduino.stackexchange.com/questions/484/arduino-as-usb-hid

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


text:
Why all unset pins of my Arduino Uno are outputting 2 volts?
I am new to Arduino and physical computing When I measure the wire coming from any UNSET Arduino uno pin, the result is approximately 2 volts even the "ANALOG IN" pins. Considering that the pins which been set to HIGH and LOW are giving 5 and 0 volts "which is cool".
Is that the nature of Arduino or is that a failure caused by short or anything else?

Unconnected pins float near a certain voltage. If the voltage bothers you somehow just attach a pull-down resistor to them.

@Avamander I am trying to measure a small voltage from some kind of sensors which is between 0.2 - 0.6 volts to the analog in pin A0. I get my hands shocked when I do that because of the 2 volts getting out of the A0. I am worried about the sensor, I think the 2 volts is not good for it.

If your getting your hands shocked when touching the Arduino pins, maybe you need to ground your power supply... You can get badly hurt or even dead in some conditions!

@fabrosell my power supply is my laptop's USB

I think this is a simple question for expert users.

After a microcontroller reset, AVR IO pins default to input.  In this state they have high impedance.  For example, according to the Atmel ATmega328 spec sheet doc8271 Table 29-15, analog input impedance typically can be taken as 100 MΩ for design purposes.  (Input pin impedance may in fact be orders of magnitude more, effectively an open circuit except for leakage currents of a few nanoamps.)  Each pin has a few pF (5-10?) of capacitance [1,2,3,4] which in general is small compared to stray capacitances of attached wiring.
When stray electromagnetic fields charge the pin and stray capacitances, a small voltage develops on the pin.  You could connect a 1 to 10 MΩ resistor between the pin and ground, to avoid the 2 V you are seeing.

Does that mean that it is natural fact to have the 2V and that the solution is to connect a resistor with the input wire to solve that problem?

It's natural for arbitrary voltages to appear when you have an antenna (the wiring) attached to a capacitor (the wiring and pin).  BTW, how did you measure the voltage?  Many cheap DVMs have fairly low input impedance (about 1 MΩ) so you might see a voltage upon first connecting, but it should soon drop to near zero unless you are using long leads or have high EM fields in the area.  Getting a shock suggests hundreds of volts, not 2 V.

@AhmedAl-sabsab with the sensor connected to the Arduino there should no longer be 2 volts on the input pin that it is connected to; if there is then there must be an error in the way you have connected everything. You might need to provide more information on what you're actually doing - by editing the question.

I have used an expensive multi-matter to measure the voltage. I also used  Serial.println(volt); to print the result to the PC screen and I get the same result. the shock stills a mastery. it is a tiny shock not a killing one of course.

What exactly shocks you? The pins?

It seems that you might need a nice conductive wristband or take off the wool socks and stop covering your floor with plastic bags :D Your description sounds like either static or something is very wrong with your power supply.

@Avamander I will try the resistor then I will try to shock my self again (bad habit :D)

I get shocked when I touch the connection of the wire coming from the sensor to the A0 analog in

Attach one end of a 10K resistor to ground, and the other end to  a wire.  Look very closely (for tiny sparks) as you move the probe end of the wire towards the input.  If no sparks, probably the shocks you've seen are from static electricity in your body.  You can also hold the probe end of the wire between thumb and ring finger, then touch the input with forefinger.  (Generally, don't let shocks go across your body.) Having no shock in this case (where the probe is grounding your hand) would be consistent with static-electricity-in-your-body theory.

The electric shocks being felt is due to leakage current from the laptop's switchmode power supply. All unearthed mains powered switchmode plug pack power supplies leak a few micro amps and voltages in excess of 80 volts AC as measured from the plug packs output socket to ground will be observed when measuring with multimeters having 10 meg ohm input impedance.
The solution is to have the GND pin of the arduino board connected to earth. Here in Australia all computer power supplies are grounded via the 3 pin power plug.

The pin is default to Tri-State or High-impedance(Hi-Z) which means they do not either sink or source current. Just as others say it's a matter about electromagnetic or some such. A voltmeter can measure its voltage because the current it takes is small enough(close to or smaller than the leakage current). The real value is undefined when you are not measuring it. Instead of reading analog pin values, You can try reading digital pins to take a better look at "floating".
A Hi-Z pin can absolutely power nothing from LED to other big stuffs. If all you want is just stable readings, well, this is where pull-up or pull-down resistors come in place. Typically these resistors can be from 10KΩ to 10MΩ, ensuring that when the pin is not connected they will provide the pins with stable values while when connected the influence of pulls can be safely ignored.

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


text:
SN76489 - Ready pin not working?
I'm testing the SN76489AN chip with Arduino and I'm able to play the 3 tones I want etc BUT I don't understand why the READY pin is not working? The datasheet says the pin goes high when the chip is ready and low when it's busy with processing a command. But the READY pin is always low! I've got 2 brand new pieces of the chip and they both act this way. I've even tried to pull-up this pin but it didn't help. I see everyone is just using delayMicroseconds in their examples, so I guess it is a common problem but it's just strange... Is it a bug in the chip or what? Does anyone know?
Thanks!

Please post a link to the datasheet for the chip. How do you know the pin is always low? Do you measure it (and if so, how?), or is it a side-effect of the code? If the latter, please post your code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

READY is open-collector. It will require a pullup-resistor. Test circuit in datasheet shows a 2kohm resistor.

Oh, so the pull-up idea was good, but I just used too big resistor. I haven't noticed the 2K resistor in the test circuit! Thanks @Mikael! (sorry I can't give you +1 here yet). Unfortunately this method is not much fuster than the version with delay. PS: @Nick, I have measured it when the chip was idle (when it should by high) and I am actively waiting for the pin to become high in a while loop.

@MikaelPatel, if you will copy your comment as an answer then I will be able to mark it as answer and close the question.

The READY signal is open-collector. It will therefore require a pullup-resistor. Test circuit in datasheet shows a 2 kohm resistor. You could try with that. Alternatively use the internal pullup resistor on the input pin but this may be too large (weak).
Cheers!

I had this problem, but the mistake was that I had missed the clock pin on my breadboard by one row, so there was no clock signal.


text:
Using SoftwareSerial to send data to itself
I'm debugging a project which includes SoftwareSerial. I'm not convinced the serial connection behaves as expected, so I came up with the following simple test:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

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

  // starting the software serial
  mySerial.begin(4800);
}

void loop() {
  for (int i=0; i <= 10; i++){
    delay(10);
    mySerial.write(i);
  }
}

I connected pin 11 to pin 1 (arduino Uno), hence forwarding the data of the software serial connection via the default (hardware) serial connection to my computer. But no data is coming through.
Am I missing something?

Shouldn't be pin 11 to pin 0? Also, you're simply "sending" data from the Software serial, but you're not reading it anywhere...

Try mySerial.print(i) instead.

If you are hoping to see the results in the serial monitor, you need to read it in and send it back (so it ends up on the USB port). Like this:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX

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

  // starting the software serial
  mySerial.begin(4800);
}

void loop() {
  for (int i = 0; i <= 10; i++) {
    delay(10);
    mySerial.println(i);

    while (Serial.available ())
      Serial.write (Serial.read ());
  }
}

Now you have to connect pin 11 to pin 0 (not pin 1) because that will now be the Serial Rx pin.
I think your method failed because with Serial active the Serial hardware was trying to drive pin 1 high (ie. idle) which was conflicting with the data from pin 11.

An alternative is to not do a Serial.begin() - which therefore does not initialize the serial hardware and it doesn't conflict any more. This also works:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // starting the software serial
  mySerial.begin(4800);
}

void loop() {
  for (int i = 0; i <= 10; i++) {
    delay(10);
    mySerial.println(i);
  }
}

Now you connect pin 11 to pin 1 as you originally wanted.

Notice I changed your mySerial.write(i); to mySerial.println(i); so you get correct data output (numbers, not control characters).

@ChrisStratton - what do you mean "unlikely to help"? I tested both of my solutions and they do work. There is no doubt about it. In the first case (using Serial to echo pin 11) the signal on pin 11 will "fight" the input from the ATmega16U2 - via a 1k resistor. That means that pin 11 has to sink 5 mA, which it is quite capable of doing. The second method, not using the hardware serial at all, means that pin 11 is connected to the ATmega16U2 (via the 1k resistor) and that pins D0 and D1 are high-impedance, and will not affect anything.

Yes, seems I misread the arduino schematic for positioning of the resistors as it is essentially drawn backwards, with the peripheral ATmega16u2 in the center and the main processor ATmega8 off to the side...

Those schematics take some getting used to! The 16U2 is drawn somewhat larger than the 328P. :)


text:
Arduino sound equalizer
I'm trying to build a led equalizer using arduino and I want to light up with the frequencies.
And I need a little help on how I should do it cause Im a beginner.
Should I use pulsein() or analogin pin to measure the freqeuencies?
The input will be an audio cable.

You are probably asking too much from your poor Arduino Uno... To get some inspiration, you may want to take a look at this homodyne detection program, which is conceptually like a single-channel equalizer. You could try to extend it to handle multiple channels, but you will pretty quickly run out of processing power.

http://arduino.stackexchange.com/q/15828/972

You seem to be describing a spectral display.  A graphic equalizer might include one, but is actually a device with a set of sliders or similar controls that allow changing the response in various frequency bands, rather than merely displaying the spectrum as is.  That would be even harder with an arduino.

Ok to make it more clear sorry for this misundarstanding. I want for example to connect the audio cable and have for example 3 leds. And I want the 1st one to light in the range of 50-60hz the 2nd to 60-200 and so on. In "real" time.

There are three steps to doing what you want, and the Arduino is going to struggle with all of them.
First you need to sample a short block of audio into a buffer that is a power-of-two in size with at least double the number of samples that you want to have bars, and at double the frequency of the highest frequency band you are interested in.
Once you have that sample set you then need to perform a Fast Fourier Transform (FFT) on it. This is quite a heavy mathematical operation, but there are integer only implementations of it that work kind of OK on a little Arduino (though a floating point version running on a better chip with FPU, or a DSP version on a chip with a DSP, is more desirable).
Then the third step is to take the results of the FFT (or "buckets") and calculate the power magnitude of each one (basically the square root of the sum of the squares of the real and imaginary values of the bucket - just like Pythagoras with a triangle).
Finally you can plot those power values on your LED bars.

https://tushev.org/articles/arduino/9/measuring-frequency-with-arduino              This method that he is describing is not possible?

@user3247715 That is completely different. That allows you to measure the frequency of one discrete (square wave) signal. It does not allow you to differentiate the different frequencies present within a piece of music. For that you require FFT.

Use a MSGEQ7. This IC is a "Seven Band Graphic Equalizer".
Here is its datasheet:
https://www.sparkfun.com/datasheets/Components/General/MSGEQ7.pdf
This method is more efficient, accurate and easier then pulsein() or analogRead(). The IC is fairly cheap and there are many libraries for it.
https://github.com/NicoHood/MSGEQ7
Here is a nice project that I found and that uses that IC. It can be a good souce of inspiration for both your code and your electronics.
https://www.youtube.com/watch?v=InrQvtUuS2w

I know about it but I want to process the signal so I will get more im depth and understand better arduino amd how signals works.


text:
and gate based on truth table
I have to code in arduino the logic gates based on the truth table with two inputs. I searched for some examples, however all that I found is using && to compared them using only onf if else condition. What I need is to do it using all the possible cases. This is what I have, however only the last condition is working. I ask you please clarify to me what concept I am not understanding well, or what is wrong in my logic. Thank you.
  const int p2  = 2;  //Ground G
  const int p13 = 13; //Input A
  const int p15 = 15; //Input B

  void setup() {
    // put your setup code here, to run once:
    pinMode(p2,   OUTPUT);
    pinMode(p13,  INPUT_PULLUP);
    pinMode(p15,  INPUT_PULLUP);
  }
void loop() {
  // put your main code here, to run repeatedly:
  if ( digitalRead(p13) == 0 && digitalRead(p15) == 0 ){
    digitalWrite(p2, HIGH);
  }

  if( digitalRead(p13) == 0 && digitalRead(p15) == 1 ) {
    digitalWrite(p2, LOW);
  }

  if( digitalRead(p13) == 1 && digitalRead(p15) == 0 ) {
    digitalWrite(p2, LOW);
  }

  if( digitalRead(p13)== 1 && digitalRead(p15) == 1) {
    digitalWrite(p2, LOW);
  }

}

"What I need is to do it using all the possible cases." Uh... there are only two possible cases. Either they are both HIGH, or the output is LOW.

Well, I am thinking in terms of input and output, no matter if the output is high or low, so there are 4 cases. I know what you mean, it is just this is an assignment. So I would like to check with the pin in my board, I do not know if I explain well, I  doing my best.

Let me give some feedback on your code, kind of a small code review:
const int p2  = 2;  //Ground G
const int p13 = 13; //Input A
const int p15 = 15; //Input B

This is useless. The purpose of creating these constants is to give them
meaningful names, and p2 is no more meaningful than just 2. You
can remove these definitions and replace in the following p2 with
2, etc. Or you could find better names:
const int inputA_pin = 13;
const int inputB_pin = 15;
const int output_pin = 2;

Notice that the comments that you put next to the constants are not
needed anymore, as the names are now explicit enough.
void setup() {
    // put your setup code here, to run once:

This comment is useless, better remove it. It is in BareMinimum.ino so
that you know what to put there, but now that you have done it, no need
to keep the comment.
if (digitalRead(p13) == 0 && digitalRead(p15) == 0) {
    digitalWrite(p2, HIGH);
}

I assume you are using negative logic: the user presses a button, and
makes the input LOW, to mean TRUE. If this is the case, you are not
being clear enough about it. You should at least have a comment to make
this explicit, e.g.:
int inputA = !digitalRead(inputA_pin);  // negative logic

where ! is the NOT logic operator.
Otherwise your program seems fine. If it does not work, check your
wirings. John Burger's suggestions on how to make it better are very
sound, and you should probably follow them. But I would like to show you
another way of writing this that could be relevant to your course: you
can implement the truth table as an actual table, i.e. a C++ array. Here
is my version:
const int inputA_pin = 13;
const int inputB_pin = 15;
const int output_pin = 2;

const bool truth_table[2][2] = {
            /* false  true  */
/* false */  { false, false },
/* true  */  { false, true  }
};

void setup() {
    pinMode(inputA_pin, INPUT_PULLUP);
    pinMode(inputB_pin, INPUT_PULLUP);
    pinMode(output_pin, OUTPUT);
}

void loop() {
    int inputA = !digitalRead(inputA_pin);  // negative logic
    int inputB = !digitalRead(inputB_pin);  // ditto
    int output = truth_table[inputA][inputB];
    digitalWrite(output_pin, output);
}

Notice that this uses the equivalence between false/true and 0/1.
In the case of the AND gate, this looks just like a silly classroom
exercise. However, for a complex gate with four inputs or more, and a
non-trivial truth-table, this technique may be the most straightforward
implementation.

Addendum – You wrote in a comment:

Not clear how your truth table works.

You are probably confused by the fact that I laid out the table in
compact form, with the first input in the row headings (comments on the
left edge) and the second input in the column headings (comments at the
top), just like a traditional multiplication table. Incidentally, it
happens to be a 2×2 multiplication table.
I could have used the more common “flat” layout, where each combination
of inputs is represented as one line of the table:
const bool truth_table[] = {
    /*   A     B     output  */
    /*-----------------------*/
    /* false false */ false,
    /* false true  */ false,
    /* true  false */ false,
    /* true  true  */ true
};

But then, since it's now a 1D table, the table index has to be computed
from both inputs, as each input provides one bit of the index:
int output = truth_table[inputA<<1 | inputB];

This is actually how I would do it if I had to simulate a gate with more
than two inputs. I've used this technique to make a 2-bit Gray code
adder (4 inputs, 2 outputs) which,
with a little bit of optimization, boils down to
for (;;) PORTB = truth_table[PINB & 0x0f];

Your explanation is very clear, I will try it. Negative logic is  Because the board I am using has the LED weld to it. Not clear how your truth table works.

@Sora: You may find the truth table easier to understand if it has the more common flat layout. See expanded answer.

I've got it, again your explanation has many details. Do not why the led is on if I have for A = false and B = true, in this case the led must to be turn off, the other cases are ok, should be something wrong with the pin of my board?

Your whole code can be replaced with one line:
digitalWrite(output_pin, digitalRead(inputA_pin) && digitalRead(inputB_pin));

That is, write out the results of a boolean AND on the state of the two inputs.

Your question title says "and", which means that if input1 is HIGH AND input2 is HIGH, then output should be HIGH. Your first line has
(...==0 && ...=0) digitalWrite(..., HIGH);

Surely these should be ==1?
Another thing is that every line of code in your program is re-reading the inputs. You should read them once, then decode the meaning behind them. So:
int input1 = digitalRead(p13);
int input2 = digitalRead(p15);

if (input1==1 && input2==1) {
    digitalWrite(p2, HIGH);
} // if
else if (input1==0 && input2==0) {
    digitalWrite(p2, LOW);
} // else if
else if ...

But note that the last three options are all the same: the code simply writes LOW. So you can combine all the last three cases into one step.
In other words, there's a single special case (both inputs ==1), and an everything-else case. In this code, I only read the inputs once, since I'm only looking for the special case. If it doesn't exist, then I simply do the alternative:
if (digitalRead(p13)==1 && digitalRead(p15)==1) {
    digitalWrite(p2, HIGH);
} // if
else {
    digitalWrite(p2, LOW);
} // else

"Your question title says "and", which means that if input1 is HIGH AND input2 is HIGH, then output should be HIGH. "
Yes, you are right.It has to be like that in the natural behavior of the and truth table, however here I just followed  an example my teacher gave to me. I do not get it. I am using this to turn on and turn off a led. I think he does it like that because the led is already turn it on before the push the pin. is it really a big difference?
Got it with the combination. Teacher ask us to write the code as it is in the truth table, that is why I did not combine it.

The official designation for what you supplied is called the NOT OR, or NOR. There are two ways to look at it: either it's "Neither input1 NOR input2 is HIGH", or that it's exactly like AND but in the opposite direction. Just to be even more confusing, some systems say that ON is 0 - but in those systems, the result of 0 AND 0 would be 0, not 1.


text:
Cast from uint8_t* to char - loses precision
I am trying to decode a received (via websocket) message (JSON) on my ESP8266.
The websocket library provides the data as uint8_t. The JSON library only understands char arrays. As far as I know uint8_t is basically char.
I am getting this error:
cast from 'uint8_t* {aka unsigned char*}' to 'char' loses precision [-fpermissive]
The websocket-function provides the payload as uint8_t:
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)

The JSON Decoder wants a char arr, as provides in the sample:
char json[] =
"{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";

How to "convert" the uint8_t to char[]?
Here is my full code:
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>

WebSocketsServer webSocket = WebSocketsServer(81);
StaticJsonBuffer<200> jsonBuffer;

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

    switch(type) {
        case WStype_DISCONNECTED:
            Serial.printf("[%u] Disconnected!\n", num);
            break;
        case WStype_CONNECTED:
            {
                IPAddress ip = webSocket.remoteIP(num);
                Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

        // send message to client
        webSocket.sendTXT(num, "Connected");
            }
            break;
        case WStype_TEXT:
        {
            Serial.printf("[%u] get Text: %s\n", num, payload);
            JsonObject& root = jsonBuffer.parseObject((char)payload);
            // send message to client
            // webSocket.sendTXT(num, "message here");

            // send data to all connected clients
            // webSocket.broadcastTXT("message here");
        }
            break;
        case WStype_BIN:
            Serial.printf("[%u] get binary length: %u\n", num, length);
            hexdump(payload, length);

            // send message to client
            // webSocket.sendBIN(num, payload, length);
            break;
    }

}

void setup()
{
  Serial.begin(115200);
  Serial.println();
  IPAddress ip(192, 168, 178, 51);
  IPAddress gateway(192, 168, 178, 1);
  IPAddress subnet(255, 255, 255, 0);
  WiFi.config(ip, gateway, subnet);
  WiFi.begin("MyWifi!", "passpasspass");

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}

void loop() {
   webSocket.loop();
  }

No, payload is a uint8_t*. Have you tried casting to char* yet?

Well, you are trying to cast pointer to uint8_t to one character, so it warns you about that. If you cast it to pointer to char, it should work:
JsonObject& root = jsonBuffer.parseObject((char *)payload);


text:
Need help understanding how RF communication works with 2 arduinos
I have two arduinos (uno) and I would like to send the results of a key press on a 5X4 matrix pad to the other arduino. The matrix keypad works great. I can identify which key was pressed with a switch function.
switch (keypad())
//switch used to specify which button
     {
      case 0:
        Serial.print("Key A Pressed");
        Serial.print(keypad());
        messageToSend = 0;
      break;
        case 1:
        Serial.print("Key B Pressed");
        Serial.print(keypad());
        messageToSend = 1;
      break;
        case 2:
        Serial.print("Key C Pressed");
        Serial.print(keypad());
        messageToSend = 2;
      break;
       }

My RF units are both nrf24l01. I have tried working with the sample code and I think the issue is I don't understand how the unit works well enough.

What is the nature of the data sent between units? I want to send
integers, possibly even text. Is that possible? Do I need to convert
to binary or something?
My understanding of "ping" and "pong" is that ping sends a message
then pong sends that same message back to ping... is this correct?
Are RF units very different? Is this one particularly difficult?
If I just want to send with one receive with the other shouldn't
this simplify the code?
What are pipes? How many can I open?
If I have 3 or more of these what changes will I need to make to the
code?

Thanks!

There are a lot of questions here. I suggest doing the best research you can on your own, and then bringing what your stuck with here as individual questions where you can get smaller, quicker answers.

I think the issue is ... - it would help to define what this "issue" is that you are having. You have posted a snippet of code. You haven't said what you expect it to do, nor what it actually does. I suggest you post the code that you are actually using, in its entirety (both sender and receiver if necessary). Then state what happens when you do something (eg. pressing a switch) compared to what you expect to happen. Include any debugging printout that you may have added to your code to help you debug it.

Many questions so broad answers, but hopefully informative for your research

What is the nature of the data sent between units? I want to send integers, possibly even text. Is that possible? Do I need to convert to binary or something?

It depends broadly on what you use. If you use an ethernet peripheral then the communications will be entire ethernet packets with whatever protocol stack you have above it in payload. For simple RF communication modules it may be as simple as a serial stream delivered 8 bits at a time. The simplest rf (buzzer-style) would simply interrupt (or drive a pin high) when the transmitter is sending a signal.
In Your case the transmitter uses an addressed protocol with a payload packet of between 1 and 25 Bytes of data. This means that you will need code to read and store the necessary payload, maintain configuration data and keep track of addresses of the other systems to message. You also need to poll (or handle interrupts from) the rf module to make sure there aren't messages from the transmit node.
How you convert the data is up to you, a string can be represented by a sequence of bytes and can be send and read as a string on the receivers end. Your rf module will deliver you data in 1-25 byte chunks, what you send in that chunk and how to encode it is entirely up to you.
On the low level,the way this module is configured, the MCU sends data into the rf ic using a serial protocol, the module incorporates a buffer to allow the MCU (slow - 8 bit) to send the data and not have to keep up with the 1Mbps throughput of the rf. On a physical level the signals of the chip look thus:

My understanding of "ping" and "pong" is that ping sends a message then pong sends that same message back to ping... is this correct?

Ping Pong is a game and not a well defined technical term. For precision you can define ping-pong as an echo where the transmitter effectively acknowledges the message by re-transmitting it back to you.

Are RF units very different? Is this one particularly difficult?

RF units can be very different depending on what high level protocol they offer. This unit is somewhere half way between full blown wifi and simple and modulated RF communications. It gives you addressing and error correction as well as a robust communication scheme
This particular unit is made to be relatively "modern", it uses GFSK - a frequency modulation scheme -to transmit and receive data to uniquely addressable nodes on a number of channels. At 2.4 GHz it is high throughput, legal.  It is not the simplest toy.
In terms of simplicity, this module has a lot of examples and documentation, given that it has an arduino library it has a high likelihood of working and succeeding, but you will need to use more advanced microcontroller features to fully utilize the device (e.g. interrupts, DMA).
For other RF options there are lots of things to consider. Going up to wifi requires you to maintain a much more complex stack, meaning more processing power and code, if you want to offer TCP/IP services (say webserver) it is even more code but can be done on an 8 bit arduino. Going down to simpler protocol may win you less power and simpler code but a headache to expand.

If I just want to send with one receive with the other shouldn't this simplify the code?

You will still need to implement both a receiving and a transmitting application so the work is still all there, it will simplify the higher level logic into separate application which is easier.

What are pipes? How many can I open?

I see nothing about pipes from a cursory glance at the docs, perhaps you can illuminate more on what you are confused about?
In general pipes are a "hole" where an application (in the broadest sense) can stream data and it will be consumed by whoever is on the other end, a black hole of a serial data stream. You can implement a pipe as a high level software construct that will buffer and consume data from peripherals and wait to send it out the RF transmitter, it may also be implemented on a hardware level with discrete buffers and additional logic around the rf transmitter etc. As a conceptual element you can probably use a "pipe" concept for communication between the different devices in your code (e.g. move byte to pipe 1 for device 1, move byte to pipe 2 for device 2, let the "driver" handle order), this is a design paradigm that makes software development easier.

If I have 3 or more of these what changes will I need to make to the code?

The rf module is fully capable of addressing up to 65,536 unique hosts, so the device is fully ready to talk to 3 of your hosts, however the software logic needs to track the addresses and other comms data about each host as well as process the data for them (if its different) in enough time.
If you are expecting this in advance, good design decisions early on (e.g. small API or library) will make this much easier on yourself to add features in the future.
Final Thought
If you need a simple echo, this may be a bit overkill for your system, however it is relatively powerful and may make it easier for you to program since you can work with "real-world" data units and send multiple byte packets easily.
I would highly recommend you read and understand the datasheet for the RF chip, be thankful that the nice library takes care of the messy details for you, but understanding how it works will certainly help you understand how to use it best.
An 8 bit Atmega may not be powerful enough to process and transmit 3 separate streams together (if they are identical its less difficult) if you require a constant high rate transmission or if you do a significant amount of processing on the arduino before sending you will feel the limitations of the chip and a 32 bit board may be worth looking at.

The 8 bit Atmega was capable of running Toorum's Quest - a sideways scrolling arcade-style game with multiple sprites, sound effects, and reading a game controller, so I think it can transmit 3 streams of data from one to another (not at the absolute same moment, but in quick succession).

It entirely depends on the nature of the stream and the demands of its processing. 2 simultaneous 1 mbit streams would be hard to do in real time the total data volume is too large (supported by the IC with a single antenna). Additionally with larger payloads the 8 bit limitations really multiplies binary size of the application for data heavy tasks. For the simple use case of occasional asynchronous data I would wager its sufficient,however using this module to its full capacity would be beyond the uno's capability.

I totally agree. However the question was I have two arduinos (uno) and I would like to send the results of a key press on a 5X4 matrix pad to the other arduino. - so I believe it would be within the capabilities of a Uno to send a single keypress from a 5x4 keypad to another Uno. Another two Unos, even.

Completely agree, I addressed the numbered questions directly and broadened the scope so I missed that detail. You don't need much to send a few keypresses.

My RF units are both nrf24l01. I have tried working with the sample
  code and I think the issue is I don't understand how the unit works
  well enough.

Start here, this is the absolutely best resource I could find. I use MIRF libary and there are send and receive examples.  They are really, really simple. Get them working first.

What is the nature of the data sent between units? I want to send
  integers, possibly even text. Is that possible? Do I need to convert
  to binary or something?

Technically, you send between 1 and 32 bytes of information. However, the libraries (see examples above) will take care of the technicality and allow you to send nums, chars or strings.

My understanding of "ping" and "pong" is that ping sends a message
  then pong sends that same message back to ping... is this correct?

Not necessarily. Since nrf24l01+ does all the signal checking for you, and you know that your TX device is the only one sending, you can just reply with "data received".
Anyways, why are even concerned with this? Pinging and ponging have nothing to do with your task at hand.

Are RF units very different? Is this one particularly difficult?

Yes, they are different in frequencies, protocols, power etc. No, this one isn't. It's an amazing, cheap and robust piece of Norwegian ingenuity.

If I just want to send with one receive with the other shouldn't this
  simplify the code?

Simplify compared to what exactly? It will simplify the code compared to a two-way communication, obviously.

What are pipes? How many can I open?
  As someone said before me, read the bloody manual, or a tutorial, or the data sheet, or something. The answer is 6.

Any unit can send on ONE pipe and receive on SIX pipes. Imagine having 6 phones on your table. You can simultaneously listen to all 6 phones but you can only TALK INTO ONE. You can choose which one to talk into to, at any point. Unless you have a lot of devices talking to each other (more than TWO), don't bother, forget the pipes.

If I have 3 or more of these what changes will I need to make to the
  code?

Get two Arduinos talking to each other first. No one has succeeded at making anything work by getting ahead of themselves.
Now here is a video of two Arduinos talking. There's only one button but you can easily change it to a 20-button setup.
The code for sending:
#include <SPI.h>
#include <Mirf.h>
#include <MirfHardwareSpiDriver.h>
#include <MirfSpiDriver.h>
#include <nRF24L01.h>

const int buttonPin = 2;
const int ledPin =  3;

// sends a string via the nRF24L01
void transmit(const char *string)
{
  byte c;

  for( int i=0 ; string[i]!=0x00 ; i++ )
  {
    c = string[i];
    Mirf.send(&c);
    while( Mirf.isSending() ) ;
  }
}

void setup() {
  //RADIO
  Serial.begin(9600);
  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.payload = 1;
  Mirf.channel = 90;
  Mirf.config();
  Mirf.configRegister(RF_SETUP,0x06);
  Mirf.setTADDR((byte *)"serv1");

  //BUTTON AND LED
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);

  Serial.println("Sending ... ");
}

void loop() {
  int buttonState = digitalRead(buttonPin);
   if (buttonState == LOW) { //pressed
    digitalWrite(ledPin, HIGH);
    transmit("X");
  }
  else {
    digitalWrite(ledPin, LOW);
  }
}

The code for receiving:
#include <SPI.h>
#include <Mirf.h>
#include <MirfHardwareSpiDriver.h>
#include <MirfSpiDriver.h>
#include <nRF24L01.h>

unsigned long lasttime;
unsigned long delaytime;
unsigned long time;
const int ledPin = 3;

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

  //RADIO
  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setRADDR((byte *)"serv1");
  Mirf.payload = 1;
  Mirf.channel = 90;
  Mirf.config();
  Mirf.configRegister(RF_SETUP,0x06);

  //LED
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);
  Serial.println("Listening ... ");
}

void loop() {
  byte c;

  if( Mirf.dataReady() ) {
    Mirf.getData(&c);
    Serial.write(c);

    if (c == 'X') {
      digitalWrite(ledPin, HIGH);
    }
  } else {
      digitalWrite(ledPin, LOW);
  }
}


text:
Removing the barrel jack connector?
My project is battery powered and it has it's own usb port for charging. Can I snip off the HUGE DC barrel jack which is making it hard for me to fit this into an enclosure.
Or could that cause problems?

Have you considered using a smaller Arduino?

You'll likely do less damage de-soldering it than trying to snip it off. Use a de-soldering pump to remove as much molten solder as you can, then heat again with de-soldering braid to wick up the remainder. If the jack's solder terminals were bent over (to stabilize the part before it was soldered) you may need to straighten them with a tweezer-nosed plier. Then you should be able to lift the part off the board. Don't overheat the board or heat any other parts or solder joints than those you intend to remove.

You can remove it safely without any issues, just make sure that there are no short circuits or any other components damaged while doing so

De sdering would be safer.  You can then use the Vin pin to supply sour voltage (IIRC you can run as high as 12 volts with the uno)

Unless you have some really specific reason to use a UNO, for example using the 2nd ATMega on the board, you would be much better off with an Micro Pro.
On ebay you can find both 3.3V and 5V versions.
You can even find ones that have redundant pins, to accommodate for a permanent installation of the ISP programmer.
Even if you happen to have a shield that is compatible with the UNO pinout, you could still wire it with a flat cable and save space.
Said this, using mechanical means on a PCB is always putting at risk the tracks, which might come off.
Desoldering is better, since it's reversible.
But you might find that it takes an unusually powerful soldering iron, compared to what is used nowadays for smd components, as you will have to heat up simultaneously several large pads, which have connected large tracks and ground areas that act as heat sink.
In case you do not have desoldering braid and or pump, there's a hackish method to remove large components with multiple pads: flood them in molten solder and literally shake them off the board by hitting the workbench sideways, while the solder is still fluid.
Not nice and at risk of adding splash shorts to the board, not to mention the splash damage to the operator: it can cause burns on unprotected skin or organs.
However, if done correctly, it works without pump or braid.


text:
What killed it? Arduino in resin
I made a simple circuit controlled by the ATMEGA IC then tried to encase it in resin. It died. What is the thing that caused it to die? I've had other circuits working fine in resin. I want to try again, what steps can I take to prevent this?
I've looked for obvious shorts but can find none.
Resin heats up when it cures, could that be the issue?

How much current does it use currently? What's that black stuff underneath the IC? I don't think heat is an issue, as the ATMega has a temperature range of -40C to 85C.

The black thing is an ic holder, like the one on UNO boards. I powered it at 3.3v and it worked fine in air.

I asked for current, not voltage. I the future I'd solder wires directly to the IC, instead of using a IC holder.

For your next try, use a conformal coating (and test it) before molding it into the resin.  Replace any switches with corresponding jumpers

my bad I just measured it at 50µA ?

One could easily imagine resin seeping into the ic pin - socket interface and pushing the contacts out of contact.

I tried sealing it with nail polish then putting it in resin and it worked! And this time I have it set up so I can reprogram if needed!

Potting of circuits can lead to various issues. It can't be told exactly what caused your device to fail until you uncover it like an archeologist.
Common problems are:

Resin entering a spring loaded contact and canceling out contact forces
Resin exsuding corrosive substances ruining contacts
Resin expanding during curing and opening spring contacts or even breaking up solder contacts
Same effect after cool down of resin

Later and often unexpected problems are:

thin gaps around potted objects (i.e. no surface contact) literally sucking in water.
potting material producing water itself during curing.

Many of these problems can be circumvented by applying conformal coating, as suggested by comments and apparently proven right by your experiments.
If it is not necessary refrain from using sockets and solder connections directly to the components. You won't be able to salvage them, anyway.


text:
How to Home a stepper and make it move 45 degree after that
I am trying to let a stepper find home (via microswitch) after power up. After that make it move 45 degrees (or the equivalent in steps) and wait for 3 seconds. Below is the code i found/adapted.
The setup part kind of works, but does not run smoothly.
The stepper1() part does not work at all (only jerking movements).
I would also like the motor to be disable when it waits which in my understanding should be achieved by digitalWrite(M2en,HIGH);but when I place this at the beginning and end (LOW, HIGH) of stepper1() it never worked. Any ideas would be great.
#include "AccelStepper.h"

int M2dirpin = 4;  //Motor Y direction pin
int M2steppin = 5; //Motor Y step pin
int M2en=12;  //Motor Y enable pin
#define home_switch 9 // Pin 9 connected to Home Switch (MicroSwitch)

// AccelStepper Setup
AccelStepper stepperX(1, 5, 4);   // (1,2,3) = (Dedicated Board, STEP, DIR)
// Stepper Travel Variables
long initial_homing = -1; // Used to Home Stepper at startup

void setup() {

  pinMode(home_switch, INPUT_PULLUP);
  pinMode(M2dirpin,OUTPUT);
  pinMode(M2steppin,OUTPUT);
  pinMode(M2en,OUTPUT);
  digitalWrite(M2en,LOW);
  Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
  stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper

  // Start Homing procedure of Stepper Motor at startup
  Serial.print("Stepper is Homing . . . . . . . . . . . ");

  while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
    stepperX.moveTo(initial_homing);  // Set the position to move to
    initial_homing--;  // Decrease by 1 for next move if needed
    stepperX.run();  // Start moving the stepper
    delay(20);
  }

  stepperX.setCurrentPosition(0);  // Set the current position as zero for now
  stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper
  initial_homing = 1;

  while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
    stepperX.moveTo(initial_homing);
    stepperX.run();
    initial_homing++;
    delay(20);
  }

  stepperX.setCurrentPosition(0);
  Serial.println("Homing Completed");
  Serial.println("");

 // Move 10 steps forward from the limit switch (to get out of the switch)
  while (stepperX.currentPosition() != 10)
  {
    stepperX.setSpeed(10);
    stepperX.run();

}
}
void loop()
{
//stepper1();
}

void stepper1()
{
  stepperX.move(22.5);
  stepperX.run();
  delay(3000);
}

You need to call run more often. From the documentation:

You must call this as frequently as possible, but at least once per minimum step time interval, preferably in your main loop. Note that each call to run() will make at most one step, and then only when a step is due, based on the current speed and the time since the last step.

So a single run call and then a delay, will make the motor move only one step. So you need to rewrite for example:
stepperX.run();
delay(3000);

to
unsigned long startMillis = millis();
while( millis()-startMillis<3000 )
{
  stepperX.run();
}

Secondly, move only works on integers, stepperX.move(22.5); will actually become stepperX.move(22);
Lastly, why are you using a totally different method from the rest, to move the motor 10 steps? I'd use a moveTo(10), like you are using everywhere else.

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


text:
Arduino Python to Serial command
I am trying to send commands via serial from Python to Arduino with the code below.
If I save this code in a dedicated python file "Stepper.py" (Python2.7 on Mac OSX) , the code runs successfully but nothing happens (the code does not trigger a motor connected to Arduino).
If I start terminal and run the same code from the interactive shell it works as expected.
How can I run it via a dedicated file ?
import serial
import time

ser = serial.Serial(port="/dev/cu.usbmodem144231", baudrate=9600, timeout = 0)
ser.write("200+")
time.sleep(1)
print ser.read()

You need to wait after opening the serial port for the board to finish resetting and the bootloader to run and exit before you can send any commands.

You are the man !!! Awesome works. Thank you so much

Majenkos comment (above) solved the problem:
"You need to wait after opening the serial port for the board to finish resetting and the bootloader to run and exit before you can send any commands."
import serial
import time

ser = serial.Serial(port="/dev/cu.usbmodem144231", baudrate=9600, timeout = 0)
time.sleep(1)
ser.write("200+")
print ser.read()


text:
Break loop/restart program at any time
maybe my problem is just that my thinking is wrong. I hope you can help me.
First of all I will point out what I think in general, then I show you some code to work with.
In general my problem is to wrap me head around a push-button (or any other input) that stops (or better restarts) a running program at any time.
If i use the digitalRead(pin-whatsoever)-statement don't I have to tackle the exact mili/microsecond my MC is working on that specific line of code?
I don't want to use an interrupt either, i want to restart the program, not to interrupt it.
My project is some kind of turn-indicators for a bicycle.
The lights shall "run" from right to left on left-turns and vice versa.
But i want to stop the sequence at any point (or at least after one loop-run) if I push the corresponding button again.
After that the MC shall wait for another button-push to run the indicator either till the for-loop is finished or i press the same button earlier.
Another (general) question: Is there a way to get rid of delay-statements and achieve similar results?
Thank You so far.
   // Var-Setup
  const int mtime = 120; // Time between lights lighting up
  const int ftime = 100; // Time between lights turning out

void setup() {
  // put your setup code here, to run once:
  // Pin-Setup
    // LED-Pins
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);

  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);

    // Button-Pins
  pinMode(12, INPUT);
  pinMode(13, INPUT);

}

void right(){
  for(int i=0; i<5; i++){
      // Indicator right with running light (like a "half-knight-rider" ;) )
      // Rise
      digitalWrite(11, HIGH);
      delay(mtime);
      digitalWrite(10, HIGH);
      delay(mtime);
      digitalWrite(9, HIGH);
      delay(mtime);
      digitalWrite(8, HIGH);
      delay(mtime);
      digitalWrite(7, HIGH);
      delay(mtime);
      delay(mtime);

      // Fade
      digitalWrite(11, LOW);
      delay(ftime);
      digitalWrite(10, LOW);
      delay(ftime);
      digitalWrite(9, LOW);
      delay(ftime);
      digitalWrite(8, LOW);
      delay(ftime);
      digitalWrite(7, LOW);
      delay(250);
    }
}

void left (){
  for(int i=0; i<5; i++){
    // Indicator left with running light
    // Rise
    digitalWrite(2, HIGH);
    delay(mtime);
    digitalWrite(3, HIGH);
    delay(mtime);
    digitalWrite(4, HIGH);
    delay(mtime);
    digitalWrite(5, HIGH);
    delay(mtime);
    digitalWrite(6, HIGH);
    delay(mtime);
    delay(mtime);

    // Fade
    digitalWrite(2, LOW);
    delay(ftime);
    digitalWrite(3, LOW);
    delay(ftime);
    digitalWrite(4, LOW);
    delay(ftime);
    digitalWrite(5, LOW);
    delay(ftime);
    digitalWrite(6, LOW);
    delay(250);
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  int sensorL = digitalRead(12);
  int sensorR = digitalRead(13);
  if(sensorL == HIGH){
    left();
  }else if(sensorR == HIGH){
    right();
  }
}

replace each delay chain with a switch statement where each delay is replaced by saving the current millis counter, a increment of the state, a case label for the new state and a if(millis()-timestamp  < timeout) return;
switch(state){
case 0;
      // Indicator right with running light (like a "half-knight-rider" ;) )
      // Rise
      digitalWrite(11, HIGH);
  timestamp = millis();
  state++;
case 1:
   if(millis()-timestamp  < mtime) return;

      digitalWrite(10, HIGH);
  timestamp = millis();
  state++;
case 2:
      digitalWrite(9, HIGH);
//etc.

The for loop around the entire thing will need to be replaced. Make i global and incrementing it in the last state and resetting it as needed. When i has been incremented to beyond 5 you always return.
This means that the left and right functions only do a few things: set the led, check a timestamp against the current time, and increment a state before returning.
This means that they will take very little time to execute and that you can check the button in the main loop() body and if pressed initiate the statemachine or end it (and putting out the LED when needed).


text:
Two data outputs to be displayed on one 16x1 lcd display
Before pursuing this very far, I would like to know if I can get two different data outputs (one on the left 8 and the other data on the right 8).  And if so, are there any requirements on the display or any other thing that might be needed.  I'm thinking that as far as the proper Arduino platform being the Mega 2560.  My idea is to put together an FSX navigation radio for my flight simulator.

You can do anything you can write code for.

lcd.setCursor(0,0); lcd.print("val1"); lcd.setCursor(8, 0); lcd.print("val2");. Try reading the manual and examples.

https://www.arduino.cc/en/Reference/LiquidCrystalSetCursor

don't forget extra spaces on the right when drawing multiple numeric data: lcd.print(String(v1,2) + "      ") which allows negatives and more digits without leaving the previous draw's numbers behind.

You can use
lcd.setCursor(x, y);

To set the cursor.
Than you can output text with
lcd.print("Text");

Make sure you add spaces in case there is already text written to overwrite older text.
You can also use
lcd.clear();

to clear the display, but this might result in flickering if you do it too often.
Another possibility is to create a 16 character string
char lcdText[16];

and write characters in this string and set it at once with:
lcd.setCursor(0, 0);
lcd.print(lcdText);


text:
Can I hook up two micros to one GPS module?
I've worked with a few different GPS modules. Most of them seem to just pump out data and not really interact with the micro controller.
I have a quadcopter (Cheerson CX 20 Big Sky) It has a gps break out board that looks similar to the one I've worked with before. Is it likely that I connect another micro controller to this board? I want to add a cellular module to my quad.
I know that the answer may be "it depends" but before I start testing and researching I just want to know if it's even likely to work.
If the gps is just barfing out coordinates and not interacting with the main board I think it could work. I could just tap in and "listen" -- is this even a possibility?

You are quite wrong. The answer is not "it depends", but "yes".
You can have any number of devices listening to (receiving) the transmitted data. You can only have one device sending anything back to whatever it is that is broadcasting the data if you need to configure it in any way. That shouldn't be a problem of course if you have one main controller that does that configuration and everything else is just a passive listener.  Just be sure that you don't connect the transmit pins of the passive listeners to anything (unless you want to use them for a completely unrelated purpose to transmit serial data to something else).
The only caveat is that each device you add as a listener will increase the load on the GPS's transmit pin and eventually the slew rate will become too slow and the signal will become distorted. If this ever becomes an issue reducing the baud rate can combat it to a certain extent. For serial though you would need quite a lot of devices for it to become an issue. Two devices certainly won't ever be an issue.

Great! Thanks. This is how I thought it might work but I wasn't certain.


text:
How to read temperature using arduino uno board with PT100 RTD sensor?
I am new to arduino programming. And almost inexperienced.
I am looking to program my arduino Uno board to read 2/3/4 wire configuration of PT100 RTD sensor (in accuracy levels of atleast 0.5°C). The temperature range is 0 to 400°C and -50 to 100°C.
Since I am totally new to this field I would appreciate a rather descriptive information with circuits and images and code.
I have researched a lot on the subject, but couldn't get anything useful or substantial to solve my problem.
Moreover, I cannot use thermistor or any IC to read the temperatures as the machine on which the RTD is installed has PIDs, but I would like to create a datalogger that can fetch temperatures on computer itself.

You can get ICs which can be used for these sensors, wouldn't that be easier?

I am unable to use ICs as already we are using RTDs with PID controllers to control the temperature. I have to use these existing RTDs to get the temperature readings otherwise there might be variation in the temperature readings of RTD and IC. Moreover, we have applications where we require temperature readings of about 400°C with an accuracy of +/- 0.5°C. I doubt that there exists any ICs that can handle such precision and temperature range.

how are the RTDs connected then at the moment

A MAX31865 can handle -200°C to 500°C. Are you concerned about the IC being exposed to temperatures?

Actually, the RTDs are installed on a cable extruder having holes to insert the RTD into them. The temperature currently are being read through PID controllers. And yes I am concerned about having the IC damaged. Moreover, how am I supposed to insert the ICs in those tiny holes in the extruder barrel?

I'd llike to clear up a slight misunderstanding: The PT100 RTD is the SENSOR and the MAX31865 is the SENSOR AMPLIFIER, SIGNAL CONDITIONER and A/D CONVERTER. As such, the MAX31865 is NOT subjected to extreme temperaturas as it is NOT the sensor. HTH.

No need to shout. I was actually pointing out the range that the IC works with, i.e. the resistive output of the RTD. The operating is -65  to 150, in my comments I never stated it was the operating temperature. Also make a worth while contribution to the forum and give answers or ask questions so you can get rep to comment rather than put up useless answers like this.


text:
Serial Communication Between 3 Arduinos Doesn't Work (Daisy-Chain)
In my project, I have to send a string from one arduino to a second arduino, and make it send the same string to a third arduino. I used UART and SoftwareSerial library, and connected the arduinos like that:
In all the arduinos:
Pin 10 - RX port, pin 11 - TX port

Arduino 1 pin 11    ---->  Arduino 2 pin 10
Arduino 2 pin 11    ---->  Arduino 3 pin 10
Arduino 3             ---->  PC (by hardware Serial)
By theory, Arduino 1 sends string "CA" to arduino 2, which resends that same string to arduino 3, that prints it back on Serial.
The problem is that I get the string "C�" instead of "CA" (that weird "C�" is equal to "067 255" on ASCII).
Does anyone knows why it happens? Maybe there's something wrong with my code?
Here's the code for all the three Arduinos:
Arduino No. 1:
#include <SoftwareSerial.h>

#define ADDR "CA"
SoftwareSerial tiny(10, 11); //TBD

void setup() {
  Serial.begin(9600); //debug only
  tiny.begin(9600);
  delay(2000);

  tiny.write(ADDR);
}

void loop() {
  //nothing here
}

Arduino No. 2:
#include <SoftwareSerial.h>
SoftwareSerial tiny(10, 11); //TBD
void setup() {
  Serial.begin(9600); //debug only
  tiny.begin(9600);
}
void loop() {
  if(tiny.available() > 0) {
    tiny.write(tiny.read());
  }
}

Arduino No. 3:
#include <SoftwareSerial.h>
SoftwareSerial tiny(10, 11); //TBD
void setup() {
  Serial.begin(9600); //debug only
  tiny.begin(9600);
}
void loop() {
  if(tiny.available() > 0) {
    Serial.write(tiny.read());
  }
}

Any idea on what went wrong?

Where are your ground connections? I don't see them there.

Where is it being modified / becoming corrupt ?  Have you printed to debug serial on Arduino 2 to see if it is receiving corrupt data, or if the data is being corrupted on the 2-> leg ?  Also have you swapped them around (Arduino 2 becomes Arduino 3 etc) ?

@Majenko They are all connected to the PC, so their grounds are connected (nevertheless, I tried to connect their grounds together and it didn't help).

@KennetRunner It is being corrupted when it gets to Arduino 2 (gives same results). I tried to swap arduino 2 and 3 but it didn't help.

Connecting the grounds through the USB is not adequate. You need a direct connection between all the boards' grounds.

SoftwareSerial is appallingly bad. It barely works at the best of times. Try sending 'C' then delaying, then sending 'A'.

@Ido Daniel - I'd also remove Arduino 3 from the picture until you get 1 -> 2 working correctly, then introduce it back in...

@KennetRunner Actually, given that Arduino 2 is merely a proxy, I'd remove Arduino 2 until 1 -> 3 directly works correctly...

@John Burger Given thatArduino 2 is where the first evidence of corruption occurs I'd start there. Either way will work though...

Arduino #2 should have two SoftwareSerial instances, one to listen to Arduino #1 and another one to talk to Arduino #3:
// In Arduino #2
SoftwareSerial tiny1(10, 11); // Listen to Arduino #1 on pin 10
SoftwareSerial tiny2(8, 9);   // Talk to Arduino #3 on pin 9

You may not need to wire unused signals (11 and 8).
There is an example here : https://www.arduino.cc/en/Tutorial/TwoPortReceive
Note that what you are trying to do is a bus. Serial in Arduino is RS232 based and that is not a bus but a point to point protocol. You should consider using I²C or SPI.


text:
Capacitive Sensor gets stuck
I want to use CapacitiveSensor library in order to make my own aluminum keys piano. I have seen many videos online showing projects like the one I'm trying to do, but for some reason mine doesn't work.
Here's my cuircit:

Here's my code:
#include <CapacitiveSensor.h>

CapacitiveSensor   cs_7_6 = CapacitiveSensor(7,6);  // 10M resistor between pins 7 & 6, pin 6 is sensor pin

void setup()
{
   //cs_7_6.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
   Serial.begin(9600);
}

void loop()
{
    long start = millis();
    long total1 =  cs_7_6.capacitiveSensor(5);

    Serial.print(millis() - start);        // check on performance in milliseconds
    Serial.print("\t");                    // tab character for debug windown spacing

    Serial.print(total1);                  // print sensor output 1
    Serial.println("\t");

    delay(10);                             // arbitrary delay to limit data to serial port
}

This happens whenever I touch the aluminum foil:

First nothing happens (for ~1 sec), then it prints -2 as the capacity value, and when I release my finger from the foil it prints a very high value.
Anyone knows the reason for it? I'm searching for an answer for a long time and still can't find a solution...

The method that library uses is incredibly crude and shouldn't be considered reliable.  It's not proper capacitative touch sensing.  To do it properly you need four things that you don't have with that library: 1. a constant current source. 2. an analog input pin. 3. MOSFET switching for charge/discharge circuits. 4. a ground plane integrated with the touch sensor.  While under some circumstances it may appear to give capacitative touch sensor-like results, I certainly wouldn't use it for anything more than making an LED light up. Certainly never anything that controlled any motors or similar.

By the way, "-2" is "timeout" (something you'd never get with a proper CTMU).

Oh, and have you read all the things on the Arduino Playground page for the Capacitive Sensing Library?

The problem is that you're touching the foil.
The "capacitive sensing" used in that library is crude at best.
If you read the Arduino Playground page for the Capacitive Sensing Library it discusses a lot of the problems with the library, including grounding.  Make sure that the Arduino is properly grounded, or provide your own ground plane under the foil sensors.
Also they talk about the value of resistor and the sensitivity.  With a 10MΩ resistor you get sensing at (supposedly) 4-6cm from the foil.  That's the value you're seeing as you remove your finger.  While you're touching the foil it's just having a complete brain haemorrhage and can't work out what is going on (completely unable to charge the pin since you are leeching off all the current).  For "absolute touch" it recommends no more than 1MΩ.
Of course, as I mentioned, that method is rather crude.  To do it properly you need to:

Discharge an analog input pin through a MOSFET to ground (low impedance).
Apply a constant current (typically 50µA is used but varies depending on ADC characteristics) to the analog input for a fixed amount of time.
Remove the current and measure the voltage on the ADC input.
Repeat.

More modern MCUs have this kind of functionality built in, in the form of a "CTMU" - Charge Time Measurement Unit.  If you want to have anything more than "there's someone vaguely in the vicinity of the sensor" then I would suggest switching to a more modern MCU and doing it properly, or employing a specific CTMU chip as an external device.
Also, the sensor should be comprised of three parts - a ground plane, a sensor plane (connected to the ADC) and a dielectric layer between them.  The sensor should also be insulated from direct touch.


text:
Saving byte array in PROGMEM instead of SRAM
For an ethernet project I do, I need to store the Ethernet Shield's MAC address.
I store it like that:
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0xE1, 0x85 };

That works OK, but in my project I need all the SRAM available, so every byte of memory is important. I've used the F() macro and PROGMEM everywhere, but I couldn't manage to store the MAC byte array in the PROGMEM.
How can I store it in PROGMEM? Is it even possible?

Try "const byte mac[] PROGMEM = { ... };" https://www.arduino.cc/en/Reference/PROGMEM

MAC addresses are usually configurable, so I'd rather store it in EEPROM.

Since the original question indicated the OP was having trouble accessing PROGMEM, s/he may also have problems with EEPROM. Could you perhaps expand your answer with a code snippet that illustrates how your suggestion would work?

As it stands, this would make more sense as a comment. But if you can address the OP's issue – how to store the MAC address outside of SRAM then it would be a good answer.

Related: Can I write to flash memory using PROGMEM? and Writing objects to PROGMEM

See Putting constant data into program memory (PROGMEM) for tips about putting stuff into PROGMEM. However personally I wouldn't get too excited about saving 6 bytes.

Example code:
Declare data globally:
const byte mac [6] PROGMEM = { 0x90, 0xA2, 0xDA, 0x0F, 0xE1, 0x85 };

Get a copy for use into a temporary variable:
  char foo [6];
  memcpy_P (foo, mac, sizeof foo);


text:
Help to get Arduino UNO with 4 SoftwareSerial transmit only ports
I just started with my Arduino UNO so please pardon my ignorance with SoftwareSerial but I need help. My goal is to make a system of 4 SoftwareSerial ports. Port1 will receive a burst of 5-10 characters and I will then transmit on eventually Port2,3 & 4. Maybe all or just 1 depending on an operator setting. I made the simplest system to try it where I receive on port1 and display on Serial Monitor. All works well until I do a begin to the second port which is commented out in the listing. When it is not commented out it looks like Port1 receives nothing, no display Port1 never says "available" therefore nothing. Any ideas would be most appreciated.
#include <SoftwareSerial.h>
SoftwareSerial RotorPort1 (8, 9); //RX, TX
SoftwareSerial RotorPort2 (10, 11);

int RotorPortSpeed = 9600;

void setup() {
  Serial.begin(9600);
 RotorPort1.begin(RotorPortSpeed);
  //  RotorPort2.begin(RotorPortSpeed);
  delay(200);
 }

void loop() {
 if (RotorPort1.available()) {
    byte incomingByte = RotorPort1.read();
    Serial.print ("data= ");
    Serial.print(incomingByte);
    Serial.print("  ");
    Serial.print(char (incomingByte));
    Serial.println();
    delay (300);

  }
}

read this : https://www.arduino.cc/en/Reference/SoftwareSerial

Do you get any errors when you compile or upload? If you do please share them

According to online examples like this: https://www.arduino.cc/en/Tutorial/TwoPortReceive suggest you use port.listen()

Multiple instances may be problematic.  Personally I would be tempted to fork the library (or maybe alt soft serial) and modify it with a method to let you change the transmit pin on the fly; then you could use a single instance and just redirect its output in between messages.

As Chris Stratton suggests, multiple instances of SoftwareSerial may cause issues, particularly with pin-change interrupts.
I adapted SoftwareSerial a while back to have a "send only" version. This can be downloaded from here - 6 KB.
One normal SoftwareSerial and 3 instances of the "send only" may possibly help. I haven't tested it.

Chris's suggestion to modify SoftwareSerial to allow pin number changes on-the-fly may be even better. SoftwareSerial can only write to one pin at a time as it blocks, and thus having 4 instances of it doesn't really achieve anything.

Another possible approach would be to use a multiplexer chip. I have a page about that. You could have a single SoftwareSerial instance, and then use the multiplexer to forward its data to one of (up to 8) pins.

You would need pull-up resistors to keep the other pins high (idle) when not in use at a particular moment.

Thanks for the input. There are no error during compile or upload. I have read all the SoftwareSerial stuff on the Arduino site and it says 2 ports receiving is a NO-NO since there is only 1 buffer but transmit should be OK. I will look at the port listen approach. Will let you know the results. Tnx.

IT WORKS!  The solution was to do RotorPort1.listening() right after starting both ports.  Apparently when there are multiple receivers you have to declare which one is the listener but can be changed on the fly.  Nothing in the documentation really said that.
I was almost ready to do the hardware mux since I have been a hardware guy for 30 years and really wanted to do it in software.
You have all been a ton of help.  Thank you. The DJ

If you are posting this as an answer can you please post the amended code, so it is obvious (to the next person) what is required to make it work? Thanks. (Edit this answer to do that).


text:
Simulation of IoT based systems in Software
Thank you for reading this.
Generally there are libraries for GSM and Ultrasound sensors for the software called Proteus and you can simulate them along with you MCU and the interfacing peripherals and simulate .
I have big problem at my hand , I want to simulate ESP8266 or any other relevant wifi module with my Arduino (Simulation Libraries for Arduino are available ) and get the data from sensor , all in software . Then , I want the wifi device (in software ) to show an ip address , so that I can log the data to an online cloud .
The software and module does not have to be specific , I want to know , If there are any professional software that let you simulate IoT based systems.
I'am new to IoT designing and I'am always comfortable with simulating everything.
If you have any other similar guide on how to design and simulate IoT systems , Let me know .
Have a great day

Possible duplicate of Can I program for Arduino without having a real board?

no mate . I already have a virtual arduino running in proteus . I wanted a much advanced featured soft. part

Sounds like the sort of thing you might use Matlab for, but equally, maybe you could just write some C-code on a PC.

There are tools to simulate Arduino, but it's not meant for anything beyond basic (i.e. simple circuit). Support is limited, you can't just simulate any and every sensor and shields (e.g. LAN, Wireless). Furthermore, ESP8266 is so cheap that hardly anybody has actual use-case to simulate them. I suggest you work on a real device =)
If you need to simulate data stream into your cloud or IoT platform, I suggest you just spin up a machine and run some code to generate data.

I don't know of any simulators, but you might be able to do it yourself.
What you could do is to add a hardware abstraction layer to your code.  When you are running on hardware this just passes the calls to the hardware, i.e. HAL_digitalRead(D0) calls digitalRead(D0).  When you want to simulate the hardware then you #ifdef the simulated code in and it calls {return DigitalPins[GetIndexFromPinName('D0')]; }
The theory is very simple but I don't think its an easy task.  I am surprised someone hasn't done it already, because debugging in Visual Studio or GDB in pure software would be much easier than doing it on the hardware.
I've never use Proteus, so I don't know if that will fit in with how that works at all.


text:
What is the best type of Arduino board for simple delivery robot?
I'm new to arduino, and I want to design a Simple Delivery Robot for Data Center, which has an arm to move items, and it follows line while moving.
I have no idea if there is a special arduino board for these types of robot or I can buy any arduino board.

This is presently unanswerable, as you cannot pick hardware (or at least not limited hardware like an Arduino) until you have determined how the robot will function.  In your case that seems to be mostly an issue of navigation and safety.

ANWSER
I would suggest you to use the Arduino UNO for all the shields that it has. Most Arduinos are so similar that it wont make a difference but the UNO has many shields to it, including a motor/servo shield which is going to be great for your project.
But at the end of the day, it's your project and you can pretty much use any of the boards listed below. They are just advantages and disadvantages of many popular board. Hope it helped you!
The summary has been removed for the sake of respecting Stack Exchanges rules.

This is a re-used answer, and copy-and-pasting answers (even your own) is inappropriate on stack exchange sites (see http://meta.stackexchange.com/questions/104227/is-it-acceptable-to-add-a-duplicate-answer-to-several-questions ) this is especially true in this case where the posting does not even really address any aspects of the question.  If this were the answer, the question would need to be closed as too broad, opinionated, or a duplicate of an existing question on which arduino to start with.

@ChrisStratton, is it better now?

Arduino UNO is the best arduino board for simple projects.
but if you want to add modules like LCD screen and some wireless sensors like bluetooth and RF and you want to make it with more motors then you should probably use Arduino Mega. It is better to use simple DC geared motors.


text:
Flash Arduino Micro code on Atmega32U micro controller
First of all, I am not an expert on electronics, so forgive me for asking something which is trivial for probably the most of you.
I am trying to get my Arduino (Micro) code running on a custom PCB with the Atmega32U chip on it. The person who made the PCB copied parts of the schematics of the Arduino Micro onto a custom PCB. What he did, is place the Atmega chip on it, and also copied the wiring for the micro USB connector.
That way, I can hook up the PCB to my USB port but now Windows does not recognize the chip as a "Arduino hosted via a COM port", but just as a atmega chip.
I learned that installing Atmel Studio 7 will also provide the correct drivers so that Windows recognizes the chip correctly via USB:

The next step for me was to get my code running on the atmega chip. So with some help from the internet I came to the following steps:

open my sketch in Arduino IDE
compile with verbose output
find the location where the ".HEX" file is stored

But how can I flash this .HEX to the Atmega chip?

To get your chip to respond to the Arduino environment over USB you need a booloader (some extra code) to be running on the Atmega32.
To install the bootloader you can use another Arduino as a programmer to the ICSP pins (or any other AVR ICSP programmer).
This procedure and description from Sparkfun for the Arduino Pro will help you.
This may help you understand the ICSP aspect, again from Sparkfun.

Very helpful link, I have an Arduino so will attempt to go for that. I will accept the answer when I got it working. Don't hold your breath waiting, as I said, I am really new on this stuff so it will take me a while :)

You can flash the .hex file to the chip with avrdude.
First, you have to add avrdude to your PATH variables.
This can be done by adding the folder of avrdude.exe to the PATH variables, described in this method.
An example path to your avrdude.exe can be this:
C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\.
Then go to your project where the .hex file lies, and use avrdude to flash the .hex file to the chip.
Example commands can be found on the avrdude website, the description of avrdude flashing can be found here.
My example command that I use in Atmel Studio with an Arduino Mega clone that has an ATmega2560 chip (slightly modified to fit the question:
avrdude.exe -v -p atmega2560 -c wiring -P COM3 -b 115200 -D -U flash:w:<hexfile.hex>:i

This will only work when the ATmega chip is recognized as a COM port isn't it? (avrdude.exe ........ -P COM3)

Yes, as the other answer pointed out, you are more than likely need to install a bootlader on it and use a programmer to program the device. The Atmel chip cannot function as a COM device while simultenously is being programmed.
I use an Arduino Mega clone, I will edit my answer to clear up confusion.

A programmer can be an USBASP, or an Atmel AVRISP MkII programmer, or another Arduino board if you have one laying around, as the other answer suggested.

thanks for the commenting, currently reading the links shared by Jack (and learning a lot ! :))


text:
Modify the call stack of interrupts on Arduino
I'm working with Arduino's libraries. And my interest in the possibility to change the call stack of the SPI interrupt, this because I want: after the interrupt happen, the program could jump to other function and not to the interrupted address.
I mean:
This is the Main code.
void loop ()
{
    func();
}

void func()
{
   // code
   // here happens the ISR interrupt
}

ISR happens inside func()
ISR(SPI_STC_vect)
{
    // code
    // SPDR = 0x00; // MY ANSWER to SPI
    // MODIFY CALL STACK TO GO TO LOOP()
}

Now, after answering the SPI, I want to go back to loop() instead of continue func().
How can I do this?
Thanks for your help.

Since the ISR entry code itself is probably pushing stuff on the stack, on top of the return address, you will have to write your ISR in assembly. This way you can pop the return address first thing in the ISR. Also, make sure func() is not using the stack and not touching the callee-saved registers. You may want to write that one in assembly too.

Now, after answering the SPI, I want to go back to loop() instead of continue func().

This is an extremely bad idea, and not what ISRs are for.
It is all very well wanting to go back to loop, but you would also have to discard whatever is on the stack, since loop started. The suggested method of using setjmp / longjmp may possibly achieve that, but almost certainly you are doing this for the wrong reason.
Jumping back to loop is like saying:

I don't care what was happening when the interrupt occurred
I don't care if it is half-way through sending some message
I don't care if it is half-way through turning on or off some device

In addition to this memory which was allocated (eg. by String objects) might not be freed. In fact the interrupt might occur during memory allocation in which case variables used by the memory allocation routine could be in an indeterminate state.
I strongly disagree with any suggested work-arounds. You simply should not be "jumping out of" an ISR and going somewhere else. Re-think the design.

You can achieve almost what you are describing with the setjmp() and
longjmp() functions. Here is an example, using INT0 to interrupt a
function calling delay():
/*
 * Test non local return from ISR:
 *   - wire a pushbutton between digital 2 and GND
 *   - monitor the serial port at 9600/8N1
 *   - pressing the button should skip "func() ending" and immediately
 *     write "func() returned"
 */

#include <setjmp.h>

jmp_buf saved_context;

/*
 * ISR triggered by low level of INT0 = PD2 = Arduino digital 2.
 * Should only be allowed to trigger while inside loop().
 */
ISR(INT0_vect) {
    EIMSK &= ~_BV(INT0);        // disable further interrupts
    longjmp(saved_context, 1);  // return to loop()
}

void func() {
    Serial.println("  func() beginning");
    EIMSK |= _BV(INT0);   // enable INT0 interrupt
    delay(3e3);           // wait 3 s for an interrupt
    EIMSK &= ~_BV(INT0);  // disable INT0 interrupt
    Serial.println("  func() ending");
}

void setup() {
    pinMode(2, INPUT_PULLUP);  // pin 2 is INT0
    Serial.begin(9600);
}

void loop() {
    Serial.println("Calling func()");
    if (setjmp(saved_context) == 0) func();
    Serial.println("func() returned");
    Serial.println();
    delay(2e3);
}


text:
Troubleshooting DC motor
I worked on the starterkit project #9 motorized pinwheel, and the motor worked just fine.
I then tried to add a potentiometer, and now the motor won't rotate at all any more (neither in the current nor in the project's baseline configuration). I also tried connecting the motor to the 9V battery directly, to no avail.
I did check the battery by briefly connecting a LED right away. The motor apparently also still generates current if I turn it manually (checked with a directly connected LED either).
What else can I do to check what's wrong with the motor? Is it possible that I somehow accidently killed it with my attempts with the potentiometer?

Have you tried a fresh battery? A good 9 V battery should blow a LED pretty fast if you tried to connect it directly.

If your motor doesn't work when connected to the 9V battery, either the battery is flat (which is likely since you were able to connect the LED without destroying it!! - they are a 2.5-3v part, not a 9v part) or the wiring to the motor is damaged. When you connect the motor directly to a 9v battery, it should turn pretty fast - may also work if you connect it to between 2 & 4 AA batteries.
9v batteries don't have that much energy in them... you would be better off with a battery pack with 6 AA batteries in it.


text:
Posting data to ASP web service from GSM using AT commands - where am I going wrong
I'm using an Arduino uno with a SIM900 GSM shield.  I'm trying to connect the Arduino to my (ASP MVC) website.  I've written an API which i've successfully tested with postman, and whilst the GET Command works fine, I've had no success with POSTING data as yet.  Using the arduino to echo serial monitor input, I've done the following...
So, some setup commands
    AT+CGATT?
    AT+SAPBR=3,1,"CONTYPE","GPRS"
    AT+SAPBR=3,1,"APN","internet"    (vodafone UK parameters
    AT+SAPBR=3,1,"USER","web"
    AT+SAPBR=3,1,"PWD","web"
    AT+SAPBR=1,1
    AT+SAPBR=2,1     (confirms i have an IP address)

i then do the following...
    AT+HTTPINIT
    AT+HTTPPARA="CID",1
    AT+HTTPPARA="PROIP","212.183.137.12"   (vodafone uk proxy settings)
    AT+HTTPPARA="PROPORT","8799"
    AT+HTTPPARA="CONTENT","application/json"
    AT+HTTPPARA="URL","http://mywebsite.co.uk/api/obs"
    AT+HTTPDATA=83, 10000    (gives the download command).
    {"SensorName": "TestSensor", "ObsValue": 31, "ObsDateTime": "2017-10-01T03:30:00"}
    AT+HTTPACTION=1

and I just get an "OK" back, no httpaction response, and no data stored on the database.
Is there anything I'm doing that is obviously wrong?  Does HTTPACTION come before the data?
Are there commands I can use to check the status of my http session on the GSM board? to confirm that my settings are correct?
Finally, I keep getting messages like
    +CREG: 1,"002A","0F48"

Always the 1 (presumably the CID i'm using), and always the 002A, but the final part varies.
Any help would be hugely welcome.  Thanks.

Check the web server logs, and sniff your network traffic for port 83 using whatever tools are suitable for your operating system. Put the SIM in a phone and try browsing the web - it may need activating first and Vodaphone are redirecting the traffic to their own activation page.

Also I have never had to use a proxy with GSM access on vodaphone. Try without.

this is a sim i've taken from an IPAD, and had been working fine.  Before I put the proxy stuff in, I was getting a 602 DNS error on my GET command, but I can give it a go :)    My website is being hosted on a commercial hosting site (1and1) so I'm not sure whether sniffing traffic is a viable option, but many thanks for the suggestiongs

so, I removed the proxy settings - and its worked!  once - still thats more often than before.

+CREG: 1,"002A","0F48"

That's the registration status. "1" is "Registered on your 'home' network", "002A" is your LAC (Location Area Code) and "0F48" is the Cell ID (CI).

so these are just messages when the serving cell changes?  Having left the serial monitor up for a while, I do see the same numbers repeating - thanks for the info.


text:
Breaking up for loop with ISR
I am curious if the following scenario is possible.
EICRB |= (0<<ISC60)|(0<<ISC61);
EIMSK |= (1<<INT6);

ISR(INT6_vect) {
  myISR();
}

void myISR() {
     digitalWrite(led_off, OFF);
     // Please break my main for loop :)
}

void loop()
{
      for (i=100; i>=0; i--)
             {

            /* STOP button */
              if (read_switch() == 1) {
                      break;
               }
           .. delays and other logic ...
}

As you see the following code is not complete but quite understandable. I have a heating process done in the main program, each loop temp adjustments, printing, delay etc takes about 2-3 seconds to complete. When somebody pushes a switch read_switch will return 1 and that breaks up this function ending the heating process.
This works just fine except the user have to hold the button for the time it finishes looping and get to this point again.
I have fortunately realized that the switch pin (Arduino promicro pin7) also an interrupt pin so I could do interrupt in real time, as I doing it in other code already.
However what you can do in this ISR routine is limited (eg you cannot print to serial etc). I could setup a global volatile bool variable here of course which would immediately get flipped as the interrupt triggered but it would not solve anything since in the main loop I would have to wait for the next round again.
So is it possible with some hack to tell the ISR to break that for loop (not the whole program with an exit(0)) and continue execution afterwards?

Fairly easy to do. In your heater code, tests the state of the switch periodically and exits if the right state is detected.
As to how periodically you should test, it will depend on your requirement for response time.

Turn the loop into a state machine instead.
Wrap the entire loop body in a switch.
Every time you have a delay(t); make it a target for a case label and replace it with
startTimeout = millis();
currentState = N;
case N: if(millis() - startTimeout < t) return;

Every for(init; condition; inc) loop that has delays inside them can be replaced with
<init>
state = N;
case N: if(!condition) state = N1;
<body>
<inc>
state = N;
return; //return from loop() and let it restart
case N1;

Then any delay inside body can be adjusted like above.
Make sure that every state case is unique and make any state that needs to persist across states global.


text:
Using Arduino or ESP8266 as a switch to turn on a 12V DC Fan
I am new to the community and this is my first question. Hope it turns out to be a nice question :)
Me and my friend are preparing a senior design project on home automation. I have several things in my mind such as controlling drapes, lights, fans with an IOS application.
We started everything from scratch and came up with a great NTC controlled fan and etched it on a PCB as follows

However, here's our bottleneck . Although this circuit works perfectly fine and dandy, this is kind of not what we want. We want a user to control the fan, which made us realized this circuit is a total waste because it is independent of the user, turns up the fan when the temperature goes high not when the user wants it to turn up. What we really want to implement is using something that can be controlled with a phone and works as a switch.
How do you think we can do this? We have this in mind :

We are writing an IOS app with Xcode and we use ESP8266 Wifi module to bridge our phone to a web server which makes the connection between the phone and system. Do you think we can go from here? If so, what should we do to make this system work ?

you can buy 4 wire 12v fans. the 4th wire accepts a logic-level PWM signal, meaning you don't need any components besides the micro, a buck (to take 12v to 3.3v), and the fan. with a cheaper fan, you use the MOSFET as described in the answer below to manage PWM. on the ESP8266, i would recommend making the PWM ultrasonic to avoid "kick noise": analogWriteFreq(19532); in setup()

Sounds like you want an ESP8266 with an API that controls a GPIO pin state.  Very simple.
Phone App or Web app -> ESP8266 with route for controlling GPIO -> MOSFET
The MOSFET should be suitable for 3.3V logic.  Don't forget the flyback diode on the motor.
Here's some pseudo-ish code:
espServer->on("/api/fan", HTTP_POST, [&]() {
    int pwmSpeed = server->arg("pwm").toInt()
    switchGpioState(pwmSpeed);
}
espServer->on("/get-state", HTTP_GET, [&]() {
    // Send state to browser/app
}

I see the answer has been down-voted. An explanation as to why would be beneficial for me and others.

The poster illustrated that he wanted to replace a switch with a software control.  Using the ESP and a MOSFET seems like sound advice. Also added that he should use a flyback diode on his motor.

aside: use use MIT app inventor if you want a no-code mobile client app to control the ESP's HTTP API.

dandavis it's a great way to do it for sure.  I like making full screen web apps because I don't like installing software on my phone.


text:
Select from Custom Array without Repeat
I found this great code to pick a random number from a "hat" without repeat:
/* RandomHat
  Paul Badger 2007 - updated for Teensy compile 2017
  choose one from a hat of n consecutive choices each time through loop
  Choose each number exactly once before reseting and choosing again
*/

#define randomHatStartNum 0  // starting number in hat
#define randomHatEndNum 25    // ending number in hat - end has to be larger than start
#define numberInHat (randomHatEndNum - randomHatStartNum) + 1

void setup()
{
  Serial.begin(9600);
  Serial.println("start ");
}

void loop()
{ // randomHat test
  for (int i = 1; i <= numberInHat; i++) {
    int x = randomHat();
    Serial.print(x);
    Serial.print(", ");
    delay(50);
  }
  Serial.println(" ");
}

int randomHat() {
  int thePick;    //this is the return variable with the random number from the pool
  int theIndex;
  static int currentNumInHat = 0;
  static int randArray[numberInHat];

  if  (currentNumInHat == 0) {                  // hat is emply - all have been choosen - fill up array again
    for (int i = 0 ; i < numberInHat; i++) {    // Put 1 TO numberInHat in array - starting at address 0.
      if (randomHatStartNum < randomHatEndNum) {
        randArray[i] = randomHatStartNum + i;
      }
    }
    currentNumInHat = abs(randomHatEndNum - randomHatStartNum) + 1;   // reset current Number in Hat
    Serial.print(" hat is empty ");
    // if something should happen when the hat is empty do it here
  }

  theIndex = random(currentNumInHat);                  //choose a random index from number in hat
  thePick = randArray[theIndex];
  randArray[theIndex] =  randArray[currentNumInHat - 1]; // copy the last element in the array into the the empty slot
  //                                                     // as the the draw is random this works fine, and is faster
  //                                                     // the previous version. - from a reader suggestion on this page
  currentNumInHat--;    // decrement number in hat
  return thePick;
}

I would like to use a custom array to choose from like so:
char *things[]={
"Thing 1",
"Thing 2",
"Thing 3",
"Thing 4",
"Thing 5",
"Thing 6",
};

Which is quite possible as I use the numbers from to first piece of code to select items from my custom array.
So I have two questions about this:
The first being the code first returns "hat is empty" before the numbers.
start
  hat is empty 11, 24, 17, .......
  hat is empty 4, 19, 23, .......

Is there a way to reverse this?
And secondly, I would like define the randomHatEndNum automatic by the lenght of my custom array, but I have trouble implementing that code. What is the right way to approach this?