text:
NodeMcu pins and an RGB LED
I'm using a NodeMcu for my project and am running out of pins to use. I have a MFRC522 Module, IR Receiver, Buzzer and RGB LED connected. I am facing the problem that whenever I start scanning for RFID tags with the MFRC522 module, the onboard LED starts flashing very fast and the RGB LED changes to an undefined color.
I looked up the pin definitions of the NodeMcu, but couldn't quite find information on what pins I can use for this and which I can't, and why this only happens once I start up the RFID reader.
This is my wiring sketch:

I found this pin layout image, as well as the datasheet.
The code shouldn't be really relevant since it works before starting the RFID reader, but here is the setup of the reader, just in case:
#define SS_PIN D4   // SPI - Slave Select Pin
#define RST_PIN D2  // SPI - Reset Pin - not actually connected

MFRC522 mfrc522(SS_PIN, RST_PIN);

// Initial setup for SPI and MFRC522
bool rfidSetupCompleted = false;
void setupReader()
{
  SPI.begin();
  mfrc522.PCD_Init();
  rfidSetupCompleted = true;
}

These are the pin definitions of the RGB LED:
#define LED_BLUE D8
#define LED_GREEN D3
#define LED_RED D2

Any help is highly appreciated! I'm assuming I am using a pin that is used for other purposes (such as maybe D8), but I can't figure out which, and why. I did try to change up the pins and switched D0 and D8 (buzzer and one LED pin), but without luck. I also tried disconnecting each LED pin separately, but didn't learn anything from that either.

what library for MFRC522  you use? I think you should set all SPI pins for the library, to set the correct SPI interface. Or if the library doesn't initialize SPI library, you should do it in setup()

@Juraj I'm using this: https://github.com/miguelbalboa/rfid
The library only takes those two parameters so I'm not sure if that is needed. And I do initialize the SPI library in my setup code.

@Juraj I have it in the setup method that I posted above. This is executed before I start using the MFRC522. I have it that way because I split up the code into several files.

then SPI looks OK, because D5, D6 and D7 are default SPI pins in SPI library

@Juraj yeah exactly. I do have one wire attached to D8, which is "HCS" according to this image: https://pradeepsinghblog.files.wordpress.com/2016/04/nodemcu_pins.png?w=616
I'm not sure if this might cause issues

D8 is Slave Select if esp8266 is slave. in your case esp8266 is master so you can choose Slave/Cable Select pins for devices on SPI bus. it is common to use SS pin as CS pin for the first device, but it is not mandatory.

the problem could be powering of the board

Is the MFRC522 module 3.3 V?

Meaning I can't use the pin for something else when I want to use the MFRC522? That does make sense that it's doing weird things once I start using it. And yes, the MFRC522 is 3.3V, and so is the NodeMcu. So that shouldn't be a problem.

I switched D4 and D8 around now, don't know why I didn't have it like that in the first place. The onboard LED doesn't flash anymore, but the RGB LED still changes it's color. Could this be because D4 is TXD1 and D8 TXD2? It shows me a connection between the two when I wire it in Fritzing. Can I use any other pins on the NodeMcu for this?

@Juraj I found out that the colors work correctly when I start scanning with the MFRC522 a second time. It's supposed to be blue during the scan, but is purple during the first scan. When pressing the button to start it again, it works correctly. So I'm assuming I have to set up the reader at the very start of the program or something similar.

@Juraj I fixed it by setting up the MFRC522 at the very start of the program now. Thank you for your help!

I fixed the issue by swapping pin D4 and D8, and then setting up the MFRC522 at the very start of the program. I originally set it up before I started using it, which caused the color to change during the first scan.

SPI.begin sets io15 (D8) mode even it is not used as SS pin for your device. It is better to use io15 (D8) as slave select pin for one of the slave devices. In your case for the one device you have on SPI bus.
Pins io 0 (D3) and io 2 (D4) have on-board pull-up, because they are boot configuration pins. Set them LOW right after setting pinMode for them, to not let current to LED RGB legs.


text:
how to increase the delay factor of DHT11?
There is no compiler error but output is showing timeout error.
as per as the instruction given in
https://github.com/RobTillaart/Arduino/issues/61
it says to increase the timeout factor but i did not found the constraints which were asked to be changed.

I think you need to change the library files themselves.

He has five dht libraries. Do you know which one you are using? The problem might be the nodemcu in combination with the library and the sensor. The dht11 and dht22 might behave differently than a few years ago. Some libraries cause a shortcut in the data signal, which is a serious problem for the nodemcu. The 'DHTLIB_TIMEOUT' is declared in the .h file. To be compatible with all arduino board, a timeout should be in milliseconds.

I didn't find any constraint named  DHTLIB_TIMEOUT which should be there in .h file.
I am using a NodeMCU board and i have tried three different DHT11 libraries but none of them seems to work.
can you provide me the  links from where can i download the necessary library

I don't know, there are so much more than 3 libraries. The libraries for the dht11 for a esp8266 is a big mess. Even the nodemcu code has troubles with the (newer) dht11 sensors: https://github.com/nodemcu/nodemcu-firmware/issues/2253 Which libraries did you try? Do you use a pullup resistor? What is the value of that resistor? Do you use long wires? Do you have another dht11 sensor, perhaps this one is broken. If you want to know the humidity then perhaps you should buy a better sensor with i2c. The dht11 returns a number that has little to do with the humidity, it is not accurate.

The dht11 that i was using had an onboard pull up register and i didn't use any sort of wire just jumper cables for minimalist connection.and i have tried 2 different sensor but all produced NAN value
I think instead of taking all this burden i will go for an i2c sensor.
Thanks a lot @Jot

I will make an answer for it.

The DHT11 and DHT22 used to be cheap and easy to use humidity and temperature sensors when they were used together with an Arduino Uno.
But things have changed.

They are not accurate and can become totally inaccurate with certain
gasses or fumes.
It turned out, that the most used DHT libraries have
a serious bug that creates a shortcut in the datasignal.
This was no problem with the Arduino Uno, which can output
40 mA with a pin. The newer processors have problems with
that shortcut.
In 2018 the DHT11 seems to behave differently,
the internal controller has probably changed.
Because the communication with the sensors requires accurate timing,
the interrupts are turned off temporarily. That was no problem
with the slow Arduino Uno, but it is not normal with
a faster processor.
Some libraries use a timeout with a loop or with clock cycles.
That worked well with the Arduino Uno,
but it is not always reliable with newer processors.

In 2018, all the DHT libraries for the ESP8266 and ESP32 have issues with the DHT11 and DHT22.
Since the sensors are not very accurate anyway, it is best to stay away from all the troubles and avoid them. There are a number of good humidity sensors with I2C interface.

source: Stack Exchange

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

sort: votes


text:
Accessing one code using another code on RobotDyn Uno+WiFi board
Ok so I've been trying to do this for quite some time now. Still couldn't get it to work. I am trying to read a ESP8266 WiFi program from a normal Arduino Uno program. I've seen some people do this:
#include <SoftwareSerial.h>

Then
SoftwareSerial esp8266(2,3);

Let me see a working example of this?
Thanks for everything.

it is an additional Serial interface called esp8266. You can print to it and read from it by Stream functions. What else? https://www.arduino.cc/reference/en/language/functions/communication/stream/

Thanks, so from what I perceive, Stream is a library? If it is, I would go include it.

Stream is a common class from which Serial, SoftwareSerial and similar are derived

You can't 'access code'. You can write sketches to communicate for example over Serial or SoftwareSerial. You connect the pins of Serial interfaces RX to TX and let sketch in one MCU read or parse what the sketch in other MCU sent over Serial with print or write.

I am using this board:
Link I bought the board from
The WiFi shield is integrated with the board, so I think no need to connect the PINs?

You can't 'access code'. You can write sketches to communicate for example over Serial or SoftwareSerial. You connect the pins of Serial interfaces RX to TX and let sketch in one MCU read or parse what the sketch in other MCU sent over Serial with print or write.
The onboard connection on Uno+WiFi board is over Serial. So you can't use USB and connection to esp8266 at the same time. But you could use SoftwareSerial like other use it with esp8266, if you connect some pins (for example 6 and 7) of Uno headers to Serial of esp8266 which is accessible on the esp8266 header on the board.

So in order to communicate because Arduino sketch and the ESP8266 sketch, I must
[1] connect the TX and RX of Arduino to RX and TX of ESP8266
[2] use serial stream class to send and receive data between them
Am I correct?

RS and TX of esp8266 and Atmega are connected on board, if you set it on DIP switches. but then the connection to computer is out. all tutorials on Internet show you how to use SoftwareSerial to connect to esp8266 and have Serial connection over USB to computer. and you can achieve this SoftwareSerial connection with this board too. by wiring selected Atmega SoftwareSerial pins to RX and TX of esp8266 and setting the DIP switches to connect Serial of Atmega to computer over USB

So does it mean, if I use SoftwareSerial, I must use the external connection as it is required by the SoftwareSerial library and it does not occupy the physical USB serial port so I can still connect the board to computer?
If I don't want to use SoftwareSerial (and thus no need external wiring), what is the option I have to communicate between ESP8266 and Arduino sketches?

Switches 1 and 2 connect Atmega to esp8266. I recommend you to use this SoftwareSerial connection for developing the sketch. otherwise you would have hard time always switching the DIP switches for upload of sketch and you could not have debug prints in Serial Monitor.

A BIG thank you for your kind assistance and advice. I now have better understanding on how should I proceed.

a small note: the Mega+WiFi has it better. Atmega 2560 on board has more Serials so Serial3 can be connected to esp8266 and Serial to USB as usual

One more question. To upload sketch to ESP8266, I need to turn on DIP switch 5,6,7. To upload sketch to Atmega, I need to turn on DIP switch 3,4. So it means I still need to switch the DIP switches when I upload. Just in case I want to get rid of external wiring, I can turn on DIP switch 1,2? In the table it says Mega328+ESP8266 if 1,2 is ON, I guess it means Mega328 and ESP8266 can communicate if DIP is 1,2?

I'll take note on your advice on using Atmega2560 on board for my next project.

a good trick is uploading to esp8266 over WiFi with ArduinoOTA library. the you need to switch USB to esp8266 only if the OTA upload doesn't success

Thanks for the ArduinoOTA tips. I am running out of time for current project. Will definitely try it out on my next project. THANK YOU!!! You made my day.

Let us continue this discussion in chat.

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


text:
How to Connect ESP8266 with ultrasonic sensor and dht11 without breadboard?
I want to connect the sensors in Esp8266 after I code those using arduino uno r3. The problem is that I don't have the idea on connecting those sensors without breadboard. Thank you

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

Don't keep asking the same question in a slightly different way, please.

If you do not want to use a breadboard, you could solder the wires together of tie them together, so long as none of the wires which aren't supposed to be touching are touching. Or you can also use flex tape! (Don't mind my meme)

