text:
ATMega328 AU bootloader burning issue using Nano
We are trying to burn bootloader into ATMega328P-AU SMD. We have taken the reference of the link and did the same. We checked wire connections and all looks fine and we tried with two chip with two separate boards and we got same result.
But we tried many times and got the same error as follows,
Could someone help us on this?
    /data/install/arduino-1.8.8/hardware/tools/avr/bin/avrdude -C/data/install/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyUSB0 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/data/install/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/sankar/.avrduderc"

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x15
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x15
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x02

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x10
         Hardware Version: 4238814
         Firmware Version: 24405360.0
         Topcard         : STK502
         Vtarget         : 1.8 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: stk500_initialize(): (b) protocol error, expect=0x10, resp=0x01
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x10

avrdude done.  Thank you.

Error while burning bootloader.

did you research the error?

in your output two avrdude processes run parallel. let one finish before starting again. do you use "Arduino as ISP"? https://www.arduino.cc/en/Tutorial/ArduinoISP

@Juraj yes. We uploaded ArduinoISP to nano first, then we change options to Arduino as ISP to burn bootloader. When that happens only we get error.

try a capacitor to suppress the auto-reset of Nano. in the link in my first comment see the instructions for Mega as programmer on how to add the capacitor. other option is to make this change in programmers.txt https://github.com/arduino/ArduinoCore-avr/pull/56/commits/a901b081aed0c60e97777c9c92350d354b721094

@Juraj: It’s working fine after changing the programmers.txt. Can you put it as answer so that I will accept..?

@per1234, this is for you to answer


text:
ATTiny85 I2C connection with Arduino Nano
I am trying to send and receive data using I2C between an Arduino Nano and an ATTiny85.
The ATTiny is mounted on this board:
Link
I've tried to reach the slave with the simple I2C scanner, but I don't find anything.
Those are the codes:
Master (I2C scanner):
// --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknown error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(500);           // wait 5 seconds for next scan
}

And this is the code of the ATTiny85 (slave):
#include <TinyWire.h>

#define led_pin 1

byte own_address = 10;

void setup() {
  // config led_pin as Output for driving an LED
  pinMode(led_pin, OUTPUT);

  // config TinyWire library for I2C slave functionality
  TinyWire.begin( own_address );
  // sets callback for the event of a slave receive
  TinyWire.onReceive( onI2CReceive );
}

void loop() {

}

/*
I2C Slave Receive Callback:
Note that this function is called from an interrupt routine and shouldn't take long to execute
*/
void onI2CReceive(int howMany){
  // loops, until all received bytes are read
  while(TinyWire.available()>0){
    // toggles the led everytime, when an 'a' is received
    if(TinyWire.read()=='a') digitalWrite(led_pin, !digitalRead(led_pin));
  }
}

Once I've programmedo both the boards I've connected SCL and SCK pins of the boards together.
If i open the serial monitor of the master this is what i get:

I2C Scanner Scanning... Unknown error at address 0x20 Unknown error at
  address 0x21 No I2C devices found
Scanning... Unknown error at address 0x78 No I2C devices found
Scanning... No I2C devices found
Scanning... Unknown error at address 0x08 Unknown error at address
  0x09 Unknown error at address 0x60 No I2C devices found
Scanning... Unknown error at address 0x70 No I2C devices found

And so on.
Can someone explain me were I'm doing errors?

did you wire ground together?

@Juraj you're right, i've forgot to wire them to the same ground.
But now i only read
"No I2C devices found"

Problem solved!
I've modified the code, this is the final one:
#include <TinyWire.h>

#define led_pin 1
#define I2C_SLAVE_ADDR  0x11

void setup() {
    // config led_pin as Output for driving an LED
    pinMode(led_pin, OUTPUT);

    // config TinyWire library for I2C slave functionality
    TinyWire.begin( I2C_SLAVE_ADDR );
    // sets callback for the event of a slave receive
    TinyWire.onReceive( onI2CReceive );
}

void loop() {

}

/*
I2C Slave Receive Callback:
Note that this function is called from an interrupt routine and shouldn't take long to execute
*/
void onI2CReceive(int howMany){
    // loops, until all received bytes are read
    while(TinyWire.available()>0){
        // toggles the led everytime, when an 'a' is received
        if(TinyWire.read()=='a') digitalWrite(led_pin, !digitalRead(led_pin));
    }
}

Like this the I2C scanner sees the board at the address 0x11.
The wirings are the following:

Arduino pin SCL to ATTiny85 pin SCL (P2)
Arduino pin SDA to ATTiny85 pinSDA  (P0)
Take care of wire to the same ground both the boards.

The I2C address is 7 bits long, followed by the direction bit. So 10 or 11 are the same address but the direction bit is different. 0x10 is reserved address. https://www.i2c-bus.org/addressing/

@Juraj Your are right in the address being 7 bits long. But the address for the TinyWire library (and also the Wire library) does not include the direction bit. It is added to the address byte by the library depending on the used functions. So 10 and 11 are not the same address here.

@chrisl, yes. decimal 10 is very different from 0x11

Also 0x11 and 0x10 are not the same address, since this does not include the direction bit

@chrisl, how would you set the direction bit on 0x10 and 0x11 to be different addresses?

You don't set the direction bit here. The OP uses the Wire libraries. The address, that you use with any of their functions does not include the direction bit. The libraries use the lower 7 bit of the provided address and builds the I2C address byte by shifting the provided address one bit to the left and setting the least significant bit (which is now zero) to the correct value depending in the requested operation. The address value, that is used in the sketch is not identical with the I2C address byte. The addresses will be converted to I2C address byte like 0x20/0x21 and 0x22/0x23

source: Stack Exchange

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

sort: votes


text:
Will a delay() function in a void SerialEvent() also stop the code that is running in the void loop() function?
Will a delay() function in a void SerialEvent() also stop the code that is running in the void loop() function?
This is about an Arduino Uno.

This is the main function of the Arduino core:
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

serialEventRun() runs the serialEvent() function, if it is assigned,
so yes, a delay in serialEventRun will delay the loop.

In an Atmega328p, the Uno's processor, there is only 1 CPU; it can only do one thing at a time. If it is executing code in the SerialEvent() function, then by definition, it is not executing code in the loop() function or anywhere else.
There is a minor exception to this: interrupt service routines will run briefly when their respective interrupts occur. In fact, one way a delay() function can operate depends on timer updates that take place as interrupts. (The other way is by executing a loop whose execution time is accurately known, a specified number of times).
But interrupt service routines do one, very short, job, and return the CPU to whatever it was doing immediately before (delay() within the SerialEvent() function), so no other user code can be executed until the delay ends.

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


text:
Rfid stops scanning after wrong card scanned
My Rfid reader stops scanning cards after scanning the wrong rfid card. It doesn't scan it anymore after turning off the relay. *It turns on the relay if my rfid card is the right one
#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9
#define relay 2
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int touchPin = 8;
unsigned long previousMillis = 0;        // will store last time LED was updated
unsigned long tacc = 5000UL;           // interval at which to blink (milliseconds)
boolean opened = false;
void setup()
{
  pinMode(touchPin, INPUT);
  pinMode(relay, OUTPUT);
  digitalWrite(relay, HIGH);
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
  Serial.println("Approximate your card to the reader...");
  Serial.println();
}
void loop()
{
  unsigned long currentMillis = millis();
  int touchValue = digitalRead(touchPin);
  if (touchValue == HIGH) {
    digitalWrite(relay, HIGH);
  }
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content = "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "72 02 EF E9" ) {
  Serial.println("Authorized access");
    digitalWrite(relay, LOW);
    opened = true;
  }
  if (((unsigned long)(currentMillis - previousMillis) >= tacc) && (opened== true)) {
  digitalWrite(relay, HIGH);
    previousMillis = currentMillis;
    opened = false;
  }
}

It turns on the relay if my rfid card is the right one - more than once?

@JaromandaX yes

There is probably an error here: if (((unsigned long)(currentMillis - previousMillis) >= tacc)


text:
Wait between UART frames
I have to reproduce a signal (of 6 UART frames) which have 950 µs delay between each of the frames. Than, a delay of 37ms at the end of those frames.
Everything going right except the delay between each frame...The baud rate is at 9600.
Here is my current code :
  Serial1.write(sw_binary_train_1);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_2);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_3);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_4);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_5);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_6);
  delay(37);

Is "Serial1" a software-serial? Potentially the timing may be more accurate using hardware serial.
Also you may check if making the delay longer or shorter works. Usually, the receiving end would have some kind of 'deadzone' (that it should be between 900-950uS) and with the value of 950uS you may just overshoot that at some moments).
Also, you should try to put "Serial1.flush();" to make sure that all bytes are sent (and not only placed in the queue).

No, I'm on the Arduino Micro. Ok shoud I use delay(1) instead of delayMicroseconds(950) ? Between each frames or at the end of all frames ?

After few more tests, for a delay of 950µs i have to set delayMicroseconds(1900)...A bit strange but it works ;) !

set delayMicroseconds(1900) do a delay of 950µs between each frames...Strange but works !

Good to hear you've found a solution, potentially you still may want to look at serial.flush(); (and then delay). But if the other option works for you, it may just be OK.

The delayMicroseconds() is actually not between frames. It is more of less the time for the frame plus the 950 us extra space. The extra 1000 us is the time of the USART ISR to push the character into the output hardware buffer plus the time for the 1+8+1 bits, which happens to be approx. 1 ms @ 9600 bps. The Serial.write() is not synchronous for a hardware USART.

It's not strange at all.  Serial doesn't block while it sends.  When you call write that pushes the byte into the send buffer and that's all.  Then the code moves on to the next instruction, the delay(950) and during that time the serial data is actually being sent.  It takes about 1 millisecond for that to happen.
This solution works as long as the send buffer doesn't have anything else in it that's slowing you down and as long as you don't change the baud rate.  If either of those things happen then you need to recalculate that time.
A better solution would be:
  Serial1.write(sw_binary_train_1);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_2);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_3);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_4);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_5);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_6);
  Serial1.flush();
  delay(37);

