text:
TMC26XMotorTester:44: error: 'TMC26XStepper' does not name a type
I am working with a TOS-100 Stepper Driver Shield and am attempting to use the pre-written TMC26XMotorTester/Motor/Serial set of files to make it work.
I unzipped the files, copied the TMC26XStepper folder into the library directory in my Arduino folder, and restarted the Arduino IDE (as well as the Arduino and Driver Shield boards).  I also switched the DIR and STEP pins (6 and 7 swapped to match the wiring on my board).
In the TMC26XMotorTester file, I wrote
    #include <TMC26XStepper.h>

so I'm assuming (given everything I've done), that the functions should be available given this file inclusion.
However, I get the error
    TMC26XMotorTester:44: error: 'TMC26XStepper' does not name a type

along with the complete list of functions from the TMC26XStepper.h/.cpp file that were not identified.
Any thoughts?  I'm using Arduino-Uno version 1.6.9.

Make sure the library folder structure is correct. Inside the TMC26XStepper folder there should be TMC26XStepper.h - If it's in a sub-folder within that it won't work. Some libraries are distributed in folders within zip files, especially some on Github.

It was in the TMC26XMotorTester folder as well as the TMC26XStepper-master folder (the 'master' portion is part of the folder name).  When I open the TMC26XMotorTester.ino file (located in the TMC26XMotorTester folder), all 5 files appear in my sketch (the one I just mentioned, Motor.ino, Serial.ino, TMC26XStepper.h and .cpp).

But I still keep receiving an error.

Sounds like you have a mess in your folder structure. Where did you download it from?

Just the Github file uploaded by the designer.   I don't know why this worked, but I switched my #include <> to #include "TMC26XStepper.h" and it worked, and uploaded.

Here's a good explanation regarding how include works.  Likely, the header file was not in the path the compiler was told to use (that is, your library directories are out of whack) but is in the directory where a source code file included it.

Arduino libraries are normally written as a C++ Class.  When you start a sketch you normally tell the compiler where to find that Class and to Instantiate that class.  If the compiler does not find the Class and you attempt to Instantiate it, the compiler will telly you it does not know what to do.  That is, it will tell you the thing you are using (TMC26XStepper) does not describe anything or is not a Type.
Study the structure of Arduino libraries to make sure what you have installed agrees with the common Arduino library.
Also, newer version of the Arduino IDE can download and unpack libraries automatically given both the IDE and the library are setup to do this.


text:
nodemcu POST request over https return error code -1
I have a nodejs application deployed and have been trying to send data to the api using the following sketch on my nodemcu:

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

void setup() {

Serial.begin(115200);
WiFi.begin("mySSID", "myPassword");

while (WiFi.status() != WL_CONNECTED)

delay(500);
Serial.println("Waiting for connection");

}

void loop() {

if(WiFi.status()== WL_CONNECTED){ //Check WiFi connection status

  HTTPClient http;
  http.begin("https://www.livesessions.host/api/v1/readings" , "cc2707645d0222700161a174671cb8b0258eaa91");
  http.addHeader("Content-Type", "application/json");
  String postMessage = "{'deviceMAC':'ddd eee fff', 'humidity':'99', 'soilTemp':'88'}";
  int httpCode = http.POST(postMessage);
  Serial.print("http result:");
  Serial.println(httpCode);
  http.writeToStream(&Serial);
  String payload = http.getString();
  http.end();

  }else{

    Serial.print("Error in Wifi connection");

}

delay(30000); //Send a request every 30 seconds

}

Although I am able to make data entries using the api and postman, the below code returns -1 (which I think is connection refused), the website is an https site.
Please advise on what I am doing wrong.
Thanks.

supply a WiFiSSLClient object to the HttpClient

@Juraj...Thanks, but can you elaborate with a bit of example code? Would really appreciate it.

see the BasicHttpsClient example

source: Stack Exchange

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

sort: votes


text:
LCD shield submenu
I need to make an app that does various functions regarding IR signals (remote-like)
I need to create a sub menu in order for me to access multiple functionalities.
Arduino-Uno-Menu-Template
I used the link above to create a menu and it works great! The problem is I can not do a sub menu without messing with the loop that display the original one. Any ideas?
This is the code I got so far:
https://pastebin.com/Vh5R2JVp
I'm trying in menuItem1() function to add a routine to create the submenu.
I tried to use a variable that changes when the menu does but it didn't work.

Can you show us the code you've written so far?

The code is the same one as the one from the link I've provided. I just modified the items so it would fit what my menu needs. The link above is a simple template but has no submenus whatsoever. That's what I need !

I added the code !

What you can do (but there are many solutions):