aha okay :) I had edited the question and added image from online based on a breadboard

A diagram of the internal wiring of a breadboard is found at http://www.fiz-ix.com/2016/04/breadboard-wiring-diagram/
Image duplicated here:

All you need to do is make sure all the same connected points from your breadboard circuit remain connected in the same way on a perfboard or PCB.
There are several ways to make a circuit on perfboard, and this answer on electronics SE shows some examples of using solder bridges as interconnects, short uninsulated wires, and insulated "wire wrap" wires.
You can also find perfboards with the same connection layout as a breadboard for easy transfer from a breadboard-wired circuit, as shown below:


text:
DIP switches on RobotDyn Uno+WiFi
There are theses 8 small pins on the Uno+WiFi board. Can someone please give me a detailed table or something on the settings of these 8 DIP switches?
I'm sorry if this question has already been answered somewhere else but I am bad at looking for stuff online.
Thanks

but the table is on the link you provided in previous question. CH340 is USB converter for connection to computer. https://robotdyn.com/uno-wifi-r3-atmega328p-esp8266-32mb-flash-usb-ttl-ch340g-micro-usb.html

Oh ok thank you very much I am sorry for the inconvenience caused here

There are 3 major chips on the board. Atmega 328, esp8266 and the USB converter CH340. Every device has one RX and one TX pin. But you need sometimes connect the Atmega to esp8266, sometimes connect the Atmega to computer over USB and sometimes connect the esp8266 to computer. The first 6 switches are in pairs (RX and TX) for connecting two of the 3 devices.

1,2 ON all others OFF connect esp8266 to Atmega. no connection to
computer.
3,4 ON all others OFF connects Atmega to computer over USB. no
connection to esp8266
5,6 ON all others OFF connects esp8266 to computer over USB. no
connection to Atmega

The switch 7 sets io 0 of esp8266 LOW which puts esp8266 to flashing mode at reboot. So you turn it ON with connection of esp8266 to USB (computer) to upload sketch to esp8266.


text:
nodeMCU - Millis() - Simple Counter - How long is LED on?
PROGRESS, now I have this (WITH GREAT HELP):
void setup() {
   Serial.begin(9600);
// initialize digital pin 13 as an output.
}
uint32_t timer_start = 0;
int timer_running = false;

void loop()
 {
// Get LDR information
  int sensorValue = analogRead(A0);         // read the input on analog pin 0
  float voltage = sensorValue * (5.0 / 1023.0);     // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V)
  float lux = voltage * 100;

 if (lux>150) {
    if (!timer_running) {
      // Timer is not already running, so capture the start time
      timer_start = millis();
      timer_running = true;
    }
  } else {
    if (timer_running) {
      // The timer is currently running; stop it calculate/print the run time
      timer_running = false;
      Serial.println((millis()-timer_start) / 1000.0, 3); // format however you like here

    }
  }

 }

This now tells me how many millis the gymnast is in the air, divided by 1000.0 with 3 decimals. If I start the Serial Monitor when the gymnast is in the trampoline bed, then I can get the seconds of air_time the gymnast has. Is there a way to have this script running ONLY for 10 loops?

You test if the lux is above 150 and always execute that code as long as the lux is above 150. You need to know the moment that the lux is above 150 for the first time. Have a look at this example: https://www.arduino.cc/en/Tutorial/StateChangeDetection Turning millis into minutes and seconds can be done with /60 and %60 after the elapsed millis is divided by 1000.

I think you need to maintain a static unsigned long last_off = 0; state variable in loop{}, resetting at the end of the else clause: last_off = millis();  and also report at the beginning of the else clause if some on_time=millis()-last_off is greater than some threshhold.  Are you having problems with the formatting?  Or with calculating the on time?

With your updated code, you did not maintain the same code structure as in the given example. In your updated code, the if (lux>150) {...} block has the timer start and stop code, where instead, the if (lux>150) {...} block should have the timer starting code, and the else {...} block (meaning, where lux<=150) should have the timer stopping code.

Declare a global (or static) boolean variable to keep track of whether the timer is running or not, as well as a variable to hold the start millis() value. When the lux drops below your threshold, subtract the current millis() from the start value, and you have the duration in milliseconds, which is trivial to convert to mm:ss.sss format.
Example code (not a complete sketch)
uint32_t timer_start = 0;
uint8_t timer_running = false;

void loop() {
  if (lux>150) {
    if (!timer_running) {
      // Timer is not already running, so capture the start time
      timer_start = millis();
      timer_running = true;
    }
  } else {
    if (timer_running) {
      // The timer is currently running; stop it calculate/print the run time
      timer_running = false;
      Serial.print(millis()-timer_start); // format however you like here
    }
  }
}

This now tells me how many millis the gymnast is in the air, divided
  by 1000.0 with 3 decimals. If I start the Serial Monitor when the
  gymnast is in the trampoline bed, then I can get the seconds of
  air_time the gymnast has. Is there a way to have this script running
  ONLY for 10 loops?

Certainly. If it is assumed that you want a cumulative total air-time, then you need to declare another global or static variable to hold the cumulative air-time, and you need to have another variable to keep track of how many cycles have passed.
void setup() {
   Serial.begin(9600);
// initialize digital pin 13 as an output.
}
uint32_t timer_start = 0;
int timer_running = false;
uint32_t total_time = 0;
uint8_t jump_count = 0;

void loop()
{
// Get LDR information
  int sensorValue = analogRead(A0);         // read the input on analog pin 0
  float voltage = sensorValue * (5.0 / 1023.0);     // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V)
  float lux = voltage * 100;

  if (jump_count<10) {
    if (lux>150) {
      if (!timer_running) {
        // Timer is not already running, so capture the start time
        timer_start = millis();
        timer_running = true;
      }
    } else {
      if (timer_running) {
        // The timer is currently running; stop it calculate/print the run time
        timer_running = false;
        // Add this-jump air time to the cumulative total:
        total_time += millis()-timer_start;
        // Increment jump_count
        jump_count++;

        Serial.println((millis()-timer_start) / 1000.0, 3); // format however you like here
      }
    }
  } else {
    // Print the total air-time for 10 jumps;
    Serial.println((total_time)) / 1000.0, 3);
  }
}

Why uint16_t and uint8_t? Why not just int?

Those types are not critical. On Arduino, memory is tight, so it's simply a preference to use the smallest necessary variable type. timer_running can fit in the smallest type, uint8_t, while any result from millis() is an unsigned long, equivalent to uint32_t (fixed in the example code; should not have been uint16_t)

Alright, thx. Now for the timer_running, what is the reason for the "!" exclamation mark? And does the timer go in the void setup, in the void loop or in between?

! is the negation operator. So you are checking if NOT(timer_running) then do whatever. So if the timer is already running, you do not save the current millis() because you're already counting time.

What it is counting? All I see are 1 and 0's?

It's counting milliseconds. That's why, when the light goes off, you take the current value of millis() and subtract the millis() value that was saved when the light first when on, and you get the duration in milliseconds. As noted, converting that to hours/minutes/seconds/milliseconds is trivial. Do you understand the code you wrote?

Hi Jose, the latest sketch you provided, works. It does however Serial.println the Total time over and over again, is there a way to only print this once? I plan later on to include a LCD or screen in another fashion but for now, a Serial.print is better than nothing. Regarding my understanding the code I wrote. The answer will be that, I have never learned this anywhere, but I experience and learn by doing / watching / asking. What I don't understand in this code is: Why do we need jump_count++ and not only jump_count+. I understand the rules of if, else, while, etc but it's all learn by doin

Let us continue this discussion in chat.


text:
ESP32 - JPEGDecoder from SPIFFS
Hello i've try to decode JPG image from FS so, i create and upload spiffs image (using /data directory and Arduino Ide Plugin )
On every jpg i've same error: "pjpeg_decode_init() failed with status 19"
here is my same code:
#include <TFT_eSPI.h> // Hardware-specific library
#include <SPI.h>
#include "GfxUi.h"

TFT_eSPI tft = TFT_eSPI(); // Invoke custom library

#define DEBUG
#define LOAD_SPIFFS

GfxUi ui = GfxUi(&tft);

void writeFile(fs::FS &fs, const char * path, const char * message);
void readFile(fs::FS &fs, const char * path);
void listDir(fs::FS &fs, const char * dirname, uint8_t levels);

void setup(void)
{
  Serial.begin(115200);
  Serial.print("Start");
  SPIFFS.begin(true);
  tft.begin();
  tft.setRotation(3);
  tft.fillScreen(TFT_BLACK);

  listDir(SPIFFS, "/", 0);
  fs::File jpeg = SPIFFS.open("/star.jpg", "r");
  //readFile(SPIFFS, "/star.jpg");
  boolean decoded = JpegDec.decodeFsFile(jpeg);
  Serial.println("===============");
  Serial.println("JPEG image info");
  Serial.println("===============");
  Serial.print  ("Width      :"); Serial.println(JpegDec.width);
  Serial.print  ("Height     :"); Serial.println(JpegDec.height);
  Serial.print  ("Components :"); Serial.println(JpegDec.comps);
  Serial.print  ("MCU / row  :"); Serial.println(JpegDec.MCUSPerRow);
  Serial.print  ("MCU / col  :"); Serial.println(JpegDec.MCUSPerCol);
  Serial.print  ("Scan type  :"); Serial.println(JpegDec.scanType);
  Serial.print  ("MCU width  :"); Serial.println(JpegDec.MCUWidth);
  Serial.print  ("MCU height :"); Serial.println(JpegDec.MCUHeight);
  Serial.println("===============");
  Serial.println("");
}

void listDir(fs::FS &fs, const char * dirname, uint8_t levels){
    Serial.printf("Listing directory: %s\r\n", dirname);

    File root = fs.open(dirname);
    if(!root){
        Serial.println("- failed to open directory");
        return;
    }
    if(!root.isDirectory()){
        Serial.println(" - not a directory");
        return;
    }

    File file = root.openNextFile();
    while(file){
        if(file.isDirectory()){
            Serial.print("  DIR : ");
            Serial.println(file.name());
            if(levels){
                listDir(fs, file.name(), levels -1);
            }
        } else {
            Serial.print("  FILE: ");
            Serial.print(file.name());
            Serial.print("\tSIZE: ");
            Serial.println(file.size());
        }
        file = root.openNextFile();
    }
}

void readFile(fs::FS &fs, const char * path){
    Serial.printf("Reading file: %s\r\n", path);

    File file = fs.open(path);
    if(!file || file.isDirectory()){
        Serial.println("- failed to open file for reading");
        return;
    }

    Serial.println("- read from file:");
    while(file.available()){
        Serial.write(file.read());
    }
}

