text:
Why are my motors attached to an Arduino MEGA not running?
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);
}

I hope you're not trying to drive the motors directly from the output pins ...

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)

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.

Comments are not for extended discussion; this conversation has been moved to chat.

Codebreaker, you are more patient than I.


text:
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?

Depending on the bootloader you might receive its tries to connect to its counterpart on your PC. Did you check how the "garbage" maps with the bootloader's protocol? -- Another thought: The xe0 and x00 bytes might indicated an unmatched baudrate.

I know I'm a month late to this question, but just out of curiosity, did you solve it? Have you tried with a Serial.flush() after the Serial.println in the Arduino code?

No I haven't managed to find a working solution so far. I would be very keen to find a fix thought. Will give this a go, thank you for the suggestion.

Okay so after having a tinker around I have found a fairly reasonable solution to the problem.Previously my app would instantly enter a infinitely repeating while loop trying to connect to the arduino over serial port as soon as it started, waiting for a successful connection to indicate that the device was connect.

Instead of this automatic repeated connection attempts, I've programmed a 'Connect' button into my apps GUI with a window saying to connect the device before attempting to connect. I think the automatic attempts to connect to the arduino, immediately after launch the app meant that the successful serial connection would happen while the arduino was in some kind of set up phase. By letting the user click connect, there is always some reasonable delay between plugging the arduino into my laptop, and the first attempt at a serial connection being made.

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)

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,

Hey, thanks for the reply! I gave this a go on the Arduino side, but I'm still running into the same kind of problems. One thing I did try was closing the serial connection in python after it is first established. Then re-opening it later when I actually want to start reading data from the Arduino. This change produced a different kind of error. When I try to re-open the serial communication for the second time, I get an error message in my Python console saying: [Errno 16] could not open port /dev/ttyACM0: [Errno 16] Device or resource busy: '/dev/ttyACM0'

source: Stack Exchange

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

sort: votes


text:
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

Are char arrays really so daunting that people go to this length to avoid them?  Why struggle with this when you could just write a char array and be done with it?

You are writing this from a position of beeing an expert about arrays of char, c-strings etc. This does explain nothing to come nearer to the point of enough knowledge to use your preferred way of using "strings". So a much more productive comment would be to explain how it works. Not with a most short and elegant single line of code but with a thoroughly explained example with lots of comments or additional text.

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());

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


