text:
"avr/io.h: No such file or directory" while compiling for board Generic STM32F103C series
I'm trying to compile FastLED library for my STM32F103C using Arduino 1.8.5 IDE, but getting this error:
In file included from C:\Program Files
(x86)\Arduino\libraries\FastLED/led_sysdefs.h:32:0,

                 from C:\Program Files
(x86)\Arduino\libraries\FastLED/FastLED.h:44,

                 from
C:\Projects\ioSmartHome\arduino\ColorPalette_stm32\ColorPalette_stm32.ino:1:

C:\Program Files
(x86)\Arduino\libraries\FastLED/platforms/avr/led_sysdefs_avr.h:12:20: fatal
error: avr/io.h: No such file or directory

 #include <avr/io.h>

                    ^

compilation terminated.

exit status 1
Error compiling for board Generic STM32F103C series.

I just have no idea why it's trying to include this file which isn't existed for this platform. Any idea?

Did you select the correct board in the IDE?

More specifically, for a variety of historical reasons, if FastLED can't determine the hardware platform/board being built for, it falls back to avr - and this particular STM chipset isn't directly supported in FastLED at the moment - there's a fork running around that has added support for it, but I haven't had a chance to pull it back into the main library.

<avr/io.h> is a header file used to interface the IO registers of the AVR micro-controllers. Most Arduinos are AVR-based, and some Arduino libraries assume an AVR core. This seems to bee the case with the FastLED library you are trying to use.
Your microcontroller, however, is an STM32, with an ARM core. It is not an AVR, and it will not work with code that assumes you have an AVR core.


text:
Pro Micro HID freezes during computer boot or resume from standby
I am using a Pro Micro as a HID touchpad, connected to a laptop running Ubuntu 17.04. Everything works, except that the board freezes or hangs while the computer boots or resumes from standby, requiring me to disconnect and reconnect it every time.
The board is definitely hanging, not resetting; I have programmed the on-board LEDs to flash in sequence during the setup and loop stages and have determined that the board hangs at random points in the program and does not reset. This suggests to me that the problem lies with the computer or the connection rather than the Arduino.
The hangs occur at specific points during the computer's boot sequence. If I boot with the Arduino connected, it will hang very early in the boot while the manufacturer's logo is visible on screen. If I connect the board at GRUB, the board will hang during Ubuntu's boot sequence, somewhere among the commands to initialize hard disk buses. Less predictably, the board will hang about 75% of the time just after logging in or when resuming from standby (just before the login manager appears).
I wonder whether the power supply may be dropping by some amount sufficient to halt execution, but not enough to reset the board, but I don't know if that's a realistic hypothesis. I don't know how to investigate further.
What could be causing this issue? What steps could be taken to determine and solve the problem?
Edit - February 2018
I have updated my operating system to Ubuntu 17.10, which uses GNOME Display Manager for the login prompt instead of LightDM, and the problem no longer occurs when resuming from suspend. So it appears the communication that froze the Arduino was triggered by LightDM, not the BIOS.

Does it always happen at the same time during boot? I.e., is it during the BIOS probing of the USB devices, or during the OS kernel boot sequence, etc?

@Majenko, I've added the information you requested in the 3rd paragraph.

It sounds like it's trying to put the board into boot keyboard mode and failing. There may be a bug in the Arduino USB stack.

OK. Do you know of any way to debug that? Given that the computer is booting and the Arduino ends up hanging, I'm not sure how I could capture the communication packets.

I would resort to using my TotalPhase Beagle 480, but that's out of the question for you. I can try and replicate it some time, but I don't have much time right now.

source: Stack Exchange

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

sort: votes


text:
Built-in LED turns on when I touch the input port
I'm a beginner. I bought a new Arduino and I uploaded the basic example button code.
const int buttonPin = 2;
const int ledPin =  13;
int buttonState = 0;

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

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

But the problem is that when I touch port 2 the output is getting so I changed the port number 2 to 3 even though without any supply the output is getting on.
Give me some suggestion.

Try pinMode(buttonPin, INPUT_PULLUP) and if (buttonState == LOW).... An input pin that is not connected is floating and touching it may give enough voltage to make it go HIGH.

Follow the basic Button tutorial: https://www.arduino.cc/en/Tutorial/Button

That's is to be expected if you leave the input floating.

When you are reading digital data through a pin you must make sure that you are steering that input pin to a stable state when no input is present.
You can do this by using either a pullup or a pulldown resistor which you can connect externally or you can use the in built pullup.
You can use a 10k ohm resistor to pulldown by connecting it to the button end where your digital pin is connected and the other to ground.
By doing this your above code must work fine.
I think by touching the pin you are actually pulling the voltage state down.
Hope this helps

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


text:
Is it right to connect Serial module directly?
I find a strange thing that the led is on when power is off. And it's the problem of my serial module. Arduino may get power from my serial module. My serial module use max2322. I don't if it will harm my arduino or has influence to my program.
Is it needed to add a resistance?

you have an Arduino ??? powered from ??? and you connected a serial module ??? to rx/tx, ground and ???

@Juraj Arduino no power。I just connect tx rx and gnd to serial module. And my module is connected to pc by usb

Maybe the serial module has a serial cable attached to it which gives a voltage.
I think it can hurt, since you have two voltage sources, one from the Arduino and one from the Serial cable. Not using the power wire from the serial cable should fix the problem.
A resistor will not help because you still have two power sources in case you have both voltage from the Arduino (adapter/USB) and serial.


text:
How to drive a stepper motor, by having it go even steps forward and odd steps back?
I have a question about driving a stepper motor back and forward. Basically I want it to do a total of 24 steps (12 forward and 12 back) but I don't want to repeat the same steps when coming back.
So 2, 4, 6, 8, 10, 12 (step numbers) forward and 11, 9, 7, 5, 3, 1 (step numbers) backwards.
Here is the code I have at the moment and I just cannot get the motor to drive properly.
EDIT: It goes 6 times 2 steps forward, then 5 times backwards and after that it starts to just jerk around. What I want it to do is to go 6 times 2 steps forward (so step 2, step 4, step 6, step 8, step 10, 12) and then come back but fill in the odd steps (step 11, step 9, step 7, step 5, step 3, step 1 and step 0). The idea is that then it doesn't just overlap when going forwards and backwards.
#include <Stepper.h>
#include <TimerOne.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);
int backwardsCount = 0;
int stepCount = 0;

void setup() {
  Serial.begin(9600);
  Timer1.initialize(2000);
  Timer1.attachInterrupt(callback);
}

void callback(){
  if(stepCount < 12) {
    myStepper.step(2);
    stepCount += 2;
  } else if(stepCount == 12) {
    myStepper.step(-1);
    backwardsCount = 11;
    stepCount += 1;
  }
  if(backwardsCount > 1) {
    myStepper.step(-2);
    backwardsCount -= 2;
  } else if(backwardsCount == 1) {
    myStepper.step(-1);
    stepCount = 0;
    backwardsCount = 0;
  }
}

void loop() {
}

I'd suggest you to implement this as a small state machine. Moreover, why doesn't it do what you want? What do you expect it to do and what does it do in reality?

I added it to the edit part in the description :)

