text:
How to get DHT11 temperature/humidity sensor to update on Arduino Uno
Trying to program a way to control my thermostat by interfacing it with my Arduino Uno. I am using a DHT11 to read temperatures and humidity. However, after making its first reading, it is not updating after that. I have included the reading in a loop that waits 2.5 seconds between readings to give the sensor time. However, its not updating. I tested the DHT11 with the example code that came with the DHT library and it is in itself functioning. To test it I have directed a warm hairdryer to the DHT sensor, but the readings dont change. However, when I reset it, the sensor will then show the higher reading initially but then wont update like before.
As well, the the photoresistor in the system will update its lux readings the whole time.
I have included the code below. Any help greatly appreciated! (sorry if the code is a bit messy, I am a novice programmer)
#include <LiquidCrystal.h>
#include <dht.h>

dht DHT;

#define DHT11_PIN 8
#define BOUNCE_DURATION 400
unsigned long checkLCD = 0;
volatile unsigned long bounceTime = 0;
unsigned long refreshBut = millis();
volatile int desiredTemp = 21;
boolean AC_on = true;
unsigned long checkBut = 0;
int temp = 0;
int humi = 0;
unsigned long lastTime = 0;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 10, 9);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  Serial.begin(9600);
  // Print a message to the LCD.
  lcd.print("DHT test");
  Serial.println("DHT TEST Type,\tstatus,\tHumidity (%),\tTemperature (C)");
  pinMode(3, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  pinMode(13, OUTPUT);
  pinMode(A1, INPUT_PULLUP);
  testDHT(); // testing DHT sensor

}

void loop() {
   if (millis() > lastTime)
  {
    temp = DHT.temperature;
    humi = DHT.humidity;
    lastTime = millis() + 2500;
    Serial.println(temp);
  }

  int luxSEND = -0.066433 * analogRead(A0) + 81.467234; //lux reading
  unsigned long refreshLCD = millis();
  int upBut = digitalRead(2); //up button
  int downBut = digitalRead(3); //down button
  int changeAC_send = digitalRead(A1);//read button for change between heating and AC
  unsigned long refreshBut = millis(); //for button for change between heating and AC

  displayReadings(humi, temp, luxSEND, refreshLCD, desiredTemp); //display on LCD - humidity, temperature, lux

  attachInterrupt(digitalPinToInterrupt(2), upButtonOn, FALLING);//Up in desired temp
  attachInterrupt(digitalPinToInterrupt(3), downButtonOn, FALLING);//Down in desired temp

  changeAC_on (changeAC_send, refreshBut); //change between heating and AC

  if ((temp > desiredTemp) && (AC_on == true)) { //AC structure
    digitalWrite(13, HIGH);

  }
  else if ((temp < desiredTemp) && (AC_on == false)) { //Heat Structure
    digitalWrite(13, HIGH);

  }
  else {
    digitalWrite(13, LOW);

  }
}

void displayReadings (int h, int t, int lux, unsigned long refreshL, int desiT) {
  if (refreshL >= (1000 + checkLCD)) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("T:");
    lcd.print(t);
    lcd.print("C  ");
    lcd.print("H:");
    lcd.print(h);
    lcd.print("%");
    Serial.print(h, 1);
    Serial.print(",\t");
    Serial.print(t, 1);
    Serial.print(",\t");
    lcd.setCursor(0, 1);
    lcd.print("L:");
    lcd.print(lux);
    lcd.print("   ");
    Serial.println(lux);
    Serial.print(",\t");
    lcd.print("Des.T:");
    lcd.print(desiT);
    lcd.print("C");
    checkLCD = refreshL;
  }

}

void testDHT () {
  // READ DATA
  lcd.clear();
  Serial.print("DHT11, \t");
  int chk = DHT.read11(DHT11_PIN);
  switch (chk)
  {
    case DHTLIB_OK:
      Serial.print("OK,\t");
      break;
    case DHTLIB_ERROR_CHECKSUM:
      Serial.print("Checksum error,\t");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Can't get reading");
      lcd.setCursor(0, 1);
      lcd.print("from DHT");
      break;
    case DHTLIB_ERROR_TIMEOUT:
      Serial.print("Time out error,\t");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Can't get reading");
      lcd.setCursor(0, 1);
      lcd.print("from DHT");
      break;
    default:
      Serial.print("Unknown error,\t");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Can't get reading");
      lcd.setCursor(0, 1);
      lcd.print("from DHT");
      break;
  }
}

void upButtonOn () {
  if (millis() > bounceTime) {
    Serial.println("Up Pressed");
    desiredTemp = desiredTemp + 1;
    bounceTime = millis() + BOUNCE_DURATION;
  }
}

void downButtonOn () {
  if (millis() > bounceTime) {
    Serial.println("Down Pressed");
    desiredTemp = desiredTemp - 1;
    bounceTime = millis() + BOUNCE_DURATION;
  }

}

void changeAC_on (int changeAC, unsigned long refL) {
  if (refL >= (200 + checkBut)) {

    if ((changeAC == LOW) && (AC_on == true)) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("HEATING MODE");
      Serial.println("Heat On");
      AC_on = false;
      checkBut = refL;
    }

    else if ((changeAC == LOW) && (AC_on == false)) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("A/C MODE");
      Serial.println("AC On");
      AC_on = true;
      checkBut = refL;
    }
    else {
      checkBut = refL;
    }
  }
}

Additionally, here is a sample of the output from the serial monitor, while a hairdryer is being directed at it:
    DHT TEST Type,  status, Humidity (%),   Temperature (C)
DHT11,  OK, Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 52
,   40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 51
,   40, 29, 52
,   Current read temperature is: 29
40, 29, 52
,   40, 29, 52
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54

DHT.read11 reads the temperature from the sensor. You call that once from setup function but not from the loop function. Therefor the DHT11 sensor is read just once during startup.
You should not use millis like that. The blink without delay example shows how to use millis.


text:
Button to stop a stopwatch not working correctly!
I'm trying to implement a stopwatch with an LCD display, and I'm supposed to be using the attachInterrupt command to catch the button press. The clock runs perfectly, but the button input isn't caught or acted upon at all.
In void setup(), I have set it up this way: attachInterrupt(digitalPinToInterrupt(buttonPin), buttonInterrupt, RISING);.
And the buttonInterrupt function only does start = !start, so in a sense just flipping the start variable.
This is the updated version of the code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int buttonPin = 7;
volatile int buttonState;
int lastButtonState;
long sec;
long startTime;

void setup() {
  lcd.begin(16, 2);
  pinMode(buttonPin, INPUT_PULLUP);
  lcd.setCursor(0,0);
  lcd.print("Push the button!");
  attachInterrupt(digitalPinToInterrupt(buttonPin),buttonInterrupt,HIGH);
}

void loop() {

  buttonState = digitalRead(buttonPin);
  if(buttonState == LOW){
    startTime = millis();
  }

  while(buttonState == HIGH){
    long time = millis();
    long z = (time - startTime);
    sec = (z/1000);
    long ms = z%1000;
    lcd.setCursor(0,1);
    lcd.print(sec);
    lcd.print(".");
    lcd.print(ms);
    lcd.setCursor(8,1);
    lcd.print("Secs");

    if(buttonState == LOW){
      break;
    }
  }
}

void buttonInterrupt() {
  if(buttonState == LOW){
    buttonState = HIGH;
  }else{
    buttonState = LOW;
  }
}

The loop function works as far as time counting is concerned, but doesn't work to stop the time with the button. Any help is appreciated, I'm extremely new to Arduino (literally started yesterday). My circuit looks like this: https://i.sstatic.net/XHHy5.png
If there is any other way to print the numbers other than printString, more than happy to hear them!
Thanks!

In your wiring diagram the button has a pullup resistor? Are you sure, that this resistor is not connected to ground instead? Also I cannot see anything for debouncing the button. You won't get good results without debouncing

@chrisl you are right, it is supposed to be connected to GND, but fixing that doesn't solve my issue either! And unfortunately I do not know what debouncing means! Will have to look that up now. Thanks!

is variable start volatile?

@Juraj, no it was not. But even I switch to volatile, it does not seem to help.

You need to set msStart to the current millis() value after the while loop. A better way would be to make the code non-blocking like in the BlinkWithoutDelay example. Also don't expect the stopwatch to be too precise because the code in your while loop will take some time and therefore sec=sec+1; will not be executed exactly every 1000 ms

Another tip: be consistent with the datatype of start. If it is a boolean, you better use true\false. If it is an integer, you better don't use the NOT-operator (!). If start becomes 1 at one point, start=!start will make it toggle between 1 and 254, which probably is not what you intended

You better post the whole, compilable code, so things like the datatype of start are clear to people reading the question.

@Sim Son thanks for your answer! I have tried a different way of flipping the start variable, now that you mentioned boolean, it's clear to me my way didn't make any sense to flip 0 to 1. That being said, this solution did not fix the issue, and I'm not sure how to set msAtStart to millis() as this causes the stopwatch to tick to 0.1s and then tick back to 0.0. Thanks for your help! I have posted the whole, compilable code in my question body now.

Does it start when you press the button, though?

@ocrdu nope, it does not! if i set start = 0; it doesn't start at all, and if i put it to 1, the timer starts as soon as I start the program.

Nothing at all from the button then. With the answer you got you from Edgar Bonet you should be able to get it to work. Get that button wired up properly first, and see what happens. Or I could post working code, but where's the fun in that?

@ocrdu I wired it up correctly and tried a different method now. The button input works now - at the click of the button, the timer starts, but a second click doesn't stop it. So now the problem is with debouncing maybe or just my interrupt function. I still don't quite get debouncing so will have to read a bit about that, but atleast the button and the clock are working sort of OK.

@ocrdu now I just cannot figure out how to get an "updated" button state that will kill the while loop and let the output stay there. that is what the Interrupt is supposed to do, but the state switch in the interrupt funct from LOW to HIGH / HIGH to LOW doesn't seem to reach the while loop. Quite confused...

Loop() already loops. Lose the while. If buttonState == HIGH, calculate and display time passed. Otherwise, do nothing.

Oh, I see you changed the code. Don't set buttonState in the loop(), leave that to the interrupt. You can worry about resetting the startTime later. And don't use INPUT-PULLUP unless the switch connects the input pin to LOW.

There are several issues here. First and foremost, your button is wired
incorrectly. If you connect one end of the button to +5V, then the other
end should have a pushdown to GND, like here:

(Image from the Arduino Button example).
The second issue is the lack of debouncing. You should ignore the rising
edges you sense for a few milliseconds after you record one.
The third issue is the timekeeping. As explained by Sim Son, your
seconds will not be very accurate. It's better to just count the
milliseconds elapsed since the button press, and then break the count
into full seconds and remaining milliseconds.

Hi @edgar bonet - thanks so much for the answer! I have fixed a couple of things you talked about here. the stopwatch now starts upon the press of a button, but a second button press doesn't stop it. I assume that's because of the interrupt function, but I don't see where exactly the problem is. Any help is appreciated! Thanks. I have posted the updated code in the main body of the question. The debouncing I have not quite understood and haven't implemented yet.

@Raighley: The code now is a mess, and I can't quite understand what it is trying to do. If you use INPUT_PULLUP, you don't need a pulldown, and the button is active when LOW. attachInterrupt() doesn't support a HIGH mode. There is no point in using both digitalRead() and attachInterrupt(). buttonState seems to serve two unrelated purposes. lastButtonState is never used... I suggest to restart from scratch: forget about interrupts, read about “button bounce”, and use a debouncing library.