The flush blocks until the send buffer is empty again.  That way you don't have to account for that time and all you need the delay for is the time between transmissions.
Even better would be if those things were in an array so you didn't have to keep repeating yourself.  Anytime you catch yourself putting numbers on variable names what you really want is an array so that you can use those numbers in the program:
for (int i=0; i<6; i++){
  Serial1.write(sw_binary_train[i]);
  Serial1.flush();
  delayMicroseconds(950);
}
delay(37)

looks much better.


text:
Specific formatting of floats and converting them to an array of chars
I have an oled display which can only display 4 digits + decimal point.
I need a way to format the number into 4 significant figures;
Then I need to convert that into an array of 5 chars (4 digits and one dp) before I can display them.
Not sure how to format to correct number of digits or how to convert into a char array. I searched a bit and printf seems to be the solution(?) but I've had no luck with it so far as it spits out all sorts of errors. if you know how to make it work, please can you provide a code snippet which compiles without errors? thanks.

printf on AVR doesn't support float formatting without some tweaking in configuration files of the builder.

Normally sprintf() would be the solution - however the sprintf() in the AVR LIBC is a cutdown version with no floating point support.
Instead you have to use dtostrf() to get the job done:
dtostrf(val, 6, 4, buffer);

The numbers there are the maximum width of the string (note: you need to take into account any minus sign in that value), and the number of decimal places (6,4 would give you room for "0.0000" but not "-0.0000"). Make sure your buffer is bigger by one byte than your text, since you have to have the trailing NULL character in there to terminate it.
Another (nasty) way would be to go via String (although I would never recommend using String for anything, ever):
String s(val, 4);
const char *buf = s.c_str(); // this points to the internal char buffer.

Is the String class in the Arduino library reallly that bad?

Indeed it is. It uses dynamic allocation for the internal data storage, and that is a terrible idea when you only have 2k.

How about for stack-allocated String objects? Won't they get freed on return, so avoid fragmentation (Obviously unless you allocate other longer-lived objects while in the same call chain.)

@DuncanC what is a stack-allocated arduino String? It still uses realloc and free from the heap. Allocating and releasing memory is not problem, but the fragmentation is. That is also caused by changes made to a String (the reallocate can cause fragmentation).

If you define a String as a local variable in a function, or in an expression to compose Strings from other strings, those String objects should be transient (In C++ objects assigned to local variables in functions get created on the stack, and released as soon as the function returns)

@DuncanC The string object is local, but the data it allocates to do its job is on the heap.

Ok, but when the string gets destroyed, it's heap data will get freed.

@DuncanC it's not about quantity. It's about heap fragmentation. Local strings are actually worse because they get freed.

Well, if you are in a local function, create some objects, and then return and some of the objects persist but some don't, you have fragmentation. If you only create temporary objects and they all get freed, you don't cause fragmentation.

@DuncanC I thing you are lacking in your understanding about how the String object works. Yes, it's an object. But it's not a simple object. The object itself allocates memory on the heap with malloc() and frees it with free(). It also resizes it with realloc(). What happens to the String object during its lifetime is what causes the fragmentation - not the simple fact that the object exists. If you create a String object then delete it again then obviously you won't get fragmentation. ... cont ...