void writeFile(fs::FS &fs, const char * path, const char * message){
    Serial.printf("Writing file: %s\r\n", path);

    File file = fs.open(path, FILE_WRITE);
    if(!file){
        Serial.println("- failed to open file for writing");
        return;
    }
    if(file.print(message)){
        Serial.println("- file written");
    } else {
        Serial.println("- frite failed");
    }
}

void loop() {

}

Output from serial:
Listing directory: /
  FILE: /logo.jpg       SIZE: 16346
  FILE: /arduino.jpg    SIZE: 8426
  FILE: /star.jpg       SIZE: 3853
pjpeg_decode_init() failed with status 19 <--- here is
===============
JPEG image info
===============
Width      :0
Height     :0
Components :0
MCU / row  :0
MCU / col  :0
Scan type  :0
MCU width  :0
MCU height :0
===============

19 is PJPG_NOT_JPEG https://github.com/Bodmer/JPEGDecoder/blob/master/src/picojpeg.h

you should add a test if (jpeg) for file existence.

as far as I can determine uploading to SPIFFS via the Arduino IDE is broken as of the beginning of 2018. The files are uploaded but are corrupted on a read. There are a few fixes reported.  I am using a core from Dec 2017 and that works fine.


text:
Can't add more code to loop() when use server.handleClient
Here's my code
void loop() {
  if (analogRead(A0) > 500)
  {
    statuss = true ;
  }
  if (statuss)
  {
    digitalWrite(D7, HIGH);
    if (millis() - lasttime > 500)
    {
      digitalWrite(D8, etat);
      digitalWrite(D6, etat);
      etat = !etat;
      lasttime = millis();
    }
  }
  server.handleClient();
}

When I use only server.handleClient everything works fine but when I add any type of code to the loop() function the server goes down and I can't see the ESP8266 access point.

what is any type of code ?  .... also,  you have not asked a question.

when i use only server.handleClient .... your code has other commands ... your statement does not make sense

that's the problem with close reason "Unclear what you are asking". for me it is totally clear about what this question is. and I am glad it is not closed yet

@Juraj, i am trying to understand .... if, for example, the OP adds a serial.print() statement to the loop(), then the server goes down ..... how is that clear to you? .... have you had similar experience?

@jsotola, read my answer

that is a specific command, not "any type of code" .... maybe the translation from OP's language is the blame, but it is still unclear what is being asked

@gre_gor, sempaiscuba, VE7JRO, MatsK, per123, you closed this question without evaluating/testing. the Question says: "if I run this code the esp8266 disappears from the WiFi network". and it is true. the question is "why?, what should I change?"

@jsotola, yes, asker didn't do the troubleshooting to reduce the code to minimum. he deserves the downvotes

Voting to re-open and +1 for your answer Juraj.

The problem is analogRead. The esp8266 uses the ADC to evaluate the strength of the WiFi signal. Hard use of analogRead disturbs it and the signal goes down. Use millis() to time analogRead.
unsigned int tempSensRead() {

  const unsigned long MEASURE_INTERVAL = 2L * 1000 * 60; // 2 minutes
  static unsigned long lastMeasureMillis;
  static unsigned int lastValue;

  if (millis() - lastMeasureMillis > MEASURE_INTERVAL) {
    lastMeasureMillis = millis();
    lastValue = analogRead(A0);
  }
  return lastValue;
}

@fakherhabib, some feedback please

Nice answer. Do you know any sources which confirm the statement "esp8266 uses the ADC to evaluate the strength of the WiFi signal"? I couldn't find this on the datasheet

https://arduino-esp8266.readthedocs.io/en/latest/reference.html#analog-input

Excellent resource, thanks.


text:
Arduino std::map returning random values
I'm working with an arduino UNO. I would like to be able to send it set and get commands over serial and have it update class data class members accordingly by key value pair. I spoke to users in the cpp room, and they suggested I try using map to map every key to value.
command structure
command:key:value
ex. set:key1:20
ex. get:key2
I created a class called Uno, assigned all my keys to private data members, and defined set and get functions. However, I am experiencing unintended behavior.
Unintended behavior
The set function ends up setting key1 and key2 to the same value, and the get function returns a random integer value that wasn't assigned.
  #include <ArduinoSTL.h>
  #include <string.h>
  #include <map>

class Uno{
  //private
    int key1;
    int key2;
    std::map<String, int Uno::*> keys;
  public:
  //Constructor
    Uno(){
      key1 = 0;
      key2 = 0;
      keys["key1"] = &Uno::key1;
      keys["key2"] = &Uno::key2;
    }
    bool setKey(String key, int value){
      if (keys.count(key)) {
          this->*keys[key] = value;
          return true;
      }
      return false;
    }
    int getKey(String key){
      if (keys.count(key)) {
          return this->*keys[key];
      }
    }
};

String inputString = "";      // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete
bool scan = false;            // whether a scan is in progress
Uno myMS;                      // global declaration of Mass Spec Class

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 250 bytes for the inputString:
  inputString.reserve(250);
}

void loop() {
  if (stringComplete) {
    t(inputString); // tokenize and process string

    //RESET STRING
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

void t(String inputString) {
    //get command
    String command = getValue(inputString, ':', 0);

    if(command == "set"){
      // get key, get value
       String key = getValue(inputString, ':', 1);
       int value = (getValue(inputString, ':', 2)).toInt();
       Serial.println(myMS.setKey(key,value));
    }
    else if(command == "get"){
       String key = getValue(inputString, ':', 1);
       int value = myMS.getKey(key);
       Serial.println(value);
    }
    else if(command == "stop"){
       scan = false;
    }
    else if(command == "scan"){
       scan = true;
       while(scan){
//        Serial.println(myMS.scan());
       }
    }
    else{
       Serial.println("not recognized");
    }
}

String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;

  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }
  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

EDIT: Here is a REPL IT working demo of concept provided by nwp.
https://repl.it/repls/AntiqueProductiveMineral
Sample output
set:key1:10 ===> 1 (GOOD)
get:key1 ===> 32512

why do you think that this is an Arduino question? ... it appears to be a C/C++ question

@jsotola It is an arduino question, because I am running the code on the arduino using the arduino String type.  I am also using Serial on the arduino. I'm open to other arduino methods for storing key value pairs.

the 32512 is the return value of getKey if it didn't found the key

Ok, but that is confusing because I am using the same method to set. I know the set function is working correctly, because if I do Serial.println(key1); from inside the class it prints the correct value.

You get random values because if the key is not found in getKey, then there is no return statement.
You attach the \n to the key in serialEvent(), then the key for getKey is "key1\n" and it is not found.
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    if (inChar == '\n') {
      stringComplete = true;
    } else {
      inputString += inChar;
    }
  }
}

If you have CR/LF set in Serial Monitor, then the \r character is send too and the parsed key is "key1\r\n".
There are obsolete things in your code, like the this->* or Uno::. Make the map std::map<String, int> keys;, because now you mix pointers and ints.

I have Newline only and it's not working anyways

change the serialEvent to not to attach the \n to the string

Right, he's not skipping it in that parser :D

Ok, I like your approach, it works!


text:
Using external battery for motor
i have a little project going on, where i want to connect vibration motors to an arduino. I found this, with example code but also found other tutorials wish use a capacitor for the motor. What is the advantage of using one ?
I am currently planning to power the arduino by a 9V battery, with 3 ultrasound sensors being connected to the 5v output of the arduino. Hence, i believe that i need an external battery for the 2 vibration motors. I think 2x AA's should do the job for some hours, right ?
I also have a question about the rating of the resistor to use at the base of the transistor. How do i calculate the rating that i need ?

a transistor is a current controlled current source. it means that you can control how much current is "Allowed" to flow from emitter to collector, by controlling the minor current flowing through the base of transistor. there is a specific ratio for this two currents for various transistors. (I recommend reading some transistor tutorials). let's say, your motor is drawing 250mA in full speed. you want to "allow" up to 300mA to be available to it.

