text:
Servo FS5106B does not work properly
I was testing out my new Servo FS5106B. Here is the code I used:
#include <Servo.h>

Servo servo;
void setup()
{
    servo.attach(10);
}

void loop()
{
    servo.write(0);
    delay(1000);
    servo.write(180);
    delay(1000);
}

After I upload the sketch, the console says:

Sketch uses 2872 bytes (1%) of your device memory. Total available 253952 bytes. Global variables use 161 bytes (1%) of the dynamic memory, leaving 8031 bytes for local variables. Maximum 8192

The delay between the rotations wasn't 1 second (as I was expecting), but 13 seconds (when I connect only a LED and use the delay function, everything works perfectly). Why is that happening?
P.S The power source for the servo is my Arduino-Mega 2560, wich outputs 5V. The model I use for wiring is:
Edit 1:
I tried to execute the program that @ChrisStratton suggested, here an updated code
#include <Servo.h>
#define led 22

Servo servo;

void setup()
{
    Serial.begin(9600);
    while(!Serial)
        delay(10);

    Serial.println("Start!");
    pinMode(led, OUTPUT);
    servo.attach(10);
}

void loop()
{
    digitalWrite(led, HIGH);
    servo.write(0);
    delay(1000);
    digitalWrite(led, LOW);
    servo.write(180);
    delay(1000);
}

When this program loads, servo does 2 rotations in 0.4 seconds and the LED goes high and low really fast, then anything changes for another 10 seconds, then again the LED goes high and low and the Servo does 2 rotations

Please give a small but working sketch. I can not compile this. The stall current of the FS5106B is about 1A, the Arduino 5V pin can not supply that.

It is critical that your post contain the exact code tested.  Obviously the posted code cannot build, which means it could not have been tested.  You need to use the "edit" button to post the exact code you tested, and you need to include a description of your wiring and the power source for the servo.  But before you do any of that, make an experimental version which blinks an LED at 1 second intervals without any connection to a servo, and make sure that interval is approximately correct.

@Jot Changed my code

@ChrisStratton Changed my code to the one I was testing with exactly

And the rest of what is missing?

@ChrisStratton It is the hole code

Reread, it's not just code that was missing from your post.  And there was an experiment you were supposed to run.

@ChrisStratton Modified my answer, was this what you meant?

No, please reread the original two comments.

@ChrisStratton Added everything you asked for. Excuse me for not reading your full comment