Changing if(backwardsCount > 1){ to else if(backwardsCount > 1){ would fix the 5 instead of 6 "steps" back.

I'm voting to close this question as off-topic because it is based on a false premise.  A rotational motor must pass through all intermediate angles of rotation, so the goal is impossible.  You could change the points at which the motor pauses for a dwell time, but if that is your goal then you need to write the question to say so, and then not abandon it for four months.

Ok, I tried to fix a couple of things from your code.
First of all I implemented a small state machine with two states: going forwards and going backwards. Normally you advance by 2 steps, but when you switch state you go directly to 0 or 11. In my opinion this is the most correct way to handle this problem.
Then I modified the way you trigger a movement. I totally dislike interrupts, specifically when not needed like in this case (at least in my opinion). I used the usual approach with millis(). Please note, however, that I had to put 2 milliseconds as period, but I think this was a mistake from your side (I think you wanted 2 seconds). If this is the case, write const uint16_t moveStepMs = 2000; instead of const uint16_t moveStepMs = 2;. If you want to keep the 2ms, please be aware that 2ms * 6 = 12ms, so it will go back and forth in about 25ms. This means it is too fast for you to see anything (and probably also for the motor to move).
Here is the code. I hope it is clear; I tested it online, but there wasn't a stepper in the simulator so I just used some LEDs (I think it works, anyway).
#include <Stepper.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);

const byte State_MovingForw = 1;
const byte State_MovingBack = 2;

byte currentState;
int8_t position; // Note: max 127 for position

const uint16_t moveStepMs = 2;
unsigned long prevMillis;

void setup() {
    Serial.begin(9600);
    prevMillis = millis() - moveStepMs;
    currentState = 0; // Invalid, so it will trigger a change
}

void executeStep(int8_t numOfSteps)
{
    myStepper.step(numOfSteps);
    position += numOfSteps;
}

void loop() {
    if ((millis() - prevMillis) > moveStepMs)
    {
        prevMillis += moveStepMs;
        byte nextState = currentState;

        // Check for a state change
        switch (currentState)
        {
        case State_MovingForw:
            if (position >= 12)
                nextState = State_MovingBack;
            break;
        case State_MovingBack:
            if (position <= 1)
                nextState = State_MovingForw;
            break;
        default:
            nextState = State_MovingForw;
        }

        if (nextState != currentState)
        {
            // Exit condition: what to do when exiting from one state
            switch (currentState)
            {
            case State_MovingForw:
                executeStep(0 - position); // Reset position to 0
                break;
            case State_MovingBack:
                executeStep(11 - position); // Reset position to 11
                break;
            }

            // Advance to next state
            currentState = nextState;
        }
        else
        {
            // no state change (so move to the next value)
            switch (currentState)
            {
            case State_MovingForw:
                executeStep(2); // Move two steps forwards
                break;
            case State_MovingBack:
                executeStep(-2); // Move two steps backwards
                break;
            }
        }
    }
}

Actually I do want the shaft to step every 2 ms because the idea is to quickly move a mirror attached to the shaft that has a laserbeam pointed on it, creating an illusion like there are multiple laserbeams. I have already tried just stepping 12 steps forward and 12 steps back and the motor can handle that kind of speed. The problem was however that the laserbeams didnt match up and they got doubled. I want to have exactly 12 laserbeams. I used a timer because I need to also control the laser (turn off when the motor is stepping and on when it is still).

Ok, but I think you will need the motor to arrive at the desired position. Maybe this is the issue you are seeing: you are firing the laser when the motor is still moving

Well the motor wasnt moving properly, it actually worked when I used the 'setspeed()' command but that command conflicts with TimerOne for some reason so the timer won't work then. However I will try your and let you know of the result :). Thanks in advance already!

@Mr.Owels if this answer "answered" your question please mark it as accepted, or the community bot will think it is still unanswered and continue pushing it to the homepage


text:
How to rotate 3 servo motors when 6 led lights are lit using EMG signals
I am completely new to arduino and trying to do a school project where i will be able to more 3 fingers with the help of a servo motor using EMG signals.
Right now i am able to read the signals. I just want to modify the code in such a way that when all 6 lights are lit on my emg reading device the servo with rotate by 90 degree. And when all leds are off the servo motor will go back to its initial position, that is will rotate back by 90 degree.
I badly need help over here. Here is the code:
 #define NUM_LED 6  //sets the maximum numbers of LEDs
#define MAX 45     //maximum posible reading. TWEAK THIS VALUE!!
int reading[10];
int finalReading;
byte litLeds = 0;
byte multiplier = 1;
byte leds[] = {8, 9, 10, 11, 12, 13};

void setup(){
  Serial.begin(9600); //begin serial communications
  for(int i = 0; i < NUM_LED; i++){ //initialize LEDs as outputs
    pinMode(leds[i], OUTPUT);
  }
}

void loop(){
  for(int i = 0; i < 10; i++){    //take ten readings in ~0.02 seconds
    reading[i] = analogRead(A0) * multiplier;
    delay(2);
  }
  for(int i = 0; i < 10; i++){   //average the ten readings
    finalReading += reading[i];
  }
  finalReading /= 10;
  for(int j = 0; j < NUM_LED; j++){  //write all LEDs low
    digitalWrite(leds[j], LOW);
  }
  Serial.print(finalReading);
  Serial.print("\t");
  finalReading = constrain(finalReading, 0, MAX);
  litLeds = map(finalReading, 0, MAX, 0, NUM_LED);
  Serial.println(litLeds);
  for(int k = 0; k < litLeds; k++){
    digitalWrite(leds[k], HIGH);
  }
  //for serial debugging, uncomment the next two lines.
  //Serial.println(finalReading);
  //delay(100);
}

Thanks :)

And what is the problem?

Why not use a linear  servo with EMG feedback on pulse rate?

Apart the problem you have (that the constants are not defined), what you are asking can be easily solved by looking at the servo library.
The servo library tells you that

You have to include the servo library header: #include <Servo.h>
You have to add a variable to hold the object: Servo myservo;
You have to attach the object to a pin: myservo.attach(SERVO_PIN);
Finally you can move the motor to any position (0 <= x <= 180) with the syntax myservo.write(val);

In your code, then, you have the variable litLeds which tells you how many leds are there. Particularly if you have 6 (or more) leds light you will move to 90°, while with 0 (or less - even if this is meaningless) you reset to 0. So the complete code is
#include <Servo.h>

int finalReading;
byte litLeds = 0;
byte multiplier = 1;
byte leds[] = {8, 9, 10, 11, 12, 13};
Servo myservo;

void setup(){
    Serial.begin(9600); //begin serial communications
    for(int i = 0; i < NUM_LED; i++){ //initialize LEDs as outputs
        pinMode(leds[i], OUTPUT);
    }
    myservo.attach(SERVO_PIN);
    myservo.write(0);
}

void loop(){
    for(int i = 0; i < 10; i++){    //take ten readings in ~0.02 seconds
        reading[i] = analogRead(A0) * multiplier;
        delay(2);
    }
    for(int i = 0; i < 10; i++){   //average the ten readings
        finalReading += reading[i];
    }
    finalReading /= 10;
    for(int j = 0; j < NUM_LED; j++){  //write all LEDs low
        digitalWrite(leds[j], LOW);
    }
    Serial.print(finalReading);
    Serial.print("\t");
    finalReading = constrain(finalReading, 0, MAX);
    litLeds = map(finalReading, 0, MAX, 0, NUM_LED);
    Serial.println(litLeds);
    for(int k = 0; k < litLeds; k++){
        digitalWrite(leds[k], HIGH);
    }
    if (litLeds >= 6)
        myservo.write(90);
    else if (litLeds <= 0)
        myservo.write(0);

    //for serial debugging, uncomment the next two lines.
    //Serial.println(finalReading);
    //delay(100);
}

Please note that some defines are missing (e.g. the MAX, NUM_LED and SERVO_PIN)


text:
Download and print data from Thingspeak
I opted to try doing this with Thingspeak Library instead, which @gre_gor suggested early on. Worked much easier!
Here's working code for anyone else trying to do this. I used the MKR1000.
#include "ThingSpeak.h"
#include <SPI.h>
#include <WiFi101.h>
#include "DHT.h"

char ssid[] = "XXXXXX";    //  your network SSID (name)
    char pass[] = "XXXXXXX";   // your network password
    int status = WL_IDLE_STATUS;
    WiFiClient  client;

unsigned long myChannel = CHANNEL;
const char * myReadAPIKey = "READKEY";
const char * myWriteAPIKey = "WRITEKEY";

#define DHTPIN 1
#define DHTTYPE DHT11
DHT dht(DHTPIN,DHTTYPE);

void setup() {
  // put your setup code here, to run once:
 Serial.begin(9600);
WiFi.begin(ssid, pass);
 ThingSpeak.begin(client);
  delay(10000);

}

void loop() {
 printWifiStatus();
    Serial.println("Reading Sensor Data... ");

  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
    float water = ThingSpeak.readFloatField(myChannel, 4);

   delay(100);

    Serial.print("Writing to ThingSpeak... ");
    ThingSpeak.setField(1, (float)h);
    ThingSpeak.setField(2, (float)t);
    ThingSpeak.setField(3, (float)f);
    Serial.print("... ");
    ThingSpeak.writeFields(myChannel, myWriteAPIKey);
     delay(5000);

  Serial.print("Current temp is: ");
  Serial.print(f);
  Serial.print(" *F and ");
  Serial.print(t);
  Serial.println(" *C");
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.println("% ");
  Serial.print("Water Signal: ");
  Serial.print(water);
  Serial.println(" seconds");

  Serial.println("Function complete, time to rest.");
  delay(10000); // Hibernate [To Do]

}

void printWifiStatus() {
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

------------ ORIGINAL MESSAGE ------------------------------------------------
I've been banging my head against this for a week now and I have made no progress.
I'm trying to convert this code to also read a field on Thingspeak and print to serial (as well as run a pump based on the output). I've tried a handful of guides and recreating it from other projects to no avail. Is there a straightforward method?
#include <SPI.h> //you don't need this as we arn't using the shiled just chip
#include <WiFi101.h>
#include "DHT.h"

#define DHTPIN 1    // what pin we're connected to, pin1 is 5th pin from end
#define floatswitch 7 // float switch
// soil moisture sensor
int soilPin = 2;
int soilPower = 6; //Variable for Soil moisture Power

// light sensor

// Uncomment whatever DHT sensor type you're using!
#define DHTTYPE DHT11  // DHT 11
//#define DHTTYPE DHT21  // DHT 21
//#define DHTTYPE DHT22  // DHT 22

DHT dht(DHTPIN,DHTTYPE);

String apiKey ="XXXXXXX"; // api from ThingSpeak

char ssid[] = "XXXXX"; //  your network SSID (name)
char pass[] = "XXXXX";    //your network password
int keyIndex = 0;     // your network key Index number (needed only for WEP)

//#define WEBSITE "api.thingspeak.com"

//int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "api.thingspeak.com";    // name address for Google (using DNS)

// this function powers and reads the moisture sensor to avoid sensor corrosion.
//int readSoil()
//{
  //  digitalWrite(soilPower, HIGH);//turn D7 "On"
    //int val = analogRead(soilPin);//Read the SIG value form sensor
   // return val;//send current moisture value
   // digitalWrite(soilPower, LOW);//turn D7 "Off"
//}

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

void setup() {
  pinMode(floatswitch,INPUT_PULLUP);

  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial)
  {
    ; // wait for serial port to connect. Needed for native USB port only
  }

}

void loop() {

pinMode(soilPower, OUTPUT);//Set D7 as an OUTPUT
 // attempt to connect to Wifi network:
  Serial.print("Attempting to connect to SSID: ");
  Serial.println(ssid);
//Connect to WPA/WPA2 network.Change this line if using open/WEP network
WiFi.begin(ssid, pass);
digitalWrite(soilPower, HIGH);//turn D7 "On"
    // wait 5 seconds for connection:
    delay(5000);
  Serial.println("Connected to wifi");
  printWifiStatus();

// READ STUFF

String url = "/channels/358435/field/6/last.txt";
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
        "Host: " + server + "\r\n" +
        "Connection: close\r\n\r\n");
    String channelData = client.readStringUntil('\n');
// READ STUFF

  int h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  int t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  int f = dht.readTemperature(true);
  int x = digitalRead(floatswitch);
//This is a function used to get the soil moisture content
  int s = analogRead(soilPin);
  int w = 5;

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f))
  {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Soil Moisture: ");
  Serial.print(s);
  Serial.print(" *F ");
  Serial.print("Float Switch: ");
  Serial.print(x);
  Serial.print("channelData");
  Serial.println();

Serial.println("Starting connection to server...");
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {

    Serial.println("connected to server");

          client.print(F("POST "));
          client.print("/update?key=apiKey&field1="
          +               (String) h
          +  "&field2=" +(String) t
          +  "&field3=" +(String) f
          +  "&field4=" +(String) s
          +  "&field5=" +(String) x
          +  "&field6=" +(String) w
                                   );

          String tsData = "field1="   //need the length to give to ThingSpeak
          +             (String)  h
          +  "&field2=" +(String) t
          +  "&field3=" +(String) f
          +  "&field4=" +(String) s
          +  "&field5=" +(String) x
          +  "&field6=" +(String) w
        ;

          client.print("POST /update HTTP/1.1\n");
          client.print("Host: api.thingspeak.com\n");
          client.print("Connection: close\n");
          client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
          client.print("Content-Type: application/x-www-form-urlencoded\n");
          client.print("Content-Length: ");
          client.print(tsData.length());  //send out data string legth to ts
          client.print("\n\n");
          client.print(tsData);
          client.stop();
          digitalWrite(soilPower, LOW);//turn D7 "Off"
          delay(200);
          Serial.println("Function complete, time to rest");
          WiFi.disconnect();

//This is where to put the sleep and hibernate stuff

          delay(20000);

//hibernate stuff ^^^^
    }

}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

Why not use a library and check the examples?

Sorry, I should have mentioned that. Trying not to get stuck with the Thingspeak library as I've read it gets buggy when other libraries update. Also trying to remain platform agnostic so I can plug this into Adafruit.io, AWS or whatever other data platforms come along down the road.