base is connected to 5V through a 2.2 kOhm resistor. The base current is : (5/220) ~=  2.2mA
the hfe of your transistor is 150 (it depends on transistor model. It’s written in the datasheet available for every transistor on the market. it's the ratio of base current and emitter collector current mentioned above. You “must” read it first as it’s highly various between transistor models).
The current allowed to flow from emitter to collector is 2.2mA * 150 = 330mA which is sufficient for you motor.

note : many simplifications are made to make it easier to understand.

Resistor is there to limit Arduino current out. 220, 270, 330, any should be okay.
Be sure to connect battery - to Arduino Gnd.
Transistor will be used to connect motor '-' to Gnd? Be sure to put a diode across it - anode to motor '+', cathode to motor '-' to dissipate current surge generated by the motor when the transistor turns off.
2AAs will last a little while. Better than using 9V for them, that will drain a battery quick.


text:
Read sensor data repeatedly after specified time?
I want to read sensor data using analogRead() after every 5ms. I have read other answers to similar questions but what I'm confused about is:

let's say, I made a loop to read sensor data using analogRead() at the end of which I write delay(50)
it means it'll take some time to read data(adc) , then it'll wait for 50ms
time to execute loop isn't same for every iteration so we get the pattern as: some time for loop execution, delay of 50ms, some time for next iteration........and so on
I want to ask if I want arduino to read sensor data exactly every 5ms, what should I do?
Thanks

do not use delay() ..... see BlinkWithoutDelay  example sketch

You store the time (millis()) of the last measurement. Then wait till 5ms have past since the last measurement. Do your measurement, and update the time.
Something like:
unsigned long lastMeasurement = millis();

void loop()
{
  while( (millis()-lastMeasurement)<5 ){/* do nothing */}
  lastMeasurement = lastMeasurement + 5; //or use `lastMeasurement=millis();` depending on whether you want accuracy between measurement, or accuracy over time
  auto measurement = analogRead(A0);
}

It waited for 5ms, then last measurement=0+5=5 ms. Then it’ll do analogRead().  Let’s say analogRead() took 10ms, then mills()- last measurement() = 15-5 ms=10 ms so the loop will do another analogRead() although it’s not reading measurement exactly after 5 ms. So this will only work if loop execution time is <5ms

Indeed. It can't magically go back in time. Was there any question there?

You do something like this
unsigned long timerMesurement = 0;

void loop()
{
  if (millis() - timerMesurement > 5UL) {
    timerMesurement = millis();
    int measurement = analogRead(A0);
  }
}

Sigma, it should be >= for the right interval. It should also be timermeasurement += 5UL; for a interval that is fixed in time without increasing delays, the return value of millis() could have increased since the previous line.


text:
missing /dev/ttyACM* on Ubuntu
I installed the Arduino IDE according to the arduino.cc instructions (invoking install.sh) rather than sudo apt install .... The ports /dev/ttyACM* were present when the following Linux command is issued.
ls -l /dev/ttyACM*
This shows that the devices have membership in the dialout group. It is necessary to add myself as a user to the group dialout.
sudo usermod -a -G dialout <username>
I selected the board and the port and did a download which eventually completed but it seemed to take a long time. The program probably wasn't working since the program was to flash an LED at a 2 second period but the flash rate was definitely much faster so it seems the download did not work.
I deleted the IDE and reinstalled and the ports disappeared.
I have applied this fix for using the Arduino IDE on Linux.
From the description of the fix the instruction is to issue the following commands:
wget https://github.com/adafruit/Trinket_Arduino_Linux/raw/master/99-adafruit-boards.rules

sudo cp 99-adafruit-boards.rules /etc/udev/rules.d/

Next reboot Linux.
According to this page on Arduino for Linux there ought to be some devices at /dev/ttyACM* but mine are missing. What is the solution to this problem? I have replaced the USB cable and it makes no difference.
The board is Adafruit Feather 32u4 which has an ATmega32u4. The OS is Ubuntu 16.04.

what board? and more important what chip for USB?

@Juraj The ATmega32u4 has built-in USB.

try this docs https://learn.adafruit.com/adafruit-feather-32u4-adalogger/faq

@abu-ahmedal-khatiri you should post that as an answer. I don't know what fixed it but that link did suggest a double click might be necessary. I don't know the click rate on a double click for this board but eventually it worked.

i will help you but i don't have Feather board to try that docs, did you check your list ports with type ll /dev/tty*  what appears as ttyACM* or ttyUSB*

let i see what the output of dmesg | grep udev

did you try sudo systemctl restart ModemManager.service and check again with sudo lsof | grep ACM?

If the Arduino IDE does not show the port or does not allow you to select the port, load a known to be working program (such as Example > Blink), start a download, and then double-click the board's reset button.
For the same advice plus extraneous information view this help page on the particular Feather, the 32u4 micro-controller board, which seems to suggest the use of a verbose download mode but that seems to be unnecessary because you can just try again if it failed. The verbose download mode is enabled in preferences. Even though it is unnecessary I eventually decided to always use the verbose download mode because it gives what appears, to me at least, more immediate and obvious feedback about success and failure.

it same purpose that speeded up of @Majenko and Juraj.

According to this page on Arduino for Linux there ought to be some devices at /dev/ttyACM*

That is not the case. On a "traditional" Arduino board, like the Uno, you have two chips: the main MCU which you program, and a USB interface chip, which is pre-programmed with code to present a CDC/ACM interface to the computer (which it then creates a /dev/ttyACMx device for).
With the feather you don't have that. You have one single chip. That chip is both the USB interface and the chip that you program - and most importantly, it is your program that provides the CDC/ACM device if you choose. If your program doesn't provide a CDC/ACM device then the computer will never see one, so it will never create /dev/ttyACMx.
In general the Arduino core always adds a CDC/ACM device whether or not you ask for it, since it is often used to initiate a reset into the bootloader. However if your sketch stops working for whatever reason then the CDC/ACM port is no longer there.
The M0 on the feather has a neat trick though - if you reset the board with the reset button twice the startup code recognises that fact and forces it to run the bootloader. That bootloader then presents the needed CDC/ACM device to the computer allowing you to upload new code.
Of course, if your program that you upload then doesn't initialise its own CDC/ACM device, or crashes, the CDC/ACM device will not be presented until you do the double-reset trick again.

doesn't he have a Micro clone? I know the double click trick for M0, but does it work for Micro?

I read the comments. Looks to me like he's talking about the feather.

at Adafruit half of the products are feathers :-)

@Juraj Also the double click thing worked, according to the comments. So the double click thing is the answer. Which means it must logically be an M0 feather.

that is what I have a problem with. the Adafruit FAQ for the 32u4 feather recommends the double click. Do they have a different bootloader or Micro bootloader has the double click too? or is the FAQ copypasted from M0 FAQ and a simple reset worked for OP?

@Juraj Who knows what goes through the mind of an Adafruit designer...?  I mean, why create the feathers at all? ;)

Do you know if the Arduino Micro has the double click trick?

@Juraj No idea. I never use AVR chips if I can help it...

The example Blink program can accept a download even though it seems there is no code related to that. void setup() { pinMode(LED_BUILTIN, OUTPUT); } void loop() { digitalWrite(LED_BUILTIN, HIGH); delay(1000); digitalWrite(LED_BUILTIN, LOW); delay(1000); }

Hence the 4th paragraph of my answer...

/dev/ttyACM* mine are missing.

I think that something udev rules issue, you can define another rules with add Feather32u4.rules and remove 99-adafruit-boards.rules file before.
SUBSYSTEM=="usb", ATTRS{idProduct}=="0c9f", ATTRS{idVendor}=="1781", MODE="0660", GROUP="dialout"
ATTRS{idVendor}=="239a", ENV{ID_MM_DEVICE_IGNORE}="0"
ATTRS{idVendor}=="239a", MODE="0660", GROUP="dialout"
SUBSYSTEM=="tty", ATTRS{idProduct}=="8011", ATTRS{idVendor}=="239a", MODE="0660", GROUP="dialout"
SUBSYSTEM=="tty", ATTRS{idProduct}=="0011", ATTRS{idVendor}=="239a", MODE="0660", GROUP="dialout"

after saved and copy your files to /etc/udev/rules.d/
sudo cp Feather32u4.rules /etc/udev/rules.d/

and then restart your udev
sudo reload udev

or,
sudo udevadm control --reload-rules
sudo udevadm trigger

don't forget to restart your service
sudo systemctl restart ModemManager.service

check again your port with following ll /dev/tty*, if it appear with named /dev/ttyUSBx or /dev/ttyACMx add a user to your group
sudo usermod -a -G plugdev <user>

also try to automatically reset button with add a delay into your sketch
while(!Serial){
  delay(1000);
}
Serial.begin(115200);

if it not showed port on /dev/tty list, try

Enabled verbose upload in the Arduino Preferences.
Open the Blink example.
and add automatically reset above.

that will showed as the Bootloader COM/Serial Port with bootloading mode.
If didn't work, i advice install driver on Adafruit_Driver Windows only using Wine or PlayOnLinux, and remove udev files. also check again your /dev/tty* list.
Hope this helps.

So I tried EVERYTHING... turns out my USB cable was a cheaper cable that didn't have the data pins in it. It is worth making sure your cable supports data transfer by plugging it into something else to make sure it w

ttyACM* didn't show up on my /dev/ also, but as soon as I changed the USB port I was working with, the arduino board started blinking differently. So I checked the IDE again and under Tools > port > Serial Port I saw ttyACM0 came up. Didn't make sense to me but it worked.

For my situation, where I'm using a custom Linux kernel, I was missing the cdc_acm driver.
This excellent page on the Gentoo Wiki helped me find it:
https://wiki.gentoo.org/wiki/Arduino


text:
Connecting to Alexa with FAUXMOESP library not detecting the device
I am using NodeMCU (ESP8266 12E) module from some days. I am trying to connect to Alexa for voice controlling. I have Amazon Alexa Echo 2 from which I am trying to discover my nodemcu as a smart home device.
Here is my sketch I am trying to use to detect.

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <fauxmoESP.h>

fauxmoESP fauxmo;

const char* ssid = "myssid";
const char* password = "mypassword";

void setup() {
  Serial.begin(115200);
  wifisetup();

  fauxmo.enable(true);

  fauxmo.addDevice("light one");
  fauxmo.addDevice("light two");

// this is not able to detect .onSetState function I am not sure about the reason.

//  fauxmo.onSetState([](unsigned char device_id, const char * device_name, bool state, unsigned char value) {
//        Serial.printf("[MAIN] Device #%d (%s) state: %s value: %d\n", device_id, device_name, state ? "ON" : "OFF", value);
//    });
}

void loop() {
    fauxmo.handle();

}

void wifisetup() {
  pinMode(2, OUTPUT);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  IPAddress ip(192, 168, 1, 243); // this 3 lines for a fix IP-address
  IPAddress gateway(192, 168, 1, 1);
  IPAddress subnet(255, 255, 255, 0);
  IPAddress dns(192, 168, 1, 1);
  WiFi.config(ip, dns, gateway, subnet);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(10000);
    digitalWrite(2, HIGH);
    ESP.restart();
  }
  if (WiFi.status() == WL_CONNECTED) {
    digitalWrite(2, LOW);
    Serial.println("");
    Serial.println("Your ESP is connected!");
    Serial.println("Your IP address is: ");
    Serial.println(WiFi.localIP());

    delay(100);
  }

}

I am using https://bitbucket.org/xoseperez/fauxmoesp library to do the setup. Alexa is not able to detect my device. Not sure whats the issue with this, but in the Serial Monitor I can see the logs which is showing that I am getting ping from Alexa to my ESP8266.
Taking an output pin is compulsory? I have tried that too although but no output found.
Thank you!

If you are using fauxmoESP library version 3.0 and above your device will not be detected by alexa, i dont know why this is.
You may degrade fauxmoESp version to 2.4.0 so that your issue ie. .onSetState will be resolved.
Are you able to connect wifi?

Yes it worked before itself. And yes i was able to connect through Wifi.

2.4.0 is not available anymore.. any idea which one works now?


text:
SPI.transfer(buffer, size) does not send data from buffer
I am having trouble getting SPI.transfer(buffer, size) to work as expected.
Here is the code:
// inslude the SPI library:
#include <SPI.h>

// set pin 10 as the slave select for the digital pot:
const int slaveSelectPin = 10;

uint16_t SPI_message = 0xABCD;

void setup() {
  // set the slaveSelectPin as an output:
  pinMode(slaveSelectPin, OUTPUT);
  // initialize SPI:
  SPI.begin();

}

void loop() {

  SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));
  SPI.transfer(0xEF);
  SPI.transfer(&SPI_message, 2);
  SPI.endTransaction();

  delayMicroseconds(300);

}

Here is the output of logic analyzer:

As can be seen the call for SPI.Transfer(0xEF) works as expected. However SPI.transfer(&SPI_message,2) sends 0x0000 instead of 0xABCD on the bus.
What am I doing wrong?

SPI.transfer(&SPI_message,2) is destructive. The buffer is updated with the received values.

I assume this is Arduino? Can you decrease SPI clock - currently you seem to be at the limit of your logic analyser. Does it work if you split the second transfer into two 1B transfers?  --- What Mikael said is probably the reason for your issue.

@MikaelPatel But still I should be able to see 0xABCD on my MOSI line on the SPI bus? I am not trying here to read data from a variable, but I am observing signals on the line of the SPI.

Only the first time loop is executed, then SPI_message is overwritten and zeroes are sent. Try reinitialising it to 0xabcd in loop.

@domen Exactly! this is what I was overseeing! Now it works.

@MikaelPatel your comment answers my question, together with explanation from domen. If you convert it into an answer, I can accept it. Thank you both for your help!