source: Stack Exchange

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

sort: votes


text:
Why is my transistor switched output so low?
Help needed! I am using an Arduino Nano and a general purpose npn (2n2222a) transistor to provide a 12v signal to a low current 12vdc load in an automobile. The Arudino code is set to pulse D2 at bootup/startup for .5 second. The PWM output setting was 255 (since switched to digitalWrite). However, the switched output measures only 4.5v (expected close to 12v). What am i doing wrong?
Applying 12v+ directly to the black box works. The purpose is to simulate a temporary button push in the car so an auto function is enabled.

the black box is raising the voltage on the emitter ... that in turn raises the base voltage necessary for transistor to turn on ... the nano is not able to supply that voltage .... connect the emitter to GND ... place black box at the collector .... this has been beat to death here and many places ... do research about driving a motor or solenoid or lamp with an arduinp

I did do research, and found this circuit (4th circuit, emitter-follower) which looked close to my desired application: https://www.electronics-tutorials.ws/blog/relay-switch-circuit.html#:~:text=PNP%20Relay%20Switch%20Circuit.%20The%20PNP%20transistor%20circuit,is%20more%20negative%20than%20that%20at%20the%20Emitter.

the problem with your circuit is that D2 does not rise to 12 V

How much current is needed for your black box with 12 V supply?

not much current - it's supplying a signal to an auto control unit simulating a short button press - a few milliamps at a guess.

Your schematic shows a common collector amplifier: it amplifies current, not voltage.

The problem is that you are using an NPN transistor as a high side switch.
The voltage at the emitter of the transistor will always be about 0.7V below the voltage at the base.  The "high" output from the Arduino is 5V.  The emitter will be at about 4.3V.
Have a look at the Wikipedia "emitter follower" page.  The emitter follower is also called a common collector circuit. That explains the "problem" in more detail.  It is only a problem in so far as it is not the correct solution for your task.
You need to use a "common emitter" circuit.
This usage is commonly called a "low side switch."
That would look like this:

simulate this circuit – Schematic created using CircuitLab
If your black box really needs its input pulled up to 12V, then you would do something like this:

simulate this circuit
The resistor values and transistor part numbers are place holders.  The values of resistors you will need depends on the transistors you use.  The transistor selection will depend on how much current you need to deliver to the black box.
I see in a comment that your black box only needs a few milliamperes.  In that case, the shown transistors should work just fine.  The resistor values may be a little too high, but I think they'll be OK.

A couple of additional points:

The Arduino has PWM outputs, not PCM.
The output voltage for your black box will be pulsing if you use any PWM value lower than 255.  Your black box probably won't like that, and your voltmeter won't read a correct voltage.

You should use D2 as a digital output rather than PWM.  Just turn it on or off rather than fiddling with the PWM duty cycle.  Use "digitalWrite" instead of "analogWrite" on pin D2.

Thanks, i switched to digitalWrite in the code.

The 2N2222 is an NPN device. Skipping all of the physics involved, that means that (in your application) it will sink current as a low-side switch, but not source current as a high-side switch.
If you want a high-side switch, you should find a PNP transistor. In this case your Nano pin will sink current from the transistor's base terminal.
I would recommend you stick with the 2N2222, but make two changes:

Connect your "black box" between the positive terminal (+) of your 12V supply, and the collector terminal of the 2N2222.

Reduce the size of your base resistor from 10Kohms to 1Kohms

The ground side of the black box is not available. The black box (control unit) circuit has to supply +12v to simulate the switch press.

thanks, I only had npn transistors on hand, so that's what I tried.

checked the parts bin, I also have a p-ch mosfet and nte184/185's.

@Seamus: An NPN transistor will quite happily source current as a high side switch.  Tha'ts what it does - it is an emitter follower.  What it can't do is to provide a voltage at the emitter that is higher than the base voltage.

No, Seamus, I'm not looking for a "chat room."  I spend most of my time on the electrical engineering stack exchange.  The statement "but not source current as a high-side switch" is incorrect.  As the original question shows it, the 2N2222 would try to deliver all the current available from the 12V source to the black box.  If the black box were a short circuit to ground, the 2N2222 would quickly burn out from trying to pass many amperes of current from the car battery.  So much for "not sourcing current."

As used, the black box won't consume much current (there's a comment that says it only needs a few milliamperes.)  That doesn't change the fact that an NPN transistor used as a high side switch can quite happily source current from its emitter.

Already posted an answer.

And an NPN transistor will deliver current as shown in the question.  Or haven't you tried it?

I did try my original circuit in car, but it would not provide enough voltage? to signal the control unit to switch states. A straight +12vdc line to the control unit does switch the state.

@handyguy: Right - the circuit you drew in your question won't work. The collector needs to go to the neg/gnd/- terminal of your black box, and the emitter needs to go to the GND point on your Arduino. Does this mean it's working for you now?

I do not have access to the ground on the black box. I only have access to the signal wire to the control unit, which required a +12vdc signal.

@handyguy: OK - that's easy enough to fix. I'll be glad to revise my answer if you'll consider it - let me know if you don't mind.

i don't mind, thanks

@handyguy: I wasn't clear; my apologies, but I wanted to know if you were still interested in a revised answer. If you've moved on with a solution already, there may be no point in revising this answer. OTOH, if you're still undecided as to how to proceed, I'll be glad to make the changes.

thanks, but no longer needed.

What I have thought about is using an opto-coupler

Connect the Arduino pin output to pin 1 through 330 ohms resistor, pin 2 to ground of Arduino, connect pin 4 to Vcc of 12 V and finally connect pin 3 to the black box load.
Try this configuration
Since black box only needs few milliamps as you said
May be the transistor is not saturated since base current has to go through the black box load opto-coupler s have no base current instead they use photons
Here is the circuit diagram

5 V supply looks like the Arduino pin D2 and lamp is the black box load.
This is 4N35 example

The opto coupler looks like a good idea. The part is cheap and small. If it can switch 12vdc at a few ma, it looks like the simplest solution.

ok, so i chose the 2 transistor high side circuit as i had the needed pnp transistor laying around. Works great, thanks everyone for your help. The trace (5v/div) shows the Arduino signal at 5v and the circuit output at 12v - perfect!

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


text:
Programfault when dereferencing a 64bit int on due
I am running into a strange behaviour with my code. The following works without problems on an Arduino Nano but it seems to crash on a DUE
void putData64(byte* packet, int pos, uint64_t data)
{
    uint64_t* h= (uint64_t*) (packet+pos+2);
    *h= data;
}

the problematic line seems to be the second one (*h= data) as commenting it out lets the program run without problems.
Similar, the following lines cause a problem on a DUE but run fine on a Nano:
char* data;
// ... data is filled with something
uint64_t* t= (uint64_t*) (data+1);
uint64_t test= *t;

Is there something I am missing?

Probably a memory alignment problem.

What are you trying to do? If you want to use bytes and byte pointers, that is okay. If you want to use 64-bit and pointers to it, that is also okay. But you have mixed the two. Why would you want to point halfway to a 64-bit value. I suggest to start over.

I concur with Majenko's comment: it's probably a memory alignment
problem. I don't know the specifics of the Due, but when you access
memory in chunks of 32 bit data words on a 32 bit CPU, it can
happen that the architecture requires the data words to be aligned to
32 bit (i.e. 4 byte) boundaries. This means that the address
of an uint32_t or uint64_t should be a multiple of 4. Maybe
even 8 for a uint64_t, you will have to check.
The only solution to this issue is to fill the packet byte by byte:
void putData64(byte* packet, int pos, uint64_t data)
{
    union {
        uint64_t integer;
        byte bytes[8];
    } h = { .integer = data };
    for (int i = 0; i < 8; i++) {
        packet[pos+2+i] = h.bytes[i];
    }
}

Note that the AVR (in the Nano) is an 8 bit architecture with no
alignment constraints whatsoever.

Thank you. I was aware of the fact of 8bit vs 32bit. I haven't tried your code but it seems right. What did the trick for me in the end was the following:
void putData64(byte* packet, int pos, uint64_t data)
{
    uint32_t* out= (uint32_t*) (packet+pos+2);
    uint32_t* in=  (uint32_t*) data;
    *(out++)= *(in++);
    *(out++)= *(in++);
}

@user2912328: You mean in = (uint32_t*) &data? Note that, although this could work, it is quite fragile. Unless you can prove that packet+pos+2 is always a multiple of 4, there is a risk that out ends up being an incorrectly aligned (and thus invalid) pointer. If you have no guarantees on the alignment of packet+pos+2, the only valid solution is to copy the data byte by byte.

yes you are right about both points. Missing & and multiple of 4


text:
ESP8266 reseted due to relay / AC plugged
My Wemos card is reseting for unknown reason. For example, the pump plugged on the relay works fine till 1am and then the pump stop. After a few research I figured out the ESP should reset because all internal parameters are reseted.

My hardware is simple Wemos card + relay + sensors (not here because not connected yet).

My program is quite complex. I can command/configure the wemos via webservice (ex relay on pin 5 with on 5min/off 10min).
https://github.com/TittyPanda/ESP-commander/blob/master/ESP-COMMANDER

OK if no AC device is connected on relay (no reset)
OK if a light is connected on relay
The issue occurs only when the water pump is connected

Maybe it's an electrical/electromagnetical thing because the pump has motor. What do you think ?
Thanks,
EDIT
Power part are done with common wires from power extension cord
AC-DC converter 5 V 1A 1.5A 500mA

Pump 40W 3000L/H 220V 50Hz

What is your pump current consumption? this sound like that you have a power supply that can't deliver sufficient power to the overall circuitry.

It could well be EMI induced by the pump. You need to specify more details about exactly what hardware you're using - what pump, what power supplies, what wiring, etc.

Thanks I added pump & converter info in the post

@hcheung I'm not sure because the whole system works fine when nothing is plugged on relays (I'm testing a light again but during 24h)

try a shorter and thicker extension cord, and a large capacitor (1000uf+) on the 5v rail.

I installed the L-C Power Filter between the breadboard and ESP as advised by @gdb.
24 h - no reset -> it was the solution.
Thanks all of you for your help and your time.
The topic is closed for me.

Try add some power filter like this:

Between the breadboard and ESP board.

Thanks @gbg It remains me my electronic/physic courses :) - found with  L-C Power Filter and google image ! https://fr.aliexpress.com/item/32842662140.html

it was the solution


text:
Can I control 4 DC Brushless motors with arduino uno and Adafruit motor shield?
I need to control 4 DC brushless motors. I have no experience with arduino or coding. After some research the cleanest setup seems to be using the Adafruit motor shield, however the motors I'm using have 5 wires. Can I still make this work? I envision the motors being connected to the shield via the negative and positive power wires, but what do I do with the rest?  Thank you in advance.

Those motor have a "built-in drive". It has electronics inside to control the motor. You don't need the adafruit motor shield for those motors. The pwm wire is used to control the speed of the motor with a pwm signal. I think the pwm signal needs to be between 15kHz and 25kHz. That is more than the 500Hz of the analogWrite arduino function. A hall signal output gives pulses when the shaft is rotating. You can use that to measure the speed. There is also a wire to control the direction (clockwise or counterclockwise).

I'm trying to get a set-up with the fewest amount of wires. Would it be possible to use these motors without making use of the built in drivers?