https://www.mathworks.com/help/thingspeak/get-channel-field-feed.html

Thanks @Juraj I ddi try working through that and another question on SE here, but it came down to basically the following, but still didn't work.
String data = "GET /channels/344468/fields/1/last";

Serial.println(data);

post the code of modified sketch

Tried updating based on iohans answer.

@gre_gor I decided to try using the Thingspeak library. And it worked so much better. Updated the question. Thanks!

You need to construct a client object and pass in a URL. Then, wait for a response and read data in from the client. Here is the main concept.
const char host[] = "api.thingspeak.com";

WiFiClient client;

const int httpPort = 80;

if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
}

String url = "/channels/1417/field/1/last.txt";

client.print(String("GET ") + url + " HTTP/1.1\r\n" +
        "Host: " + host + "\r\n" +
        "Connection: close\r\n\r\n");

while(client.available()) {
    String channelData = client.readStringUntil('\n');
    // do something with the data

}
Make sure to include a Read API key if your channel is not public. Also, check out CheerLights project examples for more ideas on how to do this. Many CheerLights projects read data from a a ThingSpeak channel.

Thanks iohans! Tried dropping it in betweet brackets of // READ STUFF still working on it though, but first time it has still sent data while trying to do a GET request.

There is a lot to tighten up in your code. Move these lines to set up

pinMode(soilPower, OUTPUT);//Set D7 as an OUTPUT
// attempt to connect to Wifi network:
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
//Connect to WPA/WPA2 network.Change this line if using open/WEP network
WiFi.begin(ssid, pass);
digitalWrite(soilPower, HIGH);//turn D7 "On"
// wait 5 seconds for connection:
delay(5000);
Serial.println("Connected to wifi");
printWifiStatus();

Also, you need the while client available to read the data into your string variable. The get is asynchronous, so the data is not ready immediately. You should separate read from write, and clear the client for each connection.

You've given me a lot of homework, thank you! Going to dig in tonight. One question about getting that into Setup, I want this to hibernate for several hours and turn off the wifi et all. Should I still move that to setup or put it in a separate loop like the printwifi status if I'm thinking about power saving.


text:
Strange issue with FHT library for sound-reactive LED project
I have been playing with the FHT library and have run into an interesting issue with fht_mag_octave() disrupting the output of my ADC actions.  Running on a MEGA ADK.
The idea is that I'm using FHT to read in the microphone input into A0, but also occasionally checking A2 pot to adjust the volume/brightness of the of the overall FastLED strip.
Here is the code in question...  it's barebones.  Just the standard FHT loop and then, every 100 loops, it checks A2 for the brightness setting.
#include <FastLED.h>

#define LED_PIN     6
#define BRIGHTNESS  200
#define LED_TYPE    WS2811
#define COLOR_ORDER GRB
#define NUM_LEDS 16
CRGB* const leds(NUM_LEDS);

#define LOG_OUT 1 // use the log output function
#define OCTAVE 1 //   // Group buckets into octaves  (use the log output function LOG_OUT 1)
#define OCT_NORM 0 // Don't normalise octave intensities by number of bins
#define FHT_N 128 // set to 128 point fht
#include <FHT.h> //

void setup() {
  Serial.begin(9600);
  delay(1000);
  FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS);
  FastLED.setBrightness (BRIGHTNESS);

  // TIMSK0 = 0; // turn off timer0 for lower jitter (commented this out b/c I think this interferes with FastLED)
  ADCSRA = 0xe5; // set the adc to free running mode (0b11100101), prescalar=32 for higher ADC clock freq
  ADMUX = 0x40 | (0 & 0x07); // use adc0 (0b1000000)
  DIDR0 = 0x01; // turn off the digital input for adc0

}

int counter = 0;

void loop() {

  while (1) { // reduces jitter

    cli();  // UDRE interrupt slows this way down on arduino1.0

    for (int i = 0 ; i < FHT_N ; i++) { // save 128 samples
      while (!(ADCSRA & 0x10)); // wait for adc to be ready  in binary 0010000 (look for ADC Interrupt flag to be set to 1)
      ADCSRA = 0xf5; // restart adc (in binary 11110101...http://www.robotplatform.com/knowledge/ADC/adc_tutorial_2.html)
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int k = (j << 8) | m; // form into an int
      k -= 0x0200; // form into a signed int
      k <<= 6; // form into a 16b signed int
      fht_input[i] = k; // put real data into bins

    }

    fht_window(); // window the data for better frequency response
    fht_reorder(); // reorder the data before doing the fht
    fht_run(); // process the data in the fht
    fht_mag_octave();
 //   fht_mag_log();

    // every 100th loop, adjust the volume accourding to the value on A2 (Pot)
    if (counter > 10) {

      ADMUX = 0x40 | (2 & 0x07); // set admux to look at Analogpin A2

      while (!(ADCSRA & 0x10)); // wait for adc to be ready
      ADCSRA = 0xf5; // restart adc
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int brightness = (j << 8) | m; // form into an int

//      brightness = map(brightness, 0, 1023, 0, 255);
      Serial.print("b: ");
      Serial.println(brightness);

      FastLED.setBrightness (brightness);

      ADMUX = 0x40 | (0 & 0x07); // set admux back to look at A0 analog pin (to read the microphone input
      counter = 0;
    }

    counter++;
    sei();

  }
}

Here's the output as shown (basically, it's outputting nonsense, non-int values):
b: ⸮
b: ⸮
b:
b:
b: ⸮
b: ⸮
b:
b: ⸮
b: ⸮
b:
b: ⸮
b: ⸮
b: ⸮
b:
b: ⸮
b: ⸮
b:

b: ⸮
b: ⸮
b:

If I comment OUT the fht_mag_octave line and uncomment fht_mag_log(), here is the output (which looks right as I turn the Pot pin):
b: 0
b: 0
b: 0
b: 0
b: 0
b: 9
b: 35
b: 38
b: 48
b: 85
b: 143
b: 171
b: 188
b: 204
b: 224
b: 245
b: 280
b: 332

The issue is that the A2 value "brightness" does not read properly if I use fht_mag_octave().  If I comment out only the fht_mag_octave() line, it works perfectly.  I can also use fht_mag_log instead, and it works fine.
This makes me think that there is something that fht_mag_octave() does something that interferes with the ADC registers.
Any ideas?

Did you try successive readings every 100 to see if it changes?

Hi!  Yes.  The code shows the loop (I've adjusted it from every 100 cycles to every cycle...with no changes in behavior).  The values do change as I turn the Pot (when I comment out the fht_mag_octave() line, but i get gibberish otherwise.  This tells me that the Pot pin is set up correctly, and that the core ADC calls are working. The ONLY variable is fht_mag_octave()

I meant repeat consecutive A2 only

@TonyStewart, You are a genius!  That worked.  I just added a duplicate A2 read right after, and the results of the 2nd read were spot on!  What do you think the cause is?  And why wouldn't just adding a delay before the 1st call have solved it?

I have no idea of cause, I am glad my intuition was correct.  Only the OEM knows for sure.

Thanks to @TonyStewart for suggesting that I just do a successive A2 read.
I modified the code by just repeating the A2 read.  b1 is the first read, and b2 is the 2nd read.
  while (!(ADCSRA & 0x10)); // wait for adc to be ready
  ADCSRA = 0xf5; // restart adc
  byte m = ADCL; // fetch adc data
  byte j = ADCH;
  int brightness = (j << 8) | m; // form into an int

  Serial.print("b1: ");
  Serial.print(brightness);

  while (!(ADCSRA & 0x10)); // wait for adc to be ready
  ADCSRA = 0xf5; // restart adc
   m = ADCL; // fetch adc data
   j = ADCH;
   brightness = (j << 8) | m; // form into an int

  Serial.print("   b2: ");
  Serial.println(brightness);

And the readout looks good.  B1 is now legible, but incorrect/low.  B2 looks accurate and scales all the way to 1024 as I wanted.

b1: 0   b2: 688
b1: 0   b2: 739
b1: 0   b2: 816
b1: 20   b2: 915
b1: 118   b2: 1016
b1: 152   b2: 1023
b1: 172   b2: 1023
b1: 165   b2: 1023
b1: 180   b2: 1023
b1: 188   b2: 1022
b1: 184   b2: 931
b1: 127   b2: 713
b1: 0   b2: 615
b1: 0   b2: 532
b1: 0   b2: 436
b1: 0   b2: 327
b1: 0   b2: 304
b1: 0   b2: 452

I'm still curious about the reasoning behind this...but I'm glad that there is a solution, and not one that is too painful.

I was experiencing something similar, adding a delay solved the issue (?), no idea why. Later trying other things I realized that if you print a number before all of this, the output will be correct (??!).
So I have in my setup function this:
// trick to 'clean and set' Serial printer to avoid    // printing weird characters instead of numbers   Serial.println(0);

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


text:
Arduino JSON extract using ArduinoJSON Library
I'm having a problem extracting the Object/Array from this sample json

[
   {
     "sensor":"gps1",
     "time":1351824120
   },
   {
     "sensor":"gps1",
     "time":1351824120
   }
]

Would anyone have some pointers or sample code to allow me to extract the 'time' from each of the objects ?
Thanks

Check the library examples?

What have you tried? Post the code. Tell us in what way it doesn't work, such as error messages on compile, or unexpected response/behaviour.

You can use the ArduinoJson Assistant on arduinojson.org to create a skeleton.
Here is what it generates in your case:
const size_t bufferSize = JSON_ARRAY_SIZE(2) + 2*JSON_OBJECT_SIZE(2) + 70;
DynamicJsonBuffer jsonBuffer(bufferSize);

const char* json = "[{\"sensor\":\"gps1\",\"time\":1351824120},{\"sensor\":\"gps1\",\"time\":1351824120}]";

JsonArray& root = jsonBuffer.parseArray(json);

const char* root_0_sensor = root[0]["sensor"]; // "gps1"
long root_0_time = root[0]["time"]; // 1351824120

const char* root_1_sensor = root[1]["sensor"]; // "gps1"
long root_1_time = root[1]["time"]; // 1351824120

Thanks, that worked perfectly.  Great library and website to help building the code.


text:
Calling I2C functions inside an ISR
I have an Adafruit 2.8" cap touch display, which has an interrupt pin (IRQ). I tried to use this with my Arduino Nano, but encountered a problem:
When trying to get the touched point from the display during a display triggered interrupt, it would not work because the touch screen is connected via I2C and according to this post, it is not possible to call I2C functions inside an ISR on an Arduino. Therefore the IRQ pin does not make much sense to me, as I would have to poll if the screen is touched inside the main loop.
My question now is: is this a problem specific for the AtMega 328p? I am thinking about getting an ESP32 based board. Would it be possible to get the I2C data inside an ISR on this chip? Or is it just not possible at all?

Use the ISR to set a boolean value. Have the main program read this value, to see if it needs to fetch an update from the display.

@Gerben Though it is possible, I don't see much sense in doing this. I could as well just poll touch.istouched() via I2C directly, so I don't need the IRQ pin at all.

Using the IRQ is a a bit faster, as touch.istouched() requires I2C communication.

@Gerben as I wrote in the comment to ratchet's answer, what's the point of setting a boolean value in the ISR vs reading the pin in the loop? the only advantage is if the pin can stay high for a very short time, but this is not the case. So instead of calling an ISR to set a bool and then poll the bool in the loop, poll the pin in the loop.

@frarugi87 if that's the case, than, with this device, using interrupts doesn't have any benefits.

Here is an analogy for you to help you understand why using the IRQ is a good idea.
Imagine you are at a conference. There's hundreds of you in the audience, and you are in a question and answer session with the person on the stage. Maybe their presentation has just come to the end and they're fielding questions from the audience.
Lots of people have questions, and any member of the audience can raise their hand at any time to ask a question.
Now there's three ways of the presenter handling it.
The first way is your way of using an interrupt and responding to the interrupt within the interrupt handler itself.  This is like the presenter stopping what he is saying mid sentence to answer the new question. That's just nasty, and both confusing for the presenter and the audience.
The second way is for the presenter to continue until the current question has finished being answered, then pick someone at random from the sea of hands. While the question is being answered people are getting antsy waving their hands around to get noticed, and there's no guarantee that it will be first come first served. People may then not be paying attention to what is a good answer to an important question because they are fixated on theirs.  That's just the same as you polling the interrupt line, or polling the screen directly. If the interrupt line isn't active at the time you poll it you'll miss it.
The third, and best way, is if the presenter sees a hand go up while he's answering a question, and acknowledges that person with an "Ok, I'll come to you next.". Everyone else knows that waving their hand around is pointless, so don't bother - and the next question can be asked immediately after the current question has been answered. Everyone is happy.  That's the proper way of handling a system like this - when the interrupt triggers you remember "Ok, I'll come to that interrupt signal in a moment when I'm ready". Then in your loop, when you have the time, you act on the interrupt that you remembered earlier. You get to respond at your speed to a signal that you may otherwise have missed.
So to sum up: using an interrupt to remember that something is pending and then act on that remembered state is how you should use interrupts to manage communication.

Great answer! I love to use analogies myself and think I got it now :)