Keep a variable (e.g. subMenu that has the state of the current menu option selected (make this an enum).
Whenever a sub menu is entered, assign the subMenu variable with the current sub menu value.
Use a switch around the current switch statement for first switching subMenu (make different functions for clearity).

So the pseudo code would look like
enum ESubMenu { MainMenu, Page1, Page2 };
ESubMenu subMenu;

void setup()
{
  subMenu =  MainMenu;
}

void loop()
{
   switch (subMenu)
   {
   case MainMenu : showMainMenu() ; break;
   case Page1Menu: showPage1Menu(); break;
   case Page2Menu: showPage2Menu(); break;
   }
}

void showMainMenu()
{
   if (`sub menu 1 selected`)
   {
      subMenu = Page1Menu;
   }
   else if (`sub menu 2 selected')
   {
      subMenu = Page2Menu;
   }
   else
   {
      // Show/handle main menu
   }
}

void ShowPage1()
{
   if `back'
   {
     subMenu = MainMenu;
   }
   else
   {
      // Show/handle page 1 menu options
   }
}

I will try this. I hope I understood the concept. I am new in Arduino

What type should my variable be?

Of type ESubMenu

It didn't work. I think it's probably because of how the loop works

It's not a full code, you have to add code for getting the buttons yourself; also I couldn't test it; it's more like a pseudo code template

I know, I've tried to adapt it to the menu template. For some reason it won't let me come back to the first menu page. I believe it's because of the loop.

If submenu is MainMenu, it should show the main menu, maybe you can add some print statements to print out the value of submenu to see if it has the expected value. Also in a submenu, when going back, make sure to assign MainMenu to subMenu to revert back to the main menu.

Can I show you the code in some way?

Add it to your question (so anybody can respond)

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


text:
Write an array to SD
I'm new to the Arduino and I asked some questions around here and they were really helpful so I'm hoping I will get help once more
#define maxLen 800

volatile  unsigned int irBuffer[maxLen]; //stores timings - volatile because changed by ISR
volatile unsigned int x = 0; //Pointer thru irBuffer - volatile because changed by ISR

void setup() {
  Serial.begin(9600); //change BAUD rate as required
  attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//set up ISR for receiving IR signal
}

void loop() {

  Serial.println(F("Press the button on the remote now - once only"));
  delay(5000); // pause 5 secs
  if (x) { //if a signal is captured
    Serial.println();
    Serial.print(F("Raw: (")); //dump raw header format - for library
    Serial.print((x - 1));
    Serial.print(F(") "));
    detachInterrupt(0);//stop interrupts & capture until finshed here
    for (int i = 1; i < x; i++) { //now dump the times
      if (!(i & 0x1)) Serial.print(F(" "));
      Serial.print(irBuffer[i] - irBuffer[i - 1]);
      Serial.print(F(", "));
    }
    x = 0;
    Serial.println();
    Serial.println();
    attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//re-enable ISR for receiving IR signal
  }

}

void rxIR_Interrupt_Handler() {
  if (x > maxLen) return; //ignore if irBuffer is already full
  irBuffer[x++] = micros(); //just continually record the time-stamp of signal transitions

}

I would like to modify the code above to write to an SD file instead of printing it on the serial port. I've tried to use myFile.write or myFile.print but it won't work. Maybe I am just not that aware of how the SD functions work. Any tips?
This is a function to capture IR signals. I require them for a Arduino remote.
The modified code:
//you may increase this value on Arduinos with greater than 2k SRAM
#define maxLen 800

#include <SPI.h>
#include <SD.h>

File myFile;

volatile  unsigned int irBuffer[maxLen]; //stores timings - volatile because changed by ISR
volatile unsigned int x = 0; //Pointer thru irBuffer - volatile because changed by ISR

void setup() {
  Serial.begin(9600); //change BAUD rate as required
  attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//set up ISR for receiving IR signal
}

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

  Serial.print("Initializing SD card...");

  if (!SD.begin(53)) {
    while (1);
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  Serial.println(F("Press the button on the remote now - once only"));
  delay(5000); // pause 5 secs
  if (x) { //if a signal is captured
    Serial.println();
    myFile.print(F("Raw: (")); //dump raw header format - for library
    myFile.print((x - 1));
    myFile.print(F(") "));
    detachInterrupt(0);//stop interrupts & capture until finshed here
    for (int i = 1; i < x; i++) { //now dump the times
      if (!(i & 0x1)) myFile.write(F(" "));
      myFile.print(irBuffer[i] - irBuffer[i - 1]);
      myFile.print(F(", "));
    }
    x = 0;
    Serial.println();
    Serial.println();
    attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//re-enable ISR for receiving IR signal
  }

}

void rxIR_Interrupt_Handler() {
  if (x > maxLen) return; //ignore if irBuffer is already full
  irBuffer[x++] = micros(); //just continually record the time-stamp of signal transitions

}

How is it not working? What is actually happening? And why don't you include the actual code in question (the SD card code), so that we can search for errors?

The code is in the question. The code is working, it prints to the serial monitor. I just want to modifiy it to 'print' to a file in an SD card.

You wrote, that you already tried to use the SD library to do so. But I cannot see this in your code. We need to see this, so that we can find possible errors in there. We will not simply write the code for you, as we are not a free code writing service. Explain what exactly the problem was, when trying to use the SD library. Otherwise your question is too broad.

file.print() should work exactly the same as Serial.print(). But you have to open the file first. Did you read the documentation of the SD library? The examples? Anything you didn't understand in these docs?

I just used file.print file instead that's why I dind't upload the code. I just need help to see where the problem is, not for someone to write my code. I will add it to the question right away.

You are still missing a description about what is actually happening? Doesn't the file exists after the program ran? Does it contain garbage or wrong values? If yes, what exactly does it contain?

That's the thing, it doesn't contain anything. That's why I wanted to make sure that the file.print() does the same thing. I'll just try to sketch the code in a different way, thanks !

If you never do a myFile.close() the buffered data will never get written to the SD card.

@Majenko that is true! It seem to work now

You are never closing the file.  The SD library (owing to how SD cards work) operates around a 512 byte buffer. Only when that buffer is full, or the library is manually instructed, will that buffer ever get written to the SD card.
The two ways of forcing the buffer to be written to the card are:

Close the file with myFile.close() or
Flush the file with myFile.flush()

Unless you do one of those after storing your data, since you are writing less than 512 bytes, the data will be lost when you power off (or reset) or remove the SD card.


text:
Serial data printing slowly
I have connected an arduino serial port to my PC and monitoring the output in realterm. I am trying to print:
CR
11.98,123,3520,01CRLF
But it is resulting with some delay. First
CR
1
Is printed. After sometime, say 0.25sec, the rest of the data (1.98,123,3520,01CRLF) is received. Finally its shown like
CR
11.98,123,3520,01CRLF
Why is there a delay between CR1 and the rest of the characters when printing using a single serial print!?
Serial.print("\r11.98," +string1+","+string2+",01"\r\n);
string1 & string2 hold data values from 2 separate sensors.

I will receive sensor values and calculate and store them in the names of string1 & string2. Because the data that i am displaying are in diff data types. So i save them as string and display

Please include a full working example, that shows this problem in your question.

Please don't try and concatenate Strings and string literals. It's just nasty. Really nasty. Just print each portion separately.

For your information, i printed each portion separately. Output mid-delay was there. I changed the code as like the post. Still i got the same...  So i need solution alone...

You still did not show a full working example. “Full” = something that defines both setup() and loop() and can be compiled and tested.


text:
Charge lipo battery while using
I have a system that uses Arduino and some modules. The system needs 5v dc power with 3A current at maximum(The system needs 3A current for some seconds every 5 minutes and after that the current will get back to 300-400mA) and on the other side i have a 5v dc charger with 400-500 mA current. So my problem is lack of amperage and i can't run correctly Arduino with 5v dc charger. For solving this problem i want to use a Lipo battery to connect to Arduino but the battery will ran out and i can't get energy from battery so i want to connect the battery to my charger while the Arduino uses the battery, How can i do that? Is there any module to do this work? Can i use TP4056 with protection version to do this work?(Note: I can't change charger)

You really shouldn't charge a lithium battery whilst discharging it. The charger may either never know that it has finished charging and overcharge it, or shut off early and never charge it up properly at all.
Instead you should arrange that your MCU is powered directly from the PSU so that it always has stable power, and feed that same power into a normal charger via some form of electronic switch so it can be turned on and off. The output of the battery can then be fed through another switch into your heavy load.
When it comes time for your load to be activated you switch off the power from the charger and switch on the connection from the battery to the load.
What you use to do the switching is entirely up to you - whether you choose P-channel MOSFETs or relays entirely depends on your situation.
Here's a block diagram to better illustrate it to you:

simulate this circuit – Schematic created using CircuitLab

If i can't charge while discharging so what is load-sharing battery charger circuit(like this https://learn.adafruit.com/adafruit-powerboost-1000c-load-share-usb-charge-boost)?

That is one which will pass the incoming power across to the load when charging (so the incoming power goes to both charging the battery and powering the load) and then switches to the battery to power the load when the incoming power is removed.

Can i use this circuit (https://www.amazon.in/CentIoT-TP4056-lithium-Charging-Protection/dp/B01MV1FAQP)?

That circuit is the single box in the diagram above called "Charger". It is up to you to provide the rest of the circuit.

I think this circuit has battery output and you can use while charging you can see in this video (https://www.youtube.com/watch?v=Qw4psECqpwI).

The critical thing with those circuits is the output current is not from the battery when there is a supply being fed to it. If you feed 400mA you will never be able to exceed 400mA. You don't draw any power from the battery when charging. Ever. It will not do what you want without all the additional components detailed in the block diagram in my answer.


text:
DHT11 sensor reporting all null values
I am using a DHT11 sensor attached to a NodeMCU ESP8266 to have a web server reporting the local humidity and temperature values. I don't have a resistor attached in the circuit, the DHT11 is directly connected to the NodeMCU board. Till yesterday, the setup was giving me correct values, but from today morning, I am getting all nulls from the sensor. Does this mean that the sensor is dead? Should I have had a resistor attached to the circuit to prevent this, or does that not make any difference?
EDIT:
Please consider my question before negative voting me. I considered this question:
Problem with a DHT11 Temperature & Humidity sensor
I have followed the circuit diagram as given in the following page:
https://www.electronicwings.com/nodemcu/dht11-sensor-interfacing-with-nodemcu
It's just that I am using a NodeMCU istead of an Arduino. Does that make my question unworthy of posting here? The problem is similar.

From your question it's not clear if you have the pure (blue) DHT11 sensor or a module with the 4pin sensor mounted on a small pcb with only 3 pins. (The only difference between the sensor and module is that the module will have a filtering capacitor and pull-up resistor inbuilt, and for the sensor, you have to use them externally if required.). Without measuring or swapping with a replacement known to function it's a guessing game.

Hi @LotPings, I have the 4 pin sensor, I have followed the circuit diagram as provided in the following page: https://www.electronicwings.com/nodemcu/dht11-sensor-interfacing-with-nodemcu


text:
Issue with Arduino car bot, the servo motor moves randomly also it turns hot pretty quickly
I trying to create an Arduino avoiding obstacle car. Using Arduino Uno +shield (sensor sheild v5.0). The problem is that when I upload the code, the servo moves randomly (it doesn't rotate to the right) and becomes hot quickly, it is an SG90 with 5v. I have already checked several times and the hardware seems all right.
I have tried to change the angle of the servo, checked the pins several times - uploaded the code many times I have also used serial.prints. researched on the internet.

#include <NewPing.h>        //Ultrasonic sensor function library. You must install this library

//our L298N control pins
const int LeftMotorForward = 5;
const int LeftMotorBackward = 4;
const int RightMotorForward = 1;
const int RightMotorBackward = 0;

//sensor pins
#define trig_pin A1 //analog input 1
#define echo_pin A2 //analog input 2

#define maximum_distance 200
boolean goesForward = false;
int distance = 100;

NewPing sonar(trig_pin, echo_pin, maximum_distance); //sensor function
Servo servo_motor; //our servo name

void setup(){

  pinMode(RightMotorForward, OUTPUT);
  pinMode(LeftMotorForward, OUTPUT);
  pinMode(LeftMotorBackward, OUTPUT);
  pinMode(RightMotorBackward, OUTPUT);

  servo_motor.attach(11); //our servo pin

  servo_motor.write(90);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop(){

  int distanceRight = 0;
  int distanceLeft = 0;
  delay(50);

  if (distance <= 20){
    moveStop();
    delay(300);
    moveBackward();
    delay(400);
    moveStop();
    delay(300);
    distanceRight = lookRight();
    delay(300);
    distanceLeft = lookLeft();
    delay(300);

    if (distance >= distanceLeft){
      turnRight();
      moveStop();
    }
    else{
      turnLeft();
      moveStop();
    }
  }
  else{
    moveForward();
  }
    distance = readPing();
}

int lookRight(){
  servo_motor.write(10);
  delay(500);
  int distance = readPing();
  delay(100);
  servo_motor.write(90);
  return distance;
}

int lookLeft(){
  servo_motor.write(170);
  delay(500);
  int distance = readPing();
  delay(100);
  servo_motor.write(90);
  return distance;
  delay(100);
}

int readPing(){
  delay(70);
  int cm = sonar.ping_cm();
  if (cm==0){
    cm=250;
  }
  return cm;
}

void moveStop(){

  digitalWrite(RightMotorForward, LOW);
  digitalWrite(LeftMotorForward, LOW);
  digitalWrite(RightMotorBackward, LOW);
  digitalWrite(LeftMotorBackward, LOW);
}

void moveForward(){

  if(!goesForward){

    goesForward=true;

    digitalWrite(LeftMotorForward, HIGH);
    digitalWrite(RightMotorForward, HIGH);

    digitalWrite(LeftMotorBackward, LOW);
    digitalWrite(RightMotorBackward, LOW);
  }
}

void moveBackward(){

  goesForward=false;

  digitalWrite(LeftMotorBackward, HIGH);
  digitalWrite(RightMotorBackward, HIGH);

  digitalWrite(LeftMotorForward, LOW);
  digitalWrite(RightMotorForward, LOW);

}

void turnRight(){

  digitalWrite(LeftMotorForward, HIGH);
  digitalWrite(RightMotorBackward, HIGH);

  digitalWrite(LeftMotorBackward, LOW);
  digitalWrite(RightMotorForward, LOW);

  delay(500);

  digitalWrite(LeftMotorForward, HIGH);
  digitalWrite(RightMotorForward, HIGH);

  digitalWrite(LeftMotorBackward, LOW);
  digitalWrite(RightMotorBackward, LOW);

}

void turnLeft(){

  digitalWrite(LeftMotorBackward, HIGH);
  digitalWrite(RightMotorForward, HIGH);

  digitalWrite(LeftMotorForward, LOW);
  digitalWrite(RightMotorBackward, LOW);

  delay(500);

  digitalWrite(LeftMotorForward, HIGH);
  digitalWrite(RightMotorForward, HIGH);

  digitalWrite(LeftMotorBackward, LOW);
  digitalWrite(RightMotorBackward, LOW);
}

Expected to the servo to rotate 90 degrees, but right now the servo is moving randomly.

If the motor gets hot quickly, there is something broken or it is connected wrong. Please show us your circuit. Are you sure about the polarity of the servos supply voltage?

I think you need to do some rigorous testing of the individual functions of your bot.
Step 1: rename your loop function to "loop_temp" which means it won't run, but it will be retained for later.
Step 2: write a new "loop" function, which sets the LeftMotorForward for 1 second, then stop for 1 second.  And observe the results.
Step 3: repeat Step 2 with LeftMotorBackward, RightMotorForward, etc
Step 4: using serial print, experiment with the output from the sonar to make sure it's delivering the expected results.
Step 5: one at a time introduce your functions and ensure they are each working properly.
Step 6: hopefully you've discovered a bug/fault somewhere, and you can re-introduce your original "loop" function.  Otherwise that function may be the issue.
I've had a look at your code, but don't see anything obviously amiss.  So I'm afraid it may be a process of elimination.


text:
Attiny85: how to rotate the servo continuously with a press of a button?
I'm trying to use two Bluetooth commands in my code:
one is press off a button "1" the servo should do its routine without stop
second one press of the a button "2" servo should stop.
What am I getting with my code is button 1 pressed servo is executing the routine only once and then I need to press again. But I want the routine to loop until I'll stop it.
I'm adding here the code:
  #include <SoftSerial.h>
#include <TinyPinChange.h>
#include <SoftRcPulseOut.h>
#define SERVO_PIN         0

#define REFRESH_PERIOD_MS 4

#define NOW               1

int pos = 0;

SoftRcPulseOut myservo;

SoftSerial mySerial(2, 3); // RX, TX
void setup()
{
 // Open serial communications and wait for port to open:
  mySerial.begin(9600);
  pinMode(greenPin, OUTPUT);
  myservo.attach(SERVO_PIN);

}

void loop() // run over and over
{
  char c = mySerial.read();
  if(c == '1')  selfservo();
  if (c == '2') selfservo2();
}

ok the selfservo() is:
void selfservo()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(REFRESH_PERIOD_MS);        // waits 20ms for refresh period
    SoftRcPulseOut::refresh(NOW);    // generates the servo pulse Now
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(REFRESH_PERIOD_MS);        // waits 20ms for for refresh period
    SoftRcPulseOut::refresh(NOW);    // generates the servo pulse Now
  }
}

and selfservo2() is:
void selfservo2()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree

  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {

  }
}

look at your code ... it says if the button IS pressed then move the servo .... change it to if the button WAS pressed then move the servo ... you do that by "remembering" if the button was pressed

@jsotola tell me more please! how should it look like?

separate the receive data function from the act on the data function  .... define a flag variable such as bool move; ... the received data makes the move variable true or false ... do this at the beginning of the loop() block .... later in the loop() block, perform actions depending on the value of move, not on the value of received data ...... it is basically a simple state machine with two states

That's precisely how I would have described it: you need a variable that indicates whether or not the servo should be rotating, toggled by the button(s). (Two buttons seems overkill, but there may be a specific UX need for this.)


text:
Run piece of code based on a feature
I am an engineering student completely new at using Arduino so my following question might be silly but still. I do not think you'll need to get the entire code so I am only going to expose the idea.
So basically, I would like a customer to choose a feature between three of them (let's name them 1, 2, 3). Depending on the feature he chose, the corresponding setup() and the corresponding loop() have to run. For example, if he chooses the second feature, in the main setup(), the setup2() has to run and in the main loop(), the loop2() has to run only. The other setup() functions and loop() functions have to do nothing. I first thought I could do this using switch cases but I am looking for another way to implement that as a teacher told me this method would take too much time.
void setup() {

      setup1(); //only runs if 1st feature chosen
      setup2();
      setup3();
}

void loop() {

      loop1(); //only runs if 1st feature chosen
      loop2();
      loop3();
}

And also, I wrote the three setup() and the three loop() in different files (of course, setup1() is in the same file as a loop1(), etc., ...). Is it possible to include them in the main file (for instance, like <#include nameoffile.h)?

What physical method are you using to determine which feature has been chosen?

@Majenko I'll use a web-based configurator for the customer to chose. Its name is MQTT

So the device will subscribe to an MQTT topic and receive a retained message to get the configuration? I would say you want to implement a Finite State Machine, since the whole "configuration" system is itself another configuration in its own right.

I don’t understand what your teacher is talking about. Seems to me that a switch-case would work just fine.

@Majenko yes that is the idea! I have never heard of a Finite State Machine but I am going to make some research about it.

@Gerben I am going to try this way too then. Just have to figure out how I am going to retrieve the feature chosen by the customer

A Switch-Case usually forms the heart of a Finite State Machine. It's the simplest way of implementing one. https://majenko.co.uk/blog/finite-state-machine

@majenko thanks, I'll give a look to this link! i really thought I could avoid Switch cases thought but I guess I'll have to deal with it

do you really have to call setup after every feature change? or could you just initialize all features at once and just switch what you are using?

@mystery I could indeed Switch the variables i am using!

You probably want to do something like this:
typedef enum { FEATURE1, FEATURE2, FEATURE3 } Feature;

//implement these
Feature getFeatureFromUser(){}
void setup1(){}
void setup2(){}
void setup3(){}
void loop1(){}
void loop2(){}
void loop3(){}

void setup() {
  Feature f = getFeatureFromUser();

  switch (f) {
    case FEATURE1:
      setup1();
      while (true) {
        loop1();
        if (serialEventRun) serialEventRun();
      }
    case FEATURE2:
      setup2();
      while (true) {
        loop2();
        if (serialEventRun) serialEventRun();
      }
    case FEATURE3:
      setup3();
      while (true) {
        loop3();
        if (serialEventRun) serialEventRun();
      }
  }
}

//never reached
void loop() {}

It's good to know that there's no hard rules about how the Arduino functions should be used. Examples like this demonstrate how Arduino's standard requirements of void setup() and void loop() don't quite match every use case.
EDIT: The serialEventRun lines are normally called behind the scenes after each execution of Arduino's normal loop(), so adding them here will result in the standard behavior of serial events

yes that is the idea! thank you very much for helping, this is really helpful! but what do you mean by the void loop() is never reached, why is that? arduino seems much clearer this way

After one of the options in the switch statement matches, and the corresponding setup function is run, the loop# function will be called forever inside a while loop. Therefore it will stay in that loop forever and never reach Arduino's loop() function. The blocks in the switch statement are very similar to how Arduino's setup() and loop() work behind the scenes.

ok that's clear now! thks I'll try this way then

The downside of that method is that it breaks serial event handling. If you don't use serial events, then that's not an issue.

@Majenko i thought about it too as I may have other operations to do. Indeed, after the first Setup(), three others Options setup11(), setup12() and Setup13() with their own Loops should run, depending again on the customer's choice (choice could be 11, 12,13) don't know if that is still clear

@Majenko I also just found an interesting article about Software product line Engineering. If you've heard about it, do you think I could take ideas from this concept?

@Majenko I just updated to add serial event handling

I wish the real world was this simple. The proposed method above requires the total sum of memory resources. If that is available no problem but in most cases the total sum of, for instance, memory for all the global variables is not available. Instead each feature would like to use the memory available, and not need to share with features that are not enabled.

@MikaelPatel The OP wanted to select a feature at runtime. Otherwise this could easily be done with preprocessor defines. The OP didn't mention being memory constrained. Of course there are a multitude of options if one is memory constrained, like dynamically allocating memory (once) when the feature is chosen, storing data in EEPROM, or reusing variables. That's outside the scope of this question.

If the feature selection is not at runtime but is at compile time you could do it like this:
#define FEATURE1 true   // Feature 1 is enabled

void setup() {
    #if FEATURE1
    setup1(); //only runs if 1st feature chosen
    #endif
    setup2();
    setup3();
}

void loop() {
    #if FEATURE1
    loop1(); //only runs if 1st feature chosen
    #endif
    loop2();
    loop3();
}

void setup1(void) {}
void setup2(void) {}
void setup3(void) {}

void loop1(void) {}
void loop2(void) {}
void loop3(void) {}


text:
How to change speed of multiple servos acting at the same time with PCA9685 module?
I'm using the PCA9685 module with its Adafruit library. In my code I have one object of the servodriver class that has 14 channels (controlling 14 servos basically).
void Positioning(){
  ServoDriver.setPWM(right_foot, 0, MapRotation(rotations[0],"1"));
  ServoDriver.setPWM(left_foot, 0, MapRotation(rotations[1],"2"));
  ServoDriver.setPWM(right_calf, 0, MapRotation(rotations[2],"1"));
  ServoDriver.setPWM(left_calf, 0, MapRotation(rotations[3],"2"));
  ServoDriver.setPWM(right_thigh, 0, MapRotation(rotations[4],"1"));
  ServoDriver.setPWM(left_thigh, 0, MapRotation(rotations[5],"2"));
  ServoDriver.setPWM(right_pelvis, 0, MapRotation(rotations[6],"1"));
  ServoDriver.setPWM(left_pelvis, 0, MapRotation(rotations[7],"2"));
  ServoDriver.setPWM(torso, 0, MapRotation(rotations[8], "1"));
  ServoDriver.setPWM(right_shoulder, 0, MapRotation(rotations[9], "1"));
  ServoDriver.setPWM(left_shoulder, 0, MapRotation(rotations[10], "2"));
  ServoDriver.setPWM(right_arm, 0, MapRotation(rotations[11], "1"));
  ServoDriver.setPWM(left_arm, 0, MapRotation(rotations[12], "2"));
  ServoDriver.setPWM(right_hand, 0, MapRotation(rotations[13], "1"));
  ServoDriver.setPWM(left_hand, 0, MapRotation(rotations[14], "2"));
}

All the function positioning does is just set all the servos to a certain position (they're in a humanoid robot and so this position is for standing). The array rotations[] just contains the servo positions from 0 to 180 which is set elsewhere in the code for each servo respectively. The second argument for map rotation just maps it between the servos pulse min and max values (115 and 560) in normal order or reverse depending on number.
My question is how do I change the speed of the servos? I cannot use delay() or loops because wouldn't that cause all the servos to turn sequentially instead of all at once. a change in any rotations[] value indicates the robot is moving and so how do I make the servos slower instead of turning at their fastest to the new rotations[] positions whenever they are changed (as positioning() is called in the loop() function)?

You cannot simply change the speed of a servo. You can only move step my step to the desired position, waiting inbetween. So for example instead of directly moving from 0° to 90°, you can first move to 5°, wait a bit, move to 10°, wait a bit, move to 15°,  wait a bit,... until you reached 90°. You can also go in 1° steps to make it smoother.
You can solve this with delays, but if you want to move the servos at different speeds, you will need a non-blocking coding style like in the BlinkWithoutDelay example of the Arduino IDE (it was described countless times at this site and on the web).
Also, when building a humanoid robot, at some point you will have to consider not only the pose, that you want the robot to reach, but also the way to get there. This can be very important and it can be a complex task. Basically you need formulas for the movements, which return you the exact position for Dach servo at any given time in a movement. Then you can set the servos to this value for the current time.


text:
HTTP PUT method on NodeMCU
I am trying to update values to Firebase. According to Firebase:
curl -X PUT -d '{ "first": "Jack", "last": "Sparrow" }' \
  'https://[PROJECT_ID].firebaseio.com/users/jack/name.json'

We can update using put command. Using curl works fine, but when I look at the header of ESP8266HTTPClient, I don't see any put or patch method there.
I can only see the following:
int GET();
int POST(uint8_t * payload, size_t size);
int POST(String payload);

Whereas in NodeMCU documentation, it is clearly stated it supports the put method too.
http.put(url, headers, body, callback)

http.put() documentation
I cannot find any example.
How can I implement the put method in NodeMCU?

Just because NodeMCU's Lua HTTP library has a PUT method, doesn't mean Arduino's C++ HTTP library has it too.

Also you are only using the NodeMCU board not the firmware, so "implementing the put method in nodemcu" makes no sense.

pardon me if i asked too soon. I found the answer.
all verb are supported. but post and get got their own names.
 int httpCode = http.sendRequest("PUT", String(data));

enven post method implement the sendRequest.

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


text:
Measuring frequency of 3-wire 12V fan on Arduino Uno
I am using a PC 12V fan (40x40mm), which I control speed with voltage (with adjustable power supply). I would like to measure the frequency of the fan with Arduino and read it on serial monitor.
I've googled over some results and I came across pulseIn(), which I don't quite understand. I've also used this code, which I found here, but it doesn't work for me. I've added serial.print and delay line.
My output of this program is: "0000000" etc. and nothing else.
My goal is to set the frequency of the fan to around 50-500 Hz somewhere.
int pin = 7;
unsigned long duration;

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
}

void loop()
{
  duration = pulseIn(pin, HIGH);
  Serial.print(duration);
  delay(1);
}

My schematics:

Edited. I hope it helps. I power supply arduino through USB cable from PC and instead of battery I just use variable bench power supply.

Thanks. Try changing pinMode(pin, INPUT); to pinMode(pin, INPUT_PULLUP); and tell us what happens. If it works, I'll write an answer explaining why.

@MarkSmith: Yes and no. But this is a step further for sure.
Yes: I do get values from arduino, but not some kind of useful.
No: As I raise the voltage (and raise the turning speed) the lower values I get by reading the input. At about 4.85V I got the value of 2800, but at voltage 2.48V I get value of 5740 (about). How can I get RPMs from this?

You should not connect the ground wire to the other side of the potentiometer! That will just waste energy.

The pulseIn measures the duration of a high pulse on the pin.  The reference page explains it as well as I ever could.  If there is a specific thing you don't understand from it, please ask.  However, I don't think it will achieve what you want.
The circuitry in the fan connects the third (yellow?) wire to ground twice per revolution of the fan.  To make this into a "pulse" you need to pull the pin high.  Twice per revolution, the fan will pull it low.
What you now have is a signal which, for every revolution of the fan, goes HIGH, LOW, HIGH, LOW.  We want to measure the time from one rising edge to the next.  This is the time for half a rotation of the fan.
Here's some untested code:
// Wait for signal to go low
while (HIGH==digitalRead(pin)) { /* Do nothing */ }

// Start timing
unsigned long start_time = micros();

// Wait for signal to go high and low again
while (LOW==digitalRead(pin)) { /* Do nothing */ }
while (HIGH==digitalRead(pin)) { /* Do nothing */ }

// Stop timing
unsigned long end_time = micros();

// How long did that take?
unsigned long duration  = end_time - start_time;

That code can be improved in various ways but I hope it will let you understand what's going on.
That tells us how LONG half a cycle takes.  You can easily find how long a whole cycle would take -- double it.  If you want the frequency in revolutions-per-minute, you need to work out how many whole cycles you can get in a minute, which is the same as the number of half-cycles in half a minute:
unsigned long rpm = 30000000L / duration;

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


text:
Arduino Uno + Sim808 GPS dont work with GSM
I am trying to get GPS data and pass it through GSM (Http Get Request). The GPS codes part works fine alone, also HTTPRequest part lonely. But when i use them together , the module don't get GPS data to send with GSM!
I've commented parts for more understanding.
//Include Libraries
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

//Define module connect pins
#define PIN_TX    12
#define PIN_RX    13
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

//store response from website
char buffer[256];

//store Http request
char datas[83];

//store GPS latitude
float lat;

//store GPS longitude
float lon;

//store GPS latitude as text
char la[8];

//store GPS longitude as text
char lo[8];

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

//Temporary for prevent of connection error from network! added now
  delay(2000);
  sim808.close();
  sim808.disconnect();
  sim808.detachGPS();
  delay(2000);

  while(!sim808.init()) {
      Serial.print("Sim808 init error\r\n");
    }
    Serial.println("Sim808 init success");

  //************* Turn on the GPS power************
  if( sim808.attachGPS())
      Serial.println("Open the GPS power success");
  else
      Serial.println("Open the GPS power failure");
 while(!sim808.join(F("mcinet"))) {
      Serial.println("join network error");
  }
  Serial.println("join network success");

  //************ Successful DHCP ****************
  Serial.print("IP Address is ");
  Serial.println(sim808.getIPAddress());

  //*********** Establish a TCP connection ************
  while(!sim808.connect(TCP,"332b8a09.ngrok.io", 80)) {
      Serial.println("Connect error");
  }

}

//this function get latitude and longitude and put them in variable (datas) for http request

void http(float loni, float lati){
    dtostrf(lati, 6, 6, la);
    dtostrf(loni, 6, 6, lo);

    strcpy(datas,"GET /index.php?lat=");
    strcat(datas, la);
    strcat(datas, "&long=");
    strcat(datas, lo);
    strcat(datas," HTTP/1.1\r\nHost: 332b8a09.ngrok.io\r\n\r\n\r\n\r\n");
}

void loop() {
    if(sim808.getGPS()) {
//get GPS data
    lat = sim808.GPSdata.lat;
    lon = sim808.GPSdata.lon;

//send GPS data to http function for put them into http request
    http(lat,lon);

    //*********** Send a GET request *****************
    Serial.println("waiting to fetch...");
    sim808.send(datas, sizeof(datas));
    while (true) {
        int ret = sim808.recv(buffer, sizeof(buffer)-1);
        buffer[ret] = '\0';
        Serial.print("Recv: ");
        Serial.print(ret);
        Serial.print(" bytes: ");
        Serial.println(buffer);
        break;
      }
    }
    delay(3000);
    Serial.println("Another Attemp...");
}

I Use sim808 EVB-V.3.2.4 module and Arduino Uno.
And this is the serial prints of program:
Sim808 init success
Open the GPS power success
join network success
IP Address is
102.168.24.54
Another Attemp...
Another Attemp...
Another Attemp...
Another Attemp...
Another Attemp...
.
.
.
And goes on Infinity Another Attemp...

I must get printed string : "waiting to fetch..." and some other strings before each "Another Attemp..."

thanks. i will do that and will comment the result

well, any of that ways not worked! the gps lat long is 00.00000

start with the GPS example code ... make sure that it works as expected ... then add the GSM code in sections ... test after each addition ... start by adding all of the declarations before setup() .... then add program lines to setup() one at a time .... that should reveal what causes your code to break

Omg this is continuing on not working! step by step, but fail!

what are you doing? .... you don't continue adding code when it fails .... you try to figure out why the added code made it fail ... so, what made the GPS example code fail?


text:
Problem in fetching http get request after put float number
I have this codes that works correctly!
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

#define PIN_TX    7
#define PIN_RX    8
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,
char http_cmd[] = "GET /index.php?lat=*******&long=******* HTTP/1.0\r\n"
                        "Host: 04d1a36d.ngrok.io\r\n"
                        "\r\n";
char buffer[512];

void setup() {
  mySerial.begin(9600);
  Serial.begin(9600);
    while(!sim808.init())
  {
      Serial.print("Sim808 init error\r\n");
      delay(1000);
  }
  Serial.print("Sim808 init Success\r\n");
  delay(3000);

  //*********** Attempt DHCP *******************
  while(!sim808.join(F("cmnet"))) {
      Serial.println("Sim808 join network error");
      delay(2000);
  }

  //************ Successful DHCP ****************
  Serial.print("IP Address is ");
  Serial.println(sim808.getIPAddress());

  //*********** Establish a TCP connection ************
  while(!sim808.connect(TCP,"39c309ae.ngrok.io", 80)) {
      Serial.println("Connect error");
  }
  Serial.println("Connection success");

  //*********** Send a GET request *****************
  Serial.println("waiting to fetch...");
  sim808.send(http_cmd, sizeof(http_cmd)-1);
  while (true) {
      int ret = sim808.recv(buffer, sizeof(buffer)-1);
      if (ret <= 0){
          Serial.println("fetch over...");
          break;
      }
      buffer[ret] = '\0';
      Serial.print("Recv: ");
      Serial.print(ret);
      Serial.print(" bytes: ");
      Serial.println(buffer);
      break;
  }

  //************* Close TCP or UDP connections **********
  sim808.close();

  //*** Disconnect wireless connection, Close Moving Scene *******
  sim808.disconnect();
  delay(5000);
  }
  void loop(){
  }

Actually i want send two numbers instead of ****** in this line:
char http_cmd[] = "GET /index.php?lat=*******&long=******* HTTP/1.0\r\n"
                        "Host: 04d1a36d.ngrok.io\r\n"
                        "\r\n";

to 04d1a642.ngrok.io/index.php for inserting in a database.
but when i use

sprintf

like this:
void setup(){
sprintf( http_cmd, "GET /index.php?lat=%f&long=%f HTTP/1.0\r\n"
                        "Host: 04d1a662.ngrok.io\r\n"
                        "\r\n", 36.423156, 48.526484);
.
.
.

The module doesn't fetch to server for get response!

Don't use sizeof(...), use strlen(...). Also Arduino cannot use floats in sprintf.

@Majenko - so how i can send float numbers as Get request to my server?

You can use dtostrf() to convert from a float to a char array.

? is inserted instead of the float value with sprintf.

print the string to serial ... see if it is valid

I'm not actually professional in arduino and c! can you help ?


text:
Arduino status of bit
Is the a way to check the status of a bit in an arduino Uno?
Like how in Atmel AVR, there is bit_is_clear or bit_is_set

If it's an AVR-based Arduino, you can use bit_is_clear() and bit_is_set().

you can do it in a single line:
bool isSet = (var & (1 << bitNumber)) != 0;

1 << bitNumber is a bit shift in this case it means that the 1 will be multiplied with the power of 2
& is the bitwise AND operator. The each bit of the result is 1 if and only if both the corresponding bits in the inputs is 1.

Arduino defines the function bit(), which makes it easy to do an if:
if (val & bit(5)) { // Is bit 5 set?
    // Do something
} // if

Note that you need to use the bit-and (&) operator, not the Boolean-and (&&) operator.
If you want to check if the bit is clear, you can use the not (!) operator - but then you need parentheses:
if (!(val & bit(5))) { // Is bit 5 not-set (clear)?
    // Do something
} // if


text:
Problem on color mixing lamp on Proteus Arduino starter kit
I set the circuit and couldn't illuminate, where is the problem?

Fritzing: https://fritzing.org/media/fritzing-repo/projects/c/color-mixing-lamp/images/Arduino%20Lamp%20Project.png

you have to run an appropriate sketch in the arduino

I thought my sketch was properly but there is a problem that rgb is not illuminating. i transferred hex code from arduino app, starterkit_basickit. on the book 9green 10red 11blue; a0red, a1green, a2blue, then i think set correctly.

what is the point of asking where the problem is, if you do not provide all of the available information ... determine where the problem occurs ... is it in reading LDRs or is it in lighting the LEDs? .... write a separate sketch to test each part

im not sure about the parts that i use. on arduino, parts were rgb led, 220 ohm resistor, 10k resistor, 3 photoresistor, 3 gel. i used 3 light dependent resistor for "3 photoresistor+3gel" is it correct? if it's correct, RGB should lit, but it doesnt. I'm new about using proteus and arduino. I just need to convert original arduino circuit to proteus. Here is the purpose: https://i.ibb.co/9yVtThk/image.png

just fixed by using TORCH LDR instead of normal ldr. FULLY WORKS.

just fixed by using TORCH LDR instead of normal LDR. FULLY WORKS.


text:
LCD displays weird characters
I have connected the LCD by the 3 wire method using the LiquidCrystal595 library+74HC595 register shift; sometimes "hello world" is displayed but other times the LCD displays weird characters.
How to solve this problem?

do you have a question?

I want to know how to solve this problem  ?

Could be a bad wire, breadboard connector or power issue. Add a capacitor on the power line to the 74595 (VCC/GND). The next step is to check the timing in the library.


text:
Need help in the project "Arduino for audio processing"
I am following this link from Instructables site:
http://www.instructables.com/id/Arduino-Audio-Input/
My question is:
Instead of using the Microphone Radioshack 33-3038, which is listed in the tutorial, can I use https://www.sparkfun.com/products/9964?
Kindly suggest if there any modifications required in other parts for the circuitry, if I go for Electret Microphone.

Oooh, another wonderful Instructable circuit design... shudder

The replacement microphone you link to contains all the circuitry in that instructable*.  You can do away with the op-amp and all the associated stuff, and just connect it direct to the analog input of the Arduino.

*Actually it's better circuitry since they do it right, unlike the Destructable that is a rubbish circuit.

Destructable! Awesome!

@Gerben 90% of what is on Instructables is complete and utter garbage. The other 10% is my comments telling them so ;)

one more query guys,
As sparkfun  Electret microphone has already inbuilt op-amp, So do I need to discard op-amp circuitry in instructable site or  just proceed with op-amp circuitry ?
confirm me.

Discard it. As I said in my answer, connect it direct to an analog input.

Thanks Majenko As you suggested I made a connection to A0 and I can see I was able to get the frequency values as my output, But I can see code is not stable at all, So could you suggest me is there any good reference code or any blog  which can help me out to get the frequency hz values as my output when I connect electret microphone to arduino.

What are you trying to get the frequency of?

Actually, I have one device on which I have to test the frequency of the sound  it generates at different operations like--success,failure..

@ferraro That really doesn't help.  What is the sound?  Most sound is made up of many different frequencies - even a sound that appears to be on one note.

I have builded the circuit as mentioned in instructables, Can see -1hz always as an output in serial, Could somebody help me what could be the reason


text:
Testing an oscilloscope with my Arduino
I bought a very old oscilloscope and although it works, I have my doubts about refreshing the screen (the electron beam fades away very slowly or is not showing up consistently across the screen).
I tested a bit with digitalWrite and anlogWrite, but this only sends either 0 or 5V out. Is there a way to make a preferably sine or triangle wave of 0 to 5V or -5 to +5V... I guess the Arduino should be capable of it, but so far I only get 0V or 5V out, nothing in between.
According to lesson 8 I should get a variable voltage of 0-5V on a pin with analogWrite, but all I get is 0 or 5V.
For what I see:

PWM gives with analogWrite a pulse signal of 0V or 5V with a duty cycle.
non PWM pins give either 0V or 5V (analogWrite of 0-127 appr: 0V, >127: 5V).

You can convert the PWM output of analogWrite() into an (approximate) analog voltage by adding a low-pass filter. That is, a resistor in series followed by a capacitor to ground.
The values to choose depend on the frequency response you want.

RC Filter Calculator (second section).

For anything more complex or accurate you will need a DAC. I often use the MCP4822 SPI DAC chip.

Thank you very much .... it worked, still the scope is very slow (meaning the old signals fade away very slowly), but it works.... guess my scope is 'kind of' usable now.
I only needed to test my oscilloscope so a 'good' DAC is not needed (yet), But I put the component in my wish list for future use :-) ... I already ordered a wave generator IC (8038) for later possible use for my project.

a few ways:
1) you can generate a square wave of a known frequency to test the time base of the scope;
2) you can generate an analog signal to test for the vertical. that can be done via pwm or dds.

Thanks ... a square wave is not really useful since it is not 'moving' vertically enough, so it's a bit hard to see if there is a problem with the scope ... I assume DDS is with the low pass filter as the accepted answer from Majenko.


text:
Arduino Due analog output has 500mV offset
I use a simple serial connection to tell the Due what to output into an analog output pin. However, the outputs are offset about 550mV (as seen on an oscilloscope) and the maximum value of 255 gives ~2.7V. What am I missing? Why can't the DAC output 0V - 3.3V mapped onto 0 - 255 values?
int output = DAC1; // analog output pin
String inData;

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

void loop() {
  while (Serial.available() > 0) {
    char value = Serial.read();
    inData += value;
    if(value == '\n'){
      val = inData.toInt(); // 0..255
      analogWrite(output, val);
      Serial.println(val);
      inData = "";
    }
  }
}

What is the voltage on VDDANA?

how do I check that?

With the black lead of the DMM on ground and the red lead on VDDANA, with the DMM in DC volts mode.

it reads about 4.2V, if by VDDANA you mean Vin pin. I don't know where to measure VDDANA otherwise

The datasheet for the MCU gives its pinout.

From the schematic, VDDANA is pin 73 on the actual chip.

is it a known problem? I am way from card for now, will update as soon as get back to work. If this is known problem, what are approximate solutions/something i can try?

I don't know how old this thread is, anyway I thought it doesn't hurt to give some insight because I experienced the same problem. Look at:
http://www.atmel.com/Images/Atmel-42187-ATSAM3X-and-ATSAM3A-Series-Checklist_AP-Note_AT03462.pdf
page 13: DAC0 and 1 voltage lays between 1/6 ADVREF and 5/6 ADVREF which corresponds to approximately ADVREF=3.2v; Span is (4/6)*3.2 = 2.1v
for periodic signals, Offset can be removed by using a small decoupling capacitor which will act as a high pass filter.
Hope this helps

Thank you for help! Numbers on atmega datasheet do make sense, they are close to what I see on oscilloscope.

int output = DAC1; // analog output pin
String inData;
int val;

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

}

void loop() {
  while (Serial.available() > 0) {
    char value = Serial.read();
    inData += value;
    if(value == '\n'){
      val = inData.toInt(); // 0..255
      val=constrain(val, 543, 2720);
      analogWrite(output, map(val,543,2720, 0, 255));
      Serial.println(val);
      inData = "";
    }
  }
}

Hi and welcome. Please [edit] your answer and provide an explanation as to why your code works. Code only answers are frowned upon. Thanks.


text:
Arduino IDE Based Data Logger - Stops Running
I have created a data logger that writes to a MicroSD on a user defined interval.  The data logger also has the ability to use an xBee unit to transmit the data received to a base station.
This is a link to the code and pictures of the data logger.
I use Arduino IDE for prototyping and coding.  After compiling the code, I use the temp HEX file and upload it to the boards using AVR Studio 4.
The problem I am experiencing is the data loggers will stop running after a random number of recordings.  This can be days or weeks of running before the problem is experienced. This issue rarely occurs when the logger is running in local mode, but occurs often when running with an XBee unit.
A temporary fix I have found for the problem is to add delay(10); before and after the SD card writes.  I do not know why this fixes the problem and would like to find a more appropriate solution.

Do you have any info on the memory foot-print (data, program, etc)? You are using String and that may end up with heap fragmentation.

This use of String is dangerous.  You are growing and shrinking the String in a loop and hoping the memory manager prevents any holes from forming:
void clockResetcheck() {

  char clkset[] = "CLKSET.TXT";
  if  (myFile.open(clkset, O_READ)) {

    uint16_t newYr;
    uint8_t  newDay;
    uint8_t  newMo;
    uint8_t  newHr;
    uint8_t  newMin;
    uint8_t  newSec;
    char data;
    String temp;
    int place = 0;

    while ((data = myFile.read()) > 0) {

    if (data == '/' || data == ':' || data == ',') {
      if (place == 0) {
        newDay = temp.toInt();
        temp = "";
      }
      if (place == 1) {
      newMo = temp.toInt();
      temp = "";
      }
      if (place == 2) {
        newYr = temp.toInt();
        temp = "";
      }
      if (place == 3) {
        newHr = temp.toInt();
        temp = "";
      }
      if (place == 4) {
        newMin = temp.toInt();
        temp = "";
      }
      if (place == 5) {
        newSec = temp.toInt();
        temp = "";
      }
      place++;
      if (place == 6) {
        myFile.close();
        break;
      }
    }
    else {
      temp = temp + data;
    }
  }
...

The line
temp = temp + data

is a danger flag.  This sort of concatenation is going to reallocate the buffer used by String to make it fit the result.  The reallocate will leave behind a hole with the previous smaller string.
String has logic to reuse the buffer if possible.  So if you start big, it should not have to reallocate.  Something like:
String temp("12345678");  // allocates the buffer at largest needed size
temp = ""; // clear out

That is a less likely to fragment memory.  You have a few other concatenates in code that are similar danger.
The best advice to long running programs I ever received:

Stay off the heap.

You are using String inside functions.  That means that buffers are allocated and freed again and again.
A better pattern is to remove all the local String's in functions.  Instead use one global String as a temp buffer.
String g_temp("                        ");
void function1() {
   g_temp = "";
   g_temp += char
}
void functionB() {
   g_temp = "";
   // do stuff with g_temp
}

With this pattern, the allocate happens once when the program starts.  If the size is setup large enough, if will never need to reallocate.  This means your high water mark for memory use is established at the time the program starts.  You don't have to monitor for a week to see if some corner case will run out of memory.


text:
Control brightness of 20 watt street LED light using Arduino
I have searched google and I now know that if we change the resistance, we can change the brightness of an LED, but I was wondering how to change resistance by using a micro controller.

Normally you use PWM instead of messing with resistances. It's easier and more efficient.

There are I2C controlled resistors. But I know none that can handle 20W. Most likely a SSR (Solid State Relay) and PWM'ing would work but I don't know how good idea that is.

High power leds don't use resistors, but have special drivers that regulate the voltage going into the led. With streetlights these drivers also handle the AC-to-DC conversion. It's unlikely you can dim these externally.

There are LED drivers that have external regulation options but as OP asked about changing resistance with a microcontroller the answer would be with a I2C pot, but it's unsuitable for dimming a 20W LED.

Did you do a web search? "arduino pwm high power led driver" gives all the info you may need to answer this.
Here is a nice youtube clip, by Julian Ilett that explains how to do this: 60W High Power LED Driver with PWM #2 - Brightness Control.

Mikael, this is basically a link-only answer. Can you expand on it a bit please in case the link goes down?

The video is by Julian Ilett, who has a rather large collection of tutorials on YouTube, so hopefully the link won't go down.


text:
3.95 MCU Friend Arduino TFT LCD flickering
I got the 3.95" LCD from aliexpress which uses IL9488. I used the MCUFRIEND_kbv library. I am using an Arduino Mega as I need other GPIO to be used for other purposes. I can't use the Uno because of this limitation.
I have other modules like the DS3231, and ESP8266 connected to the Mega and this 3.95" LCD connected as well. ESP8266 is powered separately using a 12-5V converted supply. The Mega is powered using another source. The normal graphics test is working in the LCD. I am able to make it work with the Nano, Uno and Mega. Even for the Mega I am able to write customized messages.
What I intend to do is to update the time in the LCD which is received from the DS3231. It updates the LCD but I see a flickering issue here.
Every update (LCD display function is from the loop which sets the text when there is a second/time/hour difference in the time) seems like it draining more current as the one of the LED connected to Mega dims, the Rx/Tx LEDs also dim.
I am able to get the LCD refreshed but it shows a flickering. I powered the LCD 3.3V and 5V using another separate source but still the small flickering continues.
Moreover all these time I was connected to the Mega through the USB from the laptop. Once I unplug the USB, LCD starts and shows some update and again become white. This continues and an not able to see anything on LCD there after.
I am not sure why only when the Mega is connected to USB this LCD works and that too flickering but once the USB is removed the LCD is not working at all.
Can someone please do help me in this ?

Are you referring to an LCD on a shield, like LCD Display Module TFT 3.95 inch TFT LCD screen for Arduino UNO R3 Board?  Do you have a way to measure the current draw?

Yes, the same thing only I have. But I am supplying a separate 2amp supply to the LCD .And all the grounds are set together.Not sure whether that gonna be an issue. Thanks for the reply.

Do you have a schematic or picture of your connections?

I think something is wrong with this LCD board. This is because in my case the display works sometimes perfectly with the ILI9481 driver but sometimes something hangs and the display starts to flicker. It looks like a chip charging problem. Anyway I solved the flickering problem by tuning the ILI9488 registers. Simply you have to change the initlcd.h for ILI9481 driver in UTFT library.
enter code here

case ILI9481:

LCD_Write_COM(0x11);
delay(70);

LCD_Write_COM(0x38);//Idle Mode OFF
LCD_Write_COM(0x13);//Normal mode

LCD_Write_COM(0x36); // Memory Access Control  crucial
LCD_Write_DATA(0x0A);

LCD_Write_COM(0x55);
LCD_Write_DATA(0x22);//High enhancment of CE ratio

LCD_Write_COM(0xB1);
LCD_Write_DATA(0x70);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xB4);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xB5);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x12);

