text:
Code problem w/ Uno+GPS+GPRS?
I've got an Arduino Uno, SIM900 GPRS, and the Adafruit Breakout GPS.
Can this code be optimized?
 #include <SoftwareSerial.h>
 #include <TinyGPS++.h>
 #include <Ubidots_Arduino_GPRS.h>
 //Serial Relay - Arduino will patch a
 //serial link between the computer and the GPRS Shield
 //at 19200 bps 8-N-1
 //Computer is connected to Hardware UART
 //GPRS Shield is connected to the Software UART
 #define APN "myapn"
 #define USER ""  // If your apn doesnt have username just put ""
 #define PASS ""  // If your apn doesnt have password just put ""
 #define TOKEN "ubidotsToken"  // Replace it with your Ubidots token
 #define ID "Your_id_here" // Replace it with your Ubidots' variable ID
 // You can send 1 to 10 variable at the same time
 #define ID1 "idHere" // Replace it with your variable ID
 //#define ID2 "" // Replace it with your variable ID
 //#define ID3 "Your_id_here" // Replace it with your variable ID

 TinyGPSPlus gps; // The TinyGPS++ object for interfacing with the GPS
 //Declare indexes, and strings
 char latitude[12];
 char longitude[12];
 float value_1 = 1;
 char var[18] = "Lat: ";
 char var2[18] = "Long: ";
 Ubidots client(TOKEN);
 SoftwareSerial ss(2,3);
 void setup() {

 // the Serial port of Arduino baud rate.
   Serial.begin(9600);

   client.powerUpOrDown();
   client.setApn(APN,USER,PASS);
 //.endC is for _client.end() in Ubidots_GPRS.cpp
   client.endC();
   ss.begin(9600);
 }

 void loop() {

   //handling GPS data parsing
   while (ss.available() > 0) {
     gps.encode(ss.read());}
   //Once a valid location comes up it updates Lat/Long variables
    if (gps.location.isUpdated())
 {
     strcpy(var, "Lat: ");
     strcpy(var2,"Long: ");

     dtostrf(gps.location.lat(),10,6,latitude);
     strcat(var, latitude);

     dtostrf(gps.location.lng(),10,6,longitude);
     strcat(var2, longitude);
   //Added ss.flush();
     ss.flush();
     ss.end();
     Serial.flush()
   //Added client.beginC() for _client.begin(9600) is Ubidots_GPRS.cpp
     client.beginC();
     client.add(ID1, value_1, var, var2);
     client.sendAll();
     client.endC();
     ss.begin(9600);
   }
  Serial.println(var);
  Serial.println(var2);
 }

From this link, I moved the println from inside .isUpdated() to outside the if statement. I was able to get GPS data sent from the unit to my Ubidots account while driving around town. Afterwards I was able to input the data into Google Maps and the route produced was accurate. Do I need flush()?

A simple test: comment  all the code concerned with sending the data over GPRS and run the sketch again. Are the GPS values printed without errors to the monitor?

I commented out .add() and .sendAll(), and the GPS values are being updated without error.

I have edited my post again.

From what you say, everything works. I was going to add a few listen()s in your code but this approach is also alright. If all you want to do is optimize the code, you could save the APN settings permanently to the sim900. Just add client.println("AT&W") at the end of setApn() and use readData() to ensure OK was received. Run the sketch and then you can comment out the setApn() call in setup(). Also provide a link to your updated library with its new functions.

Yes, it does work. Here is the link to my forked repository with the changes I have made so far. The code is in examples/SaveValuesGPS

Optimization is a generic word with plenty of different meanings. Please make it clear what you want: smaller code? Faster code? Code fatser to compile? Code easy to udnerstand or maintain?...

It seems you're using the same hardware Serial port for both your PC and the GPS module. This will result in the GPS module receiving everything you send to the PC with Serial.print() and this may be the cause of your problem, as it could confuse the module and either make it send an endless stream of gibberish and/or making isValid() to always be false. You should instead create a SoftwareSerial instance attached to any 2 digital pins (maybe 2 and 3) like this:
SoftwareSerial ss(2, 3);

and in setup():
ss.begin(9600);  // use your module baud rate

Then at the top of loop(), use this instead:
while (ss.available() > 0)
    gps.encode(ss.read());

Get rid of the recursive call of loop() within loop() since it will cause your stack to rapidly overflow.
If you want data to only be sent when the location values are updated based on recent received data (but not necessarily changed, since you may still be at the same location), you should use if (gps.location.isUpdated()) instead.
Your call of dtostrf() is also wrong. The second argument should be the length of the string to be created (including decimal point) and the 3rd argument should be the number of digits after the decimal point. Something like this should be okay:
dtostrf(gps.location.lat(), 10, 6, latitude);

You can also put this at the end of loop() to check if data is actually being received from the module and processed by the library:
if (millis() > 5000 && gps.charsProcessed() < 10)
  Serial.println(F("WARNING: No GPS data.  Check wiring."));
  while (1){ // infinite loop
    if (ss.available())
      Serial.print(ss.read());
  }
}

This site may provide additional details.