Not really. When you don't need to control the speed, then you can tie the pwm input to GND and power them with 12v or 24v. If two wires per motor is okay and three wires is not, then you have an other problem.

What if I switch the motors to brushed DC? https://www.aliexpress.com/item/ChiHai-Motor-CHR-GM16-050SH-Permanent-Magnet-Miniature-DC-Metal-Tooth-Speed-Reduction-Motor-DV-6v/32826266828.html?spm=2114.10010108.100009.1.33603ae1FeAwMD&gps-id=pcDetailLeftTopSell&scm=1007.13482.95643.0&scm_id=1007.13482.95643.0&scm-url=1007.13482.95643.0&pvid=d7b4942c-3c6e-4747-8026-e7cf8bc0ed32

You don't need the motor shield at all. The motor you link to has its own driver built in.
According to the connection table on the page you link to:

Red wire to +24V
Green wire is for sensing the RPM - you can ignore it
Yellow wire is the direction select - connect to any GPIO
Black wire is ground - connect to 24V GND and Arduino GND.
Blue wire is PWM control. Connect to any PWM output on the Arduino

Note that the motor will probably spin immediately power is applied until your sketch tells it to stop by driving the PWM output LOW (or 0% duty cycle).  There appears to be a 15-25kΩ (typical) pullup resistor on that pin, so adding a smaller pulldown resistor (say 1kΩ) on it should force it to be off until you turn it on.

Majenko, I'm sure that the 15-25k are not resistors but is the frequency for the pwm signal. I read elsewhere ( https://www.aliexpress.com/item/BLDC-brushless-gear-MOTOR-DC24V-12V-High-torque-high-efficiency-long-life-Motor-diameter-25mm-10v/32654537700.html ) that it can operate with a pwm frequency of 1kHz. When the pwm signal is low, the motor is on. And the motor has also a gear.

@Jot Could be. It's hard to tell from that Chinglish spec sheet. The OP may just have to make do with having the motors spin out of control at powerup - or add extra power control so they only get power once the IO pins are set LOW.

I'm trying to get a set-up with the fewest amount of wires. Would it be possible to use these motors without making use of the built in drivers?


text:
Trying to Pulse an LED a number of times outside of the main loop
I'm trying to call a class function that pulses an LED "x" number of times. I dont want to use a delay, which is making it tough. If I use a while loop, the LED just stays on. I attach an interrupt in the begin() - the location of the LED is pin 13
I call the following in my sketch like so:
robot.lights.pulse(0, 2000, 10000, 500); //in milliseconds

My goal is to pulse an LED "x" number of time at a rate I specify.
This is the code inside my class:
void StatusLights::begin(int locations[]){
    for(int i=0;i<NUM_OF_LIGHTS;i++){
        this->locations[i]=locations[i];
        pinMode(locations[i], OUTPUT);
    }

    ledState = LOW;
    previousMillis = 0;
    attachInterrupt(0, pulse_ISR, RISING);

};

void StatusLights::pulse(int location, int interval, int count, int speed){

    int value = 0;
    previousMillis = 0;
    // while(pulsecnt<count) {
        long currentMillis = millis();

        if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            value = 128+127*cos(2*PI/interval*(speed-currentMillis));
            analogWrite(locations[location], value);
        };
    // };
    // digitalWrite(locations[location], LOW);
};

void pulse_ISR() {
    pulsecnt++;
};

This is my first time using interrupts to do this - I'm really trying to avoid delays since i need other things to happen synchronously.
Thanks!

Can you show us a working sketch? The currentMillis should be unsigned long. What kind of pulse do you want, because the human eye has a log scale and you use cosine. How often do you want an update of the led brightness?

@Jot added a function call to my question. thanks

A working sketch is something we can try without guessing what the rest of the code is. I would like to see the rest of the sketch because I think you have made it too complex. Start with the 'update' function to keep it going as @JRobert writes in his answer. That is a common way to deal with it in arduino projects.

then no i dont without the other five classes

Is your previousMillis a long as well? That's not okay. This is what I mean with guessing.

You'll want a class function that decides whether 'now' is time to toggle the LED or not, and returns quickly. Call that function frequently from your loop function. Your other class functions will set or clear the whether the LED is to toggled, and when, how many times, etc.  Something like the following pseudo-code, which is not a full solution but should point out the essential details:
void loop()
{
   myStatusLights.updateLED();     // call this frequently
}

...

void StatusLights::updateLED(){
  if LED_active,
     if it's time to change the LED,
        toggle LED on/off;
        if LED has toggled enough times,
           set LED_active false;
        endif;
     endif;
  endif;
}

Update:

How would you refresh the count, track the pulses, and refresh the state of the status light without any parameters?

Some class-function must initiate the blinking, whether it knows to do it itself or it is called from your application code. That class-function will need to set those parameters. If it to be called from outside, perhaps the outside sets them - ? Only you know that. Either way, they will need to get saved in the class' private data so the .updateLED() function can have access to them. The .updateLED() function will, for instance, count down the remaining number blinks to display, keep track of whether the LED is on or off, actually turn it on or off, etc., until there is nothing left for it to do. In that case it just quickly returns without doing anything.

I'm not sure I follow toggle LED on/off;         if LED has toggled enough times,            set LED_active false;         endif; this is exactly what im trying to do, but I'm not sure of the syntax - sorry the sudo code isn't helping in this case. @JRobert

I understand that you want to repeatedly call an update function - How would you refresh the count, track the pulses, and refresh the state of the status light without any parameters? what if i want to set pulse the led 10 times in the setup function?

@rcpilotp51, you have a class for status lights and you don't know where to hold the status of lights? http://www.cplusplus.com/doc/tutorial/classes/

@Juraj i actually have an array of light locations "pins" and want to call them based on other events and want them to do different things...do i need an update function for each?

You don't need a function for each; one update function can loop through the array of LEDs and apply the same logic to each one, based on each particular LED's class variables' values. Each LED will needs its own set of e.g., pin#, blink-interval, blinks-remaining, etc.


text:
Error compiling a sketch to class/library conversion
I'm trying to take a sketch and turn it into a class for a library I'm making, but I'm getting compile issues.
This is not a duplicate as suggested. as i explain in the comment and my answer. Thank you all for your help - as I am new to creating libraries - figured I would attempt something correctly for a change :)
Here is the original sketch: Gotten here
#include <ros.h>
#include <sensor_msgs/BatteryState.h>

#define K           0.00472199
#define CELLS       6
#define MAX_CELLS   12

double cell_const[MAX_CELLS] =
{
  1.0000,
  2.1915,
  2.6970,
  4.1111,
  4.7333,
  6.6000,
  6.6000,
  7.8293,
  8.4667,
  9.2353,
  11.0000,
  11.0000
};

ros::NodeHandle nh;
sensor_msgs::BatteryState batt_state;
ros::Publisher batteryState("battery_state", &batt_state);

void setup()
{
  // Initialize the ROS node.
  nh.initNode();
  nh.advertise(batteryState);

  // Populate battery parameters.
  batt_state.design_capacity = 2200;      // mAh
  batt_state.power_supply_status = 2;     // discharging
  batt_state.power_supply_health = 0;     // unknown
  batt_state.power_supply_technology = 3; // LiPo
  batt_state.present = 1;                 // battery present

  batt_state.location = "Crawler";        // unit location
  batt_state.serial_number = "ABC_0001";  // unit serial number
  batt_state.cell_voltage = new float[CELLS];

}

void loop()
{
  // Battery status.
  double battVoltage = 0.0;
  double prevVoltage = 0.0;

  // Populate battery state message.
  for (int i = 0; i < CELLS; i++)
  {
     // Read raw voltage from analog pin.
    double cellVoltage = analogRead(i) * K;

    // Scale reading to full voltage.
    cellVoltage *= cell_const[i];
    double tmp = cellVoltage;

    // Isolate current cell voltage.
    cellVoltage -= prevVoltage;
    battVoltage += cellVoltage;
    prevVoltage = tmp;

    // Set current cell voltage to message.
    batt_state.cell_voltage[i] = (float)cellVoltage;

    // Check if battery is attached.
    if (batt_state.cell_voltage[i] >= 2.0)
      batt_state.present = 1;
    else
      batt_state.present = 0;
  }

  // Update battery health.
  batt_state.voltage = (float)battVoltage;

  if (batt_state.voltage > CELLS * 4.2)
    batt_state.power_supply_health = 4; // overvoltage
  else if (batt_state.voltage < CELLS * 3.0)
    batt_state.power_supply_health = 3; // dead
  else
    batt_state.power_supply_health = 1; // good

  // Publish data to ROSSERIAL.
  batteryState.publish( &batt_state );
  nh.spinOnce();
  delay(1000);

}

Here is my header file:
#ifndef battery_h
#define battery_h

#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

#include <ros.h>
#include <sensor_msgs/BatteryState.h>

#define K           0.00472199
#define CELLS       6
#define MAX_CELLS   12
#define CRITICAL    0.30

double cell_const[MAX_CELLS] =
{
  1.0000, 2.1915, 2.6970, 4.1111,
  4.7333, 6.6000, 6.6000, 7.8293,
  8.4667, 9.2353, 11.0000, 11.0000
};

ros::NodeHandle nh;
sensor_msgs::BatteryState batt_state;

ros::Publisher batteryState("/battery/info", &batt_state);

class Battery
{
  private:
   void updateBatteryHealth();
   double battVoltage;
   double prevVoltage;
  public:
    void begin();
    void updateBatteryState();
};

#endif

This is my cpp file:
#include "battery.h"

void Battery::begin(){

  // Launch ROS node and set parameters.
  nh.initNode();

  // Setup publishers/subscribers.
  nh.advertise(batteryState);

  // Populate battery parameters.
  batt_state.design_capacity          = 2200;  // mAh
  batt_state.power_supply_status      = 2;     // discharging
  batt_state.power_supply_health      = 0;     // unknown
  batt_state.power_supply_technology  = 3;     // LiPo
  batt_state.present                  = 1;     // battery present

  batt_state.location      = "Crawler";        // unit location
  batt_state.serial_number = "ABC_0001";       // unit serial number

  batt_state.cell_voltage = new float[CELLS];  // individual cell health

}

void Battery::updateBatteryState() {
  battVoltage = 0.0;
  prevVoltage = 0.0;
  // Reset Power Supply Health.
  batt_state.power_supply_health = 0;
    // Populate battery state message.
  for (int i = 0; i < CELLS; i++)
  {
    // Read raw voltage from analog pin.
    double cellVoltage = analogRead(i) * K;

    // Scale reading to full voltage.
    cellVoltage *= cell_const[i];
    double tmp = cellVoltage;

    // Isolate current cell voltage.
    cellVoltage -= prevVoltage;
    battVoltage += cellVoltage;
    prevVoltage = tmp;

    // Set current cell voltage to message.
    batt_state.cell_voltage[i] = (float)cellVoltage;

    // Check if battery is attached.
    if (batt_state.cell_voltage[i] >= 2.0)
    {
      if (batt_state.cell_voltage[i] <= 3.2)
        batt_state.power_supply_health = 5; // Unspecified failure.
      batt_state.present = 1;
    }
    else{
      batt_state.present = 0;
    }
  }
};