LCD_Write_COM(0xB6);        // Display Function Control
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x21);       // 0x42 = Rotate display 180 deg.
LCD_Write_DATA(0x3B);

LCD_Write_COM(0xC0);
LCD_Write_DATA(0x1F);//0X1F
LCD_Write_DATA(0x01);//0X10

LCD_Write_COM(0xC1);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xC2);
LCD_Write_DATA(0x00);//0X44 lower better
LCD_Write_COM(0xC4);
LCD_Write_DATA(0x00);//0X10

LCD_Write_COM(0xC5);
LCD_Write_DATA(0x00);//0X10
LCD_Write_DATA(0x80);//optimum
LCD_Write_DATA(0x80);//0X10

LCD_Write_COM(0x3A);//Interface Pixel Format
LCD_Write_DATA(0x55);

LCD_Write_COM(0x2A);//Column Address Set
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x01);
LCD_Write_DATA(0xDF);//320

LCD_Write_COM(0x2B);//Page Address Set
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x01);
LCD_Write_DATA(0x3F);//480

delay(60);

LCD_Write_COM(0x29);//Display ON
delay(30);

LCD_Write_COM(0x2C);//Memory Write
delay(30);
break;


text:
Arduino stops sending/receiving data over Serialport after random time
I got a C# WPF application wich communcates with my arduino uno over serial port. Everything works fine for 3 to 20 seconds then i can not send or receive anything from/to the arduino.
What im trying to archieve:
 Connected a arduino uno to an optical sensor of a mouse to read from its registers, now i want to process the data on my pc.