In the official Arduino examples, a servo motor is powered by the 5V pin of the Arduino board. In real life, that is a bad idea.
Your FS5106B has specified about 1A stall current. The average current is less than that, but the start peak current could indeed be 1A.
Could you try to use a seperate power supply of 5V (or 6V) for the servo motor ?
To check if the Arduino resets, you could do a Serial.begin(9600); in setup, directly followed by Serial.println("the sketch has started");
Some servo motors require different timing. That would not explain the 13 seconds delay, so I assume that your servo motor has normal timing.
Do you use a breadboard ? Sending a current peak through a breadboard (with bad contacts) can cause a lot of voltage spikes.
(To the other problem solvers: I'm ignoring the 13 seconds and assume that once in a while the servo motor is able to start, just a guess, I could be wrong).
[ADDED]
@ChrisStratton is trying to tell you this:
void setup()
{
  pinMode( LED_BUILTIN, OUTPUT);
}

void loop()
{
  digitalWrite( LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite( LED_BUILTIN, LOW);
  delay(1000);
}

The next step would be:
#include <Servo.h>

Servo servo;

void setup()
{
  Serial.begin(9600);
  Serial.println("The sketch has started");
  pinMode( LED_BUILTIN, OUTPUT);
  servo.attach(10);
}

void loop()
{
  servo.write(0);
  digitalWrite( LED_BUILTIN, HIGH);
  delay(1000);

  servo.write(180);
  digitalWrite( LED_BUILTIN, LOW);
  delay(1000);
}

[ADDED2]
Or even more fun, with a counter (as @ChrisStratton wrote):
#include <Servo.h>

Servo servo;

unsigned int counter;

void setup()
{
  Serial.begin(9600);
  Serial.println("The sketch has started");
  pinMode( LED_BUILTIN, OUTPUT);
  servo.attach(10);
}

void loop()
{
  servo.write(0);
  digitalWrite( LED_BUILTIN, HIGH);
  delay(1000);

  servo.write(180);
  digitalWrite( LED_BUILTIN, LOW);
  delay(1000);

  Serial.print("Still alive after ");
  Serial.print(counter);
  Serial.println(" seconds");
  counter += 2;   // two seconds per loop iteration
}

The serial output on start is a good idea, but if the servo motor is causing the arduino to brown out, depending on if the USB port / chip are also involved, the serial device may keep dissapearing and so subsequent output may not be obtained. It might be better to have the Arduino print out "still alive after " and a running count - that way the messages would indicate success in the case where they could be seen. This could then be run with the motor removed from the circuit, with it powered by an external supply having only a common ground, or (dubiously) with Arduino/USB power.

@ChrisStratton Tried your suggestion, modified my question.

You were supposed to try it first without the servo connected.  Also you don't seem to be monitoring the serial output Jot suggested, but it would be even better if you generated output in between each operation in the loop.

@ChrisStratton I tried it without the servo connected and it worked. I actually wrote it in my question > (when I connect a LED and use the delay function, everything works perfectly)

Sounds like you have a power problem. As we've been saying, you shouldn't try to power a servo through an Arduino.

@ChrisStratton I tried another power supply (6V), and it did not work either. Do you think the servo is broken?


text:
Are the output pins on the 74HC595 shift register protected against shorting?
In the following schematic you can see that Q1 and Q4 both are connected to a Arduino's Digital Input Pin. So if Q1 is high and Q4 is low, would there be current flowing from Q1 through Q4 (and through the chip) to Ground - or is there already some protection inside?

Are the output pins on the 74HC595 shift register protected from connected voltages in the realms of their own VCC? Or do you need to put a diode in?

I feel like this is a very basic question, which makes it very weird that I didn't find an answer to this, already... :-( Am I looking into the wrong resources? I had a look into the provided datasheet, but couldn't find any information. Didn't get any results from searching for existing posts on Stack Exchange or other sites.

In this data sheet it says:

When the output-enable (OE) input is high,the outputs are in the
  high-impedance state.

However on page 3 you will notice that the *OE pin controls all outputs at the same time.  So if you connect 2 output pins and one is high and the other is low and you hold *OE low ... you will likely burn out the driver for one of the 2 output pins if not the chip its self.
If you add diodes to BOTH outputs you are essentially creating a wired or gate.  (You should add a resistor.  See the examples in the provided link.) This is fine as long as you understand how a wired or gate works.

Thank you :-) However, this causes a follow-up question: under 10.2.2 in this datasheet it says "Outputs should not be pulled above VCC." I understood this as: outputs (in LOW) can be pulled up (for example by another output in HIGH) as long as it's not above VCC. If that's not what this sentence from the datasheet means, what does it mean then?

it means that when the output is in a high impedance state (OE pulled high) if you take the pin to a higher voltage than vcc you will damage the IC. if the OE pin is enabled and you try and drive it to any state other than the voltage its alreay at, you are creating a short and would also damage the IC.

@JamesKent Ah, of course... I forgot about OE, again. (It's always pulled LOW in my circuit.) So that makes sense now. Excellent. Thank you very much. :-)

source: Stack Exchange

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

sort: votes


text:
How do I choose proper diodes for a 74HC595 shift register with a wired OR connection?
I want to use a wired OR connection to connect some pins of the 74HC595 shift register to an Arduino Digital Input Pin. How do I choose proper diodes for this situation?

Maximum rated forward current has to be higher than whatever current a single pin of the 74HC595 produces.
The V_F forward voltage drop has to be as low as possible to make sure that a HIGH from the shift register has still a voltage high enough to result in a HIGH at the Arduino pin after passing through the diode.
Switching time has to be low enough to match the shift register's frequency.

So far, so good? What did I miss?
By the way, I haven't decided on the voltage for VCC, yet. Most likely, either 5 V or 3.3 V.

Why?? Your "requirements" are contradictory; RTL went out of vogue in the early 1960s precisely because it was slow (among other problems). You have not specified the frequency, but it is unlikely to be so high that you need to worry. This also is not an Arduino question?

@Milliways Thank you for your comment. :-) You seem really taken aback by my question. I'm just getting started with electronics and Arduino, so it's fairly probable that I'm approaching something the completely wrong way. With RTL, do you mean Register-transfer_level? I'm having problems understanding the correlation. Could you elaborate, please?

Concerning the relevance towards Arduino, I was thinking that the microcontroller on hand plays a part in choosing the proper diode. Despite the diode's voltage drop, I still have to reach the HIGH logic level for exactly this microcontroller. Isn't this dependent on which microcontroller is being used?

For this, almost any diode will work.  Searching, it turns out that the 1N4148 is a popular ubiquitous choice.  But don't go out of your way to obtain this particular diode.

Maximum rated forward current has to be higher than whatever current a
  single pin of the 74HC595 produces.

You should turn your thinking around.  Consider the nominal high voltage of the 74HC595, subtract the forward bias diode voltage drop (usually  0.7V for a silicon diode) and divide that by the resistor you pick.  That will be the current passing out of the 74HC595, through the diode and resistor.  Only a small amount of current will pass into the Arduino.  It should be negligible for most applications.  You should pick a resistor high enough to only allow milliamps of current to pass through this circuit.

The V_F forward voltage drop has to be as low as possible to make sure
  that a HIGH from the shift register has still a voltage high enough to
  result in a HIGH at the Arduino pin after passing through the diode.

Check the voltage margin allow for a logical high input to the Arduino (Atmel processor).  I think 3V - 0.7V = 2.3V is still considered a logical high.  However, if you think this is too close, then switch to the 5 volt Arduino where the 0.7 volt drop will make less difference.

Switching time has to be low enough to match the shift register's
  frequency.

I doubt this will be a problem.  That is, I doubt the CMOS logic will surpass the speed at which the diode can turn on / off.

Isn't there a very short period of time, when a diode in front of a former HIGH pin (now LOW) is still conducting and now allows for a short into this now LOW pin?

There might be.  But I believe it will not be noticeable relative to the time it takes for a CMOS device to charge up and start conducting or discharge and stop conducting.  Almost all logic chips use CMOS like technology these days.

Aah, I might be getting somewhere now. You're saying the shift register needs some time to switch from LOW to HIGH as well - and this time is enough time for the diode to switch to reverse biased?

That almost right.   A computer designer is interested in something called propagation delay.  Every "gate" (which is made up of transistors and in some cases diodes) contribute to the over all propagation delay.  There are dozens of gates in the shift register.  So there is significant delay between the shift register's clock input changing and the shift register's outputs changing.  The software program you write for the Arduino and hard ware you are designing will have to work in harmony to pull this off.  Adding diodes as you have done will add an insignificant amount of propagation delay.

After reading about propagation delay, this seems important to explain that the additional diode won't "affect the signal". (So thank you very much for introducing me to this technical term!) However, I feel terrible for suggesting this, because your answer helped me so much already - is it possible you misunderstood my follow-up question? There is a short period of time which the diode needs to switch from forward bias to reverse bias. Isn't it possible, that current flows through this still forward biased diode (during its switching time) into the (now LOW) output pin, and harm the IC?

You are now asking questions that are dealt with in introductory college level logic classes.  I can not imagine how including a Wired Or Gate using diodes and a properly selected resistor can cause damage.  Nor can I image how the diode switching bias delay is significant with respect to charging the capacitance load naturally found at the input of CMOS based logic chips and processors. As such you may ask why the circuit you added is not more common.  Power consumption.  When any of the shift register's outputs are high, a current flows through the resistor and that power is wasted as heat.

"Only a small amount of current will pass into the Arduino. " Yes, only 1uA max per the datasheet.

That is not the current that is wasting power.  The current that is wasting power occurs when any of the shift register output pins are pulled high.  Then the current flows through the diode connected to that pin and through the resistor to ground.  That said, you can reduce power loss by choosing a larger resistance.  But a larger resistance will allow more noise which can affect the input to the Arduino in unexpected ways.

I should add that the amount of current (likely a couple of mA) we are talking about here doesn't make all the much different in a plug in project.  But it starts to affect battery life a in portable project.

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

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


text:
Is there anything wrong with this code
Hi I'm pretty new to cpp.
Could someone review my code and explain any pitfalls or problems?
Below is the code and an example to read from a flow meter with a hall sensor.
Thanks in advance.
Greg
    /** example
    #include "flow.h"
    Flow f(3);
    Flow f2(4);
    volatile unsigned int counter;
    void flow_counter() // ISR
    {
          // Increment the pulse counter
          counter ++;
    }

    void setup()
    {
      f.start(); //using default ISR
      f2.assign_isr(&flow_counter);
      f2.assign_counter(&counter);
      f2.start();
    }

    void loop()
    {
     Serial.printf("flow rate on 3 = %f \n",f.rate());
     Serial.printf("flow total = %dml %f%% of 500ml \n",f.total_ml(),f.percent(500));
     Serial.printf("flow rate on 4 = %f \n",f2.rate());
     delay(1000);
    }

    */

    #include <math.h>
    #include "Arduino.h"

    volatile unsigned int flowPulseCounter;
    void flowCounter() // ISR
    {
          // Increment the pulse counter
          flowPulseCounter ++;
    }

    class Flow{
      public:
        Flow(uint8_t pin)
        {
          if(flowPin==254)
           flowPin = pin;
        }

        void assign_isr ( void (*isr)()){ this->flowISR = isr; };
        void assign_counter (volatile unsigned int * counter ){ this->counter = counter; };
        void assign_pin(uint8_t pin){ flowPin = pin; };

        void  set_calibration_factor( float factor ) { this->calibrationFactor = factor; };
        float get_calibration_factor( ) { return this->calibrationFactor; };

        uint8_t retrieve_pin(){ return flowPin; };

        void start()
        {
          detachInterrupt(digitalPinToInterrupt(this->flowPin));
          *this->counter = 0; // counter is a pointer so * assigns the value at that address to 0
          this->flowRate = 0;
          this->flowMillilitres = 0;
          this->flowMilliseconds = millis();
          pinMode(this->flowPin, INPUT_PULLUP);
          this->running = true;
          attachInterrupt(digitalPinToInterrupt(this->flowPin), this->flowISR, FALLING);
        }

        void calculate()
        {
          if(this->running)
          {
            this->flowRate = ((1000.0 / (millis() - this->flowMilliseconds)) * ( *this->counter )) / this->calibrationFactor;
            this->flowMilliseconds = millis();
            // convert to millilitres.
            this->flowMillilitres = (this->flowRate / 60) * 1000;
            // Add the millilitres to the cumulative total
            this->totalMillilitres += this->flowMillilitres;
          }
        }

        void stop()
        {
          detachInterrupt(digitalPinToInterrupt(flowPin));
          this->calculate();
          this->running = false;
          pinMode(this->flowPin, INPUT_PULLUP);
        }

        bool is_max( uint32_t millilitres )
        {
          this->calculate();
          return (this->totalMillilitres >= millilitres) ? true : false;
        }

        float percent( uint32_t millilitres )
        {
          this->calculate();
          return (float)((double) this->totalMillilitres / (double) millilitres)  * 100.0;
        }

        float rate ()
        {
          this->calculate();
          return this->flowRate;
        }

        uint32_t total_ml()
        {
          this->calculate();
          return this->totalMillilitres;
        }

      private:
        uint8_t flowPin=0;
        uint32_t flowMilliseconds = 0;
        float flowRate=0;
        uint32_t flowMillilitres = 0;
        uint32_t totalMillilitres = 0;
        float calibrationFactor = 4.5;
        bool running = false;
        void (*flowISR)() = &flowCounter;
        volatile unsigned int * counter = &flowPulseCounter;
    };

Why is the entire first section commented out?

@chrisl: It's a library. The comment block is an example of how to use it.

The only problem I can see is in your use of the counter variable. This is a volatile variable that is incremented in an interrupt routine and read from the main loop context.  The variable is "non atomic" in that it is made up of a number of smaller bytes (at least on 8 bit Arduinos it is) which means it takes multiple sequential instructions to read it from memory.
At any point during that sequence the interrupt could trigger and modify the value, corrupting your data.
You should always use a critical section around any accesses to variables that are modified inside interrupt routines, such as:
noInterrupts(); // Disable interrupts
uint32_t currentCount = this->counter; // Grab the current count
interrupts(); // Re-enable interrupts

// Do things with currentCount instead of this->counter

re:You should always use a critical section around any accesses to variables that are modified inside interrupt routines, such as:
As the variable is volatile and thus explicitly read every time why is this necessary. Killing the interrupts breaks so much other stuff.

Because, as I said, it is not atomic. That means that the variable can change while it is being read because it is not one single operation but a sequence of smaller operations.

And you always keep the critical section as short as possible so as to reduce the impact of temporarily disabling interrupts, which in this instance should be zero impact.

Sorry @Majenko I was rushing out to work and didn't read your comment properly.

Here is what I propose as a solution. I am happy to be wrong though.           uint32_t this_count = count;             uint32_t count_check = count;             if((this_count>>3)!=(count_check>>3)               return -0.0; // I like this return as it allows for valid 0 values to be returned as well              // valid read ie. all but the last 3 bits match allowing some advancement in the counter

While I understand your thinking I don't totally agree.
Yes it may be correct for an 8bit single thread environment as are many AVRs it is not always the case.
I don't like the idea of having an interrupt disable section hidden inside a class.
Working with the esp32 (ie. multiple cores and a very simple multi-thread system) the possibility of breaking many things increases.
Also if I run several instances of the class they could interrupt each others counters.

@Yardie: 1. If you publish a library that only works on the ESP32, you should document this limitation, and have a conditional #error directive in the header that prevents anyone from using it on another platform. 2. This critical section is so tiny it will have no impact. If the pulses come so fast that it does have an impact, your program will be unable to process them anyway.

@Yardie It's not "my" thinking: critical sections have been around since the dawn of computing. Nothing in your question says you want to use an ESP32, and since this is the Arduino site we have to assume, unless you tell us otherwise, that you are using an Arduino. And since the majority of Arduino boards are 8 bits it's safe to assume that a critical section will be required. If your do happen to want to use some other board then you have to take the action appropriate to that board. For a 32-bit board it may well be that the operation is atomic and no action ...

... is required. But of you want to publish your library for others to use you cannot assume that they will all want to use an ESP32. You will need to take appropriate steps to craft a suitable critical section for those boards that require them (all non-32 bit boards for sure, and maybe some 32-bit ones as well). For that defining your own macros that change depending on what is being compiled for will be useful. Also depending on the target architecture you may be able to use a more fine grained critical section whereby you only disable the interrupt that you are working with, rather ...

... that disabling them globally. But in general, to allay your fears about critical sections, when interrupts are disabled any interrupts that would occur would generally be deferred until the interrupts are re-enabled again, at which point they will then be handled. And if your critical section is only a handful of clock cycles long and interrupts only occur with thousands of clock cycles between them then the impact of the critical section is going to be non-existent.

Ok thanks guys.

Yes you are right however code for Arduino now needs to consider the ESP. I am working with both and write code primarily for myself. If I was to publish the code this post is the only place I would publish it. I have gained a lot from free software and like to put back when I can. That's all. I love my ATTinies and want to write something that works for both. I was simply trying to cover both possibilities. Stopping the whole interrupt system to read a variable has always bothered me. However reading your last comment Majenko that does allay this and clarify my misconception

I have investigated enough low level code to see some rather nasty assumptions and oversights. I wanted to avoid that in my code even if it is just for me.

Anyway thanks heaps everyone your help has been fantastic and very enlightening. Sorry if I have offended anyone in any way. It was never intended. No one was born with this knowledge and we all travel different paths. Thank you for sharing your knowledge

Edgar I could never publish this code anyway. It's basically your code now anyway. :) Thanks. I now have a simple library to easily add a flow meter to an attiny or an esp32. That's all I wanted. Oh and a deeper understanding of the issues involved as well.

Here are some random comments from looking at the code.
First issue, which is more about the example than the library itself:
there is no Serial.printf() in the standard Arduino cores. Yes, it is
provided by some alternate cores, and it is a shame it is not available
in the Arduino ones, but that's how it is.
In the constructor, there is if(flowPin==254). Why this condition?
flowPin is initialized to zero, so it would seem the condition should
always be false.
As a matter of style, you can remove all the this-> from the methods.
It is implicit anyway.
For the sake of naming consistency, I would rename retrieve_pin() as
get_pin(), and all the assign_*() method as set_*().
It is not useful to detachInterrupt() right before
attachInterrupt(), as the latter implies the former.
In calculate(), avoid calling millis() twice. You have no guarantee
that both calls will return the same value and, if they do not, the
timing calculations will be off. Also, this function will fail badly
(division by zero) if called twice within the same millisecond.
It makes no sense to convert a flow rate to milliliters. Do you mean
milliliters per minute? Per second? In any case, you here converting a
rate to another unit, but it is still a flow rate.
The computation of totalMillilitres is wrong: it is incremented by a
flow rate. It should instead be incremented by a product rate × time. Or
better yet: compute it from the pulse count, without going through the
rate. Otherwise you are computing a numerical derivative (to get the
rate) only to integrate it later (to get a total volume). This extra
computations serve no purpose other than accumulating rounding errors.

Edit: Thinking further about this program, I found a few more things
that I think could be improved. A couple of minor points an one not so
minor.
One of the minor points is that begin() would be a better name for
start(), for consistency with most other Arduino libraries.
Another one is that there are a couple of methods that have no business
being in the class: is_max() and percent(). They are trivial
calculations that are in no way related to handling a flow meter. As a
user of the library, I would rather write
if (flow.total_ml() >= threshold_volume) ...

than
if (flow.is_max(threshold_volume)) ...

as the former is way clearer and easy to understand.
The more serious point is about the handling of multiple flow meters.
The first one is completely handled by the library, which is nice.
However, for the second one, the user has to provide the lowest level
bricks. The user of a library should not have to handle himself such
low-level details. Thus, I think both the counter variable and the ISR
function should be handled by the library, as members of the Flow
class.
I am aware this creates some difficulties. In order to be attached to an
interrupt, the ISR should be a static method of the class. In order for
this method to access the counter, that counter should be a static
member. In order for each flow meter to have its own counter, we must
have a separate class for each one.
I found a solution that I think is elegant enough: have Flow be a
class template, parametrized by the pin number. This creates a
separate class for each flow meter. In order to avoid code duplication,
these classes could be almost empty shells that delegate as much as
possible to a handler which is a common, regular class.
Here is what that “handler” class could look like. It has everything
but the ISR:
class FlowMeterHandler {
    // Everything here is private, only accessible to the Flow class.
    template<uint8_t pin> friend class Flow;
private:
    void begin(uint8_t pin, void (*isr)()) {
        attachInterrupt(digitalPinToInterrupt(pin), isr, FALLING);
    }
    float flow_rate() {
        uint32_t now = millis();
        if (now - last_millis >= 10) {
            uint32_t this_count;
            noInterrupts();
            this_count = count;
            interrupts();
            last_flow = calibration * (this_count - last_count)
                                    / (now - last_millis);
            last_millis = now;
            last_count = this_count;
        }
        return last_flow;
    }
    // + other methods...
    volatile uint32_t count = 0;
    uint32_t last_count = 0;
    uint32_t last_millis = 0;
    float last_flow = 0;
    float calibration = 1e3 / 4.5;
};

I've written the methods inline, but you could also put the
implementations in a separate .cpp file.
And here is the template class. Save for the ISR, it forwards everything
to the handler.
template<uint8_t pin> class Flow {
public:
    static void begin() { handler.begin(pin, isr); }
    static float flow_rate() { return handler.flow_rate(); }
    // other methods also forwarded to the handler...
private:
    static FlowMeterHandler handler;
    static void isr() { handler.count++; };
};

template<uint8_t pin> FlowMeterHandler Flow<pin>::handler;

Note that the class has no instance data: everything in it is static.
Here is how this would be used:
Flow<3> f1;
Flow<4> f2;

void setup()
{
    f1.begin();
    f2.begin();
}

void loop()
{
    Serial.print(F("flow rate on 3 = "));
    Serial.println(f1.flow_rate());
    Serial.print(F("flow rate on 4 = "));
    Serial.println(f2.flow_rate());
    delay(1000);
}

Thank you I have to go to work now but will check this properly after. Thanks Edgar

Edgar this is gorgeous very elegant. I still don't like the
noInterrupts();
this_count = count;
interrupts();

the if(flowPin==254) was left over from an earlier attempt at multiple instances which I didn't finish fleshing out sorry that was a red herring

I also like your thinking withif (flow.total_ml() >= threshold_volume) makes everything very simple.

@Yardie: Re “I still don't like the noInterrupts(); ...”: avr-gcc has the ATOMIC_BLOCK() macro which encapsulates this interrupt masking in an arguably semantically clearer way. It is, however, AVR-specific, and thus not suitable in a wider Arduino context. AFAIK, the Arduino core provides nothing better than noInterrupts()/interrupts() for atomic access to variables.

Ok so if anyone is interested here is what I ended up with
/*
  this is yet to be varified but comes from the following links
  *
  https://www.bc-robotics.com/tutorials/using-a-flow-sensor-with-arduino/

  "These are not able to monitor a flow of less than 1 liter per minute or in excess of 30 liters per minute.
  The sensor is rated to a Maximum of 2.0MPa (290 PSI) "
  and
  every rotation means 2.25mL of fluid has passed the sensor

  another is

  https://diyhacking.com/projects/FlowMeterDIY.ino
  "// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
   // litre/minute of flow.
  "

  then finally

  https://arduino.stackexchange.com/questions/84578/is-there-anything-wrong-with-this-code

  I make no personal claim to any of this code. It is simply my version of Edgar's version.
  Thanks Edgar
  *
  *
  *
  * I have used start and stop as they signify the start and stop of the process
  * the class begins when it starts and has no end the isr stays linked to the class for the duration
  * and start simply attaches the interrupt to the isr
  * stop simply calculates the total volume and detaches the interrupt.
  *
  * as flow rate related to time
  * just set your own start time
  * read the total_ml
  * then after your own predefined time
  * read the total_ml again
  * and work out the flow rate from that.
  */

class FlowMeterHandler {
  // Everything here is private, only accessible to the Flow class.
  template<uint8_t pin> friend class Flow;
private:

  void start(uint8_t pin, void (*isr)())
  {
    noInterrupts();
    count = 0;
    interrupts();
    attachInterrupt(digitalPinToInterrupt(pin), isr, FALLING);
  }

  void stop(uint8_t pin)
  {
    detachInterrupt(digitalPinToInterrupt(pin));
  }

  unsigned int count_is()
  {
    unsigned int this_count;
    noInterrupts();
    this_count = count;
    interrupts();
    return this_count;
  }

  volatile unsigned int count = 0;
  unsigned int ul_per_tick = 2250;

};

template<uint8_t pin> class Flow {
public:
    static void start() { handler.start(pin, isr); }
    static void stop() { handler.stop(pin); }
    static unsigned int total_ul() { return handler.count_is() * handler.ul_per_tick; }
    static unsigned int total_ml() { return ( handler.count_is() * handler.ul_per_tick ) / 1000 ; }
    static void set_ul_per_rotation( unsigned int ul) { handler.ul_per_tick = ul; }
private:
    static FlowMeterHandler handler;
    static void isr() { handler.count++; };
};

template<uint8_t pin> FlowMeterHandler Flow<pin>::handler;

the example ino looks like this
#include "flow.h"
Flow<3> f1;
Flow<4> f2;

void setup()
{
    f1.start();
    f2.start();
}

void loop()
{
    Serial.print(F("So far volume on 3 = "));
    Serial.println(f1.total_ml());
    Serial.print(F("and the volume on 4 = "));
    Serial.println(f2.total_ml());
    delay(1000);
}

Compiles cleanly on all my boards.
Runs ???
Any other suggestions will be gratefully received.
Thanks.
Greg

Note that it is not useful to store total_ml inside FlowMeterHandler, as it is only ever used right after being set. That could instead be a local variable of ml(), or even be removed altogether: float ml() { return count_is() * ml_per_tick; } Also, it is not useful to call ml() from stop().

Edgar thanks yep you are totally correct. They were unfinished/unnecessary ideas. Don't like redundant code either. I guess I've gotten sloppy self debugging for so long. These are the things I usually find months/years later. Why the hell did I do that? I have asked myself many times. Nice to have someone looking over my shoulder for a change. I changed the code tosuit.

probably could have just done return handler.count_is() * handler.ml_per_tick; in the template.

getting rid of the floats could speed it up a little. Using microlitres instead of ml.

It's hard to answer without any description of the actual problem.
On the top of my head, with that much code i'd consider starting off by creating a separate class declaration, and write your member definitions outside. It will make the code way more manageable, and easier to troubleshoot.
https://www.learncpp.com/cpp-tutorial/class-code-and-header-files/
Also, you have several include statements in at least two different places. They usually go first in a file, along with include guards. If your code consists of separate files, please make that clear to readers.

Re: the includes - I thought that at first too, until I noticed the first includes are inside a big comment.

I see it now. How do you make the snazzy color formatting, by the way?

You wrap it in something I can't type here ;) - backtick-backtick-backtick-c++ and backtick-backtick-backtick

I added the language specifier after the tripple-ticks in the question.  Seemed to have tripped enough people.  Sometimes without it the system doesn't syntax highlight or chooses the wrong language type.  You can see in the difference in the edit history.

```c++ [code]```

Excellent that is exactly the sort of answers I was after thankyou. The static ISR issue was particularly anoying to me.

@Erik sorry I thought the  /** example part and having it commented out would make it clear enough

Thank you @timemage for adding the language specifier. It certainly helps clarify the question

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


text:
How do I switch between while loops before the current loop finishes? IR Remote + LED's
I have a project that requires rotation of a tank tread. I've simulated LED's to go off in a rotation using an IR Remote. I want to stop the clockwise rotation halfway through so I can immediately rotation counterclockwise.
Unfortunately, my code waits until after the complete rotation (or the complete while/if loop) to move into the ccw rotation loop. How do I code this to immediately switch between loops?
Here is my code:
#include <IRremote.h>

int RECV_PIN = 10;
int Switch = 10;
IRrecv irrecv(RECV_PIN);
decode_results results;

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

  pinMode(2, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);

  irrecv.enableIRIn();         // Start the receiver
}

void loop()
{
  if (irrecv.decode(&results))
  {
    Serial.println(results.value);
    irrecv.resume();           // Receive the next value
  }

  while (results.value == 16615543)     // button 2: clockwise rotation
  {
    digitalWrite(2, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(9, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(3, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(2, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(4, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(3, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(5, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(4, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(6, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(5, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(7, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(6, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(8, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(7, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(9, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(8, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)
  }

  while (results.value == 16580863)     //power button - break other loops and wait for next IR transmission
  {
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    digitalWrite(5, LOW);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
  }

  while (results.value == 16619623)     // button 8: ccw rotation
  {
    digitalWrite(9, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(2, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(8, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(9, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(7, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(8, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(6, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(7, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(5, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(6, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(4, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(5, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(3, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(4, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(2, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(3, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)
  }
}

Regarding your parenthetic comment in the original edit, the thing you were missing formatting-wise was sequence of three backticks to quote the code.  There is built-in help through an icon (a question mark with a circle) in the upper right when you're editing.  I ran your code through an auto-formatter and manually collapsed a lot of the double-spacing.

In addition to Majenko's answer, what you should use is a so called State engine.
First you define an enum:
enum EState { Off, Clockwise, CounterClockwise };

EState _state;

In setup you set  _state to some default value.
In loop you check for button changes, and set the state accordingly.
Then you act on the state:
switch (_state)
{
case EState::Off:
    {
        // Switch all off
        for (int n = 0; n < 9; n++)
        {
            digitalWrite(n, LOW);
        }
    }
    break;

case EState::Clockwise:
    ... See below

case EState::CounterClockwise:
    ... Similar as above
}

For the Clockwise and CounterClockwise states, you have to keep a variable, that increases every 100 ms, resets itself when going to the new state.
Depending on the step value, you do something. e.g. for the first two clockwise steps:
digitalWrite(2, HIGH);
delay(500);                // Wait for 500 millisecond(s)

digitalWrite(9, LOW);
delay(1000);               // Wait for 1000 millisecond(s)

you can make a switch like this inside the case you already have (or better: create a new function):
switch (_step)
{
case 0: // 0 ms
    digitalWrite(2, HIGH);
    break;

case 5: // 500 ms
    delay(1000);

...

Note it is a bit more clean to create a sort of hash/array but the above should work too. You can increase _step every 100 ms or only when the (counter)clockwise states are active.

How do I code this to immediately switch between loops?

You don't. You remove the loops. You don't want them - they can never end, since there is no way for the results to change between iterations.
You have a fundamental misunderstanding of how IR remotes work. There can be no "while" since a remote sends a signal either just once per button press, or repeatedly while the button is held down, depending on the function the button is supposed to perform.
Instead all you can do is "If the button has been pressed then do something". There's no "It's currently pressed" or "It's been released", only "I got a signal that it's pressed".


text:
Can I create an hemi-cycle raising signal with one pin and the other hemi-cycle signal with another pin?

I am new to Arduino, I would like to know if someone could help me to create this type of signal with the Arduino Uno. Many thanks!!

I'd use an MCP4822.

the arduino does not have analog output per se ... it is a PWM output ... please clarify what pin 9 and pin 10 signify in the diagram ... what is the purpose of the signal

it is to create an induced magnetic field in coils and stray currents. It is for an electrochemical project. Yes!! I know you cannot generate an analog output but if it is similar to the sketch would be OK. The pins 9 and 10 are I want to use, so the pin 9 and ground and the pin 10 and ground.

it is unclear how pin 9 and pin 10 are used ... if pin 9 and pin 10 are analog outputs, then you should draw two separate waveforms

Yes!! you are right, my fault it is unclear, they are two different waveforms superimposed


text:
I2C code working on Mega 2560 but not on Uno and nano
I have recently purchased this Heart rate sensor and was trying to make it work. I used this MAX30100 library I found on Github. For some reason when I use any of the given examples, they seem to work well when I use a Mega2560 I have but not on the Uno or Nano. Does this have to do with the processor? I don't think so because the README on Github mentions that they tested it on an Uno. But if it is so, how could I change the code to make it work with the Uno and nano?
Example Code I used:
// This example can be used to test connectivity and operation of the sensor
// check the README file on the repo's root for a troubleshooting guide in casem
// any of the tests running fail

#include <Wire.h>
#include "MAX30100.h"

MAX30100 sensor;

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

    Serial.print("Initializing MAX30100..");

    if (!sensor.begin()) {
        Serial.print("FAILED: ");

        uint8_t partId = sensor.getPartId();
        if (partId == 0xff) {
            Serial.println("I2C error");
        } else {
            Serial.print("wrong part ID 0x");
            Serial.print(partId, HEX);
            Serial.print(" (expected: 0x");
            Serial.println(EXPECTED_PART_ID, HEX);
        }
        // Stop here
        for(;;);
    } else {
        Serial.println("Success");
    }

    Serial.print("Enabling HR/SPO2 mode..");
    sensor.setMode(MAX30100_MODE_SPO2_HR);
    Serial.println("done.");

    Serial.print("Configuring LEDs biases to 50mA..");
    sensor.setLedsCurrent(MAX30100_LED_CURR_50MA, MAX30100_LED_CURR_50MA);
    Serial.println("done.");

    delay(1000);

    Serial.print("Lowering the current to 7.6mA..");
    sensor.setLedsCurrent(MAX30100_LED_CURR_7_6MA, MAX30100_LED_CURR_7_6MA);
    Serial.println("done.");

    delay(1000);

    Serial.print("Shutting down..");
    sensor.shutdown();
    Serial.println("done.");

    delay(1000);

    Serial.print("Resuming normal operation..");
    sensor.resume();
    delay(500);
    Serial.println("done.");

    uint32_t tsTempSampStart = millis();
    Serial.print("Sampling die temperature..");
    sensor.startTemperatureSampling();
    while(!sensor.isTemperatureReady()) {
        if (millis() - tsTempSampStart > 1000) {
            Serial.println("ERROR: timeout");
            // Stop here
            for(;;);
        }
    }

    float temperature = sensor.retrieveTemperature();
    Serial.print("done, temp=");
    Serial.print(temperature);
    Serial.println("C");

    if (temperature < 5) {
        Serial.println("WARNING: Temperature probe reported an odd value");
    } else {
        Serial.println("All test pass.");
    }

    Serial.println();
    Serial.println("Press any key to go into sampling loop mode");
    while (!Serial.available());

    sensor.resetFifo();
}

void loop()
{
    uint16_t ir, red;

    sensor.update();

    while (sensor.getRawValues(&ir, &red)) {
        Serial.print("IR=");
        Serial.print(ir);
        Serial.print(" RED=");
        Serial.println(red);
    }
}

What code are you using? Please show us. Also: Have you connected it correctly? As I remember the I2C hardware is on different pins for Uno/Nano and Mega

Also: What does not work well on Uno/Nano? What error do you get? Have you checked for the result of the tester example of the library?

I have added the example I was using in the question. For the connections, I simply connected Vin to 3.3V, SDA to SDA, SCL to SCL and GND to GND.

The main difference is that Arduino mega has pull up resistors on SCL/SDA lines.

Please test with the tester example of the library. It might show, what problem we have here exactly. Have you tried adding pullup resistors to the lines as mentioned in the troubleshooting section of the libraries readme?

I added pull-up resistors to the board and it started working. Turns out that the boards weren't well designed and the I2C lines were pulled up to 1.8V instead of Vin. By removing the pull-ups and adding pull-ups to Vin, the circuit started functioning. The circuit worked with Mega because it has in-built Pull-up Resistors.

And this can be done because those pins can be pulled up to 6V (absolute max).


text:
multiple RC522 RFID on arduino yun
I was trying for one month to make multiple RC522 rfid readers work together on SPI on an arduino yun, one works fine, but if I plug 4, each with a specific slave select, only one, sometimes 2, sometimes none are working.
The library i use is RFID.h (i think the miguelbalboa one) , but I had the same results with MFRC522.h wich have a specific readUidMultiReader so I dont think my code is at fault.
Searching for this issue, I found this question wich is basically my issue, as I suspect the readers I bought are not supporting multidrop. These readers dont work either.
I read about solutions using multiplexers for SPI lines, tristate buffers on miso lines and/or diodes but these are workarounds, and there should be a more straightforward solution.
Also I tested with no resistors most of the time, but tried putting 10kΩ from all MISO to 3v3, no change, as i really dont understand what their use are, even if I feel they could be mandatory.

I am using a yun for the builtin ethernet, because I tried nanos with ethernet shields and again the shields are ignoring the Slave select and thus not working with spi multidrop, so each time I plugged the shield on nano, even not using it, rfid stopped working.

your note about Ethernet shield makes me think you don't set all CS pin HIGH before begin() the individual devices in setup()

I have the same problem.
Did you find a solution ?
how to put HIGH the CSin the code ? Best regard.

Multiple SPI devices on the same bus shouldn't be a problem. I would try the following steps to narrow down the problem:

Add Pull-Up resistors to each CS line (10k should be enough)
(The is no need for resistors on the MISO, MOSI or CLK lines since they a push/pull when active)
Make sure each CS is set to HIGH before you attempt to access the reader
Use a simple sketch that only access 1 reader.

if you could access the first reader -> change the sketch to use the second one without changing the hardware setup. Continue until you've checked all readers.
if you are not able to communicate with one reader, you still have a bug in your hardware setup

When the readers work independently, you could start to write your sketch using more than one at a time. (depending on the libraries this could be quite difficult since the lib must support multiple instances, but first we should check the hardware setup)

The problem is that the MFRC522 devices do not release the MISO output pins to high impedance state when chip select is inactive.
What you can do is to implement an OR circuit to all MISO pins.
This can be done

Either with diodes (anodes to MFRC522 MISO pins, cathodes together to Arduino board MISO pin with 330.. 1k Ohm resistor connected to GND)
Or use 74HC125 circuit (chip select signals to enable inputs, inputs are the MISO pins of the MFRCs, outputs connected together should go to Arduino MISO).

I suppose that digital output power from yun is insufficient to drive all four readers - so, you need to add some digital buffers to MOSI, SCK, and RST lines.
74LS07 digital buffer:

can vcc and ground of the digital buffer be the ones of the yun (as they can output more intensity than the pins) or must they be from an external source then ?

Yes, they can ofk

You shouldn't need buffers for the SPI lines. The only power needed on these lines is the charge the input capacities on the slaves / master und 5 devices on a bus don't need much current.


text:
Uno - error during uploading with library
I'm writing the code in VS Code on IO Platform. Yesterday i finished my code and uploaded it to the Arduino Uno. It works fine. Next day i launched the VS Code and i changed the code a bit, then i uploaded it and i got the error.
Error:
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `__vector_7'
NewPing.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\uno\firmware.elf] Error 1

I am using the libary NewPing.h. The code should does this: If is distance more than 20cm, the the buzz makes the sound and turns on the red led. If distance is less than 20cm, the blue led turns on
The code:
#include <Arduino.h>  //It has to be there, because the arduino ide in VS Code will not work.

#include <NewPing.h>

#define echo_pin 3
#define trig_pin 4
#define max_range 450

#define red_led_pin 7
#define blue_led_pin 9
#define buzz_pin 10

int distance = 0;

NewPing sonar(trig_pin, echo_pin, max_range);

void setup(){
  Serial.begin(9600);
  pinMode(red_led_pin, OUTPUT);
  pinMode(blue_led_pin, OUTPUT);

  pinMode(buzz_pin, OUTPUT);
}

void loop() {

  distance = sonar.ping_cm();
  delay(50);

  if (distance > 0) {
          distance = 0;

    for (int i=0; i<5; i++) {
      distance += sonar.ping_cm();
      delay(50);
    }
    distance /= 4;

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

    if (distance > 20) {

      digitalWrite(blue_led_pin, LOW);
      digitalWrite(red_led_pin, HIGH);
      tone(buzz_pin, 1500);
      tone(buzz_pin, 800);
    }

    else {

      digitalWrite(red_led_pin, LOW);
      digitalWrite(blue_led_pin, HIGH);
    }
  }
}

I don't undersand, what has changed. I tried to import again the libary https://www.arduino.cc/en/guide/libraries by importing the *.zip file, also installing in IDE.

Please look into "NewPing.h". Is the line #define ENABLE_TIMER_BASED_PING 1 commented out or active?

Did you change the pin numbers from before? If yes, which exactly?

@chrisl How can i look into? How to open that file?

I'm not sure, why you are asking be that. It is a simple text file. You can open it with any text editor. All the source files are pure text files, that can be edited easily with any text editor

I was able to compile your code without errors (using the Arduino IDE). I used this NewPing library from github. Please give us information about, which NewPing library you have used exactly.

@chrisl I am using this library https://github.com/as000fm/NewPing-1.9.1/blob/master/NewPing.h Version 1.9.1. I tried to upload it with Arudino IDE to my arduino and it works. But the VS Code still doesn't work and i am getting the same error.

I'm not a VSCode expert, but that sounds like VSCode is using the wrong library files for compilation. Cannot say, how to fix that

@chrisl sure. But THANKS you for fix my problem with Arduino! And if i may ask, which code editor do you use for arduino or for any other language? I don't really like how the IDE looks, that's why i am asking.

You have a conflict of interrupts. Both the internal tone() command and the NewPing.h use Timer 2 by default, which makes them mutually exclusive.
However you can change NewPing to not use a timer by editing the src/NewPing.h file and setting TIMER_ENABLED to be false:
    #define TIMER_ENABLED true      // Set to "false" to disable the timer ISR (if getting "__vector_7" compile errors set this to false). Default=true

I wrote it to the my code under line with including th libary, but nothing has changed. What exactly and where should i type it? Finally, I installed the library based on instructions in this video: https://www.youtube.com/watch?v=_pSVzV4PdiA

@AuthorCliment Majenko asked you to change the corresponding line in the NewPing.h file, not in your sketch. Open the NewPing.h file (which you can find somewhere in your libraries folder) with a text editor, find that line and change it according to Majenkos answer

@chrisl I dound that line. I changed it to false. And I'm still getting the same error.


text:
Client.available remains empty (0)
i use the "client.availbale" to check incoming data on the (mkr1010) client coming from (mkr1010) server but it always contains "0". Serial printing (monitor) it on server works. It looks as if the data never arrives? Thanks for helping out !
client code :
if (client.connect(ServerIP, 23)) {
client.print("741G");
byte i = 0;
Serial.println(client.available());

    while (client.available() > 0 && i < bufferSize) {

      incomingMessage[i] = client.read();
      Serial.println(incomingMessage[i]);
      Serial.println(i);
      // check if end of incoming message
      if (incomingMessage[i] == '\r') {
        // replace carriage return with null terminator
        incomingMessage[i] = '\0';
        // set array index counter to end
        i = bufferSize;
        // flush out any remaining control characters which would
        // stay in client buffer until next loop
        client.flush();
      }
      // increase array index counter
      i++;

my server code :
// when the client sends the first byte, say hello:
  if (client) {
    if (!alreadyConnected) {
      // clead out the input buffer:
      client.flush();
      Serial.println("We have a new client");
      client.println("Hello, client!");
      alreadyConnected = true;
    }

    if (client.available() > 0) {
      // read the bytes incoming from the client:
      char request = client.read();
      Serial.print(request);

      for (i = 0; i < 4; i = i + 1) {
      Serial.print(myseq[i]);
      server.write(myseq[i]);

      }

use client.write(). does the server print "We have a new client"?

thanks for your reply. Apparently client.write gives same result. this is logic since if I'm right client.write writes to the specific client and server.write writes to all clients connected.

I don't know that specific board, but most often you need to accept the client's connection on the server with client = server.available().

that is done in another part of my server code. data from client to server works fine it is the other direction that doesn't work

@Majid that's what Majenko says. Do you use client.connected() anywhere?


text:
Two SD card interfaces on one ESP8266?
I know it's possible to hook up multiple SPI devices, but how can one access the second drive from a sketch?
Looking at the SDWebServer.ino example, my doubt is with the SD.begin(SS); part. If I call begin() again with the other CS pin, it seems that I would lose a reference to my first volume, or maybe it won't work at all. I would instantiate another SD instance, but the sketch never seems to instantiate that object, it first appears in setup() with SD.begin(SS);
If I copy the lib (sd.h+sd.cpp) and replace all literal instances of SD with SD2, can I then include and use SD2 just like the original (provided the different .begin(pin))? Is there a less hacky way of using two SD cards in ESP8266 Arduino?
In case anyone's wondering, it's for a crypto project where one card will contain one-time-pads of plaintext length and the other contains the XOR'd ciphertext, both are fed by wifi upload, and the max file size must be bigger than SPIFFS, so I really need two SD cards...

Can't you just create another instance of  SDClass SD2 in the sketch?

and of course choose a different pin for slave select signal

Not possible without changing the library code. Because the current library code is written intended for only one SD card, ie not intended for multiple SD cards because it will be complicated to do so. The SPI library also uses FatFS library, which is a bottleneck in this scenario.
Worth a try.
sdfatlib is library written for Arduino. I have never used it, but you can give a try on ESP.
Let us know if it works.

You should (I have not tested it) be able to do it if the library is well coded and doesn't use global variables and you do something like this:
// Don't know what the class name is so replace TYPE with what it should be.
TYPE SDCardOne;
TYPE SDCardTwo;

SDCardOne.begin(CS1);
SDCardTwo.begin(CS2);
....

Thanks for the edit Juraj, it makes a lot more sense now :)

Unfortunately, standard SD.h library is designed as a singleton, so the sketch code does not instantiate card interfaces, as @Devidas pointed out in another answer


text:
Transfer byte-buffer with ENC28J60
How do I transfer a series of byte[256]-buffers to a server with an ENC28J60 Ethernet adapter? I get blocks of uint8_t from an Arducam camera module and I'd like to transfer them to a host. Does somebody have an idea how to solve that? I asked a previous question regarding that topic but now new issues arrived.
This is how the array is filled:
uint8_t temp = 0, temp_last = 0;
byte buf[256];
length = myCAM.read_fifo_length();
while (length--) {
  temp_last = temp;
  temp =  SPI.transfer(0x00);
  if ((temp == 0xD9) && (temp_last == 0xFF)) {
    buf[i++] = temp;
    is_header = false;
    i = 0;
  }
  if (is_header == true) {
    //Write image data to buffer if not full
    if (i < 256)
      buf[i++] = temp;
    else {
      i = 0;
      buf[i++] = temp;
    }
  }
}

What protocol does your "host" use?

UDP, too. But probably I'm bad at writingn a proper receiver. Do you have an advice how this could look like?

Assuming you are using the EtherCard library you can send a UDP packet with:
ether.sendUdp(packet_data, length, srcPort, hisip, dstPort );

Assuming you have already set up your source port and have the destination IP address and port in hisip and dstPort.
The prototype for the function is:
void sendUdp (char *data,uint8_t len,uint16_t sport, uint8_t *dip, uint16_t dport);

The example udpClientSendOnly.ino with the library shows you UDP sending in action.

Thank you, I already did that. But only trash arrives at the receiver-side.

How do you know it is trash? Have you examined the actual data you are getting from the camera to make sure that you are actually sending what you think you are sending?

Yes, when I look at my console on arduino-side I get eg the JFIF-header. But when I make a plain plot of the incoming data from UDP than I cannot find that certain header.

This is what I tried: ether.sendUdp(buf, 256, srcPort, hostip, dstPort);

And you are sure that buf contains that JFIF header at the point of sending?

Well, if I do it in another way, that means, I add the line ether.sendUdp(temp, 1, srcPort, hostip, dstPort); directly behind temp = SPI.transfer(0x00); I'd expect at least the header (which I could recognize) to arrive. But it doesn't.

What OS are you using to receive it?

Right now: Mac OS X, node-js UDP-Server. I can switch to linux, though.

OS X may be fine - not sure what tools are available. Use tcpdump -s0 -X <portno> (that's what I use on Linux) to look at the raw data as it arrives on the computer to see if it's the same as your program says it is.

pktap_filter_packet: pcap_add_if_info(en5, 1) failed: pcap_add_if_info: pcap_compile_nopcap() failed

Do it as root...?

Actually, I missed the word "port" from there too - sudo tcpdump -s0 -X port <portno>

0x0000:  38c9 8624 db62 4c5e 0c90 9e16 0800 4500  8..$.bL^......E.
0x0010:  001d 0000 4000 3f11 0a0e c0a8 583e c0a8  ....@.?.....X>..
0x0020:  5833 10e1 0539 0009 b2ff 0500 0000 0000  X3...9..........
0x0030:  0000 0000 0000 0000 0000 0000            ............

I need to check if that is equivalent to what I've sended.

Also the buffer is maybe to big with 256. I lowered it to 32 for debugging.

I found the header!!!! 0x0000:  38c9 8624 db62 4c5e 0c90 9e16 0800 4500  8..$.bL^......E.
0x0010:  003c 0000 4000 3f11 09ef c0a8 583e c0a8  .<..@.?.....X>..
0x0020:  5833 10e1 0539 0028 143d 04d8 ffe0 0010  X3...9.(.=......
0x0030:  4a46 4946 0001 0101 0000 0000 0000 ffdb  JFIF............
0x0040:  0043 0004 0303 0403 0304                 .C........

Let us continue this discussion in chat.


text:
How to make two small micros communicate with my Arduino over BLE?
I want to do a project with an Arduino Uno and two other BLE (or regular bluetooth) capable modules. I want the Bluetooth modules to be hooked up to buttons (one button for each Bluetooth module). I then want the Bluetooth-capable modules to send the state of their buttons to a central Arduino board.
Is this possible? Can I have two different BLE boards connected to one Arduino?
I have a RedBear BLE (Bluetooth low energy) shield for my Arduino. What micro-controllers should I get for the peripheral modules? And where can I learn about pairing Bluetooth modules? Everything I read seems to be about pairing Bluetooth boards to a phone.
Can I do this all with BLE or am I going to need to get a new shield for my Arduino to talk with the two peripheral boards?
Thanks.

You can use SoftwareSerial to communicate with two modules from an uno. But You will have to wire 'em up separately, not through your shield. (making the total number of bluetooth modules 4.
You could also use your existing sheild and poll between the two remotes. I.e. disconnecting from one and connecting to the other at a regular interval.
For the micros and bluetooth for your button, you could use a HM10 with an ATtiny like in this instructable. He uses two HM10 modules to talk to each other. HM-10 is a popular BLE module. If you want regular bluetooth(2.0), you can use HC-05.

The page for the RedBear BLE shield that you note indicates that the BLE chip is the nRF8001, which it says supports peripheral (slave) role only. This means it must be connected to from a BLE Central role device.
Since you want your Uno to be the central device, listening for data from these 2 remote buttons, your RedBear shield won't work this way.
A short overview of BLE is available by AdaFruit.


text:
My HM-10 Bluetooth module only returns OK after any AT command
I bought an HM-10 Bluetooth module (BLE 4.0) to use in my school project. Every command that I send to it, it always returns "OK". Can you guys help me?
Here's the code that I am using in my Arduino Uno.
#include <SoftwareSerial.h>

SoftwareSerial BT(10, 11); // RX, TX
String command = ""; // Stores response of bluetooth device

void setup() {
  BT.begin(9600); // HC-06's usual default baud-rate
  Serial.begin(9600);
  Serial.println("Type AT commands!");
}

void loop() {
  if (BT.available()) {
    // Read device output if available.
    while(BT.available()) {
      // While there is more to be read, keep reading.
      delay(10); //Delay added to make thing stable
      char c = BT.read(); //Conduct a serial read
      command += c; //build the string.
    }
    Serial.println(command);
    command = ""; // No repeats
  }
  if (Serial.available()) {
    delay(10);
    BT.write(Serial.read());
  }
}

On the command write you read only one character to send to bluetooth.
Make same than for bluetooth to serial part above:
void loop()
{
if (BT.available()) // Read device output if available.
{
  while(BT.available()) // While there is more to be read, keep reading.
 {
   delay(10); //Delay added to make thing stable
   char c = BT.read(); //Conduct a serial read
   command += c; //build the string.
  }
  Serial.println(command);
  command = ""; // No repeats
}

if (Serial.available())
{
  while(Serial.available())
  {
     delay(10);
     char d = Serial.read(); //Conduct a serial read
     command += d; //build the string.
  }
  BT.write(command);
  command = "";
 }
}

There was a small bug in your code which I've fixed, hope you don't mind. Also worth noting that the delay(10) is a very risky approach to making sure the whole response is read. It would be more reliable to wait for a line ending.


text:
Using ArduCam library for Ov7076 camera
I am using OmniVision OV7076 camera (without FIFO) with Arduino Uno.

So I want to use Github code provided in ArduCAM repository. They have provided OV7076 FIFO version straightaway but it is using more memory.
I have used computer nerd code (provided in this tutorial Instructables OV7076 camera) and the camera had worked.
But I want to use the ArduCAM repository. It would be nice if any one could provided link for the guide or can give a little walk-through.
In the ArduCAM repository, they have make an ArduCAM class which have many methods. Thus we get rid of initialisation provided in computernerd code.
I want to use functions of the class directly. But i am unable to understand which method can be used for ov7076 camera. If you could write a starter code it would be very helpful.

I'm not able to add them in the question :(

I'll fix it up. For future reference there is a question mark in a gray circle in the top right-hand of the edit form - this will provide you with help.

I don't have much reputation that's why i'm unable to add the links. Thanks for your efforts. :D

Does this post help? http://embeddedprogrammer.blogspot.com.au/2012/07/hacking-ov7670-camera-module-sccb-cheat.html

According to this page, you should be able to post up to 2 links. I've finished editing the post, so you have your links plus more. You may be able to approve my edits.

Sorry but it is not what i want.


text:
Is it possible to run two for loops separated?
I have three funtion which describe the brightness of three LEDs. I want the seconde loop run 1 second after the first one and the third 1 second after the second one. One loop needs approximately 5 seconds. So basically I need to run three loops separated. How is this possible?
Update:
So I have this code running which I can compile but does not work:
int LED = 3;
int LED2 =10;
int LED3 = 9;

bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

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

void loop()
{
// Update loop enablers.
switch(periodIndex)
{
case 0:
 loop1state = true;
 loop1index = 0;
 break;

case 1000:
 loop2state = true;
 loop2index = 0;
 break;

case 1500:
 loop3state = true;
 loop3index = 0;
 break;

case 4000:
 periodIndex = 0;
 break;
}

if (loop1state)
{
 for (loop1index = 0; loop1index<255; loop1index++){
  analogWrite(LED,loop1index);
 }

 loop1state = loop1index < 256;
 }

 if (loop2state)
 {
 for(loop2index = 0; loop2index<255; loop2index++)
 {
  analogWrite(LED2,loop2index);
 }

 loop2state = loop2index < 256;
}

 if (loop3state)
 {
 for(loop3index = 0; loop3index<255; loop3index++)
 {
  analogWrite(LED3,loop3index);
 }
 loop3state = loop3index < 256;
 }
 delay(10);
 }

it's often forgotten that you can use goto in arduino, not that you should...

A Scheduler might be an alternative (to avoid all the complexity:). See example sketch https://github.com/mikaelpatel/Arduino-Scheduler/blob/master/examples/SchedulerBlink/SchedulerBlink.ino and library https://github.com/mikaelpatel/Arduino-Scheduler.

No, but there is a solution to put the action in one loop (main loop).
If I understand you well, you have the following scheme:
Time[s]
0..1     Loop 1
1..2     Nothing
2..3     Loop 2
3..4     Nothing
4..5     Loop 3
Define a variable that keeps track of the time.
Check against the current time (millis) and when within the correct 'range' perform an action.
After 5 seconds start over again.
uint32_t lastTime = -1;

void loop()
{
    if (lastTime == -1)
    {
        lastTime = currentTime; // Initialization, can be done in setup too
    }

    uint32_t diffTime = millis() - lastTime;

    if (diffTime < 1000) // 0..1 sec
    {
        DoLoop1();
    }
    else if (diffTime < 2000)
    {
         // Do nothing();
    }
    else if (diffTime < 3000)
    {
       DoLoop2();
    }
    else if (diffTime < 4000)
    {
        // Do nothing
    }
    else if (diffTime < 5000)
    {
       DoLoop3();
    }
    else // diffTime >= 5000
    {
         lastTime == currentTime; // Reset after 6 s
    }
}

Update
Since you need all three loops together (and mixed), it's easier to define some variables.
bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

Too bad I don't know the conditions when a loop starts, but let's say each iteration is 10 ms, and loop 1 starts immediately, loop 2 after 1000 ms, loop 3 after 1500 ms. After 3000 ms it starts all over.
void loop()
{
  // Update loop enablers.
  switch(periodIndex)
  {
  case 0:
     loop1state = true;
     loop1index = 0;
     break;

  case 1000:
     loop2state = true;
     loop2index = 0;
     break;

  case 1500:
     loop3state = true;
     loop3index = 0;
     break;

  case 4000:
     periodIndex = 0;
     break;
  }

  if (loop1state)
  {
     DoLoop1(loop1index++);
     loop1state = loop1index < 256;
  }

  if (loop2state)
  {
     DoLoop2(loop2index++);
     loop2state = loop2index < 256;
  }

  if (loop3state)
  {
     DoLoop3(loop3index++);
     loop3state = loop3index < 256;
  }

  delay(10); // 10 ms
}

Note, not tested, but the idea shold be clear
New update
You should not do a full loop during each switch, but only one iteration of the loop.
I did not run the sketch, just out of my head.
Some tips: print out the variables during each loop, so you get a clear idea what is happening (so all loop states and indices, and the periodIndex).
int LED = 3;
int LED2 =10;
int LED3 = 9;

bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

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

void loop()
{
  // Update loop enablers.
  switch(periodIndex)
  {
  case 0:
    loop1state = true;
    loop1index = 0;
    break;

  case 1000:
    loop2state = true;
    loop2index = 0;
    break;

  case 1500:
    loop3state = true;
    loop3index = 0;
    break;

  case 4000:
     periodIndex = 0;
     break;
  }

  if (loop1state)
  {
    analogWrite(LED,loop1index++);
    loop1state = loop1index < 256;
  }

  if (loop2state)
  {
    analogWrite(LED2,loop2index++);
    loop2state = loop2index < 256;
  }

  if (loop3state)
  {
    analogWrite(LED3,loop3index++);
    loop3state = loop3index < 256;
  }

  periodIndex++;
  delay(10);
}

@ChrisStratton Updated my answer according to the recalling millis() problem. Delay is possible too indeed (with your remark when possible to use).

@ChrisStratton True, with some addition for 'no-action'parts

Oh,you're absolutely right, sorry about that! Feel free to change it back if you prefer the way you previously had it.

@ChrisStratton No I like this better, It's more clear I think.

I just wanted to try your sketch but I get an error at the bottom of the code at the last else loop: "currentTime was not declared in this scope"
However, I'm not quite sure if this code will work the way I was thinking of. The wirst loop should start an while x is increasing at the first loop, the second one should start.
Time[s]:0..1:Loop 1 starts, 1...2: Loop2 starts while Loop 1 is increasing, 2...3: Loop 3 starts while Loop 1 and 2 are increasing,3...5:all Loops are increasing until 255. In that order Loop 1 reaches 255 first, Loop 2 is second and Loop 3 third.

I updated my answer with your changed requirements, not tested, but the idea is clear I hope

Thanks for your help. Unfortunately it doesn't work. I'm still a beginner in coding so I think I misunderstood something. This is how I try to run my first loop:
if (loop1state)
{
for (loop1index = 0; loop1index<255; loop1index++){
analogWrite(LED,loop1index);
}
 loop1state = loop1index < 256;

}
I can however compile it but it does not work. I also wanted to ask you how I can change my delay of 10ms?

I forgot the delay indeed, I put it at the end

Thank you but I still got the problem that only one LED is shining. How can I fix that?

Can you update your question with your current sketch, it's hard to see from here

Let me see if I understand correctly what you want... You want to ramp
up the brightnesses of 3 LEDs, one step every roughly 10 ms, and
you want the brightness ramps to start at different times. If this is
the case, I would start by writing a function that handles one LED,
increases its brightness by one step, and tells the caller whether the
ramp is done or not:
// Update the LED.
// Returns true if there are brightness steps left,
// false if we have finished the brightness ramp.
bool update_led_1()
{
    static uint8_t level = 0;  // brightness level
    analogWrite(LED1, level);
    level++;  // wraps to zero when we are done
    return level != 0;
}

This stores the brightness level as a single byte, rather than a
two-byte int, because I am cheap. ;-) Notice that on the last step of
the ramp, the value 255 is sent to the LED, then level++ wraps the
level to zero, then the function returns false to tell us the ramp is
finished. At this point, since level is zero, the function is ready
for the next ramp.
You can copy and paste this function three times, for each of the three
LEDs. Name them update_led_1(), update_led_2() and update_led_3().
The main loop can then go along these lines:
void loop()
{
    static int periodIndex = 0;  // increasing every 10 ms

    static bool led1active = false;
    if (periodIndex == 0)
        led1active = true;
    if (led1active)
        led1active = update_led_1();

    static bool led2active = false;
    if (periodIndex == 1000)
        led2active = true;
    if (led2active)
        led2active = update_led_2();

    static bool led3active = false;
    if (periodIndex == 1000)
        led3active = true;
    if (led3active)
        led3active = update_led_3();

    if (++periodIndex == 4000)
        periodIndex = 0;
    delay(10);
}

Notice the idiom if (led1active) led1active = update_led_1();. This
will be executed on every loop iteration, it will increase the LED
brightness if the LED is supposed to be active, and it will set
led1active to false when the brightness ramp is complete.
There is something I do not like in the solution I am suggesting here:
the copy-and-paste programming paradigm. If I am allowed to use C++
constructs, then I would encapsulate the ramp logic in a C++ class:
class RampingLed {
    const uint8_t pin;
    bool active;
    uint8_t level;
public:
    RampingLed(uint8_t pin)
        : pin(pin), active(false), level(0) {}
    void start() {
        active = true;
        level = 0;
    }
    void update() {
        if (!active) return;
        analogWrite(pin, level++);
        if (level == 0)
            active = false;
    }
};

Then the logic of the main program would appear more straightforward:
RampingLed led1(LED1), led2(LED2), led3(LED3);

void loop()
{
    static int periodIndex = 0;  // increasing every 10 ms

    // Start the LEDs at the appropriate times.
    if (periodIndex == 0)
        led1.start();
    if (periodIndex == 1000)
        led2.start();
    if (periodIndex == 1500)
        led3.start();

    // Update every LED.
    led1.update();
    led2.update();
    led3.update();

    if (++periodIndex == 4000)
        periodIndex = 0;
    delay(10);
}

If your three described for loops are the only thing the Arduino needs to do, then you can simply use blocking delay() calls.  However, this scheme will not be extensible to also satisfying other needs at the same time - should you anticipate those, then you should use a mechanism of time comparisons instead.
void loop() {
    int i;
    /* First loop */
    for (i=0; i < 255 ; i++) {
        your_led_function(LED_1, i);
        delay(20); //256 * 20 = 5.12 seconds
    }

    /* I want the second loop run 1 second after the first one */
    delay(1000);

    /* Second loop */
    for (i=0; i < 255 ; i++) {
        your_led_function(LED_2, i);
        delay(20);
    }

    /* and the third 1 second after the second one */
    delay(1000);

    /* Third loop */
    for (i=0; i < 255 ; i++) {
        your_led_function(LED_3, i);
        delay(20);
    }
}

Ultimately which type of solution is best depends on your goals - you can do things in a simple but limited way, or a more complicated but less limited one.  For every 3d printer firmware that cleverly squeezes every last drop of coordinated capability out of an Arduino, there are also those that spend their days sitting in a blocking delay() waiting for the next trivial bit toggle task.

So I have this code running which I can compile but does not work:

because it is wrong.
try something like this instead:
  time_elapsed = millis() / 1000 - start_time;  //time past start time, in seconds
       if (time_elapsed < LOOP1_ENDTIME) loop1();
  else if (time_elapsed < LOOP2_STARTTIME) do_nothing();
  else if (time_elapsed < LOOP2_ENDTIME) loop2();
  else if (time_elapsed < LOOP3_STARTTIME) do_nothing();
  ...
  else start_time+=TOTAL_TIME; //update start time

edit 2:
so here is the above code in action.

three simple tasks: loop1() flips D12, loop2() flips D13 and loop3() flips D8.
The time duration + gaps for those tasks are specified by the following macros:
#define LOOP1_DURATION  5  //time in x100 ms for easier simulation
#define LOOP1_GAP       1
#define LOOP2_DURATION  4
#define LOOP2_GAP       2
#define LOOP3_DURATION  3
#define LOOP3_GAP       6

from those macros, I built the ending and starting time used in the code above.
the code is long-term error free and will never lose track of time.
As you can see, it is essentially a fancy way of executing the following:
  do {loop1();} while (loop1's time isn't up);
  do {nothing();} while (loop1's gap time isn't up);
  do {loop2();} while (loop2's time isn't up);
  do {nothing();} while (loop2's gap time isn't up);
  ...

the advantage with my implementation is that each loop run is very quick and you can execute other tasks as well.
But the general idea is the same.

I notice a number (maybe most?) of your posts do not have properly capitalized sentences. Please slow down and type proper English. A sentence starts with a capital letter. An example here. Your answers look good, now just take a bit of time to format them properly. Proper formatting makes the site in general look better. Thanks for your understanding and cooperation!


text:
Using software Serial for Adafruit Thermal library and more general cpp question
I'm working on a proof of concept for using the Adafruit_Thermal printer library with an ATTiny85.
The ATTiny85 does not come with hardware serial capability, so I started looking into using SoftwareSerial to create the serial port necessary. I started down this path and ran into an error in the thermal library's constructor:
// thermal-printer.ino example file

#include "SoftwareSerial.h"
#define TX_PIN 3
#define RX_PIN 4

SoftwareSerial mySerial(RX_PIN, TX_PIN);

#include "Adafruit_Thermal.h"

Adafruit_Thermal printer(&mySerial); // Pass addr to printer constructor

// Adafruit_Thermal.h

class Adafruit_Thermal : public Print
{

public:
    // IMPORTANT: constructor syntax has changed from prior versions
    // of this library.  Please see notes in the example code!

    Adafruit_Thermal(Stream *s = &Serial, uint8_t dtr = 255);

Documents/Arduino/libraries/Adafruit_Thermal_Printer_Library/Adafruit_Thermal.h:125:33: error: 'Serial' was not declared in this scope
     Adafruit_Thermal(Stream *s = &Serial, uint8_t dtr = 255);

If I understand correctly, the verification process is failing because the compiler is looking for a global Serial value in the Adafruit_Thermal.hfile that doesn't exist because the ATTiny85 does not have HardwareSerial.
But, going by the Adafruit_Thermal class' constructor signature the reference passing of Serial is just a default value (right?) so I should be able to remove it and pass in my software serial reference. The SoftwareSerial class inherits from Stream, so it should still be a valid reference pass:
// this:
Adafruit_Thermal(Stream *s = &Serial, uint8_t dtr = 255);

// changes to this:
Adafruit_Thermal(Stream *s, uint8_t dtr = 255);

But when I do that, I start getting verification errors that make it look like the thermal instance wasn't constructed, like:

undefined reference to `Adafruit_Thermal::begin(unsigned char)'

and

undefined reference to `Adafruit_Thermal::Adafruit_Thermal(Stream*, unsigned char)'

Does this mean the class isn't getting constructed?
I looked at the underlying constructor definition to see if something was blowing up in there, but there doesn't seem to be anything fancy at the constructor level:
// Constructor
Adafruit_Thermal::Adafruit_Thermal(Stream *s, uint8_t dtr) :
  stream(s), dtrPin(dtr) {
  dtrEnabled = false;
}

This should still work with the software serial reference pass, right?
I'm a bit lost on how to debug this now. Any ideas?
Update
After a reply from Majenko I pulled up the cpp file and looked at the header reference:

So this means the cpp file was still referring to the include path header file instead of the lib version?
I updated my cpp file to use:
#include "lib/Adafruit_Thermal.h"

and I still get undefined reference errors, so it may still be something else, but I wanted to share this additional info.

On the face of it, removing = &Serial is exactly what you want to do, and behaves exactly as you expect. I suspect the other errors you are now getting are unrelated.

Ah ok. I'll keep digging then. If I figure out exactly what was happening I'll post back. Thanks for the confirmation!

It looks like the IDE might not be compiling the .cpp file from the library.

OH! Holy cow I totally didn't think of that! I'm adding an update to show a screen shot.

What IDE is that then?

Ah, this is VSCode (https://code.visualstudio.com) using the arduino extension (https://marketplace.visualstudio.com/items?itemName=vsciot-vscode.vscode-arduino). I'm a web app dev and I already had vscode set up the way I wanted, so switching to the arduino IDE was rough. Luckily the arduino extension allows for doing pretty much everything you'd want to do in the arduino IDE in vscode instead :)

Ah. So is there something you have to do in that IDE to say "Include the files in lib in the compilation`?

Your last comment helped me figure it out. I posted a detailed explanation in the answers section. Thanks for your help @Majenko

:'( it's a bitter sweet solution.
After @majenko's last comment:

Ah. So is there something you have to do in that IDE to say "Include the files in lib in the compilation`?

I remembered that this issue has bitten me before. Specifically, the issue of including subfolders into a sketch.
Normally in programming languages (at least all of the ones I work in normally), you can use relative paths or namespaces to include files from subfolders, but for some reason with Arduino if you want to include files from subfolders you have to put the files in a directory named src.
And it specifically needs to be src. You can't use lib or libs or source or whatevernameyouwant, it needs to be src.
I can't find a spot in the arduino reference docs or the IDE's github repository that explains that you need to use src for the subfolder name, but you can find various mentions in the forums. E.g.
https://arduino.stackexchange.com/a/54655/35534
So yeah, the solution to my problem was three parts.

Adopting the Adafruit_Thermal library into my codebase so that I could edit the source code without worrying about those changes polluting the orginal.
Removing the &Serial reference pass in the constructor declaration of Adafruit_Thermal.h
using the src directory name to include things from a subfolder.

After doing this, the sketch passes verification.
But here's the bittersweet part. After getting past all of this and seeing the compiler get past the sketch verification the bombshell dropped; the sketch is too big for the attiny:

I guess it was not meant to be :'(
Well, at least I know what was causing the linker/compiler errors and I'll be able to sleep at night :P
Thanks for your help Majenko :bows:.


text:
HC-05 can not use lower pins only 8 and higher
#include <Arduino.h>
#include <SoftwareSerial.h>

char Incoming_value = 0;

// SoftwareSerial BTSerial( 10, 11 ); // RX | TX +
// SoftwareSerial BTSerial( 9, 10 ); // RX | TX +
// SoftwareSerial BTSerial( 8, 9 ); // RX | TX +
// SoftwareSerial BTSerial( 7, 8 ); // RX | TX - ???
// SoftwareSerial BTSerial( 6, 7 ); // RX | TX - ???
// SoftwareSerial BTSerial( 5, 6 ); // RX | TX - ???
// SoftwareSerial BTSerial( 4, 5 ); // RX | TX - ???
// SoftwareSerial BTSerial( 3, 4 ); // RX | TX - ???

SoftwareSerial BTSerial( 8, 9 ); // RX | TX +

void setup() {
        BTSerial.begin( 9600 );
        pinMode( 13, OUTPUT);
}

void loop() {
        delay( 1000 );
        BTSerial.println( "hello" );
        if( BTSerial.available() > 0 ) {
                BTSerial.println( "BINGO!" );
                Incoming_value = BTSerial.read();
                BTSerial.println( Incoming_value );
                if ( Incoming_value == '1' ) digitalWrite( 13, HIGH );
                else if ( Incoming_value == '0' ) digitalWrite( 13, LOW );
        }
}

My HC-05 Bluetooth module wont't work on lowers digital pins.

BOARD_TAG = leonardo

It works fine on highers digital pins: 8-9, 9-10 or 10-11 - everything fine.
but 2-3, 3-4, 4-5, 5-6, 6-7 or 7-8 - no....

Why? Should I inject jumper somewhere or what?
And yes: @Majenko, "0,1 - is required to debug from host". I want to have Serial from PC and BTSerial from bluetooth - to have both accesses to device simultaneously.
@Peter_Paul_Kiefer, so, you think, this is impossible with lowest pins, lower than 8?

Why are you using SoftwareSerial on a Leonardo? Just use Serial0 and pins 0/1.

From the official SoftwareSerial Site: https://www.arduino.cc/en/Reference/softwareSerial (Section Limitations)

Not all pins on the Leonardo and Micro support change interrupts, so
  only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15
  (SCK), 16 (MOSI).