... If you create a String object, then assign a value to it, then concatenate more data to the end of it, then get a substring, the reassign something else to it, by the end of that, who knows what your heap looks like? Strings, when used sparingly, for simple operations, can be a benefit - however the risks of using them (when you don't know how to use the properly, and what the dangers with them are) far out weigh the small benefit you get from them.  Every time I have seen someone with the problem "My Arduino freezes randomly" the issue has been ... cont ...

cured by removing the String objects and reimplementing it with character arrays. Every single time. Strings used by a novice are deadly. Strings used by an intermediate user are still a minefield. Strings used by a professional is something you never see.

I'm an IT professional with over 30 years of experience. It's been a long time since I worked in C++, and I have little experience with Arduino String objects, which is why I'm asking. What are the alternatives using C strings? I'm perfectly comfortable with C, but used to having printf() and sprintf(), so feel a bit lost.

Let us continue this discussion in chat.


text:
How to use parameteric function arguments
I have a function defined as follows:
void turn_leds_on(int col_indx, int bright_1 = BRIGHTNESS, int del_1 = 5, bool dir_1 = true )
This function is called using MQTT from user to define led's properties, which only first is mandatory ( has no default value ) - MQTT format is : 1,50,40,0, but can be 1,10.
Now, to implements this - I read MQTT message and store os into parameters as follows:
splitter(incoming_msg, 4, parameters); // read 4 parameters

when it defined as:
    void splitter(char *inputstr, int x, char *output[]) {
  char * pch;
  char *pnts[x];
  int i = 0;

  pch = strtok (inputstr, " ,.-");
  while (pch != NULL)
  {
    output[i] = pch;
    pch = strtok (NULL, " ,.-");
    i++;
  }
}

The problem starts when the user enters only 2 parameters and when passing parameters into :
if ( atoi(parameters[0]) <= tot_colors - 1 && isDigit(*parameters[0])) { // color num
      if (atoi(parameters[1]) <= 100 && isDigit(*parameters[1])) { //brightness
        if (atoi(parameters[2]) <= 100 && isDigit(*parameters[2])) { //delay between leds
          if (atoi(parameters[3]) <= 1 && isDigit(*parameters[3])) { //direction
            turn_leds_on(atoi(parameters[0]), atoi(parameters[1]), atoi(parameters[2]), atoi(parameters[3]));

So the question is: how to pass arguments, and on the other hand when they are not given, to use their default values as defined inside the function?

https://en.cppreference.com/w/cpp/utility/variadic

Hint: Use sscanf and let it scan, convert and check number of parameters.

turn_leds_on(3); will be compiled as turn_leds_on(3, BRIGHTNESS, 5, true);

@Juraj - that is correct, and not what i'm trying to change, but how it when parameters[i] is not given

you can do nothing if don't know the count of items filled in the array

@Juraj - I know they are 4, but is there a way to define parameters[i]=NULL, that when it is entered to the function, and not be an actual value, the defualt arguments will be considered

yes a pointer to char array can be NULL

So I checked, but default arguments were not used.


text:
Converting Client input char to int
I'm trying to print out the temperature from a DS18B20 sensor to my app via a tpc connection. Because I have two sensors connected I will need to call the one needed by an Index. This index comes from my app and is a char value which I need to convert it to an int for comparision later. The problem I have is the conversion from to input char value to int.
My code:

void loop() {
  //setting default sensor to 0
  sensorindex = 0;
  //starting server
  WiFiClient client = wifiServer.available();

  if (client) {
  Serial.write("Client connected");
          client.println("connected");
    while (client.connected()) {
      while (client.available()>0) {

        //instream from client/mobile device
        char c = client.read();
        //converting char c to int
        sensorindex = String(c).toInt() ;
        Serial.println(sensorindex);
      }

      //comparing client input to DS18B20 sensor index
      sensors.requestTemperatures();
      if(sensorindex == 1){
           client.println(sensors.getTempCByIndex(1));
           Serial.println("Index 1");
      }
      if(sensorindex == 0){
           client.println(sensors.getTempCByIndex(0));
             Serial.println("Index 0");
      }

      delay(50);
    }

    client.stop();
    Serial.println("Client disconnected");
  }
}

The serial output:
Client connectedIndex 0
Index 0
Index 0
Index 0
Index 0
Index 0
1
0
Index 0
Index 0
Index 0
Index 0
Index 0
Index 0
Index 0
Index 0
Client disconnected

When I type in 1 from my android app it shows
1
0

in the output. What am I doing wrong?

why do you present a sketch with WiFi if you ask about Serial input conversion?

@Juraj It's the same in the end because I'm I will get a char value in both cases which I need to convert to an integer. And I've never asked directly for a serial input conversion but rather the wifi input, which is basically the same

so while client is connected you print the output based on the last sensorindex value. why?

So it refreshed the app every 50ms to show the current temp of the sensor which is chosen by the index value, which is based on the input which came from the app

so the only thing that bothers you is the 0 after the 1?

Yep because it should only return one line with the given integer but instead prints out two lines. And I can't use this integer or whatever it is to compare it because it this int hasn't got the exact value which came from the app, there must be a way to smoothly convert a char to int. Or at least a digit of a char.

do you send it as println? then the '\n' would be the second char

Oh yeah makes sense but why does it convert a 1 into a 10 in the first place?

1 is 1 and \n doesn't convert at all so toInt returns 0. you convert single chars - digits of the sent number (what could be done as c - 48).

@Juraj When I use sensorindex = c-48; it just prints out 1-38 or 0-38. How can I get rid of the second char digit? I tried using atoi but that just gave me an error cuz it isnt a const char

all c < 32 are nonprintable. but if you want to read the number, not only the digits, then use client.parseInt()

Tried client.parseInt() but it just printed out the digit I want, then waits and prints out a zero. Looks like a timeout which retuns a 0 if no other digit is transmitted.


text:
Connect two ESP8266 using serial link
I am trying to build a gateway for ESP-NOW (https://github.com/HarringayMakerSpace/ESP-Now) and I would like to get help with connecting two esp8266 (nodemcu + esp01) with serial link (for use as gateway).

What I done so far:
ESP01 ... NODEMCU
-----------------
3V3   ...  3v3
GND   ...  GND
CH_PD ...  3v3
TX    ...  RX
RX    ...  TX

The problem is that with this setup NodeMCU (and I think ESP01 too) is not booting (probably because TX is connected?). What's the correct way to connect two ESP8266 as described in ESP-NOW project?
NodeMCU is running this code:
https://github.com/HarringayMakerSpace/ESP-Now/tree/master/EspNowFromSerialGateway
ESP-01 is running this code:
https://github.com/HarringayMakerSpace/ESP-Now/tree/master/EspNowToSerial

RX to TX. receive to transmit. and pull-up for io 0 of the esp-01

Ahoj Juraj, I tried this as well, but the main problem is not this. If I remove ESP-01, it boots correctly.

the code running on nodemcu seems to use softwareserial (on pins 14 and 12 - which are Dx and Dy on the NodeMCU - where x and y are seemingly arbitrary numbers), but you're connecting the hardware serial - I could be misreading the code though - I mean, how do you know it's not booting anyway?

This was the problem, problem solved. Thank you. If you post this as answer I can accept as solution.


text:
How do you make a switch case run until another serial input is detected?
I am trying to create a Traffic Light Controller.
There are three modes to the controller:
Mode 1 - the traffic light operates RED-YELLOW-GREEN-YELLOW and should repeat
* (The other modes are not necessary apart from knowing the user can select the mode.)*
I want to loop the function of the mode until I receive an input from the serial monitor. If no input is detected, then it should continue with the current mode.
At the moment I am using Serial.read() at the start of the main loop function before my switch statement to select the mode. However, this needs an input, but I want the switch cases to loop until an input is received.
All help will be much appreciated.

use a variable to store the mode ..... run the display sequence depending on the value of the variable ..... update the variable when a command is received

Show us the sketch that you have so far. Do you know what a finite state machine is? https://majenko.co.uk/blog/finite-state-machine

Use something like this (it is pseudo code so convert it to your sketch):
enum EState { NORMAL, SPECIAL } _state; // States
enum ENormalState { RED, YELLOW1, GREEN, YELLOW2 } _normalState; // State only valid when _state == NORMAL
unsigned long _time; // _time only valid when _state == NORMAL

void loop()
{
   if ('serial input available')
   {
      if ('input == ...')
      {
         _state = NORMAL;
      }
      else if ('input == ...')
      {
         _state = SPECIAL;
      }
      ...
   }

   switch (_state)
   {
   case NORMAL:
       if (_time + ... > time())
       {
          // Change to next state
          switch (_normalState)
          {
          case RED:
              _normalState = YELLOW1;
              _time = time();
              break;

          case YELLOW1:
              _normalState = GREEN;
              _time = time();
              break;
          ...
          }

       setLight(_normalState); // Change the light according to the _normalState
       break;

   case SPECIAL:
       ...
       break;

   ...
   }
}

Ideas to improve/explain:

Try to make some specific functions for setting the light according to the current state
You do not need a delay
Split functions (like above, make a separate function for normal state, and specific state

thankyou for your responses.
I managed to solve this myself by using a while loop to store the code inside each switch case, my working code is below, utilising Serial.peek() and by changing the input ending in the serial monitor to no line ending.
while ((Serial.peek() == -1)){
          regularMode(ledRed, ledYellow, ledGreen);
}

Serial.peek() gets the next item from the serial stack, if there is nothing there, it returns '-1' so i can check against that as shown above.

Yes, you need a non-blocking operation to check if there is pending chars in the stream. peek() is correct, but Serial.available() is more stream-related.


text:
Help with code for changing motor speed depending on MPU6050 angles read
I have been trying to create code where my MPU6050 is constantly reading the angle it is at and based on that angle, increase or decrease the motor speed. For example the motor will be off when the sensor is level and maximum speed at 45 degrees, and 22 degrees is roughly half speed.
I have a 5065 200kv brushless motor going to a ESC with a bec which i can attach to the Arduino. I have tried to modify a self balancing drone code that used PID. I took out the PID and tried to do an if-then for if the angle is > 5 < 45 then servo write (anglex36) because the maximum angle is 45 and if i multiply 45 by 36 it will be 1620. It says in the code the maximum rpm is 2000, although mine can go faster, and I will change it later after testing.  It is recommended to have the max motor speed be at most 85% motor power to prevent damage so that is why I have it at 1620 for now and not 2000.
I am fairly new with Arduino and have no experience with the MPU6050 so I apologize for any misunderstanding of information or code.
Here is my code :
#include <Wire.h>
#include <Servo.h>

Servo right_prop;

int16_t Acc_rawX, Acc_rawY, Acc_rawZ,Gyr_rawX, Gyr_rawY, Gyr_rawZ;

float Acceleration_angle[2];
float Gyro_angle[2];
float Total_angle[2];

float elapsedTime, time, timePrev;
int i;
float rad_to_deg = 180/3.141592654;

double throttle=0; //initial value of throttle to the motors

void setup() {
  Wire.begin(); //begin the wire comunication
  Wire.beginTransmission(0x68);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(250000);
  right_prop.attach(3); //attatch the right motor to pin 3

  time = millis();

  right_prop.writeMicroseconds(1000);
  delay(7000);

void loop() {

/////////////////////////////I M U/////////////////////////////////////
    timePrev = time;
    time = millis();
    elapsedTime = (time - timePrev) / 1000;

     Wire.beginTransmission(0x68);
     Wire.write(0x3B);
     Wire.endTransmission(false);
     Wire.requestFrom(0x68,6,true);

     Acc_rawX=Wire.read()<<8|Wire.read();
     Acc_rawY=Wire.read()<<8|Wire.read();
     Acc_rawZ=Wire.read()<<8|Wire.read();

     Acceleration_angle[0] = atan((Acc_rawY/16384.0)/sqrt(pow((Acc_rawX/16384.0),2) + pow((Acc_rawZ/16384.0),2)))*rad_to_deg;
     /*---Y---*/
     Acceleration_angle[1] = atan(-1*(Acc_rawX/16384.0)/sqrt(pow((Acc_rawY/16384.0),2) + pow((Acc_rawZ/16384.0),2)))*rad_to_deg;

   Wire.beginTransmission(0x68);
   Wire.write(0x43); //Gyro data first adress
   Wire.endTransmission(false);
   Wire.requestFrom(0x68,4,true); //Just 4 registers

   Gyr_rawX=Wire.read()<<8|Wire.read();
   Gyr_rawY=Wire.read()<<8|Wire.read();

   /*---X---*/
   Gyro_angle[0] = Gyr_rawX/131.0;
   /*---Y---*/
   Gyro_angle[1] = Gyr_rawY/131.0;

   /*---X axis angle---*/
   Total_angle[0] = 0.98 *(Total_angle[0] + Gyro_angle[0]*elapsedTime) + 0.02*Acceleration_angle[0];
   /*---Y axis angle---*/
   Total_angle[1] = 0.98 *(Total_angle[1] + Gyro_angle[1]*elapsedTime) + 0.02*Acceleration_angle[1];

    Serial.println(Total_angle[1]);

if( Total_angle[1]> 5 && Total_angle[1]< 45)
{
right_prop.write(Total_angle[1]*37);
}
else{
right_prop.write(0);
}
}

//end of loop void


text:
Arduino libraries development and Eclipse Soleber
I have a project on Arduino IDE. A .ino sketch with some extra .h/.cpp files and 2-3 libraries that I keep in ~/Arduino/libraries.
In addition to the IDE I do open the libraries as generic project in eclipse, of course this means no symbols resolution and no indexing which is bad for me.
So I wanted to give Solebera try. I can see that Soleber includes the directory above however when compiling, I can clearly see it doesn't include any of those libraries! Also trying to add them doesn't work as the preference screen doesn't allow it/lists it.
So you help please,

how can i make it even compile?
will eclipse index it? I mean if I press 'ctrl + shift + r' and start typing RH_RF95 (radiohead rf95 driver cpp file) will it let me open it? (it does for Platformio).

in Eclipse Arduino Preferences you can set if it adds the libraries automatically. If you choose not auto, then use "Add a library to selected project" in Arduino menu. 2) yes

I edit and debug libraries in a test project for the library. So the developed library is one of the libraries used by the project.

nop didn't work for me, "automatic is set for me but adding RHGeenricDriver.h doesn't cause the library to be added. adding "libraries" to the project adds ALL the libraries , i can see them in the makefile but they are excluded including radiohead which has an include in the main file. so it doesn't work. seems like it's not the way to go after all.

do you have the libraries folder configured in Preferences?

Yes i do.  Its configured correctly,  i checked.

try with a new project

It is a new project,  i ipened it just for the tseting...

Let us continue this discussion in chat.


text:
GPS detecting stationary?
can someone please point me at some code snippets to detect when the GPS is stationary. I am currently using tinyGPS library and it is working fine, but my data-logger has thousands of stationary details I'd like to not bother logging. Currently I am using this,
uint8_t speedZero() {
uint8_t spd = gps.speed.mph();
  if (spd < 5) {
    return 0;
  } else {
    return spd;
  }
}

But it is too granular at slow speeds, but the NEO-6M drifts a lot and 5mph standing still is not uncommon.
I have tried comparing Last Lat/Lon but not having any success as this Math is waaaay out of my skill-zone.

Just add accelerometer sensor to your device. It's just around 1USD and it will easily detect lack of movement.

I have tried comparing Last Lat/Lon but not having any success as this Math is waaaay out of my skill-zone. - find a function that gives you a distance between two lat/long points, the remaining math is trivial

I gave an answer in PHP a few month ago, maybe it can help: https://stackoverflow.com/questions/7222382/get-lat-long-given-current-point-distance-and-bearing/26938066#26938066

Only log the values when they've significantly changed?

I found this to get me started.
http://apexlogic.net/code-bank/arduino/serial-gps-find-distance-between-two-points/


text:
Help with sending data to MIT app inventor through bluetooth

I'm trying to connect my arduino bluetooth sensor to an MIT App Inventor app I made, and in doing so display the readings of two of my sensors. Whenever I test the sensors in the serial monitor, I get normal readings, but sending them to MIT APP Inventor makes them glitch out and give me the error "Select list item: Attempt to get item number 2 of a list of length 1". I've reviewed all of my code for both the Arduino and the MIT App Inventor, and I haven't been able to find anything that may be hindering me. The timer interval for the MIT App inventor code is correct.
My Arduino code is below; the MIT app inventor code is shown in the above image
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

//  Variables
const int PulseWire = A1;       // PulseSensor PURPLE WIRE connected to ANALOG PIN A1
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
                               // Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
                               // Otherwise leave the default "550" value.
const int PIEZO_PIN = A0; // Piezo output

PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

void setup() {
  Serial.begin(9600);          // For Serial Monitor
  // Configure the PulseSensor object, by assigning our variables to it.
  pulseSensor.analogInput(PulseWire);
  pulseSensor.setThreshold(Threshold);
  }
void loop() {
  int piezoADC = analogRead(PIEZO_PIN); //Get the analog value of the Piezo sensor
  float piezoV = (piezoADC / 1023.0 * 5.0);  //Get the voltage of the Piezo sensor
  int myBPM = pulseSensor.getBeatsPerMinute(); //Get the BPM detected of the user

  Serial.print((double)piezoV); // Print Piezo voltage

  Serial.print("|"); //Use this character to separate the vibration from the heartbeat

  if (pulseSensor.getBeatsPerMinute() == 0){
  Serial.println("N/A");
 }
 else{
  Serial.println((int)myBPM); //Print the BPM
 }
  delay(5000);

}

the split text at "|" ... is that "|" or " | "?

The split text is |, not an capital i or a lowercase L. The thing where you click shift and the backslash key.

start by writing a minimal sketch that sends a single fixed byte every 5 seconds or so. ..... write an app to receive that byte

I'm not asking if it's "l" or "I" or "1" - I'm asking if it's "|" or " | " .... the difference being SPACES

Ah, I'm sorry. No spaces, its just "|"

My guess is that BytesAvailableToReceive > 0 is true after Serial.print((double)piezoV) but before Serial.print("|") ... hence the issue ... try changing your input processing to only process input once it receives end-of-line ... i.e. \n .... alternatively Serial.printf("%f|%s\n", (double)piezoV, myBPM ? "N/A" : String(myBPM)); may work for you

I'm sorry, but I'm a bit new to Arduino and I don't quite understand how I would change the example code you gave me to put it into my sketch. I understand the issue you're pointing out, though. Could you please rephrase the code somewhat? Again, I'm sorry and I hope this won't annoy you too much.
EDIT: It's because whenever I paste your code into my sketch, it gives me the error "HardwareSerial has no member named printf", despite working with different inputs.

Scratch that, printf never works.

To clarify on what I meant by the first comment: putting the example code you gave me into the sketch causes a lot of errors, so I was wondering if you could please reformat it so it would work with the code without any issues?

oh ... I'm spoiled by having printf on ESP8266 Arduino :p - if you can't print using printf then use char buffer[80]; sprintf(buffer, "%f|%s\n", (double)piezoV, myBPM ? "N/A" : String(myBPM)); Serial.print(buffer); perhaps

The error still occurs; perhaps I need to place it in a specific place in the code, or do I maybe have to replace something?

Yeah, I'd say the only fix is to make sure the receiving side doesn't "parse" the received data until it gets all of it

How would I do such a thing? I tried editing the MIT App Inventor so that it would only display the data if the length of the list was 2 (the amount of individual readings I should get), but instead the app now never shows the data, almost like it's not receiving readings at all.

Another thing: I think I might be able to use the solution you gave me, I just need to know where I should place that line of code and what I should replace with it.


text:
Normally-Open opto-coupler board
I'm looking for a Normally-Open optocoupler board for arduino. I need to control power of a device (DC 12v, 500mA).
I tried to use TLP281 board, which works, except that it inverts the output: device is powered when there is no control signal (i.e., it is Normally-Closed).
For this reason, the TLP281 board is not useful in my project.
This is picture and schematics for TLP281 board:

I need an optoisolator board which works analogous to normally open mechanical relay: when there is no signal, device must not be powered; and when there is signal, device must be powered.
NOTE: workaround by inverting the control signal in microcontroller firmware is not permitted, as the device must not be powered when microcontroller is off

@JaromandaX Do you know a schematic which explains how to create Normally-Open relay based on TLP281 (or any other opto-isolator)?

@JaromandaX I tested it and I can say for sure that this board inverts the signal (on low input, there is power on output, on high input, there is no power on output).

I think every driver does what you want, only this one has it inverted. What is the device? A motor? Do you need pwm to control the speed? This could be a normal driver: https://www.aliexpress.com/store/product/Mosfet-MOS-Optocoupler-Isolation-Driver-Drive-Module-Field-Effect-Transistor-Trigger-Switch-PWM-Control-Controller-Board/612195_32860424049.html There are similar modules for 4 and 8 channels.

@Jot the device is Panasonic KX-TCD245, I need just to turn it on or off.

@JaromandaX the links that you give are for the same board which is in OP - it is Normally-Closed - I need Normally-Open

@JaromandaX let's use just the terms "Normally-Open" and "Normally-Closed" - that would be less confusing

looking closely at the circuit diagram .... if nothing is connected to INx or INx is "LOW", then OUTx will be at HGND - when INx is "HIGH", OUTx will be HVCC... this is exactly what you want  - there's no "open" or "closed" - if it's not working, then it's how you've connected your circuit to that board that is the problem - i.e. the circuit you haven't shown is the problem - the "relay" you've shown looks wrong because there's only two connections to it - so perhaps that's another problem

is hacking the TLP281 board an option for you?

@jsotola I don't mind hacking the board if I understand how

talking about only one channel here, repeat 4x if needed ....... basically, insert the photo-transistor in series with the base pullup resistor of Q1, and add a pulldown resistor to the base of Q1 .... that way Q1 turns on when input signal is present ......... cut the trace between Q1 and R2/IC1_pin16 ...  disconnect IC1_pin15 (emitter) from GND and connect to Q1 base ..... connect 5kΩ pulldown resistor between Q1 base and GND

I don't think there is a need for a specific "normally-open" opto-coupler. Same result can be easily achieved by using "normally-closed" opto-coupler and making a slightly modified "NOT" logic gate using three resistors and NPN transistor.

1. When INPUT is LOW:
Base of Q1 is shorted to ground through R1 so Q1 not letting the magic pixies go through. This makes OUTPUT show 5V and be in HIGH logic state.
2. When INPUT is HIGH:
Base of Q1 is powered by voltage divider R/R1. R needs to be much lower than R1 to keep Q1 saturated. This makes Q1 to be passing current and setting OUTPUT to LOW state by creating a voltage divider R2/Q1(collector-emitter resistance) This means that value of R2 should be much higher then c-e resistance of Q1.
3. When INPUT is floating (microcontroller is turned off):
Any voltage on INPUT caused by imperfections of the hardware, E-M noise induction, static electricity, etc. should be discharged to ground by resistors R+R1 keeping INPUT in LOW state. (This means that R+R1 cannot have to high value or the discharge speed might be to slow)

There is a problem with your solution: microcontroller is powered from USB, so the "5V" in your scheme will not be there when microcontroller is off. Thus, changes must be made to "output" side of optocoupler, not to "input" side.

If you use tougher npn transistor (for example the same one as uour opro-coupler) and higher resistor values (similar values as your opto-coupler) you can use this with 12V power source. You can remove R1 then because right side is never floating.

If I understand you correctly, you are suggesting something like this, right? http://www.ti.com/lit/ds/symlink/uln2003a.pdf

Actually I was suggesting that you simply get S8050 transistors (100 for 1 USD) and 5.1K resistors (100 for 0.70USD) and make a NOT gate with identical load bearing properties to the opto-coupler you shown. I assumed that you use that opto to steer a MOSFET since anything spiking above 500mA could burn it anyway (S8050 used in opto is rated for max 500mA)

For those, who are stumbling over this old thread and @igor-liferenko, since this board is still quite common:
This board definitely does NOT invert the inputs.
The comment of Igor Liferenko "tested it and I can say for sure that this board inverts the signal (on low input, there is power on output, on high input, there is no power on output)." is wrong. I don't know what he has tested, but both the schematics and tests show, that the board does not invert (or actually inverts twice -- once by the TLP281-4 itself and once by the following S8050-transistors).
So: low on input -> low on output; high on input -> high on output.


text:
Problem I²C Communication between Arduinos
My Problem seems to be that my I²C slave randomly disconnects.
I have an Arduino Due communicating with a Arduino Chestnut board (bought hardware).
I now measure data with the Due and then send the data via an I²C interface to the Chestnut. No other devices are on the I²C bus.
The problem is that I randomly receive the error code "2" from the endTransmission method which seems to imply that the slave device disapeared from the bus. The connection sometimes works fine, and then sometimes right after startup or some time later this error occurs. I measured the signals with an oscilloscope and the clock signal then is always low.
Has someone an Idea what could be the problem?

lack of, or incorrect, pullup resistors?

Standard Arduino pullups, 4k7

The Arduino Due has sometimes troubles with the i2c bus. Lately I see more people having problems with the Due and the i2c bus. The Due has onboard pullup resistors of 1k5 (sometimes 1k), that is very low. Some add 100 ohm resistors in the signal path of sda and scl to reduce the slew rate. Can you replace the Due with a samd21 (zero, m0, mkr boards)? Add a delay of 1ms between Wire.endTransmission and Wire.requestFrom. Show us the sketch of the master and the slave please. The slave is not allowed to turn off interrupts. How long are the wires? Do you use a cable? Are the GND connected?

I can't switch boards, I got the circuit, hardware and the code from my supervisor with the task to fix the i2c problem. But I will tell him about the problems of the Due with the i2c interface and how to fix it and the we'll see what I am allowed to do.

The master (Due) just sends data to the slave (actuator) because my actuator is hardwired to be a slave device. The GND are connected (same power source) and the cable is a standart, shielded three wire cable (just SDA and SCL used, one is connected to GND).
What do you mean the slave is not allowed to turn off interrupts? I use a simple protocoll, master sends data, slave waits to receive data (gets interrupt when data is reveiced) and then moves some motors according to the data. I guess  the slave can only turn off interrupts because of a library error, but how can I check this?


text:
I can't send GPS data to server
I am trying to send gps location data every 3 seconds to mqtt server if it's updated but my device shows weird stack errors and resets. What i am missing?
I am using tinygps++ and pubsubclient as libraries.
LOOP:
void loop() {
  if (WiFi.status() != WL_CONNECTED)
  {
    connectWifi();
  }
  if (WiFi.status() == WL_CONNECTED && !client.connected())
  {
    mqtt_connect();
  }
  client.loop();

  if (WiFi.status() == WL_CONNECTED && client.connected())
  {
    long now = millis();
    if (ss.available() > 0)
    {
      if (now - lastMsg > 3000) {
        lastMsg = now;
        gps.encode(ss.read());
        display.setTextSize(1);
        display.setTextColor(WHITE);
        display.setCursor(0, 0);
        display.println("Lat:" + String(gps.location.lat(), 6));
        display.setCursor(0, 10);
        display.println("Lng:" + String(gps.location.lng(), 6));
        Serial.print("Latitude  : ");
        Serial.println(gps.location.lat(), 5);
        Serial.print("Longitude : ");
        Serial.println(gps.location.lng(), 4);
        if (gps.location.isUpdated())
        {
          String pos = String(gps.location.lat(), 6) + ";" + String(gps.location.lng(), 6);
          client.publish(mqtt_output, pos.c_str());
          display.setCursor(0, 50);
          display.println("Data Sent");
          m_alert();
        }
        display.setCursor(0, 30);
        display.println("Satellites: " + gps.satellites.value());
        display.setCursor(0, 40);
        display.println("HDOP: " + gps.hdop.value());
        display.display();
      }
    }
  }
}

connectWifi :
void connectWifi() {
  Serial.println('\n');

  WiFi.begin(ssid, password);             // Connect to the network
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  int i = 0;
  while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(1000);
    Serial.print("*"); Serial.print(' ');
  }
  w_alert();
  Serial.println('\n');
  Serial.println("Connection established!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());
}

mqtt_connect :
void mqtt_connect() {
  Serial.print(F("MQTT Connecting..."));

  char* clientId = "app";
  while (!client.connected()) {
    mqttConnectAttempt = millis();
    if (client.connect(clientId, mqtt_user, mqtt_pass)) {
      s_alert();
      Serial.println(F("connected"));
      String ready = "Connection Success!\r\n";
      client.publish(mqtt_output, ready.c_str());
      client.subscribe(mqtt_output);
    }
    else {
      Serial.print(F("Failure, rc="));
      Serial.print(client.state());
      Serial.println(F("Connecting Again in "));
      Serial.print(MQTT_PERIOD + " Seconds");
      delay(MQTT_PERIOD);
    }
  }
}

you are missing an explanation of what weird stack errors and resets means

reduce you code .... send a single fixed value to the MQTT server ...... what errors do you get?

Do you get any of your Serial.print output at all?


text:
Sending .wav via network
I'm working in a project and part of this project is sending a .wav file from an Arduino to other device (for example anther Arduino).
I already am able to send a .txt file from an SD which was included in the Ethernet Shield to other Arduino SD card, but it doesn't work when I try to send a .wav file.
Any idea ?
void loop() {
if(digitalRead(push1) == LOW){
    writeanddeletSDcard();
      Serial.println("i will send now");
      Udp.beginPacket(destIp, port);
     Udp.write(a);
      Udp.endPacket();
      Serial.println("Sending UDP message");}}

void writeanddeletSDcard(){
    SD.remove("S13.txt");
   myFile = SD.open("S13.txt", FILE_WRITE); // boolean
   data = myFile.size();
  // if the file opened okay, write to it:
  if (myFile) {
    Serial.println("i will Write now ");
    delay(2000);
    Serial.println(data);
    myFile.println("HELLO WORLD");
    myFile.close();

    // close the file:
  }
else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");}

// ---------------- here end of Writing an a massege on the SD Card
  // re-open the file for reading:
  myFile = SD.open("S2.WAV");
  if (myFile) {
    Serial.println("inside the file there's");

c= 0 ;
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      a[c] = myFile.read();
      c++;
    }
    Serial.println(c);

   // close the file:
    myFile.close();
  } else {
   // if the file didn't open, print an error:
    Serial.println("error opening test.txt");}}

What is a? How big is the WAV file?

hello, a is an array of char type i want to store the data on it , and then send it , the size of the wav file is  49289 Byte

And you want to store 49289 bytes in an array on an Arduino with only 2K of memory...? Good luck...

i don't want to store it in the Arduino, i want to Store it in the SD card, then dived it to small byte and send it as a Stream of byte

At the moment you're just "reading from the file until there's nothing in it". I see no attempt at only reading a portion of the file and sending it.

You should look at: https://www.arduino.cc/en/Reference/StreamReadBytes


text:
Read from serial monitor and put it in a array of byte
I'm a new here and this is my first question.
I would like to read from serial monitor and stock the information in a array of bytes. then I want to print this array in serial monitor.
This is the code that I tried:
byte A[6];

void setup()
{
}

void loop() {
  A[6] = Serial.read();
  Serial.write (A);
}

https://majenko.co.uk/blog/reading-serial-arduino https://majenko.co.uk/blog/arrays-pointers-what-c

If you want to print it only, I would suggest not to store it. But if you want to do some calculations, you might store it.
The problem you make is you always store the value in the 6th element of the array A, however A only has elements A[0] to A[5], so A[6] is beyond the storage space, and results in crashes (sometimes) or at least unexpected behavior.
To fix it you have to store the value in the correct element of A, and for that you need an index variable. Since you can only store 6 values, after the 6th, start with the 0 and process it.
Like:
byte arr[6];
index arrIndex;

void setup()
{
   arrIndex = 0;
}

void loop() {
  // Read serial.
  arr[arrIndex] = Serial.read();

  // Increase counter
  arrIndex++;

  // If the maximum is read, print values and reset it.
  if (arrIndex == 6) {
     // Print the elements.
     for (index = 0; index < 6; index++)
     {
        Serial.write(A[index]);
     }

     // Restart counter.
     arrIndex = 0;
  }
}

An improvement: instead of 6 everywhere, use a define:
#define MAX_ELEMENTS 6

Hey Michel,
Thank you for your response--
I tried your code but some question marque keep showing up .
if i print for example 11111. the Serial monitor show
?????????????????????????????????????????????????????????????????????????????????????????????????11111

I assume the read data are characters, if you try to print out non ascii values you might get the ? values... Try converting it to a string (with itoa(...) for example. Or maybe using an int array helps (not sure, cannot test it here).

I didn't explain it well, actually the question mark keep showing even if I print nothing. when I print something, the Serial monitor show it then go back to the next line

use https://www.arduino.cc/reference/en/language/functions/communication/serial/available/

You're welcome, good luck with your project


text:
Good quality sound using a microcontroller
I am a hobbyist. Doing some experiments with sound quality. I'll pin point my problem and requirements.

Problem statement :I want to play audio files ( recorded in human voice, not music files, just some plain human speech files)
I have tried : a project with an Arduino microcontroller and MicroSD card but audio quality was not at all good from the link below
https://www.instructables.com/id/Audio-Player-Using-Arduino-With-Micro-SD-Card/
https://circuitdigest.com/microcontroller-projects/arduino-audio-music-player
It just used an arduino UNO board, microSD using SPI, a speaker and an LM386 Audio Amplifier.

I read about the details and got to know that I need a DAC for better quality (as PWM cannot serve the purpose), and a speaker also. But there are a number of things available and I dont understand which one to buy and start a project.
Can you share the details of some micro-controller board with a DAC which suffice my purpose, memory to store audio files (or I can use a microSD card device), and a speaker project which I can follow and make one.
I am looking for a board based solution, after getting some results, I can go for separate micro-controller and DAC.
Thanks in advance.

For what I read about it (no references readily available), it's mostly better to have a separate DAC since internal DACs are mostly 10 or 12 bits, for decent audio quality you need at least two channels of 16 bit DAC.

Hi and welcome to the Arduino SE community. It is good to see the effort you put into your question. I hope to see you more around this site.

There are boards that will read the SD, decode the audio, and amplify it, all-in-one. You micro-controller only has to "tell" the board to play sound file 1, 2, 3, or whatever number. For example the DFPlayer (or one of it's clones on eBay).

I really liked the DFPlayer and it seems that its a readymade solution for my problem. Can I find its circuit diagram and ICs used in this so that I can implement it in parts on breadboard.

You can buy a cheap MP3 player and use Arduino to "press" its buttons, works the best assuming the UI logic of the thing isn't too convoluted.

Here is the schematic and breadboard layout I was using.
Coding can be found in this Arduino.cc thread
https://forum.arduino.cc/index.php?topic=180769.60

One would think that single channel for voice would be enough.  Remember the old Sprint commercials? "So quiet you can hear a pin drop", that was only single channel.  12 bits at 16 MHz for max 8 KHz bandwidth would be good.  Per Wikipedia "In telephony, the usable voice frequency band ranges from approximately 300 Hz to 3400 Hz. It is for this reason that the ultra low frequency band of the electromagnetic spectrum between 300 and 3000 Hz is also referred to as voice frequency, being the electromagnetic energy that represents acoustic energy at baseband. The bandwidth allocated for a single voice-frequency transmission channel is usually 4 kHz, including guard bands, allowing a sampling rate of 8 kHz to be used as the basis of the pulse code modulation system used for the digital PSTN. "
I think several folks, such as Adafruit.com, DFRobot.com, and others make cards with DAC outputs.  Or you could get a DAC only card from Gravitech.us
I started a project at Arduino.cc to sample 16 bits at 44.1KHz, store to SD card, then play it back later. I used external SPI ADC and DAC, and member fatlib16 there helped me to code it.  You can find it by searching "sample, record, playback later" and it should pull it up.

Thank you for the answer and the details. I am thinking that I'll record audio with 16 bits depth at 44.1KHz and do some experiments with adafruit for sound quality and store in SD card. Arduino already has SPI to interact with SD card module. Can you please tell me that which DAC you have used and which speaker you have used.

Digitizing with ADC AD7680, sending it to DAC AD5662-1. Speaker, I was using self-powered PC speakers for playback. See answer for schematic.


text:
What is the difference between the digital temperature sensors SHT31 and DHT11 or DHT12?
I am looking for a digital temperature sensor with I2C interface.
I found the SHT31 and the DHT12 (compatible to DHT11). Both also include humidity sensors. And I found libraries for both of them. But I did not find a comparison.
https://sea.banggood.com/GY-SHT31-D-Digital-Temperature-and-Humidity-100-RH-I2C-Sensor-Module-For-Arduino-p-1167498.html
https://sea.banggood.com/KEYES-DHT12-Digital-Temperature-and-Humidity-Sensor-Module-Compatible-DHT11-For-Arduino-p-1400920.html
What are the (significant) differences between those sensors and libraries?
In the moment I want to use a sensor to measure the intake air temperature of a motorcycle. One degree celsius accuracy is good enough for this purpose. I don't want to calibrate them, this is why I looked for the digital sensors.

If the dht12 is as terrible inaccurate as the dht11, then the humidity is not 5% accurate, but more like 50%. The dht12 can be used for 3.3 and 5v arduino boards. The sht31-d can also be used for 3.3 van 5v arduio boards. the sht31-d is accurate. Conclusion: dht12 = bad, sht31-d = good.

Thanks, that good enough for me. I will order the SHT31-D. But for the record: Is that your personal experience or do you have any source for this information?

Both. I have a dht11 and dht22 that are very bad in measuring the humidity value. It turns out that when they are packaged in the wrong plastic, the humidity sensing element gets disturbed. This is a test (the sht31-d was not tested): http://www.kandrsmith.org/RJS/Misc/Hygrometers/calib_many.html but this test does include the sht31: https://www.kandrsmith.org/RJS/Misc/Hygrometers/calib_many_addsht31.html I also trust the information that adafruit gives: https://www.adafruit.com/product/2857


text:
How to combine two different sensor sketches to one complete sketch?
How to combine two different sensor sketches to one complete sketch for a complete circuit that attaches to one Arduino Uno?
Sharp Dust Sensor
int measurePin = A0; // Connect dust sensor to Arduino A0 pin
int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2

int samplingTime = 280;
int deltaTime = 40;
int sleepTime = 9680;

float voMeasured = 0;
float calcVoltage = 0;
float dustDensity = 0;

void setup(){
  Serial.begin(9600);
  pinMode(ledPower,OUTPUT);
}

void loop(){
  digitalWrite(ledPower,LOW); // power on the LED
  delayMicroseconds(samplingTime);

  voMeasured = analogRead(measurePin); // read the dust value

  delayMicroseconds(deltaTime);
  digitalWrite(ledPower,HIGH); // turn the LED off
  delayMicroseconds(sleepTime);

  // 0 - 5V mapped to 0 - 1023 integer values
  // recover voltage
  calcVoltage = voMeasured * (5.0 / 1024.0);
  dustDensity = 0.17 * calcVoltage - 0.1;

  Serial.print("Raw Signal Value (0-1023): ");
  Serial.print(voMeasured);

  Serial.print(" - Voltage: ");
  Serial.print(calcVoltage);

  Serial.print(" - Dust Density: ");
  Serial.println(dustDensity); // unit: mg/m3

  delay(1000);
}

MQ-135 Sensor
int airquality = A2;
void setup()
{
  Serial.begin(9600);

}
void loop()
{

  int sensorValue = analogRead(A2);
  Serial.print("Air Quality = ");
  Serial.print(sensorValue);

  Serial.print("*PPM");
  Serial.println();
  delay(1000);

}

it is unclear what you are asking .... combine 2 sensors has multiple meanings  .......... please ask a detailed question

I will leave a simplified answer and I would recommend to read https://www.makeuseof.com/tag/getting-started-with-arduino-a-beginners-guide/ or similar to get a understanding of how to code.
An Arduino sketch has a structure.

Initialising values
A void setup() this code only run once the MCU is started
A void loop() and this code runs continuously.

So to merge two sketches you need to combine the code that is in the same sections and of course avoid duplicate code and ensure that you have unique variable names
Sharp Dust Sensor
int measurePin = A0; // Connect dust sensor to Arduino A0 pin
int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2

void setup(){
  Serial.begin(9600);
  pinMode(ledPower,OUTPUT);
}

MQ-135 Sensor
int airquality = A2;
void setup()
{
  Serial.begin(9600);
}

Combined code
int measurePin = A0; // Connect dust sensor to Arduino A0 pin
int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2
int airquality = A2;

void setup(){
  Serial.begin(9600);
  pinMode(ledPower,OUTPUT);
}

There is no way of "automatically" combine two sketches into one. That's because resources of Arduino are very limited. For example UNO it has only 4 timers. If both of the sketches want to use same resource they will not work properly.
If you want to combine two sketches into one you have to write a new sketch that combines mechanisms of both sketches. It's not easy, because delay and delayMicroseconds are going to give you problems, but you should be able to do that using micros() and millis() plus some modular math.


text:
Sending data to UART using Atmel Studio with Attiny84
I want to send data to TFDI. It can be hello world or any value of variable. But I can't do. I haven't found example code on the internet. Some examples doesn't work. I am using Atmel Studio.

The Attiny84 does not have a hardware USART interface. Use something like the SoftwareSerial library. I got it working on an Attiny85.

yes I know.But I haven't found working example.If you have working example,can you share with me?

Doesn't the SoftwareSerial example from the Arduino IDE work? What happens, if you try it? What is going wrong with it?

I don't want to burn bootloader.I want to use atmel studio.And,I haven't still find any way.

The ATTiny84 does not have a hardware UART peripheral. Instead it has a USI (universal serial interface), which does not have all the capabilities needed for UART ("serial") interface.
You don't need to burn the Arduino bootloader to use libraries, that were written for the Arduino IDE. You only might need some of the definitions, which you can get by including the arduino.h file.
I think your best bet is to use existing libraries, like the SoftwareSerial library. There are also lots more libraries, that provide bit banged serial interfaces. You can also get them running in Atmel Studio, by including the source files. This is the easy way.
If you want to go the hard way, you might be able to program a hybrid software/hardware UART interface by utilizing some functions of the USI. In a search I found this site, which is about implementing UART with the USI. They also link to Atmel's Application Note  AVR307, which is a good source for understanding this. From this starting point you might also find a ready to go implementation for the USI. If not, you will have to do the work yourself.


text:
Why is this Code not working with Esp8266 when it worked perfectly with Arduino Uno?
I'm making an attendance System using an RFID scanner, scanning RFID Card & saving Data in Excel.
When I used this code with Arduino Uno (by changing #define SS_PIN 12 and#define RST_PIN 9) it worked perfectly fine.
However, when I used the same code (by changing #define SS_PIN 15 and #define RST_PIN 5) the RFID is unable to scan any of the RFID Cards.
PIN CONNECTION Of ESP8266 & MFRC522
SDA to D8
SCK to D5
MOSI to D7
MISO to D6
GND to GND
RST to D1
3.3V to 3V3
#include <ESP8266WiFi.h>     //Include Esp library
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <SPI.h>
#include <MFRC522.h>        //include RFID library

#define SS_PIN 15 //RX slave select
#define RST_PIN 5

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.

byte card_ID[4]; //card UID size 4byte
byte Name1[4]={0x36,0x69,0x25,0xD9};//first UID card 36 69 25 D9
byte Name2[4]={0xA7,0xB5,0x33,0x04};//second UID card A7 B5 33 04

int NumbCard[2];//the number of cards. in my case i have just two cards.
int j=0;
int statu[2];//the number of cards. in my case i have just two cards.
int s=0;

int const RedLed=6;
int const GreenLed=5;
int const Buzzer=8;

String Log;
String Name;//user name
long Number;//user number
int n ;//The number of card you want to detect (optional)

void setup() {

  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin();  // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card

  Serial.println("CLEARSHEET");                 // clears starting at row 1
  Serial.println("LABEL,Date,Name,Number,Time IN,Time OUT");// make four columns (Date,Time,[Name:"user name"]line 48 & 52,[Number:"user number"]line 49 & 53)

  pinMode(RedLed,OUTPUT);
  pinMode(GreenLed,OUTPUT);
  pinMode(Buzzer,OUTPUT);

  delay(200);
   }

void loop() {
  //look for new card
   if ( ! mfrc522.PICC_IsNewCardPresent()) {
  return;//got to start of loop if there is no card present
 }
 // Select one of the cards
 if ( ! mfrc522.PICC_ReadCardSerial()) {
  return;//if read card serial(0) returns 1, the uid struct contians the ID of the read card.
 }

 for (byte i = 0; i < mfrc522.uid.size; i++) {
     card_ID[i]=mfrc522.uid.uidByte[i];

       if(card_ID[i]==Name1[i]){
       Name="First Employee";//user name
       Number=123456;//user number
       j=0;
       s=0;
      }
      else if(card_ID[i]==Name2[i]){
       Name="Second Employee";//user name
       Number=789101;//user number
       j=1;
       s=1;
      }
      else{
          digitalWrite(GreenLed,LOW);
          digitalWrite(RedLed,HIGH);
          goto cont;//go directly to line 71
     }
}
      if(NumbCard[j] == 1 && statu[s] == 0){
      statu[s]=1;
      Serial.print("DATA,DATE," + Name);//send the Name to excel
      Serial.print(",");
      Serial.print(Number); //send the Number to excel
      Serial.print(",");
      Serial.print("");
      Serial.print(",");
      Serial.println("TIME");

      }
      else if(NumbCard[j] == 0){
      NumbCard[j] = 1;
      n++;
      Serial.print("DATA,DATE," + Name);//send the Name to excel
      Serial.print(",");
      Serial.print(Number); //send the Number to excel
      Serial.print(",");
      Serial.print("TIME");
      Serial.print(",");
      Serial.println("");
      digitalWrite(GreenLed,HIGH);
      digitalWrite(RedLed,LOW);
      digitalWrite(Buzzer,HIGH);
      delay(30);
      digitalWrite(Buzzer,LOW);
      }
      else if(statu[s] == 1){
     //Turn Red LED when the employee Already Left
     digitalWrite(RedLed,HIGH);
      }
      delay(1000);
cont:
delay(2000);
digitalWrite(GreenLed,LOW);
digitalWrite(RedLed,LOW);

//if you want to close the Excel when all card had detected and save Excel file in Names Folder. in my case i have just 2 card (optional)
/*if(n==2){
    Serial.println("SAVEWORKBOOKAS,Names/WorkNames");
    Serial.println("FORCEEXCELQUIT");
    }*/
}

What voltage do the SPI lines expect/require? The Arduino Uno signals with 5V, while the ESP8266 signals with 3.3V.
Also, you may check if the MFRC522.h library supports the ESP8266 (or if it's using low level atmega code)

pinMode(RedLed,OUTPUT); ... RedLed is GPIO 6 ... GPIO 6 is SDCLK - the clock for the flash ram ... using GPIO 6 like that will cause your code to fail - similarly, using GPIO 8 ... SD_DATA1 ... will also cause failure ...you're also using GPIO 5 as reset AND buzzer

sorry, not flash ram - flash memory :p i.e. GPIO 6 and 8 (and 7, 9, 10, 11) are instrumental in being able to read the flash memory that contains your code .... and are not even broken out on the bulk of ESP8266 modules on the market - the nodemcu being the exception of course, because, well, it's nodemcu and they do things differently - but GPIO6-11 should NEVER be used by your code ... Though 9 and 10 can be, if you know what you are doing

you mix Dx labels and io pin numbering, so it is hard to know what is where wired. esp8266 doesn't use Dx constants only some boards use it to match the labels

@Juraj, actually, its code only uses gpio numbers

second time you've asked the same question and ignored comments @Ashish - do you need to take a tour of the site to understand how it works?

Sorry for reposting the question @JaromandaX but i havent got any solution

your comments didnt sloved my problem yet @Juraj

did you connect a LED to D6? then use int const RedLed=D6;, D6 is io 12 and io 6 is a different pin wired on-board to the flash memory. https://electronics.stackexchange.com/questions/402066/esp8266-free-gpios-for-relay-switching/404845#404845

@Ashish - the problem is, you're using GPIO pins in your sketch that you shouldn't be using


text:
Send files via network
I want to send a file from an Arduino to the server or another Arduino.
I wrote a code that's open the file then write the content of the text on an array and then send it.
That would work if the data is small, but when i try to send, .wav it will takes lots of time if i do it that why (storing each byte in array).
I want to send the whole file at on time.
Is there a way or a library helps ?
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <SD.h>

const int push1 = 2;

File myFile;
char a[400];
int c= 0;

// network parameters
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0x05, 0x02 };  // ethernet interface MAC address
IPAddress localIp(10,131,41,72);    // local ip address
IPAddress destIp(10,131,41,74);      // destination ip address
unsigned int port = 9631;               // destination port

// EthernetUDP to send and receive messages.
EthernetUDP Udp;

// timing

// setup the arduino and shields
void setup() {

    pinMode(push1, INPUT);

  //Initialize serial and wait for port to open:
  Serial.begin(9600); // 19200
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // start ethernet and udp
  Ethernet.begin(mac, localIp);   // static ip version
  //if(Ethernet.begin(mac) == 0) {     // dhcp version
  // report failure to obtain network parameters
  // Serial.println("DHCP error");

  // no point in carrying on, loop indefinitely:
  // while(true)
  // ;
  //}

  // open UDP port
  Udp.begin(port);

  // show the local ip address (useful for dhcp)
  Serial.print("Local IP: ");
  Serial.println(Ethernet.localIP());

  // initialize previous millis variables

}

// do tasks
void loop() {

if(digitalRead(push1) == LOW){

   myFile = SD.open("R.wav" , FILE_READ);

  if (myFile) {
    // read from the file until there's nothing else in it:
    Serial.println("i will send now");
    while (myFile.available()) {
        a[i] = myFile.read();
        i++;
        }
      Udp.beginPacket(destIp, port);
     Udp.write(a);
      Udp.endPacket();
      Serial.println("Sending UDP message");
      Serial.println();
    }
    // close the file:
    myFile.close();
  } else {
   // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }  } }

You may try:
Serial.println("Sending UDP message");
Udp.beginPacket(destIp, port);
while (myFile.available()) {
  Udp.write(a);
}
Udp.endPacket();
Serial.println("Message sent!");

Or send the message part by part (for example 100bytes or 500bytes at a time)
Though, what makes you think that Arduino would be a platform that can rapidly send large files over network?
Potentially you are better off with an Raspberry Pi.


text:
Is it possible to make an HTTP get request using AT Commands without knowing the IP address of the web server?
I have the following code that can read a web page using HTTP get but I can only do it because the website I am doing it to has a static IP address, but in my project I am just hosting it on a free service and IP changes rapidly. So is there a way to do the same with only the URL address?
#include <SoftwareSerial.h>

SoftwareSerial cell(2,3);  // Create a 'fake' serial port. Pin 2 is the Rx pin, pin 3 is the Tx pin. connect this to the GSM module

const String apn = "web2"; // access-point name for GPRS

const String ip = "212.26.27.181"; // IP address of server we're connecting to
const String host = "kfu.edu.sa"; // required in HTTP 1.1 - what's the name of the host at this IP address?
const String request = "GET /sites/Home HTTP/1.1";
const String useragent = "Mozilla/5.0"; // for our purposes the user agent doesn't matter - if I understand correctly it's helpful to use something generic the server will recognize

void setup()
{
  //Initialize serial ports for communication with computer
  Serial.begin(9600);

  Serial.println("Starting SM5100B Communication...");
  cell.begin(9600);

  waitTil("+SIND: 4"); // keep printing cell output til we get "+SIND: 4"
  Serial.println("Module ready");
}

void loop()
{
  Serial.println("Attaching GPRS...");
  cell.println("AT+CGATT=1");
  waitFor("OK");

  Serial.println("Setting up PDP Context...");
  cell.println("AT+CGDCONT=1,\"IP\",\""+apn+"\"");
  waitFor("OK");

  Serial.println("Activating PDP Context...");
  cell.println("AT+CGACT=1,1");
  waitFor("OK");

  Serial.println("Configuring TCP connection to TCP Server...");
  cell.println("AT+SDATACONF=1,\"TCP\",\""+ip+"\",80");
  waitFor("OK");

  Serial.println("Starting TCP Connection...");
  cell.println("AT+SDATASTART=1,1");
  waitFor("OK");

  delay(5000); // wait for the socket to connect

have you tried using a URL in place of IP? ....... ip="google.com";
cell.println("AT+SDATACONF=1,\"TCP\",\""+ip+"\",80");

Yes, but it does not give "OK" back.

you get absolutely nothing back?

the method getMessage() gives "⸮⸮⸮⸮⸮"

what are the bytes in the returned string?

It seems you're not using the proper at command. Don't know the SM5100B but init of HTTP, sending etc is commonly made using comands like AT+HTTPINIT, AT+HTTPACTION=0 and so on.

Short answer: of course. Long answer: depends on your AT interface.

Hi, an update to the question I have upgraded to premium and now they give me a static IP. The same code still works with the website given in the question but with my website I can't seem to get an acknowledgement from the server, even though I have a public + static IP.


text:
Having trouble with motor shield running off external power source
I apologize if I don't immediately give important info, I'm very new to arduino's/circuity of any kind.  I'll try to include as much info as possible.
Some preface:
I'm currently working on a project that generates electricity using TEG's (Thermoelectric generator). The setup I currently have is able to output upwards of 9V. The motor I'm using is able to run when directly connected to the TEG wires, sp they produce enough electricity to work. Due to the nature of the project, a stopping mechanism is being used via a photoresistor and an LED. Essentially when the light signal picked up by the photoresistor is low  enough,  power is cut to the motor.
So up until recently, the motor and the Arduino board/motor shield (Arduino UNO, Arduino Motor Shield Rev3) were being run using a 9V battery. Everything worked correctly, the motor would start when needed and stop when needed. Once I switched to the TEG's the set up stopped working (motor stopped running). What is weird is that if I connect a voltmeter to channel 1 of the motor shield, I read 6V-7V (some voltage drop but not drastic) when the LED was on and 0 when the led was off. So everything seemed to still be working, but the motor itself just won't actually run. In fact, when the LED is on, it makes a very faint noise for a second but doesn't run.
The only thing I can think of is that the current being produced by the TEG's is only enough to power the motor when directly connected, but when wired indirectly through the board thus powering the board, it no longer has enough amperage.
I included the code I wrote for it, which worked fine with a 9V battery powering the motor/board.
const int sensorPin = A5;
const int ledPin = 5;
int lightLevel;

void setup(){
  Serial.begin(9600);
  pinMode(12,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  lightLevel = analogRead(sensorPin);
  lightLevel = constrain(lightLevel, 0, 800);
  Serial.println(lightLevel);

  if(lightLevel < 200){
    digitalWrite(9,LOW);
    digitalWrite(12,HIGH);
    analogWrite(3,255);
  }
  if(lightLevel > 200){
    digitalWrite(9,HIGH);
    analogWrite(3,0);}
}

maybe the polarity of the TEG is reversed  ...... are you able to run a simple LED blink sketch?

Why don't you ever write pin 12 LOW?  Should it always be HIGH?  What is it connected to?

Try a decoupling capacitor acorss your TEG : 100µF/35v (+ at the +).
This will avoid micro power drops...
Verify that y hardware driving motor works below 9V.


text:
Fast data logging
I want to store noise data (basically from A0) from an Arduino Uno to an SD card with faster writing speed, preferably by using 512 data together and the write it at once. What should be the code?

What did you come up yourself?

Please read [ask].

why do you need fast data logging ....... noise that is sampled at one hour interval, still results in a random data set .......... are you referring to noise as being random data? ..... or are you referring to recording a sound?

Read the values into an array big enough to store them
Write the array with the write(const uint8_t *buffer, size_t size) method.

Each write then gives you a block of binary data (512 values, 1024 bytes if they're 16-bit integers) written to the SD card. What you do with it then is up to you.
Note: an Arduino UNO only has 2kB of memory. If you have 512 integers that's half your memory gone. The SD card library needs another 512 bytes or more for its internal sector buffer. That's another 25% of your memory used. Already you're up to 75% of your memory gone.

Sounds like a small customization of the SD card lib is in order so it doesn't gobble up a quarter of your memory.

@ratchetfreak That wouldn't be a "small" optimization...  SD card sectors are 512 bytes. You can only read or write entire sectors. You need somewhere to store the current sector...

You could reuse the user's buffer. Then flip-flop 2 512 byte buffers as you transfer the data accross.


text:
How to chose softserial library use on Arduino project?
I want to do a project that has multiple Arduino communication through UART, that project project one of limit is using Arduino Nano (small and cheap). I need to set 4 serial port instance on Nano to connect other nano to receive and write, I searched about serial port of nano that only have one hardware serial port, so after I found the many softserial library such as pre-bulite softserial and altsoftserial NeoSWSerial and NeoHWSerial and NeoICSerial.
Because library too libraries i don't know which one can help complete my project.

what's wrong with the arduino softwareserial library? in what way does it not work for you?

Is using UART a hard requirement?
If not, consider using an I2C connection which uses a single connection and addresses to communicate with many devices.

I think your problem is that you need 4 serial ports.
With software serial that's just not going to happen:

SoftwareSerial can only receive on one serial port at any given time.
AltSoftSerial is limited to specific pins, and only one instance because there is only one set of pins
NeoSWSerial is kind of between the two. More efficient than SoftwareSerial, but still (as far as I can tell) limited to one instance (it uses a timer interrupt to drive the communication, so can use any pins)

If you need communication between lots of devices over serial then you will either need devices with more hardware serial ports (Arduino Mega, for example), or implement a multi-drop bus system (like RS-485) which only needs one serial port to communicate with many devices. Extra external hardware is required though.

Good answer. Another hardware option is a SPI to UART expander.


text:
Path relater errors on compilation in Arduino IDE 1.8.5 under Windows XP
For the XP under the Russian locale I'm getting the strange output when trying to compile Marlin project for Anycoubic 3d printer according to instruction https://3dtoday.ru/blogs/trialon/marlin119-for-anycubic-kossel-linear-plus
avr-g++: error: C:\DOCUME~1\ИЖИ: No such file or directory
avr-g++: error: Ь~1\LOCALS~1\Temp\arduino_build_153827\sketch\Marlin.ino.cpp: No such file or directory
avr-g++: error: Ь~1\LOCALS~1\Temp\arduino_build_153827\preproc\ctags_target_for_gcc_minus_e.cpp: No such file or directory
avr-g++: warning: '-x c++' after last input file has no effect
avr-g++: fatal error: no input files
compilation terminated.
exit status 1
Ошибка компиляции для платы Arduino/Genuino Mega or Mega 2560.

I have realized that the root cause was the windows user with the Cyrillic name. So creating a new user wiht base Latin name and running Arduino IDE from it helped


text:
RGB and Potentiometer

How do I start this program???
int x=0;
int P1=A5;
int P2=A4;
int P3=A3;
int R1=3;
int G1=5;
int B1=6;
int R2=9;
int G2=10;
int B2=11;
int sValue1;
int sValue2;
int sValue3;
int oValue1;
int oValue2;
int oValue3;
int timer(1000);

void setup() {
 pinMode(P1,INPUT);
 pinMode(P2,INPUT);
 pinMode(P3,INPUT);
 pinMode(R1,OUTPUT);
 pinMode(G1,OUTPUT);
 pinMode(B1,OUTPUT);
 pinMode(R2,OUTPUT);
 pinMode(G2,OUTPUT);
 pinMode(B2,OUTPUT);

}

void loop() {

sValue1=analogRead(P1);
sValue2=analogRead(P2);
sValue3=analogRead(P3);

oValue1=map(sValue1,0,1023,0,255);
oValue2=map(sValue2,0,1023,0,255);
oValue3=map(sValue3,0,1023,0,255);

if ((sValue1=0)&&(sValue2=0)&&(sValue3=0));
{
  setColor1(0,255,255);
  delay(timer);
  setColor2(255,0,0);
}
}

void setColor1(int red1, int green1, int blue1){
  {
    analogWrite(R1,red1);
    analogWrite(G1,green1);
    analogWrite(B1,blue1);
  }
}

void setColor2(int red2, int green2, int blue2){
  {
    analogWrite(R2,red2);
    analogWrite(G2,green2);
    analogWrite(B2,blue2);

  }
}

Also i get Error compiling from this program I started and I don't know what's wrong.

Welcome to SO. You should edit your question, select the entire block of code, and click the "format as code" button. (it looks like opening and closing curly braces, {}.) Unformatted code is really hard to read. (and never post more than a short code fragment in a comment since those don't line breaks.)

What do you mean "how do I start this program?" Do you mean how do you install and run it on an Arduino?

Now it has an error compiling for board. How do i fix this?

@DuncanC I think so. The question could be "How to run this sketch from a source code", screenshot is irrelevant.

@D3DSEC What compiling error do you get? BTW: Your if line is wrong. Replace = by ==. Also remove the ; at the end of the line.

int B1=6;
 ^

exit status 1
Error compiling for board Arduino/Genuino Uno.

I don't know what's wrong with my int B1=6;

Dude, you need to improve your question. State your problem more clearly, and then identify which specific lines are giving you trouble, and the exact, complete error message(s) you are getting.

I think int timer(1000); should be int timer = 1000;. sValue1=0 should be sValue1==0, or to actually match the assignment's <=50%; sValue1<=127.

I'd also like to point out that using potentiometers to collect 0 or 1 values and then drive an RGB LED is absurd. The pots should be used as voltage dividers to feed into analog inputs, and then the Arduino should be set to feed PWM signals to the different color channels of the RGB LED proportional to the inputs to the pots.

Arduino has created binary numbers: B1, B101, B00111, and so on.
It is documented in the reference page "Integer Constants".
The "B1" is defined in "binary.h".
They should not have done that. Not a single C++ software engineer thinks that it was a good addition. The C++ language is perfectly fine for creating binary values: 0b1, 0b101, 0b00111, and so on.
It is not your fault, you can blame Arduino. Because of this, you should never create variables with the name: B1, B101, B00111, and so on.

This sounds like the source of the error on that one line `int B1=6; Good callout. (Voted)

Install Arduino IDE
New sketch
Paste code
Connect the Arduino board to your PC
Upload sketch

Also i get Error compiling from this program

Obviously B1 is already defined as something, like your A5, A4 and A3 are.
You will very likely have the same issue with B2.

See Jot's answer. It sounds like B1 is the problem because apparently the Arduino library has some binary constants. like B1, B101, etc.


text:
MPU9250 and ESP8266 are not working together with Arduino Uno
I am trying to send IMU sensor data via WiFi using ESP8266. Both MPU9250 and ESP8266 worked individually with 3.3 V when tested, but are not working when interfaced together. I am not sure what the problem is; it looks like the ESP8266 is getting connected to WiFi, but the IMU is having a problem.
First I connected the ESP and the IMU parallel with 3.3 V from the Arduino, but it did not work.
Then I connected the IMU separately with 5 V but still unsuccessful.
Connections of MPU9250

Connection of ESP8266

note:-
3.3 supply is common to esp and imu
reset is connected to ground
board selected in Arduino IDE is 'generic ESP8266'
code:
#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP
#include "MPU9250.h"

const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
const char *pass =  "786110786";

const char * pubkey = "pub-c-4a9cdbca-5688-4939-a852-f63cf6743980";
const char * subkey = "sub-c-9b4067ae-1293-11e9-b4a6-026d6924b094";

const char * pubchannel = "demo_keyset";
const char * subchannel = "demo_keyset";

MPU9250 IMU(Wire,0x68);
int status;

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(115200);

       Serial.println("Connecting to ");
       Serial.println(ssid);

       WiFi.begin(ssid, pass);
       while (WiFi.status() != WL_CONNECTED)
          {
            delay(500);
            Serial.print(".");
          }
      Serial.println("");
      Serial.println("WiFi connected");

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);

    while(!Serial) {}

  // start communication with IMU
  status = IMU.begin();
  if (status < 0) {
    Serial.println("IMU initialization unsuccessful");
    Serial.println("Check IMU wiring or try cycling power");
    Serial.print("Status: ");
    Serial.println(status);
    while(1) {}
  }
}

void loop() {
    // read the sensor
  IMU.readSensor();
  // display the data
  Serial.print(IMU.getAccelX_mss(),6);
  Serial.print("\t");

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "String(IMU.getAccelX_mss())");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

I didn't get any error but here is the serial port message:-
.....
WiFi connected
IMU initialization unsuccessful
Check IMU wiring or try cycling power
Status: -1

Soft WDT reset

>>>stack>>>

ctx: cont
sp: 3ffffdf0 end: 3fffffc0 offset: 01b0
3fffffa0:  3fffdad0 00000000 3ffeec60 40206dd0
3fffffb0:  feefeffe feefeffe 3ffe8538 4010150d
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,7)

What could be the problem here?

wires are connected like above

so you think that the esp8266 should be able to read the IMU wired to Uno? how?

I thought sensor readings will go to arduino, which will upload data to wifi through ESP8266. What should i do then? using node mcu?


text:
How can I get the count of pulses of two encoders on the serial monitor?
I have two encoders; I connected them to pin 2 and 3 and I want to count the pulses of them to make two DC motors to work until it reaches a specified number of pulses, than stop working. I have finished the code of one encoder, but the other one I can't put in the same code.
byte pin = 2;
volatile float elapsed;
volatile float previous;
float rpm;
volatile int pulses;
volatile bool flag;

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
  attachInterrupt(0, elapse, RISING);
  previous = millis();
}

void loop() {
  pulses = 0; // reset pulses counter

  attachInterrupt(0, elapse, RISING); // attach interrupt for rpm counter
  delay(500);
  detachInterrupt(0); // detach interrupt for rpm counter

  if (flag == true) {
    attachInterrupt(1, count, RISING); // attach interrupt for pulses counter
    delay(elapsed);
    detachInterrupt(1); // detach interrupt for pulses counter
    flag = false; // reset flag
  }

  rpm = 1000 / elapsed * 60;

  Serial.print("elapsed: "); // print resuslts
  Serial.println(elapsed);
  Serial.print("rpm: ");
  Serial.println(rpm);
  Serial.print("pulses: ");
  Serial.println(pulses);
}

void elapse() {
  elapsed = millis() - previous;
  previous = millis();
  flag = true; // set flag to activate pulses counter
}

void count() {
  pulses++;
}

what is preventing you from counting the pulses of both of the encoders? ...... this does not count as a description of a problem .... I can't put in the same code

if you think  that you cannot do multiple things  in your sketch, then look at the six Serial.print() lines ..... that is "doing multiple things" right there