I tried using another arduino uno and also some other mouse optical sensor, wich did not change anything.
Opening and closing the serialport after each communication did not work for me.
I have seen a few questions here on stack exchange, i looked through everyone but they could not help me.
 Serial.flush() seems to be not working, or its some kind of overflow i cant figure out.
I would really appreciate it if someone could explain me what the root of this problem is.
For completeness, here is my C# code:
 public class SerialCommunication
    {
        public SerialPort serialPort = new SerialPort();

        public SerialCommunication()
        {
            string[] ports = SerialPort.GetPortNames();
            if (ports.Count() == 1)
            {
                MessageBox.Show("No serialport is available");
                return;
            }
            serialPort.PortName = ports[1];
            serialPort.BaudRate = 115200;
            serialPort.Parity = Parity.None;
            serialPort.DataBits = 8;
            serialPort.Handshake = Handshake.None;
            serialPort.StopBits = StopBits.One;
            serialPort.NewLine = "\r\n";
            serialPort.WriteTimeout = 2000;
            serialPort.ReadTimeout = -1;

            serialPort.Open();
        }
    }

public partial class MainWindow : Window
    {
        public static readonly object _lock = new object();

        private SerialCommunication serialCommunication = new SerialCommunication();

        public MainWindow()
        {
            InitializeComponent();
            GetWindow(this).KeyDown += HandelKeyDown;

            serialCommunication.serialPort.DataReceived += (sender, args) =>
            {
                string bufferstring = ((SerialPort)sender).ReadLine();
                OnMessageReceived(bufferstring);
                //serialCommunication.serialPort.DiscardOutBuffer();
                //serialCommunication.serialPort.DiscardInBuffer();
                //Thread.Sleep(3);
                //byte[] buffer = new byte[15];
                //((SerialPort)sender).Read(buffer, 0, buffer.Length);
                //string bufferstring = Encoding.UTF8.GetString(buffer);
            };
            serialCommunication.serialPort.WriteLine("OK");
        }

        private void OnMessageReceived(string message)
        {
            if (message.Length != 15 || message.Contains('O') || message.Contains('K') || message.Contains('\n') || message.Contains('\r'))
            {
                serialCommunication.serialPort.DiscardInBuffer();
                serialCommunication.serialPort.DiscardOutBuffer();
                serialCommunication.serialPort.WriteLine("OK");
                return;
            }

            //Format: "y: 0x%02X,x: 0x%02X"
            string x = message.Substring(3, 4);
            string y = message.Substring(11, 4);

            int offsetX = (Convert.ToInt32(x, 16) - 128);
            int offsetY = (Convert.ToInt32(y, 16) - 128);

            // the next three lines only visualize the received data but do not change it
            MoveX(offsetX / 50);
            MoveY(offsetY / 50);
            ShowMessage(message);
            Thread.Sleep(2);
            serialCommunication.serialPort.WriteLine("OK");
        }
}