SPI.transfer(&SPI_message,2) is unfortunately destructive. The buffer is updated with the received values. There is a SPI member function[1] that can be used for 16-bit data; SPI.transfer16(SPI_message).
To correct your sketch either initialize the buffer before each call (as recommended by @domen) or use the 16-bit transfer function.
There are other SPI APIs that included non-destructive transfer function e.g. read/write. Please see [2].
Cheers!
Ref.

https://www.arduino.cc/en/Reference/SPITransfer
https://github.com/mikaelpatel/Arduino-SPI/blob/master/src/SPI.h#L137


text:
Serial communication mac to Digispark ATtiny85
I want to use the Arduino IDE serial monitor with my Digispark ATtiny85 over USB.
I can without problems upload this code(Digispark CDC example):
#include <DigiCDC.h>
void setup() {
  SerialUSB.begin();
}
void loop() {
  SerialUSB.println(F("TEST!"));
 //SerialUSB.delay(10);
}

In a terminal, I can confirm, that it indeed creates a new devise:
ll /dev/*usb*
crw-rw-rw-  1 root  wheel   21,  89 27 Sep 10:36 /dev/cu.usbmodem1411
crw-rw-rw-  1 root  wheel   21,  88 27 Sep 10:36 /dev/tty.usbmodem1411

When trying to start the Arduino serial monitor, I get the error:
 Error opening serial port '/dev/cu.usbmodem1411'. (Port busy)

I have confirmed that there are no open files or processes using the USB port. I have the same problem trying to use cu or screen in the terminal.
I have googled the problem, and found that several people has the same problem on new mac computers, but I have not been able to find a solution. -any ideas?

Digispark Rev3 (Chinese clone - with bootloader firmware 1.6 (1.06))
Arduino IDE 1.8.7
Mac OSX High Sierra 10.13.6

I don't know about OS X, but I do know that the ATTiny85 doesn't have a USB interface - so it's all done in software. TBH you're lucky it gets as far as it does. I have never been a fan of bit-banged USB like that. It's nasty.

@Majenko I can use the Digispark as a USB HID keyboard, so the banging of the bits do work :o)

You can only bit-bang low-speed USB. Low-speed is only intended for use with keyboard and mouse. CDC/ACM really requires full- or high-speed, so trying to use it over low-speed is "undefined".

@Majenko: I appreciate the support. I would be happy with any low speed way of sending a string from my computer to the Digispark. If it is not possible, do you know of a chip, that I can add to the ATtiny85 to give it hardware USB?

Unfortunately, it's a known issue on mac os that has no solution at the moment. digiUSB is mentioned on one forum as a workaround. However, sending and receiving is done via python scripts with this method of communication. If you want hardware USB in the same board format, you can try ATMega32U4-based "beetle" boards available for ~5 USD on ebay.

Don't use DigiUSB! It's deprecated using old usblib0 (new is libusb-1.0) and the highly dysfunctional libusb-win32. Also if you use that, you have to be careful not to overwrite the internal V-USB, perhaps by disabling your own after some time. Apparently DigiCDC is the followup of that.

@not2qubit: I do not understand. What is DigiUSB? How am I using it? Actually I do not understand what you are writing at all. What am I doing wrong, and what can I do instead?

From DigiUSB: This library has been deprecated in favour of: DigiCDC. With DigiCDC the Digispark will show up as a COM port and the Arduino Serial monitor can be used normally. DigiUSB requires communication to the Digispark through a seperate application.

@not2qubit: Ok - I have now come to the conclusion, that you have not read my question at all, and you have no idea about the problem on a mac.

Oh, sorry, I was merely responding to the comments above. Do you have lsof on the mac? If so try lsof |grep "/dev/cu.usbmodem1411". It should in theory show you what process is using that device. You can also try various options to ps.

SoftSerial and a real serial port on the mac will work. Or if you are careful use the DigiKeyboard and print the debug to the HID keyboard REMEMBERING to switch to a notepad equivalent window on the mac to receive and display the debugging text and not have it overwriting the arduino sketch by mistake.
DigiCDC is a kludge that does not work properly on modern operating systems sorry!

Thanks for your input, but I do not understand what you mean by " ...a real serial port on the mac ..."? Do you mean something like this https://plugable.com/2011/07/12/installing-a-usb-serial-adapter-on-mac-os-x/ ?What debug are you referring to? HID works perfectly, but I want serial communication from and to the Digispark.

presumably no modern Mac has a builtin RS232 interface so you'd need a USB to RS232 interface yes like in that article you link to. There are a few common chips that are used in the devices PL2303, CH340/CH341, FT232RL and so on. There is a software serial emulation library that works on the Attiny85 digispark boards and uses 1 or 2 or the IO pins obviously there are certain limitations with software emulation but it does work adequately. Serial is often used to output debugging messages with arduinos when developing sketches.


text:
HTTP post via GPRS (SIM808) to Azure http endpoint logic app is failing
I am using a SIM808 with a atmega2560.
I have setup the endpoint in Azure and that works when I try a http post via postman and/or an online http post tool (I get a 202 as result and see data comming into Azure)
I want to send a json package to an Azure http endpoint (smart app) using the function httpPOST in the SIMCom library from itead.
I am connecting to the network:
logging (I printed all that is written to GSM):
AT+CIFSR
DB:STARTING NEW CONNECTION
AT+CIPSHUT
DB:SHUTTED OK
AT+CSTT="provider.net","","" DB:APN OK
AT+CIICR
DB:CONNECTION OK
AT+CIFSR
DB:ASSIGNED AN IP
GPRS status=ATTACHED
AT+CIPSTART="TCP","prod-13.westeurope.logic.azure.com",443
DB:RECVD CMD
DB:OK TCP

Then call the httpPost function from the library with the following variables:
const char server[35] = "prod-13.westeurope.logic.azure.com";
const int port = 443;
const char path[200] = "/workflows/someazureID/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=someazuretoken";
const char parameters[100] = "{\"device\":\"alive\",\"timestamp\":\"09270845\"}";

Part of the httpPost function from the library for sending the data
    int InetGSM::httpPOST(const char* server, int port, const char* path, const char* parameters, char* result, int resultlength)
         ....
    gsm.SimpleWrite("POST ");
    gsm.SimpleWrite(path);
    gsm.SimpleWrite(" HTTP/1.1\r\nHost: ");
    gsm.SimpleWrite(server);
    gsm.SimpleWrite("\r\n");
    gsm.SimpleWrite("User-Agent: Arduino\r\n");
    gsm.SimpleWrite("Content-Type: application/json\r\n");
    gsm.SimpleWrite("Content-Length: ");
    itoa(strlen(parameters),itoaBuffer,10);
    gsm.SimpleWrite(itoaBuffer);
    gsm.SimpleWrite("\r\n\r\n");
    gsm.SimpleWrite(parameters);
    gsm.SimpleWrite("\r\n\r\n");
    gsm.SimpleWrite(end_c);
....

Which gives this output on the serial monitor (I printed all that is written to GSM):
AT+CIPSEND
DB:>
POST /workflows/someazureID/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=someazuretoken HTTP/1.1
Host: prod-13.westeurope.logic.azure.com
User-Agent: Arduino
Content-Type: application/json
Content-Length: 55

{"device":"alive","timestamp":"09270845"}

DB:SENT

And then it is waiting for a response:
Starting read..
Waiting for Data............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
CLOSED

Done..
response:
10

CLOSED

which times out I guess.
And I see nothing coming into Azure.
(I am getting data when I try a httpGet on a random site. So hardware, sim and network is working ok I guess)
Any ideas?
thx!

doesn't Azure use https?

yes it does, I am connecting to port 443 'const char server[35] = "prod-13.westeurope.logic.azure.com";
const int port = 443;'  But honestly I have never done this before so maybe I am forgetting/missing something

I don't know the AT commands for the GSM module, but it doesn't look like you would handle SSL

Juraj's comments put me on the right track, for SSL you need to do more then just select the port.
I did some searching and got it to work using a different GSM library that also supports SSL:
tinyGSM
in combination with ArduinoHttpClient
Jeroen
EDIT: It works, but there is a big downside. It looks like there is major overhead, each message seems to uses 13Kb of data...? I suspect this comes from the data that is returned by the endpoint.
This is way too much over GPRS so now looking into MQTT.


text:
Reprogram Atmega 16u2 on Arduino Mega with Arduino IDE?
I had an Arduino mega 2560, suddenly Arduino didn't recognize my computer and I thought the problem is about Atmega 16u2 and I decided to copy hex file from another Arduino Atmega 16u2 and paste to damaged Arduino but it didn't work.
in fact, in our laboratory, we don't have any Linux and other software to reset or reprogram Atmega 16u2 on the other hand I know several methods to solve the problem but I need to know can I use the Arduino IDE to reset Atmega 16u2 without other software.
thanks a lot.

Another option is to use FDU to upload the 16u2

@Gerben, isn't that page outdated?

Yes, you can recover the firmware in 16u2 only with Arduino IDE installed. In subfolder hardware/arduino/avr/firmwares/atmegaxxu2/ of the IDE installation folder is the hex file of the firmware Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex. The README.txt file in that folder has sample command line to upload the firmware with avrdude.


text:
How to deal with this array correctly?
I am using a led strip WS2812b, an ESP8266 (NodeMCU 1.0) and a gesture sensor APDS9960.
I want that when I move my hand from left to right and from right to left I change the colors of the strip of leds, previously saved in an array of strings:
const char * colors [11] = {"CRGB :: White",
"CRGB :: WhiteSmoke",
"CRGB :: CadetBlue",
"CRGB :: SteelBlue",
"CRGB :: Teal",
"CRGB :: SlateGray" ,
"CRGB :: MediumPurple",
"CRGB :: Purple",
"CRGB :: PapayaWhip",
"CRGB :: LightPink",
"CRGB :: Crimson"};

But when I'm going to turn on the colors using the functions of the FastLed library in this way:
for (int i = 0; i <NUM_LEDS; i = i + 1) {
       leds [i] = colors [2];
       FastLED.show ();
       delay (10);}

All I get is this error:

invalid conversion from 'const char *' to 'uint32_t {aka unsigned
  int}' [-fpermissive]

I guess the problem is me when declaring the array, could someone help me?

You don't want an array of strings containing the (badly formatted) names of variables. Instead you want an array of 32-bit integers containing the values held within those variables.
const uint32_t colors[] = {
    CRGB::White,
    CRGB::WhiteSmoke,
    CRGB::CadetBlue,
    CRGB::SteelBlue,
    CRGB::Teal,
    CRGB::SlateGray,
    CRGB::MediumPurple,
    CRGB::Purple,
    CRGB::PapayaWhip,
    CRGB::LightPink,
    CRGB::Crimson
};

Since colours are just numbers, in the (hexadecimal) form of 0xRRGGBB you just store them as 32-bit unsigned integers.  The names you have there are just such (constant) variables used for easy reference (CRGB::White is 0xFFFFFF).

Thanks!!! Your recomendation did the work correctly!!!
Thanks again!!!


text:
Trying to instantiate a DS3231 real-time clock within a library
I'm trying to write a library encapsulating things that I do with a DS3231 real time clock. I have managed to compile a sketch using the library, but it apparently blows up when attempting to call clock methods such as getTime().
Header:
// JBP_DS3231.h
#ifndef __JBP_DS3231_h__
#define __JBP_DS3231_h__

#include <SD.h>
#include "DS3231.h"
#include "Arduino.h"

class JBP_DS3231
{
  public:
    JBP_DS3231();
    String TimeStamp();
  private:
    DS3231* _realTimeClock;
};

#endif

cpp:
#include <JBP_DS3231.h>
#include <SD.h>
#include "DS3231.h"
#include "Arduino.h"

JBP_DS3231::JBP_DS3231() {
  String thisTime = "";

  _realTimeClock = &DS3231(SDA, SCL);

  Serial.println("About to try to get time from RTC."); // Last line we hear from.

  thisTime = _realTimeClock->getTimeStr();
  Serial.print("Time in constructor is: ");
  Serial.println(thisTime);
}

String JBP_DS3231::TimeStamp() {
  String timeStamp = "";

  Serial.println("In TimeStamp().");
  timeStamp = _realTimeClock->getDateStr(FORMAT_LONG, FORMAT_MIDDLEENDIAN, '/');
  Serial.print("Value of timestamp is: ");
  Serial.println(timeStamp);
  timeStamp.concat(" ");
  timeStamp.concat(_realTimeClock->getTimeStr());
  Serial.println(timeStamp);

  return timeStamp;
}

Script:
const String WHO_AM_I = "JBP_DS3231_library_test.ino";
const    int VERSION = 0;

#include <JBP_DS3231.h>

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

  JBP_DS3231 johnsRTC;
  Serial.println(johnsRTC.TimeStamp());
}

void loop() {
  return;
}

void AnnounceAwakening() {
  Serial.print("Sketch ");
  Serial.print(WHO_AM_I);
  Serial.print(" version ");
  Serial.print(VERSION);
  Serial.println(".");
  Serial.println("");
}

Define "blows up"...?

If all you want to do is to enhance what the existing DS3231 library can do I suggest you just extend the class (create your own class which inherits the existing class) and add your own functions to it.

Also, you will have to provide a link to the DS3231 library you are using. I found at least 3, and none of them appear to be the one you are using (judging by the constructors).

Library: http://www.rinkydinkelectronics.com/library.php?id=73

"blows up" means that no subsequent statements are executed after the first call to _realTimeClock->getDateStr().

You appear to be providing a pointer to a constructor, not to an object.  Either create a new object with new, or instantiate the object separately and provide the pointer to the object:
_realTimeClock = new DS3231(SDA, SCL);

Better still, extend the existing class and implement your own methods:
clsss JBP_DS3231 : public DS3231 {
    public:
        JBP_DS3231(uint8_t d, uint8_t c) : DS3231(d, c) {
            String thisTime = "";
            Serial.println("About to try to get time from RTC."); // Last line we hear from.

            thisTime = getTimeStr();
            Serial.print("Time in constructor is: ");
            Serial.println(thisTime);
        }

        String TimeStamp() {
            String timeStamp = "";

            Serial.println("In TimeStamp().");
            timeStamp = getDateStr(FORMAT_LONG, FORMAT_MIDDLEENDIAN, '/');
            Serial.print("Value of timestamp is: ");
            Serial.println(timeStamp);
            timeStamp.concat(" ");
            timeStamp.concat(getTimeStr());
            Serial.println(timeStamp);

            return timeStamp;
        }
};

void setup() {
    Serial.begin(115200);
    JBP_DS3231 myRTC(SDA, SCL);
    Serial.println(johnsRTC.TimeStamp());
}

void loop() {
}

(Note: untested)

For what I'm doing, extending the source class seems to be logical. I will attempt and report back, thank you.

Majenko, the example you gave is not in the form of a library. I attempted a few variations on; this gives me error: expected primary-expression before ',' token.
JBP_DS3231.h
class JBP_DS3231 : public DS3231 {
  public:
    JBP_DS3231(uint8_t, uint8_t) : DS3231(uint8_t, uint8_t);

JBP_DS3231.cpp
JBP_DS3231::JBP_DS3231(uint8_t _SDA, uint8_t _SCL) : DS3231(_SDA, _SCL) {


text:
16 bit SPI on Arduino Due
I'm trying to control AD7091-8 using Arduino Due.
This IC calls for 16 bit SPI R/W. I'd read that I can change the transmit and receive bits of Arduino DUE by changing a register (bits 4-7 of SPI_CSR).
I was able to change the SPI of Due from 8 to 16 bits. Confirmed this by looking at SCLK and MOSI in the scope. However, the data I want to transfer is becoming intermittent.
I want to send 0x1000. On 8 bits, using the line
SPI.transfer(10,0x10,SPI_LAST);

I really can see this being sent on MOSI.
However, when I'm on 16 bits, the line
SPI.transfer(10,0x1000,SPI_LAST);

It's either becoming 0x0000 or 0x0008. I'm losing the bit or it's becoming LSB_FIRST. Not MSB_FIRST.
Below is the actual code.
#include <SPI.h>
#include "C:\Users\Smart Surface 2\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\component\component_spi.h"
#include "C:\Users\Smart Surface 2\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\instance\instance_spi0.h"

#define CS 10

void setup() {

  pinMode(CONV,OUTPUT);

  Serial.begin(9600);
  SPI.begin(CS);
  SPI.setDataMode(CS, SPI_MODE0);
  SPI.setClockDivider(CS,21);

  REG_SPI0_WPMR=0x53504900;
  REG_SPI0_CR=0x1;
  SPI0->SPI_CSR[0]=0x00001580;

  SPI.setBitOrder(MSBFIRST);
  delay(1);
}

void loop() {

  SPI.transfer(CS,0x1000,SPI_LAST);

  int a = SPI.transfer(CS,0x0000, SPI_LAST);
  delay(1000);

  Serial.println(a);
}

How can I make my data reliable and the order still with MSB first?

Found the problem on the SPI library.
When I do the command SPI.transfer, the data is stored on a byte type variable. And I'm passing a 16 bit data on it.
I've changed line 84 of SPI.h to
uint16_t transfer(byte _pin, uint16_t _data, SPITransferMode _mode = SPI_LAST);

so it will return and receive 16 bit data.
Also have to change the corresponding function on SPI.cpp (line 174)
uint16_t SPIClass::transfer(byte _pin, uint16_t _data, SPITransferMode _mode)

so they will match.
I've copied and renamed the SPI library that I've changed so it won't affect other codes.


text:
Preventing EMI on PCB
i've made a project consisting of 3 DC motor pumps, Atmega328p on custom PCB, and a relay. I found a problem which causes my PCB custom arduino trips over and over again caused by 12V DC MOTOR. I fix it already by putting a flyback diode on motor. it runs much better but still have a small number of trips on my arduino.

probably i've a bad PCB design and lack of components.
is there a way to prevent these electromagnetic interference caused by motor?
or some improvements on my PCB board?

Step one would be to add the missing decoupling capacitors to the MCU. Step two would be to use a proper ground pour instead of wimpy traces.

is there other way to put  the decoupling capacitors without making and design the new pcb? using this current PCB that i already make?

Use 0805 SMD capacitors and solder them between the MCU pins on the underside of the board.

Place the through-hole capacitors flat on the underside of the board. Bend the leads so they touch the solder joints of the IC(-holder). The solder them, and clip any excess lead.

Had a problem like this. I ended up using a separate power supply for my DC motor. Don't forget to connect the GND's.

do you mean to connect GND motor and arduino in the same GND? because mine was using 12V DC pump while the arduino had their own power supply.

Yes, connect a GND between both

There are few things you can try. First thing that comes to mind is hooking up the power source to an oscilloscope and see if there is not a big voltage dip when motor starts running/runs. This could happen if the motor attempts to draw more current than the power source can deliver, hence the voltage of source would drastically drop and Arduino would restart.
Second thing, assuming this is EMI, which I doubt - You need a proper ground plane, not just a thin trace. That would definitely help. Third thing would be reducing loop areas, by which I mean putting power and GND lines close to each other, look at http://www.ti.com/lit/an/szza009/szza009.pdf. This is a very resourceful document.
Third thing is - put a decoupling capacitor as close to the Arduino as possible. This will even out any spikes you may get, or any unexpected instability.
Hope this helps

The most critical failing of your PCB is the fact that you have no decoupling capacitors near your MCU power pins. These are absolutely required, and are not optional.
To modify your existing PCB, so you don't have to roll a new one, just solder a 0.1µF 0805 SMD capacitor between each VCC and GND pair of pins on the underside of the board.
You should also reduce both the ground impedance and the power supply impedance by replacing your ground traces with a ground pour, and fatten your power traces up a little.

i don't have SMD components over here. any alternative? a ceramic or something?

You could solder a small leaded ceramic in the same way - just be careful of shorts. Insulate the leads if you can.

can i use ceramic 22uF? as this only on my inventory for now.

Ceramic 22uF? I think you have the wrong value there. If they're the ones that you use for the crystal then you probably mean pF not uF. And no. They're too small a value. You need around 100nF (0.1uF, 100000pF). They are the single most common value of ceramic capacitor in use in digital circuits. Get some. You will need them.


text:
Servo going up to the limit as soon as attached
I have a Futaba S148 servo (https://servodatabase.com/servo/futaba/s148)
connected to an Arduino Uno.
As soon as the script attaches the servo, it rotates to its limit and gets stuck.
I've tried several scripts, and narrowed to the simplest:
#include <Servo.h>  // servo library
Servo servo1;  // servo control object
void setup()
{
  //  Attach the servo1 object to digital pin 4.
  servo1.attach(10);
}
void loop()
{
}

Also connected the servo to the board with this:
#include <Servo.h>  // servo library
Servo servo1;  // servo control object
void setup()
{
  //  Attach the servo1 object to digital pin 4.
  //servo1.attach(10); <--- notice this commented out
}
void loop()
{
}

and then the servo remains still.
I'm using a battery pack of 4.8 V which works fine with the servo and the RC radio, so the battery and the servo, works fine together with remote control.
I have another different SG90 servo running with its own power source and connected to the pin 9, and with a different sketch, it works perfectly.

https://www.arduino.cc/en/Reference/ServoAttach - This should answer it. The library you are using supports only 2 specific pins

oh, good thinking..but it is now in pin 11, because I tried so many things that didn't work out...I've tried with 9 and 10 also with the same result. I'll try again just in case and update the question if nothing changes.

tested, same result, once attached the servo rotates until the limit.

Have you tried the default examples? If you go to File -> examples ->servo, there are 2 scripts, sweep and knob. Try them. Also, use external power source for servo, do not power it from Arduino 5V

I've tried the Sweep one, as it is simpler, and keep the servo unplugged from power until the program is uploaded. Then I connect the battery and the servo runs out the limit :(

Well...I think is a cable problem...it seems that the long cable I connected between the servo and the arduino board is too long (1.5m) and mess with the signal, does it make any sense?


text:
Differing Serial Values Between Arduino Uno and TTGO ESP32 SX1276
I'm wanting to analogRead the value off a MQ-135 gas sensor. I have tired this with both an Arduino Uno and an TTGO ESP32 SX1276.
When reading the value of the sensor off the Uno, I get values approximately equal to 400 which is expected, as shown in this video. When doing the same on the TTGO, I get values close to 2000. For some reason, this person gets a similar value range as shown in this video.
What I don't understand is how these values are different when only the board is being changed. Do different boards analogRead differently?
More or less, how do I get the TTGO to read the same values as the Uno?
Below is my code for both boards. Nothing is changed between the boards:
#define sensor 2 //sensor pin

int gasLevel = 0; //int variable for gas level

void setup() {
  Serial.begin(9600); //start serial comms
  pinMode(sensor,INPUT); //set sensor for input
}

void loop() {
  gasLevel = analogRead(sensor);
  Serial.println(gasLevel);
  delay(1000);
}

The following things I have tested:

Multiple boards of both the Arduino Uno and TTGO
Different pins, both analog and digital

I also am powering the sensor using 3.3V pin, so there is no variation in the voltage the sensor is receiving.

Do different boards analogRead differently?

Yes.
Your typical Arduino has a 10-bit ADC. That can give values between 0 and 1023 (210-1), with 400 falling just short of half way.
The ESP32 has a 12-bit ADC. That gives values between 0 and 4095 (212-1), which means that your 2000 falls, yes, just short of half way.
It is not the value from the ADC that is important - it is what the value represents. It is meaningless until you convert it into something meaningful, like a voltage.
Like asking "How heavy is it?" -- "It's 23." Completely meaningless, until you qualify it with units, and the units are different because of the different resolutions, so you need to "convert" it into units that have a meaning.
Typically the value represents a proportion of the supply voltage (but not necessarily: it's actually a proportion of the ADC reference voltage, which is often the same thing as the supply voltage).  On the Arduino the value is 1/1024th of the supply voltage. On the ESP32 it's 1/4096th.

That makes complete sense. Thanks for the clarification.


text:
Formula creation
I was creating a scoring formula for a game.
The formula in question is
millis() * 1.1 ^ (millis()/10000);

However, I'm having trouble understanding the different error messages that the Arduino IDE is projecting to me

invalid operands of type to binary operator

I have declared the score as an unsigned long.

^ is the binary exclusive-or operation. You are probably trying to raise it to the power of. Use pow(base, exponent) instead.

Creating two declarations, score = millis() * 1.1 and divisor = millis()/10000 and then creating a new unsigned long machinescore = pow(score, divisor) outputs consistent 1's. does it have anything to do with it being integer math? as such it wont display anything until something is greater than another?

add a .0 for the divisor: 'millis()/10000.0'. Hopefully you've also declared both score and divisor as floating point numbers. Also the result will be a floating point number. This is basic C programming language stuff. You can try it on your local machine instead of uploading it to the board every time you try to figure out something.

Thank you so much, ive been working on other projects hence the arduino IDE. cant wrap my head around basic principals at the moment.

I would avoid calling millis() twice within the same expression. Not
really a big deal in your case, but the two calls can very well return
different values, which would make your formula slightly inconsistent.
Then, using the proper syntax for the power function, as explained by
Kwasmich:
uint32_t t = millis();
float score = t * pow(1.1, t/1e4);

Note that 1e4 is the scientific notation for 10000.0. I personally
find the former more readable, as you don't have to count the zeros.
Now, it is worth noting that the pow() function is very expensive to
compute on this kind of 8-bit FPU-less processor. It involves both a
logarithm and an exponential. The second line is essentially equivalent
to
float score = t * exp(t/1e4 * log(1.1));

The floating point division is also quite expensive. You could save
something like half the processing cycles by pre-computing
log(1.1)/1e4 and using the result in your expression:
float score = t * exp(t * 9.53e-6);

Thanks for that, i added it in and it works as the graph shows.
I do have another question if you could help. I'm preparing the score to send via UART so i need to convert the score in 4 8bit packets, my way of thinking is using modulus 256 and storing the frames in a respective variable to send, but i can only think of how to do it once, leaving me with 24 more bits to shift and send.
cheers for any help.

@ReidPilkington: To send numeric data through the serial port, use Serial.println(score). This will format the number in ASCII. If that can't work for you, open another question, explain why ASCII won't do it, and provide a complete specification of the binary format you want (IEEE 754 v.s. integer, endianness...).


text:
Apply patch to library for custom changes in Arduino IDE
I wish to obtain unix epoch timestamps in millisecond precision. I am using an ESP32 along with DS3231 RTC breakout board from adafruit.
Apparently the Repository is not maintained often but I see a PR which overcomes the rollover for software timer and the developer provided a patch in the comment to use the unix timestamps in ms.
I went to the libraries folder where all the downloaded adafruit repos exist. But when I did  git status it mentions that the library download (from the library manager) is not a git repository.
I wan't to inculcate the changes to the RTClib library by using the patch provided. Should I just change the code directly via the Arduino IDE editor?

Save the patch to a file, put it in the directory holding the library,
open a terminal on that directory and type:
patch -p1 < patchfile

You may have to install the "patch" utility if you don't have it yet. On
a Debian-like OS (I don't know for other OSes):
sudo apt install patch

Well I blundered and cloned a fork from your repo and added the patch to it. Added this updated repo to the IDE. I think I will revert back to your method.


text:
Is there a module that will allow me to pair a bluetooth keyboard to an arduino?
I want to pair a bluetooth keyboard to an arduino project, so that pressing a key on the keyboard causes an action to happen on the Arduino. Let's say that pressing Q on the keyboard makes an LED turn on, and pressing W makes it turn off.
I know that I need some sort of bluetooth module connected to the Arduino, and I need to pair the keyboard to the module. I also know that it must be a module that can act in Master mode and use the HID protocol. But I cannot find a module that does what I want. For example, the HC05 module cannot do HID.
Has anyone done this? Can you tell me which module you used please? I don't want to involve anything else, just an Arduino, a module, and a bluetooth keyboard.

I googled "arduino bluetooth hid host" https://www.circuitsathome.com/mcu/arduino/bluetooth-hid-devices-now-supported-by-the-usb-host-library/

I also looking for a module that could act as a master and support HID!


text:
Arduino - My problem is when the condition is greater than 900.00 it will continue the loop and do the code below once
I want is to stop the loop and when it read  Greater than 900.00 again it will do task again.
I need condition. When it back to greater than 900.00 the code below will do task and then it will stop. And when it will reach the condition again it will do the code again and it will stop .. Please help me
void loop(){
  float reading = analogRead(LIGHTSENSORPIN); //Read light level
  float square_ratio = reading / 1023.0;      //Get percent of maximum value (1023)
  square_ratio = pow(square_ratio, 2.0);      //Square to make response more obvious

  analogWrite(LEDPIN, 255.0 * square_ratio);  //Adjust LED brightness relatively
  analogWrite(LED_BUILTIN, 255.0 * square_ratio);  //Adjust LED brightness relatively
  Serial.println(reading);                    //Display reading in serial monitor

if(reading >= 900.00){

  digitalWrite(smDirectionPin, LOW); //Writes the direction to the EasyDriver DIR pin. (LOW is counter clockwise).
    /*Turns the motor fast 1600 steps*/
      for (int i = 0; i < 400; i++){
    digitalWrite(smStepPin, HIGH);
    delayMicroseconds(700);
    digitalWrite(smStepPin, LOW);
    delayMicroseconds(700);
}
}

  delay(1000);

}

