message:
Why are my motors attached to an Arduino MEGA not running?

[![enter image description here][1]][1][![enter image description here][2]][2][![enter image description here][3]][3][![enter image description here][4]][4][![enter image description here][5]][5]I verified my code and uploaded it to the board and that was successful.

Info:
  - Using Mega 2560 Arduino Board with Adafruit V1
  - 3 DC 12 volt motors
  - on HP computer

Here is my code:

    #include <AFMotor.h>

    AF_DCMotor motor(1, MOTOR12_8KHZ);
    AF_DCMotor motor2(2, MOTOR12_8KHZ);
    AF_DCMotor motor3(2, MOTOR12_1KHZ);

    void setup()  {
      Serial.begin(9600);
      Serial.println("Motor Test!");
      motor.setSpeed(20); //set speed of motor
      motor2.setSpeed(20); //set speed of motor
      motor3.setSpeed(25); //set speed of motor
    }

    void loop() {
      Serial.print("tick");
      motor.run(FORWARD);
      delay(2000);

      Serial.print("tock");
      motor.run(RELEASE);
      delay(5000);

      Serial.print("tack"); //first song starts
      motor.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor.run(RELEASE);
      delay(14000);

      Serial.print("tack");
      motor.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //first song ends
      motor.run(RELEASE);
      delay(13000);

      Serial.print("tick");
      motor.run(FORWARD);
      delay(2000);

      Serial.print("tock"); //second song starts
      motor.run(RELEASE);
      delay(24000);

      Serial.print("tick");
      motor.run(FORWARD);
      delay(2000);

      Serial.print("tock"); //second song ends
      motor.run(RELEASE);
      delay(17000);

       Serial.print("tick");
      motor.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //third song starts
      motor.run(RELEASE);
      delay(23000);

      Serial.print("tick");
      motor.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //third song ends
      motor.run(RELEASE);
      delay(21000);

      Serial.print("tick");
      motor.run(FORWARD);
      delay(2000);

      Serial.print("tock");
      motor.run(RELEASE);
      delay(5000);

      Serial.print("tick");
      motor.run(FORWARD);
      delay(3000);

      Serial.print("tack"); //fourth song starts
      motor.run(RELEASE);
      delay(5000);

      Serial.print("tack");
      motor.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //fourth song ends
      motor.run(RELEASE);
      delay(21000);
       //waving motor
      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(5000);

      //Waving motor
      Serial.print("tick"); //first song starts
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

       Serial.print("tock");
      motor2.run(FORWARD);
      delay(1000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //first song ends
      motor2.run(RELEASE);
      delay(14000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(5000);

      Serial.print("tack"); //SEcond song starts
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

       Serial.print("tock");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //second song ends
      motor2.run(RELEASE);
      delay(15000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(5000);

      Serial.print("tack"); //Third song starts
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

       Serial.print("tock");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tock"); //third song ends
      motor2.run(RELEASE);
      delay(14000);

      Serial.print("tick"); //fourth song starts
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

       Serial.print("tock");
      motor2.run(FORWARD);
      delay(1000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //fourth song ends
      motor2.run(RELEASE);
      delay(7000);

      //dancing motor
      Serial.print("tock"); //first song starts
      motor3.run(RELEASE);
      delay(11000);

      Serial.print("tick");
      motor3.run(FORWARD);
      delay(22000);

      Serial.print("tock"); //first song stops //second song starts
      motor3.run(RELEASE);
      delay(16000);

        Serial.print("tick"); //Second song stops
      motor3.run(FORWARD);
      delay(28000);

      Serial.print("tock"); //Third song starts
      motor3.run(RELEASE);
      delay(15000);

      Serial.print("tick"); //Third song stops
      motor3.run(FORWARD);
      delay(33000);

      Serial.print("tock"); //fourth song starts
      motor3.run(RELEASE);
      delay(16000);

      Serial.print("tick");
      motor3.run(FORWARD);
      delay(5000);

      Serial.print("tock");
      motor3.run(RELEASE);
      delay(1000);

      Serial.print("tick"); //fourth song ends
      motor3.run(FORWARD);
      delay(16000);

      Serial.print("tock");
      motor3.run(RELEASE);
      delay(5000);
    }

  [1]: https://i.stack.imgur.com/M3e0o.jpg
  [2]: https://i.stack.imgur.com/aAU02.jpg
  [3]: https://i.stack.imgur.com/sk6xd.jpg
  [4]: https://i.stack.imgur.com/Y8ZEO.jpg
  [5]: https://i.stack.imgur.com/k7WQg.jpg

body:
As you did not give details I assume the following:

  - You supply the MEGA via USB or external 5-12V power supply
  - the motors are supplied via an extra external 12V power supply with sufficiant amperage
  - All cabeling is checked and correct

Looks like this schematic (without 12V power supply attached to the motor shield)
[![AF_motor_shield_v1][1]][1]
[![AF_Motor_shield_v2][2]][2]

To your code:

  -  Get rid of the delay()s - they block processing so what happens:

         motor.run(FORWARD);  // => You give a command via lib
         delay(2000); // You stop your processing so the motor is not running

so you have two options both need the definition of a timeStamp var

  - working with a (blocking) while loops
  - or creating a finite state machine (search here on SO for details)

So I will for simplicity use the first approach

     // Copy this var before your setup
     unsigned long timeStamp = 0;
    // use your complete setup
     void setup(){...}
     // Change your loop functions like thes first three converted lines
     void loop(){
      timeStamp = millis();
      Serial.print("tick");
      while(millis()-timeStamp < 2000){
         motor.run(FORWARD);
      }
      timeStamp = millis();   // resets the time to current
      Serial.print("tock");
      while(millis()-timeStamp < 5000){
         motor.run(RELEASE);
      }
      timeStamp = millis();   // resets the time to current
      Serial.print("tack"); //first song starts
      while(millis()-timeStamp < 2000){
         motor.run(BACKWARD);
      }
    // .... AND SO ON .....
    }

Be aware that the whiles are blocking but for your sequential processing its ok.

  [1]: https://i.stack.imgur.com/4jF1P.jpg
  [2]: https://i.stack.imgur.com/toMGU.jpg


sender: user

message:
Arduino sends bad data ONLY when not connected at the launch my application

I'm trying to write a little sensor reading application with a light sensor attached to an Arduino, which writes the information from the sensor over serial. I have written a python program to read the data from the serial port. The good news, is that my program is working completely fine... only if I make sure that the Arduino USB is connected to my laptop before I launch my Python program.

I have myself forgotten to connect the Arduino before running the program before, which can leave it hanging... until you realise and plug the Arduino back in. It would be nice to have a window helping users if they ever make the same mistake.

Here is the Arduino sketch I have running on my Arduino.

    int photoTran = A1;
      int reading = 0;

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

    void loop() {
      // We just read the value on the analogPin
      reading = analogRead(photoTran);
      Serial.println(reading);
      delay(100);

    }

Here is the little catcher part of the Python script which checks whether the Arduino is connected before I get into the main part of my application. When I plug in the Arduino before running the Python script, it can still sometimes take a few attempts before connecting. (Just FYI: the window(), button, values, variables are from the PySimpleGUI framework that I'm using.)

    connected = False
    while connected == False:
        button, values = window.Read(timeout=300)
        if button in (None, 'Exit'):
            break
        try:
            print("Attempting to connect")
            SER = serial.Serial(serial_port, baud_rate, timeout=0.1)
            connected = True
            ser.append(SER)
        except:
            time.sleep(0.1)
            attempts += 1
            window.FindElement('attempts').Update(attempts)
    window.close()

    # User exited from the GUI connection window
    if not connected:
        sys.exit(0)

Later on in my Python code, I want to read the sensor data coming to us from the Arduino. ReadArduino, and CleanThe are the functions that I use to read data from the Arduino.

    def ReadArduino( serialCon ):
    """ Try to read in a value from the Arduino. Sometimes we might read a value from the serial
        port before the arduino has sent anything. In such cases we will wait a small time, and read again.
        Until we pick up our first non empty integer value."""
    while True:
        val = serialCon.readline()
        print(val)
        val = cleanThe(str(val))
        if val != '':
            return val

    def cleanThe( lineVal ):
    """ The Arduino returns non-clean data back to us.
        We need to remove all the non-integer values to get
        a nice plottable integer value. Will accept '.' unconditionally for now,
        we may have to add conditions later. """
    S = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.'}
    clean = ''
    for char in lineVal:
        if char in S:
            clean += char
    return clean

Now the confusing part. When I run the application without the Arduino connected to my computer. It gets stuck in the while connected == False: while loop above. This is exactly what I want. Then when I plug it in, the serial port sets up and we break out of the loop. I even have a serial port object that I read from.

However, when I read from the serial port, I get back garbage hex values, without any sign of any useful integer values that I would expect.

Here are some sample raw val values that get read back when the python script is run with the Arduino connected before running: `
b'336\r\n'
b'349\r\n'
b'343\r\n'
b'322\r\n'`

Then here is the output I receive when the Arduino was not connected to my computer before running the Python script.

    b'\xe0\x00\xe0\x00\x00\xe0\x00\x00\x00\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\xe0\x00\x00\x00\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\xe0\x00\x00\xe0\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\xe0\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\xe0\xe0\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\x00\xe0\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\xe0\x00\x00\xe0\xe0\x00\x00\xe0\x00'

    b'\x00\x00\x00\xe0\x00\x00\xe0\x00\x00\xe0'

I have noticed, that when I am running my script with the Arduino plugged in from the start (i.e. the working case). The first value I read back from the Arduino is the same type of garbage hex:

    b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

It seems like in the working case, the hex is all sent on one line. Where as in the non-working case, these hex values, seem to be sent intermittently in smaller chuncks. Perhaps I could add a check to the Arduino code, to only write values back to serial if they are good? I do realise this may be more of a python serial issue than an Arduino issue, let me know if this is the case and I will move the post.

Has anyone experience some kind of problem like this before?

sender: assistant

body:
On the Arduino side make your code non blocking:

     unsigned long timeStamp = 0;
     unsigned long timerDelay = 1000; // 1 second

     setup(){....}

    void loop() {
    // We just read the value on the analogPin
     if (millis() - timestamp > timerDelay ) {
         reading = analogRead(photoTran);
         Serial.print(reading); // instead of println which sends additional \r\n
         timeStamp =millis();  // reset timer instead of delay(100);
     }
    }

On the Phyton side try to implement a routine waiting for the first char and then start reading from the next message on. The 1 second between sends on Arduino should suffice to ensure its working. The garbagge chars could be an init sequence from the port driver - this can not come from your code,


body:
Just to explicitly show what I changed to my python code I thought I would answer my own question. The solution I found ended up being in the Python, but the other suggestions were useful for cleaning up the output of my Arduino.
Here is the old auto connecting solution.

    connected = False
    window = sg.Window('Arduino Connection').Layout(layout)
    attempts = 0
    while connected == False:
        print("In connection while loop")
        button, values = window.Read(timeout=300)
        if button in (None, 'Exit'):
            break

        try:
            print("Attempting to connect")
            SER = serial.Serial(serial_port, baud_rate, timeout=0.02)
            print(SER)
            connected = True
            ser.append(SER)
        except:
            time.sleep(0.1)
            attempts += 1
            window.FindElement('attempts').Update(attempts)

Here is the working solution where I ask the user to press a connect button.

        connected = False
    window = sg.Window('Arduino Connection').Layout(layout)
    attempts = 0
    while connected == False:
        print("In connection while loop")
        button, values = window.Read(timeout=300)
        if button in (None, 'Exit'):
            break
        if button == 'Ok':
            try:
                print("Attempting to connect")
                SER = serial.Serial(serial_port, baud_rate, timeout=0.02)
                print(SER)
                connected = True
                ser.append(SER)
            except:
                time.sleep(0.1)
                attempts += 1
                window.FindElement('attempts').Update(attempts)


message:
How to assign a string-variable to a StackString based on the StackString-library?

I'm trying to use the StackString-library which offers not to eat up RAM over time by re-assigning values to strings. I started from scratch and wrote a very basic democode which works.
Then I added an assignment to a STackString-variable from a normal string or a function with return-value string
See code below
If I try to compile
I get a compiler-error saying
no matching function for call to 'Stack::StackString<50>::append(String&)'

here is the code

    #include <StackString.hpp>
    using namespace Stack;  // it is very important to have this line of code. Otherwise the code won't compile

    StackString<50> myString = StackString<50>("Hello, World!");

    String NormalString = "1234Test";

    void setup()
    {
      Serial.begin(115200);
      Serial.println();
      Serial.println();
      Serial.println(myString.c_str());

      myString.prepend("Everybody say: ");
      Serial.println(myString.c_str());

      myString.append(" How are you doing?");
      Serial.println(myString.c_str());
      Serial.println();

      //myString = NormalString;
      myString.append(NormalString);

    }

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

    }

Do I have to do some typecasting? and if yes how does it look like?
WHat I want to do is assigning a StackString a new value. This means the STackString is on the left side of the "="  assigning operator. I have tried different variants to no avail.

Could this be a problem of the special construction as a "namespace" ?
No idea no clue

you find the STackString-library here:
https://gitlab.com/arduino-libraries/stackstring

best regards

Stefan

body:
`StackString` doesn't know what a `String` is.  The `append` function only accepts a `const char *`, a `const char` or an `int`:

```
void append(const char* string);
void append(const char character);
void append(int number);
```

You can get a `const char *` from a `String` easily enough with `.c_str()`, so use that in the append:

```
myString.append(NormalString.c_str());
```

There is also no simple assignment (or complete content replacement) with `StackString` - you have to "clear" the string first.  So to replace the content with what is in `NormalString` you would:

```
myString.clear();
myString.append(NormalString.c_str());
```


message:
Arduino webserver POST receive varriables

I have been learning lower level data reading on internet communication
As a part of bigger project I am testing web interface.

So far I could get main website displayed and by seeing the web-address read the data from GET request.
As I intend to send codes I wish to use POST method.

I am Trying to make this as standalone class for mine future projects, so I am only sending the class method itself. (Latter it would take websites content as a string, but for now input variables are yet to be implemented)

I am using esp8266, but would prefer to avoid esp8266 specific libraries as I wish it to eventually run on its realtek equivalent.

The code:

```
uint8_t Stranky::Stav(String obsahStranky, uint8_t obnovovat){
 WiFiClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    char vstupRiadok[150]={'\0'};
    uint8_t i=0;
    bool currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
  char c = client.read();
        vstupRiadok[i]=c;
        if(c=='\n' || i>=149) {
   Serial.println(vstupRiadok);
   //------------Extract variables here--------
   for(uint8_t j=0; j<149; j++) {
    //Serial.print(vstupRiadok[j]);
    vstupRiadok[j]='\0';
   }
   i=0;
  } else i++;
        if (c == '\n' && currentLineIsBlank) {
   Serial.println("Sending page");
   client.println(ohlasSa(1,1));
   client.println("<!DOCTYPE HTML>");
          // send a standard http response header
   client.println("<html><head> <meta charset=\"utf-8\"></head><body>");
   client.println("<h1> Nic nove</h1>");
   client.println("<form method='POST'>");
   client.println("Name:<input type=\"text\" id=\"Name\" name=\"Name\"/><br>\nSurname:<input type=\"text\" id=\"Surname\" name=\"Surname\"><br>\n<input type=\"submit\" value=\"Submit\"/><input type='reset'/> </form> </body>");
   client.println("</html>");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
    Serial.println("Prehliadač dpojený");
  }
}
```
This results in Browser code:
```
<!DOCTYPE HTML>
<html><head> <meta charset="utf-8"></head><body>
<h1> Nic nove</h1>
<form method='POST'>
   Name:<input type="text" id="Name" name="Name"/><br>
   Surname<input type="text" id="Surname" name="Surname"><br>
<input type="submit" value="Submit"/><input type='reset'/> </form> </body>
</html>
```
When I send any data over the form it does not get received  and only receive these:
```
WS:ac
:ref 1
WS:av
:ref 2
:ur 2
:rn 469
POST / HTTP/1.1

Host: 192.168.43.209

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:63.0) Gecko/20100101 Firefox/63.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: sk,cs;q=0.8,ru;q=0.6,en;q=0.4,en-US;q=0.2

Accept-Encoding: gzip, deflate

Referer: http://192.168.43.209/

Content-Type: application/x-www-form-urlencoded

Content-Length: 25

Connection: keep-alive

Upgrade-Insecure-Requests: 1

Sending page

```

No post, or Cookie variables that I could extract

I am far from home and too short of data to be installing more software like wire-shark over phones network sharing

body:
Check your definition of

    String vstupRiadok

it should not be

    String vstupRiadok="                                      "; //80 blanks

I would replace it with a decent sized fixed char anyway

    char vstupRiadok[81] = {'\0'};

if you create an empty line or other text do not forget to write the end terminator `'\0'` and make sure the char array is +1 the size for the longest string totake

As String class is a problem on its own as an Arduino class.

The HTML code generated has a missing

     <meta charset    ="utf-8">

error in the dev-tools. Aside from that whats the server code running on the Arduino,its not given. The class creates a html page, but at least in FF75 it tries to call server.ip\odpoved - so there has to be some js or Arduino code to decode this route there are no params attached from the form.

**EDIT**An extraction routine would look like:

 bool currentLineIsBlank = true;
 bool currentLineIsGet = true;
 uint8_t tCount = 0;
 char tBuf[64];
 uint8_t n=0;
    uint8_t s=0;
 char *pch;

 Serial.print("Client request: ");

  while (client.connected()) {
   while (client.available()) {
  char c = client.read();

  if (currentLineIsGet && tCount < 63) {
    tBuf[tCount] = c;
    tCount++;
    tBuf[tCount] = 0;
  }

  if (c == '\n' && currentLineIsBlank) {
    Serial.println(tBuf);
    // retrieve the POST data
    Serial.print("POST data: ");
    while (client.available()) Serial.write(client.read());
    Serial.println();

    pch = strtok(tBuf, "?");

    while (pch != NULL) {
   if (strncmp(pch, "Name=", 5) == 0) {
              pch = pch+6;
     char Name [24] = {'\0'};
              while(pch != '&'){
                 char Name [n] = pch;
                 n++;
               }
              char Name [n+1] = {'\0'};
     Serial.print("Name="); Serial.println(Name);
   }

   if (strncmp(pch, "Surname=", 8) == 0) {
              pch=pch+9;
     char Surname[24] = {'\0'};
              while(pch != '\r') {   // check if your response has that after the content or if its '\0'
                 char Surname [s] = pch;
                 s++;
               }
              char Surname [s+1] = {'\0'};
     Serial.print("Surname="); Serial.println(Surname);
   }
   pch = strtok(NULL, "& ");
    }
   // here the Sending response part starts

 You do not need a JSON parser for this just get the post request


body:
Based on codebreakers code I have been able to combine it into working one

The problem was on a fact that communication starts with header variables, then empty line, then body containing the variables

First get the connection: and create base variables
```
uint8_t Stranky::Stav(){
 WiFiClient client = server.available();
  if (client) {
    // an http request ends with a blank line
 bool currentLineIsBlank = 0;
 bool body=0;             // Helps seeing if this is still header
 bool finished=0;         // To know if to terminate connection
 uint8_t i = 0;           // To prevent iterator from resetting to 0
 char fullLine[81]={'\0'};  // buffer for input character to line
 // char *pch;

 Serial.print("User connected\n");
 while (client.connected()) {
  while (client.available()) {
   bool linEnd=0;          // When to deal with line (print it)
```
Get one incoming character:
```
   char c = client.read();
```
Now deal with new line character first

If the last line was empty That would mean: Header is finished and moving to the body of the incoming data
 If not change currentLineIsBlank (until new line gets its first character)
```
   if(c=='\n') {
    if(currentLineIsBlank) {
     if(!body) body=1;
     currentLineIsBlank=0;
    } else {
     Serial. print("/");
     currentLineIsBlank=1;
     linEnd=1;
    }
```
Now lets deal with any other character then new line:

```
   } else {
    currentLineIsBlank=0;   //If it has a character then its not empty
    fullLine[i]=c;
    i++;                //Move to the next letter
   }
```
Make sure that our array doesn't overflow
```
   if(i>=81) linEnd=1;
```
Now we know what is happening we can take some action after the buffer line is finished

if we are at the body stage, but we havent "finised" sending code
```
   if(linEnd){
    if(body && !finished) {
     finished=1;          // Finishing sending page
     Serial.printf(F("Variables:\n\t"));
```
Start extracting characters from body of the incoming data.

In a simple form like ours POST variables are on a last line, so we will just keep rewriting the line
```
     uint8_t k=0;
     while (client.available()) {
      fullLine[k]=client.read();
      Serial.printf(F("%c"),fullLine[k]);
      if(k<80) k++;
      if(fullLine[k]=='\n') {
       k=0;
       Serial.println();
      }
     }
     // Here you can extract variables as shown in codebreakers' answer

```
Finaly send then websites html code:
```
     Serial.print("Sending page\n");
     client.println(heatheRoutine()); //I have extra routine to inject heather so I do not have to write it every time I write a page
     client.println("<!DOCTYPE HTML>");
     // send a standard http response header
     client.println("<html><head> <meta charset=\"utf-8\"></head><body>");
     client.println("<h1>Fill the form now !!!</h1>");
     client.println("<form method='POST'>");
     client.println("Meno:<input type=\"text\" id=\"Name\" name=\"Name\"/><br>\nPriezvisko:<input type=\"text\" id=\"Surname\" name=\"Surname\"><br>\n<input type=\"submit\" value=\"Submit\"/><input type='reset'/> </form> </body>");
     /*Serial.printf(F("Page source send\n"));*/
     client.println("</html>\n");
     break;
    }
```
If we are not dealing with the body yet:
```
    currentLineIsBlank=1;
    for(uint8_t j=0; j<i; j++) { //Print the last line
     Serial.print(fullLine[j]);
     fullLine[j]='/0';     //restore default values To prevent characters leaking into next line
    }
    Serial.println();
    i=0;    //Since we are on an end of a line we are starting from first position in a buffer
   }
  }
```
If we have finished what we have wanted we need to get out of communication loop
```
  if(finished) {
   Serial.printf(F("Ending\n"));
   break;
  }
    }
```
And close the connection:
```
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
 client.stop();
    Serial.println("browser disconnected");
  }
}
```
Complete code:
```
uint8_t Stranky::Stav(){
    WiFiClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    bool currentLineIsBlank = 0;
    bool body=0;             // Helps seeing if this is still header
    bool finished=0;         // To know if to terminate connection
    uint8_t i = 0;           // To prevent iterator from resetting to 0
    char fullLine[81]={'\0'};  // buffer for input character to line
    // char *pch;

    Serial.print("User connected\n");
    while (client.connected()) {
        while (client.available()) {
            bool linEnd=0;          // When to deal with line (print it)
            char c = client.read();
            if(c=='\n') {
                if(currentLineIsBlank) {
                    if(!body) body=1;
                    currentLineIsBlank=0;
                } else {
                    Serial. print("/");
                    currentLineIsBlank=1;
                    linEnd=1;
                }
            } else {
                currentLineIsBlank=0;   //If it has a character then its not empty
                fullLine[i]=c;
                i++;                //Move to the next letter
            }
            if(i>=81) linEnd=1;
            if(linEnd){
                if(body && !finished) {
                    finished=1;          // Finishing sending page
                    Serial.printf(F("Variables:\n\t"));
                    uint8_t k=0;
     while (client.available()) {
      riadok[k]=client.read();
      Serial.printf(F("%c"),riadok[k]);
      if(k<80) k++;
      if(riadok[k]=='\n') {
       k=0;
       Serial.println();
      }
     }
                    // Here you can extract variables as shown in codebreakers' answer

                    Serial.print("Sending page\n");
                    client.println("HTTP/1.1 200 OK\r\n");
                    client.println("Content-Type: text/html\r\n");
                    client.println("Connection: close\r\n");
                    client.println();
                    client.println("<!DOCTYPE HTML>");
                    client.println("<html><head> <meta charset=\"utf-8\"></head><body>");
                    client.println("<h1>Fill the form now !!!</h1>");
                    client.println("<form method='POST'>");
                    client.println("Meno:<input type=\"text\" id=\"Name\" name=\"Name\"/><br>\nPriezvisko:<input type=\"text\" id=\"Surname\" name=\"Surname\"><br>\n<input type=\"submit\" value=\"Submit\"/><input    type='reset'/>  </form> </body>");
                    /*Serial.printf(F("Page source send\n"));*/
                    client.println("</html>\n");
                    break;
                }
                currentLineIsBlank=1;
                for(uint8_t j=0; j<i; j++) { //Print the last line
                    Serial.print(fullLine[j]);
                    fullLine[j]='/0';     //restore default values To prevent characters leaking into next line
                }
                Serial.println();
                i=0;    //Since we are on an end of a line we are starting from first position in a buffer
            }
        }
        if(finished) {
            Serial.printf(F("Ending\n"));
            break;
        }
    }
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
    Serial.println("browser disconnected");
  }
}
```


message:
Developing Standalone Arduino GUI Controller

I am rather new to using an Arduino.
As a part of my Graduate-Level Chemistry research, I am trying to further the development of a cheap DIY, open-source, Flow Chemistry Syringe pump system.

The device utilizes Stepper Motors, Step Motor control boards, an Arduino Uno, and a 3D printed Pump frame. Simple code was previously developed using the Arduino IDE. I have expanded on this a bit to allow for more customization (syringe size, mostly). The limitation here, is that the Serial Monitor inputs will be taxing to the users. I need to develop a simple GUI that allows for all of the inputs I need (syringe size, flow (step) rate, start and stop functions, etc.). I need this gui to be a standalone application that can be easily shared (no need to download anything extra, no installations, deploy-able on at LEAST Win and Mac).

Our labs goal is to develop a system that is easy to use and distribute, reducing the costs associated with using Flow Chemistry. I have a decent understanding of Arduino IDE, and I am willing to learn whatever I need to make this work.

I have seen a few things about Python, and 'Processing', but they seem to require the simultaneous use of Arduino IDE which would make deployment too complicated.

How should I approach this? What language do I need to learn? What advice do you have?

body:
The Uno is connected to the PC with a Serial interface (emulated over USB). The program on the PC only sees the Serial interface. It is not important, if there is really an Arduino at the other end. Nearly every programmung language can be used for interfacing a Serial interface, each gives advantages and disadvantages. But you will not have a single portable program file, that you can start on different OS without installing anything. Either you need to compile the program for each OS individually, or you can use a portable programming language, where you first need to install it's framework on the OS (for example python).

I would propose a different solution (that I'm currently also working on): Depending on your lab situation you could extend your project with a network interface, either Wifi or LAN. Then you can present a webinterface to the user. When writing HTML/javascript websites, it is easy to have them display correctly on most mayor browsers.

That way the GUI is really independent from the OS. For adding the network connection, you could use a LAN shield, Wifi shield, or directly change the microcontroller from an Arduino Uno to an ESP board, which has Wifi build in and is also has more computation power and memory.

The webinterface can be interactive by the use of javascript (since you cannot run php or similar on the Arduino or ESP).

Wether you want to use a companion application, that you write for the PC, or a webinterface is up to you and depends on your exact lab situation.


body:
I have a similar project ahead of me. While it is quite but obvious to be able to read the output voltages using arduino, I was wondering if we could create a python file which will be saved as an executable, but have in it, code that will run the original arduino cc file to read the averaged voltages from the pins. I tried using pyqt5 and/or tkinter but I am having thread issues in that the gui hangs after a few seconds of activity.(I used pyserial library here)
It will be really helpful if someone can help me out here.


message:
Digispark - Bootloader stuck

I have a digispark that I want to reprogram, soldered into a circuit. I have burned the default t85 micronucleus firmware.

**This is the command I used:**

    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" -C "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -pattiny85 -cstk500v1 -PCOM4 -b19200 -Uflash:w:D:\Documents\micronucleus-master\firmware\releases\t85_default.hex:i

    avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM4
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
             AVR Part                      : ATtiny85
             Chip Erase delay              : 400000 us
             PAGEL                         : P00
             BS2                           : P00
             RESET disposition             : possible i/o
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
               flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

             Programmer Type : STK500
             Description     : Atmel STK500 Version 1.x firmware
             Hardware Version: 2
             Firmware Version: 1.18
             Topcard         : Unknown
             Vtarget         : 0.0 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.03s

    avrdude: Device signature = 0x1e930b (probably t85)
    avrdude: safemode: hfuse reads as D7
    avrdude: safemode: efuse reads as FF
    avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
             To disable this feature, specify the -D option.
    avrdude: erasing chip
    avrdude: reading input file "D:\Documents\micronucleus-master\firmware\releases\t85_default.hex"
    avrdude: writing flash (8116 bytes):

    Writing | ################################################## | 100% 0.07s

    avrdude: 8116 bytes of flash written
    avrdude: verifying flash memory against D:\Documents\micronucleus-master\firmware\releases\t85_default.hex:
    avrdude: load data flash data from input file D:\Documents\micronucleus-master\firmware\releases\t85_default.hex:
    avrdude: input file D:\Documents\micronucleus-master\firmware\releases\t85_default.hex contains 8116 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 0.07s

    avrdude: verifying ...
    avrdude: 8116 bytes of flash verified

    avrdude: safemode: hfuse reads as D7
    avrdude: safemode: efuse reads as FF
    avrdude: safemode: Fuses OK (E:FF, H:D7, L:F1)

    avrdude done.  Thank you.
I have not set any fuses (I hope the frequency is right.)

The board is recognized by my computer and I can program a sketch into it using Arduino IDE. Despite all this the program I burned into it does not run. It seems it is stuck into the bootloader section.

**The sketch:**

    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(0, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(0, HIGH);
    }
Pin `PB0` has never a voltage bigger than `1.7V`(noise or floating). All pins have similar voltages (except `PB3`,`PB4` which are pulled up or high)

**The schematic:**
[![enter image description here][1]][1]

The circuit works. I tested both displays previously with the atiny which I directly programmed with the `Uno`. The upper right connector is directly plugged into the `digispark` with the following pins: `VIN`,`GND`,`5V`. The middle connector is also plugged into the `digispark`.

**I have tried:**

 - Powered by USB: I am afraid this will be detected by the bootloader and enter the programming state thus never running the schematic(shouldn't happen but you never know...)
 - Powered by VIN with a 9V battery. Nothing. All voltages are in check (`5V pin` has `5v` on it. All other pins are floating)
 - Powered by `5V pin` using an `Arduino UNO` as the source. Nothing.
In all cases the voltage on PB0 stays the same. It varies between `0.6V` and `1.6V`.

**In Arduino IDE:**

 - Tried Digispark 16.5Mhz
 - Digispark Pro 16Mhz
 - Digispark(No Usb) 16Mhz

Always a succesfull uploading.

**Notes:**

 - After uploading in Arduino this text comes up:

    > Starting the user app ...
    running: 100% complete

     So it is supposed to run the program but the board actually resets because it gets renumerated by windows.

 - It's not quite possible to de-solder it and program the sketch directly with `Arduino` as `ISP`
 - I use Windows 10
 - Fuses used when I burned the `micronucleus` `L:F1` `H:D7` `E:FF`. These are the default "safe" values. The actual fuses needed by the firmware are `L:E1` `H:DD` `E:FE`.
 - Difference in extended fuse: Self-programming is curently disabled...Is this the culprit?
 - I managed to desolder `PB0`,`PB1` and `PB2` from the back of the pcb. Now I can't program it directly with `Arduino as ISP`. The setup I have should work because I can easily program an t45. So it has something to do with the digispark. Checked the connection between pins and the actual MCU. The error I get is `Yikes...` and sometimes it finds an 0x00ff00 or other junk id for the board but probably it's because of misconnection.

**Question #2:**

 In the current configuration(soldered) would it be possible to use again  `Arduino as ISP` to program it?  `PB0`,`PB1`,`PB2` are connected to `Serial Clock`,`Serial Data` and `Serial Storage Clock` respectively. I am trying right now to set the right fuses but every time I get this:

    avrdude -C "C:\Program Files (x86)\Arduino\hardware\tools\avr\etc\avrdude.conf" -c stk500v1 -p attiny85  -U lfuse:w:0xe1:m -U hfuse:w:0xdd:m -U efuse:w:0xfe:m -B 20 -b19200 -P COM7

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.06s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.05s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.05s

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.

    make: *** [fuse] Error 1

  [1]: https://i.stack.imgur.com/B1dOC.png

body: Solved it! I don't know what the real issue was but I constructed a HV programmer and just blasted the digispark with the new and proper fuses. Now it works as it should.


message:
Is my Arduino skipping a statement?

So, I made this code (I'm rather new to this). The only thing that the Arduino should do, is when I press the button on pin 2, turn on the LED on pin 4 and emulate CTRL + R on the keyboard for the computer. Then, if the LED is on and I hit the button again, turn it off and hit the spacebar on my computer. But as soon as I hit the button for the first time, it does indeed press CTRL + R and the LED turns on, but after the delay, it immediately skips checking if I am pressing the button and assumes that I am pressing the button. Thereby it only sees that the LED is on and it turns it off while hitting the spacebar. Any suggestions?

<pre>

    #include <Keyboard.h>

    int buttonPin = 2;
    int ledPin    = 4;
    int val = 0;

    void setup() {
      // put your setup code here, to run once:
      pinMode(ledPin, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP);
      Keyboard.begin();
    }

    void loop() {
      val = digitalRead(buttonPin);
      // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
      if ((val == LOW) && (digitalRead(ledPin) == LOW)) {
        // turn LED on:
        digitalWrite(ledPin, HIGH);
        Keyboard.press(KEY_LEFT_CTRL);
        Keyboard.press('r');
        delay(100);
        Keyboard.release(KEY_LEFT_CTRL);
        Keyboard.release('r');
        delay(500);
      }
      if ((val == LOW) && (digitalRead(ledPin) == HIGH)) {
        digitalWrite(ledPin, LOW);
        Keyboard.write(32);
      }
      if ((val == HIGH) && (digitalRead(ledPin) == LOW)) {
        digitalWrite(ledPin, LOW);
      }
      if ((val == HIGH) && (digitalRead(ledPin) == HIGH)) {
        digitalWrite(ledPin, HIGH);
      }
    }

<code>

body:
Your code isn't checking for a button.  It's checking the value in val.  That only gets updated once per loop.  Let's say the code enters the first if statement because the val is LOW and the LED is also LOW.  This sets the LED to HIGH.  Now the next if statement, val is still LOW and now LED is HIGH so that one is true as well.

I think what you want is to use "else if" so it will skip the rest once it finds a true one.

    void loop() {
      val = digitalRead(buttonPin);
      // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
      if ((val == LOW) && (digitalRead(ledPin) == LOW)) {
        // turn LED on:
        digitalWrite(ledPin, HIGH);
        Keyboard.press(KEY_LEFT_CTRL);
        Keyboard.press('r');
        delay(100);
        Keyboard.release(KEY_LEFT_CTRL);
        Keyboard.release('r');
        delay(500);
      }
      else if ((val == LOW) && (digitalRead(ledPin) == HIGH)) {
        digitalWrite(ledPin, LOW);
        Keyboard.write(32);
      }
      else if ((val == HIGH) && (digitalRead(ledPin) == LOW)) {
        digitalWrite(ledPin, LOW);
      }
      else if ((val == HIGH) && (digitalRead(ledPin) == HIGH)) {
        digitalWrite(ledPin, HIGH);
      }
    }


body:
Try something like this.

The code does not use button states in its decision making.

Instead, it looks for the transition between button states, so holding the button does not generate events.

    void loop() {

      val = digitalRead(buttonPin);

      if (val != oldButtonState) {      // button state transition
        oldButtonState = val;
        if (val == LOW) {               // transition from "released" to "pressed"
          buttonClicked = true;         // set click flag
        }
      }

      if ( buttonClicked ) {

        buttonClicked = false;                // clear click flag

        if (digitalRead(ledPin) == LOW) {
          digitalWrite(ledPin, HIGH);         // turn LED on
          Keyboard.press(KEY_LEFT_CTRL);      // send CTRL-R
          Keyboard.press('r');
          delay(100);
          Keyboard.release(KEY_LEFT_CTRL);
          Keyboard.release('r');
          delay(500);
        }

        else {
          digitalWrite(ledPin, LOW);          // turn LED off
          Keyboard.write(32);                 // send space
        }
      }
    }


message:
Arduino digital pin input used to power device?

I am attempting to debug a W65C02 and I am using an Arduino Mega to look at the inputs and outputs of the device, which is behaving weird.

I have Pin 22 to 52 connected as INPUT on the MEGA and they are all connected to A0-A15 and D0-D7 on the 6502. However when I unplug my Arduino and keep the 6502 powered on it seems to stay on in that the power light is on. Is something fried or is this normal behavior?

Nothing else is plugged in to the Arduino except GND and the digital inputs.

body:
Arduino get the power from the port of 6502 via the protecting diod in the Arduino port. This the normal behavior.
// Mikael


body:
tl;dr: Don't **do** that.

As a general rule with CMOS digital circuits you don't want logic pin input voltages to be significantly higher than the VCC power input. (The same is true for TTL for that matter.) Doing that risks damage to the circuit.

That means that if a chip/board is not powered, you should not drive the logic lines at all.

`Carlmikael` says the behavior you are seeing is normal. I would call it *expected*, but I would not call it normal. It's "a normal error response" to a circuit being driven in a way that could damage it.


message:
From Arduino and breadboard to PCB

After building a working prototype with a breadboard, I was wondering what's next.
So I read about integrating the arduino into a PCB layout.

But in my case, it's worth it?

My project will use a Arduino Mega, futhermore some wired piezo switches therefore I need pcb connectors, and a small amount of resistor and transistors.
I am considering to buy a Mega of the shelf and use the contactpins on a header to fix it on my PCB. Also probably fix it with some screws.

It will save me a lot of pcb design time (a maybe some mistakes) and it will save me buying all diferent components. The  ATMega2560 alone is already around 10,-

I think I only need 10 or 15 pcb's, definitly no massproduction.

Your opinions...

body:
I agree with Majenko's proposal for a proto shield, or <br>if you need a "flat" design beside the Mega get yourself a striped (one /two sided and in different sizes) vero board (its like a breadboard to solder)

[![enter image description here][1]][1]

You could even use Fritzing to design the most efficient layout for this option in regards to space/material saving or minimum solder points

  [1]: https://i.stack.imgur.com/9WSDg.png


message:
NEMA17 and DRV8825 200 steps give only half revolution

I have this code:

    #include <stdint.h>

    # define STEP 14

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

    long steps = 0;
    void loop()
    {
        if (steps < 200)
        {
            digitalWrite(STEP, digitalRead(STEP) ^ 1);
            delay(10);
            steps++;
        }
    }

Simple implementation and I have a nema17 motor with 1.8 degrees per step, which should give 200 steps per revolution, but I only have half a revolution on 200 steps, I tried connecting all MODEx pins to VCC and this should give me 6400 steps per revolution but 6400 steps also gives mi half an revolution.
Could there be an issue with the wiring of the motor? Why don't I receive a full revolution?
By full revolution I mean that the motor shaft should complete the whole circle but it completes only half.

body:
See page 33 of the DRV8825 datasheet https://www.ti.com/lit/ds/symlink/drv8825.pdf.

DRV8255 moves the stepper on a rising edge in the signal.

That requires the signal to go low, then high.

 That is two cycles of your program.

Add two lines to your code so that it is `output low, delay 10, output high, delay 10`


message:
Monitoring multi analog ports with ACS712 current sensors

Making a Auto Blast Gate for dust collection in my wood shop. Arduino Nano using ACS712's to detect when tool is in use.  Using DRV8825 to drive a single Stepper motor that will spin a disk to line up blast gate for the tool in use. Code works as expected with one sensor coded but I can't figure out how to make it work with additional sensor coded in.
**Not sure if this is the way the question shows up,  Thanks**

 [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/u9NgN.png

    /*This one is atarting to work.   When tool is turn on the ACS712 detects it and the stepper moves 90 deg/steps.
When the tool is turned off it remains in position which is desireable as I would use the same tool multiable times in a row.
Need to add sensor A1 and assign different steps to it.
Can I declare the values of each sensor 1 time to be used whenever that analog port read > current Threshold?
Can I have a statement that will check all the analogs and act on the one that is >current Threshold?
Need for the stepper to only move if a different sensor (than the previous analog#) is > current Threshold?
IF/Else
*/

    #include <Arduino.h>
    #include "BasicStepperDriver.h"
    #include "DRV8825.h"

    #define MOTOR_STEPS 360 // Motor steps per revolution. Most steppers are 200 steps or 1.8 degrees/step
    #define RPM 200
    #define MICROSTEPS 1    // Since microstepping is set externally, make sure this matches the selected mode
                            // If it doesn't, the motor will move at a different RPM than chosen
                            // 1=full step, 2=half step etc.
    #define DIR 2           // All the wires needed for full functionality
    #define STEP 3
    #define ENABLE 4        // 2-wire basic config, microstepping is hardwired on the driver
    BasicStepperDriver stepper(MOTOR_STEPS, DIR, STEP, ENABLE);

    #define CURRENT_SENSOR_PIN A0 // Current sensor is connected to analog pin A0

    #define CURRENT_THRESHOLD 570 // The analog value above which the relay shall be triggered
    #define CURRENT_SAMPLE_PERIOD 500 // The number of milliseconds to sample the current reading

    int analogValue = 0; // Stores ADC values read in from the current sensor
    unsigned long stopwatch = 0; // Used to keep track of elapsed time

    void setup() {
      Serial.begin(9600);
      pinMode(DIR, OUTPUT);
      pinMode(STEP, OUTPUT);
      pinMode(ENABLE, OUTPUT);
     // pinMode (A0, INPUT);

        stepper.begin(RPM, MICROSTEPS);
        stepper.setEnableActiveState(LOW);
      }

    void loop() {
        analogValue = 0; // Initialize analogValue to a known state
        stopwatch = millis(); // Store a snapshot of the current time since the program started executing

        // Collect the max ADC value from the current sensor for the predetermined sample period
        while (millis() - stopwatch < CURRENT_SAMPLE_PERIOD) {
          analogValue = max(analogValue, analogRead(CURRENT_SENSOR_PIN));
          Serial.println(analogValue);
        }

        // If the max ADC value from the current sensor exceeds the threshold, set the state to LOW
        if (analogValue > CURRENT_THRESHOLD) {
          stepper.enable();  //  energize coils - the motor will hold position
          stepper.rotate(90);  //Moving motor using the degree notation in ()

       }
        while(analogValue > CURRENT_THRESHOLD)
          stepper.disable();  // pause and allow the motor to be moved by hand
    }
    // need to return to top of loop

body:
First: As written in the comments, your current code will only work once. After the first reaching of the threshold it will permanently stay in the last while loop, since `analogValue` can never change in there (you don't assign a new value to it). Thus this part should be removed.

---

To extend your code for multiple sensors, you can organize all the relevant data into arrays, so that you can loop over them. First we define an array of the used analog input pins (together with a define for the array size, so that we can later easily loop over the array and still be able to easily add further sensors):

    #define SENSOR_N    2
    uint8_t sensor_pins[SENSOR_N] = {A0, A1};

Then we are defining similar arrays for the thresholds and stepper positions:

    uint16_t sensor_thresholds[SENSOR_N] = {570, 400};
    uint8_t stepper_positions[SENSOR_N] = {90, 180};

Now in the `loop()` function we can surround the measurement and stepper code into a loop over the arrays. Where you used defines before, we are now using the array elements of the corresponding index:

    for(uint8_t i=0;i<SENSOR_N;i++){
        analogValue = 0; // Initialize analogValue to a known state
        stopwatch = millis(); // Store a snapshot of the current time since the program started executing

        // Collect the max ADC value from the current sensor for the predetermined sample period
        while (millis() - stopwatch < CURRENT_SAMPLE_PERIOD) {
            analogValue = max(analogValue, analogRead(sensor_pins[i]));
            Serial.println(analogValue);
        }

        // If the max ADC value from the current sensor exceeds the threshold, set the state to LOW
        if (analogValue > sensor_thresholds[i]) {
            stepper.enable();  //  energize coils - the motor will hold position
            stepper.rotate(stepper_positions[i]);  //Moving motor using the degree notation in ()
        }
    }

Now you still have 2 things to consider:

- Depending of the number of sensors, your code currently can take rather long. With lets say 6 sensor, you are measuring for 3s in total at the worst case (when the last machine is turned on). You might want to reduce your measurement duration (500ms is rather long).

- You need to add code for defining, what happens, when you turn multiple machines on at the same time. Currently that would lead to the stepper motor going back and forth; surely not what you want. The easiest thing would be to only consider the first sensor, that reaches the threshold, which then gets to set the position ("first" not in chronological sense, but in the order of the pin in the `sensor_pins` array). You can reach that with a `break;` command at the end of the threshold if condition.

---

Notes:

- The arrays hold, what they say. `sensor_thresholds` holds all the thresholds. In my example `570` is the threshold of the first sensor and `400` is the threshold of the second sensor. `90` in `stepper_positions` is the position of the stepper for the first sensor. `180` is the position for the second sensor.

- I used 2 sensors in my example. You can extend that yourself by setting the define `SENSOR_N` to the number of sensors and adding elements for every sensor into the arrays.

- `uint8_t` and `uint16_t` are unsigned integer types with the mentioned number of bits: `uint8_t` has 8 bits (1 byte), `uint16_t` has 16 bits (2 bytes). `uint8_t` is the same as `unsigned char` or `byte`. `uint16_t` is the same as `unsigned int` on the Uno/Nano. I used these types, because it is a good practice to use types, that have the same size on every platform. When changing to a different platform, types like `unsigned int` might have a different size, like being a 32 bit unsigned integer instead of a 16 bit one. As that might break code, that relies on the specific size of the type, I try to always use types with the same size on all platforms. These types have always the same pattern. There are also: `uint32_t`, `int16_t` (signed integer) or `int8_t`.

- I've chosen the type sizes according to the expected values. Pin numbers are typically 8bit/1 byte. That is sufficient. The thresholds are above 255, thus 8 bits are not enough, so I chose a 16 bit integer. Depending on the stepper positions, that you need, you might want to change it's type also to `uint16_t`.


message:
SCLK pulses not seen when using SPI on ESP32

I am using the following code in my esp32 using Arduino IDE for spi communication which is an example code -
```c++
    #include <SPI.h>

    static const int spiClk = 1000000; // 1 MHz

    //uninitalised pointers to SPI objects
    SPIClass * vspi = NULL;
    SPIClass * hspi = NULL;

    void setup() {
      //initialise two instances of the SPIClass attached to VSPI and HSPI respectively
      vspi = new SPIClass(VSPI);
      hspi = new SPIClass(HSPI);

      //clock miso mosi ss

      //initialise vspi with default pins
      //SCLK = 18, MISO = 19, MOSI = 23, SS = 5
      vspi->begin();
      //alternatively route through GPIO pins of your choice
      //hspi->begin(0, 2, 4, 33); //SCLK, MISO, MOSI, SS

      //initialise hspi with default pins
      //SCLK = 14, MISO = 12, MOSI = 13, SS = 15
      hspi->begin();
      //alternatively route through GPIO pins
      //hspi->begin(25, 26, 27, 32); //SCLK, MISO, MOSI, SS

      //set up slave select pins as outputs as the Arduino API
      //doesn't handle automatically pulling SS low
      pinMode(5, OUTPUT); //VSPI SS
      pinMode(15, OUTPUT); //HSPI SS

    }

    // the loop function runs over and over again until power down or reset
    void loop() {
      //use the SPI buses
      vspiCommand();
      hspiCommand();
      delay(100);
    }

    void vspiCommand() {
      byte data = 0b01010101; // junk data to illustrate usage

      //use it as you would the regular arduino SPI API
      vspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      digitalWrite(5, LOW); //pull SS slow to prep other end for transfer
      vspi->transfer(data);
      delay(500);
      digitalWrite(5, HIGH); //pull ss high to signify end of data transfer
      vspi->endTransaction();
    }

    void hspiCommand() {
      byte stuff = 0b11001100;

      hspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      digitalWrite(15, LOW);
      hspi->transfer(stuff);
      delay(500);
      digitalWrite(15, HIGH);
      hspi->endTransaction();
    }
```

I am able to see the toggling of the **SS** pin, but the **SCLK** pin does not show any pulses on the oscilloscope. It is a constant low. Should the pulses be given from an external source? If so, what is the purpose of this line - `static const int spiClk = 1000000; // 1 MHz`?

body:
Try to set the pins explicitly to Output <br>
**EDIT**Different issues with the test programs indicate that acc. to espressif the pin has to explicitly set to high which is not done by the libs begin method (as of core 1.04)

      digitalWrite(30, HIGH); // turn on pullup resistors
      digitalWrite(xxx, HIGH); // turn on pullup resistors
      pinMode(30, OUTPUT); //VSPI SLCK
      pinMode(XX, OUTPUT); //HSPI SCLK

The ESP32 docs say:

> gpio18 will output low level(because gpio18 is input mode by default).
> If you don’t want this behavior, you should configure gpio18 as output
> mode and set it to hight level before calling

As this is not the issue - the Wroom32 modules v1-3 have a problem with SPI when flashed in certain modes with 80Mhz So try flashing with 40Mhz. I check for my test program in the meantime.

So here is a working test routine:

    /* SPI Test routine for Wroom32
    Connect the MISO with  the MOSI pin*/
    #include<SPI.h>       //Library for SPI

    #define SPI_SCK 18 // Serial Clock (Master Output)
    #define SPI_MOSI 23 // Master Output,Slave Input
    #define SPI_MISO 19 // Master Input, Slave Output
    #define SPI_CS 5 // Chip Select, Slave Transmit Enable (active low, Master Output)
    #define SS 5

    char returnStr[40] = {'\0'};
    char returnChr;

    void setup () {
      Serial.begin(115200); // Set baud rate to 115200 for usart
      pinMode(SPI_CS, OUTPUT);
      pinMode(SPI_SCK, OUTPUT);
      pinMode(SPI_MOSI, OUTPUT);
      pinMode(SPI_MISO, INPUT);

      digitalWrite(SS, HIGH); // disable Slave Select
      SPI.begin (SPI_SCK, SPI_MISO, SPI_MOSI);
      SPI.setBitOrder(MSBFIRST);
      SPI.setDataMode(SPI_MODE0);
      SPI.setClockDivider(SPI_CLOCK_DIV8); // divide the clock by 8=2 MHz @ESP32
    }

    void loop () {
      char c;
      digitalWrite(SS, LOW); // enable Slave Select
      /* Send test string in a loop */
      for (const char *p = "SPI TEST! We are online over SPI\n\r" ; (c = *p); p++)  {
        returnChr = SPI.transfer (c);
        Serial.print(c);
        Serial.print(returnChr); // MOSI MISO Link sends echo back
      }
      digitalWrite(SS, HIGH); // disable Slave Select
      delay(500);
    }

To measure the signals you have to trigger to the falling edge of SS/CS and set the resolution to 2µs per grid field (round about). I tested on an AIThinker module (ESP32) and everything worked with that sketch.


message:
Error compiling for board Arduino Uno

I am relatively new to Arduino and I am trying to code some neo pixels and every time I try to verify my code this error comes up:

>Arduino: 1.8.12 (Mac OS X), Board: "Arduino Uno"
>
>loading libs from /Users/erinshankland/Documents/Arduino/libraries: reading dir >/Users/erinshankland/Documents/Arduino/libraries: open >/Users/erinshankland/Documents/Arduino/libraries: operation not permitted
>
>Error compiling for board Arduino Uno.
>
>This report would have more information with
>"Show verbose output during compilation"
>option enabled in File -> Preferences.

this is my code:

    #include <Adafruit_NeoPixel.h>

    #define PIN        6

    #define NUMPIXELS 15

    Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRBW + NEO_KHZ800);

    // this constant won't change:

    const int  btnRed = 2;  // the pin that the pushbutton is attached to

    const int  btnBlue = 3;  // the pin that the pushbutton is attached to

    const int  btnGreen = 4;  // the pin that the pushbutton is attached to

    const int  btnPurple = 5;  // the pin that the pushbutton is attached to

    void setup() {

      randomSeed(analogRead(A0));

      // put your setup code here, to run once:

      pinMode(btnRed, INPUT);

      pinMode(btnBlue, INPUT);

      pinMode(btnGreen, INPUT);

      pinMode(btnPurple, INPUT);

      // initialize the LED as an output:

      // initialize serial communication:

      Serial.begin(9600);

      pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)

        pixels.clear(); // Set all pixel colors to 'off'

        pixels.show();

        delay(1000);

    }

    void loop() {

    if (digitalRead(btnRed)==HIGH){

        rndRed();

      delay(100);

    }

    if (digitalRead(btnBlue)==HIGH){

        rndBlue();

      delay(100);

    }

    if (digitalRead(btnGreen)==HIGH){

        rndGreen();

      delay(100);

    }

    if (digitalRead(btnPurple)==HIGH){

        rndPurple();

      delay(100);

    }

    }

    void rndRed() {

      int led = random(0, 15);

      pixels.setPixelColor(led, pixels.Color(255, 0, 0,0));

      pixels.show();   // Send the updated pixel colors to the hardware.

      delay(500);

    }

    void rndBlue() {

      int led = random(0, 9);

      pixels.setPixelColor(led, pixels.Color(0, 0, 255,0));

      pixels.show();   // Send the updated pixel colors to the hardware.

      delay(500);

    }

    void rndGreen() {

      int led = random(0, 9);

      pixels.setPixelColor(led, pixels.Color(0, 255, 0,0));

      pixels.show();   // Send the updated pixel colors to the hardware.

      delay(500);

    }

    void rndPurple() {

      int led = random(0, 9);

      pixels.setPixelColor(led, pixels.Color(171, 0, 255, 0));

      pixels.show();   // Send the updated pixel colors to the hardware.

      delay(500);

    }

I am using a new library for the neo pixels but this has been downloaded and updated.
Hopefully someone can help me!

body:
> loading libs from /Users/erinshankland/Documents/Arduino/libraries: reading dir
> /Users/erinshankland/Documents/Arduino/libraries: open
> /Users/erinshankland/Documents/Arduino/libraries: operation not permitted

This is not an Arduino problem but an OS problem.

Either your `/Users/erinshankland/Documents/Arduino/libraries` is not accessible by your user (check the permissions) or it's not a directory.

You can try, from a terminal:

```
sudo chown -R erinshankland /Users/erinshankland/Documents/Arduino/libraries
chmod -R 755 /Users/erinshankland/Documents/Arduino/libraries
```

which will reset ownership and file permissions on the directory and everything underneath it.

If not, then delete your libraries folder (which may in fact be a file, not a folder) and recreate it and repopulate it with your desired libraries.


message:
Unable to understand the acquisition of data from Magnetometer HMC5883L and Accelerometer ADXL345

Below are the X,Y,Z registers for HMC5883L.
[![HMC5883L registers][1]][1]

while this is the Arduino code for HMC5883L to acquire X,Y,Z reading.
If you look at this code, we do not mention the X, Y, Z address specifically.

      Wire.beginTransmission(0x1E);
      Wire.write(0x02);
      Wire.write(0b00000001);
      Wire.endTransmission();
      delay(10);

      Wire.requestFrom(0x1E,6);
      if (Wire.available() > 5)
      {
        x = readValue();
        y = readValue();
        z = readValue();
      }
      else
      {
        Serial.println("No data found");
      }
    int readValue()
    {
      int val = Wire.read()<<8;
          val |= Wire.read();

      return val;
    }

We only write `Wire.request()` and do not mention X,Y,Z addresses specifically for HMC5883L.
While in the case of ADXL345 we mention every register of X,Y,Z separately to acquire data. Which is exactly my question like why not simply use `Wire.requestFrom()` for ADXL345 too. When will we access each X,Y,Z register separately? and when will we do not?

Below is Arduino ADXL345 code for reading X axis data.

      Wire.beginTransmission(0x53);
      //Ask the particular registers for data
      Wire.write(0x32);
      Wire.write(0x33);
      Wire.endTransmission();
      Wire.requestFrom(0x53,2);
      if(Wire.available()<=2) {
        X0 = Wire.read();
        X1 = Wire.read();
        X1=X1<<8;
        X_out =X0+X1;
        Xa=X_out/256.0;
      }

Datasheets for both sensors are available on the link.

The code above is not mine.
https://drive.google.com/open?id=1AswNTdBz55Rfg3nu4-YsLFj4ANrsCL5I

  [1]: https://i.stack.imgur.com/30jnB.png

body:
If you read the datasheet for the mentioned magnetometer, it is clearly mentioned that the data is to be read at once. Below is the implementation of pseudo code mentioned in the datasheet.

    void setup()
    {
      // put your setup code here, to run once:
      Serial.begin(9600);
      //send 0x3C 0x00 0x70 (8-average, 15 Hz default, normal measurement)
      Wire.begin();
      Wire.beginTransmission(0x1E);
      Wire.write(0x00);
      Wire.write(0x70);
      Wire.endTransmission();
      delay(10);
      //send 0x3C 0x01 0xA0 (Gain=5, or any other desired gain)
      Wire.beginTransmission(0x1E);
      Wire.write(0x01);
      Wire.write(0xA0);
      Wire.endTransmission();
      delay(10);
      //send 0x3C 0x02 0x00 (Continuous-measurement mode)
      Wire.beginTransmission(0x1E);
      Wire.write(0x02);
      Wire.write(0x00);
      Wire.endTransmission();
      delay(10);

    }
    void loop()
    {

      Wire.requestFrom(0x1E,6);
      if (Wire.available() > 5)
      {
        x = readValue();
        y = readValue();
        z = readValue();
      }
      else
      {
        Serial.println("No data found");
      }
      data = String(x) + "   ,   " + String(y) + "   ,   " + String(z);
      //Send 0x3C 0x03 (point to first data register 03)
      Serial.println(data);
      Wire.beginTransmission(0x1E);
      Wire.write(0x03);
      Wire.endTransmission();
      delay(100);
    }

Similarly, it is mentioned in the datasheet for ADXL345 as well that the data should be read separately from each axis register separately.


message:
Arduino atmega328p

This program should prompt the user for an encryption key to be input through the serial
monitor. The encryption key contains 16 characters. However, the message that will be
encrypted can be up to 128 characters. As such, when storing the encryption key in the
EEPROM, you should repeat it so that it fills locations 0-127.

in the code, I'm trying to repeat the 16 character key 8 times

    volatile bool prese_button = false;
    String Password;
    int counter = 8;
    boolean right_pass;
    void setup() {
      DDRD &= 0b11111011;
      PORTD |=0b00000100;
      EICRA |= 0b00000010;
      EIMSK |= 0b00000001;
      Serial.begin(9600);
    }

    void loop() {
      Serial.println("Please enter a 127 character password:");
      while (Serial.available() == 0) {}  //wait for serial terminal to be ready
      Password = Serial.readString();
      Serial.print("your password is: ");  //just to verify it was read correctly
      Serial.println(Password);
      for ( int j = 0 ;j < 128; j++) //   28 char
      {
        for (int i = 0; i<16 ; i++) {     //16 char
          EEPROM_write ( (j), Password[i] );
        }
      }
    }

body:
       for ( int j = 0 ;j < 128; j++) //   28 char
      {
        for (int i = 0; i<16 ; i++) {     //16 char
          EEPROM_write ( (j), Password[i] );
        }
      }

In these two for loops you are writing 128 times 16 characters.  That seems more than you described in your post.  If you have 16 things and need to repeat to fill 128 slots then you need 128 / 16 = 8 repeats of the 16 character sequence.  It's just basic math.  So that outer loop should count to 8, not 128.

    for ( int j = 0 ;j < 8; j++) //  8 repeats of the 16 char
          {
            for (int i = 0; i<16 ; i++) {     //16 char
              EEPROM_write ((i + (16*j)), Password[i] );
            }
          }


message:
Send/receive data from/to Raspberry Pi to/from Arduino with HM-10 (Bluetooth LE module)

My goal is to send a string from an Arduino via an HM-10 bluetooth module to a Rasperry Pi. I do this today by connecting the HM-10 on the Arduino to another HM-10 module (master/slave) and then from that module to the Raspberry Pi via USB Serial adapter which gives me a /dev/ttyUSB0 that I can read. I would like to just have the Arduino's HM-10 connect up directly to the Bluetooth of the Raspberry Pi without any extra modules at all.

I found the app "Arduino Bluetooth Controller" (Android) that can connect to the module and serial communication is working.

I also have the HC-05 module and there I can solve it by using rfcomm bind 2 <device address>, but that doesn't work on the HM-10.

I'm open to any solution that can do this. Either bind the serial communication using rfcomm (or alternative) like on the HC-05, or try to build an app that is doing the same thing the Android app does, only on the Raspberry Pi.

body:
HM-10 is a BLE device. You'll need to understand BLE programming, which is quite different than classic Bluetooth.
There is no standard BLE service for serial communication.
The best way on a Pi to use BLE is with the

  - [noble and bleno modules for node.js](https://www.skyrise.tech/blog/tech/bluetooth-raspberry-pi-bleno-part-1-ibeacon/).
  - Or start by [playing with gatttool](https://www.instructables.com/id/Bluetooth-Low-Energy-Read-Write-to-Sensor-Network-/).

If you are fit in Phyton:
The HM-10 style device will send notifications that the Pi's BLE device can read. Basically you need to
attach a 'delegate' call-back function to the Peripheral object,
and then wait for notifications.
The call-back can then process the received data.
You'll have to install the bluepy lib on the PI. This sample code writes to an Arduino HC-10 device

 import bluepy.btle as btle

 p = btle.Peripheral("AA:BB:CC:DD:EE:FF")
 s = p.getServiceByUUID("0000ffe0-0000-1000-8000-00805f9b34fb")
 c = s.getCharacteristics()[0]

 c.write(bytes("Hello world\n", "utf-8"))
 p.disconnect()

Here is some code for reading from an Arduino HC-10 device

 import bluepy.btle as btle

 class ReadDelegate(btle.DefaultDelegate):
  def handleNotification(self, cHandle, data):
   print(data.decode("utf-8"))

 p = btle.Peripheral("AA:BB:CC:DD:EE:FF")
 p.withDelegate(ReadDelegate())

 while True:
  while p.waitForNotifications(1):
   pass

 p.disconnect()


message:
How can I control Servo motor properly by using TimerOne and ServoTimer2 Library?

In this project I want smooth rotation of the Servo(Pin (D10) periodically where period time select by a potentiometer(actually I will use pressure sensor in this pin now it is unavailable to me so I am using g potentiometer).The Time period controlled by by a potentiometer position(two) change at Pin A0.Two Led(blue & red) (D7,D9)(in this pin I will use two valve controller servo) blink with same period and other yellow Led blink same period but oppositely.All working except Servo which rotation is not smooth .It's rotation sometime maintain proper period and sometime unnecessarily stop.Before I tried TimerOne and Servo Library but they are creating some conflict and not uploaded to Board.I am using Arduino Uno Board.What change should I do either in Circuit or in Code.I am new in this field.Any kind help would be grateful for me thank you.And my code is

    #include <TimerOne.h>
    #include "ServoTimer2.h"
    const int potPin = A0;
    const int bluePin =7;
    const int redPin =8;
    const int whitePin = 9;
    const int yellowPin = 11;
    const int myServoPin = 10;
    ServoTimer2 myServo;
    int angle;
    int speed;
    int potVal;
    int breathPress;
    int lowPress=12;
    int upPress=24;
    int lowCount=0;
    int upCount =0 ;
    int time1;
    int time2;
    int timeDiff;
    int temp;
    int potPin1 = A2;
    int breathRatio;
    int ratioVal;
    void setup() {
      pinMode(potPin,INPUT);
      pinMode(bluePin,OUTPUT);
      pinMode(redPin,OUTPUT);
      pinMode(potPin1,INPUT);
      pinMode(whitePin,OUTPUT);
      pinMode(yellowPin,OUTPUT);
      myServo.attach(10);

      Timer1.initialize(100000);
      Timer1.attachInterrupt(Blink);
      Serial.begin(9600);
     }

    void loop() {
      breathRatio=analogRead(potPin1);
      ratioVal = map(breathRatio,0,1023,1,6);

      digitalWrite(bluePin,HIGH);
      digitalWrite(yellowPin,HIGH);
      digitalWrite(whitePin,LOW);
      myServo.write(90);

      delay(timeDiff);
      digitalWrite(bluePin,LOW);
      digitalWrite(yellowPin,LOW);
      digitalWrite(whitePin,HIGH);
      myServo.write(60);
      delay(timeDiff);

    }

    void Blink(){
      potVal = analogRead(potPin);
      breathPress = map(potVal,0,1023,0,30);
      Serial.print("Pressure=");
      Serial.println(breathPress);
      Serial.println(time1);
      Serial.println(time2);
      Serial.print("Time Difference :");
      Serial.println(timeDiff);
      if(breathPress<10){
      digitalWrite(redPin,LOW);
      }
      if(breathPress>27){
        digitalWrite(redPin,LOW);
      }
      else {
        digitalWrite(redPin,HIGH);
      }
      if ((breathPress - 10 )<= 0){
        lowCount = 1;
        upCount =0;
        time1 = millis();
      }
      if((breathPress - 27)>=0){
        lowCount = 0;
        upCount = 1;
        time2 = millis();
      }
      if(time1-time2 >= 0){
        timeDiff = time1-time2;
      }
      else{
        timeDiff = time2-time1;
      }
And output showing

13096
14994
Time Difference :1898
Pressure=15
13096
14994
Time Difference :1898
Pressure=15
13096
14994
Time Difference :1898
Pressure=15
13096
14994
Time Difference :1898
Pressure=15

body:
What you are claiming does not makes sense to me. In your code you are not moving the sensor smoothly. You are setting it to 60 and 90 degrees successively. You don't control the movement between these values. That's, what the servo does. It moves directly, where you tell it to move. You cannot control how the servo moves between two values, that you set. To move slower (you could call that smooth) between the values, you would need to set the inbetween values for the servo. So instead of going directly from 60 to 90, you would go in steps, from 60 to 61, to 62, ... to 89, to 90 degrees.

Also you are not controlling the servo with the Timer1 library, at least not directly. You measure a time difference with the library. This time difference is then the time, that the servo will stay in the current position, until it is moved again.

---

Note, that this

    if((breathPress - 27)>=0)

is an over-complicated way of writing

    if(breathPress >= 27)


message:
What is the difference between delay() and delaymicroseconds()

Does delaymicroseconds() provide something more than the time accuracy

body:
There is a more important difference between the two functions other than the unit of time the accept as parameters
the function delay() calculates time using the time interript of the arduino. However Delaymicroseconds() does not use the time interrupt
As you may know once an interrupt is called it stops all other interrupts
So the real difference is you can not use delay() in a program in which you are using an interrupt and instead, use delaymicroseconds() but be aware that it has a range where it is accurate and it is between 3 and 16383 micro seconds


message:
Arduino vs Wemos Fan control

I have a working fan control with the correct wiring that works with arduino.

I would like to change the arduino with a Wemos D1 mini board.

When I hook everything up. The fans are not activated.

The fan is driven by a 12v charger. And the irf540n cicruit powers that. They just share a common ground and the pwm pin D5

Is there something I need to know about the difference in both of them?

Below is the code, I've changed D5 in the code to 14.

Still nothing seems to work.

        #define fan D5

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      Serial.println("start");
      pinMode(fan, OUTPUT);

      digitalWrite(fan, LOW);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      delay(1000);
      digitalWrite(fan, HIGH);

      delay(1000);
      digitalWrite(fan, LOW);
    }

body:
The IRF540 is not suitable to be controlled by a 3.3V device because it has a gate-source-threshold voltage of 2-4V (that's the voltage at which the mosfet **starts** to conduct, but you need to be above that voltage). While this worked at 5V logic level on the arduino, the 3.3V are not enough to make the mosfet switch entirely.

A suitable mosfet has a threshold voltage below 1V. Also for a fan, you eon't need a big mosfet rated for 30A, a tiny one will do it.


message:
Sending Variable to IFTTT via ESP32 using Asynchronous Web Server

I have been trying to send three variables to IFTTT from my ESP32 using Asynchronous Web Server. However, I couldn't set the "URL" that was supposed to be the response that will trigger my IFTTT. Here's is my code:

    server.on("/ifttt", HTTP_GET, [](AsyncWebServerRequest *request){

    String jsonObject = "{\"value1\":\"" + Global_T + "\"" + ",\"value2\":\"" + Global_H  + "\"" + ",\"value3\":\"" + Global_K +  "\"}";

    AsyncWebServerResponse *response = request->beginResponse(200, "application/json", jsonObject);

    response ->addHeader("Host", server_ifttt);
    request ->send(response);
    });

It shall get triggered every fixed interval that I have set, and enter here to send it to IFTTT, but this is how it looks like. I not sure where should I add in the "URL" so that the response could be directed to IFTTT.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/4KdbY.png

body:
As already said in the comments you need client code - Here are ready to use blocks for your scenario - **NEVER use String class** if you want to have a stable running IoT device, so define global char arrays (compiled to flash) and keep heap fragmentation at a minimum, The code is commented to get you started, change to your needs:

    /* Your constants */
    #define READ_THIS_PIN 4
    const char MakerIFTTT_Key[] = "r8X-blahblahYourKeyGoesHere";
    const char MakerIFTTT_Event[] = "stack_exchange_example";

    /* Define global char arrays to get rid of string class */
        char numBuf[20];       // We "just know" this is big enough for (un)signed longs
        char postRequest[256];    // Hand-calculated to be big enough (size to your needs)
    /* Helper functions for constructing the POST data
        append a string or int to a buffer, return the resulting end of string */

    char *appendStr(char *tempChr, char *s) {
        while ((*tempChr++ = *s++))
            ;
        return tempChr-1;
    }

    char *appendUl(char *tempChr, unsigned long u) {
        return appendStr(tempChr, ultoa(u, numBuf, 10));
    }
    /*
     This is called once per iteration to read the pin
     and send a POST to trigger the IFTTT/Maker event
    */

    void updateEvent() {
        WiFiClient client;

        /* Connect to the Maker event server */
        client.connect("maker.ifttt.com", 80);

        /* Construct the POST request */

        postRequest[0] = {'\0'}; /* Reset char array */
        char *p = postRequest;
        p = appendStr(p, "POST /trigger/");
        p = appendStr(p, "MakerIFTTT_Event");
        p = appendStr(p, "/with/key/");
        p = appendStr(p, "MakerIFTTT_Key");
        p = appendStr(p, " HTTP/1.1\r\n");
        p = appendStr(p, "Host: maker.ifttt.com\r\n");
        p = appendStr(p, "Content-Type: application/json\r\n");
        p = appendStr(p, "Content-Length: ");

        /* We need to remember where the content length will go, which is: */
        char *contentLengthHere = p;

        /* It's always two digits, so reserve space for them (the NN) */
        p = appendStr(p, "NN\r\n");

        /* End of headers */
        p = appendStr(p, "\r\n");

        /* Construct the JSON; remember where we started so we will know len */
        char *jsonStart = p;

        // This example reports a pin, uptime, and "hello stack" change to your need */
        p = appendStr(p, "{\"value1\":\"");
        p = appendUl(p, 12);    //analogRead(READ_THIS_PIN));
        p = appendStr(p, "\",\"value2\":\"");
        p = appendUl(p, millis());
        p = appendStr(p, "\",\"value3\":\"");
        p = appendStr(p, "hello, stack!");
        p = appendStr(p, "\"}");

        /* Go back and fill in the JSON length
           we just know this is at most 2 digits (and need to fill in both) */
        uint8_t i = strlen(jsonStart);
        contentLengthHere[0] = '0' + (i/10);
        contentLengthHere[1] = '0' + (i);

        // finally we are ready to send the POST to the server!
        client.print(postRequest);
        client.stop();
    }