text:
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(" <meta charset=\"utf-8\">");
            client.println("
 Nic nove
");
            client.println("<form method='POST'>");
            client.println("Name:<input type=\"text\" id=\"Name\" name=\"Name\"/>
\nSurname:<input type=\"text\" id=\"Surname\" name=\"Surname\">
\n<input type=\"submit\" value=\"Submit\"/><input   type='reset'/>  </form> ");
            client.println("");
          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>
 <meta charset="utf-8">

 Nic nove

<form method='POST'>
   Name:<input type="text" id="Name" name="Name"/>

   Surname<input type="text" id="Surname" name="Surname">

<input type="submit" value="Submit"/><input type='reset'/>  </form>

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

I found that I have to decode a json object, but how do I get it from received data?

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(" <meta charset=\"utf-8\">");
                    client.println("
Fill the form now !!!
");
                    client.println("<form method='POST'>");
                    client.println("Meno:<input type=\"text\" id=\"Name\" name=\"Name\"/>
\nPriezvisko:<input type=\"text\" id=\"Surname\" name=\"Surname\">
\n<input type=\"submit\" value=\"Submit\"/><input    type='reset'/>  </form> ");
                    /*Serial.printf(F("Page source send\n"));*/
                    client.println("\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(" <meta charset=\"utf-8\">");
                    client.println("
Fill the form now !!!
");
                    client.println("<form method='POST'>");
                    client.println("Meno:<input type=\"text\" id=\"Name\" name=\"Name\"/>
\nPriezvisko:<input type=\"text\" id=\"Surname\" name=\"Surname\">
\n<input type=\"submit\" value=\"Submit\"/><input    type='reset'/>  </form> ");
                    /*Serial.printf(F("Page source send\n"));*/
                    client.println("\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");
  }
}

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.
EDITAn 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

Comments are not for extended discussion; this conversation has been moved to chat.


text:
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?

how do you intend to display the GUI?

I plan to have the GUI displayed on my computer monitor.

then, which part of your question is actually Arduino related?

I am searching for pointers on developing a standalone portable program to control the Arduino hardware. The Arduino hardware and Arduino IDE are understood. However, I have not found any examples that use a standalone program to control an Arduino that does not require the use of Arduino IDE on the side. Does this clarify my objective?

I use Java. The only "Arduino" portion is the serial communication to transfer commands and data (which we can help you with), but the GUI has nothing really to do with Arduino.

So, in embarking on this journey, should I learn how to develop a GUI using Java or another language first? Then learn how to incorporate the serial communication to control the Arduino?

you are not correct about this ... Python, and 'Processing', but they seem to require the simultaneous use of Arduino IDE ... google processing arduino serial

The Processing IDE is the one that Arduino "stole" to use for the Arduino IDE. It looks similar but does a completely different job. You should learn a programming language before you start thinking about how to integrate it with an Arduino.

I now know what to do to get started. Thank you all!

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.

+1 for web.  its the way to go for windows and mac.  if you just expose the command interfaces on a socket, you can make as complex a web gui page as you wish hosted elsewhere or on computer.  if hosting on arduino, keep it simple.  by making a command response program on a socket, you are essentially doing the work of php (server side stuff).

languages: C (or C++) for arduino, html and javascript for the gui

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.

This doesn't provide an answer to the question. To ask another question, just click Ask Question above. If you wish, include a link to this question to help provide context.

This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review


text:
Parsing Data from local websever
i´m trying to build a little monitor of an ESP8266 and an OLED display that displayes the Status of a Robotarm.
The robotarm is controled by a RAMPSboard that has a webserver, so i can check the status from a browser.
For that i´m trying to use the BasicHttpClient Sketch from Arduino to read the status and progress.
The problem is i.... don´t know how?
I guess i know where the data is in my HTML document, but i dont know how to call it via GET request.
With the modified BasicHttpClient Sketch i can read the whole html site and print it out on serial, but after weeks of reading and watching tutorials i´m still stucked.
Long story short.
i want to read "just" the status and progress off of that webserver, with a GET request
this is the part of HTML code where my data is...i guess:
here are 3 different times of the informations i´d like to "extract" and displayed on my little ESP8266 monitor
Idle
Working
Done

0% Complete
   //äusseresHTML

1% Complete

22% Complete

and i just need to change that part of the sketch as it now prints out everything of the page:
void loop() {...

     ... Serial.print("[HTTP] GET...\n");
      // start connection and send HTTP header
      int httpCode = http.GET();

      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
----->          String payload = http.getString();   <---as i understand here i ask for everything
          Serial.println(payload);
        }
      } else {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }

      http.end();
    } else {
      Serial.printf("[HTTP} Unable to connect\n");
    }
  }

Hopefully someone has the time to take a look at that and point me to String i need to call.
BTW, i think the main problem why i couldn´t find the answer myself is my english isnt that professional for that kind of stuff, so im doin hard to understand similar tutorials

how is the progress bar updated?  ... are you able to see the update if you use a web browser on a PC?

you cannot get just a part of a web page by using the GET call ... pethaps you could use an XMLHttpRequest ... google http xhr ... as it stands, your question is not really related to the arduino at all

Good morning(from Germany), thank you for your fast answer.   i looked for http xhr and edited my question, i think i clarified my question a little more.as far as i understand this http xhr is for a Server to send status to a client, am i right?