Foto of how the application and data it receives look like:

Here is my arduino code:
#include <Arduino.h>

// 5v
#define POWER 13
// Serial I/O
#define SDIO 11
// Serial clock
#define SCK 12

// Registers
#define DELTAY 0x02
#define DELTAX 0x03

#define serialInputBufferSize 16
char dataBuffer[serialInputBufferSize];
unsigned short inputBufferLength = 0;

bool sendPosition = true;

char tmp[16];

void InitMouse()
{
  digitalWrite(SCK, HIGH);
  delayMicroseconds(5);
  digitalWrite(SCK, LOW);
  delayMicroseconds(1);
  digitalWrite(SCK, HIGH);

  // Wait for the serial transaction timer to time out:
  delay(1000);
}

byte readRegister(byte addr)
{
  byte r = 0;

  // Set the dataline to output
  pinMode(SDIO, OUTPUT);
  for (int i = 7; i >= 0; i--)
  {
    digitalWrite(SCK, LOW);
    digitalWrite(SDIO, addr & (1 << i));
    digitalWrite(SCK, HIGH);
  }

  // Switch the dataline from output to input
  pinMode(SDIO, INPUT);
  // The datasheet mentions to wait at least 100 µsec
  // when switching from write to read operations.
  // This is needed for the chip to prepare the data
  delayMicroseconds(110);

  // Clock trough the register and read its data
  for (int i = 7; i >= 0; i--)
  {
    digitalWrite(SCK, LOW);
    digitalWrite(SCK, HIGH);
    r |= (digitalRead(SDIO) << i);
  }

  // Delay at the end guarantees >100 µsec before next transaction
  delayMicroseconds(110);

  return r;
}