Well, in the third way there is no guarantee that first come is first served. Moreover it implies that when the presenter is mid sentence he stops, looks at the person with the raised hand, tells "yes, I noticed you, I'll answer you next" and then resumes from mid sentence. In my opinion your third way is applicable only n two cases. First is when "timid people" raise their hand for a brief moment and then lower it. If you are not fast enough to catch it then you may miss it. The second is if there is a very urgent task, and the person needs to be answered in a very quick time. In all the[...]

[...] other cases, IMHO, it is useless to stop the main operations to just notice that something happened; you can check it later. So, to sum up, interrupts are good if 1) the event is so short you may miss it between polls or 2) the event is so important it requires immediate reply. In this case, a human interaction lasts for at least some hundreds of ms, and requires a reply in almost the same time, which is eternity compared to the microcontroller speed. If you cannot guarantee one check every, let's say, 50ms you have problems in responsiveness that you have to solve regardless of ISRs

No analogy is ever perfect, that's why it's an analogy, not a similie. And in general most interrupt signals from peripherals come in 2 types: active until acknowledged, or a brief pulse. The former can be polled, the latter really requires an interrupt handler to catch it and latch it.

exactly .. :D +1

I started writing this as a comment, but the more I wrote the more I needed space to complete my thoughts, so here it is as answer.
In my opinion, reacting to a user interaction should NOT be put in ISR; consequently the best thing to do is to avoid the interrupt and poll that wire.
IMHO interrupts need to be used in very few cases, and only when the reactivity to a trigger is needed within (tenths of) microseconds. Whenever the latency can become greater than one millisecond it is much better to avoid the interrupt and all its problems, which are (not limited to)

the need for the microcontroller to save the context
interrupting other "tasks", which can be time critical (see for instance the timing in a software serial)
interrupts can happen any time (maybe in the middle of a write to a int variable)
variables shared between an interrupt and "normal" program cannot be optimized (should always be declared volatile)
ISRs must be as short as possible
usually you can't have multiple interrupts (you become blind to other interrupts, or they get delayed until your ISR is completed)

Point 1 delays your actions uselessly.
Point 2 will be a problem when trying to debug some strange problem in your communication or acquisition or software PWM or anything based on precise timing.
Point 4 implies that shared variables will always be read from memory rather than saved in register (and this will slow down your code)
Point 5 and 6 state that you cannot use long communication routines (serial, I2C, SPI, anything) inside the ISR.
These are common to all microcontrollers generally speaking, so my advice is don't use the interrupt, at least not in this case, since reacting to a user interaction is slow (even 50-100ms will not be noticeable). Poll the wire, then when you detect it ask the controller the position.

The better way to do it would be to set a volatile flag in the ISR and handle that in the main loop.
This relies on you making sure the main loop never blocks so the flag can be check often.
volatile bool isr_happened;

void isr(){
    isr_happened = true;
}

void loop(){
    if(isr_happened){
        //do i2c

        isr_happened = false;
    }

}

But then what's the point on having the ISR? Better to poll the pin periodically rather than polling the variable and have the ISR to block the normal code. This can be useful only when the pin can change very quickly, but a user interaction runs for at least 100ms, and moreover knowing that it was pressed but being unable to know where is useless, so I'd avoid the ISR as per my answer

The ISR can react to the change in the signal's level much more reliably than polling, since it is always checking, whereas polling checks periodically. Checking the state of a single pin, or a boolean variable, is far more efficient than repeatedly transferring chunks of I2C data. Use the ISR as a latch to store when the IRQ pin has changed, and use that latched value at a time that suits you, not the display, to read the coordinates.


text:
OV7670 Camera Module - wrong pins?
I would like to ask you some helpful informations.
Recently I bought an OV7670 Camera Module.
Unfortunately, this item is not compatible with any tutorial I found in dozens and dozens of sites.
It has 18 pins with these signs:
3.3v   GND
SCL    SDA
VS     HS
PCLK   MCLK
D7     D6
D5     D4
D3     D2
D1     D0
RESET  PWDN

I aint noticed these pins on any OV7670 Camera in any site of tutorial, like youtube or arduino.cc or many others at google searching.
The most comon OV7670 Cameras I found in tutorials have SIOC SIOD instead of SCL SDA, HREF instead of HS and XCLK instead of MCLK.
Did I bought a fake or what do you think?
Please, if any of you, knows how to make it conect or have any useful link, I will apreciate to inform me.
Thank you all for your time.

They are actually named in a different manner.
Your camera module has i2c interface.
SIOC is nothing but Serial Input Clock , same as SCL - i2c clock
Similarly , SDA and SIOD are the same - i2c data
HREF and HS are the same too - Hsync signal
MCLK and XCLK are the same too - system clock
Here is a useful link:
https://www.google.co.in/amp/www.instructables.com/id/OV7670-Arduino-Camera-Sensor-Module-Framecapture-T/%3famp_page=true
Cheers !


text:
Arduino IDE fails on Fedora with arduino-builder error "Parameter 'tools' is mandatory"
The arduino-builder app when invoked directly with parameter --tools /usr/bin works, but the IDE fails with the error in the title for any sketch (including the Blink example).
I've tried adding things to preferences.txt like
tools.path=/usr/bin

And variations, but I keep getting the same failure in the IDE.  This is using a fresh distro package install on Fedora 27 (I did not have this problem previously using Fedora 25).

I'd be interested to hear whether the official version of the Arduino IDE downloaded from https://www.arduino.cc/en/Main/Software also has this issue. I've noticed the Arduino IDE version that is in the package managers is always mucked around with so you will encounter strange bugs like this that don't happen with the official version.

Thanks a lot my friend!!!!! All is working

I don't understand why this worked, but I found this comment in Redhat Bugzilla (it doesn't seem to be a bug report specifically about that...but anyway):

Parameter 'tools' is mandatory
    [...]

However, if I create the packages directory in ~/.arduino15, compilation now works.
mkdir ~/.arduino15/packages

Seemed like an easy thing to try, and voila -- after an hour of fuss.
I do not understand why this is so (nothing ends up in that directory, either) but I'm leaving this in hopes it may save someone else some time.

Yep, this looks stupid, but works :)

Yep, worked! Thanks.

I'm glad you posted this. I just updated to Fedora 33 and the latest Arduino IDE to find this issue.

The problem occurs because arduino does not have permission to modify directory in /usr/share/arduino to create tools-builder
All you have to do is navigate to usr/share/arduino create 'tool-builder' directory
sudo mkdir /usr/share/arduino/tools-builder

This is what I needed to do. Fedora 27, arduino IDE 1.8.4

Ditto for Fedora 32


text:
U8glib funny problem
I have strange problem with u8glib library. I have code:
void void_Menu_draw_func_men()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_func_men();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}

void Menu_draw_func_men()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(30, 0, "Funkcje");
  u8g.drawStr(15, 15, "Zerowanie modulu");
  u8g.drawStr(15, 30, "Modul na max");
  if(menu_pos == 0){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  u8g.setPrintPos(5, 50); u8g.print("R:  "); u8g.print(pot_R , 2); u8g.print("   L:  "); u8g.print(pot_L , 2);

  Serial.println("func md");//just for check...

}

And oled display shows only cursor and I can move that cursor as I change menu_pos value. But no letters or values are printed on screen. Only cursor...
If I copy and paste only code from void Menu_draw_func_men(); to other part of my program:
void void_Menu_draw_test_man()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_test_man();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_draw_test_man()
{

  u8g.setFont(u8g_font_6x13);   //replace this dwo lines
  u8g.drawStr(0, 0, "wykonywanie tefsdfs man...");

}

Everything works perfect... I was trying to change void name, and I don't know where is problem...
This is on Arduino Uno; I have 66% used of program memory, and 60% used of dynamic memory.
Maybe you have some idea?...

Your void_Menu_draw_test_man() function checks menu_redraw_required
Does your other part of the program update that variable? Do you call void_Menu_draw_test_man() from the loop() function?
It may help if you show the complete code, rather than small segments, since there are variables, such as menu_redraw_required, which are not changed anywhere in what is visible.
Note also that u8glib is no longer updated in favor of u8g2

I will check u8g2 library, maybe my u8glib couse problem...

about loops, I have while functions till i press back button, and then I back to main menu. It work fine