You need to also store the old reading. Then change the if to if(oldReading<900.00 and reading>=900.00)

how can i store the old reading??

Please post your code, instead of an image.

Sir can u please modify my code to do that?

anybody can help?? please..

how can i store the old reading??  the first line in loop() stores  a reading .... the second line did something with that reading and stored the result

setup(){ ....
......
}
float old_reading=0;
loop() {
float reading = analogRead(LIGHTSENSORPIN); //Read light level
// ... do this always (maybe empty)
// in your code it is LED shining and printing
if ((old_reading<=900) && (reading>900)) {
   // ... do this just just once when reading goes over 900 up
   // in your code it is manipulating motor
   }
old_reading=reading;
// ... do this always , but after special part (maybe empty)
// in your code it is just delay
}

So on begining old_reading is just zero, but being declared outside loop, it keeps its value between different runs of loop.
the if (condition) does not hit, as reading is less than 900 (if it starts with more then 900, see next part)
the end with old_reading=reading; makes old_reading to be the last known value of reading
when reading goes Greater than 900 for first time, the old_reading is Less or Equal 900 (as it was the last value of reading before it crossed 900 up.

so the if (condiotion) is true and you start moving motor

then (on the end) you set old_reading=reading; and old_reading is also larger then 900

while reading stays over 900 in next loops, the old_reading does so, and therefore the if (condition) does not hit - (old_reading<=900) is not true

when reading falls down 900 or lower, the if(condition) also does not hit, but after that the old_reading=reading; makes old_reading less or equal 900

and so we are at the start again, skipping the part after if(condition) until reading gets Greater than 900 (then we run motor, set old_reading to something greater than 900 and we already was here and know, how it works :)

Thank you sir gilhad... i appreciate your time and effort doing this.. keep helping others

:) This is just basic programming (not even about Arduino) - you really should read more articles/books about programming and read examples and shorter programs and try to understand it by yourself - it will give much more understanding. I suggest to read arduino.cc and/or other sites about arduino and about programming for beginers. Really pays off in long term :)