Check the documentation of the RAMPSboard server. There may be a JSON endpoint that provides the data you are looking for in a format more amenable to being consumed by  a program. Failing that, you may want to search for a regex library for your ESP: that is the Swiss knife for parsing text strings.

Thank you, ill have a look at that

open the web page with a web browser ... press F12 (should work for most browsers) .... examine the data that is being sent by the server .... it may already be using xhr ... if it is, then you will see the GET request URL

i would loop though line-by-line, and if i see a smoking gun, process the line further to parse out the values encoded in the html markup using string commands.


text:
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:

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

Your schematic needs some work. For example the connector(?) in the upper right corner, I can't tell what order the pins are in. I can't tell what the names of the resistors are (because they layer on top of each other). There are dangling wires (stubs) and it seems like a lot of spaghetti. There are no capacitors anywhere so that might be an issue.

The upper connector is for power. It is directly pulled into digispark. So is the middle connector. Digispark already provide the capacitors for the power. And yes..It still needs a lot of work. BUT the schematic works. Tested both screens with numbers by directly programming the attiny.

This is driving me crazy. Since I programmed this bootloader nothing works. I think it is software related because the board works..in its way. It is recognized by the pc, I can program it..but it executes nothing it should have.

have you read this? https://digistump.com/wiki/digispark/tutorials/connecting

I programmed the digisprk a hundred times before. It always worked.

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.


text:
Can ultrasonic distance sensor get good readings for a passing object?
I am working on a project where I laid 5 Ultrasonic distance sensors in a string on a rigid wood plank that lays on the ground and points all the sensors upward behind the guy with the bat.
When the pitcher pitches the ball and the ball goes over the sensors, the sensors have to detect the passing ball and compute their distance from the ground to have an idea whether the ball passed within the strike zone.
I ran into the following issues
Issue #1: The ultrasonic distance sensor was giving a lot of "noise", the pulse in was giving some 10-15 different values all the time even when it's just statically placed on the table while looking at the ceiling. Which was computing 15 different distances to the ceiling some of them were far off from the others.
I solved issue #1 by using a "initialization" routine where for first 10 seconds the sensor collects those noises and adds them to an array so it can ignore them later. All good.
Issue #2: The sensors failed to detect a fast moving ball, in fact I had to pass the ball super slow like 2 centimeters per seconds for it to detect it, otherwise there was no reading (may be something wrong with my code).
Here are my questions

Is ultrasonic distance sensor capable of detecting a fast moving object? My initial assessment with a simple pulseIn did show me something that sounded meaningful but that may have been just the noise throwing me off.
What other type of sensors can be good for this type of problems?

Here is my code. My apologies if this ridiculously long and rough sketch is not easy to read.
#include "stdio.h"

const int PIN_TRIG = 9;
const int PIN_ECHO = 10;
const int PIN_WARN = 11;

long distance;
int duration;
long oldDistance;

 int min = 1024;
unsigned int max = 0;
int totalUniques[100];

unsigned int cycles = 0;
bool warnOn = false;
unsigned int warnTime = 0;

bool uniqueCollected = false;

void setup() {
  // put your setup code here, to run once:
 pinMode(PIN_TRIG, OUTPUT);
 pinMode(PIN_ECHO, INPUT);
 pinMode(PIN_WARN, OUTPUT);
 InitializeUniques();

 Serial.begin(9600);

  digitalWrite(PIN_WARN, HIGH);
  warnOn = true;
}