byte y = 0;
byte x = 0;

void WaitForMovementThenSendPositionOffset()
{
  x = 0;
  y = 0;

  while (((y == 0 && x == 0) || x == NULL || y == NULL) && sendPosition)
  {
    delay(1); // kann eigentlich weg
    y = readRegister(DELTAY);
    x = readRegister(DELTAX);
  }

  if (sprintf(tmp, "y: 0x%02X,x: 0x%02X", y, x) > 0)
  {
    tmp[16] = 0;
    if (!Serial.println(tmp))
    {
      // Serial.end();
      // Serial.begin(9600);
      // Serial.begin(115200);
      Serial.flush();
    }

    sendPosition = false;
  }
}

void serialEvent()
{
  sendPosition = false;

  // Read serial data into the buffer
  while (Serial.available())
  {
    dataBuffer[inputBufferLength++] = Serial.read();
  }

  Serial.flush();

  if (strstr(dataBuffer, "OK"))
  {
    sendPosition = true;
    WaitForMovementThenSendPositionOffset();
  }
}

void setup()
{
  pinMode(SCK, OUTPUT);
  pinMode(SDIO, INPUT);
  pinMode(POWER, OUTPUT);

  digitalWrite(POWER, HIGH);

  Serial.setTimeout(1000);
  // Serial.begin(9600);
  Serial.begin(115200);

  InitMouse();
}