text:
8relay module asks more than specs
I have a 8 relay module that should use not more than 20 mA per relay.
Altough when measuring it asks around 70.
If I use 6 relays, that would be more than an Arduino Mega can give.
(I already lost 1 arduino here.)
How this is possible..?

What are you measuring? The input pins will be the low current pins, however the power supply pins will take more (and you can power those without going through the arduino)

Someone told me to give 5v en GND to the relais module not from arduino but from another source. Will try that.

I don't see why and Arduino mega can't supply 420mA from the 5V pin. It's also below the USB limit of 500mA.

please add a link to where you bought the relay module .... also add the schematic of the connections between the arduino and the relay module

Hello Gerben, it should be indeed possible for the mega but in practice it seems that the relays are asking more than the specs are telling..
Jsotola: will look up the fritzing

@jsotola I've uploaded a fritzing. This is the version which doesn't work. It means, powering the 6 relays from the arduino.
There are signals coming from buttons that can put - if in the correct order - will cut of the power of the magnets which have external power.
The 8module relays says it doesn't need that much mA but in practice it is no solution. It keeps asking quite some mA.
Why it's not as the specs are telling?
It's this one: https://www.sainsmart.com/products/8-channel-5v-relay-module.
Should the module has external power too?

it is solved by giving the relay module power with external transfo. Not by arduino.