void loop() {

  digitalWrite(PIN_TRIG, LOW);
  delayMicroseconds(2);

  digitalWrite(PIN_TRIG, HIGH);
  delayMicroseconds(15);
  digitalWrite(PIN_TRIG, LOW);

  duration = pulseIn(PIN_ECHO, HIGH);
  distance = duration*0.034/2;

  if (distance < min && distance != 0)
  {
    min = distance;
  }

  if (distance > max)
  {
    max = distance;
  }

 if (uniqueCollected == false)
 {
  int st = AddUnique(distance);

  printWithLabel("Adding unique", distance, "Total Unique Status", st);
  if (cycles > 1000)
  {
    PrintAllUniques();
    uniqueCollected = true;

    warnOn = false;
    digitalWrite(PIN_WARN, LOW);
    warnTime = millis();
  }
  else
  {
    cycles++;
  }
 }

  if (warnOn == true && uniqueCollected == true)
  {
    auto t = millis();
    if (abs(t - warnTime) > 10000)
    {
      digitalWrite(PIN_WARN, LOW);
      warnOn = false;
    }
  }

  if (distance > 150)
  {
    AddUnique(distance);
  }
  if (warnOn == false && uniqueCollected == true && FoundInUniques(distance) == false)
  {
    PrintAllUniques();
    printWithLabel("distance", distance);
    warnOn = false;
    digitalWrite(PIN_WARN, HIGH);
    delay(10000);

    digitalWrite(PIN_WARN, LOW);
   // warnTime = millis();
  }

  if (oldDistance < 0 && distance > 0 && distance < 150)
  {
   // printDistances(1);
  }
  else if (abs(oldDistance - distance) > 30)
  {
  //  printDistances(2);
  }

  oldDistance = distance;

 // Serial.print("Distance: ");
  //Serial.println(distance);

}

void printDistances(int caller)
{

    Serial.print("Something detected in the way");
    Serial.print(caller);
    Serial.print(" old : ");
    Serial.print(oldDistance);
    Serial.print(" new : ");
    Serial.println(distance);
}
void printWithLabel(char* label, int value)
{
   Serial.print(label);
   Serial.print(": ");
   Serial.println(value);
}
void printWithLabel(char* label1, int value1, char* label2, int value2)
{
   Serial.print(label1);
   Serial.print(": ");
   Serial.println(value1);
   Serial.print(", ");
   Serial.print(label2);
   Serial.print(": ");
   Serial.println(value2);
}
int AddUnique(int value)
{

  if (value == 0)
  {
    return -1;
  }
  int i=0;
  for (i=0;i<100;i++)
  {
    if (abs(totalUniques[i] - value) <= 3 || totalUniques[i] == 0)
    {
      break;
    }
  }

  if (i >= 100)
  {
    return -2;
  }
  else if (totalUniques[i] == 0)
  {
    totalUniques[i] = value;
    return i + 1;
  }
  return CountTotalUniques();
}

void InitializeUniques()
{
  for (int i=0;i<100;i++) totalUniques[i]=0;
}

int CountTotalUniques()
{
  for (int i=0;i<100;i++)
  {
    if (totalUniques[i] == 0)
    {
      return i;
    }
  }
}

void PrintAllUniques()
{
  Serial.print("Unique Values :");

  for (int i=0;i<100 && totalUniques[i] != 0;i++)
  {
    Serial.print(totalUniques[i]);
    if (i < 99)
    {
       Serial.print(", ");
    }
  }

  Serial.println(" ");
}

bool FoundInUniques(int value)
{
  if (value == 0)
  {
    return true;
  }

  for (int i=0;i<100 && totalUniques[i] != 0;i++)
  {
    if (abs(totalUniques[i] - value) <= 3)
    {
      return true;
    }
  }

  return false;
}

This doesn't sound very feasible.  In order for it to work you'd have to fire the ping sensor at exactly the right millisecond so that the sound meets the ball directly above the sensor.   Whatever means you use to detect the ball in order to fire the sensor would probably itself be a better option for locating the ball.

@Delta_G What's the harm in firing the sensor every few microseconds? It can't miss the ball unless Nolan Ryan is pitching. Correct?

Because the sensor can't fire that fast.  How high is the ball above the sensor?  How long does it take sound to go that far?  How fast is the ball moving?  How long will it be in the spot above the sensor?