void loop()
{
}

what troubleshooting have you done?

@jsotola as mentioned above: I tried using another arduino uno and also some other mouse optical sensor, wich did not change anything. Opening and closing the serialport after each communication did not work for me. I have seen a few questions here on stack exchange, i looked through everyone but they could not help me.
I also tried around with delay() and other useless stuff for 2 days now

start with basics ... lower the baud rate ... use a simple Arduino sketch that sends repeatedly "ABC123" one character at a time with a short pause in between characters ... observe the result on the C# side of the connection

@jsotola i tried baudrate 9600 wich did not help, on the c# side i get the results i want. I will add a foto of how my wpf application looks like and the data it receives, but thank you

you need to modify the arduino sketch to the minium code that still exhibits the undesired behavior ... that is why i said to start by sending ABC123 and see if it still happens

@jsotola ok i try it with "ABC123"

The problem was in the serialEvent() method. I did not rest the bufferindex where i red the received message so it allways stayed there until the arduino ran out of memory and also i did not gave the arduino enough time to receive the message so i added delay(1) there.
Here is my updated code:
void serialEvent()
{
  inputBufferLength = 0;
  sendPosition = false;
  delay(1);
  // Read serial data into the buffer
  while (Serial.available())
  {
    if (inputBufferLength < serialInputBufferSize)
    {
      dataBuffer[inputBufferLength++] = Serial.read();
    }
    else
    {
      Serial.read();
    }
  }

  Serial.flush();

  if (strstr(dataBuffer, "OK"))
  {
    sendPosition = true;
    WaitForMovementThenSendPositionOffset();
  }
}

Every time you receives data, it tries to read a full line (SerialPort.ReadLine()).
If there's not a full line available, it will block the current thread until there is or until it times out.
These calls will stack up and eventually cause the application to fail.

If i restart the c# application, it still does not work. I have to restart the arduino, then it works again. I think problem is on the arduino side, but i give it a try and use a buffer with SerialPort.Read() instead.


text:
Alternative to delay() when using Ticker in ESP8622
When using the Ticker library on the ESP8266 you can't use the delay() function because Ticker functions are using the underlying timer. The original Arduino library says that you can use a Ticker as delay, but in the ESP8266 implementation things work differently. You "attach()" a callback function and specify the period.
How can I generate a delay that doesn't require the underlying timer?
(BTW, where is the documentation for the ESP8266 Ticker library? The repository has no documentation nor comments on the functions.)

use the ticker callback to increment a value. this value can be used as millis() substitute. actually the "millis" is made that way.
write a simple function to give you a delay. this code assumes the callback function is interrupt/event driven like a systick timer in ARMs.
uint32_t ticks;

void callbackFunc()
{
   ticks++;
}

void myDelay(uint32_t del)
{
   uint32_t tempTime = ticks;
   while (ticks < tempTime + del);
}

Yes. That seems to work, but I do need to put ESP.wdtFeed(); inside the while loop in the delay function. Otherwise the watchdog timer is triggered.