it is solved by giving the relay module power with external transfo. Not by arduino

Most of Arduino relay modules have a relay and a supporting circuit. The circuit connects the VCC line to relay coil if signal line is HIGH. Some relays have it conversely, they disconnect if signal is HIGH and hold the coil if signal is LOW.
Your relays need VCC which you can supply for 8 relays from 5 V pin of Arduino. This pin is connected over regulator to power supply of the board so it is limited only by power supply and regulator parameters. The power doesn't go over MCU.
The signal pins of individual relays should be connected to digital pins of Arduino. The signal pins don't draw much current since they only signal a state to the circuit of the relay module.


text:
Custom Debounce Code Not Working
It's my custom debounce code
It keeps the led on by flipping the required threshold value when triggered after the led has turned on to keep the led in a high state and vice verse triggered again, the comments on the code explain it in more detail.
/*
 * This code is my custom debounce code, I made this but this isn't working as planned,
 * see the thing is that it turns on when I hold the button and if I release it,
 * it starts to flickers and then gradually turn off, what is wrong with my code ?
 * I can't see it.
 */

const int ledPin = 13; // led connected to pin 13
const int PushButton = 2; // a pushbutton connected to pin 2
int switcher = HIGH; // the switcher changes it's value, we require this later
int dilay = 1; // controls the delay
unsigned long lastTrigger = 0; // records the last time the led was turned on

void setup() {
  pinMode(ledPin, OUTPUT); // sets ledpin as output
  pinMode(PushButton, INPUT); // sets pushbutton pin as input
}

void loop() {
  int pushButtonState = digitalRead(PushButton); // stores the value of the pin each time the loop begins agian

  if((millis() - lastTrigger) >= dilay){ // my custom debounce code
    if(pushButtonState == switcher){ //  this is the trick, when the pushbutton pin is high it's equal to the switcher value
      digitalWrite(ledPin, HIGH); // it turns on the led
      int switcher = LOW; // now the switcher value will be low now the pushbutton pin value will also be low keeping the led on
    }else{
      digitalWrite(ledPin, LOW); // now if the led is on and pushbutton is high, then it will not be equal to the switcher because we had changed it in the previous statement
      int switcher = HIGH; // now the switcher is high and the pushbutton value low, switcher isn't equal to pushbutton so there by keeping the ledpin as low

    }

    if(pushButtonState == 1){ // if pushbutton is high
      int lastTrigger = millis(); // then  lastTrigger equals to the current time
    }
  }

}

how is the button wired? do you have a pulldown resistor?

the button is a switch which connects the 5v pin and pin 2, and no i don't use a pull down resistor

without pulldown, the pin free floats between LOW and HIGH when disconnected from 5V

Change int switcher = LOW/HIGH to just switcher = LOW/HIGH.
Otherwise you are redefining the variable, and will make it a local variable, and not change the global variable with the same name (as you are expecting).

PS you code isn't actually doing any debouncing. It negates it a bit by only polling the input pin every 1 ms. But in some switches bouncing can take up to 6ms.

now with the change you suggested, it makes the led blink now


text:
listing sd card files on a tft screen
I'm currently working on a Arduino project that plays audio files from SD card through a speaker.
First Arduino sends the list of all music files, and when I send it a file name, the music is played.
The project is working well but there's no GUI. Everything has to be done via serial, and now I want to add a TFT screen that will list the music files on the screen, so that whenever I touch a file name  it should be played.
I haven't bought the TFT yet, and that's because I have a little question for which I need an answer.
If I start listing the files, can I scroll up and down ? Because at some point the TFT screen will become full of text, and I don't want the text to be overwritten.
Any help would be appreciated.

If I start listing the files, can I scroll up and down ? Because at some point the TFT screen will become full of text, and I don't want the text to be overwritten.

If you program that kind of facility, yes.
A TFT screen is like a blank piece of paper, and you have a set of crayons. You draw on the screen (sometimes with pre-defined shapes, called "letters"). If you want to change what is on the screen you can either throw away your piece or paper and start with a new blank page, or you can get some Tip-Ex® and cover up parts that were there already so you can draw over them.
If you want scrolling you will have to work out for yourself how best to do that given the limited resources you have available.
The simplest method is just to retain a list of the filenames in memory and print just a subset of them on the screen. "Scrolling" then just means displaying a different subset of names.


text:
How to establish a connection between an Arduino and a web server via ESP8266
I'm working on a IOT project where three or more IOT device communicates with a web server. The IoT device will have Arduino UNO which is connected to a ESP8266 so internet access is available. Arduino UNO reads current sensor data and post it to a website that I built and I also want to control a single relay switch from the same website. I am a beginner and most project I find is only single directional communication or making ESP8266 as web server. Please point me to right Direction.
I was able to post sensor data to thingspeak.com. I was also able to control The relay switch from a website but only separately. I was not able to make it work when I combined the two.
Directions:

How to build web APIS to send and receive data to Arduino UNO via esp8266?
How to send data and check the received data in Arduino UNO VIA esp8266?
Can I send and receive data in JSON format Arduino UNO?
How can the Arduino UNO filter required data from the received json?
Is this project possible without Arduino and just by programming the ESP8266 module?

I know basic HTML, Basic CSS, Basic JavaScript, Basic Nodejs, json and a tiny bit of JQuery.

@MichaelT, it is not a duplicate of that question. in this question he wants 3 esp8266 communicate with a web server, not to run a web server on esp8266 with AT commands

Thank you @Juraj... that is exactly what I want. How can it be done?

@tonymathew, I wrote an Answer yesterday as I could to your broad question. read it and ask in comments

Is this project possible without Arduino and just by programming the
  ESP8266 module?

Yes if you use ESP-12 or an esp8266 dev board like Wemos or NodeMCU. The problem could be the current sensor. I would recommend to read it with I2C ADC module, because the esp8266 A0 can read only to 1 V and is shared with WiFi functions. Wemos boards use a circuit to read analog until 3.3 V, but it doesn't help much.

How to build web APIS to send and receive data to Arduino UNO via
  esp8266?

Run your Web server in Internet and let the esp8266 and clients communicate over it. But think about security.
For accessing a Web server from Arduino or esp8266 see the WebClient example of networking libraries.

How to send data and check the received data in Arduino UNO VIA
  esp8266?

For Arduino with esp8266 as network adapter connected to Serial you can use AT firmware in esp8266 and WiFiEsp library in Arduino. Or you can have a sketch for the esp8266 with Arduino esp8266 core package and your own protocol over Serial to communicate between esp8266 and Uno. And there are firmwares for esp8266 written as esp8266 sketch, which you can use with corresponding Arduino library (WiFiLink, WiFiSpi).

Can I send and receive data in JSON format Arduino UNO?
  How can the Arduino UNO filter required data from the received json?

ArduinoJson library helps with processing the JSON format. Amount of RAM could be a problem on Uno.

I not only want to post data to a web server and using this data the web server will automatically send an instruction to Arduino UNO to turn off the switch, also I should be able to manually turn the light on and off from the website

I am using ESP-01 ESP8266 and Current Sensor ACS712

the IoT device must check the server for commands (with GET requests). try Blynk service. it is good for remote controlling of iot device

I finall could HTTP GET and POST data to node_express server.. thanks for help.. heres link to my entire project https://github.com/tonyclx/Nodewifiesp/tree/master


text:
ESP8266 01 wifi module
I have a weird problem  , as I.m trying to connect to esp8266 01 with Arduino Uno when i try sending commands from the serial it doesn't work but if i send it in a function in the setup phase it works
#include <SoftwareSerial.h>

SoftwareSerial esp8266(2, 3);

void setup()
{
Serial.begin(9600);
esp8266.begin(9600);
delay(1000);
//sendData("AT", 1000);
//sendData("AT+CWMODE=1", 1000);
}

void loop() {
// put your main code here, to run repeatedly:
if(esp8266.available()) // check if the esp is sending a message
  {
      while(esp8266.available())
      {
          // The esp has data so display its output to the serial window
          char c = esp8266.read(); // read the next character.
          Serial.write(c);
      }
  }
  if(Serial.available())
  {
    delay(1000);
    String command="";
    while(Serial.available()) // read the command character by character
    {
        command+=(char)Serial.read();
    }
    esp8266.println(command); // send the read character to the esp8266
  }
}

void sendData(String command, const int timeout) {
 String response = "";
 esp8266.println(command);
 long int time = millis();
 while ((time + timeout) > millis())
   while (esp8266.available()) {
     char c  = esp8266.read();
     response += c;
    }
 Serial.println(response);
}

try to print back to Serial the command variable

i did , the command was fine just AT command it responds with busy p... then error

do you have CR/LF in Serial Monitor? then replace println(command) with print(command)

sorry , i don't know about CR/LF . i tried print and it just responds with error

in Serial Monitor one of the settings is line ending. LN & CR

ooh , i found it it's set to Newline

AT firmware requiers \r\n (CR/LF). println adds it. so you need to set it in Serial Monitor or don't set in Serial Monitor and use println. (\n\r\n was the worst combination)

i changed the settings to Both NL& CR and now it works ... thanks man

well ... another problem appears ... AT+CWJAP="SSID" , "password" dont work ... this i have tried with send data function and serial monitor i don't know what is the problem although that AT+CWLAP works

you have a space after the comma? you still print back the command? is it complete?

AT+CWJAP="ssid", "password"     that's exactly how i wrote it

remove the space after the comma

tried it and many other ways i tried space after and before comma , and removed all spaces ... nothing works

did you send CWMODE first?

omg .... finally it's connected .. many thanks you are great

ya i did but my problem was a space before = i guess

i wanted to do that from the beginning but i can't you added comments not answers add an answer so i can upvote

I take your code as a test sketch and will not comment on the terrible way you read Serial input.
The AT firmware requires \r\n as command ending characters. You can set them in Serial Monitor as option LN & CR, but then use print to send the command to esp8266.
Or set in Serial Monitor "No line ending" and let in sketch the println to send the command. println adds \r\n to printed string.
If you had only "New line" set in Serial Monitor and used println the resulting command was for AT firmware disturbing "AT\n\r\n".

i don;t know the right way to read serial input can u please demonstrate as i took the code from internet .

I fixed that problem now i send AT commands and it responds well my problem now is connecting to an access point