Sound travels at around 1100 feet per second.  So that gets us about 1.1 feet per millisecond.  If the ball is shoulder high then we've got something on the order of 10ms for the round trip before we can safely say we didn't see the ball.  And that's assuming nothing misses high.  So once every ten or fifteen milliseconds you can fire the sensor.    If we're in the little league throwing 60mph then we're at 88 ft/s.  That's 11ms to cross a 1 foot section.   You see where we're going?  That's on the same order as your cycle time for the sensor.  You can't fire fast enough.

@Delta_G "So once every ten or fifteen milliseconds you can fire the sensor", did you mean Microseconds? I am firing every few microseconds.

@fahadash No, he ment milliseconds. It is irrelevant how fast you create a trigger pulse on the Arduino. It needs 10ms to receive the echo of trigger pulse. You need to wait for the echo to arrive, before firing the next pulse, or you will get false readings, because the echo of the first pulse is still to come (also most likely your sensor simply cannot trigger a new pulse before the current pulse is finished

you would be better off detecting the breaking of two planes a know distance apart, and measuring the time between breaks.

If you are firing the pulse every few microseconds and it takes 10ms for the pulse to travel to the ball and back, how will you know which pulse hit the ball?  How will you calculate distance if you don't know which pulse it was?


text:
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?

#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);
  }
}

think about what is the sequence of button states when you press the button twice ... are you checking for all of the states?

You declared ledPin as output, then in the loop you check its status with digitalRead(ledPin). This is not going to work as you intend doing. How is a pin meant to source current, read its own voltage? For that purpose you need a flag representing its state, not the electric state.

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
    }
  }
}

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);
  }
}

Hmm, if I try this, the LED does stay solid after the first press and it doesn't hit my spacebar yet. But when I hit the button a second time, it performes both CTRL + R and the spacebar and the LED stays solid. I think we're on the right trace but there's still some problems.

Well there's no delay or anything after the action in that second if statement like there is on the first one.  My bet is that the loop comes back around and sees that the button is still pressed and catches the first if again.  Look at the State Change Example in the IDE for some inspiration on how to respond to the change in state of the button and not just the fact that it is held down.  Detect the edges.  Only react once per press.

You got me on the right track. I now used press counts. After it its CTRL + R it sets the button press count to 2, and if the value becomes 3 (ie hitting the button a 2nd actual time) it hits space bar, turns off the LED and sets the press count back to 0. Works fllawlessly. THANK U very much!


text:
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.

EEVBlog covered this behaviour with a great explanation of what’s going on: https://youtu.be/2yFh7Vv0Paw

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

It may be "normal" behaviour, but it is far from desired behaviour. Damage to the Arduino can be caused by it as the internal protection diodes get overpowered and blow. Best case: the diodes fail open circuit and you don't notice any difference. Worst case: diode fails short and the pin is permanently HIGH.

The best case is bad too, because it means that pin no longer has a protection diode, and can be burned out. This answer should be edited to say "DON'T DO THAT" in very strong terms.

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.

I agree, that is " a normal error response" // Mikael


text:
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...

Well, in my last job we're using own arduino mega clone with micromatch connectors (much more reliable than the original ones). But we didn't want to integrate it, it's easier to swap or test it (without that 300mm x 250mm board with relays, optotriacs, power supplies and many more.

Maybe a simple Prototyping Shield would be sufficient for you.

I agree with Majenko's proposal for a proto shield, or 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)

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