Thank you for your input. I have made the changes you suggested. I'm getting errors from serial monitor, but it may be I made a mistake in the one of the changes. `void setup() {
// the Serial port of Arduino baud rate.
Serial.begin(9600);
ss.begin(9600);
client.powerUpOrDown();
client.setApn(APN,USER,PASS);
}`

What errors exactly? did you connect the RX of the gps module to pin 3 of the arduino and its TX to pin 2?

Yes. If I run it with Serial.begin() first in setup() it will work, and with ss.begin() last it will parse data. But within .isUpdated() it will display error when trying to run .add().

What error are you getting exactly? How do you know it parses data? is the gps data changing (as you change your location) and being displayed by the Serial.print()s?

It will get a fix and show the coordinates in the serial monitor. I know there is an error because the .add() is displaying the error string "Error with AT+CSQ" on the serial monitor. It only seems to be working depending on where Serial.begin() and ss.begin() are located in setup().  `void setup() {
// the Serial port of Arduino baud rate.
Serial.begin(9600);
client.powerUpOrDown();
client.setApn(APN,USER,PASS);
ss.begin(9600);
}`

@roe-el Ah, its because there are multiple instances of SoftwareSerial being used. To what pins is the SIM900 connected?

From Ubidot_GPRS.h,  \nclass Ubidots{       private           SoftwareSerial _client = SoftwareSerial(7, 8);               bool httpInit();           char* _token;           bool httpTerm();           char* readData(uint16_t timeout);           void flushInput();           uint8_t maxValues;           uint8_t currentValue;           Value * val;    So 7,8?

@roe-el Edit your code so I can see the changes you've made so far. I will edit some of the library code.

I have edited code the code above.


text:
A good place to begin with Arduino?
So I bought the Arduino starter kit a few weeks ago and I've done a few of the projects in the book supplied with the set. Unfortunately the book is quite poor, with inaccurate explanations and sometimes no explanation behind what they want you to do in the projects.
So I'd like to know what people would reccomend? I found 2 well reviewed books; Arduino for Dummies and Arduino Workshop, but I'm torn which to take. So I'm asking in here in hope that I can save time and money on buying and reading a good book from the start.
I'm a programmer by profession and also know a bit of physics, but have little experience with electronics.

Try to come up with a project you can make that is useful in your life, and just make it. Just like programming; you'll learn the most by just doing, running into problems and finding solutions. Book are overrated.

I got some ideas of what I'd like to do, but I know already they will be complicated projects, so I'd like to build up some basic knowledge before I begin.

Try spitting them into sub-problems. E.g. you project requires a lcd display. Try to get an lcd display working. Your project needs to sound a buzzer when some condition is met. You need to read light levels; try getting a LDR or phototransistor to work.

I'd guess that with your background, you could find some useful tutorials online, from which you could build a couple of projects and learn while you're doing it. Since you have a goal - or at least a direction - in mind, you can direct your searches toward features you think you'll need.

could you please say which starter kit you have? Some of them are very good, some are not so good. The one I have is very clear, all the experiments worked, and the purpose was well understood - it is shown in this video review where I gave it a good rating... https://www.youtube.com/watch?v=pf4qosqpv3A

@Jasmine Sorry Jasmine, I hadn't considered that. It's the official starter kit sold on Arduinos own website.

There is some good discussion going on here but I'm going to have to close this question as it's "primarily opinion based" and there is no correct answer. The arduino chat would be a better place for something like this. http://chat.stackexchange.com/rooms/8489/pin-13

@sachleen Fair enough.

I have read a lot of materials, watched many videos and completed lots of searching to find great stater Arduino lessons. By far the best place I found was
opensourcehardwaregroup.com
Free to start learning Arduino site
Free initial course and if you like the lessons you can pay a small fee to get to the advanced course. You will learn a lot!

source: Stack Exchange

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

sort: votes


text:
Proto Shields wthout breadboard?
I want to use a proto shield (brand is unimportant) and solder some components to it, to make something more premanent than using a breadboard.
My question is can the components be soldered directly to the middle area where there are a lot of small holes?
I would assume this is possible, but everywhere I look people add mini breadboards to their proto shields.
If it's possible, then I assume components and wires can't just be connected in a row like on a breadboard and would instead need some solder between 2 holes where for example a component and seperate wire are connected?

You are completely right there. Just note that some proto-shield have some interconnected rows, just like a breadboard. But you can easily see that (example)

Thanks Greben. Would upvote and accept if you posted as an answer. :)

There are many different types of photo-shields, sometimes they have interconnected rows or they just have individual solder holes or even breadboards.  What you get all depends on what you are doing.  My personal favorite are the interlocked rows so I buy that and use a breadboard while I am developing my project then take off the breadboard and solder everything into place.
Example of non interlocked rows  and an My favorite proto-shield, it has a little of both kinds

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


text:
Starting usb on pro micro after deep sleep (ATmega32u4)
I have just started playing with a low power arduino project, and have managed to get the power drain down to about 220uA using powerDown from LowPower.
What I would love to be able to do is start the USB controller and send some data every 8 seconds, but I cant seem to send anything...
Any idea would be greatly appreciated :)
Her is my code:
// **** INCLUDES *****
#include <LowPower.h>

#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <avr/io.h>

void setup()
{
  DDRD = B00100000;       // PORTD5 = TXLED
  DDRB = B00000001;        // PORTB0 = RXLed

  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  Serial.println("Starter...");
  delay(100);
  Serial.end();

  /*
  *  IKKE FJERN DENNE!!! Da greier vi ikke å omprogramere kortet...
  */
  delay(10000);
  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  Serial.println("low-power...");
  delay(100);
  Serial.end();
  flash();
}

void loop()
{
  //LowPower.idle(SLEEP_8S, ADC_OFF, TIMER4_OFF, TIMER3_OFF, TIMER1_OFF, TIMER0_OFF, SPI_OFF, USART1_OFF, TWI_OFF, USB_OFF);//, USB_OFF);
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  //USBCON &= B11011111; //Disable USB Freeze clock USBCON.FRZCLK
  //USBCON |= B10010001; //SET USB_MACRO_ENABLE_BIT USBCON.USBE

    PLLCSR |= B00000010;   //-Enable             PLL PLLCSR.PLLE = 1;
    while (!(PLLCSR & 1)); //-Wait PLL LOCK      while (PLLCSR.PLOCK != 1);
    USBCON &= B11011111;   //-Unfreeze USB clock USBCON.FRZCLK = 0; (Clear to unfreeze)
    //-Clear Resume information ???

  flash();

  /*
  * Test USB kommunikasjon :)
  */
  Serial.begin(9600);
  while (!Serial);
  delay(5);
  Serial.println("Hello world!!!");
  delay(5);
  Serial.end();
   PORTD |= B00100000;
   PORTB |= B00000001;
}

void flash() {

   PORTD &= B11011111;
   PORTB &= B11111110;
   delay(100);
   PORTD |= B00100000;
   PORTB |= B00000001;
   delay(100);

   PORTD &= B11011111;
   PORTB &= B11111110;
   delay(100);
   PORTD |= B00100000;
   PORTB |= B00000001;
   delay(100);

   PORTD &= B11011111;
   PORTB &= B11111110;
   delay(100);
   PORTD |= B00100000;
   PORTB |= B00000001;
   delay(100);
}

Best regards, Richard
EDIT
The manual specifies this resume protocol:
Resuming the USB interface (21.13 USB Software Operating Modes)

Enable PLL
Wait PLL lock
Unfreeze USB clock
Clear Resume Informtion

which I have translated into this:
PLLCSR |= B00000010;   //-Enable             PLL PLLCSR.PLLE = 1;
while (!(PLLCSR & 1)); //-Wait PLL LOCK      while (PLLCSR.PLOCK != 1);
USBCON &= B11011111;   //-Unfreeze USB clock USBCON.FRZCLK = 0; (Clear to unfreeze)
//-Clear Resume information ???

It have no effect whatsoever, have no idea how to clear resume information though...
Also, for the record, the LEDs are flashing happily every 8 seconds.

You might have to put some delay after the serial.write. Once it comes back from sleep, it probably has to reestablish a USB connection (though your code seems to already account for that), and after that send the serial data. It can't do that when it's sleeping.

Hi Gerben, I just tried that with 800ms, but no success, I will try a little more... Is there any low-level USB commands that needs to be issued again maybe?

Also, when running in Idle, 200ms is enough before sending data and receiving... [edit] even 50ms is enough in when idle(usb_off) / serial.end before sending again

Sorry, I never worked with any USB chip, so I can't really help you any further.

I found an answer to a similar question here:
https://forum.sparkfun.com/viewtopic.php?f=32&t=39214&start=15#p175098
Note: it requires you to close and open the serial monitor at proper timings.
// disable the USB prior going to sleep
USBCON |= _BV(FRZCLK);  //freeze USB clock
PLLCSR &= ~_BV(PLLE);   // turn off USB PLL
USBCON &= ~_BV(USBE);   // disable USB

// and wake it up after
//routine to properly wake up
sleep_disable();
delay(100);
USBDevice.attach(); // keep this
delay(100);
Serial.begin(9600);
delay(100);


text:
Pass custom element of an array from an inherited class to main sketch
I'm building a base class that creates color patterns using FastLed's CRGB structure. I use the base class as inheritance for another more specific class that modifies a vector of colors (Pixels[]) and at some point I want to pass the color of a specific element from my class to the main sketch. But i'm having some issues with it, since the content of Pixels[] doesn't seem to match what I actually write in there.
Pattern.h:
class Pattern
{
    public:
    CRGB PixelAt(int idx);
    CRGB Pixels[6];
}

Pattern.cpp:
CRGB Pattern::PixelAt(int idx)
{
  // safety check
  if (idx >= 0 && idx < NumLeds)
  {
    return Pixels[idx];
  }
  else
  {
    Serial.print("Index out of bounds: "); Serial.println(idx);
    return CRGB::Black;
  }
}

TestPattern.h:
class TestPattern : public Pattern {
    void Tick(unsigned long millis);
}

TestPattern.cpp:
void TestPattern::Tick(unsigned long millis)
{
    for (int p = 0 ; p < NumLeds ; p++)
    {
      Pixels[p]=CRGB::Blue;
    }
}

Main Sketch:
for (int p = 0; p < NUM_PATTERNS; p++)
{
  // update pattern
  ledPatterns[p].Tick(millis());

  if (ledPatterns[p].Status == Enabled)
  {
    // sum the values of the pixels
    for (int l = 0; l < NUM_LEDS; l++) {
      leds[l] += ledPatterns[p].PixelAt(l);
    }
  }
}

I'm skipping parts of the code to make it easier to read, but I think with this much you should be able to help me make it work. I'm still getting acquainted with C and pointers, which is where I think the problem lies.
So how should I declare and use Pixels[] so that the Main Sketch, the base class and the inherited class all have consistent information?

On the face of it that all looks fine. What is the actual problem you are having though? You have gone through and told us what it is supposed to do, but you have forgotten to tell us what actually happens.

I was not clear when i said "the content of Pixels[] doesn't seem to match what I actually write in there.". I write all the pixels to Blue and when i read them back in the main sketch i get random values.

I figure out something else that is wrong. I have the Tick function in the parent class, but i actually want every child class to overload Tick with its own implementation, which is not happening. When i call Tick in the Main Sketch (also edited that in the main question since i forgot to put it there), the Tick that is being called is the one from the parent class, not the child class, why is that? I thought by default the child function would be called, and not the parent.

@LuisFerreira thats usually caused by changing of object copies. Try to add Pattern(Pattern &) = deleted; and Pattern & operator=(const Pattern &) = deleted; into the Pattern class. And it won't let you copy this object.

@KIIV you mean add those lines in the Header file? I get this compile error if i past them there in the public section:
"error: invalid pure specifier (only '= 0' is allowed) before ';' token"

If you want a child member function to override a parent member function the parent member function has to be marked as virtual.

@LuisFerreira About ticks: if you have TestPattern * patterns[N]; and then you assign pointer to child, you have to use virtual void Tick(unsigned long millis);  and the same in child class.

@KIV In the child class you can use final to say "this will never be overwritten in a further child" which helps the compiler do a better job of optimizing.

@Majenko i want the Tick function to override the parent function since different patterns will have different behaviours . And i want the parent class PixelAt function to be used for all childs, since this code doesn't change from pattern to pattern

@Majenko if you are talking about deleted copy constructor it's basically impossible to override. But, if he's overriding something, it's good idea to add override specifier. If it doesn't actually override anything it'll refuse to compile.

@KIIV I mean in the virtual function. Parent: virtual void Tick(.....); - child: final void Tick(......);

@Majenko Or he can make whole child class final:  struct Child final : public Parent { and for the methods I think it should be at the end:  virtual void Tick(...) final override;

After reading comments i got some more clues where to search and indeed the problem was somewhat in the inheritance and how i was calling the functions. This post helped me find the problem.
I forgot to post the piece of code where i was creating the patterns in the Main Sketch, this is how it was initially:
Pattern ledPatterns[NUM_PATTERNS];
ledPatterns[0] = TestPattern(NUM_LEDS, "Test Pattern 1", TestPat, 0, 0);
ledPatterns[1] = TestPattern(NUM_LEDS, "Test Pattern 2", TestPat, 0, 1);

...
ledPatterns[p].Tick(millis());
...

When i later called ledPatterns.Tick (the function that modifies the values, the function actually being called was the parent and not the child. Thus the unexpected result.
This is how i should have been initializing the patterns, since they are inherited:
Pattern* ledPatterns[NUM_PATTERNS];
ledPatterns[0] = new TestPattern(NUM_LEDS, "Test Pattern 1", TestPat, 0, 0);
ledPatterns[1] = new TestPattern(NUM_LEDS, "Test Pattern 2", TestPat, 0, 1);

...
ledPatterns[p]->Tick(millis());
...

Sorry for the huge confusion, i thought the problem was in a completely different part of the code


text:
Initializing pointer to vector of objects inside another object
i want to create a somewhat complex structure of classes in an arduino. The short story is: a Device has Presets, and each Preset has a Patterns. For that i created the following structure (i am only posting the important stuff, if something is missing let me know):
INO file
#include "LedDevice.h"

LedDevice device;

void setup() {
  device = LedDevice(10, 10, 10);
}

void loop() {
  Serial.println(F("Ticking"));
  device.Tick();
  delay(500);
}

LedDevice
#if !defined(_LEDDEVICE_H)
#define _LEDDEVICE_H

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

class LedDevice {
public:
  Preset* Presets[];

  LedDevice(){}
  LedDevice(int numPixels, int numPresets, int numPatterns)
  {
    *Presets = (Preset*)malloc(sizeof(Preset) * numPresets);

    for (int p = 0; p < numPresets; p++)
    {
      Presets[p] = new Preset("test", numPixels, numPatterns);
    }
  }

  void Tick()
  {
    Serial.print(F("Preset ")); Serial.println(Presets[0]->Name);
    Presets[0]->Tick();
  }
};

#endif  //_LEDDEVICE_H

Preset
#if !defined(_PRESET_H)
#define _PRESET_H

#include "Pattern.h"

class Preset {
public:
  char *Name;
  int NumPatterns;
  Pattern* Patterns[];

  Preset(char* name, int numPixels, int numPatterns) : NumPatterns(numPatterns)
  {
    Name = (char *)malloc(strlen(name) + 1);
    strcpy(Name, name);

    *Patterns = (Pattern*)malloc(sizeof(Pattern) * NumPatterns);

    for (int p = 0; p < NumPatterns; p++)
    {
      Patterns[p] = new Pattern(numPixels);
    }
  }

  void Tick()
  {
    for (int p = 0; p < NumPatterns; p++)
    {
      Patterns[p]->Tick();
    }
  }
};

#endif

Pattern
#if !defined(_PATTERN_H)
#define _PATTERN_H

class Pattern {
public:

  Pattern(int numPixels){}

  void Tick(){}
};

#endif

The code compiles but when i run the full version (this is a simplified version of the code) i get some strange behavior, so i would like to know if i am doing the initialization of the Presets and Patterns correctly.
Also when i try to print the Preset name in the LedDevice Tick function i get strange characters, so either i am not initializing the string correctly or the pointers to the Presets are wrong.
Can you tell if anything is not being done correctly in the constructors?

You may have provided enough info – I don't know – but I think it would be helpful if you edit your question to include a Minimal, Complete, and Verifiable example of code, as well as the snippets.  Otherwise, anyone who wishes to test an answer before posting it has to do the busy work of putting the snippets together.

My concept of what new does is: allocate memory for an object and construct the object.  Doesn't *Presets = (Preset*)malloc(sizeof(Preset) * NumPresets); allocate memory for an array of Presets and for ... Presets[p] = new Preset(...) allocate the same amount again?  (This would be a problem, not the problem.)

I'm new to Arduino, but isn't it possible to use a 2 dimensional array (of Pattern)? Or does Device has more properties than only a list an array of patterns?

@jwpat7 I added a complete version of the code. If i remove the New keyword from the objects initialization it complains that "cannot convert 'Preset' to 'Preset*' in assignment", so i tought it was still necessary despite the malloc.

@MichelKeijzers each class, LedDevice, Pattern and Preset has other attributes and functions, therefore i need a class for each, even a structure won't do. I'm already having issues initializing 1 dimensional array, if i go for 2 i guess it will be even worse

@LuisFerreira yes in that case it's getting worse (if you need more). I think the problem might be in too much initialization like jwpat7 says above. But I only know C and C++, not Arduino language yet well enough to answer.

@MichelKeijzers i just read this tutorial: https://arduino.land/FAQ/content/4/26/en/how-to-use-dynamic-memory.html
which clear some doubts. Using New is the C++ way of reserving memory. Malloc is the C way. Only one way is needed. I will do some more tests knowing this.
And Arduino uses GCC to compile, so its C++ and C compatible

Three things that need to be different:
Pattern* Patterns[];

should be
Pattern** Patterns;

It's a pointer to some pointers to patterns, not a pointer to an array (which is basically a pointer itself so same basic idea but an array implies a known size).
and
*Patterns = (Pattern*)malloc(sizeof(Pattern) * NumPatterns);

should be
Patterns = (Pattern*)malloc(sizeof(Pattern*) * NumPatterns);

*Patterns is the thing pointed to by Patterns which at this point is undefined. You want to set Patterns to the allocated address.
And we only need to allocate space for the pointers not the actual objects.
Your for loops then become
for (int p = 0; p < NumPatterns; p++)
{
  (Patterns+p) = new Pattern(numPixels);
}

You then have the same issues with Presets.
And finally
LedDevice device;
void setup() {
  device = LedDevice(10, 10, 10);
}

should be
LedDevice device(10, 10, 10);
void setup() {
}

Thank you for the input, some of those errors i was aware, and others i didn't know, but i can understand the logic now.

Sorry, just realised that the origional post was wasting too much memory, As Nick pointed out the new command is allocating the space for the actual objects. All you need to malloc is enough space for the pointers to those objects rather than enough space for the entire objects.

This is wrong:

Device device;

void setup()
{
   device = Device();
}

I don't know what your intentions are, but the first line instantiates device. You don't need to do anything in setup here. It sort-of looks like you are trying to call the constructor but that is called when the class instance is created (in the first line).

Preset* Presets[];

What's this? A pointer to an array of zero length?

    *Presets = (Preset*)malloc(sizeof(Preset) * NumPresets);

Now you are allocating memory for a pointer to the array to be big enough to hold the contents of the array.

for (int p = 0; p < NumPresets; p++)
{
    Presets[p] = new Preset("test", NumPixels, NumPatterns);
}

Now you are allocating memory for the contents of the array again.

There is too much dereferencing going on here. Please post a Minimal, Complete, and Verifiable example. For example, make the classes in question do not much. Then make code we can actually work on.

I realize the first call is to the default constructor, but in the setup i do the real construction ...

Well, you can't call the constructor twice. What is commonly done is to do nothing (or almost nothing) in the constructor, and then make a begin function which you call in setup. This function can then do whatever is required at the proper time.

I just updated the code to a Complete version. Here are some answers:

i declare Device, now named LedDevice outside of the setup because i want to use it in the Loop cycle as well. Is there another way to do it? I realize the first call is to the default constructor, but in the setup i do the real construction
I would like to be able to initialize the Preset and Pattern vector during run-time, so i am creating a pointer to a vector that i don't know the size yet. At least that's what i tought, is this wrong?
so i dont need to use both malloc and new? what is the correct way?

See amended answer.

malloc allocates memory. new also allocates memory but also calls the constructor. You should use new when allocating memory for classes.


text:
How to find out all #define used by arduino-cli in compile?
How to find out all #define used by arduino-cli in compile?
I had seen something some time ago, but I cannot find it again. I think that it was some option somewhere, and the result was that the compile did not end normally, but some generated file contained lots of useful and lots of obscure defined names.
I would like to find everything that's defined in my program, which I want to write, compile, and then run on different Arduinos, but it sometimes need different Serial to be used, different pin assignments, different internal buffer sizes and so on.
And I would like to organize the differences better, than just put all and everything to one big #ifdef - #endif for each extra platform.
Something like:

if it does not have Serial but Serial1, #define Serial Serial1
if it has 2kB RAM or less, set MY_BUF_SIZE to 10; if it has less than 3kB use 30, else use 100.
but if it is Micro Pro, use this pin assignment, else if it is Nano Every use that, else issue error/warning for user, that pins need to be assigned.

And many others...

@dda: Thank for your help :) English is my third foreing language and I am still not good at it.

I am not familiar with arduino-cli. If you can manage to find the g++
command line it uses for compiling your sketch, then you can get the
list you are looking for by using a modified version of that command:

add the options -E -dM
find the option -o output_file and change the name of the output
file to something more appropriate.

Edit: Following a suggestion by @gilhad, you can build the required
command line by piping the output of arduino-cli through sed:
arduino-cli compile | \
    sed -n '/g++.*\.ino\.cpp\.o/{s/-MMD//;s/-o .*/-E -dM -o defines.dump/;p}'

Thank you very much - I just made script, that use the make, which normally runs arduino_cli and simply reuse its output:
make |grep g++|grep .ino.cpp.o|sed "s/-o .*/-E -dM -o defines.dump/"|sh removed one unneeded file
rm defines.d and got defines.dump as result :)  You can add this to your answer for better visibility (or I vill make extra answer for that, but in your answer it would fit better)

@gilhad: I added this to my answer, with a some modifications: I merged the two grep command into the sed call, and removed the compiler option -MMD in order to prevent the generation of defines.d.

Nice, thank you :) I just typed that without thinking much, to try it as soon as possible :) (And to have all the flags and all as near as possible to original build, because my builds are sometimes more complicated)

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


text:
How to detect, if Serial is really connected to listening PC program? (on atmega32u4)
How to detect, if Serial is really connected to listening PC program? (on atmega32u4)
I need to connect from PC to Arduino Micro Pro over USB Serial and disconnect again and not slow down the Arduino with timeouting on all Serial.print.
Difference from other
Not same as Arduino Leonardo(Atmega32u4) - Detecting if USB is connected to a computer?

difference is what should happen after disconnecting PC program

"it is still connected to PC" (so it is OK, solved there)
"it is not listend to" and timeouting (so it is BAD, asked here)

I tried the both solutions mentioned there (UDADDR & _BV(ADDEN)) and (USBSTA & _BV(VBUS)) as well as (Serial) - it behave the same from my point of view

fast before screen connects, fast when screen connected, slow after screen ends, fast when screen reconnected

Details
I have Arduino Micro Pro managing a lot of things at its own, but I want sometimes connect to it via USB from my computer. I open screen /dev/ttyACM0 115200 and get a lot of debugging info and so on. Then I close the screen and let it work in peace. But there is problem with timeouts - when I stop listening, it waits for me and everything is terribly slow, until I connect there again.
Here is my loop
    void loop() {
        DoSomethingImportant(); // it works
        StatusOff(); // Green LED off, Yellow On
        if (displayTime()) {  // print debug only on new second
            if (Serial) {   // ######## If there is somebody listening ... #########
                Serial.print(F("Ctrl: "));Serial.print(W00.Used());
                Serial.print(F("); R1/W1: "));Serial.print(R01.Used());Serial.print(F("/"));Serial.print(W01.Used());Serial.print(F(" ("));Serial.print(R01.Total_Count());Serial.print(F("/"));Serial.print(W01.Total_Count());
                Serial.print(F("); R2/W2: "));Serial.print(R02.Used());Serial.print(F("/"));Serial.print(W02.Used());Serial.print(F(" ("));Serial.print(R02.Total_Count());Serial.print(F("/"));Serial.print(W02.Total_Count());
                Serial.print(F("); R3/W3: "));Serial.print(R03.Used());Serial.print(F("/"));Serial.print(W03.Used());Serial.print(F(" ("));Serial.print(R03.Total_Count());Serial.print(F("/"));Serial.print(W03.Total_Count());
                Serial.println(F("); "));
            };
        };
        StatusOn(); // Green LED on, Yellow Off
    }

Problem
When I connect the Arduino to PC (so it gets powered, I do not have much of the rest HW completed yet), it starts to do Something Important as fast as it can and every second the yellow LED blinks too fast to see that Green was off. It is OK.
Then I connect with screen /dev/ttyACM0 115200 and it gets new long line every second. Still the Green looks all time on and Yellow can be seen just blink. Still OK.
Then I end screen and it went slow - Yellow is on for like 7 second, while Green is on for 1 sec. And it is BAD.
Then I connect with screen /dev/ttyACM0 115200 and it gets new long line every second. The Green looks all time on and Yellow can be seen just blink. Again OK.
Question
How to detect, if I am connected or not?
Or maybe better, how to prevent the terrible slowdown, when I am not connected?

This is weird. Sending data to a disconnected serial port shouldn't slow things down, the data just gets sent to nowhere. I'm not sure what if (Serial) exactly does on that board, but have you tried just removing that test?

You have something weird going on with the }; before StatusOn(); and the lack of { after if (displayTime()). I'm guessing it's just from editing, but it's something you may want to fix in the question.

@timemage I fixed the formating for better readability, but the code was correct. The syntax is if (condition) command; where command may be compound command, like { ... } or simple command, or another if (condition) command; block as it was here. You are right, that the formating was remainder from earlier changes.

@PMF I had it first totally without the if (Serial), in hope that the output will just 'go nowhere' eventually and all will work the same. But I had seen the ?timeouts?, which behaved the same as is described in Problem section, so I tried the if (Serial) construction recomended somewhere, but it did not work. I also tried other conditions as in Difference from other section, but the problem remains.

@gilhad it's mostly the semicolon that throws things. You can put a semicolon after code block like that, but it's not terminating it. it's actually it's own statement called a "null statement". you use them in places to fulfill a syntax requirement. but, when you put it there, without a requirement, it just makes it look like you intended to do something else. if you really want to throw people put a number in front of it like if (condition) {} 7; it'll still be "correct", but it will look even less so than what you have. =)

I can reproduce this on Ubuntu, however it seems to be an anomaly of the screen program. If I use this small Python program to listen to the port, the Micro doesn't seem to slow down.
import serial

ser = serial.Serial('/dev/ttyACM0', 115200)  # Adjust the serial port accordingly

while True:
    if ser.readable():
        line = ser.readline().decode().strip()
        print (line)

You may need to import pyserial into Python, for example:
python -m pip install pyserial

My Arduino test code was:
const byte LED_PIN = 5;  // some pin for an LED

void setup() {
  Serial.begin (115200);
  pinMode (LED_PIN, OUTPUT);

}

void loop() {
  digitalWrite (LED_PIN, HIGH);
  delay (250);
  digitalWrite (LED_PIN, LOW);
  delay (250);

  Serial.println(F("Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n"
   "Ut molestie quam cursus, feugiat massa eget, lobortis ante.\n"
   "Nulla semper nisi a pretium finibus. Proin rutrum accumsan massa sit amet gravida.\n"
   "Etiam mollis, ipsum ac sagittis aliquam, sem urna euismod ipsum,\n"
   "eget accumsan orci sapien ornare felis. Nulla ex felis, facilisis in tincidunt at,\n"
   "dignissim vitae ligula. Aliquam facilisis tristique velit,\n"
   "a scelerisque turpis mollis quis. Nulla porta, mi vel ornare feugiat,\n"
   "mauris ligula commodo felis, in congue orci neque a est. "));

}

By looking at the rate of flashes of the LED I can see that it doesn't slow down when running the Python program, or if you Ctrl+C to exit the Python program.
However it does slow down if you attach to the USB using screen and then kill it.

I don't think the Arduino can per se know whether or not a program on the PC happens to be listening to the USB port or not. That is a function of what is happening in the operating system, not a function of the USB hardware.

Another approach which I haven't tested might be to get your Python program to periodically (eg. for each line) send a character, and get the Arduino to check for serial input. If no serial input (ie. not prompting character) then don't echo the debugging data.

Another approach (and possibly the simplest) is just to have a switch on the micro on a spare port, and close the switch if you want debugging information, and open it if you don't. Then you have total control over the debugging.

Thank you very much, the screen was culprit after all. But it is too convenient for me and I call it from Makefiles all the time, so I found fix for it, which close the Serial anyway :)

Thanks to Nick Gammon for his answer, the problem is really in the screen program.
There is detailed explanation from Majenko in
if(Serial) not working correctly on micro or pro micro
The problem is, that some programs (like screen) or some systems, or drivers, or so do not pull down RTS and DTR signals for Micro. (The DTR down is supposed to restart Uno and other non-USB arduinos).
It could be solved by running some small program to close the USB Serial properly after the screen is done with it - here are two which works for me
C program
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>

int main(int argc, char *argv[]) {
        // Check if the correct number of command-line arguments is provided
        if (argc != 2 ) {
                fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
                fprintf(stderr, "  %s /dev/ttyACM0 - close USB Serial for Arduino on the port\n", argv[0]);
                return 1; // Return an error code
        }
        int fd;
        fd = open(argv[1],O_RDWR | O_NOCTTY );//Open Serial Port

        int RTS_flag;
        RTS_flag = TIOCM_RTS;

        int DTR_flag;
        DTR_flag = TIOCM_DTR;

//      ioctl(fd,TIOCMBIS,&RTS_flag);//Set RTS pin
//      ioctl(fd,TIOCMBIS,&DTR_flag);//Set DTR pin

        ioctl(fd,TIOCMBIC,&RTS_flag);//Clear RTS pin
        ioctl(fd,TIOCMBIC,&DTR_flag);//Clear DTR pin
        close(fd);
}

Python
#!/usr/bin/python -u

import serial
import sys

# Check if the correct number of command-line arguments is provided
if not len(sys.argv) in {2,3}:
        print("Usage: {} <filename> [baudrate]".format(sys.argv[0]))
        print(" {} /dev/ttyACM0 - close USB Serial for Arduino on the port".format(sys.argv[0]))
        sys.exit(1)  # Exit with a non-zero error code

# Get the filename from the command-line argument
baudrate=115200
filename = sys.argv[1]
if len(sys.argv) > 2:
        baudrate=sys.argv[2]

# Open the serial port
ser = serial.Serial(filename, baudrate, xonxoff=False , rtscts=True , dsrdtr=True )
ser.rts=False
ser.dtr=False

Re “the problem is really in the screen program”: I suggest you ditch screen and try picocom. This is a small program (tiny compared to screen) for accessing devices that provide serial consoles. It does only one thing but does it well; it does not try to emulate or multiplex terminals. I do not know whether picocom defaults to the correct behavior, but it keeps you in control: see the options --noreset, --hangup, --lower-rts, --raise-rts, --lower-dtr and --raise-dtr.

@EdgarBonet can I somehow "type in" file to picocom? As if I open picocom /dev/ttyACM0 communicate with Arduino over its Serial.read and then "type-in file lorem.txt" and Arduino will get impression, that I am typing really fast really long texts. (the Serial.read will just receive lots of chars - the content of the file)

I am using Gentoo Linux and I also use serial communication with other 8-bit computers, where I need sometimes send few kilobytes of hexa code (Intel Hex) so it will be more convenient, then simply copy-paste text to terminal window

picocom -b 115200 -s cat /dev/ttyUSB0 works (-s cat) and then C-a C-s ./test_serial.002.0200.s.x.hex

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


text:
How to pass Encoder object to constructor of a different class
I am trying to create a class (Arm) that controls an arm. The arms have 2 motors, each with an encoder, so I pass 4 integers for the pins and I am trying to pass 2 pointers (one for each encoder object).
the .ino file is:
#include "Arm.h"
#include <Encoder.h>

//motor driver pins
#define ShoulderUP 7
#define ShoulderDW 8

#define ElbowUP 9
#define ElbowDW 10

#define encoderShoulderPinA 20
#define encoderShoulderPinB 21

#define encoderElbowPinA 22
#define encoderElbowPinB 23

//make encoder objects
Encoder ElbowEncoder(encoderElbowPinA, encoderElbowPinB);
Encoder ShoulderEncoder(encoderShoulderPinA, encoderShoulderPinB);

//make arm object
Arm Arm1(ShoulderUP, ShoulderDW, ElbowUP, ElbowDW, ElbowEncoder, ShoulderEncoder);

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

void loop() {

  Arm1.ShoulderMoveTime(1, 255, 1000);
}

the .h file is:
#ifndef Arm_h
#define Arm_h

#include <Arduino.h>
#include <Encoder.h>

class Arm {

public:
  Arm(int ShoulderUpPin, int ShoulderDownPin, int ElbowUpPin, int ElbowDownPin, Encoder *ElbowEncoder, Encoder *ShoulderEncoder);

  //pins connected to your encoder:
  //   Best Performance: both pins have interrupt capability
  //   Good Performance: only the first pin has interrupt capability
  //   Low Performance:  neither pin has interrupt capability

  void ShoulderMoveTime(int dir, int speed, int time);
  //dir = 0 means up, dir = 1 means down; speed between 0-255
  void ElbowMoveTime(int dir, int speed, int time);
  //dir = 0 means up, dir = 1 means down; speed between 0-255

  //Moves arm to poition given
  void ArmMovePosition(int shoulderPos, int elbowPos);

  // calibrates current arm position to zero
  void ZeroArm();

  //returns position of the arm
  void getArmPosition();

private:
  Encoder *ElbowEncoder;
  Encoder *ShoulderEncoder;
  int _ShoulderUpPin;
  int _ShoulderDownPin;
  int _ElbowUpPin;
  int _ElbowDownPin;
};

#endif

and the .cpp file is:
#include "Arduino.h"
#include "Encoder.h"
#include "Arm.h"

Arm::Arm(int ShoulderUpPin, int ShoulderDownPin, int ElbowUpPin, int ElbowDownPin, Encoder *ElbowEncoder, Encoder *ShoulderEncoder) {

  pinMode(ShoulderUpPin, OUTPUT);
  pinMode(ShoulderDownPin, OUTPUT);
  pinMode(ElbowUpPin, OUTPUT);
  pinMode(ElbowDownPin, OUTPUT);

  _ShoulderUpPin = ShoulderUpPin;
  _ShoulderDownPin = ShoulderDownPin;
  _ElbowUpPin = ElbowUpPin;
  _ElbowDownPin = ElbowDownPin;
  //_ShoulderEncoderPinA = ShoulderEncoderPinA;
  //_ShoulderEncoderPinB = ShoulderEncoderPinB;
  //_ElbowEncoderPinA = ElbowEncoderPinA;
 // _ElbowEncoderPinB = ElbowEncoderPinB;
  ElbowEncoder = *ElbowEncoder;
  ShoulderEncoder = *ShoulderEncoder;
  //ElbowEncoder(_ElbowEncoderPinA, _ElbowEncoderPinB);
  //ShoulderEncoder(_ShoulderEncoderPinA, _ShoulderEncoderPinB);
}

void Arm::ShoulderMoveTime(int dir, int speed, int time) {
...
}

void Arm::ElbowMoveTime(int dir, int speed, int time) {
 ...
}

void Arm::ArmMovePosition(int shoulderPos, int elbowPos) {
  int ShoulderinitialPos = ShoulderEncoder.read();
  int ElbowinitialPos = ElbowEncoder.read();

  //TODO:I think this will only move one joint at a time

  //Move shoulder-------------------------------------------------------------------------------------
  if (shoulderPos > ShoulderinitialPos) {  //check to see which direction arm needs to move

    while (shoulderPos > ShoulderEncoder.read()) {  //while the target position is greater than the motor's actual position, move the shoulder up
      digitalWrite(_ShoulderUpPin, HIGH);           //THIS MAY BE REVERSED
    }
    digitalWrite(_ShoulderUpPin, LOW);  //stop the arm from moving up

  } else if (shoulderPos < ShoulderinitialPos) {

    while (shoulderPos < ShoulderEncoder.read()) {
      digitalWrite(_ShoulderDownPin, HIGH);
    }
    digitalWrite(_ShoulderDownPin, LOW);

  } else {
    Serial.print("Error: invalid shoulder target position");
  }

  //Move elbow-------------------------------------------------------------------------------------
  if (elbowPos > ElbowinitialPos) {  //check to see which direction arm needs to move

    while (elbowPos > ElbowEncoder.read()) {  //while the target position is greater than the motor's actual position, move the elbow up
      digitalWrite(_ElbowUpPin, HIGH);        //THIS MAY BE REVERSED
    }
    digitalWrite(_ElbowUpPin, LOW);  //stop the arm from moving up

  } else if (elbowPos < ElbowinitialPos) {

    while (elbowPos < ElbowEncoder.read()) {
      digitalWrite(_ElbowDownPin, HIGH);
    }
    digitalWrite(_ElbowDownPin, LOW);

  } else {
    Serial.print("Error: invalid elbow target position");
  }
}

void Arm::ZeroArm() {
  ShoulderEncoder.write(0);
  ElbowEncoder.write(0);
  Serial.println("Arm has been tared");
}

void Arm::getArmPosition() {
  Serial.print("Shoulder Position: ");
  Serial.print(ShoulderEncoder.read());
  Serial.print("Elbow Position: ");
  Serial.println(ElbowEncoder.read());
}

Unfortunately, there appears to be some sort of problem with passing the  Encoder object. I am getting the error:

Compilation error: no matching function for call to 'Arm::Arm(int, int, int, int, Encoder&, Encoder&)'

I am definitely a noob when it comes to coding, so thanks in advance for what is probably a simple problem.

What happens when you pass the Encoder object as pointer via &ElbowEncoder?

I get "Compilation error: no match for 'operator=' (operand types are 'Encoder' and 'Encoder*')"

please copy all of the error message and paste it into your question ... do not put it into a comment like you just did ... also, no pictures of text ... format the text as code

you can use reference. member and parameter as Encoder& type and in constructor initialization list you set the value of the member from the value of the parameter. MyClass::MyClass(Encoder& _encoder) : encoder(_encoder) {}

You're jumping backwards and forwards between pointers and the objects themselves.
Change it to pass pointers to the arm constructor and consistently use pointers (or pass a reference and always use that, just be consistent). This would be something like:
    // main code, pass a pointer rather than the object itself
    Arm Arm1(ShoulderUP, ShoulderDW, ElbowUP, ElbowDW, &ElbowEncoder, &ShoulderEncoder);

    // header
    public:
      Arm(int ShoulderUpPin, int ShoulderDownPin, int ElbowUpPin, int ElbowDownPin, Encoder *ElbowEncoder, Encoder *ShoulderEncoder);

    // cpp
    Arm::Arm(int ShoulderUpPin, int ShoulderDownPin, int ElbowUpPin, int ElbowDownPin, Encoder *ElbowEncoder, Encoder *ShoulderEncoder) {

      pinMode(ShoulderUpPin, OUTPUT);
      pinMode(ShoulderDownPin, OUTPUT);
      pinMode(ElbowUpPin, OUTPUT);
      pinMode(ElbowDownPin, OUTPUT);

      _ShoulderUpPin = ShoulderUpPin;
      _ShoulderDownPin = ShoulderDownPin;
      _ElbowUpPin = ElbowUpPin;
      _ElbowDownPin = ElbowDownPin;
      this.ElbowEncoder = ElbowEncoder; // use 'this.' to indicate the class private variable since it's the same name as the passed parameter.
      this.ShoulderEncoder = ShoulderEncoder;
    }

And then within your class, since ElbowEncoder is a pointer rather than the encoder itself, use ElbowEncoder->method() rather than ElbowEncoder.method()
Personally, I'd restructure it a little. Why create the encoders at the top level when they are only used within the arm class?
Create them in the arm class instead:
    //in .h
    public:
      Arm(int ShoulderUpPin, int ShoulderDownPin, int ShoulderEncoderPinA,int ShoulderEncoderPinB,
          int ElbowUpPin, int ElbowDownPin, int ElbowEncoderPinA, int ElbowEncoderPinB);

    private:
      Encoder ShoulderEncoder;
      Encoder ElbowEncoder;

    // in .cpp
    Arm::Arm(int ShoulderUpPin, int ShoulderDownPin, int ShoulderEncoderPinA,int ShoulderEncoderPinB,
             int ElbowUpPin, int ElbowDownPin, int ElbowEncoderPinA, int ElbowEncoderPinB) :
                 ShoulderEncoder(ShoulderEncoderPinA,ShoulderEncoderPinB),
                 ElbowEncoder(ElbowEncoderPinA,ElbowEncoderPinB) {
       // constructor code
    }

This will create the encoders as private to the arm as soon as you call the arm constructor. Especially handy if you want to have more than one arm.


text:
Stepper Motor Direction Not Changing with Toggle Switch - Need Help
I’m trying to control the direction of a stepper motor using a toggle switch with my Arduino. While the LED indicates that the switch is working correctly (i.e., it changes state as expected), the stepper motor's direction does not change as anticipated. Here’s the code I’m using:
#include <Stepper.h>

const int stepsPerRevolution = 2048; // Number of steps per revolution
const int motSpeed = 10;             // Motor speed (RPM)

// Pin configuration
const int buttonPin = 2;             // Button pin number
const int ledPin = LED_BUILTIN;      // Built-in LED pin number

// State variables
int motDir = 1;                      // Motor direction (1 = forward, -1 = backward)
int newVal;                          // Current button state
int oldVal = HIGH;                   // Previous button state
unsigned long lastDebounceTime = 0;  // Last debounce time
unsigned long debounceDelay = 50;    // Debounce delay (ms)
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  Serial.begin(9600);                  // Initialize serial communication
  pinMode(buttonPin, INPUT_PULLUP);    // Set button pin with pull-up resistor
  pinMode(ledPin, OUTPUT);             // Set LED pin as output
  myStepper.setSpeed(motSpeed);        // Set motor speed
}

void loop() {
  // Read button state
  int reading = digitalRead(buttonPin);

  // Debounce handling
  if (reading != oldVal) {
    lastDebounceTime = millis(); // Record the time of last state change
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // Check if button state has changed
    if (reading != newVal) {
      newVal = reading;

      // Toggle direction on button press
      if (newVal == LOW) {
        motDir = -motDir; // Reverse motor direction

        // Toggle LED state
        digitalWrite(ledPin, (motDir == 1) ? LOW : HIGH);

        Serial.print("Motor Direction: ");
        Serial.println((motDir == 1) ? "Clockwise" : "Counter-Clockwise");
      }
    }
  }

  // Rotate motor
  myStepper.step(motDir * 10); // Move motor by 10 steps

  // Update previous button state
  oldVal = reading;

  // Delay for smooth operation
  delay(20);
}

Problem:
The LED and serial monitor correctly show the change in state when the switch is pressed and released.
However, the stepper motor does not change its direction as expected. It seems to continue rotating in the same direction regardless of the switch state.
What I've Tried:

Checked Hardware Connections:

Verified that the stepper motor and driver connections are correct.

Checked power supply to the stepper motor.

Code Review:

Ensured debounce logic is correctly implemented.
Verified that the motDir variable is being updated correctly.

Request for Help:
Can someone help identify what might be causing the stepper motor direction not to change? Any suggestions or insights would be greatly appreciated.

I know you said the button works. But the code uses a pull up but in the diagram the button is connected to the positive rail.  Probably want to connect the button tot he negative rail.

Are you really powering the stepper motor with a small rectangle 9 volt battery? This likely does not have enough current to work dependably.

I am unfamiliar with the way the stepper motor is wired. Can you include a part number or a detailed description of the stepper motor in your question (not here, but in your question).

Some prototyping board power connectors do not span the entire length of the board. Check your prototyping board and add jumpers if necessary.

Sometimes the coil wiring is different than expected.  Try swapping pairs of pins, like myStepper(stepsPerRevolution, 8, 10, 9, 11);

Sounds like you have tested everything. Try to test the motor separately. Only the motor and the Arduino. All other components should be removed. This will show if the motor itself is faulty. For future use, you can design a motor stepper motor control board like this: https://www.pcbway.com/project/shareproject/Stepper_motor_developing_platform_d2e5fcf7.html


text:
ESP32 can't handle trigger signal to take photo
The problem is, the following code doesn't work. If I am not using the if to check if there is a signal at GPIO 16, then the code is working. I'm using a ESP32-CAM module. It doesn't save a picture to the SD card.
If I leave the if (digitalRead(16)) away, the code will save every loop a picture to the SD-Card.

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-cam-pir-motion-detector-photo-capture/

  IMPORTANT!!!
   - Select Board "AI Thinker ESP32-CAM"
   - GPIO 0 must be connected to GND to upload a sketch
   - After connecting GPIO 0 to GND, press the ESP32-CAM on-board RESET button to put your board in flashing mode

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

#include "esp_camera.h"
#include "Arduino.h"
#include "FS.h"                // SD Card ESP32
#include "SD_MMC.h"            // SD Card ESP32
#include "soc/soc.h"           // Disable brownour problems
#include "soc/rtc_cntl_reg.h"  // Disable brownour problems
#include "driver/rtc_io.h"
#include <EEPROM.h>            // read and write from flash memory
// define the number of bytes you want to access
#define EEPROM_SIZE 1

RTC_DATA_ATTR int bootCount = 0;

// Pin definition for CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27
#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22

int pictureNumber = 0;

void setup() {
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
  Serial.begin(115200);

  Serial.setDebugOutput(true);

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;

  if(psramFound()){
    config.frame_size = FRAMESIZE_UXGA; // FRAMESIZE_ + QVGA|CIF|VGA|SVGA|XGA|SXGA|UXGA
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }

  // Init Camera
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  Serial.println("Starting SD Card");

  delay(500);
  if(!SD_MMC.begin()){
    Serial.println("SD Card Mount Failed");
    //return;
  }

  uint8_t cardType = SD_MMC.cardType();
  if(cardType == CARD_NONE){
    Serial.println("No SD Card attached");
    return;
  }

  camera_fb_t * fb = NULL;

  // initialize EEPROM with predefined size
  EEPROM.begin(EEPROM_SIZE);

 pinMode(16, INPUT);

}

void loop() {
  if((digitalRead(16)))
  {
    fotomachen();
  }
  delay(1000);

}

void fotomachen(){
camera_fb_t * fb = NULL;

  // Take Picture with Camera
  fb = esp_camera_fb_get();
  if(!fb) {
    Serial.println("Camera capture failed");
    return;
  }

pictureNumber = EEPROM.read(0) + 1;

  // Path where new picture will be saved in SD Card
  String path = "/picture" + String(pictureNumber) +".jpg";

  fs::FS &fs = SD_MMC;
  Serial.printf("Picture file name: %s\n", path.c_str());

  File file = fs.open(path.c_str(), FILE_WRITE);
  if(!file){
    Serial.println("Failed to open file in writing mode");
  }
  else {
    file.write(fb->buf, fb->len); // payload (image), payload length
    Serial.printf("Saved file to path: %s\n", path.c_str());
    EEPROM.write(0, pictureNumber);
    EEPROM.commit();
  }
  file.close();
  esp_camera_fb_return(fb);
}

the code doesn't work ...  what does it do? ... edit your post ... add a clear description of what it does ... do not write a comment

Your button GPIO (16) is only checked once every second, instead of more often. You should have any delay and add debouncing: https://docs.arduino.cc/built-in-examples/digital/Debounce/. Also, you don't say how you've wired up the button. The pinMode(16, INPUT); together with if((digitalRead(16))) demands a button with an external pull-down resistor on GPIO16, and the button being wired to +3.3V on one side, and GPIO16 on the other.

@MaximilianGerhardt thank you for the tip with the delay. But that didn't changed the main problem. I also tried if((digitalRead(16)==0) and put a cable to the ground, but then the esp32 also didn't take a photo.

So what's the wiring diagram?


text:
3 input (on/off/off with delay) to control 1device using ESP8266 as Web Server
I want to control one device in three ways : turn on / turn off / turn off with delay.
To do that I use an ESP8266 web server + android phone app.
The problem is that turn off with delay wont work.
It works with delay() but I don't want to use delay() as it stops other functions.
I would be grateful if you could help me.
here is my code :
#include <ESP8266WiFi.h>
const int device1 = 14;
unsigned long previousMillis = 0;
const long interval = 5000;
const char* ssid     = "****";
const char* password = "****";
#include <Arduino.h>
WiFiServer server(80);
String data = "";

void setup() {
 pinMode(device1, OUTPUT);
Serial.begin(115200, SERIAL_8N1, SERIAL_TX_ONLY);
WiFi.begin(ssid, password);
IPAddress ip(*,*,*,*);
IPAddress gateway(*,*,*,*);
IPAddress subnet(*,*,*,*);
WiFi.config(ip, gateway, subnet);
 while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
 }
 Serial.println("");
 Serial.println("WiFi connected");

 server.begin();

 Serial.println(WiFi.localIP());
 }

void loop() {
    unsigned long currentMillis = millis();

  WiFiClient client = server.available();
 if (!client) {
   return;
 }

 while(!client.available()){
 }

 String req = client.readStringUntil('\r');
 client.flush();
 if (req.indexOf("/on") != -1)
   { digitalWrite(device1, HIGH);}
 if (req.indexOf("/off") != -1)
   { digitalWrite(device1, LOW);}

 if (req.indexOf("/delay") != -1)
 {
  unsigned long currentMillis = millis();
  unsigned long previousMillis = millis();
if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    digitalWrite(device1, LOW);

}
}

separate out the command decoding and the resulting action .... reception of /on should set a flag ... reception of /off and /delay should clear the flag and set turnoff time   ... the device control is done after the if statements have completed

You have various logic problems:
You block until WiFiClient has bytes available. Everything comes to a stop. So if you send a "/delay" command, it will receive and parse that command, turn on the device, then block again, indefinitely, until you send another command. Once you send another command, it will check the interval ONCE, and then lock up again. You need to rewrite your loop to check for bytes, read them if found, and do other work (like checking your time interval) if no bytes are available.
Next, your timing code is a mess. You only ever set currentMillis and previousMillis at the same time, so they will never be different. And you only ever check the times once when you first detect a "/delay" command.
Instead, refactor your logic. Only set previousMillis when you first detect the delay command, and then only compare if previousMillis to currentMillis if  previousMillis is not 0:
if (req.indexOf("/delay") != -1)
{
    previousMillis = millis();
}

if (previousMillis != 0 && millis() - previousMillis >= interval) {
    digitalWrite(device1, LOW);
    previousMillis = 0;
}

(Also note that you were declaring a second, independent variable  previousMillis inside your if statement, which only exists inside the curly braces for that if statement. Don't do that. Use the existing global variable you defined, as I show in my edited code.)

its not working. im confused.could anyone write the whole sketch in correct way  for me please


text:
Arduino read thermocouple Type K with ADS1115
I ordered a ADS1115 so I could measure temperature of a type K thermocouple, but I am not managing to get accurate readings. I had it working while having a normal A0 pin, but since the type K table shows pretty low voltages, the 0-1023 scale is not accurate.
When the thermocouple is at room temperature (around 22°c), it shows 00.0 millivolts on the multimeter (which I dont understand since it does not match with the table), and my program outputs a value of around -40 and a voltage of -0.005. When I heat it up until I measure 10.0 millivolts (around 250°c according table), the Arduino prints a value of 53 and a millivolts of 300.
What am I doing wrong? I suspect something with the calculation, but I am not able to find out how I should do it, I know very little about millivolts.
Can someone help me out what I am doing wrong here and what I should do?
I have the thermocouple and ADS1115 connected as shown in the image below.

The code I am using is as following
#include <Adafruit_ADS1X15.h>

const int analogFruitPin = 0;

Adafruit_ADS1115 ads;

void setup()
{
  Serial.begin(9600);
  ads.begin();
  ads.setGain(GAIN_FOUR);
  ads.setDataRate(RATE_ADS1115_860SPS);
}

void loop()
{
  int sensorValue = ads.readADC_SingleEnded(analogFruitPin);
  float voltage = sensorValue * (5.0 / 32768.0);
  Serial.println(voltage,3);
  Serial.println(sensorValue);
  delay(500);
}

it shows 00.0 millivolts on the multimeter ... how did you measure this?

I just measure at the + and - of the thermocouple with a normal multinmeter, it does increase the measurement of the multimeter when i heat it up

See the library function computeVols() on how the voltage is calculated versus your sensorValue * (5.0 / 32768.0).

@Bart, when you get around to it, you should accept an answer that addresses your question or rephrase your question.  That will trigger emails to all so far involved to give them a chance to rephrase their answer.  Also, if you were wondering why bother w/a thermocouple if you need a 2nd more conventional temperature sensor ... well, thermocouples can work in extreme heat (like a pottery kiln) and they are inexpensive.

Welcome! Interesting but expected. Thermocouples need what is called a cold junction compensation. That is a circuit or another thermonuclear that compensates for the thermocouple effect where the lead wires are connected to your measuring device. These thermocouple lead wires should be the same metallic material as the wires in the thermocouple. The metals are different where you connect to the measuring device and will generate a voltage as the temperature changes regardless of the sensing probe, that is how the thermocouple works. This link will help: https://www.tegam.com/what-exactly-is-cold-junction-compensation/
For more information check this link: https://randomnerdtutorials.com/arduino-k-type-thermocouple-max6675/

So, this means I could never measure it with some sort of accuracy?

... not w/o a cold reference.  For example, a DMM with a thermocouple feature has an additional temperature sensor close to where the thermocouple wire connects to the wires (creating the 2nd junction) that then connect to the ADC.  Ideally we want to know the temperature of the 2nd junction.  You should up-vote or accept @Gil's answer.  But I'll add an answer pointing you to an Adafruit product that contains both the ADC and the cold junction temperature sensor.

To simplify your thermocouple temperature sensor project, consider using an ADC which also contains a cold junction temperature sensor.  This product from Adafuit.com integrates both into one package by using a Microchip.com MCP9601 integrated circuit.
In short, thermocouples generate small amounts of voltage where dissimilar metals touch. This is true where the thermocouple wires are touching each other. And is also true where the thermocuple wires are touching the metal connecting them to the ADC circuit (commonly called the "cold junction"). To find the temperature where the thermocouple wires are touching we need to subtract the effects of the "cold junction". To do that, we need to first know the temperature of the "cold junction". We commonly do this with a second temperature sensor as it is a more practical (and portable) solution than a traditional zero centigrade ice bath (likely where the term "cold junction" came from).


text:
Attiny85 appears to be drawing 0.2mA current but battery running down more quickly
I am trying to get a temperature sensor (tmp36) working with an Attiny and if possible I would like it to run for several weeks. I have tried to power down the Attiny and it appears to be drawing only 0.2mA current when asleep, and around 4mA when awake (using a multimeter). However the CR2032 battery went from 3.24V to 2.9V in about 1.5 days.  If it was really only using 0.2mA I would have thought it would go down much more slowly than this.
I wonder if it's using a lot of current every 8s when it turns on briefly and I'm not seeing this on the multimeter, or drawing a lot of current every hour when it reads the temperature or is there something else that I'm missing.
My circuit is an Attiny85 connected directly to a tmp36 temperature sensor.  I have a capacitor connected across the GND and Vcc of the tmp36.  Since I am using a surface mount tmp36 I also have the shutdown pin on the tmp36 pulled high (connected directly to Vcc). Otherwise there are no other connections, it's a very simple circuit and since the current normally appears to be 0.2mA I'm not sure why the battery voltage reading is going down so fast.
I am new to turning off the attiny(and still pretty new to arduino programming) and I copied most of the code for putting the arduino to sleep from here: https://folk.uio.no/jeanra/Microelectronics/ArduinoWatchdog.html
(and possibly other places).
The code I have is as follows:
#include <stdlib.h>
#include <EEPROM.h>
#include <SoftwareSerial.h>

#include <avr/sleep.h>    // Sleep Modes
#include <avr/power.h>    // Power management
#include <avr/wdt.h>      // Watchdog timer
#include <avr/interrupt.h> // Interrupts handling

// Definitions
#define rxPin 3
#define txPin 4

// 0 1 0 Internal 1.1V Voltage Reference, calling INTERNAL should set the            reference voltage to 1.1

SoftwareSerial mySerial(rxPin, txPin);

int currentTime = 0;
int timeLastSaveFullTemp = 0;

int nbr_remaining;
int sensorPin = 7; // This is the 7th pin on the ATtiny85,

                         // it is an analog input when reading as digital  call it 7? analogpintochannel function
                         // (On the HLT tutorial it is labelled as Pin2:  Analog input 1, SCK )

float temperature = -500.00f;     // Create a new float called temperature and give it the value -500 to start with
float prevTemp = -500.00f;
float tempDiff = -500.00f;

int tempAsInt = 0;
int tempDiffAsInt = 0;  // create int to store temperature difference between samples

signed char tempDiffAsChar; // create char to store temp difference between samples, hopefully this saves as a 1 byte no. between -128 and 127 (will store like this on EEPROM where difference is small enough since only 1 byte) (range around -128 to 128 so can't use for temp diff greater than 10 deg)
signed char warningNextDataIsTwoBytes = 111;

int eepromAddress = 0;       // initialize variable for position in eeprom to store data collected

int decideWhatToSaveFlag = 1;    // Decide what to save,  if this = 0 then save the temp difference as a char (1 byte), otherwise save the entire temperature as an integer.

// interrupt raised by the watchdog firing
// when the watchdog fires during sleep, this function will be executed
// remember that interrupts are disabled in ISR functions
ISR(WDT_vect)
{
        // not hanging, just waiting
        // reset the watchdog
        wdt_reset();
}

// function to configure the watchdog: let it sleep 8 seconds before firing
// when firing, configure it for resuming program execution
void configure_wdt(void)
{

  cli();                           // disable interrupts for changing the registers

  MCUSR = 0;                       // reset status register flags

                               // Put timer in interrupt-only mode:
  WDTCR |= 0b00011000;            // Set WDCE (5th from left) and WDE (4th from left) to enter config mode,
                               // using bitwise OR assignment (leaves other bits unchanged).
  WDTCR =  0b01000000 | 0b100001; // set WDIE: interrupt enabled, 8 seconds
                               // clr WDE: reset disabled
                               // and set delay interval (right side of bar) to 8 seconds

  sei();                           // re-enable interrupts

}

// Put arduino to sleep.
void sleep(int ncycles)
{
 nbr_remaining = ncycles; // defines how many cycles should sleep

  // Set sleep to full power down.  Only external interrupts or
  // the watchdog timer can wake the CPU!
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  // Turn off the ADC while asleep.
  power_adc_disable();

  while (nbr_remaining > 0){ // while some cycles left, sleep!

  // Enable sleep and enter sleep mode.
  sleep_mode();

  // CPU is now asleep and program execution completely halts!
  // Once awake, execution will resume at this point if the
  // watchdog is configured for resume rather than restart

  // When awake, disable sleep mode
  sleep_disable();

  // we have slept one time more
  nbr_remaining = nbr_remaining - 1;

  }

  // put everything on again
  power_all_enable();

 }

// the setup routine runs once when you press reset:
void setup() {
  analogReference(INTERNAL);    // This sets the internal ref to be 1.1V (or close to this), note that this makes 1.1V the highest voltage. The TMP36 gives 1.1V at around 55 or 60 deg so need to not put the chip in temperatures hotter than 55deg
  pinMode(sensorPin, INPUT);    // make pin 7 on the ATTiny an input pin

  delay(1000);

  configure_wdt();              // configure the watchdog

  mySerial.begin(9600);         // begin software serial at rate of 9600

}

// the loop routine runs over and over forever:
void loop() {

  sleep(450);                                                 // sleep for a given number of cycles (here, 450 * 8 seconds = 60mins) in lowest power mode

  currentTime = currentTime + 60;                             // add 60 min to current time

  if((eepromAddress<=510))                                    //  the eeprom still has space
  {

/***********Get temperature from sensor, then calculate difference since previous reading****************/

//Earlier set the reference voltage for the analog to digital converter to 1.1V.  This means a value of 1.1V will be read as the maximum (not sure if 1023 or 1024, but anyway)
//Note that this means an input greater than 1.1V from the temperature sensor (temperature about 55deg) is bad, not sure if it will damage the circuit or give bad readings but avoid.

temperature = analogRead(sensorPin)*1100.0/1024.0;  // read value on pin 7, between 0 and 1023 where 1023 is max, convert result back to a voltage in millivolts.
temperature = (temperature - 500)/ 10;              //Celcius temperature = [(analog voltage in mV) - 500] / 10
tempDiff = temperature - prevTemp;

/******* Change temperature diffence to integer and a signed char if it's between -2 and 2 deg ***********/
tempAsInt = int(round(temperature*10));  // multiply temp. by 10 then round and change to an integer type, this should give temp. as a three digit integer scaled by x10, e.g. 335 = 33.5deg, 120 = 12.0deg etc.
tempDiffAsInt = int (round(tempDiff*10));

// work out whether want to save complete temperature or just temp difference
if ((currentTime - timeLastSaveFullTemp) >=10)           // If the entire temperature hasn't been saved for more than 10 min, then want to save the entire temperature rather than just difference
{
  decideWhatToSaveFlag = 1;                               // Set flag to 1, since want to save entire temperature
  }
else
  decideWhatToSaveFlag = 0;                               // If the entire temperature has already been saved recently then set flag to zero since only want to save the difference.

if ((tempDiffAsInt>-20 and tempDiffAsInt<20)and (decideWhatToSaveFlag == 0))    // if temp change is less than 2 degrees and if the decideWhatToSaveFlag hasn't been previously set to 1 for another reason.
  tempDiffAsChar = (char)(tempDiffAsInt);

else decideWhatToSaveFlag = 1;                                                  // if the temp diff since prev sample is > 2 degrees or less than -2 degrees then set flag to 1 since want to save the entire temp. not just the difference

if (decideWhatToSaveFlag == 0)
  {
  //mySerial.print(" Temp diff");
  EEPROM.put(eepromAddress, tempDiffAsChar);
  eepromAddress = eepromAddress + sizeof(tempDiffAsChar);
  }

else
  {
  EEPROM.put(eepromAddress, warningNextDataIsTwoBytes);
  eepromAddress = eepromAddress + sizeof(warningNextDataIsTwoBytes);
  EEPROM.put(eepromAddress, tempAsInt);
  eepromAddress = eepromAddress + sizeof(tempAsInt);
  timeLastSaveFullTemp = currentTime;                       // Update time entire temperature was last saved to the current time.
  }

prevTemp = temperature; // copy temp to prev temp for next time.

}

}

Please excuse my coding I'm still learning.  I deleted my comments at the start of the program which explain why I'm changing the temp. to char etc. as they weren't really relevant to this question but if anyone wants them let me know.
Here is the circuit, a 3V battery is connected between Vcc and GND.  The capacitor is 0.1uF ceramic.  I am using the SOIC (surfacemount) type package of the tmp36, the (not) shutdown pin in the SOIC version needs to be pulled high so I have connected it to Vcc as specified in the datasheet (this pin doesn't exist in the TO92 through-hole version of the tmp36).

All help is greatly appreciated,
I'm also interested in suggestions for reducing the current further.  (Or for how to store more temperatures in a 512 byte EEPROM but that's less important than the battery)
Thanks very much!!
p.s. I have tested this code and it did save one temperature per hour as expected. (The section of code that saves temperature differences rather than temperature doesn't run when there is a 60 min gap between temperatures so all temperatures were saved to the eeprom as integers).

0.2mA is noise to most DMMs. What are you using to measure it?

I tried one $5 DMM and another slightly better one but brand Jaytech so not really particularly accurate probably, but I would have thought if the current was 1mA or more it would say so.  Unless it's oscillating up and down quickly or something.

Going to try changing the clock speed to 1MHz (from 8MHz) to see if that helps...

I uploaded your code to my Attiny85 (nothing connected to it) and got 0.2 mA current draw at 3V. That actually sounds far too high for sleeping, it should be more like 6µA rather than 200µA.

@IgnacioVazquez-Abrams Measurement error does not seem to apply in this particular case. Possibly other things in the (unposted) circuit are drawing more than expected.

I've just realized that was a silly thing to say, as I got that current draw myself, with nothing connected. So, code problem. :)

Using this calulator http://oregonembedded.com/batterycalc.htm you'd end up with around 42 days of run time. PS power_adc_disable doesn't actually do anything unless you've already disabled the ADC using ADCSRA &= ~_BV(ADEN);, as power_adc_disable only updates the PRR register.

2.9V doesn't sound too bad. See a datasheet for the CR2032 I found:

It looks like slightly more than 2.9V would be the expected voltage for up to 600 hours.
3.2V looks like it is fully charged, and won't stay at that level for long.
Having said that, 200 µA current sounds like a lot. You should be able to get it down to 6 µA. Perhaps post your schematic?

After a bit of experimenting I got the current draw down to the (expected) lower level of 4.25µA running at 3V, and 6.77µA running at 5V.
You had not in fact turned the ADC off. You need to change:
 // Turn off the ADC while asleep.
  power_adc_disable();

To:
  // Turn off the ADC while asleep.
  ADCSRA = 0;            // turn off ADC
  power_all_disable();

I can't comment on what extra draw, if any, your TMP36 will cause, however this should help get the overall current down.

Of course, you need to put the ADC back on afterwards, so this might be better:
  // Turn off the ADC while asleep.
  byte saved_ADCSRA = ADCSRA;
  ADCSRA = 0;            // turn off ADC
  power_all_disable();

  ... sleep here

  power_all_enable();
  ADCSRA = saved_ADCSRA;

oh, thanks!! This looks like the problem,  it looks like I need to test it for more than 1.5 days then.  I did notice it was already 3.14 after an hour or so. I will try testing it for a few days and then accept your answer assuming that was the problem (which it seems like it is).  I hope so :)  I just tried changing the frequency to 1MHz (from 8MHz) which lowered the ON current and sleep current remained about the same.  Will post circuit, I think perhaps I can turn off the tmp36 but haven't tried yet, was a bit worried it might not turn on again or something.

...also it's possible it's not using 0.2mA as I don't have a high accuracy multimeter.

I will set up a few circuits and run them for a week and see how long they last :), then get back to you, thanks again!!  (I need to wait until tomorrow to start, unfortunately all the shops which potentially sell batteries in the small town where I Iive at the moment have already closed for today).

p.s. thanks again, I also read your webpage about how to lower current draw a month or so ago and it really helped a lot, otherwise probably wouldn't have gotten this far even.

In my amended reply I show how to get the current draw down to 4.25µA (excluding whatever the TMP36 takes).

all the shops which potentially sell batteries in the small town where I Iive at the moment have already closed for today - your existing batteries should be fine. After all, you only ran them for 36 hours, and it should last 600 hours at 0.19 mA according to the datasheet.

I just tried changing the frequency to 1MHz (from 8MHz) which lowered the ON current and sleep current remained about the same - yes, well in power-down sleep mode the clock isn't running so it won't make any difference. The bad side-effect of a slower clock is it takes longer while it is awake (8 times as long in your case) which is something you don't want. You don't want it to be awake for longer than necessary.

Hi, thanks very much!! I will try the changes and get back to you, probably early next week or hopefully sooner.  I've found someone with a proper multimeter now and it was actually using about 0.2mA.I should be able to check it again once I've made the changes, hopefully in the next few days if they are at work.  I didn't want to keep using the same battery as I accidentally connected my attiny to the USB power supply on the computer and forgot to turn the switch connecting the battery off, the battery still works but it got very hot and I wouldn't completely trust any capacity results.

p.s. the tmp36 datasheet says 50uA so it should be ok even when turned on, if change the circuit and turn it on and off it should be 5uA.

Hi Nick, thank you very much, after adding your changes to turn the ADC off (and on again) it's now reading 30uA, not sure how accurate my multimeter is but it's certainly less than the 0.25mA it was reading before.  I imagine most of the current is from the temperature sensor so later I will probably try to turn the temperature sensor on and off with the microcontroller.  (Will put the frequency back to 8MHz later too.)

THIS IS NOT AN ANSWER; it's just a very long comment and I was not able to add all the formatting and ideas in the comment I was writing. Please don't consider it as a valid answer.
I leave all the low current topics to Nick, since he's doing a great work as usual. I wanted just to give you some ideas for the temperature acquisition and storing.
First of all, the floats. Forget them. floats are one of the worst things you can do to your poor microcontroller, unless you have an onboard FPU.
I haven't checked your sensor, so I assume that the calculations you performed were correct. (Note: voltages above 1.1V should not damage the board, but will not be detected - the value will cap at 1023)
So when you read number X (from 0 to 1023) you get the temperature by writing
((X * 1100 / 1024) - 500) / 10

You are using floats to do this. I don't like them at all, so let's switch to ints. Moreover you decided to store them with a 0.1°C precision, so that /10 is meaningless. So in the end
<integral type> finalTempInTenthsOfDegree = ((X * 1100 / 1024) - 500);

Now, the types. The value of the final temperature is between +60°C (corresponding to 1.1V) and -50°C (0V - not sure about this, but let's stick with these value). This means an integral value going from +600 to -500; the proper type is therefore int16_t (signed 2-bytes value). During your calculations, the X (which is a uint16_t) is multiplied by 1100; this value can rise up to 1125300 (when X = 1023), which does not fit a 2-bytes variable. You can reduce 1100/1024 to 275/256, but this does not solve the problem.
EDIT: As Edgar Bonet pointed out in the comments, the problem of having a 4 bytes is not solved with this trick, but dividing by 1024 is more "time consuming" than dividing by 256 (because the 10-bit shift involves shifting bits through bytes, while a 8-bit shift is just moving the bytes. His tests (avr-gcc 4.9.2, optimization for size -Os) show that a shift by 10 bits (=division by 10) is converted in a routine to shift one bit through all the four bytes and then this is repeated 10 times. This lead to 72 clock cycles. A 8-bit shift, on the other hand, was converted to a byte movement for three out of four bytes and the zeroing of the uppermost. So 4 clock cycles. So... Yes, this does not solve the problem, but can optimize the code; I'll think of this trick in my future projects. Of course this can be done in a much more optimized way, and the number of cycles required can change according to the way the operation is written and the optimization level, but it is worth remembering that if you shift by a multiple of 8 bits (on an 8-bit machine) it is more optimized than another arbitrary value.
In any case, even with either of the two values, a 4-bytes int is required. In order to reduce unnecessary overhead, let's switch it back to a 2-bytes whenever possible. Something like
int16_t finalTemp = ((int16_t)((((uint32_t)X) * 1100U) / 1024) - 500;

So the operation order is

Take the X value
Promote it to a unsigned 32 bit variable
Multiplicate by 1100 (values from 1125300 to 0)
Divide it by 1024 (values from 1098 to 0)
Cast it back to a signed 16 bit value
subtract 500 (values from 598 to -500)

Now, the storage. If you store the values as they are, you will get 256 measurements, which at one measurement per hour mean something like 10 days.
One easy way to increase this space is noticing that you are using only 11 bytes out of 16. So you can compact it and get 372 measurements (around 15 days)
The trick you used (ten measurements with just the difference) is ok only if you guarantee that in ten hours the value will not drift by more than +/- 12°C.  This is not guaranteed and probably also not optimal. I'd prefer another approach, which is based on the fact that you are using only 11 bytes out of 16. You can have two different data stored in the EEPROM, which are differences (1 byte) or whole temperatures (2 bytes). You will distinguish them with the first bits: a 0 denotes a difference, a 1 a whole temperature (followed by 0 is the low byte, by a 1 is a high byte). This means that for the difference you have seven bits, so it can range from +63 to -64. Whenever you reach a difference from the previous temperature within 6 degrees you don't save anymore the whole temperature. The code to do this is for instance the following one:
// int16_t finalTemp calculated before
// int16_t prevTemp initialised, at beginning, for instance to -32000, so the difference is greater and you force a full writing at the first round

int16_t tempDiff = finalTemp - prevTemp;
prevTemp = finalTemp; // update the temperature

if ((tempDiff <= -63) || (tempDiff >= 63)
{
    // In this case we want to save the whole integer
    EEPROM.update(eepromAddress++, (((uint8_t)finalTemp) & 0x3F) | 0x80); // Write the lowest 6 bits, and set the first two to 0b10
    EEPROM.update(eepromAddress++, (((uint8_t)(finalTemp >> 6)) & 0x3F)| 0xC0); // Write the highest 6 bits, and set the first two to 0b11
}
else
{
    // In this case we save only the difference
    EEPROM.update(eepromAddress++, ((uint8_t)tempDiff) & 0x7F); // Just remove the highest bit, and store it
}

In this case, provided that the temperature does not vary a lot, you will get 511 measurements, which is like 21 days. For each variation greater than 6°C/h you will lose one hour of measurement, down to 256 measurements. Please note that I wrote EEPROM.update instead of write, even if this is not necessary (just one of the things I do every time).
The last possibility is to switch to a 0.5°C resolution. If you use this resolution, you can map your values on a range 120/-100, thus being able to use only one byte for each measurement. Since the accuracy is +/- 2°C, you can also choose this without problems.
Apart from the storage, if you record only 256 bytes of information how do you know which are the correct values and which are the previous ones? My suggestion is to reserve one value (for instance if you have used my code you can get an impossible value such as 0x40 - which if I'm not wrong maps to DIFFERENCE -64, which is impossible since the difference is stored only when greater than -63) and fill the memory before starting to insert the values. beware that if you do it then turning on the board will reset the memory...
One last suggestion: you have a sensor which stores the data internally, but.. How do you get them out of it? My personal suggestion is to have a dedicated pin (for instance PB3) tied to a jumper. If it is open then you will proceed with the normal program, otherwise you wait for a download request. (don't do the opposite since the jumper inserted drains the battery). Consequently the code can be something like this:
const uint8_t invalidEepromValue = 0x40;
const int16_t maxAddress = 510; // Not equal to 512 to avoid a last reading of 2 bytes

void dumpMemory()
{
    int16_t prevTemp = 0;
    for (int16_t i = 0; i < maxAddress; i++)
    {
        int16_t value = EEPROM.read(i);
        if (value == invalidEepromValue)
            break; // Finished the reading

        if (value & 0x80)
        { // WholeData
            int16_t value2 = EEPROM.read(i+1);
            if (((((uint8_t)value) & 0xC0) != 0x80) || ((((uint8_t)value2) & 0xC0) != 0xC0))
            {
                mySerial.print("Error with memory cell ");
                mySerial.println(i);
                continue;
            }

            prevTemp = (value & 0x3F) | ((value2 & 0x3F) << 6);
            if (value2 & 0x40) prevTemp |= 0xF000; // Extend the sign

            mySerial.println(prevTemp);
            i++; // skip the next value (already analysed)
        }
        else
        { // Difference
            if (value & 0x40) value |= 0xFF80; // Extend the sign

            prevTemp += value;
            mySerial.println(prevTemp);
        }
    }
}

void setup() {
    pinMode(modePin, INPUT_PULLUP);
    mySerial.begin(9600);         // begin software serial at rate of 9600

    delay(1);
    if (digitalRead(modePin) == LOW)
    { // Enter read mode
        while (1) // loop forever
        {
            while (mySerial.available() == 0); // Wait for some chars

            dumpMemory();

            while (mySerial.available() > 0)
                mySerial.read(); // Flush receiving buffer
        }
    }

    // Clear the memory
    for (int16_t i = 0; i <= maxAddress; i++) // Equal to cover the last reading of 2 bytes
        EEPROM.update(i, invalidEepromValue); // Here update is almost mandatory

    // Go on with the initialization you already implemented
    ...
}

I hope that the software serial works even without the main structure (so in a while(1) in the setup).
Please keep in mind that all the code written here has NOT been tested, so it may require some corrections

You wrote: “You can reduce 1100/1024 to 275/256, but this does not solve the problem.” It may not solve the problem, but it can be used as an optimization. Dividing an unsigned number by 256 is almost free, as it only involves moving bytes. Dividing by 1024, on the other hand, requires extra shift instructions.

Thank you very much, I really appreciate the time taken to help.  I will have a look at the current first and once that's working have a look at this.  Actually my problem is a bit bigger than 1 point per hour. I plan to measure skin temperature of bats and ideally it would be good to have one temperature per 10 minutes for 10 days or longer.  Since with 512 bytes I'm not sure if that's possible I'm thinking what would be best, I really only need to know if the bats lower their body temperature (use torpor) so perhaps I will do one point per hour and then....

increase the frequency to 10 minutes if the temperature changes.  Though of course any time I change the frequency I also need to record the time so I can work out at what time each temperature was recorded.  Overall therefore a better option might be to put up with a lower sample rate such as one point per half hour. It could be enough, I will have to test it and see which one is best for the information I'm trying to record.

Anyway, thank you very much, I will definitely look at this properly and probably use it, have upvoted it.  Sure it will also be useful to anyone else doing similar things. Thanks also about the float comments, good point, I don't really need them at all!

@EdgarBonet Seems reasonable; did you ever test if the compiler is this smart? I cannot test it these days, but it would be useful to check the actual generated code. In any case thank you for your contribution :)

I just gave it a try with avr-gcc 4.9.2 at -Os. The division by 1024 compiles to a loop of 10 iterations, each shifting the 4 bytes of the number one by one. With the loop overhead, the total execution time is 72 CPU cycles. The division by 256 compiles to an instruction that clears one byte, and three register moves. Total execution time is 4 CPU cycles. Both codes are sub-optimal. By reassigning registers, the division by 1024 could be done in 6 cycles and the division by 256 in 0 cycles.

@EdgarBonet Impressive as usual! Thank you. If you agree, I'll add these info in the answer not to lose them

Yes, sure, I'll be glad if you do so!

@EdgarBonet Done. Thank you for your idea and tests :)