menu_redraw_required is in every code segment, but all segments are in while loop, there is no chance to update menu_redraw_required in different part code... My code is quite big now... but, when I enter to Menu_draw_func_men(), cursor is turned on, I can move it. I also add Serial.print(); to be sure that I enter to this void Menu_draw_func_men();. And I have always receive in console, a confirmation.
This is how I enter to selected screen from main menu:
if (digitalRead(KEY_SELECT) == LOW)
  {
    in_mmenu = false;

    switch(menu_current)
    {
      case 0:
        menu_redraw_required = 1;
        key_choose();
        break;
      case 1:
        menu_redraw_required = 1;
        test_auto();
        break;
      case 2:
        menu_redraw_required = 1;
        test_man();
        break;
      case 3:
        menu_redraw_required = 1;
        pot_read_menu();
        break;
      case 4:
        menu_redraw_required = 1;
        other_options(); **//previously i was function_menu**
        break;
    }

All screen works properly on almost the same code, only last screen on menu have problem...
See pictures how it looks. I also add code to "wybor klucza" menu. Just print part.

How I enter to void_Menu_draw... works fine in others screens. Just small part for entering methode.
 if(digitalRead(KEY_NEXT) == LOW)
{unit++; if(unit >= UNIT_ITEMS + 1)
{unit = 1;}
menu_redraw_required = 1; void_Menu_draw_keyMenu(); delay(200);}

and
void void_Menu_draw_keyMenu()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_keyMenu();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_draw_keyMenu()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(30, 0, "Wybor klucza");
  u8g.drawStr(15, 15, "Zespol:  "); u8g.drawStr(60, 15, menu_unit_num[unit - 1]);
  u8g.drawStr(15, 30, "Numer mod:  ");  u8g.drawStr(78, 30, menu_mod_num[module - 1]);
  u8g.drawStr(8, 50, "Modul to 2 silniki!");
  if(menu_pos == 0 && in == false){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1 && in == false){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  if(menu_pos == 0 && in == true){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(148); u8g.enableCursor(); u8g.setCursorPos(110,20);}
  if(menu_pos == 1 && in == true){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(148); u8g.enableCursor(); u8g.setCursorPos(110,35);}

}

I show you 2 more codes. There are the same, this one void_Menu_draw_test_man works, this one Menu_other_options not. Notice that I change name from functions_men to other_option, just to be sure that name don't cause this issue. I aleso update u8glib to last version. I try use u8g2 library but i will have to change almost everything...
void test_man()
{
  menu_redraw_required = 1; void_Menu_draw_test_man();
  while(digitalRead(KEY_BACK) == HIGH)
  {
    if(digitalRead(KEY_PREV) == LOW){menu_pos = 1; menu_redraw_required = 1; void_Menu_draw_test_man(); delay(200);}
    if(digitalRead(KEY_NEXT) == LOW){menu_pos = 0; menu_redraw_required = 1; void_Menu_draw_test_man(); delay(200);}
  }
  menu_redraw_required = 1;
  u8g.disableCursor();
  in_mmenu = true;
}

void void_Menu_draw_test_man()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_test_man();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_draw_test_man()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(40, 0, "Funkcje");
  u8g.drawStr(15, 15, "Zerowanie modulu");
  u8g.drawStr(15, 30, "Modul na max");
  if(menu_pos == 0){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  u8g.setPrintPos(5, 50); u8g.print("R:  "); u8g.print(pot_R , 2); u8g.print("   L:  "); u8g.print(pot_L , 2);

}

and second
void other_options()
{
  menu_redraw_required = 1; void_Menu_other_options();
  while(digitalRead(KEY_BACK) == HIGH)
  {
    if(digitalRead(KEY_PREV) == LOW){menu_pos = 1; menu_redraw_required = 1; void_Menu_other_options(); delay(200);}
    if(digitalRead(KEY_NEXT) == LOW){menu_pos = 0; menu_redraw_required = 1; void_Menu_other_options(); delay(200);}
  }
  menu_redraw_required = 1;
  u8g.disableCursor();
  in_mmenu = true;
}

void void_Menu_other_options()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_other_options();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_other_options()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(40, 0, "Funkcje");
  u8g.drawStr(15, 15, "Zerowanie modulu");
  u8g.drawStr(15, 30, "Modul na max");
  if(menu_pos == 0){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  u8g.setPrintPos(5, 50); u8g.print("R:  "); u8g.print(pot_R , 2); u8g.print("   L:  "); u8g.print(pot_L , 2);

}


text:
Arduino Nano + RC522 + w5500 Ethernet Module
has anyone had any experience wiring up an arduino nano with an RC522 RFID module and a W5500 ethernet module? i can get each of them to work individually, but i cannot get them to work together. i am not super experienced, but this seems to be some sort of SPI collision
The RobotDyn Ethernet Module i am using:

The RFID Module i am using:

If both modules use SPI then they should each have a separate pin connected to the slave select.
This lets you select which module you are talking to every time you start a communication. If the modules are well behaved then its MISO pin will be in high impedance when it is not selected instead of pulling it low or high trying to send data.
If it is not well behaved then you will need to add a buffer.

thanks for your comment @ratchet-freak, it turned out the RC522 is not well behaved (as you indicated) and i have to set the SS pin HIGH before the Ethernet module would work properly


text:
Arduino and MatLab with OWI Robotic Arm Edge -- Issue with I2C
I'm working on a project where I want to be able to program a robotic arm in Arduino using MatLab. I've used the Arduino Uno with an Adafruit Motor Shield V2.3 and the OWI Robotic Arm Edge kit. The arm is perfectly assembled and works just fine with the standard remote it comes with. All of the connections with the Adafruit Motor Shield are correctly placed, and the shield has been soldered onto pins that connect to the Uno.
I am absolutely positive that the physical and electronic setup is correct. However, whenever I try to move the motors attached to the shield, none of them register. Below is my code:
a = arduino('COM3', 'Uno', 'Libraries', 'Adafruit\MotorShieldV2')
shield = addon(a, 'Adafruit\MotorShieldV2')
addrs = scanI2CBus(a,0);

dcm = dcmotor(shield, 1);
dcm.Speed = 0.01;
start(dcm)

dcm2 = dcmotor(shield, 2);
dcm2.Speed = 0.2;
start(dcm2)

dcm3 = dcmotor(shield, 3);
dcm3.Speed = 0.2;
start(dcm3)

dcm4 = dcmotor(shield, 4);
dcm4.Speed = 0.2;
start(dcm4)

I believe the issue is with the third line:
addrs = scanI2CBus(a,0);

When I run the code, the shield has the following properties:
shield =

motorshieldv2 with properties:

          Pins: A4(SDA), A5(SCL)
    I2CAddress: 96 (0x60)
  PWMFrequency: 1600 (Hz)

So while the I2C address should be 0x60, the actual value of the addrs variable is a 2x1 cell instead of 0x60, as the project demands/specifies as seen in the workspace:

I'm almost certain that this is the reason behind why none of the motors are being registered, but how can I fix it?
Thanks in advance for any assistance! Please let me know if I need to supply more information.

The documentation in MATLAB for scanI2CBus() notes that the return is a cell array of character vectors
They even give the example:
a = arduino('COM9');
scanI2CBus(a,1)

with result:
ans =
            '0x48'

It appears you will need to parse the cell array into the numeric value or otherwise convert it to a number, perhaps using the MATLAB function hex2dec('hex_value')

Thank you for your help, I'll give it a try as soon as I get home!  I'll also be sure to share my results, hopefully I'll get feedback from my motors. Out of curiosity, is it "allowed" for me to assign the value '0x60' to the I2C address variable?

The I2C address is defined by the device. Your sensor probably has it hard coded or it may be set by hardware jumpers on the sensor. It’s not likely you can change it by just assigning a value to the variable.

I think I found out what the  defecting factor is--the I2C address issue may be due to improper soldering of the Motor Shield to the Arduino itself; I realized that the power of the Motor Shield flickers in and out, so that may be the root of the problem.

Don’t try to power the motor shield from the Arduino.


text:
MySensors GatewaySerial code not compiling
I am trying to compile GatewaySerial code from MySensors library for my Arduino Leonardo and it gives me EEPROM errors.
Gateway code:
/**
* The MySensors Arduino library handles the wireless radio link and protocol
* between your home built sensors/actuators and HA controller of choice.
* The sensors forms a self healing radio network with optional repeaters. Each
* repeater and gateway builds a routing tables in EEPROM which keeps track of the
* network topology allowing messages to be routed to nodes.
*
* Created by Henrik Ekblad
* Copyright (C) 2013-2015 Sensnology AB
* Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
*
* Documentation: http://www.mysensors.org
* Support Forum: http://forum.mysensors.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
*******************************
*
* DESCRIPTION
* The ArduinoGateway prints data received from sensors on the serial link.
* The gateway accepts input on seral which will be sent out on radio network.
*
* The GW code is designed for Arduino Nano 328p / 16MHz
*
* Wire connections (OPTIONAL):
* - Inclusion button should be connected between digital pin 3 and GND
* - RX/TX/ERR leds need to be connected between +5V (anode) and digital pin 6/5/4 with resistor 270-330R in a series
*
* LEDs (OPTIONAL):
* - To use the feature, uncomment any of the MY_DEFAULT_xx_LED_PINs
* - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved
* - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly
* - ERR (red) - fast blink on error during transmission error or recieve crc error
*
*/

// Enable debug prints to serial monitor
#define MY_DEBUG

// Enable and select radio type attached
#define MY_RADIO_NRF24
//#define MY_RADIO_NRF5_ESB
//#define MY_RADIO_RFM69
//#define MY_RADIO_RFM95

// Set LOW transmit power level as default, if you have an amplified NRF-module and
// power your radio separately with a good regulator you can turn up PA level.
#define MY_RF24_PA_LEVEL RF24_PA_LOW

// Enable serial gateway
#define MY_GATEWAY_SERIAL

// Define a lower baud rate for Arduino's running on 8 MHz (Arduino Pro Mini 3.3V & SenseBender)
#if F_CPU == 8000000L
#define MY_BAUD_RATE 38400
#endif

// Enable inclusion mode
#define MY_INCLUSION_MODE_FEATURE
// Enable Inclusion mode button on gateway
//#define MY_INCLUSION_BUTTON_FEATURE

// Inverses behavior of inclusion button (if using external pullup)
//#define MY_INCLUSION_BUTTON_EXTERNAL_PULLUP

// Set inclusion mode duration (in seconds)
#define MY_INCLUSION_MODE_DURATION 60
// Digital pin used for inclusion mode button
//#define MY_INCLUSION_MODE_BUTTON_PIN  3

// Set blinking period
#define MY_DEFAULT_LED_BLINK_PERIOD 300

// Inverses the behavior of leds
//#define MY_WITH_LEDS_BLINKING_INVERSE

// Flash leds on rx/tx/err
// Uncomment to override default HW configurations
//#define MY_DEFAULT_ERR_LED_PIN 4  // Error led pin
//#define MY_DEFAULT_RX_LED_PIN  6  // Receive led pin
//#define MY_DEFAULT_TX_LED_PIN  5  // the PCB, on board LED

#include

void setup()
{
    // Setup locally attached sensors
}

void presentation()
{
    // Present locally attached sensors
}

void loop()
{
    // Send locally attached sensor data here
}

Error:

In file included from /home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.cpp:20:0,
                 from /home/szymex/Arduino/libraries/MySensors/MySensors.h:64,
                 from /home/szymex/Arduino/libraries/MySensors/examples/GatewaySerial/GatewaySerial.ino:86:
/home/szymex/Arduino/libraries/MySensors/core/MyTransport.cpp: In function 'bool transportAssignNodeID(uint8_t)':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:54:82: error: 'eeprom_update_byte' was not declared in this scope
 #define hwWriteConfig(__pos, __val) eeprom_update_byte((uint8_t*)(__pos), (__val))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MyTransport.cpp:503:3: note: in expansion of macro 'hwWriteConfig'
   hwWriteConfig(EEPROM_NODE_ID_ADDRESS, newNodeId);
   ^
/home/szymex/Arduino/libraries/MySensors/core/MyTransport.cpp: In function 'void transportSetRoute(uint8_t, uint8_t)':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:54:82: error: 'eeprom_update_byte' was not declared in this scope
 #define hwWriteConfig(__pos, __val) eeprom_update_byte((uint8_t*)(__pos), (__val))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MyTransport.cpp:1065:2: note: in expansion of macro 'hwWriteConfig'
  hwWriteConfig(EEPROM_ROUTES_ADDRESS + node, route);
  ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp: In function 'void _begin()':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:54:82: error: 'eeprom_update_byte' was not declared in this scope
 #define hwWriteConfig(__pos, __val) eeprom_update_byte((uint8_t*)(__pos), (__val))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp:140:2: note: in expansion of macro 'hwWriteConfig'
  hwWriteConfig(EEPROM_PARENT_NODE_ID_ADDRESS, MY_PARENT_NODE_ID);
  ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp: In function 'bool _processInternalMessages()':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:56:114: error: 'eeprom_update_block' was not declared in this scope
 #define hwWriteConfigBlock(__buf, __pos, __length) eeprom_update_block((void*)(__buf), (void*)(__pos), (__length))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp:415:4: note: in expansion of macro 'hwWriteConfigBlock'
    hwWriteConfigBlock((void*)&_coreConfig.controllerConfig, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS,
    ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp: In function 'void saveState(uint8_t, uint8_t)':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:54:82: error: 'eeprom_update_byte' was not declared in this scope
 #define hwWriteConfig(__pos, __val) eeprom_update_byte((uint8_t*)(__pos), (__val))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp:499:2: note: in expansion of macro 'hwWriteConfig'
  hwWriteConfig(EEPROM_LOCAL_CONFIG_ADDRESS+pos, value);
  ^
exit status 1

What Arduino IDE version are you using? What platform (Windows, Linux, Mac)? Using IDE 1.8.1 on Windows, I added the MySensors library, opened the Gateway Serial example, set the device to Arduino Leonardo, and it compiled just fine.

I am missing something? There is practically no code and #include is missing the filename.

@gre_gor this appears to be just the example code from the MySensors library, unchanged.

The sketch and library are here: https://github.com/mysensors/MySensors. The sketch in that repository does have the full #include statement and it compiles for Leonardo fine for me to with Arduino IDE 1.8.5.

Also asked at: https://github.com/mysensors/MySensors/issues/1007 and https://forum.mysensors.org/topic/8045/problem-with-compiling-gatewayserial. If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

It's arduino ide 1.8.4 on linux mint 18.1

Fixed here:
https://github.com/mysensors/MySensors/issues/1007
I needed to update Arduino IDE, reinstall board definitions and MySensors library


text:
Nested for loop used to evaluate a two dimensional array of integers
I am trying to use a nested for loop to evaluate and change numbers within the two dimensional array. Basically these numbers are minutes, or hours. This function is meant to reset the button controlled numbers when they go above 23 (hours) or above 59 (minutes) and also from going below 0. The two dimensional array that I made also has three arrays that need to be skipped (P1[0], P1[2] and P1[10] because they do not contain any time variables. When I click the buttons and increment the numbers nothing unusual happens they just don't bounce back like they are supposed to.
Here is the two dimensional array:
int P1[][12] = { //0-10
  {0}, //MODE
  {0, 0, 0, 0,}, //TOD variables
  // OnHR, OnMin, OffHr, OffMin
  {0}, //DOW
  {0, 0, 0, 0,},  //Sunday
  {0, 0, 0, 0,},    // OnHR, OnMin, OffHr, OffMin
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},  //Saturday
  {0, 0, 0, 0, 0,} // Temperature variables
  //Sensor, GreaterThan/LessThan, Temp, Buffer, State
};

Here is the for loop that doesn't seem to work:
void HrMinBounce() {
  int i = 0;
  int q = 0;

  for (int i; i < 10; i++) { //iterating down Plug arrays
    for (int q; q < 4; q++) {
      if (i != 0 || i != 2) { //non time arrays
        if (q == 0 || q == 2) { //hours
          if (P1[i][q] > 23) {
            P1[i][q] = 0;
          }
          if (P1[i][q] < 0) {
            P1[i][q] = 23;
          }
        }//End of hours
        if (q == 1 || q == 3) { //minutes
          if (P1[i][q] > 59) {
            P1[i][q] = 0;
          }
          if (P1[i][q] < 0) {
            P1[i][q] = 59;
          }
        }//End of minutes
      }
    }
  }
}

I have 5 of these arrays, so I was hoping to make one loop that could take care of all 5 at once. Here is my previous loop that works but I would have to copy and paste a whole lot to get the result without the extra for loop.
void MinHrLimit() {
  int i = 0;

  for (int i; i < 3; i++) {
    if (i == 0 || i == 2) {
      if (P1[1][i] > 23) {
        P1[1][i] = 0;
      }
      if (P1[1][i] < 0) {
        P1[1][i] = 23;
      }
    }
  }
}

            if(i != 0 || i != 2){ //non time arrays

Let's see.

If i is 0 then that is true (it isn't 2)
If i is 1 then that is true (it isn't 0 or 2)
If i is 2 then that is true (it isn't 0)
If i is 3 then that is true (it isn't 0 or 2)

In fact that expression is always true. You probably want:
            if(i != 0 && i != 2){ //non time arrays

   void MinHrLimit(){
      int i = 0;

      for(int i; i < 3; i++){

You don't need the declaration of i there, because it is redefined in the for loop. In the for loop the variable i has an undefined value. You really want:
   void MinHrLimit(){

      for(int i = 0; i < 3; i++){

a few pointers:
1) your array has unevent number of items. so an array of struct is likely more useful here;
2) use brackets liberally, if you want to be sure of sequence of computation, like:
if ((i == 0) || (i == 2)) {

3) if you are going to use a lot of date / time types, think about unix time_t data type. it simplifies coding considerably, and makes your code much more portable.

I will definitely look into Unix time_t. Thank you!

Your problem here is not in your code. It's in the data structures: you
are doing it the wrong way. Of course, it can work, but not only is
your approach wasteful of RAM, it will also inevitably lead to code that
is difficult to write, to understand, to debug and to maintain.
You should really try hard to make your data structures as clean as
possible. I would argue that clean data is even more important than
clean code. If your data mode is clear and makes sense, then clean code
flows naturally. If your data model is contrived, your code will always
look awkward.
Here is how I would go about structuring your data. First thing: you are
using (hour, minute) pairs to represent times. Thus, here is the obvious
way to put them:
struct Time {
    int8_t hour, minute;
};

Notice the variable type: uint8_t takes only one byte, and it can
represent numbers from −128 to +127. Now, this is the right place to
write a function that clamps the numbers to the allowed values. In C,
this would be a plain function. But since we are writing C++, it makes
more sense to make it a method of the struct. Thus:
struct Time {
    int8_t hour, minute;
    void limit() {
        if (hour > 23)   hour = 0;
        if (hour < 0)    hour = 23;
        if (minute > 59) minute = 0;
        if (minute < 0)  minute = 59;
    }
};

It seems all your times come in pairs, with an “on time” and an “off
time”. So here is a data structure for such a pair:
struct OnOffTime {
    Time on_time, off_time;
    void limit() {
        on_time.limit();
        off_time.limit();
    }
};

I added the convenience method limit(), so you can limit an
OnOffTime rather than having to always explicitly limit moth times.
Then, you have a “mode” variable. A mode is normally represented as an
enum, where each possible mode is given a name. Using names instead of
numbers makes everything clearer. For the temperatures and the day of
week, I would use the type uint8_t, which takes only one byte and can
represent a number from 0 to 255. Then, your 2D array becomes an
instance of this:
struct Settings {
    enum { MODE_FOO, MODE_BAR, MODE_BAZ, MODE_QUX } mode;
    uint8_t doy;
    OnOffTime tod, days[7];
    uint8_t temperatures[5];
};

You can probably find better names for the fields of the struct. And you
should.
So, back to the original problem: how to apply the limit() method to
all the times in all your 5 settings. Here it goes:
const int settings_count = 5;

Settings P[settings_count];

void HrMinBounce()
{
    for (int i = 0; i < settings_count; i++) {
        P[i].tod.limit();
        for (int j = 0; j < 7; j++) {
            P[i].days[j].limit();
        }
    }
}

As you see here, the code is short and easy to understand. This is the
benefit of well though data structures: the code that follows is more
natural.


text:
Timer interrupt library for new Arduino based on MCU SAMD21
I'm looking for a timer interrupt library for the new Arduinos based on MCU SAMD21.
I want to wake up periodically the MCU form sleep state, do some task and go sleep again. Using one timer interrupt Arduino wakes up. For new Arduino MKR family.
Do you know a library to do this?

I'm voting to close this question as off-topic because it is a request to find an external library or resource, which is not one of the intended purposes of the stack exchange network.  Try a web search, it seems to yield results.

@ChrisStratton Library recommendations are on-topic, according to Arduino SE's on-topic help page.

Do you know a library to do this?

it is generally very difficult to find a library that does precisely what your application wants. in fact, the purpose of a library is so that it is generic enough for you to tailor it for your specific application.
in this particular case, what you wanted to do is quite simple:
1) read through the datasheet;
2) figure out how the timer works;
3) figure out how the power management works;
4) configure timer isr to wake up the mcu periodically; an overflow isr is typically all you need;
5) run the task directly in the isr if is it short or set a flag for its execution in the loop;
6) upon completion, put the mcu to sleep.
all you need is to tackle the little steps above and you will get it done in no time, and learn a ton about your device.
device datasheet is the best friend of any embedded engineer, not the worst enemy.

The question is if anyone knows a library, not how to do that, I know how to do. I'm looking for a similar library to mstimer2 (https://github.com/PaulStoffregen/MsTimer2) which has a generic purpose. I'm asking if anyone knows to avoid lost time doing it. The rest of the process is done in my project, you can find in https://github.com/jecrespo/Arduino-MKR-FOX-1200-Contest/blob/master/MKR1200_SendData/MKR1200_SendData.ino


text:
Loop one specific case inside of a switch
I want to loop one specific case inside of my switch, until the button gets pressed a second time. How can i make this work?
Code:
const int ledrood = 9;
const int ledgroen = 10;
const int ledblauw = 11;
const int buttonPreset = 2;
const int buttonMix = 4;
float sensorWaarde = 0;
int switchtel = 1;

int roodval;
int groenval;
int blauwval;
int buttonState = LOW;

void setup() {
Serial.begin(9600);
pinMode(ledrood, OUTPUT);
pinMode(ledgroen, OUTPUT);
pinMode(ledrood, OUTPUT);
pinMode(sensorWaarde, INPUT);
pinMode(buttonPreset, INPUT);
pinMode(buttonMix, INPUT);

}

void loop() {
int sensorWaarde = analogRead(A0);
buttonState = digitalRead(buttonMix);
if (buttonState == HIGH) {

delay(200);
switch (switchtel) {
  case 1:
  roodval = 255;
  roodval = sensorWaarde / 4;

    groenval = 0;
    blauwval = 0;
    analogWrite( ledgroen, groenval );
    analogWrite( ledrood, roodval );
    analogWrite( ledblauw, blauwval);
    Serial.println(roodval);
    switchtel = switchtel + 1;
    break;

  case 2:

    roodval = 0; // cyaan
    groenval = 255;
    blauwval = 255;
    analogWrite( ledgroen, groenval );
    analogWrite( ledrood, roodval );
    analogWrite( ledblauw, blauwval);
    Serial.println("2");
    switchtel = switchtel + 1;
    break;

  case 3:

    roodval = 255; // magenta
    groenval = 0;
    blauwval = 255;
    analogWrite( ledgroen, groenval );
    analogWrite( ledrood, roodval );
    analogWrite( ledblauw, blauwval);
    Serial.println("3");
    switchtel = switchtel + 1;
    break;
    switch (switchtel) {

    }
   }
 }
}

Start with the state change detection: https://www.arduino.cc/en/Tutorial/StateChangeDetection . Should there be a timeout for the second press of the button?

You need to split your cases into multiple parts.
For example, you have a case which sets up a mode, and a case that runs a mode, and if needed a case that finishes a mode.
For example:
switch (mode) {
    case 0: // Idle
        break;
    case 1: // Start - do whatever to set up the mode here
        redValue = 100;
        greenvalue = 200;
        mode = 2; // Switch to the next case
        break;
    case 2: // Run - this is the bit that repeats
        if (digitalRead(3) == HIGH) {
            mode = 3; // Finish it
        }
        // Do whatever for each loop here.
        break;
    case 3: // It is finished.
        redValue = 0;
        greenValue = 0;
        // etc.
        mode = 0; // Or whatever you want to do next
        break;
}

The key thing here is that case 1 is equivalent to a mini setup() and case 2 is equivalent to a mini loop(). You switch to case 1, which does the setup, and that case then switches to case 2, which it stays at until you tell it otherwise. That case will keep getting executed until you tell it to move to another case.

I want to loop one specific case inside of my switch, until the button gets pressed a second time. How can i make this work?

not sure why it needs to be anything more complicated than this:
  if (isPressed2x(btn)) do_something(); //if button is pressed twich, execute do_someting()

there are lots of ways to implement isPressed2x(). the simplest would be to use a static variable to keep track of it:
char isPressed2x(uint8_t btn) {
  static char cnt=0; //button press counter
  if (isPressed(btn)) {  //button is pressed
    cnt+=1; //increment counter
    if ((cnt&0x01) == 0) return 1; //button has been pressed twich
  }
  return 0; //button not pressed, or not pressed twice
}

similarly, isPressed(btn) can be implemented, with or without debouncing.
the key is to break down any task into small, simple and well defined blocks so when re-assembled together, those small, simple and well defined blocks can perform tasks as complicated as you wish them to be.
the alternative is to jumbo all of them into one routine, making it hard to understand, hard to debug and hard to port.


text:
Pointers, libraries, and arrays:
I'm trying to pass variable addresses to functions/methods within a custom library that should change the values at the specified addresses.  However, I think I'm missing something as it's taking me ages to tweak things just to get it to compile, let alone gather some useful information from it.
Note:
I've not tested the code as I'm focused on understanding (1.) through to (5.) and is just a quick example of the current pipeline:
Main.ino
#include <customLibrary.h>

CustomLibrary cLib();

byte someByte[6];
unsigned int theAddress;

setup(){};

loop(){

    // (1.)
    theAddress = &someByte; // normally need this here, or before setup(), for it to work.

    cLib.setValues(theAddress);

    // because:
    // cLib.setValues(&someByte);
    // doesn't seem to work
};

customLibrary.h
#ifndef CustomLib
#define CustomLib
#if(ARDUINO > 100)
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class CustomLibrary {
    public:
        CustomLibrary();
        void setValues(unsigned int theAddress); // (2.)
    private:
};
#endif

customLibrary.cpp
#include <customLibrary.h>

CustomLibrary::CustomLibrary(){
};

void CustomLibrary::setValues(unsigned int theAddress){ // (3.)

    byte _someNewValues[6] = {a,b,c,d,e,f};

    // Assign the variable from _someNewValues[_x] to (theAddress + _x)
    int _x = 0;
    for(unsigned int i = theAddress;i < (theAddress + 6);i++){ // (4.)
        // (5.)
        _x++;
    };

};

(1.) - Feels like it should be simpler.
(2-3-4-5.) - I have left out any "*" and "&" hoping that someone can provide the preferred way of doing this, or provide a better solution as it's taking far too long to get this working with everything else leading me to think I'm missing something basic.
There are some excellent tutorials out there which I have been
following with great success, but, only when all the pointers are within the same file.  Once I try and use them in a library it's a constant headache at the moment and I don't understand it enough to know what's wrong.
Need to go before I can proof-read and check it, but I think it's all there.  I'll be back later/tomorrow if there's anything that needs clearing up.
Edit:
I didn't know who to mark for the answer as both @dannyf and @KIIV answered perfectly.  I considered marking the answer based on the time it was posted, but decided instead to let @dannyf have it as his reputation was only 1.
Thank you both! Much appreciated!

somebyte itself is a pointer. so "&somebyte" doesn't make sense.
instead, use "&somebyte[0]" (or "&somebyte[5]" if you want an offset), or "somebyte" (or "somebyte + 5" if you want an offset).
arrays are actually pointers.

Excellent, I had heard that arrays were pointers, just never came across them being an issue explicitly using them as pointers. I missed a second variable, byte anotherByte;, not an array, however, it has an identical pipeline to follow as _someByte[] does.  In that case, what would you do for (2-3-4.)? *theAddress for (2-3-4.)? and at (5.) have something similar to *theAddress = anotherSomeValue; . Apologies, I'm just making 100% sure I've got this because trying to debug it through the error window which is abstract at best when I'm not 100% about something. Thanks!

if you wish to change the value stored at the address pointed to by theAddress, use "*theAddress = someValue;" But the function should indicate that theAddress is a pointer of a particular data type.

To make this a bit more explicit: A reference to an array is a pointer to the array's first member. That is what actually gets passed when you "pass an array" to a function, or a function returns an array.

I'm not sure how it could ever work for you in both variants.
There is simple example how to work with arrays:
class CustomLibrary {
    public:
        CustomLibrary() {;}

        void setValues(byte * address);

        template <class T, int SIZE>
        void setValuesTemplate(T(&bytes)[SIZE])
        {
          for (int8_t i=0; i<SIZE; ++i)
          {
            ++bytes[i]; // just increment the value
          };
        }
 };

void CustomLibrary::setValues(byte * address){
    byte somethingNew[] = {'a','b','c','d','e','f'};

    for (int8_t i=0; i<6; ++i)
    {
      address[i] = somethingNew[i];
    }

};

CustomLibrary lib;

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

void loop(){
  byte someByte[6] = {'z','y','x','w','v','u'};

  Serial.println("Values before:");
  for (byte b : someByte) Serial.print(b, HEX);
  Serial.println();

  lib.setValuesTemplate(someByte);

  Serial.println("Values after templated method:");
  for (byte b : someByte) Serial.print(b, HEX);
  Serial.println();

  lib.setValues(someByte);

  Serial.println("Values after method:");
  for (byte b : someByte) Serial.print(b, HEX);
  Serial.println();

  delay(5000);
};

It's in single .ino file for testing purposes. If you want to use templates, you have to place template method definition into the header file (it doesn't have to be inside class definition, it just have to be in header file).
Range based for loop was introduced by C++11 standard (suported by Arduino IDE for a while - since about version 1.6.5?). It's realy handy on static arrays (like int arr[] = {......}), so you don't have to care about it size. But it's basically everything it can do on avr-g++, as there are no containers, no iterators and so on.
Templates are quite huge topic on C++, in this case it's working with T as array element type and SIZE as its size (it won't work on pointers, it only works on static arrays).
I could've use range based for loop in int too:
    template <class T, int SIZE>
    void setValuesTemplate(T(&arr)[SIZE])
    {
      for (T& item : arr) // it must be a reference type, if you don't want to change local value only
      {
        ++item; // just increment the value
      };
    }

And I didn't even needed that class T part. If you need byte array only:
    template <int SIZE>
    void setValuesTemplate(byte(&arr)[SIZE])
    {
      for (byte& item : arr)
      {
        ++item;
      };
    }

But there is a downside for using templates -> there will one instance of that method for each type/size. But it's possible to use it as a "proxy" and pass it to function that expects just pointer and the size.

Thanks for the help!  That's introduced two new things, which is great as I've not used them before.  template <class,size> and for(byte b : someByte)! As a guess: for(x : y) /* something */ ; is shorthand, like (x) ? x : y;?

@Timeless I've added more detailed description into the answer.


text:
A clarification needed about the HC-05
I have just got a new pair of HC-05 Bluetooth modules. I am working on a simple project. I'm trying to move two servo motors using two potentiometers. I followed a simple tutorial to move one servo, and it worked successfully.
How to make the same thing with 2 potentiometers and two servos?
UPDATE:
I have successfully managed to write down something that get to read values from two potentiometers, but I'am still facing problems with the slave part.
Can't figure out the problem.
(Master)
//Master
int potValuePins[] = { A0, A1 };
void setup() {
  Serial.begin(9600); // Default communication rate of the Bluetooth module
   for (auto pin : potValuePins) {
     pinMode(pin, INPUT);
   }
}

void loop() {
 for (auto pin : potValuePins) {
   Serial.write(pin); // Send the pin number
   Serial.write(analogRead(pin)); // Send the pin value with a trailing
 newline as a delimiter
   int value=analogRead(pin);
   Serial.print(" Pin is: ");
   Serial.print(pin);
   Serial.print("\t");
   Serial.print("Value is: ");
   Serial.println(value);
   }
 }

(Slave)
//Slave
#include <Servo.h>
Servo myServo1;
Servo myServo2;

void setup() {
Serial.begin(9600);
myServo1.attach(9);
myServo2.attach(10);
}

void loop() {
if (Serial.available()) {
 char input[3];
 Serial.readBytes(input, 2);
 int pin = input[0];
 int angle = input[1];
 Serial.print("the pin:");
 Serial.print(pin);
 Serial.print("\t");
 Serial.print("the angle:");
 Serial.println( angle);

 switch (pin) {
  case A0:
    myServo1.write(angle);
    break;
  case A1:
    myServo2.write(angle);
    break;
  default:
    Serial.println("Unknown value");
    break;
   }
  }
 }

Looking at the example you linked to, the "communication" between the two ends is just writing a (byte) value between 0 and 255, and reading that on the other end.
One simple (out of many possibilities) to extend this to handle a set of two is just to send 2 bytes in sequence, with the first byte being an identifier of which servo you are denoting.
Where the example master code shows:
// Reading the potentiometer
potValue = analogRead(A0);
int potValueMapped = map(potValue, 0, 1023, 0, 255);
Serial.write(potValueMapped); // Sends potValue to servo motor

You instead write:
// Reading the potentiometer 1
pot1Value = analogRead(A1);
int pot1ValueMapped = map(pot1Value, 0, 1023, 0, 255);
Serial.write(1);
Serial.write(pot1ValueMapped); // Sends pot1Value to servo motor

// Reading the potentiometer 2
pot2Value = analogRead(A0);
int pot2ValueMapped = map(pot2Value, 0, 1023, 0, 255);
Serial.write(2);
Serial.write(pot2ValueMapped); // Sends pot2Value to servo motor

And on the slave side, where the example has:
if (Serial.available() > 0) { // Checks whether data is comming from the serial port
  state = Serial.read(); // Reads the data from the serial port
}
// Controlling the servo motor
myServo.write(state);

You have to separate out the two possible choices:
if (Serial.available() > 0) {
  servo_num = Serial.read();
}
if (Serial.available() > 0) {
  state = Serial.read();
}

switch (servo_num) {
  case 1:
    myServo1.write(state);
    break;
  case 2:
    myServo2.write(state);
    break;
}

Note that you'll also have to declare the servo_num variable, and instantiate two of the Servo objects. The code above is just a guide.
The simple expansion above is not robust, as it's possible that the 2nd byte is not received by the time the 2nd Serial.read() is called, and then that byte would be caught next time around the loop() by the first Serial.read() call and you'd be out of sync. But hopefully, this shows the general concept of how to start developing a protocol that is more complex than just single values.
Edit: What's probably happening is the system is getting out of sync. As I noted, it's not a robust protocol, but I think you may now understand the idea.
You can re-map the servo values to go from 2-255, rather than 0-255, and set the servo_num to either 0 or 1. In the slave, if you get a number <2, then it's a servo selector, otherwise it's a servo value. but then you lose the ability to set the servo to 0 or 1.
Also, you may want to space out the master sending the values, as you are likely sending data faster than the servo could respond. You could put a delay(100) or something in the loop() function, or change your code to use a millis()-based state machine (see the "BlinkWithoutDelay" Arduino example).

I have set the " pot2Value = analogRead(A0); " to A1, the pin in which I have inserted my second potentiometer.
I have done what you told me too, the servos are not moving the way they are suppose to.
both of them are moving at the same time and not following the potentiometers.
moving constantly.

I left the rest of the coding as an exercise to the reader :-)  How did you instantiate both Servo objects?

Servo myServo1;
Servo myServo2;
and I attached each one of them to the pin I'am using .

Edit/append the updated code you wrote to the question, or join the Pin 13 chat room and we can discuss it

I need to have 20 reputation in order to join the chat room, which I don t have them "yet" so I updated the post.

I added some other options. I'm trying to keep it simple and conceptual. You  could also go into a more complex protocol where you need to implement a state machine and tag the various parameters within the protocol. You'll likely want to go that route, but I hope I answered basically "how" you can do this. The HC-05 can send bytes, but you aren't limited to just one byte as the only data element. You can send series of bytes, etc.

I am still quiet new to the world of arduino and programming.
Its still a bit foggy what you have just said but I will try to look it up and understand what should be done.
Thank You.

Search for articles/examples on serial communication protocols, since that's what you want. You can move a servo already, and you can send a byte. Now you need to expand your knowledge to be able to do more! https://henryforceblog.wordpress.com/2015/03/12/designing-a-communication-protocol-using-arduinos-serial-library/

Can't be thankful enough for your help. :D


text:
ESP8266 only executes Sketch after switching on/off CH_PD pin
I started a new project with an ESP8266-01 module. I want to use it as stand-alone circuit to send an Email at the press of a button.
The wiring is:

VCC    -  3.3v VCC
CH_PD  -  3.3v VCC
GND    -  GND
GPIO_2 -  Push down button (internal pullup)

I've the sketch (Arduino IDE), I've upload it and it essentially works. However:

If I call the sendEmail(); method inside the void setup(){}, it works like a charm.
If I add an push down button on Pin #2 (GPIO_2) it only works if I previously have removed VCC from the CH_PD pin and reattached it again shortly after.

Now, I would bet I read something regarding (or similar) this situation a couple of days back, but I am unable to find it again, now that I need it.
Is there a solution for this or am I missing something?
Any help will be greatly appreciate it!
Thanks in advance!

The GPIO0 and GPIO2 determine what mode the module starts up. GPIO0 and GPIO2 need to have pull-up resistors connected to ensure the module starts up correctly. You can also use RX pin for the button.

Thanks @AltAir for your response. I've followed step #4 of this instructable http://www.instructables.com/id/How-to-use-the-ESP8266-01-pins/   but still doesn't work as I needed it to...

You can try a bulk capacitor between VCC and GND close to the module.

Well, after literally spending hours trying to figure out what the heck is going on, I decided to test the setup with a ESP8266-12 NodeMcu, which is essentially the same but more resembling to an Arduino in that it has more in/out pins and it's better for testing.
On this platform I got a different behavior. I was able to send an Email by the push of the button but... only once. So apparently, contrary to what I believed, something was wrong with the code.
In the code there is this method, which essentially initiates the WiFi connection:
void initializeWifi(){

  WiFi.begin(WIFI, PASSWORD);

  // allow time to make connection
 while (WiFi.status() != WL_CONNECTED)  delay(5000);

  }

Somehow the delay(5000); didn't seem right as delay usually freezes the whole thing. When I commented out the line, everything worked as expected. With the NodeMcu as well as with the ESP8266-01.
However, I still have to figure out how to give time to the WiFi to connect without freezing out all together. Probably it's the time for millis();
I hope this becomes useful to somebody else in the future.


text:
Can I use a 3.3v GPIO to control an opto-isolated 5v relay board?
I am working on a DIY home automation project using a Wemos D1 Mini as the controller, and I ordered some 4-channel 5v-triggered relay boards. The ESP8266 that Wemos D1 Mini's are built on has GPIO output voltage of 3.3v, ostensibly too low to trigger the relays.
I've read a Reddit post that was saying that as long as you use a separate 5v power suppy for the relay board, 3.3v should be enough to trigger the relays. Is that accurate, or do I need to use a transistor or something to provide the relay board inputs with 5v?

Yes, the Reddit post's approach is likely to work ok, as long as you correctly follow the cautions in it:  • connect the VCC pin of the relay board to a 5V source,
•  connect together the Arduino ground,  the relay ground, and the  5v-source ground.
Here is a typical relay-module circuit diagram (for one channel):
(Note, this diagram is from a home automation blog; for more discussion and similar diagrams, see eg
4-relay-shield-diagram at yourduino.com and stripboard-shield-relay-sm at startingelectronics.org.)
As you can see in the diagram, the Arduino pin that connects to JP2-2 will not be exposed to voltages.  (The base of an NPN transistor effectively is at the junction of two back-to-back diodes.)
When the Arduino or ESP pin at JP2-2 is at about 0 V (ie, when the Arduino pin is off) IBE=0; that is, no Q2 base-emitter current will flow; thus, Q2 will be off, so that both of LED1 and relay U1 will remain off.
When the Arduino or ESP pin at JP2-2 is at about 3.3 V (ie, when the Arduino pin is on) IBE is about 2.5 mA, which should be enough to reduce VCE to about 1 V, leaving 4 V across the relay coil, or enough to turn it on.
Note, the 2.5 mA figure for this circuit is calculated as follows:  IBE = (3.3-VBE)/1000 - VBE/10000 = (3.3-0.7)/1000 - 0.7/10000 = .00260 - .00007 = .00253 A = 2.53 mA.  Note that the alternate circuit diagrams linked above don't have a 10KΩ resistor like that in the diagram above, so instead of about 2.5 mA would have about 2.6 mA drive.
If for some reason you don't have quite enough base drive – in which case you might be able to hear a slight click from the relay, even if it doesn't switch – you could increase the "5 V" line into the LED and relay to say 5.5 V or 6 V.  As noted before, the  back-to-back diodes structure of the NPN transistor will isolate that voltage from your Arduino or ESP.

Just to assure the OP - every 5V relay I've used works fine with 3.3v for the "trigger"

Short answer : it will probably work.
If your relay board is opto-isolated, there is a small potential risk that 3V3 may not be enough to lit the optocoupler sufficiently, you will have to test it.
The reddit board is not using optical separation but only a transistor, like on the schematic of the answer above,. In that case, 3V3 is always enough to saturate the transistor. Anything above around 1V5 would probably do, but this can vary according to the resistors, relay consumption and transistor gain.
There is an extensive discussion of this topic at https://www.forward.com.au/pfod/HomeAutomation/OnOffAddRelay/index.html#Mods3v3