void Battery::updateBatteryHealth() {
    // Update battery health.
  if (batt_state.present)
  {
    batt_state.voltage = (float)battVoltage;
    float volt = batt_state.voltage;
    float low  = 3.0 * CELLS;
    float high = 4.2 * CELLS;
    batt_state.percentage = constrain((volt - low) / (high - low), 0.0, 1.0);
  }
  else
  {
    batt_state.voltage = 0.0;
    batt_state.percentage = 0.0;
  }

  // Update power supply health if not failed.
  if (batt_state.power_supply_health == 0 && batt_state.present)
  {
    if (batt_state.voltage > CELLS * 4.2)
      batt_state.power_supply_health = 4; // overvoltage
    else if (batt_state.voltage < CELLS * 3.0)
      batt_state.power_supply_health = 3; // dead
    else
      batt_state.power_supply_health = 1; // good
  }
   // Publish data to ROSSERIAL.
  batteryState.publish( &batt_state );
  nh.spinOnce();
};

this is the error im getting simply by calling the Battery::begin function in my main class:
libraries/KBROSRobot/KBROSRobot.cpp.o (symbol from plugin): In function `KBROSRobot::KBROSRobot()':
(.text+0x0): multiple definition of `nh'
sketch/rob_test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/KBROSRobot/KBROSRobot.cpp.o (symbol from plugin): In function `KBROSRobot::KBROSRobot()':
(.text+0x0): multiple definition of `batt_state'
sketch/rob_test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/KBROSRobot/KBROSRobot.cpp.o (symbol from plugin): In function `KBROSRobot::KBROSRobot()':
(.text+0x0): multiple definition of `batteryState'
sketch/rob_test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/KBROSRobot/KBROSRobot.cpp.o (symbol from plugin): In function `KBROSRobot::KBROSRobot()':
(.text+0x0): multiple definition of `cell_const'
sketch/rob_test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
/var/folders/m4/lq13_j5j23qc0l2wp8dqmt4h0000gp/T//cczNyzqC.ltrans1.ltrans.o: In function `begin':
/Users/keith.brown/Documents/Arduino/libraries/KBROSRobot/KBROSRobot.cpp:9: undefined reference to `Battery::begin()'
collect2: error: ld returned 1 exit status
exit status 1

Possible duplicate of Multiple definition error when linking firmware.elf

@KIIV, how is this a duplicate of that? that was a mess with header guards and file extensions. here the linker can't find a function which exists in the source code. please explain if you see something I don't see

@Juraj In the answer I tried to cover how to declare something in the header and define it in the source file so it won't results into multiple definitions.

@KIIV, sorry, yes, but the answer by tttapa covers that too. but the last error is perhaps something else undefined reference to Battery::begin()

@Juraj True true. Undefined Battery::begin is weird. I can't see anything in the question that explains why it's failing

@Juraj and KIIV check below to my answer. I had each class in named folders /sensors/battery... drive/motors... /utility/statusLights... each other class had to be placed in the utility folder... so the Battery class wasn't compiling.

Don't define your global variables in the header file. Only declare them, using external linkage. Then define them in the implementation file
Header (.h):
extern ros::NodeHandle nh;

Implementation (.cpp):
ros::NodeHandle nh;

Try to keep usage of global variables to a minimum. If you don't need them outside of the library, declare them in the implementation file and mark them static.
Or even better: encapsulate them inside of the class.

The reason that you are getting these errors is because each implementation file is compiled separately. You have two implementation files that include your header file, so the header file is compiled twice. This results in two global variables with the name nh. During the linking stage, the linker tries to combine the compiled version of both KBROSRobot.cpp and rob_test.ino.cpp (these are called object files, .o). The linker has no way of knowing which variable is which, because they are both defined twice, so it throws an error.
Multiple declarations are fine, because it just tells the compiler "there is a definition somewhere", and the linker will find that definition eventually. That's why the declaration with external linkage solves your problem.
Multiple definitions are not allowed (in most cases).

i will give the above a try - do you think i converted the sketch ok? should i do something else differently?

@rcpilotp51 You have to do the same for all definitions in the header file. I haven't looked at the rest of your code in detail.

im getting an error about the extern: warning: 'batteryState' initialized and declared 'extern'  extern ros::Publisher batteryState("/battery/info", &batt_state);

@rcpilotp51 remove the initializer in the header file (i.e. just use extern ros::Publisher batteryState;). Do add the initializer in the implementation file.

ok got rid of the multiple errors, niw just left with : var/folders/m4/lq13_j5j23qc0l2wp8dqmt4h0000gp/T//ccB5PTqK.ltrans0.ltrans.o: In function begin':
/Users/keith.brown/Documents/Arduino/libraries/KBROSRobot/KBROSRobot.cpp:9: undefined reference to Battery::begin()' collect2: error: ld returned 1 exit status exit status 1

if the above variable are 'extern' should i jkust define them in the private var section? @tttapa

@rcpilotp51 You didn't define void Battery::begin() in your implementation file. No, class and member variables should not be marked extern.

its defined in the Battery class .h and implemented as Battery::begin() in the cpp  file void begin(); in the header.  @tttapa

@rcpilotp51 The compiler doesn't seem to agree. Check your semicolons and brackets. Also keep in mind that it uses the version in your libraries folder.

I'm editing directly in the libraries folder. as far as i can tell its there.... any other suggestions? @tttapa

I also found that all other classes in the library have to be in the utility folder or the wont compile. Answering my comment above. Thank you @tttapa for your help.
Now I just have to intelligently program the robot, which is unfortunately subjective... ;)

library folder structure specs: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification


text:
Nodemcu + GSM IOT-GA6
I've connected my NodeMCU to GSM module using GND, RX and TX.
I use At Comand Tester. When I try to get sim status or something I get error for example:

Unable to get Sim status.

Only AT comand returns

AT
OK

When I send any AT comand to GSM module I can see that the diode on the module blink.
How can I solve this problem?
Let me know if you need more informations to help me.

Please, post your full code, schematic circuit (also a picture if you want) and GSM module model.

Gsm module is in the post's title. If I test with at comands it means that I don't have any code. Pictures I will add as soon as it is possible

link I'm trying to use this module

I mean, what sketch are you upload on NodeMCU board?

I have't uploaded anything


text:
map() function with stepper motor
I am controlling a stepper motor with a potentiometer and I am trying to map the potentiometer values (0-1023) to the stepper motor steps (200). I only want this stepper motor to turn 1 (one) rotation from 0 on the potentiometer (0 steps on the stepper, yes I have a micro switch to mark 0) all the way to 1023 on the potentiometer (200 steps on the stepper). But I have trouble understanding the map() function.
potValue = map ( potPinValueRead,0,1023,0,200) ;

As per the Arduino example:
map(value, fromLow, fromHigh, toLow, toHigh)

I think I am interpreting the map() function wrong
UPDATE:
Even with the map() values the stepper still turns 5 (and a bit (1023/200) ) rotations and not just 1 (one) rotation.
Here is my code:
#include <Stepper.h>
#define STEPS 200
Stepper stepper(STEPS, 7, 8, 9, 10);
int previous = 0 ;
int potData = 0 ;
int potPin = A0 ;

int outputA = 7 ;  //Stepper Output
int outputB = 8 ;  //Stepper Output
int outputC = 9 ;  //Stepper Output
int outputD = 10 ; //Stepper Output

int limitSwitch = 2 ; //Limit switch (home switch) is on pin 2

void setup() {
   Serial.begin(9600) ;
   stepper.setSpeed(10);
   pinMode ( outputA, OUTPUT ) ;
   pinMode ( outputB, OUTPUT ) ;
   pinMode ( outputC, OUTPUT ) ;
   pinMode ( outputD, OUTPUT ) ;
   pinMode ( limitSwitch, INPUT ) ;

   //Turn the motor until the limit scwitch is triggered
   while ( digitalRead(limitSwitch) == 0 )
    {
      stepper.step(30);
    }
   //Stop turning when the limit switch has been triggered
   while ( digitalRead(limitSwitch) == 1 )
    {
      stepper.step(0);
    }
   //Turn 5 steps away from the limit switch to un-trigger
   //This is also the "home" position
   stepper.step(-5);
 }

 void loop() {
   int potData = map(analogRead(potPin),0,1024,0,200);

   if (potData>previous)
    {
      stepper.step(5);
    }
   if (potData<previous)
    {
      stepper.step(-5);
    }

  previous = potData;
}

I have updated my post and added code

you have misdiagnosed the problem ...... write a sketch that moves 200 steps, waits for a second, then repeats .... no potentiometer code, no limit switch code ... do you get one revolution? ..... you have to get 1 rev per 200 steps  before you do anything else

I did as you suggested and I get 1 revolution for 200 steps

now you are certain that the hardware works correctly ..... that means that the problem is inside your program ...... look at your loop() code  ..... how many steps will the motor move if you change the potentiometer by one "position"?

@jsotola : it turns out the Arduino I was using was defective. I bought 20 of them and it turns out 4 of them had the same issues (the supplier got it from you know where). I returned all for genuine Arduino's. Anyway, everything is working fine now. Thank you for your help.


text:
Using an external pull-up resistor vs INPUT_PULLUP
When would one would prefer to use an external pull-up resistor vs the internal:
pinMode(fanPin, INPUT_PULLUP);

Dredging through the forums and this site, the commonly recommended value for a pull-up resistor is seems to fall at 10K.
However, the ATmega32U4 datasheet's Table 29-1 says that RPU or "I/O Pin Pull-up Resistor" is between 20K and 50K ohms.
This question asks about internal vs external pull-ups for a simple button, but I'm asking in the general case.
What types of projects would fare better with internal pull-ups, and what type of projects would be better off with external pull-ups?
What are the considerations for preferring one over the other?
At the present, my project is hooking up an AM2302 / DHT22 temperature sensor.

Whats OUTPUT_PULLUP? Pulling an output high doesn't make a lot of sense.

I2C requires lower value pull-up resistors, so in that case you'd need external resistors. High noise environments could accidentally trigger an input if the pull-up is weak. But in most cases the internal pull-up is fine. And it's cheaper to not add a resistor, especially in very high volume manufacturing.

During manufacturing they sometimes change the value of the pull-up to a value resistor that is already on the board. Reducing the setup cost.

the internals are fine for most things, unless you have semi-low impedance on the sensor's output. Impedance is more than resistance.

@tkausl Thanks for pointing out that OUTPUT_PULLUP doesn't exist. Edited.

There is no OUTPUT_PULLUP that I am aware of. Use INPUT_PULLUP for most things.
Add 3.3K (3.3V) or 4.7K (5V) external pullups for I2C. If you saw a 'scope trace with 10K I2C pullup on 5V system and even short wiring, the rise time is really slow. 4.7K is much quicker.
10K for external pullup works well for slow things, like buttons, switches.  If the wire lengths are longer, then 4.7K could be used as well, maybe even 1K if the wires are long.  If running on battery power, 10K is better as there is less current flow when the input is low.

I almost always use external pull up/down resistors. I get more control over the value and can do more in hardware with them, whether that is debouncing buttons or using different types of transistors.
The easiest way to answer your question is to ask what you want to do. If you want active low, use pull up. Active high is pull down. Some transistors work much better with one or the other, so they could determine what you use. I2C uses weak pull ups to bias the transmission lines. If you need hardware filtering its much easier to design a filter with a known 25k resistor than with an unknown 20k-50k resistor. The list could go on an on but those are the most common situations I've run into.


text:
Selected board depends on 'arduino' core (not installed)
When I load the Arduino IDE with Board: Pololu A-Star 32U4 selected, I see:
The current selected board needs the core 'arduino:arduino' that is not installed.

I installed the board manually via these instructions.
When verifying the initial empty sketch, I see:
Arduino: 1.8.8 (Linux), Board: "Pololu A-Star 32U4"

The current selected board needs the core 'arduino:arduino' that is not installed.
/usr/share/arduino/arduino-builder -dump-prefs -logger=machine -hardware /usr/share/arduino/hardware -hardware /home/ravi/Arduino/hardware -tools /usr/share/arduino/tools-builder -libraries /home/ravi/Arduino/libraries -fqbn=pololu:avr:a-star32U4 -ide-version=10808 -build-path /tmp/arduino_build_299010 -warnings=none -build-cache /tmp/arduino_cache_842714 -prefs=build.warn_data_percentage=75 -verbose /tmp/untitled689103723.tmp/sketch_feb05a/sketch_feb05a.ino

Selected board depends on 'arduino' core (not installed).

Error compiling for board Pololu A-Star 32U4.

How do I prevent this error and compile a sketch?

and what is the question? it is so that board packages can use other board packages and it is normal

I needed to install the boards package for:
Arduino AVR Boards

Under Tools -> Board -> Board Manager

I ran into a similar issue with the MySensors Sensebender Gateway but was not able to fix it by installing "Arduino AVR Boards". However, I was able to fix it by installing Arduino SAMD boards. This was a guess based on the fact that the package containing the actual SenseBender gateway board was called MySensors SAMD board. So just a note that this message apparently just means a board package dependency is mising, not necessarily the "Arduino AVR Boards" one.


text:
Latest datasheet for Leonardo's ATmega32U4
What is the authoritative source(s) for the ATmega32U4 (or any Arduino chip for that matter) datasheet?

the manufacturer is Microchip. https://www.microchip.com/wwwproducts/en/ATmega32u4

4/2016 does appear to be the latest datasheet for the Atmega32U4. If you go here www.microchip.com and select Design, then Documentation, then Datasheets, then Search by Products, you can enter a part number. Entering Atmega328P brings up the complete datasheet dated 1 Nov 2018. You can check that to see if there is more characterization data.
(question was originally about characerization of ADC for '32U4 and other sources of info on same, hence the '328P reference here).


text:
Parsing array of an object in a library constructor
I am trying to develop an Arduino library that consists out of two classes. I want 'WayPointStack' to store an array of 'WPCommand', but I can't get it to work.
WayPointStack.h
#ifndef WayPointStack_h
#define WayPointStack_h

#include "Arduino.h"
#include "WPCommand.h"

class WayPointStack
{
  public:
    WayPointStack();
    WayPointStack(WPCommand* wp);
    WPCommand GetNextWP();
    WPCommand GetWP(int i);
    void AddWP(int target, int time);
    int SetWPPointer(int i);
    int GetLength();
  private:
    WPCommand* _wp;
    int pointer;
    int length;
};
#endif

WPCommand.h
#ifndef WPCommand_h
#define WPCommand_h

#include "Arduino.h"

class WPCommand
{
  public:
    WPCommand(int target, int time );
    WPCommand();
    int GetTarget();
    int GetTime();
    int LEFT;
    int RIGHT;
    int FORWARD;
    int BACKWARD;
    int STOP;
    int END;
  private:
    int _target;
    int _time;
};

#endif

Parts of WaypointStack.cpp
#include "Arduino.h"
#include "WayPointStack.h"
#include "WPCommand.h"

#define arrSize 100

WayPointStack::WayPointStack()
{
  _wp = new WPCommand[arrSize]; // should be enough, heap blabla
  length = 0;
  pointer = 0;
}

WayPointStack::WayPointStack(WPCommand[] wp)
{
    _wp = new WPCommand[arrSize]; // should be enough, heap blabla
    for (int i = 0; i < sizeof(wp), i++){
        _wp[i] = wp[i];
    }
    length = sizeof(wp);
    pointer = 0;
}

I'm pretty sure I'm doing something wrong with the pointers, but I don't know how to fix it. The first two errors are
WayPointStack.cpp:24:42: error: expected ',' or '...' before 'wp'
WayPointStack::WayPointStack(WPCommand[] wp)

and
WayPointStack.cpp:27:29: error: 'wp' was not declared in this scope
for (int i = 0; i < sizeof(wp), i++){

I obviously have to use a pointer. This is all I know, so far.
Has someone an idea?

Arduino is not Java it is based on C++. Check the syntax for array/vectors and passing parameters by reference. Also check who to determine the number of elements in a vector. Sizeof() is the number of bytes.

This is a C++, not Arduino question and should be asked on Stack Overflow.
In C/C++ the [] must be on variable name, not on type. WPCommand wp[] (it is the same as WPCommand* wp).
sizeof return size in bytes, not element count. send length as parameter
Dynamic memory allocation in MCU is not a good thing. You can have in WayPointStack
WPCommand _wp[arrSize]

Thank you. It reduced the error amount dramatically.


text:
Arduino freezes while running code
I am frustrated with my arduino project can you help me?
I am using Arduino Uno, electric lock (high/low), 4 distance sonic modules. Basically I have 4 drawers, I am measuring the distance - how much are they opened and if they are opened in given limits, I set the electric lock open (high).
It is working, but after some while, it stops and it stops running.
I have tried to comment all serial communication - didn't help. I have tried to use proper variable data types - same. I have tried to buy much powerful power source - 12V 3,5A and I bought Electrolyte condenzator 4,7mF to balance the power peaks while the lock closes - didn't help.
The lock is turned on using relay, connecting it directly to power source 12V.
Relay is powered from 5V arduino supply and controlled by arduino Digital pin.
4 Sonic distance modules are powered from arduino power supply.
Its even more funny that it starts running after ~10 minutes from nothing. Im confused.
Code:
    // defines pins numbers
const int trigPin1 = 2;
const int echoPin1 = 3;
const int trigPin2 = 6;
const int echoPin2 = 5;
const int trigPin3 = 9;
const int echoPin3 = 8;
const int trigPin4 = 12;
const int echoPin4 = 11;
const int relayPin = 7;
//distance limits
const int minSuplik4=27;//suplik4
const int maxSuplik4=29;
const int minSuplik3=22;//suplik3
const int maxSuplik3=24;
const int minSuplik2=32;//suplik2
const int maxSuplik2=34;
const int minSuplik1=9;//suplik1
const int maxSuplik1=11;
/*
double PreDistance1[4]={0,0,0,0};//supliky
double PreDistance2[4]={0,0,0,0};//supliky
double PreDistance3[4]={0,0,0,0};//supliky
*/
long distance[4]={0,0,0,0};//array with distances
int i;
int x;

int trigPinX[4]={trigPin1,trigPin2,trigPin3,trigPin4};//supliky
int echoPinX[4]={echoPin1,echoPin2,echoPin3,echoPin4};//supliky
int maxD[4]={maxSuplik1,maxSuplik2,maxSuplik3,maxSuplik4};//supliky
int minD[4]={minSuplik1,minSuplik2,minSuplik3,minSuplik4};//supliky
void setup() {
pinMode(relayPin, OUTPUT);
pinMode(trigPin1, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin1, INPUT); // Sets the echoPin as an Input
pinMode(trigPin2, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin2, INPUT); // Sets the echoPin as an Input
pinMode(trigPin3, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin3, INPUT); // Sets the echoPin as an Input
pinMode(trigPin4, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin4, INPUT); // Sets the echoPin as an Input
digitalWrite(relayPin, LOW);
Serial.begin(9600); // Starts the serial communication
}
void loop() {

for (int i=0; i<4; i++)
{
  delay(5);
  distance[i]=DistanceFunction(trigPinX[i],echoPinX[i]);
  delay(20);
  /*********** DEBUG ************
  Serial.print("Distance");// Prints the distance on the Serial Monitor
  Serial.print(i+1);
  Serial.print(":");
  Serial.print(distance[i]);
  Serial.print("<");
  Serial.print(minD[i]);
  Serial.print(":");
  Serial.print(maxD[i]);
  Serial.print(">");
  Serial.print(";");
  *********************************/
}

if(distance[0]>=minD[0] && distance[0]<=maxD[0] && distance[1]>=minD[1] && distance[1]<=maxD[1] && distance[2]>=minD[2] && distance[2]<=maxD[2] && distance[3]>=minD[3] && distance[3]<=maxD[3])
      {
        OpenFcn();
      }
else
      {
        CloseFcn();
      }
delay(100);
}

int DistanceFunction(int trigPin, int echoPin)
{
  digitalWrite(trigPin, LOW);// Clears the trigPin
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);// Sets the trigPin on HIGH state for 10 micro seconds
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);// Reads the echoPin, returns the sound wave travel time in microseconds
  long distanceFcn= duration*0.034/2;// Calculating the distance
  return distanceFcn;
}

int OpenFcn()
{
  digitalWrite(relayPin, HIGH);
  //Serial.println("OPENED");
  for (int x=5; x>0; x--)
    {
      //Serial.println("Otevreno:");
      //Serial.println(x);
      delay(1000);
    }
}

int CloseFcn()
{
  digitalWrite(relayPin, LOW);
  //Serial.println("CLOSED");
}

That might be a memory/stack problem or an electrical pulse problem. I can not spot a memory/stack problem, so let's focus on the electric lock and the relay. How much is 4,7mF? I suggest to use 1000µF to the arduino 5v and gnd. If you replace the electric lock or relay with a led plus resistors, does that help? What can you tell about the electric lock and the relay? Can you give a link to them? Please add a message with Serial.println after the Serial.begin in the setup function, so at least you will know if the arduino has reset.

Please add all the extra information to your question. A arduino digital pin can give 20mA. The 40mA is the shortcut current and should be avoided. Are you powering a 70mA relay with a digital pin? That is the problem then. Can you give a schematic or drawing or photo of your wiring?

please post the serial terminal output as text instead of a picture ...... disconnect the electric lock and see if the program still crashes

I have tried to supply the sonic modules and the relay with external supply, but its the same problem. But I supplied the arduino with different source. Can this be the reason? Relay is this one http://www.g7electronica.net/1444-2227-thickbox/rele-srd-05vdc-sl-c.jpg
sonic modules are these https://www.banggood.com/cs/10Pcs-HC-SR04-Ultrasonic-Ranging-Sensor-Ultrasonic-Module-For-Arduino-p-942912.html

Ok so I tried to connect everything on external 5V 3,5A source and only the lock connected to 12V. It still crashes, the same behaviour.

If I disconnect the lock, controlling the relay without the lock, it is working good.

relay without the lock, it is working sounds like a missing freewheeling diode

It looks like that there was a problem in the relay module or power supply cord. I have changed these two HW elements and looks like it is working. The reason why it did malfuctioning the arduino was, that when i moved the drawer, it slightly moved the power cord which had bad connection, so it made voltage drop on arduino supply and started to do crazy things.
Thanks all for your time


text:
Arduino ESP8266 - stack ERROR - ESPExceptionDecoder to debug - need help to find ERROR
i have one project that can ready compiled. The function is break on the hardware an i need help to finde the error. I am a beginner and ask for help. How can I narrow the error down?
Sketch:

SIGNALESP.ino (https://github.com/HomeAutoUser/ERROR_search/tree/master/SIGNALESP)

Platform

Hardware: AZDelivery NodeMCU Lua Amica Modul V2 ESP8266 ESP-12E
Core Version: latest git
Development Env: Arduino IDE
Operating System: Windows

Settings in IDE

Module: Nodemcu v1.0
Flash Size: 4MB
Flash Frequency: 40Mhz
CPU Frequency: 80Mhz
Upload Speed: 115200

Problem Description
15:54:11.662 -> Fatal exception 3(LoadStoreErrorCause):
15:54:11.662 -> epc1=0x4000e041, epc2=0x00000000, epc3=0x00000000, excvaddr=0x4024bcc2, depc=0x00000000
15:54:11.701 ->
15:54:11.701 -> Exception (3):
15:54:11.701 -> epc1=0x4000e041 epc2=0x00000000 epc3=0x00000000 excvaddr=0x4024bcc2 depc=0x00000000
15:54:11.701 ->
15:54:11.701 -> >>>stack>>>
15:54:11.701 ->
15:54:11.701 -> ctx: cont
15:54:11.701 -> sp: 3ffffce0 end: 3fffffc0 offset: 01a0
15:54:11.701 -> 3ffffe80:  00000000 00000019 4024bcaa 00000000
15:54:11.701 -> 3ffffe90:  00000001 3fff16a4 00000000 000001ff
15:54:11.701 -> 3ffffea0:  00000000 00000019 401003fc 0001687b
15:54:11.701 -> 3ffffeb0:  00000000 00000000 00000001 4024bcaa
15:54:11.701 -> 3ffffec0:  00000000 00000019 3fff1134 4020ef28
15:54:11.701 -> 3ffffed0:  ffffffff 3fffc6fc 00000001 4024bcaa
15:54:11.741 -> 3ffffee0:  00000001 00000000 3fff1134 4020efc2
15:54:11.741 -> 3ffffef0:  00000019 00000000 3fff1134 4020f09d
15:54:11.741 -> 3fffff00:  40214e08 00000000 00001388 00000057
15:54:11.741 -> 3fffff10:  4020f060 3ffef254 4024bcaa 4021104d
15:54:11.741 -> 3fffff20:  3ffef10c 3ffef10c 3ffef254 40211275
15:54:11.741 -> 3fffff30:  007a1200 3ffef10c 3ffeeec0 402019b9
15:54:11.741 -> 3fffff40:  00000000 00000000 00000001 40100304
15:54:11.741 -> 3fffff50:  3ffef10c 00000000 3fff1134 4020f130
15:54:11.741 -> 3fffff60:  3ffef10c 3ffef254 0000000d 3ffef115
15:54:11.781 -> 3fffff70:  3ffef10c 3ffef254 3ffeeec0 402027dd
15:54:11.781 -> 3fffff80:  3fffdad0 00000000 3ffef728 3ffef768
15:54:11.781 -> 3fffff90:  3fffdad0 00000000 3ffef728 40202849
15:54:11.781 -> 3fffffa0:  3fffdad0 00000000 3ffef728 40212b68
15:54:11.781 -> 3fffffb0:  feefeffe feefeffe 3ffe8500 40101059
15:54:11.781 -> <<<stack<<<
15:54:11.781 ->
15:54:11.781 ->  ets Jan  8 2013,rst cause:2, boot mode:(3,6)
15:54:11.781 ->
15:54:11.781 -> load 0x4010f000, len 1392, room 16
15:54:11.821 -> tail 0
15:54:11.821 -> chksum 0xd0
15:54:11.821 -> csum 0xd0
15:54:11.821 -> v3d128e5c
15:54:11.821 -> ~ld
15:54:11.861 ->

ESPExceptionDecoder Debug
Exception 3: LoadStoreError: Processor internal physical address or data error during load or store
PC: 0x4000e041
EXCVADDR: 0x4024bcc2

Decoding stack results
0x401003fc: millis() at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_wiring.cpp line 188
0x4020ef28: ClientContext::_write_some() at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 514
0x4020efc2: ClientContext::_write_from_source(DataSource*) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 450
0x4020f09d: WiFiClient::write(unsigned char const*, unsigned int) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 364
0x4020f060: WiFiClient::write(unsigned char const*, unsigned int) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src\WiFiClient.cpp line 220
0x4021104d: Print::write(char const*) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266/Print.h line 60
0x40211275: Print::println(char const*) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\Print.cpp line 129
0x402019b9: commands::HandleShortCommand() at D:\Temp\arduino_build_652018\sketch/commands.h line 363
0x40100304: ets_post(uint8, ETSSignal, ETSParam) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x4020f130: ClientContext::_consume(unsigned int) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 557
0x402027dd: serialEvent() at E:\Programme\Rasberry - Projekt\Projekt_FHEM\_Arduino\Firmware_SIGNALDUINO\SIGNALDuino-dev-r332_cc1101_200113\___funktionstuechtig_ESP\SIGNALESP/SIGNALESP.ino line 591
0x40202849: loop() at E:\Programme\Rasberry - Projekt\Projekt_FHEM\_Arduino\Firmware_SIGNALDUINO\SIGNALDuino-dev-r332_cc1101_200113\___funktionstuechtig_ESP\SIGNALESP/SIGNALESP.ino line 470
0x40212b68: loop_wrapper() at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 180

Well it crashes somewhere related to either answering something via WiFi or a serial command in commands::HandleShortCommand(). What are you entering as input?

The input ist only a command like V or ? link

exactly. What have you inputted? And what is your line end setting in the serial monitor?

I have to enter a V. If I look at the ESP with Netcat and type V, I get an answer. If I do the same with Putty Telnet (port 23), the stack comes :-(
V V 3.4.0-dev SIGNALESP cc1101 (chip CC110 unknown) - compiled at Feb  8 2020 16:08:51 ? ? Use one of V R t X S P C r W s x e V  With linebreak, but here ist it not view

I'm assuming you're taking the sketch from https://github.com/RFD-FHEM/SIGNALDuino and this issue is from you? (https://github.com/RFD-FHEM/RFFHEM/issues/795) Which ino file are you using exactly?

Right, here link is the testcode. This code have one ino SIGNALESP.ino
So you can see all files.

Yes the error is reproducable with PuTTY. It has something to do with line endings and invalid / empty commands. E.g., using ncat -v 192.168.1.135 23 and typing V it works, but with Putty there is a crash. With PuTTY configuration Terminal -> Local Line Ending: Force Off things are a bit better but still empty commands crash it. I'll have a look at the code.

The problem is that code like
            MSG_PRINTLN(TXT_UNSUPPORTED1);

with
#define MSG_PRINTLN(...) { MSG_PRINTER.println(__VA_ARGS__); }

and
static const char TXT_UNSUPPORTED1[]        PROGMEM = "Unsupported short command";

On the ESP8266 calls the println() function which accepts a char*, expected from RAM. However since the string here was put into flash and not RAM, this function will crash upon execution.
The fix is to use the __FlashStringHelper class which calls the correct println() overload and doesn't crash.
See PR https://github.com/HomeAutoUser/ERROR_search/pull/1 and https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html


text:
DT-06 program using arduino uno
I'm working to program DT-06 wireless wifi module.
And right now when i'm trying to program i get the following error message :
espcomm_send_command: can't receive slip payload data
Module RX - Arduino RX
TX - TX
VCC - 5v
GND - GND
Right now i can upload black program to arduino and send serial AT commands to my module and alson getting response.
How can i program ?
Thx
Appendix:

Module:  https://www.banggood.com/Geekcreit-DT-06-Wireless-WiFi-Serial-Port-Transparent-Transmission-Module-TTL-To-WiFi-p-1141047.html

Oh sorry I think I misunderstood the question -- Do you want to Programm the DS-06 module or do you want to program an Arduino to talk to the DS-06 module? If it is the latter, what current code are you using?

i want to programm the DT-06

Just program it like you would program a normal ESP8266.
The documentation is here:

https://github.com/SmartArduino/SZDOITWiKi/wiki/ESP8266---TTLtoWiFi

The datasheet provides the schematic of the module

So SW2 is the reset button and "SW1" is the "FLASH" button. To enter the bootloader mode in which the ESP8266 can be programmed, you first have to hold down the "FLASH" button then press "RESET" once.
For programming you would ideally get a 5V USB-UART adapter make the connections

VCC to 5V (it has a regulator to generate the actually needed 3.3V)
GND to GND
EN to 5V (e.g. via a pullup)
TXD to RX of UART adapter
RXD to TX of UART adapter

After the ESP is in the bootloader mode as described above, you can just program it normally through the Arduino IDE. Follow the instructions at https://github.com/esp8266/Arduino to install the ESP8266-Arduino core in the board manager.
Refer to the similiar procedure:

https://www.hackster.io/harshmangukiya/program-esp8266-esp-12e-with-arduino-using-ftdi-cable-2310c9

Thank you very much sir!  i'm new to this things. Thank you very much !

Right now i can flash the module like you show me. The code is uploaded but nothing in the serial monitor. #include <ESP8266WiFi.h>
WiFiServer server(80);
void setup() {
WiFi.mode(WIFI_AP);
WiFi.softAP("Hello_IoT","12345678");
server.begin();
Serial.begin(115200);
IPAddress HTTPS_ServerIP= WiFi.softAPIP();
Serial.print("Server IP is: ");
Serial.println(HTTPS_ServerIP);
}

@user863873 Did you press the reset button (SW2) after flashing?

Yes. I get in serial the reset 2 and the rest of the info

More info : i haven 2 module. One i did flash it and the other one not. When i wire the second one (the one that i dont flash it) it responds in serial using arduinonto AT commandas. The second with the same wiring and code using same arduino does not. Maybe it helps

What is the output after reset on 38400 baud (bootloader messages?) Can you try to blink GPIO4? pinMode(4, OUTPUT); et cetera. @user863873

I don't know if i understand correctly. But i flash the following code : void setup() {
pinMode(4, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(4, LOW);
delay(1000);
digitalWrite(4, HIGH);
delay(1000);
} with no  blink led from my module. I did hit "reset"

What does the bootloader report? What USB/UART adapter are you using?

I'm using arduino to flash my module

i'm getting 100% when i flash my module

After i flash my module and "reset" i get : ets Jan  8 2013,rst cause:2, boot mode:(3,6)
load 0x4010f000, len 1384, room 16
tail 8
chksum 0xef
csum 0xef
csum err
ets_main.c

There is a checksum error because you probably selected the wrong module size. Try selecting a different board variant in the Arduino IDE with different flash sizes until one works. Could also be the flash mode (DIO/QIO) or you must mass-erase the flash once. See the https://www.letscontrolit.com/forum/viewtopic.php?t=3071

That was the fix. After i set to ESP8285 all was good. Also i notice that i must have blank code in my arduino to be able to flash my module. Thank you sir !


text:
BMP280 seems to give odd pressure readings
I have connected an UNO with BMP280 and it sends reading through ESP-01 to thingspeak, and all seems working fine, but my pressure readings seem a bit odd.
To be clear any unchanged pressure reading is around 35.000 value.
As i understood that is in pascal, which is a bit strange, because the expected pascal value should be around 100.000
Code used is below, what am i missing ? Or are the readings ok?
Connection diagram and code used below:

    //ThingSpeak channel Key
String statusChWriteKey = "asd";

//Basic icludes
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>
#include <SoftwareSerial.h>
SoftwareSerial EspSerial(6, 7); // Rx,  Tx
#define HARDWARE_RESET 8

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10

Adafruit_BMP280 bme; // I2C

int temperature = 0;
int pressure = 0;
int altitude = 0;

// Variables to be used with timers
long writeTimingSeconds = 17; // ==> Define Sample time in seconds to send data
long startWriteTiming = 0;
long elapsedWriteTime = 0;

int spare = 0;
boolean error;

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

  pinMode(HARDWARE_RESET,OUTPUT);

  digitalWrite(HARDWARE_RESET, HIGH);

  Serial.println(F("BMP280 test"));

  if (!bme.begin()) {
    Serial.println("Could not find a valid BMP280 sensor, check wiring!");
    while (1);
  }

  EspSerial.begin(9600); // Comunicacao com Modulo WiFi
  EspHardwareReset(); //Reset do Modulo WiFi
  startWriteTiming = millis(); // starting the "program clock"

}

void loop()
{

  start: //label
  error=0;

  elapsedWriteTime = millis()-startWriteTiming;

  if (elapsedWriteTime > (writeTimingSeconds*1000))
  {
    readSensors();
    writeThingSpeak();
    startWriteTiming = millis();
  }

  if (error==1) //Resend if transmission is not completed
  {
    Serial.println(" <<<< ERROR >>>>");
    delay (2000);
    goto start; //go to label "start"
  }
}

/********* Read Sensors value *************/
void readSensors(void)
{
  temperature = bme.readTemperature();
  pressure = bme.readPressure();
  altitude = bme.readAltitude(1013.25);

}

/********* Conexao com TCP com Thingspeak *******/
void writeThingSpeak(void)
{

  startThingSpeakCmd();

  String getStr = "GET /update?api_key=";
  getStr += statusChWriteKey;
  getStr +="&field1=";
  getStr += String(temperature);
  getStr +="&field2=";
  getStr += String(pressure);
  getStr +="&field3=";
  getStr += String(altitude);
  getStr +="&field4=";
  getStr += String(spare);
  getStr += "\r\n\r\n";

  sendThingSpeakGetCmd(getStr);
}

/********* Reset ESP *************/
void EspHardwareReset(void)
{
  Serial.println("Reseting.......");
  digitalWrite(HARDWARE_RESET, LOW);
  delay(500);
  digitalWrite(HARDWARE_RESET, HIGH);
  delay(8000);//Tempo necessário para começar a ler
  Serial.println("RESET");
}

/********* Start communication with ThingSpeak*************/
void startThingSpeakCmd(void)
{
  EspSerial.flush();//limpa o buffer antes de começar a gravar

  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += "184.106.153.149"; // Endereco IP de api.thingspeak.com
  cmd += "\",80";
  EspSerial.println(cmd);
  Serial.print("sent ==> Start cmd: ");
  Serial.println(cmd);

  if(EspSerial.find("Error"))
  {
    Serial.println("AT+CIPSTART error");
    return;
  }
}

/********* send a GET cmd to ThingSpeak *************/
String sendThingSpeakGetCmd(String getStr)
{
  String cmd = "AT+CIPSEND=";
  cmd += String(getStr.length());
  EspSerial.println(cmd);
  Serial.print("sent ==> lenght cmd: ");
  Serial.println(cmd);

  if(EspSerial.find((char *)">"))
  {
    EspSerial.print(getStr);
    Serial.print("sent ==> getStr: ");
    Serial.println(getStr);
    delay(500);//tempo para processar o GET, sem este delay apresenta busy no próximo comando

    String messageBody = "";
    while (EspSerial.available())
    {
      String line = EspSerial.readStringUntil('\n');
      if (line.length() == 1)
      { //actual content starts after empty line (that has length 1)
        messageBody = EspSerial.readStringUntil('\n');
      }
    }
    Serial.print("MessageBody received: ");
    Serial.println(messageBody);
    return messageBody;
  }
  else
  {
    EspSerial.println("AT+CIPCLOSE");     // alert user
    Serial.println("ESP8266 CIPSEND ERROR: RESENDING"); //Resend...
    spare = spare + 1;
    error=1;
    return "error";
  }
}

the data sheet says that it reports the value in hPa (hectopascal)  ...... note: i just checked https://www.wunderground.com/ and it reports the atmospheric pressure in my area to be 950.9 hPa (which is 95090 Pa)

to start, test the sensor by removing all the code that has nothing to do with reading the sensor and print out the raw reading from the sensor

i have done that, loaded the basig example sketch onto the uno that comes with the BMP280 lib, with out any convesion it outputs the measured data, and it gives values inbetween 34.000 and 35.000. so it is not a wiring issue i believe, but suspect a faulty chip

It appears that you might be looking at a field 3 in Thingspeak instead of field 2...Here is why:
Do you live at a low elevation?  Here is why I ask that question.
This statement:
pressure = bmp.readPressure();
returns the pressure in pascals (sea level is 101325 pascals) from the BMP280 and assigns it to the variable pressure.
To get pressure in mb you would divide by 100 (a mb is = to 1 hPa or 100 Pascals).
If you were expecting a value of 100 (kPa?) perhaps that means you would be living near sea level.. perhaps about 100 feet (35m) or so.
If that is the case then the statement:
altitude = bmp.readAltitude(1013.25);
which ultimately feeds the Thingspeak field 3 the calculated altitude in meters (in this case about 35 meters).
Check and make sure you are looking at Thingspeak field 2 and not field 3 for pressure readings.
If you want to see pressure in mb change the line that reads pressure from the BME280 to the following:
pressure = bmp.readPressure()/100;


text:
keypad storing problem (void value not ignored as it ought to be)
I am trying to input 11 numbers only by the use of keypad but the problem is whenever i use this code. It gave me this error.
Here's my code. Help please.
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
SoftwareSerial mySerial(6, 5);
int table[] = { 0, 0, 0 };
#include <Keypad.h>
#include <Wire.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

char keys[ROWS][COLS] = {
    { '1', '2', '3' },
    { '4', '5', '6' },
    { '7', '8', '9' },
    { '*', '0', '#' }
};
byte rowPins[ROWS] = { 2, 3, 17, 16 }; //connect to the row pinouts of the keypad
byte colPins[COLS] = { 15, 14, 13 }; //connect to the column pinouts of the keypad
int count = 0;
Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
char entryStr[13]; // This can hold up to 4 digits
int i = 0;
char n1, n2, n3;
char buf[15]; // i put here***
void setup()
{
    Wire.begin();
    Serial.begin(9600);
    Serial.begin(9600);
    lcd.begin(20, 4);
    ask();
}

void loop()
{
    Wire.requestFrom(2, 3); // request 6 bytes from slave device #2 for(int i=0;i<3;i++) {

    int c = Wire.read(); // receive a byte as character
    Serial.print(c);
    table[i] = c;
    Serial.print('\t');
    // print the character } Serial.print('\n'); Serial.print(table[0]); Serial.print('\t'); Serial.print(table1); Serial.print('\t'); Serial.print(table[2]); Serial.print('\n');

    //if(table[0]<=8) //{ //Serial.print("Flame Detected!"); //Serial.println("Level1");
}
void ask()
{

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no1.:");
    lcd.setCursor(0, 1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    n1 = GetNumber(buf, sizeof(buf) - 1);

    Serial.print(n1);

    delay(1);

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no2.:");
    lcd.setCursor(0, 1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    n2 = GetNumber(buf, sizeof(buf) - 1);

    Serial.println(n2);
    delay(1);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no3.:");
    lcd.setCursor(0, 1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    n3 = GetNumber(buf, sizeof(buf) - 1);

    Serial.println(n3);
    delay(1);
    Serial.println(n1);
    Serial.println(n2);
    Serial.println(n3);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("list of numbers ");
    lcd.setCursor(0, 1);
    lcd.print("will be shown press");
    lcd.setCursor(1, 2);
    lcd.print("reset if wrong");

    delay(7000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Numbers Stored:");
    lcd.setCursor(0, 1);
    lcd.print("no1.:0");
    lcd.print(n1);
    lcd.setCursor(1, 2);
    lcd.print("no2.:0");
    lcd.print(n2);
    lcd.setCursor(2, 3);
    lcd.print("no3.:0");
    lcd.print(n3);
}
void GetNumber(char* result, const int maxLength)
{
    char key = kpd.getKey();
    int i = 0; // how far through buffer we are
    while (key != '#') {
        switch (key) {
        case NO_KEY:
            break;

        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':

            lcd.print(key);
            if (i < maxLength) {
                result[i++] = key;
                result[i] = 0; // terminating null
            }
            break;

        case '*': // backspace
            if (i > 0) {
                i--;
                result[i] = 0; // terminating null
            }

            break;
        }

        key = kpd.getKey();
    }

} // end of GetNumber

Please describe in greater detail.

The GetNumber() function is coded in such a way as to pass the collected value back through the result parameter.

void GetNumber(char* result, const int maxLength)

So, when you use the GetNumber() function, you pass it buf, and after the call returns, you will find the result in the buf char array.
However, you appear to be trying to store the result in n1, n2, and n3, which are char type variables, and can hold only one character, or a number between 0 and 255, neither of which can hold an 11-digit string of numbers like you wish.
A char is an 8-bit variable. An int (on Arduino Uno) is a 16-bit value and can hold at most 32,768. Even an unsigned long, a 32-bit variable of all positive numbers, can hold a maxiumum value of 4,294,967,295, which gets at most all 9-digit numbers, and some 10-digit numbers.
You would probably be better off holding the numbers as character arrays just like buf, and passing those as the first parameter of GetNumber() instead of buf:
char n1[15], n2[15], n3[15];
...
GetNumber(n1, sizeof(n1) - 1);
...
GetNumber(n2, sizeof(n2) - 1);
...
GetNumber(n3, sizeof(n3) - 1);

If you do that, then you can get rid of buf entirely.
Alternatively, you can keep buf as the temporary holder of the incoming string and use strncpy() to copy the string from buf to n1 (etc.):
GetNumber(buf, sizeof(buf) - 1);
strncopy(n1, buf, sizeof(n1));

This method uses more memory, as you have buf taking up space, but it has an advantage that you can later do validation or error checking on the user input before you overwrite n1 or the others with the new value.

I already change the code to char[15] n1, n2, n3; but this line give me error it says "expected unqualified-id before '[' token"

My typo. The declaration should have said char n1[15], n2[15], n3[15];

Thank you I already change it but it gives me another new error to this line  n1 = GetNumber(n1, sizeof(n1) - 1); the error is "incompatible types in assignment of 'void' to 'char[15]' " Thank you really.

Don't say n1=. Please re-read the answer. Take the time to understand what the code does instead of copying-and-pasting blindly, and you will do much better.

Really sorry and its okay now. Thank you for your help . Thanks a lot :)

Your GetNumber function is defined to return void (nothing) while you use it as if it returns the number typed.
change GetNumber to return a int and the end of it do a atoi using the buffer and return the result.

Thank you . Can you give me idea how to do it in my code?Please elaborate thanks a lot.

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


text:
2 buttons, 1 servo, turn when pressed only
I have a code problem. I need to turn a servo clockwise or counter clockwise using 2 microswitches.
The problem is that my code is fine on startup, but when i press the button the servo continues to spin.
How do i make this so it only spins while the buttons are pressed and turn off when they are not pressed?
#include <Servo.h>

Servo myservo; // create servo object to control a servo

// CONSTANTS

// PINS
const int crServo = 12; // sets pin 12 as servo
const int buttonPinCW = 2; // sets pin 2 as button; CW => clockwise => FOCUS FAR
const int buttonPinCC = 3; // sets pin 3 as button; CC => counterclockwise => FOCUS NEAR

// SERVO PROPERTIES
const int crSpeedDefault = 0; // is the stay still position, motor should not turn
const int crSpeedCW = 110; // turns the motor full speed clockwise
const int crSpeedCC = 70; // turns the motor full speed counter-clockwise

// SET BUTTON STATES
int buttonStateCW = 0; //sets button 1 as off
int buttonStateCC = 0; // sets button 2 as off

void setup()
{
  myservo.attach(crServo); // attaches the servo on pin 12 to the servo object
  pinMode (crServo, OUTPUT);
  pinMode (buttonPinCW, INPUT); // sets button as input
  pinMode (buttonPinCC, INPUT); // sets button as input
  myservo.write(crSpeedDefault); // default servo to crSpeedDefault
}

void loop()
{
  crServo = digitalRead(crSpeedDefault);
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);
  // clockwise rotation
  if (buttonStateCW == HIGH) {
    myservo.write(crSpeedCW);
    // counterclockwise rotation
  }
  if (buttonStateCC == HIGH) {
    myservo.write(crSpeedCC);
  }
}

Do you have an external pull-down on your buttons?

Hi Maximilian, Yes, i have a wheel which spins manually by a user. The idea is that when the steering wheel spins 180 degrees a microswitch is pushed. This turns the servo one direction, the opposite is to turn the servo in the opposite direction.

I meant a pull-down resistor. Your firmware logic is that if the button pin reads "HIGH" it is pressed. Thus you must have a button via pull-down to GND and other side to +5V connected right? Also: Why is the line crServo = digitalRead(crSpeedDefault); there? With const int crServo = 12 the variable cannot be changed. It doesn't make sense to re-write the servo pin to 0 or 1 using the result of digitalRead, which reads from pin 0 which is the Serial TX of the Arduino.

If you want the logic "if none of the two buttons are pressed, stop the servo immediately", then you'd express this in your loop as a if expression where you check if both buttons read LOW:
void loop()
{
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);
  // clockwise rotation
  if (buttonStateCW == HIGH) {
    myservo.write(crSpeedCW);
    // counterclockwise rotation
  }
  if (buttonStateCC == HIGH) {
    myservo.write(crSpeedCC);
  }

  //Are both buttons not pressed?
  if(buttonStateCC == LOW && buttonStateCW == LOW) {
    //Stop the servo.
    myservo.write(0);
  }
}

This assumes your buttons are with pull-down resistors to GND on one side and with +5V on the other side, as detailed in the Arduino tutorial. In short this means that an unpressed button reads as 0 and a pressed on reads as 1 (HIGH). This is unusual because we usually use the internal pullup resistors via the INPUT_PULLUP pinMode parameter with a switched logic (1 = unpressed, 0 = pressed).
I've also removed the line crServo = digitalRead(crSpeedDefault); because that doesn't make sense in my opinion, as I've detailed in my comment.

thank you, Maximilian i think this must be in my switch wiring, the code edit you sent makes them spin continuously in either direction when the button is pressed. I think i need to have a look at quite how i wire these up to the Uno as something is a-miss here i think.

Please edit your question to show your circuit then.

sorry for the delay, ok the buttons go to GND and to the input pins 2 & 3 (there are 2 buttons 1 to 2 and 1 to 3)

then the servo comes off 12 and is also connected to GND and +5v

@Richard When you edit your question you will notice a "Schematic" tool button with which you can accurately present your circuit.

@Richard there was a copy-paste error in my answer in the if-statement which may have caused the fail. Retry please.

This solution is similar to @Maximilian Gerhardt's solution. So his comments on the pull-up/down resistors apply.
I assume that you only want to turn either CW or CC and not oscillate between the two.
Then you should cater for 4 button conditions:
None pressed, CW only press, CC only press, both pressed.
We only need to worry about the "only pressed" conditions and a default state when coding.
Here is my solution:
void loop()
{
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);

  // CW button pressed only
  if (buttonStateCW == HIGH && buttonStateCC == LOW) {
    myservo.write(crSpeedCW); // clockwise rotation
  }
  // CC button pressed only
  else if (buttonStateCW == LOW && buttonStateCC == HIGH) {
    myservo.write(crSpeedCC); // counterclockwise rotation
  }
  // Default condition
  else {
    myservo.write(crSpeedDefault);
  }
}


text:
ESP8266 stops working when I use 2x static const char(PROGMEM)
*Sdk version: 2.2.2-dev(5ab15d1)
*Core Version: 2_6_1
This is the error returned:
Exception 3: LoadStoreError: Processor internal physical address or data error during load or store PC: 0x4000bf64 EXCVADDR: 0x4024e963
Decoding stack results
0x4020175d: HTML1(String) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266/WString.h line 128
0x40238c26: umm_info(void*, int) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\umm_malloc/umm_info.c line 164
0x40100278: millis() at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\core_esp8266_wiring.cpp line 188
0x40238c26: umm_info(void*, int) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\umm_malloc/umm_info.c line 164
0x4020af74: String::copy(char const*, unsigned int) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\WString.cpp line 214
0x40201a3c:

Code:
static const char HTML1[] PROGMEM = R"=====(
<!DOCTYPE HTML><html><head>
<meta charset='utf-8' name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0'>
)=====";

static const char HTML2[] PROGMEM = R"=====(
<button type='button' onclick='sendData(2)'>Test2</button>
)=====";

String html_return = HTML1;
html_return += "<button type='button' onclick='sendData(1)'>Test</button>";
Serial.println("Before Second Const Char");
html_return += HTML2; //<< ESP stops working here

If I remove static declaration, it doesn't compile in local function. I've tried to declare HTML1[] and HTML2[] out of the function without static declaration, but the error is the same.

I still have memory, I'm only using (42%) of 81Kbytes.
So I'm working without PROGMEM and it works like bellow:
String HTML2 = R"=====( <button type='button' onclick='sendData(2)'>Test2</button> )=====";

See Guide to PROGMEM on ESP8266 and Arduino IDE.
Since you put your char array into PROGMEM, special functions must be used to load it from flash into RAM; so to load it into a String object, the FlashHelper class must be used. You can simply use the macro FPSTR(progmem_ptr).
#include <Arduino.h>

void setup() {
    Serial.begin(115200);
    Serial.println("\nStart firmware");

    static const char HTML1[] PROGMEM = R"=====(
    <!DOCTYPE HTML><html><head>
    <meta charset='utf-8' name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0'>
    )=====";

    static const char HTML2[] PROGMEM = R"=====(
    <button type='button' onclick='sendData(2)'>Test2</button>
    )=====";

    String html_return = HTML1;
    html_return += "<button type='button' onclick='sendData(1)'>Test</button>";
    Serial.println("Before Second Const Char");
    //html_return += HTML2; //crashes
    html_return += FPSTR(HTML2); //works
    Serial.println("Result");
    Serial.println(html_return);
}

void loop() {

}

Outputs
Start firmware
Before Second Const Char
Result

        <!DOCTYPE HTML><html><head>
        <meta charset='utf-8' name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0'>
        <button type='button' onclick='sendData(1)'>Test</button>
        <button type='button' onclick='sendData(2)'>Test2</button>

FPSTR macro casts the type and so forces the use of the right + operator for a PROGMEM string. It is the same as html_return += F("some text stored in progmem");

Dear Maximilian, thank you for the detailed answer, works very well. Saved my ESP memory!


text:
Arduino Uno & ESP32 communication using RS485
I am trying to establish a communication between Arduino Uno ( Master) and ESP32 (Slave) using RS485 protocol (using MAX485 module).
I have successfully done this between two Arduino Unos. SoftwareSerial library is what i am using between two Arduino Unos, now trying with ESP32 and Arduino Uno (using MAX485 module)
.
For ESP32 i have used SoftwareSerial (https://github.com/akshaybaweja/SoftwareSerial) library.
After reading the library and making connection i am not be able to establish a communication between them. Sharing my code below.
Receiver
#include <SoftwareSerial.h>

SoftwareSerial softwareSerial(9, 10);
String str;

void setup()
{

  Serial.begin(9600);
  softwareSerial.begin(9600);

}

void loop()
{

  while (softwareSerial.available() > 0) {

    char inChar = softwareSerial.read();

    if (inChar == '$') {

        str.trim();
        Serial.println("received command" + str);
        memset(&str, 0, sizeof(str));
        Serial.flush();
        softwareSerial.flush();
    }
    else {
        str = str + inChar;
    }

 }

}

Sender
#include <SoftwareSerial.h>

SoftwareSerial swSer1(22, 23, false, 256);
String str;

void setup() {

  Serial.begin(9600);
  swSer1.begin(9600);

}

void loop() {

  String sendCmd = "MSG1$";
  Serial.println("Sending ");
  Serial.println(sendCmd );
  char copy[50];
  sendCmd.toCharArray(copy, 50);
  swSer1.write(sendCmd);
  delay(1000);

}

Here my question is where i am going wrong in this project. Please guide me.
Note : DE AND RE PINS are connected to high for sender device and to low for receiver device as given in the RS485 documentation.

Maybe you have already solved this but in any case, have you tried working with the hardware serial ports? You have three of them in the ESP32. I read sowhere else that there may be some interrupt issues using the SoftwareSerial library on the ESP devices, especially at higher baud rates.

I havent solved yet , i changed the circuit itself other than what i was using.. also i have tried but those are not so helping me in my application.

@dejoo Where you read about some interrupt issues? I work in Arduino Libraries and I'll like receive this information. Thanks!:) Pd. I can't comment because I just registered

I don't think you can use pins 9 and 10 they are connected to the internal mSPI flash, uart0 is connected to FTDI usb chip, use uart2 on 16 and 17.


text:
Creating a router with ESP32 and SIM800c
I am trying to create a device which is a combination of ESP32 and Sim800c.
This device (Master) will start AP mode on ESP32, so that other devices (Nodes) will connect to this AP. The Sim800c will provide 2G internet connection to the ESP32.
The nodes will be executing a HTTPS request and via this device (Master) the http request will gets executed and the response will be received via the Master device and again forwarded to the Node.
Basically this device which i am trying to create will act as a WiFi router which provides internet connection to the Nodes.
Hence my question is, will this device work as expected.

yes, such a device should work

@jsotola : thanks for the quick response. i have a query here, you have written should work in your comment. Can u reply with the possible challenges you think will occur.

it is unknown if you have the skill to develop the necessary code

Sure you can write code that will receive a request over WiFi in some format that you specify, then make a HTTPS request over 2G, and send the response back over WiFi. It won't be simple code, and you have to remember that it's the "server" node that has to make the HTTPS request, not the "client" nodes.


text:
Using Visual Studio Code with Arduino
I'm trying to figure out how you can work with multiple sketches using Visual Studio Code and the Arduino.
Let's say I have three projects that I want to actively develop.
Motors.ino
Motors_with_controls.ino
Motors_with_lights.ino

Each one is a different project, but I want to quickly be able to upload one, then upload another.
My folder for Visual Studio Code is set up as such:
ArduinoProjects
   .vscode
       arduino.json
       c_cpp_properties.json
   Motors
       Motors.ino
   Motors_with_controls
       Motors_with_controls.ino
   Motors_with_lights
       Motors_with_lights.ino

But it seems like the only way to upload a particular ino is to go into the arduino.json file and hand edit the "sketch" parameter.
"sketch": "Motors\\Motors.ino"

Is there a quicker way? Ideally I'd like it to upload the ino I am currently editing without having to go and edit the arduino.json file.

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