text:
pin change interrupt on arduino Due
Greeting! I am finding it difficult setting up a pin change interrupt on an arm board ( I am using Arduino due). I found a sample online which I have used but I discovered that when ever an interrupt occurs on a particular pin, it tends to pick up noise from other pins (i.e it prints the state of other pins which didn't get an interrupt) even after appropriate de-bouncing of the signal. For that reason it is quite difficult to carry out appropriate decision with the result am getting. Please I need a code example on how to set of pin change interrupt on Arduino Due for me to continue with my final year project. its very urgent, thanks in anticipation.
Code as Follows:
#include <ArduinoJson.h>
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

#define DEBOUNCE_TIME 50L

#define interruptPin3 3
//#define interruptPin4 4

byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(172, 168, 1, XXX);
IPAddress server(172, 168, 1, XXX);

EthernetClient ethClient;
PubSubClient mqttClient(ethClient);

char data2[700];
void reconnect() {
  // Loop until we're reconnected
    while (!mqttClient.connected())
    {
   SerialUSB.println("Attempting MQTT connection...");

    if (mqttClient.connect("arduinoClient")) {
       SerialUSB.println("Now connected!");
    } else {
      SerialUSB.println("Failed! Please wait for reconnection ...");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

//ISR Flags
volatile bool ISR_DEACTIVATED = false;
volatile bool display_int_time = false;

bool debounce_started = false;
unsigned long Isr_debounce_pin_timer;

volatile bool initializationFlag = false;
volatile bool pinVoltStatus = HIGH;
volatile bool lastVoltStatus=LOW;
String pinStatusValue="HIGH";

volatile int interruptPinDigitalPin;

void PinsInitialization() {

  pinMode(interruptPin3, INPUT);
  attachInterrupt(digitalPinToInterrupt(interruptPin3), Pin3ChangeInterrupt, CHANGE);
}

void setup()
{
  SerialUSB.begin(9600);
  while (!SerialUSB) continue;
  mqttClient.setServer(server, 11883);

  Ethernet.begin(mac, ip);
  // Allow the hardware to sort itself out
  delay(1500);
  reconnect();

  ISR_DEACTIVATED = false;
  display_int_time = false;
  initializationFlag = false;

  PinsInitialization();
}

void getPinStatus()
{
   bool pinStatus;
    pinStatus = digitalRead(interruptPinDigitalPin);
    if(pinStatus == LOW)
    {
      pinStatusValue = "LOW";
      pinVoltStatus = LOW;
    }else{
      pinStatusValue = "HIGH";
      pinVoltStatus = HIGH;
    }
}

void Pin3ChangeInterrupt()
{
  if(!ISR_DEACTIVATED)
  {
    interruptPinDigitalPin = interruptPin3;
    ISR_DEACTIVATED = true;
    display_int_time = true;
  }
}

//Returns TRUE if pin is stable at desired state, FALSE if bouncing or other state
bool debounce(const int debounce_pin, const bool state, unsigned long &state_latch_start)
{
  static bool current_state;

  // Read the required pin
  current_state = digitalRead(interruptPinDigitalPin);

  if ((!debounce_started) && (current_state == state)) {

      state_latch_start = millis();
      debounce_started = true;
  }

  if (debounce_started && (current_state != state))

      debounce_started = false;

  if (debounce_started && (current_state == state) && (((unsigned long)(millis() - state_latch_start)) >= DEBOUNCE_TIME))
  {
    debounce_started = false;
    // report back that all is goood.
    return(true);
  }

  //Either the pin is at the wrong level, or is still bouncing. Try again later!
  return(false);
}

void messageToPublish(String digitalPinNumber, String voltageStatus)
{
  StaticJsonDocument<200> doc;

    doc["digitalPin"] = digitalPinNumber;
    doc["voltStatus"] = voltageStatus;

    String payload = doc.as<String>();
    payload.toCharArray(data2, (payload.length() + 1));
    mqttClient.publish("interruptTopic", data2);
    SerialUSB.println((String)digitalPinNumber+ ":"+(String) voltageStatus);
}

void loop()
{
  //This runs every time an interrupt occurs
  if (display_int_time)
  {
    detachInterrupt(interruptPinDigitalPin);
    //Done with interrupt stuff. Clear the interrupt flag
    getPinStatus();
  }

   //Debounce for the ISR routine in main loop
    if (ISR_DEACTIVATED)
    {//Wait until the pin settles LOW to reactivate the ISR
      bool debounceStatus = debounce(interruptPinDigitalPin, pinVoltStatus, Isr_debounce_pin_timer);
      if(debounceStatus)
      {
        if (initializationFlag == false)
        {
          ISR_DEACTIVATED = false;
          initializationFlag = true;
        }else
        {

           if(interruptPinDigitalPin == interruptPin3)
          {
            attachInterrupt(digitalPinToInterrupt(interruptPin3), Pin3ChangeInterrupt, CHANGE);
            messageToPublish("Pin3", pinStatusValue);
          }
          display_int_time = false;
          ISR_DEACTIVATED = false;
        }
      }

    }
}

I haven't worked with the Due yet, but on other Arduinos you can deactivate the pin change interrupt for the pins, that you don't need, by setting a mask register. Please post the code, that is showing this problem

@chrisl Thanks alot for your prompt response, am actually just a beginner with arduino and programming at large. Here is the updated question with my code attached

@chrisl can you kindly share a code example on how to achieve that on other arduino boards (AVR am guessing).


text:
WiFi connection in loop function
What I am trying to do is while connected locally in the esp8266 and give it a ssid and password, save them in a global variable and use them to start a connection inside loop function with a flag so it happens only once and let the program run while I check when the connection is complete. Do you foresee any problems with this application?:
setup(){
    wifi.mode(WIFI_AP_STA);
    setup softAP
    server.on("/",handleroot)
    server.begin()
}
loop(){
    server.handleClient()
    if(credential_submited){
        Wifi.begin(credentials);
        flag_connection_started =true;
        credential_submited = false;
        flag_for_internet_server=true;
    }
    if(WiFi.status()==WL_CONNECTED && flag_for_internet_server==true){
        server.on("/",handleroot)
        server.begin()
        flag_for_internet_server=false;
    }

I know there is also WifiManager But I am trying to do it on my own. The thing is some wifi networks take a lot of time to connect. More precisely they connect but then the esp doesn't get an ip and disconnects.
Thank you for your time

Is the esp in access point or in station mode? Probably it's possible, but I don't really understand the scenario. You could make it clearer by at least providing some pseudo code

Don't see problems there, since this is somewhat standard. Have you tried anything?

Take a look at https://github.com/tzapu/WiFiManager it does exactly what you want.

@Dougie I am trying to create it on my own to learn mostly.

WiFi.begin() in ESP8266WiFi library doesn't wait until the connection completes, it returns immediately.
You can check if the connection to WiFi network is established using WiFi.status() as most of the examples show. And it is not mandatory to wait for the connection in setup().
BTW: You can use a separate sketch to set the SSID and password in esp8266 and then in all other sketches not use WiFi.begin(), only wait for the connection to WiFi network to finish.

Could you elaborate on the separate sketch part. You mean that I can upload two sketches on the eps and run one at the time and when the one is finished run the second program?

no. you run the configuration sketch and the esp8266 remembers the ssid and password. any other sketch uploaded after that will use this settings. the esp8266 will connect automatically even if you upload Blink

This is not a big deal...
You can do it vary easily, the most simple way is that you can use EEPROM to achieve this..
Simply pass the SSID and PASSWORD of new network to ESP8266 and save it in EEPROM and also create a new variable in eeprom that store the status that new network credentials is entered or not and check it in loop and then fetch new network credentials from the EEPROM and try to connect to it...
You can also check and connect to your desired network from the loop...
Or alternatively you can use the library that can help you in doing that [WiFiManager]: https://github.com/tzapu/WiFiManager

ESP8266 doesn't have an EEPROM but stores the SSID and password in flash automatically if you don't disable this feature. that is what WiFiManager utilizes


text:
analogWrite and For Loop Bug
I wrote the following code that outputs a packet data structure bit by bit.
I do this using two for loops. These two for loops should always terminate, but the presence of analogWrite() makes them not terminate.
More concretely:
#define PACKET_SIZE 2
#define NUM_BITS 8

#define LOGICAL_LOW 127
#define LOGICAL_HIGH 255
#define LOGICAL_NULL 0

#define DATA_OUT_PIN 13
#define DATA_IN_PIN 3

#define DELAY 200

struct packet {
  byte content[PACKET_SIZE];
  byte checksum;
};
void testFun(struct packet *p) {
  for (int i = 0; i < PACKET_SIZE; i++) {
    byte m = 1;
    for (int j = 0; j < NUM_BITS; j++) {
      Serial.println(i);
      if ((p->content[i] & m) == m) {
        analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
      }
      else {
        analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
      }
      m <<= 1;
    }
    Serial.println(i);
  }
  Serial.println("Other loop");
  for (int i = 0; i < NUM_BITS; i++) {
    byte m = 1;
    if ((p->checksum & m) == m) {
      analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
    }
    else {
      analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
    }
    Serial.println(i);
  }
  analogWrite(DATA_OUT_PIN, LOGICAL_NULL);
}
void setup() {
  Serial.begin(115200);
  pinMode(DATA_OUT_PIN, OUTPUT);
  pinMode(DATA_IN_PIN, INPUT);

  struct packet p;
  p.content[0] = 127;
  p.content[1] = 98;

  delay(3000);
  testFun(&p);

}

loops forever but this one doesn't:
#define PACKET_SIZE 2
#define NUM_BITS 8

#define LOGICAL_LOW 127
#define LOGICAL_HIGH 255
#define LOGICAL_NULL 0

#define DATA_OUT_PIN 13
#define DATA_IN_PIN 3

#define DELAY 200

struct packet {
  byte content[PACKET_SIZE];
  byte checksum;
};
void testFun(struct packet *p) {
  for (int i = 0; i < PACKET_SIZE; i++) {
    byte m = 1;
    for (int j = 0; j < NUM_BITS; j++) {
      Serial.println(i);
      if ((p->content[i] & m) == m) {
        analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
      }
      else {
        analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
      }
      m <<= 1;
    }
    Serial.println(i);
  }
  Serial.println("Other loop");
  for (int i = 0; i < NUM_BITS; i++) {
    byte m = 1;
    if ((p->checksum & m) == m) {
      analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
    }
    else {
      //analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
    }
    Serial.println(i);
  }
  analogWrite(DATA_OUT_PIN, LOGICAL_NULL);
}
void setup() {
  Serial.begin(115200);
  pinMode(DATA_OUT_PIN, OUTPUT);
  pinMode(DATA_IN_PIN, INPUT);

  struct packet p;
  p.content[0] = 127;
  p.content[1] = 98;

  delay(3000);
  testFun(&p);

}

the difference between these two being a single commented line in testFun
My entire sketch is as follows:
#define PACKET_SIZE 2
#define NUM_BITS 8

#define LOGICAL_LOW 127
#define LOGICAL_HIGH 255
#define LOGICAL_NULL 0

#define DATA_OUT_PIN 13
#define DATA_IN_PIN 3

#define DELAY 200

struct packet {
  byte content[PACKET_SIZE];
  byte checksum;
};
void testFun(struct packet *p) {
  for (int i = 0; i < PACKET_SIZE; i++) {
    byte m = 1;
    for (int j = 0; j < NUM_BITS; j++) {
      Serial.println(i);
      if ((p->content[i] & m) == m) {
        analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
      }
      else {
        analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
      }
      m <<= 1;
    }
    Serial.println(i);
  }
  Serial.println("Other loop");
  for (int i = 0; i < NUM_BITS; i++) {
    byte m = 1;
    if ((p->checksum & m) == m) {
      analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
    }
    else {
      analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
    }
    Serial.println(i);
  }
  analogWrite(DATA_OUT_PIN, LOGICAL_NULL);
}

void setup() {
  Serial.begin(115200);
  pinMode(DATA_OUT_PIN, OUTPUT);
  pinMode(DATA_IN_PIN, INPUT);

  struct packet p;
  p.content[0] = 127;
  p.content[1] = 98;

  delay(3000);
  testFun(&p);

}

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

}

and its two outputs are
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
Other loop
0
1
2
3
4
5
6
7
and
0
0
0
...

Please provide also a sample serial output, since this seems to be where you sense, that the loop goes on indefinitely. Is the loop() function empty? You didn't provide it. I don't see a obvious reason, why there should be an infinite loop, but I also don't see, why this should work. You don't wait for the signal to be outputted on the pin. You restart PWM so fast, that it cannot really do a cycle. You have to wait a bit, otherwise the code will be executed way too fast

The loop function is empty. The serial output for the first snippet is always 0 (implying i is never incremented) while that for the second loop is what you would expect  and prints out “Other loop”. I tried adding a one second delay to prevent what you mentioned, and that didn’t work.

I loaded both codes (with an empty loop) on a Nano and they both worked identically.  The behavior where one seemingly unrelated line completely changes the program is often due to undefined behavior at a completely separate point in the program.  It can be really hard to find.  Please post the complete program that will exhibit the problem.  The error may be somewhere completely unrelated to this code.

Just added the entire sketch. Its pretty much identical to the first two snippets I gave. I also added the exact output I get on an Arduino Mega 2560

I get the same output as you, but only once. A bunch of 0s, a bunch of 1s, "other loop" and 0-7 - then it stops. Your code is fine.

What output did you actually expect?! The provided output is what I would expect from looking at your code...


text:
Control 12V power with 3 transitors to 3 seperate consumers
I have this shematic. With one electrical Pump and two solenoid valves I want to control via the arduino.
Here are the specs for the parts:

Pump: 12V max. 250mA
Valve 1: 12V max. 160mA
Valve 2: 12V max 220mA
Source: 12V max 2A

simulate this circuit – Schematic created using CircuitLab
My questions is:
Are the 4.7k resistors enough?
Do I need different resistors for the different consumers?
And I am using S8050 as transistors. Are they to small for the load?
And where do I have to connect the ground of the arduino to?

I think you mean S8050 as transistors and in the circuit I see 2N3904's

Thanks. I corrected it.

Connect the Arduino Gnd to the 12V supply Gnd.  From what I see here, https://www.digikey.com/products/en/discrete-semiconductor-products/transistors-bipolar-bjt-single/276?k=S8050 most S8050 parts need 80mA or more to turn into saturation - which is more than an Arduino can supply.  You'd be better off with N-Channel MOSFET, which takes little drive current, and with low Rds will have little voltage across the  Drain-Source.
Example: https://www.digikey.com/products/en/discrete-semiconductor-products/transistors-fets-mosfets-single/278?k=aod5

(5v/4700r) * 100hfe = 0.106A; not enough current for any of them. Try a 330R: good for 1.5A (or still 600ma at the worst-case 40hfe), while only pulling 15ma from the MCU. You can go up to 680r...