Big fan of Veroboard - to add I have used VeroDes (https://heyrick.eu/software/verodes/) which is a free CAD tool for Veroboard design!


text:
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.

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


text:
Adafruit 2.8 TFT LCD Touchscreen 4 wire pins - unclear instructions
Warning - Noob question
I am trying to follow the instructions provided by the vendor https://learn.adafruit.com/2-8-tft-touch-shield/touchscreen-paint-example to no avail. Specifically:

We connect the 4 pins as follows:
  Y+ is connected to Analog 1
  Y- is connected to Digital 7
  X+ is connected to Digital 6
  X- is connected to Analog 2

My board looks like this

and I cannot see any X/Y/+/- labelled pins. I then found the schematic of the board
https://github.com/adafruit/Adafruit_2.8_Inch_TFT_Shield_PCB/blob/master/schem.png
where these pins are labeled but what is the representation of the schematic on the board?
Finally, once I do find the pins, how do I connect them if they are already used? Do I have to use a breadboard?
Edit: After the helpful comments of jsotola, I got a photo:

Are these the 4 "pins"? If so, how on earth do I connect these to the arduino?

I thought the touch panel and the LCD are essentially the same thing because they are embedded to each other.

I did try the example, the colored boxes showed up fine but no touch input registers.

@jsotola do you know if I can detach the TFT from the board to inspect the connection of the touch panel? I inherited this arduino / TFT and I do not know the history of its touchscreen. Yes I am using the tftpaint_shield sketch

TFT touchscreen shield https://imgur.com/a/WSMifOu

looks like the touch panel has been removed

Seems really to be as jsotola wrote. The 4 line flat cable, that you marked, was cut. It should go to the touch panel in front of the TFT, but it seems to miss. So no touch detection

Thanks both - well that is the end then of any touchscreen plans. Will keep it as a screen only

buy another touch panel and stick it on the LCD .... https://www.instructables.com/id/Touch-Screen-Overlay-with-Arduino/


text:
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

/*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

Your current code only works exactly one time, because the code can never leave the last while loop in the loop() function. analogValue doesn't change in the while loop, so the condition will always be true.

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.

Thanks very much for your input.  Have a few questions that I don't understand.T

Thanks very much for your input.  Have a few questions that I don't understand.  SENSOR_N    2   // this is stating there are 2 sensors  I would change the 2 to=num of sensors. uint8_t sensor_pins[SENSOR_N] = {A0, A1}; Not familiar with the uint  (I will look up) what is the 8?    Next, all my sensors would have the same threshold, so below the 570 is the threshold and 400 is the steps?    uint16_t sensor_thresholds[SENSOR_N] = {570, 400}; The unit  "16/8"?   I will work on this.  Thanks for taking the time to help me

@Greg I added some notes in my answer to address your questions

chrisl, Thanks again.  That explained much.  I haven't decided yet if I will be using steps or degrees.  If I understand this, using degrees 360 would be the largest number so I could use 16.  Is there a problem with using 16  even if you don't need that much?  I will go to work on this. Thanks so much.  Is it OK if I post or send my completed code to you.  Just getting use to Stack overflow

It no problem to use a 16 bit type, when you only need 8 bits. That's more of a best practice; to use only the memory, that you need, as most AVR based Arduinos (like the Nano) have relatively little memory. Though that is only important, when you are reaching the limit with your program.

About posting the completed code: If the completed code works correctly and you want to share with others to help them with the same problem, you can post the finished code as an answer. If you want us check it for errors it is different. If your code still doesn't work because of a problem directly related to this question, you can add the new code at the end of your question. If it is not closely related, then you can ask a new question about it. If you didn't test it to that point, you should test it first, before asking us to check for errors (searching a needle in a haystack is no fund)

chrisl,  Your code works as describe!  I added additional Analog inputs and tested them. I can't fix 2 issues (may be the same)  Need to disable stepper after it moves. If I don't it will overheat the driver, I don't need  to hold position. If I use the Disable() it rotates every time the loop is done, or if no tool is turned on it pulses the stepper, (think this is enable/disable every loop.  Also need to ignore the same sensor if it was the last one detected.  Many times I will use the same tool repeatedly, need it to remain Disabled until it see a different sensor.  Thanks as always.

If i go to a encoder for the stepper might solve my problems.  As i understand a encoder it knows and remembers where its at.  So if I use the same tool repeatedly it should stay in the same position.  Should rotate to the new position.  Am I thinking right and do I need to add code for the encoder.  As a alternate I could add senors to detect that the sensor is in correct position.

chrisl, like most,  2020 has had many obstacles, but I'm back at it and have made progress.


text:
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 -
    #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?

What device are you using? Some board vendors print the GPIOnum (which is different from the pin num) to the silk screen, some times a vendor uses a different layout than the reference design so you have to look up in the circuit diagram (if you get/have it) - I know the "search" for the SCLK pin and other mappings ;-)

I'm using esp32 wroom. Yes, I know that gpio 5  (pin 29)is chip shredder, gpio 18(pin 30) is clock pulses etc using vspi.i am getting those toggling pulses on gpio5 but am not able to see any transfer of data. I.e clock pulses on gpio18 or pin 30

Try to set the pins explicitly to Output
EDITDifferent 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.

tried the same, but it did not work. I even changed the syntax to pinMode(18, OUTPUT) as pin 30 gpio 18. If you do have an ESP32, can you try it too?

thanks - ive tried changing clock speeds too with no luck. Were you able to  try it?


text:
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!

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.

Thank you this worked! looked like it was a problem with my libraries!


text:
SHT30 activating Fan control
I've a working hardware setup and two codes 1 to read the sht30 and push the data to my tft screen.
And 2 a code to set a fan (2fans) on and off.
I want to combine these whenever the humidity is over 50% the fans should go on.
3 issues arise.

less important my serial.println() doesn't print anything anymore
my second if loop doesn't get printed not in serial or in display
Fans are not getting activated by the code.

My searching leads me to think I need to convert my sht30.humidity into an int before making the if loop.
Or it could be something entirely else ofcourse.
#include <WEMOS_SHT3X.h>

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

Adafruit_SSD1306 display(1);
#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

SHT3X sht30(0x45);

void setup() {
  Serial.begin(115200);
  pinMode(14, OUTPUT);
  // initialize with the I2C addr 0x3C
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.display();
  delay(1000);
  Serial.print("start");
  // Clear the buffer.
  display.clearDisplay();
}

void loop() {

 // Clear the buffer.
  display.clearDisplay();
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.setTextColor(WHITE);

  if(sht30.get()==0)
  {
    display.setCursor(35, 10);
    display.println("T: ");
    display.setCursor(50, 10);
    display.println(sht30.cTemp);
    display.setCursor(35, 20);
    display.println("H: ");
    display.setCursor(50, 20);
    display.println(sht30.humidity);
  }
  else
  {
    display.setCursor(35, 10);
    display.println("Error!");
    Serial.println("error");
  }
  display.display();
  delay(1000);

  Hcheck();
  Serial.println("checking humidity");

}

void Hcheck() {
  delay(5000);
  Serial.println("============ Check Humidity ===============");
  display.clearDisplay();
  display.setCursor(35, 10);
  display.println(sht30.humidity);
  display.display();
  delay(1000);
  Serial.println(sht30.humidity);

  if(sht30.humidity <= 50 ) {
    digitalWrite(14, HIGH);
    display.clearDisplay();
    display.setCursor(35, 20);
    display.display();
    delay(500);
  }else {
    digitalWrite(14, LOW);
    delay(500);
    Serial.println("Air is dry");

  }

  }

Are you sure, that the I2C communication works? You can check, if the lines are HIGH most of the time. If one of them is constant low, the problem is a stuck I2C bus

are you saying that start does not print when you reset the ESP8266?

If my sht30 works and the tft screen works I2C must work correct? It's the pwm signal that doesn't work. @jsotola Nope not a single serialprintln works so I guess something else is wrong here...?

put Serial.print("start"); right after Serial.begin .... try to narrow down where the program hangs up


text:
Unable to understand the acquisition of data from Magnetometer HMC5883L and Accelerometer ADXL345
Below are the X,Y,Z registers for HMC5883L.

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

use the datasheet to determine the correct way to retrieve data from the device

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.