text:
Why am I getting an 'invalid conversion' error on compile?
I have one of these NodeMCU ESP8266 OLED Arduino Wifi Modules which I am trying to load with SpaceHuhn's deauther software from Github
I am trying to compile the source code using Arduino IDE with the display enabled and have followed the instructions to do so from github repository here.
I initially downloaded the latest software but as I didn't know which display option to enable before compiling, I went for an earlier version, v1.6, which has a video on how you are supposed to install it on YouTube.
After uncommenting line 18 from:
//#define USE_DISPLAY /* <-- uncomment that if you want to use the display */
so that it reads:
#define USE_DISPLAY /* <-- uncomment that if you want to use the display */
and then trying to compile, I get this error:
D:\Documents\Innovateking-EU Nodemcu ESP8266\Deauther\esp8266_deauther-v.1.6\esp8266_deauther\esp8266_deauther.ino: In function 'void setup()':

esp8266_deauther:592:32: error: invalid conversion from 'const char*' to 'const uint8_t* {aka const unsigned char*}' [-fpermissive]

   display.setFont(Roboto_Mono_8);

In file included from D:\Documents\Arduino\libraries\esp8266-oled-ssd1306-master\src/SSD1306Wire.h:34:0,

                 from D:\Documents\Arduino\libraries\esp8266-oled-ssd1306-master\src/SSD1306.h:33,

                 from D:\Documents\Innovateking-EU Nodemcu ESP8266\Deauther\esp8266_deauther-v.1.6\esp8266_deauther\esp8266_deauther.ino:28:

    D:\Documents\Arduino\libraries\esp8266-oled-ssd1306-master\src/OLEDDisplay.h:243:10: error:   initializing argument 1 of 'void OLEDDisplay::setFont(const uint8_t*)' [-fpermissive]

     void setFont(const uint8_t *fontData);

Multiple libraries were found for "SSD1306.h"
 Used: D:\Documents\Arduino\libraries\esp8266-oled-ssd1306-master
 Not used: C:\Users\cos\AppData\Local\Arduino15\packages\deauther\hardware\esp8266\2.0.0-deauther\libraries\esp8266-oled-ssd1306-4.0.0
exit status 1
invalid conversion from 'const char*' to 'const uint8_t* {aka const unsigned char*}' [-fpermissive]

The youtube video shows the process working, assuming nothing was edited out....  As far as I can see I have done everything the same.
Has anyone had any experience of loading this on to these boards?  Or know what the problem is?

It looks like the font data being used in that code (I haven't found where that is yet) isn't the right data type.  Probably a conflict between old code and new libraries.  You want to get the newest code working with the newest libraries.

esp8266 core in 2.5.1 changed char to unsigned as default, so it looks like you use some older version of the core

So what is the best course to fix this?  Use an earlier version of esp8266-oled-ssd1306-master. I cannot use a later version of deauther as there doesn't appear to be an option for a oled display...I can compile it but the display does not work!!

go in the data.h TAB
find : const char Roboto_Mono_8[] PROGMEM = {
and replace with : const uint8_t Roboto_Mono_8[] PROGMEM = {
Voilà


text:
Unable to burn bootloader with avrisp
I want to burn the arduino optiboot_atmega328.hex bootloader but it doesn't work. I remember that I was able to burn the BL using the arduino IDE which was quite easy, this time I'm having some problems.
I'm always using an avrispv2 programmer to flash my atmegas and it was also this programmer I used once to burn the BL. When I try, the IDE gives the following output:
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 "/home/xxx/Downloads/arduino-1.8.7-linux64/arduino-1.8.7/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/xxx/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM2
         Using Programmer              : stk500v1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

Fehler beim Brennen des Bootloaders.

After this didn't work I tried to manually upload the optiboot_atmega328.hex with avrdude on the commandline (following this guide). The output of avrdude is as follows:
avrdude -b 19200 -c avrispv2 -p m328p -v -e -U efuse:w:0x05:m -U hfuse:w:0xD6:m -U lfuse:w:0xFF:m -P /dev/ttyACM2

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

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/home/tabaluga/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM2
         Using Programmer              : avrispv2
         Overriding Baud Rate          : 19200
         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 : STK500V2
         Description     : Atmel AVR ISP V2
         Programmer Model: STK500
         Hardware Version: 10
         Firmware Version Master : 2.10
avrdude: stk500v2_command(): command failed
avrdude: stk500v2_getparm(): failed to get parameter 0x9a
         Topcard         : Unknown
         Vtarget         : 3.3 V
         SCK period      : 17.4 us
         Varef           : 3.3 V
         Oscillator      : Off

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: erasing chip
avrdude: reading input file "0x05"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0x05:
avrdude: load data efuse data from input file 0x05:
avrdude: input file 0x05 contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0xfd != 0x05
avrdude: verification error; content mismatch

avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: safemode: efuse changed! Was 5, and is now fd
Would you like this fuse to be changed back? [y/n] y
avrdude: safemode: Wrote efuse to 5, read as fd. 9 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 8 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 7 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 6 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 5 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 4 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 3 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 2 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 1 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 0 attempts left
avrdude: and COULD NOT be changed
avrdude: safemode: Fuses not recovered, sorry

avrdude done.  Thank you.

As I'm unable to set the fuses it's no wonder that the actual upload doesn't work as well:
avrdude -b 19200 -c avrispv2 -p m328p -v -e -U flash:w:optiboot_atmega328.hex -U lock:w:0x0F:m -P /dev/ttyACM2

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

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/home/tabaluga/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM2
         Using Programmer              : avrispv2
         Overriding Baud Rate          : 19200
         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 : STK500V2
         Description     : Atmel AVR ISP V2
         Programmer Model: STK500
         Hardware Version: 10
         Firmware Version Master : 2.10
avrdude: stk500v2_command(): command failed
avrdude: stk500v2_getparm(): failed to get parameter 0x9a
         Topcard         : Unknown
         Vtarget         : 3.3 V
         SCK period      : 17.4 us
         Varef           : 3.3 V
         Oscillator      : Off

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: erasing chip
avrdude: reading input file "optiboot_atmega328.hex"
avrdude: input file optiboot_atmega328.hex auto detected as Intel Hex
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against optiboot_atmega328.hex:
avrdude: load data flash data from input file optiboot_atmega328.hex:
avrdude: input file optiboot_atmega328.hex auto detected as Intel Hex
avrdude: input file optiboot_atmega328.hex contains 32768 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 32768 bytes of flash verified
avrdude: reading input file "0x0F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x0F:
avrdude: load data lock data from input file 0x0F:
avrdude: input file 0x0F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0xcf != 0x0f
avrdude: verification error; content mismatch

avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (E:FD, H:D9, L:62)

avrdude done.  Thank you.

I personally doubt that the µC or my programmer are bricked because I'm able to upload program code via ISP as I always used to, also I've tried two different ATmega328p.
Do you see what I'm doing wrong?
Why does one actually have to change fuses before flashing the bootloader (just curious)?

I can see you are on Linux so I won't give you instructions for using AVR Studio - but do know that if you have access to a Windows machine that is another option you could try.
I can't tell you exactly why it is not working through the Arduino IDE - it could be that the settings are not set correctly or any number of reasons. What I can say is that it is not seeing the AVRISPmkII. Try turning on verbose mode in the Arduino SE settings.
However when using avrdude, you are requesting the efuse be set to 0x05. The value of 0x05 (or b0000 0101) means that you are requesting a brownout detection of 2.7V. But because only the last 3 bits of the fuse are relevant, the chip fills the rest of the bits with 1 not 0. So b0000 0101 (aka 0x05) becomes b1111 1101 (aka 0xFD), hence you get a mismatch.
Also, according to my \Arduino-x.x.x\hardware\arduino\avr\boards.txt file, the fuses for the Arduino/Genduino Optiboot are:

low_fuses=0xFF
high_fuses=0xDE
extended_fuses=0xFD

Change your avrdude command to the following:
avrdude -b 19200 -c avrispv2 -p m328p -v -e -U efuse:w:0xFD:m -U hfuse:w:0xDE:m -U lfuse:w:0xFF:m -P /dev/ttyACM2

The last block of output in your question shows that you are trying to load the optiboot hex file. That part works so it seems, as it writes and verifies successfully. The interesting part is the lock bit fails verification. It is reading 0xCF which means it is in bootloader protection mode #3: LPM and SPM prohibited in boot loader section.
From the datasheet:

SPM = Store Program Memory instruction
  LPM = Load  Program Memory instruction

And

SPM is not allowed to write to the Boot Loader section, and LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section.

But it appears that these lock bits can be removed by doing a chip erase:

The Boot Lock bits can be set in software and in Serial or Parallel Programming mode, but they can be cleared by a Chip Erase command only.

And

The Chip Erase will erase the Flash and EEPROM(1) memories plus Lock bits. The Lock bits are not reset until the program memory has been completely erased. The Fuse bits are not changed. A Chip Erase must be performed before the Flash and/or EEPROM are reprogrammed.

So it looks like you need to do a full chip erase with avrdude.

For reference I use the following fuse calculators:

http://www.engbedded.com/fusecalc/
http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p

source: Stack Exchange

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

sort: votes


text:
Two Arduino boards with I2C sensors
I have been searching the internet about how to transfer data from multiple sensors from one Arduino to another using I2C, but no luck. All the code and tutorials online focus on multiple slaves with one sensor.
The attached Fritzing is not my project, but my project involves 22 pressure sensors and I need to log their readings in Excel using plx, so the picture is just for demonstrating the idea.
The main idea is to transfer the sensors' data from the slave to the master over I2C.
Is this doable?

Do you know how to transfer one sensor's data over I2C?

yes i did it for one sensor

Then you can do it with more sensors. Just request (and send) more data.

if it is not too much to ask is there any example u can send me to follow?

Take your code. Where you request the data for 1 sensor, change that to request the data for more than 1 sensor. Where your code responds with the data for 1 sensor, change it to respond with the data for more than 1 sensor.

Your code is the example.

There's two basic ways of doing it.

Send a byte from the master to the slave first to select which sensor you want, then request the data for the currently selected sensor, or
Request lots of bytes from the slave and fill them in one at a time as the requests arrive.

The first way is the slow, but "I2C" way of doing it - basically each sensor is its own register in the slave, and you select which register you want to read from.
The second way is faster, but you have to keep track internally of where you are.
A good compromise is to implement "auto increment" which does both scenarios: if you send a byte it sets the current sensor to read from. Then each read returns the current sensor and increments the sensor number internally in the slave, so the next read will get the next sensor.
That way you have a way to "reset" the sensor index that you are reading from, and it's reasonably quick to get all the sensors, since you just need to do multiple reads after a single write.

Wire.begin(9);//9 here is the address(Mentioned even in the master board code)
Wire.onReceive(xxx);
void xxx(int bytes)
{
l = Wire.read();//Receive value from master board
Serial.print("Pressure 12= ");
Serial.print(l);
Serial.println(" PSI ");
}
this is the code i used to read data from slave for one sensor which is working fine
how to add registory for each sensor?

That looks like you're sending from the master to the slave, not from the slave to the master. You have it backwards.

Wire.begin(9);
Wire.beginTransmission(9);
Wire.write((byte)l);
Wire.endTransmission();
this is the code i send data from salve board to master

You are showing me code that is the complete opposite of what you are claiming in your question.

Is there any specific reason why you feel you need to do it with I2C? It's probably the hardest protocol to implement.

are there any alternatives?

Plenty. Probably the simplest to implement is using one of the UARTs on each board.  Serial1.print(analogRead(0)); Serial1.print(","); Serial1.print(analogRead(1)); Serial1.print(","); ... Serial1.println(analogRead(10));

will research on UART and how to use it Thank you

on the receiving end of ur code, how is it gonna look to store each sensor data?

https://majenko.co.uk/blog/reading-serial-arduino | https://majenko.co.uk/blog/splitting-text-c

Why not put all the sensors on one Arduino?

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


text:
Is the arduino nano 33 IOT schematic wrong?
As am i was copying the schematics of the arduino nano 33 IOT from the Official arduino schematic i noticed something was wrong in the schematic, specifically in the PRTV5V component
Here is a snip on the schematic

It would seems that the pin numbering on the PRTR5V is wrong. Here are snippits from the PRTR5V Datasheet

The sample schematic does look like the same of the arduino but if you look at it using the pin number it is different.For example on the arduino schematic pin 2 is at the middle of the two diodes, while on the datasheed pin 2 is before the diodes.
Now which one should i follow? Did arduino intentionally pin it that way ?

It is correct. You are looking at the wrong datasheet.
This is the correct one:

https://assets.nexperia.com/documents/data-sheet/PRTR5V0U2X.pdf

Thank you good sir ! you just saved me from buying the wrong part :)


text:
Can I disable the TX pin by setting its mode to INPUT while still receiving data on the RX pin of a UART?
I'm using the ATmega328PB in a personal project with MiniCore. My board streams data in on the RX pin from another microcontroller, but my board also has a DIP switch connected to the TX pin, that's used for configuration. My board has already been manufactured, so a hardware solution means a board redesign and extra cost/time.
This DIP switch is connected between TXD (Arduino pin "1") and GND. Upon startup, I read the value of this pin when in mode INPUT_PULLUP. However, when I go to start the Serial, if this switch is in the closed position, it shorts the TXD pin to GND.
Is it possible to disable the TX pin by putting it into INPUT mode while still receiving data on the RX pin?

modify the library

Well, I ended up answering my own question in a few minutes of forum research.
You can disable the TX pin of the hardware UART with:
UCSR0B &= ~bit (TXEN0);


text:
invalid conversion from 'const char*' to 'char*' [-fpermissive]
With WebSocket various messages arrive.
Task:

Find message "setBrightness: 15"
Extract the value "15" from the message (the value can be any)
Convert this value to uint8_t

My code:
#include <string.h>

String payload_str = "setBrightness: 15"; // WebSocket message
const char* payload = payload_str.c_str(); // Convert string to char

const char* value; // Message value
uint8_t brightness;

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

  if(strncmp(payload, "setBri", 6) == 0) { // Search message
   value = strtok(payload, " ");
   value = strtok(NULL," "); // Get value (15)
   brightness = (uint8_t)atoi(value); // Convert to uint8_t
  }
}

void loop() {}

Compilling error:

error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
error:   initializing argument 1 of 'char* strtok(char*, const char*)' [-fpermissive]

Maybe I'm doing it completely wrong and not safe. How can this be fixed?

strtok modifies the char buffer entered as first parameter. It replaces the delimiters with terminating zeros. To parse a constant string with strtok, you must first copy it into a working char buffer.
For your test you can initialize a char array as in following example.
char payload[] = "setBrightness: 15";

uint8_t brightness;

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

  if(strncmp(payload, "setBri", 6) == 0) { // Search message
   strtok(payload, " ");
   const char* tok = strtok(NULL," "); // Get value (15)
   brightness = (uint8_t) atoi(tok); // Convert to uint8_t
  }
}

void loop() {}

if you know the 'name' part of the name:value string, you can skip it for atoi this way:
brightness = (uint8_t) atoi(payload + strlen("setBrightness: "));
(strlen("setBrightness: " will be evaluated at compile time to a constant number)
const char payload[] = "setBrightness: 15";

uint8_t brightness;

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

  if(strncmp(payload, "setBri", 6) == 0) { // Search message
     brightness = (uint8_t) atoi(payload + strlen("setBrightness: ")); // Convert to uint8_t
  }
}

void loop() {}

Thanks for the help! I will try today and say the result.


text:
Sending Simultaneous Data from 2 NRF24L01 Transmitters to 1 NRF24L01 Receiver
I'm using three NRF24L01 transceivers, each connected to one Arduino Nano. One of the NRF24L01's is configured as a receiver, while the other two NRF24L01's are set as transmitters. Firstly, I'm aware that is not possible for two transmitters to send data at once, but what I want to do, basically is to simultaneously display the transmitters' data in the serial monitor in the same time, and row as each other.
The transmitters collect data from the respective sensors attached to it, such as accelerometer and so forth. Both have the same amount of inputs and sensors.
The receiver is plugged in to the computer awaiting the transmission of data from the transmitters.
Everything is fine in the serial monitor when only one of the transmitters are transmitting, however, when both the transmitters are sending data to the receiver, a garbled mess of data could be seen in the jpg file.

What I'm trying to visualize in the serial monitor is this: the sensor values of transmitter 1 and transmitter 2, all placed in the same row every second of transmission. That is the format, because I've written a short Python script that takes the serial data and prints it in a csv file, so the format needs to be preserved.
How do I go about it? I've read about the use of arrays and payloads but I'm relatively unfamiliar with those as it is my first time exploring networking peripherals in Arduino. I hope you could help me. Thank you.
Edit: Here is the left transmitter code:

#include <SPI.h> //libraries para sa nrf24l01
#include "RF24.h" //

#include <Wire.h> // MPU-6050 I2C LIBRARY
#include <I2Cdev.h> //
#include <MPU6050.h> //

#define flex_1 A0 //declaring ng variable tsaka pin assignment ng 5 flex sensors
#define flex_2 A1
#define flex_3 A2
#define flex_4 A3
#define flex_5 A6

MPU6050 accelgyro; // variable ng mpu6050

int16_t ax, ay, az; // variables para accelerometer and gyroscope
int16_t gx, gy, gz;

int pinx=2; // pin assignment ng contact sensors
int piny=3;

RF24 myRadio (8, 9); // CSN AT CE PIN ASSIGNMENT
byte addresses[6] = {"1Node"}; // address ng both transmitter and receiver

// structure para masend ng inorder
struct Pack {
  int data11;
  int data22;
  int data33;
  int data44;
  int data55;
  int accxx;
  int accyy;
  int acczz;

} packet1;

void setup() {

  Serial.begin(9600); // para magamit ang serial monitor
  Serial.println(F("RF24/Simple Transmit data Test"));

  Wire.begin(); //

  accelgyro.initialize(); // para maread ang pin ng mpu6050

  pinMode(pinx, INPUT);
digitalWrite(pinx, HIGH);
pinMode(piny, INPUT);
digitalWrite(piny, HIGH);
/*
    accelgyro.setXAccelOffset(2825);
    accelgyro.setYAccelOffset(457);
    accelgyro.setZAccelOffset(645);
*/
  myRadio.begin(); // nrf24l01
  myRadio.setChannel(108);
  myRadio.setPALevel(RF24_PA_MIN);
  myRadio.openWritingPipe(addresses[1]);
}

void loop() {
  packet1.data11 = analogRead(flex_1);
  packet1.data11=map(packet1.data11, 450, 950, 3000, 4000);
  packet1.data22 = analogRead(flex_2);
  packet1.data22=map(packet1.data22, 450, 950, 3300, 4500);
  packet1.data33 = analogRead(flex_3);
  packet1.data33=map(packet1.data33, 450, 950, 3000, 4000);
  packet1.data44 = analogRead(flex_4);
  packet1.data44=map(packet1.data44, 450, 950, 3000, 4000);
  packet1.data55 = analogRead(flex_5);
  packet1.data55=map(packet1.data55, 450, 950, 3000, 4000);
  packet1.accxx=ax;
  packet1.accyy=ay;
  packet1.acczz=az;

  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  if (myRadio.write(&packet1, sizeof(packet1))) {
    Serial.print(F("flex1 = "));
    Serial.print(packet1.data11);
    Serial.print(F(" flex2 = "));

    Serial.print(packet1.data22);
    Serial.print(F(" flex3 = "));
    Serial.print(packet1.data33);
    Serial.print(F(" flex4 = "));
    Serial.print(packet1.data44);
    Serial.print(F(" flex5 = "));
    Serial.print(packet1.data55);

    Serial.print(F(" accx = "));
    Serial.print(packet1.accxx);
    Serial.print(F(" accy = "));
    Serial.print(packet1.accyy);
    Serial.print(F(" accz = "));
    Serial.print(packet1.acczz);
    Serial.print(F(" con1 = "));

    Serial.println();
  }

  else {
    Serial.print(F("Send failed."));
  }

}

And here is the right transmitter code:
#include <SPI.h> //libraries para sa nrf24l01
#include "RF24.h" //

#include <Wire.h> // MPU-6050 I2C LIBRARY
#include <I2Cdev.h> //
#include <MPU6050.h> //

#define flex_1 A0 //declaring ng variable tsaka pin assignment ng 5 flex sensors
#define flex_2 A1
#define flex_3 A2
#define flex_4 A3
#define flex_5 A6

MPU6050 accelgyro; // variable ng mpu6050

int16_t ax, ay, az; // variables para accelerometer and gyroscope
int16_t gx, gy, gz;

int pinx=2; // pin assignment ng contact sensors
int piny=3;

RF24 myRadio (8, 9); // CSN AT CE PIN ASSIGNMENT
byte addresses[6] = {"1Node"}; // address ng both transmitter and receiver

// structure para masend ng inorder
struct Pack {
  int data1;
  int data2;
  int data3;
  int data4;
  int data5;
  int accx;
  int accy;
  int accz;
  int con1;
  int con2;
} packet;

void setup() {

  Serial.begin(38400); // para magamit ang serial monitor
  Serial.println(F("RF24/Simple Transmit data Test"));

  Wire.begin(); //

  accelgyro.initialize(); // para maread ang pin ng mpu6050

  pinMode(pinx, INPUT);
digitalWrite(pinx, HIGH);
pinMode(piny, INPUT);
digitalWrite(piny, HIGH);
/*
    accelgyro.setXAccelOffset(2825);
    accelgyro.setYAccelOffset(457);
    accelgyro.setZAccelOffset(645);
*/
  myRadio.begin(); // nrf24l01
  myRadio.setChannel(108);
  myRadio.setPALevel(RF24_PA_MIN);
  myRadio.openWritingPipe(addresses[0]);
}

void loop() {
  packet.data1 = analogRead(flex_1);
  packet.data1=map(packet.data1, 450, 950, 3000, 4000);
  packet.data2 = analogRead(flex_2);
  packet.data2=map(packet.data2, 450, 950, 3300, 4500);
  packet.data3 = analogRead(flex_3);
  packet.data3=map(packet.data3, 450, 950, 3000, 4000);
  packet.data4 = analogRead(flex_4);
  packet.data4=map(packet.data4, 450, 950, 3000, 4000);
  packet.data5 = analogRead(flex_5);
  packet.data5=map(packet.data5, 450, 950, 3000, 4000);
  packet.accx=ax;
  packet.accy=ay;
  packet.accz=az;
  packet.con1=digitalRead(pinx);
  packet.con2=digitalRead(piny);

  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  if (myRadio.write(&packet, sizeof(packet))) {
    Serial.print(F("flex1 = "));
    Serial.print(packet.data1);
    Serial.print(F(" flex2 = "));

    Serial.print(packet.data2);
    Serial.print(F(" flex3 = "));
    Serial.print(packet.data3);
    Serial.print(F(" flex4 = "));
    Serial.print(packet.data4);
    Serial.print(F(" flex5 = "));
    Serial.print(packet.data5);

    Serial.print(F(" accx = "));
    Serial.print(packet.accx);
    Serial.print(F(" accy = "));
    Serial.print(packet.accy);
    Serial.print(F(" accz = "));
    Serial.print(packet.accz);
    Serial.print(F(" con1 = "));
    Serial.print(packet.con1);
    Serial.print(F(" con2 = "));
    Serial.print(packet.con2);

    Serial.println();
  }

  else {
    Serial.print(F("Send failed."));
  }

}

And the code for the receiver:
#include <SPI.h>
#include "RF24.h"

RF24 myRadio (8, 9);
byte addresses[][6] = {"1Node"};

int accelgyroscope[3];

int ax, ay, az;
int gx, gy, gz;

int LED_GREEN = A3;
int LED_RED = A2;

struct Pack {
  int data1;
  int data2;
  int data3;
  int data4;
  int data5;
  int accx;
  int accy;
  int accz;
  int con1;
  int con2;

} packet;

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

  myRadio.begin();
  myRadio.setChannel(108);
  myRadio.setPALevel(RF24_PA_MIN);
  myRadio.openReadingPipe(1, addresses[0]);
  myRadio.startListening();

  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_RED, OUTPUT);

}

void loop() {
  if ( myRadio.available())   {

    analogWrite(LED_GREEN, 1023);
    analogWrite(LED_RED, 0);

    myRadio.read( &packet, sizeof(packet) );
    Serial.print("0");
    Serial.print(", ");
    Serial.print(packet.data1);
    Serial.print(", ");
    Serial.print(packet.data2);
    Serial.print(", ");
    Serial.print(packet.data3);
    Serial.print(", ");
    Serial.print(packet.data4);
    Serial.print(", ");
    Serial.print(packet.data5);

    Serial.print(", ");
    Serial.print(packet.accx);
    Serial.print(", ");
    Serial.print(packet.accy);
    Serial.print(", ");
    Serial.print(packet.accz);
    Serial.print(", ");

    Serial.print(packet.con1);
    Serial.print(", ");
    Serial.print(packet.con2);
    Serial.println();

  }
  else
  {
    analogWrite(LED_RED, 1023);
    analogWrite(LED_GREEN, 0);
  }

}

Without seeing your code it's impossible to know what you're doing that makes the output look like that. I think you need to decouple your reception from your printing and update an internal list of values whenever you happen to receive them, and periodically print that list of values as a single unit whenever you deem appropriate.

I already added the codes per your request. What do you mean with "decouple your reception from your printing and update an internal list of values whenever you happen to receive them, and periodically print that list of values as a single unit whenever you deem appropriate."? I'm unfamiliar with those as my Arduino skills are limited.

That code doesn't match the output that you are showing in your image.

I'm sorry I just updated it again

It seems like you are assuming both transmitters are sending at the same rate, and all packets get received. Why do you want to have the data from the two receivers next to each other? I'd put them all on their own line. It might be useful to add a column for the received timestamp.

PS It seems that the left transmitter's packet is different from the right's (no con1 and con2). While the receiver assumes both types of packets are of the same size.


text:
why data value is 0
i want to apply formula. but getting 0 at output.

#include "HX711.h"
int data;
HX711 scale(A1, A0);		// parameter "gain" is ommited; the default value 128 is used by the library

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

  scale.set_scale(2280.f);
  scale.tare();

}

void loop() {
  Serial.print("one reading:\t");
  data==(scale.get_units()/10);
  Serial.println(data);

		        // put the ADC in sleep mode
  delay(500);

}

why do you have == in data==(scale.get_units()/10);?

It's zero because you never assign it a value.
Here you are comparing the current value of data (0) with the results of your calculation:
data==(scale.get_units()/10);

I think you intended to use the assignment, not comparison, operator =:
data = (scale.get_units()/10);


text:
Can I use this board to control multiple vibration motors?
I am looking at this: https://learn.adafruit.com/16-channel-pwm-servo-driver
Although it’s meant for servos, I was wondering if I could use them to control vibration motors.
Motors like these: Diameter Flat Button Type 3V-4.5V Cellphone Micro Vibration Motor (Pack of 3) https://www.amazon.in/dp/B07CQXZBZD/ref=cm_sw_r_cp_tai_yzSvDb8V7JAF4
Any suggestions? I would like to control about 200 motors with minimal number of controllers.
Each motor should be controllable individually.

It's not really meant for servos, it's LED driver chip that can be used to drive position of servo too (with on board pull up resistors). It could be strong enough to drive low current vibration motors, but there must be snubber circuit.

And if you need on/off only, there are led drivers for that too.

@kiiv From what I have seen the board can drive 25mA max - but those motors appear to be 66mA from what I have managed to find.

Not directly, no.  Those boards are designed to generate a low power PWM signal for passing to a servo with a built-in controller. To use that output directly with a motor you will need to add a transistor to each output to control the motor.

simulate this circuit – Schematic created using CircuitLab

instead of a diode, I'd recommend a capacitor across the motor, I think that would allow finer control for a square signal, and reduces power factor for a high-frequency signal

@tuskiomi Good point. Had my head in relay mode ;)

@SimSon In the question there is this final note: Each motor should be controllable individually.

How to you control each motor individually?

Also can you run all or some of the motors at the same time? Like how you light up only some Leds in a board to spell out a message.

You have to build this circuit for every single motor. Then connect each of the MOSFET gates to a single PWM output of the used PWM boards. If you only need on off control, you should use shift registers with the circuit above.


text:
Starting DC Pump with Arduinowhen it is powered by 9v Battery
I'm using Arduino Mega, and would like to start a DC Motor Pump. In my circuit, there are several sensors that are going to take up the voltage offered by Mega.
Hence, I would like to know whether there is a way to control the working (start/stop) of the pump using arduino as the controller while the motor being powered by a 9V battery.

use a relay to turn the power on off.  This gives you control over the pump, as well as isolates it from the micro-controller

A 9V battery doesn't give very much current and doesn't give any for very long.  They're usually not good for motors.  Generally AA or AAA would be better.

Thanks, So is there any way to reduce the complexity of the circuit as we don't have space for the relay module! We simply need a switch that gets ON upon Arduino's signal

How strong is your pump? An optocoppler or a simple transistor are smaller alternatives.

Thanks, its of 3.3V. I've connected it to my accessible motor driver shield of Adafruit v1. Hence I am able to switch it on or off just as any other DC Motor!!.


text:
Cycling through switch states
I'm making a desk lamp out of 2x WS2811 strips (attached to the triple ports at top right of board below). The brightness of the strips is controlled by a potentiometer, and the colour by a switch. Each press of the switch cycles through red, blue and white:

Here's the code I've come up with:
#include <FastLED.h>

#define strip_pin     7
#define NUM_LEDS    15

CRGB leds[NUM_LEDS];
int distance;
int brightness;
int brightnesspin = 2;
int pin_switch = 3;

// variables to hold the new and old switch states
boolean oldSwitchState = LOW;
boolean newSwitchState1 = LOW;
boolean newSwitchState2 = LOW;
boolean newSwitchState3 = LOW;
byte state = 0;

void setup()
{
  Serial.begin(9600);
  FastLED.addLeds<WS2811, strip_pin, BRG>(leds, NUM_LEDS);
}

void loop()
{
  delay(500);
//  Colour control
//##############################################
    newSwitchState1 = digitalRead(pin_switch);
    delay(1);
    newSwitchState2 = digitalRead(pin_switch);
    delay(1);
    newSwitchState3 = digitalRead(pin_switch);
    // if all 3 values are the same we can continue
    if (  (newSwitchState1==newSwitchState2) && (newSwitchState1==newSwitchState3) )
    {

        if ( newSwitchState1 != oldSwitchState )
        {

           // has the button switch been closed?
           if ( newSwitchState1 == HIGH )
           {
                // increase the value of state
                state++;
                if (state > 3) { state = 0; }
                for (int i = 0; i < NUM_LEDS; i++)
                {
                if (state==1) { leds[i].red = 100;Serial.println("Red"); }
                if (state==2) { leds[i].blue = 100;Serial.println("Blue"); }
                if (state==3) { leds[i].red = 100; leds[i].blue = 100; leds[i].green = 100;Serial.println("White");}
                }
                FastLED.show();
            }
           oldSwitchState = newSwitchState1;
        }

//    Brightness control
//##############################################
  brightness = analogRead(brightnesspin);  brightness = map(brightness, 0, 1024, 0, 255);
    for (int i = 0; i<NUM_LEDS; i++)
      {
        FastLED.setBrightness(brightness);
      }
  FastLED.show();
  Serial.print("Brightness: ");
  Serial.println(brightness);
    }
}

The brightness control works fine, and the switch cycles through the colours once, but the strip stays white once it's there, even though the serial monitor shows the switch changing state. How can I get the strip to cycle back round to red?

The problem lies in your for cycle.

If (state == 1) you are switching the red colour ON.
If (state == 2) you are switching the blue colour is ON. So at this moment, you have red AND blue colour on, not only blue. I assume the output colour is purple-ish.
If (state == 3), you activate red (which is already ON), blue (which is also already ON) and also green (which changes state from OFF to ON) so you get white colour. At this moment you went through all three possible conditions.
Then you go back to (state == 1). All colours are already activated, so from this moment you get only white...

Solution:
for (int i = 0; i < NUM_LEDS; i++) {
  if (state == 1) {
    leds[i].red = 100;
    leds[i].blue = 0;
    leds[i].green = 0;
    Serial.println("Red");
  }
  if (state == 2) {
    leds[i].red = 0;
    leds[i].blue = 100;
    leds[i].green = 0;
    Serial.println("Blue");
  }
  if (state == 3) {
    leds[i].red = 100;
    leds[i].blue = 100;
    leds[i].green = 100;
    Serial.println("White");
  }
}

In your lines:
                if (state==1) { leds[i].red = 100;Serial.println("Red"); }
                if (state==2) { leds[i].blue = 100;Serial.println("Blue"); }
                if (state==3) { leds[i].red = 100; leds[i].blue = 100; leds[i].green = 100;Serial.println("White");}

The LEDs are set on, but are never turned off.
Sequence is:
1: Red leds turn on; strip appears red.
2: Blue leds turn on (the leds will probably actually look purple rather than blue here as the red leds are still on)
3: Green leds turn on (red and blue leds are already on); strip appears white
back to start:
1,2,3: nothing changes as all leds are already on, strip remains white.
I'd suggest adding:
leds[i].green = 0; leds[i].blue = 0;

to the state == 1 condition and
leds[i].green = 0; leds[i].red = 0

to the state == 2 condition.


text:
Arduino is running as a server, but want to occasionally act as a client to update time
My Arduino (actually an ESP32-based Adafruit HUZZAH32) is running as a wifi server. Its main job is to service GET requests from a user, and to periodically turn devices on and off based on the commands implicit in those GETs.
It needs to keep an accurate time/date - in order to turn devices on/off as directed.   My cheap real-time clock is off a couple seconds or more per day.   So I figure I'll use code such as the example at:
https://randomnerdtutorials.com/esp32-ntp-client-date-time-arduino-ide/
... in which the Arduino creates a client to get the time from an NTP server.  Once a day (e.g. checking for the RTC time to be 00:00hrs in my "loop"), I'll adjust the RTC using NTP.
Looking around, it sounds like this is ok, for the Arduino to act as a client, as long as it's not actively servicing a client (the user's GET requests).  Do I have that right ?   Need I worry that a user might be sending a GET when that happens ?

you don't need to worry. and use the built in SNTP function, not an Arduino library. https://github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/examples/Time/SimpleTime/SimpleTime.ino

it's not in access-point mode is it? if so, that's a problem. otherwise you can run arbitrary client requests from a server no problem.

I think not (access-point).   My sketch is built on top of the SimpleWiFiServer example.

There is no problem with running multiple servers and use multiple clients with the WiFi library of the ESP32 core for Arduino as it is not a problem with most of the WiFi libraries for Arduino (some can't run servers (TinyGsm) or can run only one server (WiFiEsp(AT)).
But you don't need a WiFiClient for NTP time. First because NTP runs on UDP and second because the ESP32 SDK provides SNTP and the ESP32 core for Arduino wraps it in functions presented in the ESP32 examples library's SimpleTime example.

I have used the code in the SimpleTime example and it works like a charm.   Thanks.  I'm simply going to call getLocalTime once a day and reset my RTC.   I don't care if I'm off by a few seconds, just don't want those to accumulate over many days.

I was mildly concerned I could get into an infinite loop - RTC is running fast, when time of day for adjusting via SNTP comes, it gets reset to slightly earlier time, and then hits the adjustment time again.   But that's just silly - it doesn't get retarded much at all the second time.

what for the RTC? ESP32 has built in RTC and updates it over SNTP

I am using cheap ($4.95) PCF8523 w/ battery.

I did not know about one on ESP32 (Adafruit's doc for HUZZAH32 does not mention it).  It appears to require an external crystal for any kind of reasonable accuracy, and doesn't maintain if ESP32 is off.  Of course, if I usually am wifi-connected and with SNTP, maybe that doesn't matter.


text:
DS3231 OSF register changing without lost date
Dears, I have an logger prototype with arduino and ds3231 breadboard. My code check periodically OSF register to check if oscillator is/was stopped, as informed in datasheet. I turn on my logger, setting up date/hour, turn of and after some time, turn it on again to check if it's ok.
After that, the logger stay tuned off for a month. When I turned it on after this time, I note that OSF bit was changed, indicating that oscillator was stopped, but the data/time wasn't lost. I don't found possible process that can change the OSF bit in datasheet and Maxim recommendation. Maybe a negative voltage on VCC that force battery go to bellow threshold can changes the OSF bit (Maxim recommendation and this post).
Then, I test my logger connecting and disconnecting voltage (VCC) and checking the OSF bit, to simulate this possible begative voltage and not have problem with it.
My question is:

why the OSF bit changed, indicating lost of battery and consequently lost of date/time, and not lost date/time in my logger;
what could have happened with my turned off logger to change OSF bit and not lost date;

I'm using Adafruid RTCLib. Follow the simple code to check OSF bit:
#include <Wire.h>
#include <RTClib.h>

RTC_DS3231 rtc;

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

void loop()
{
  if(rtc.lostPower())
  {
     Serial.println("Date lost");
  }

  delay(1000);
}

Thank you!

excuse me @jsotola. I edited post to make myself clear. My question is why/how OSF bit changed, indicating lost of battery and data, and not lost data in my case (battery is ok)

How full is the battery? Is it a rechargable or not? The product page is a bit contradicting. As the schematic shows a crude charging circuit, while the photo and schematic show the use of a non-rechargeable CR2032. Is the resistor removed like shown in the second product picture?

The battery is a CR2032 non rechargeable and new (3.11V). I didn't remove resistor for this test, but I will. The question is that the OSF bit, for lost battery, change while the system was turned off for a month, only with CR2032 for keeping date/time. I'm using a Chinese breadboard as link in post.

the breadboard have a diode in positive of battery, then negative voltage will not affect battery.


text:
Fail to obtain Sizeof Array
I have a nested array, but I get only the correct size of the first one.
I use this as a reference Arduino sizeOf
int clockOn_0 [] = {19,0,0};
int clockOn_1 [] = {20,0,0};

int clockOff_0[] = {6,0,0};
int clockOff_1[] = {22,0,0};

int clock_flag_0[] = {0};
int clock_flag_1[] = {0};

int *dailyTO0[] = {clockOn_0,clockOff_0, clock_flag_0};
int *dailyTO1[] = {clockOn_1,clockOff_1, clock_flag_1};
int **test[] = {dailyTO0,dailyTO1};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  Serial.println("\n");

  for (int m=0; m<sizeof(test)/sizeof(test[0]);m++){
    for (int n=0; n<(sizeof(test[m])/sizeof(test[m][0]));n++){
      for (int i=0; i<(sizeof(test[m][n])/sizeof(test[m][n][0]));i++){
        Serial.println(test[m][n][i]);
      }
    }
  }

}

void loop() {
  // put your main code here, to run repeatedly:
}
This is the result:
⸮Hpxy⸮ $08⸮x$:⸮⸮
23:29:40.059 ->
23:29:40.059 -> 19
23:29:40.059 -> 20

sizeof(test[m]) is sizeof of the pointer. because you have an array of pointers, not an array of arrays. this is where array is not like pointer

but flag field consists only 1 item- I can’t use always with size of first element

the element is a pointer, not an array. (sorry, I edited the first comment, while you wrote yours)

In case of pointers- how can it be done?

you can use nested static initialized arrays like {{},{}}, or use defines or costants for the sizes

I think you are looking for a record, struct. Something like struct clock_t { int on[3]; int off[3]; bool flag; }; and then a vector clock_t clock[2] = { .... };


text:
measure very small ( negative and positve ) Voltage with Arduino
How can I measure Voltage in Range -100mv to +100mv with Arduino ,
Is that an Arduino-shield can do that ?

You need to turn it 100% positive. Make it 2.4V to 2.6V by adding 2.5V to it. Then just use the ADC.  If you like, increase the range by amplifying the signal at the same time.

@Majenko that is output from circuit , so i can't add any voltage to this output

Yes you can. You take your existing voltage and add another voltage to it. It's commonly done with op-amps. Here's examples: http://hyperphysics.phy-astr.gsu.edu/hbase/Electronic/opampvar5.html

@Majenko can I use UA471cp ? , can you draw and post the Schematic please ?

Yes, you can probably use that chip, and there are plenty of summing amplifier examples online to pick from.


text:
can I use Arduino cuurent-shield-sensor to measure very small voltage?
I want to measure very small voltage in small Range -100/+100 mv from a circuit,
can Arduino-shield ACS712 (max471) do that direkt ?

That chip is for measuring current, not voltage.

@user59015, why didn't you edit the original question instead of posting this new second question?

you want something like an ina219

You could use an opamp circuits to amplify and limit the signal to whatever range you like...


text:
Send ECG data using buffer in real time to the server without using delay
I am trying to make a ECG monitoring system using Arduino, GSM and ECG sensor which data should be sent to the private server in real time. Those data are then collected via Matlab on the remote computer and analysis should be executed in real time. When using delays in Arduino sketch GSM successfully sends data to the server but those data are sent in big delays (around 30 seconds) and the sketch doesn't send the data of the whole buffer for some reason (it should be 300 samples, but I had to try to lower that number in order to see any results). After removing delays in the loop where data should be continuously sent, GSM is not executing send data command - AT+CIPSEND. Can anybody help me fix the timer issue and explain why is not the whole buffer sent? Thanks in advance.

#include <SoftwareSerial.h>
#include <String.h>
#include "DHT.h"
int sensorPin = 0;    // set the input pin for the potentiometer
int sensorValue = 0;
#define DHTPIN A0
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

#define DHT11_PIN A0

SoftwareSerial gprsSerial(7,8);

float t; // temperature in celcius
float f; // temperature in fahrenheit
float h; // humidity

  int samplesPerBuffer = 60;
  char separator = ',';
  String buffer = "";
  int currentBufferPosition = 0;
  unsigned long startSamplingTime = 0;
  const long sampleInterval = 50;

  // gsm modem config
  String gsmBuffer = "";
  int gsmSendingState = 0; // 0 not sending, 1 preparing sending, 2 sending, 3 finishing sending
//  int gsmSendInterval = 1000;

  int gsmPreparingDelay = 200;
  int gsmSendingDelay = 1500;
  int gsmFinishingDelay = 100;
  unsigned long startRequestTime = 0;

void setup() {
  // put your setup code here, to run once:
  gprsSerial.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);    // the GPRS baud rate
  dht.begin();
  delay(1000);
  initModem();
}

float getSensorData() {
   t = dht.readTemperature();
  //Read humidity
  h = dht.readHumidity();

  // Compute temperature values in Celcius
  t = dht.computeHeatIndex(t,h,false);

  // Check if any reads failed and exit early (to try again).
  if (isnan(t)) {
    Serial.println("Failed to read temp from DHT sensor!");
    return 1;
  }

  return t;
}

void initModem() {
  // model init
  if (gprsSerial.available())
    Serial.write(gprsSerial.read());

  gprsSerial.println("AT");
  delay(1000);

  gprsSerial.println("AT+CPIN?");
  delay(1000);

  gprsSerial.println("AT+CREG?");
  delay(1000);

  gprsSerial.println("AT+CGATT?");
  delay(1000);

  gprsSerial.println("AT+CIPSHUT");
  delay(1000);

  gprsSerial.println("AT+CIPSTATUS");
  delay(2000);

  gprsSerial.println("AT+CIPMUX=0");
  delay(2000);

  ShowSerialData();

  gprsSerial.println("AT+CSTT=\"prepaidnet\"");//start task and setting the APN,
  delay(1000);

  ShowSerialData();

  gprsSerial.println("AT+CIICR");//bring up wireless connection
  delay(3000);

  ShowSerialData();

  gprsSerial.println("AT+CIFSR");//get local IP adress
  delay(2000);

  ShowSerialData();

  gprsSerial.println("AT+CIPSPRT=0");
  delay(3000);

  ShowSerialData();
}

void prepareSending() {
  gprsSerial.println("AT+CIPSTART=\"TCP\",\"website.com\",\"80\"");//start up the connection
  ShowSerialData();
}

void sendData() {
  int time = millis();
  gprsSerial.println("AT+CIPSEND");//begin send data to remote server
  String str="GET http://website.com/channel/" + gsmBuffer;
  Serial.println(str);
  gprsSerial.println(str);//begin send data to remote server
  gprsSerial.println((char)26);//sending
}

void finishSending() {
  gprsSerial.println("AT+CIPSHUT");//close the connection
}

void loop() {
 int time = millis();
 if (time - startSamplingTime >= sampleInterval) {
    if (buffer.length() == 0) {
      buffer = buffer + (String)getSensorData();
    }
    else {
      buffer = buffer + separator + (String)getSensorData();
    }
    currentBufferPosition++;
    startSamplingTime = time;
 }
 if (gsmSendingState == 0) {
   // copy buffer to gsmBuffer and triger preparing of the request
   if (currentBufferPosition == samplesPerBuffer) {
    Serial.println("GSM - Preparing sending");
    gsmBuffer = buffer;
    Serial.print("Buffer length: ");
    Serial.println(gsmBuffer.length());
    Serial.println(gsmBuffer);
    buffer = "";
    currentBufferPosition = 0;
    prepareSending();
   }

   // send data if we have something in gsmBuffer
   if (time - startRequestTime >= gsmPreparingDelay) {
    if (gsmBuffer.length() > 0) {
      Serial.println("GSM - Sending data");
      sendData();
      gsmBuffer = "";
      gsmSendingState = 1;
      startRequestTime= time;
    }
   }
 } else {
  if (gsmSendingState == 1) {
    if (time - startRequestTime >= gsmSendingDelay) {
      Serial.println("GSM - Finishing request");
      finishSending();
      gsmSendingState = 2;
      startRequestTime = time;
    }
  }
   else {
      if (gsmSendingState == 2) {
        if (time - startRequestTime >= gsmFinishingDelay) {
          Serial.println("GSM - Request finished");
          gsmSendingState = 0;
          startRequestTime = time;
        }
      }
   }
 }
}

void ShowSerialData()
{
  while(gprsSerial.available()!=0)
    Serial.write(gprsSerial.read());
    Serial.print("Temperature = ");
    Serial.println(t);
    Serial.print("Humidity = ");
    Serial.println(h);
    //delay(5000);
}

float readTemp() {
  // Read temperature as Celsius
  t = dht.readTemperature();
  //Read humidity
  h = dht.readHumidity();

  // Compute temperature values in Celcius
  t = dht.computeHeatIndex(t,h,false);

  // Check if any reads failed and exit early (to try again).
  if (isnan(t)) {
    Serial.println("Failed to read temp from DHT sensor!");
    return 1;
  }

  return t;
}

I tried with flush but it didn't resolve the problem. What I read yesterday after so much research is that the GSM module (I am using SIM900) cannot transmit more than 64 bytes with GET method, so I decided to try with the POST method, but no luck - code is returning HTTP 411 error - The request has an invalid header name. I tried some variants of resolving that problem but it didn't work. Does anyone have an ide how to resolve this? I haven't found some working example on the Internet, just some explanations which were unclear to me. The new code is below, along with the output.
/**************************************************************
 *
 * This sketch connects to a website and downloads a page.
 * It can be used to perform HTTP/RESTful API calls.
 *
 * TinyGSM Getting Started guide:
 *   https://tiny.cc/tinygsm-readme
 *
 **************************************************************/

// Select your modem:
//#define TINY_GSM_MODEM_SIM800
// #define TINY_GSM_MODEM_SIM808
 #define TINY_GSM_MODEM_SIM900
// #define TINY_GSM_MODEM_UBLOX
// #define TINY_GSM_MODEM_BG96
// #define TINY_GSM_MODEM_A6
// #define TINY_GSM_MODEM_A7
// #define TINY_GSM_MODEM_M590
// #define TINY_GSM_MODEM_ESP8266

// Increase RX buffer if needed
//#define TINY_GSM_RX_BUFFER 512

#include <TinyGsmClient.h>
#include <ArduinoHttpClient.h>
#include <SoftwareSerial.h>
#include <String.h>
#include "DHT.h"
int sensorPin = 0;    // set the input pin for the potentiometer
int sensorValue = 0;
#define DHTPIN A0
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

//SoftwareSerial gprsSerial(7,8);

float t; // temperature in celcius
float h; // humidity
String headerValue = "";

int samplesPerBuffer = 60;
char separator = ',';
String buffer = "";
int currentBufferPosition = 0;
unsigned long startSamplingTime = 0;
const long sampleInterval = 50;
String gsmBuffer = "";
  int gsmSendingState = 0; // 0 not sending, 1 preparing sending, 2 sending, 3 finishing sending
//  int gsmSendInterval = 1000;

  int gsmPreparingDelay = 200;
  int gsmSendingDelay = 1500;
  int gsmFinishingDelay = 100;
  unsigned long startRequestTime = 0;

// Uncomment this if you want to see all AT commands
//#define DUMP_AT_COMMANDS

// Uncomment this if you want to use SSL
//#define USE_SSL

// Set serial for debug console (to the Serial Monitor, default speed 115200)
#define SerialMon Serial

// Use Hardware Serial on Mega, Leonardo, Micro
#define SerialAT Serial1

// or Software Serial on Uno, Nano
//#include <SoftwareSerial.h>
SoftwareSerial SerialAT(7, 8); // RX, TX

// Your GPRS credentials
// Leave empty, if missing user or pass
const char apn[]  = "prepaidnet";
const char user[] = "mts";
const char pass[] = "064";

// Server details
const char server[] = "ekg.velizarius.com";
const char resource[] = "/71F977B8DE73/";

#ifdef DUMP_AT_COMMANDS
  #include <StreamDebugger.h>
  StreamDebugger debugger(SerialAT, SerialMon);
  TinyGsm modem(debugger);
#else
  TinyGsm modem(SerialAT);
#endif

#ifdef USE_SSL
  TinyGsmClientSecure client(modem);
  const int  port = 443;
#else
  TinyGsmClient client(modem);
  const int  port = 80;
#endif

HttpClient http(client, server, port);

void setup() {
  // Set console baud rate
  SerialMon.begin(9600);
  delay(10);

  // Set GSM module baud rate
  SerialAT.begin(9600);
  delay(3000);

  // Restart takes quite some time
  // To skip it, call init() instead of restart()
  SerialMon.println(F("Initializing modem..."));
  modem.restart();

  String modemInfo = modem.getModemInfo();
  SerialMon.print(F("Modem: "));
  SerialMon.println(modemInfo);

  // Unlock your SIM card with a PIN
  //modem.simUnlock("1234");
}

void loop() {
  SerialMon.print(F("Waiting for network..."));
  if (!modem.waitForNetwork()) {
    SerialMon.println(" fail");
    delay(10000);
    return;
  }
  SerialMon.println(" OK");

  SerialMon.print(F("Connecting to "));
  SerialMon.print(apn);
  if (!modem.gprsConnect(apn, user, pass)) {
    SerialMon.println(" fail");
    delay(10000);
    return;
  }
  SerialMon.println(" OK");

  SerialMon.print(F("Connecting to "));
  SerialMon.print(server);
  if (!client.connect(server, port)) {
    SerialMon.println(" fail");
    delay(10000);
    return;
  }
  SerialMon.println(" OK");

/*==================================================================================*/
  http.connectionKeepAlive();
  http.beginRequest();
  int codePost = http.post("/71F977B8DE73/");
//
//  DEBUG_MSG_LINE(F("Returned status after post = "));
//  DEBUG_MSG(codePost);
  http.post("url");
  http.sendHeader(F("Content-Type"), F("text/html"));
  http.sendHeader(F("Content-Length"), String(t).length());
  client.println();
  http.beginBody();
  http.println(String(t));
  http.endRequest();
/*===============================================================================*/

  // Make a HTTP POST request:
  client.print(String("POST ") + resource + " HTTP/1.0\r\n");
  client.print(String("Host: ") + server + "\r\n");
  client.print(String(F("\r\nHeader: ")) + headerValue);
  client.print(String(F("\r\n\r\n")));
  client.print(String(t));
  client.print("Connection: close\r\n\r\n");

  unsigned long timeout = millis();
  while (client.connected() && millis() - timeout < 10000L) {
    // Print available data
    while (client.available()) {
      char c = client.read();
      SerialMon.print(c);
      timeout = millis();
    }
  }
  SerialMon.println();

  // Shutdown

  client.stop();
  SerialMon.println(F("Server disconnected"));

  modem.gprsDisconnect();
  SerialMon.println(F("GPRS disconnected"));

  // Do nothing forevermore
//  while (true) {
//    delay(1000);
//  }
}

float getSensorData() {
   t = dht.readTemperature();
  //Read humidity
  h = dht.readHumidity();

  // Compute temperature values in Celcius
  t = dht.computeHeatIndex(t,h,false);

  // Check if any reads failed and exit early (to try again).
  if (isnan(t)) {
    Serial.println("Failed to read temp from DHT sensor!");
    return 1;
  }
  return t;
}

Can it be, that the GSM module has a limitation on how long the URL can be? Big data chunk are normally send via the body of a POST request, not via the URL of a GET request.

Yeah, putting data in the URL of a GET request is a bad idea. You should refactor your server API to use RESTFul conventions (send a POST with the data in the body in JSON)

Thanks for the answers. The URL of a  GET request can contain up to 2400 characters, something like that, so I think that shouldn't be a problem. My code with the POST didn't work, GSM commands couldn't have been executed for some reason.

Hook up the gsm serial port to your computer to see what the SoftSerial library is really sending to the GSM module. See if adding gprsSerial.flush() at end of sendData helps. See if switching to a different softwareserial library helps (for example AltSoftSerial). See if switching the hardware and software serial helps (use hardware serial, which is generally more reliable, for the GSM module).


text:
Voice receiver arduino
I have the following situation.
    I would like to develop a bracelet prototype that identifies when a person is on the go and also issue a question to the person for that bracelet and get an answer, depending on the status of the response by sending a notification to a mobile app. I am interested in what Arduino technologies to use.

Do you talk about speech recognition?

that's right...

You won't do that with an Arduino. There are VR and sound playing modules that you can add to Arduino, but they're crude and bulky. You won't want that in a bracelet.  You would be better looking at the K210 and MicroPython instead.

I see, but if you were using arduino, can you tell me which components would be needed?

I only want one prototype for my course work.

Some voice recognition module (which one depends on how you want it to work). Some audio playback module (which one depends on what you want to play back). Some device that will tell you if you are "on the go" (what that is depends on your definition of "on the go"). Some device that will communicate with your mobile app (which one depends on how you want to communicate). And of course an Arduino that can coordinate the whole lot.

Is there any component to check if the body is moving?

An AVR-based Arduino is woefully underpowered for something like this. It has an 8 or 16 mHz 8 bit processor without hardware floating-point support. They are too slow, have too little memory, and too little I/O bandwidth. There are some ARM based Arduino compatible boards that might be a decent foundation for something like this, but you should probably look at using a Raspberry Pi or other platform instead.

The K210 dual core 400MHz RISC-V with embedded AI processor is really what you want. You can get them as "MAix BiT" boards with MicroPython installed on them. Easy to program (if you like Python...) and does voice recognition natively. I guess they can do audio playback too if you have a DAC attached. We can't help you with them though since they're neither Arduino hardware nor using Arduino software (though there is Maixduino to allow you to program using the Arduino IDE...)

Isn't the Sparkfun EasyVR 3 Plus Shield exactly what you want? https://www.youtube.com/watch?v=z5Fgraby1Rk

@MaximilianGerhardt That's fine for doing the VR side of things if an Arduino is chosen, but like I said... bulky... and prototyping bulky with no prospect of shrinking it (how would you shrink that?!) is not good. Start small (though on a big board) and go from there. A MAix BiT module with built in ESP8266 could be good (if WiFi is wanted) for the final product, and a MAix BiT board for prototyping.

Instead of letting the end concept run the project into the ground due to extreme complexity, why not consider alternative user interfaces better suited for an Arduino.  OTOH, consider almost any Android phone contains the hardware you are looking for (accelerometer, microphone, speaker) and would be much smaller than an Arduino with a battery and a few shield boards mounted on it.

@DarlanCandiotto, would you be interested in a solution that does not involve voice recognition or speech play back?


text:
Nano can't get reply from ENC28J60 Ethernet Shield
My Arduino Nano can't get a reply from my new ENC28J60 Ethernet Shield - I can't get any library examples to work. Using the UIPEthernet lib, and running the EchoServer example with logging turned up, I get:
ENC28J60::init DEBUG:csPin = 10
ENC28J60::init DEBUG:miso = 12
ENC28J60::init DEBUG:mosi = 11
ENC28J60::init DEBUG:sck = 13
ENC28J60::init DEBUG:Use Native hardware SPI
Enc28J60Network::writeOp(uint8_t op, uint8_t address, uint8_t data) DEBUG_V3:Function started
ENC28J60::init DEBUG_V3:Before readOp(ENC28J60_READ_CTRL_REG, ESTAT)
Enc28J60Network::readOp(uint8_t op, uint8_t address) DEBUG_V3:Function started
...

so it gets nicely into the Enc28J60Network::init function. But shortly after, it does a phyWrite, tries to read a response, and then times out.
ENC28J60::init DEBUG_V3:Before phyWrite(PHCON2, PHCON2_HDLDIS)
Enc28J60Network::phyWrite(uint8_t address, uint16_t data) DEBUG_V3:Function started
... lots of attempts to read
Enc28J60Network::phyWrite ERROR:TIMEOUT !!

And then it all starts to fail, and it never gets better. I tried the EtherCard lib, too, and it fails in a similar way.
I put the scope on the SPI pins, and I see reasonable stuff: activity on SCK and MOSI, nothing on MISO, and the SS (pin 10) switching ok - and the shield claims to use pin 10 (I briefly tried pin 8 as I flailed in confusion, but no luck there either).
So at this point, either I'm misunderstanding something, or the shield is DOA.
Update: Earlier, I strongly suspected the SCK line because it showed a very poor signal on my scope. But it turned out to be poor grounding on the scope probe, and the signal  was actually fine, a red herring. Thanks to @Majenko for drawing my attention to it.
Update 2: After getting no SPI response from the shield under any circumstances, my working hypothesis is that it was DOA. I've gone back to my UNO with W5100: all working fine. I have ordered more Nano ethernet shields, to arrive in a week or two, so I'll try with those, and provide updates/answers then.

How much bandwidth does your scope have? That looks awfully low resolution, and the kind of output I'd expect on a scope with not enough bandwidth to display the waveform correctly.

is ethernet cable connected?

@Majenko good point - and thanks for the pointer. I'd not earthed the scope probe  properly, so fixed, and the SCK line looks perfectly fine now. D'oh, beginner's mistake. I'll edit it out of the question.

@Juraj yes, all connected - and I get a little green light on the shield and on the hub, so I think it's all good there.

How much current can your 3.3V supply to the ENC28J60 Ethernet Shield? The data sheet says it uses 120mA when it's "Active, not transmitting Ethernet packets". Up to 180mA is required when it's "Transmitting Ethernet packets".

@VE7JRO oh I never thought of that... I've spent a whole day trying to .... :-) ok, checking now ...

@VE7JRO Your suggestion seems to be backed up by this discussion: https://forum.arduino.cc/index.php?topic=452822.0 ... I couldn't find anything much to test: my nano's 3.3V pin is stable, but that might be because the shield isn't drawing power when it sees the supply so weak. I'm now building an independent 3.3V supply...

@VE7JRO I've just hooked a 3.3V 2A supply up to the Nano's 3.3V line to give it more juice - no change. I think it's ok to just wire the power straight up to it, even though the 3.3V line is nominally an output (am I right?); I believe I'll definitely need to augment it anyway, but I'm starting to feel the shield is DOA. I wonder if running it with weak power killed it....? seems a bit feeble if it did.

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

Perhaps this could bring some solution. https://www.mikrocontroller.net/topic/477142

@Riad what happened to your nice answer?

@Riad My shield matches the one on that forum and has the miscreant connection. I haven't tried fixing it because it's hard and I have other shields now. But I have high confidence that this is the answer. If you want to take credit, please write an answer; otherwise I shall do so myself.

Thanks to @Riad, who posted this as a comment. The problem appears to be a design fault in the "DK ectronics" V1.0 Ethernet Shield.

Perhaps this could bring some solution. https://www.mikrocontroller.net/topic/477142

The site is in German, so here's a brief translation of the key parts:

I bought an ENC28J60 for the Arduino Nano, but it does not respond from the programmed IP.
The shield has "NANO Ethernet Shield V1.0 DK ectronics" inscribed on the underside (spelling error in the original). There
  there is a via on the bottom between pins D11 and D12,
  missing from a (different) working shield. This via connects D12 line to GND from the AMS1117 on the top (easy to check D12 to GND with a multimeter). If that's the case with your shield, then this is the problem: we just have to cut out the via connection. I have
  Do this with a 1mm drill by placing the top copper layer in the
  via very gently (really gently!) Mill it away. If you drill too deep, you break the D12 connection completely and must possibly
  solder on a new wire. Keep checking D12 and GND for continuity to see whether you've milled away enough. Work really carefully!
After I did that, and tried the TCP Server example in the UIPEthernet
  library on the Arduino, the shield was reachable.
-- Christoph K

I haven't yet tried to make the changes described above, because they are fiddly and I have a new batch of working shields. But my device is exactly as described by Christoph and his photos, and the fault description matches mine.

The ENC28j60 shield for Nano has reset of the ENC28j60 chip on the pin 7 of the shield/Nano. Try to set the pin 7 HIGH.

If this solves it, it would be hilarious... ok, will try it at the weekend - alas I'm away atm. So, I just have to add: pinMode(7, OUTPUT); digitalWrite(7, HIGH); on setup? Hmm, I wonder why the UIP/EtherCard library examples don't have this. Perhaps the reset is non-standard, or there's a (too) weak pull-up?

@SusanW, did it help?

no it didn't, I'm afraid - I added pinMode(7, OUTPUT); digitalWrite(7, LOW); delay(1000); pinMode(7, OUTPUT); digitalWrite(7, HIGH); just to give it the best chance possible, but it still times-out on read and the MISO line is silent. Which is annoying, because what you suggested would be the perfect answer - and on reading around, it appears the pin-7 reset is an under-publicised feature. Anyway, I've ordered some more shields which should arrive any day, so I'll be able to eliminate board failure as a factor. I'll keep you posted... Thanks!

@SusanW, do not reset it. only set the pin HIGH. do it as first in setup().

Yep, I tried that first ....

Ok, new shields turned up - and worked first time. We have pings and TCP. And ironically, it works even without me setting pin-7 high. The other board must be dead. Hmm ... would you like to add that as an "alternative explanation" to your answer, or something, then I can mark this as the accepted answer. (I could add/accept an answer myself saying "Board was dead", but that would hide your more useful answer!)

@SusanW, at least you know you can not use the pin 7 or you must bend it on shield to use it on Nano. Or you can use it as reset of the shield, but I didn't find it useful with module I have.

It works if pin 7 is input on Nano, because the reset pin of the ENC28j60 has a pull-up.

I've written up an answer based on Riad's link about faulty ethernet shields, which matches the problem I had. But I feel bad because your answer is informed and helpful. If there's a better way to get the "Susan bought a rubbish board off eBay" explanation out there, do let me know! Thanks.


text:
How to debug Arduino using Atmel studio?
I have an Arduino Yun board and an Atmel ICE programmer/debugger. There are 6 pins on the Arduino Yun to connect to Atmel ICE for programming only, but I can't find the pins for debugging. Anyway to do so? Which pins on the Arduino should I connect to Atmel ICE?

Use the same pins.

https://www.avrfreaks.net/forum/atmega32u4-jtag-debug

Possible duplicate of Using Atmel Studio 7 to program Arduino Uno

I found another very easy way to debug the arduino board with atmel studio without even using an external debugeer like the atmel ice debugger. It's an extension called vMicro which can be added within atmel studio (visual studio as well) you connect the arduino board over the micro USB to the computer and specify the parameters in the vMicro toolbar in atmel studio and that's it!
 It's ready to debug! Finally I think atmel ice is thought for other boards maybe, since debugging can be done without it easily!


text:
5 minute timer output time remaining
I am trying to create a timer that outputs the time remaining in minutes. I am using an Adafruit Circuit Playground Express.
For example, if the timer is 5 minutes, then every minute it should output the time remaining, until the time ends.
5 minutes timer started.
Delay: 5 minutes
Delay: 4 minutes
Delay: 3 minutes
Delay: 2 minutes
Delay: 1 minute
This is my attempt to implement this. I would like it to start by displaying  "Delay: 5 minutes"; however, this is not output until 1 minute has passed.
What am I doing incorrectly?
const long interval = 1 * 60 * 1000UL;
unsigned long previousMillis = 0;
int minutes = 5 ;

 unsigned long currentMillis = millis();

  while (minutes >= 0){
  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    Serial.print(F("Delay: "));
    Serial.print(minutes);
    Serial.println(F(" minute(s)"));
    minutes = minutes - 1;
  }
  }

it does not output the correct remaining time is not a useful description of the output .... it would be much more useful if you say what the output actually is

Also, h ow is previousMillis defined and initialized?

Same question was asked and is being discussed here  https://forum.arduino.cc/index.php?topic=632900.msg4285177#msg4285177

why are you posting your question here? ... the Arduino forum is giving you good suggestions

Try this: (I don't have an Arduino here so i can't test it)
int minutes = 5;
int passedminutes = 0;
void setup() {
 Serial.begin(9600);
}
void loop() {
  while((millis() - minutes*60000) < 0)
  {
    if(millis()%60000 == 0)
    {
      Serial.print("Remaining Time: ");
      Serial.println(minutes-passedminutes);
      Serial.println();
      passedminutes++;
      delay(1);
    }
  }
}

millis()%60000 is fragile, because the millis() counter skips some values. Roughly one every 42 values.


text:
Problem with powering ublox NEO-6M GPS module
Firstly, I'd like to mention that I'm a beginner. This is the first time I've worked with a GPS module. The serial monitor is completely empty when I upload the following code to my circuit:

#include <SoftwareSerial.h>

// The serial connection to the GPS module
SoftwareSerial ss(4, 3);

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

void loop(){
  while (ss.available() > 0){
    // get the byte data from the GPS
    byte gpsData = ss.read();
    Serial.write(gpsData);
  }
}

Things I might've done wrong and some things I'd like to mention:

As you can see, I connected the module to 5V pin of Arduino but the datasheet says:

The reason why I think this might not be the case is that there are multiple projects on the internet that have used a circuit like mine.
I've placed my module on the window edge so that it can get a good line of sight. I'm yet to try it outdoors.
After reading the datasheet, I tried a potential divider using resistors to get 3.3V and the result is still nothing. I later realized that this was probably a really silly thing to do since I created an unstable supply which is not suitable for the module.
For cold-start conditions, how long can it take to lock to a satellite? I've waited several times for half an hour each time only to get no result in the end. Can it take more than that? Should I wait?
What can I use to supply constant 3.3V to the module? Are there any special power supplies for GPS modules?
Is it possible to tell if my module is damaged just by seeing?

The module may very well be dead now, due to giving it 5V.

But depending on which board the module is mounted on, there might be a voltage regulator that expects 5V. Check the specifications for the board you bought.

A window means that at least 50% of the sky is blocked by the building. The module might not be able to get a signal from enough satellites for a cold start.
A voltage divider only works if there is constant current. As you've noted, you just created an unstable power supply.
The datasheet says 27 s but that is probably with a clear view of the sky.
Next to the 5V pin on the Uno is a 3.3V pin. How about using that?
Visually, no. But the Arduino should be able to communicate with the module if the module still works, regardless if the module has a GPS fix or not.

I've tried that too, forgot to mention. Also, could you please say something about the other points in my question as well?

Tried that after I had initially used the 5V pin.

"But depending on which board the module is mounted on, there might be a voltage regulator that expects 5V. Check the specifications for the board you bought." I know this is a really dumb question but how do I do that?

If the store where you bought the module knows what they sold to you, you could get the information form them. If the store does not know, and you do not now, you're in for quite some detective work.

"But the Arduino should be able to communicate with the module if the module still works, regardless if the module has a GPS fix or not." Does that mean that the serial monitor for the code I uploaded should not give empty output?

That depends on which module board you have, and if it was correctly wired. But yes, the code should give output similar to page 2 in https://www.terraelectronica.ru/pdf/show?pdf_file=%2Fz%2FDatasheet%2FU%2FUART+GPS+NEO-6M+User+Manual.pdf


text:
Getting wrong value from sd card
I stored "28328630" in sd card but at output i getting wrong value.
on serial "5566" getting this value.

#include "HX711.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <SD.h>
int data = 0;
int curr_rate = 0;  // current flow rate in L/M

File dataFile;
HX711 scale(A1, A0);
LiquidCrystal_I2C lcd(0x3F, 16, 2);  // set the LCD address to 0x27 for a 16 chars and 2 line display
const int buttonPin = 8;
int total;
int buttonState = 0;
void setup()
{
  lcd.init();
  lcd.init();
  lcd.backlight();

  lcd.setCursor(0, 0);
  lcd.print("KWALITY PVT.LTD.");
  Serial.begin(38400);

  while (!Serial)
  {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (!SD.begin(4))
  {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    // return;
  }
  Serial.println("card initialized.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt"); //<<<<<<<<<<<<<< set the name

  // if the file is available, write to it:
  if (dataFile)
  {
    while (dataFile.available())
    {
      Serial.write(dataFile.read());      //<<<<<<<<<<<<< remove
      total = total + dataFile.parseInt();  //<<<<<<<<<<<<<<<< new
    }
    lcd.clear();
    dataFile.close();
    Serial.print("Total: ");
    lcd.setCursor(0, 1);
    lcd.print("Total:");
    Serial.println(total);
    lcd.setCursor(6, 1);
    lcd.print(total);
    Serial.print("Value in sd card 28328630....");
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening file");
  }

  scale.set_scale(2280.f);
  scale.tare();

}

void loop()
{
  buttonState = digitalRead(buttonPin);
  dataFile = SD.open("datalog.txt", FILE_WRITE);

  if (buttonState == HIGH) {

    if (scale.get_units() > 10 && scale.get_units() < 200)
    {

      //SET1
      lcd.setCursor(0, 0);
      lcd.print("LPM: ");
      lcd.setCursor(5, 0);
      data = (scale.get_units() / 10);
      lcd.print(data);
      scale.power_down();
      delay(5000);
      scale.power_up();

    //  scale.power_down();
      delay(60000);
     // scale.power_up();
      lcd.clear();

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

      curr_rate = (data + total);
      Serial.print("Total: ");
      lcd.setCursor(0, 1);
      lcd.print("TOTAL:");
      lcd.setCursor(7, 1);
      lcd.print(curr_rate);

    }
    else
    {
      lcd.setCursor(0, 0);
      lcd.print("LPM: ");
      lcd.setCursor(5, 0);
      lcd.print("000   ");
      delay(500);
      lcd.print("        ");

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

    }
  }
  else {
    lcd.setCursor(0, 0);
    lcd.print("     SENSOR    ");
    lcd.setCursor(0, 1);
    lcd.print("  DISCONNECTED  ");
    delay(2000);
    lcd.clear();

  }

}

2 bytes type int can only hold numbers from -32,768 to 32,767. but you have more  issues in you code

https://forum.arduino.cc/index.php?topic=632947.0

i replaced int with long int, on output i get

Total: 8328630
Value in sd card 28328630....

the Serial.write(dataFile.read()); stole the 2 and wrote it as invisible character

you have a lot of unnecessary code in your sketch that has nothing to do with writing to SD card ... reduce your sketch to only write 28328630 and read it back


text:
How come some Arduino Nano pins (D3, D4, A3, A4, A6, A7) cannot be set high?
I made a sketch to switch on all digital and analog pins, and found out several pins did not work as expected. Note: I manually put a jumper wire from each digital and analog pin (one at a time) to a resistor, LED and GND pin.
What I noticed was that some pins did not work (D3, D4, A4, A6 and A7) and pin A3 was only lit about half intensity. I tried two different Nanos and they performed both equally (also pin A3 at half intensity).
I also tried the jumper wires directly touching the pins (without a breadboard in between, to rule out a breadboard problem). Same behavior (so the breadboard is ok).
My questions:

How come pins D3, D4, A4, A6 and A7 are not output VCC (3.3V) ?
How can I switch pins these pins on?
What is the reason pin A3 is blinking at half intensity?
How can I switch this pin fully on?
Bonus question: I used numbers, why are the pin names A0..A7 and D0..D12 not defined in Arduino IDE?

Test sketch:
const int NR_OF_PINS = 22;

int pins[NR_OF_PINS]   =
// 0  1  2  3  4  5  6   7   8   9  10 11   12  13  14  15  16  17  18  19  20  21
//D0 D1 D2 D3 D4 D5 D6  D7  D8  D9 D10 D11 D12 D13  A0  A1  A2  A3  A4  A5  A6  A7
 { 1, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26 };

void setup()
{
  for (int n = 0; n < NR_OF_PINS; n++)
  {
    pinMode(pins[n], OUTPUT);
    digitalWrite(pins[n], HIGH);
  }
}

void loop()
{
}

A6 and A7 are analog only on classic Nano. 3.3 V on Nano?

Also D0 is pin 0, not pin 1.  Why are you bothering with an array?

@Juraj Ok, thanks, but the other analog pins work (except A3 partly).

your array is wrong. A0 is 13

@Majenko Yes, I accidentaly switched D0 and D1, I need an array because I want to use them in a loop (not for my test program but in my real program).

you use pin numbers not valid for Nano, you skip D3 and D4

@Juraj Yes I now notice that the numbering is already built in the functions pinMode and digitalWrite.

@Juraj I used this table: http://www.circuitstoday.com/arduino-nano-tutorial-pinout-schematics  there A0 is 19.

that are pins of the PCB. sorry A0 is 14. https://github.com/arduino/ArduinoCore-avr/blob/7a2e1cd815266fef3012a5c9b48f88d78551f838/variants/standard/pins_arduino.h#L56

@Juraj Thanks (nice that the built in LED has its own separate 'pin' )

@MichelKeijzers, with what Arduino board did you work until now? Because Nano is really only a small Uno.

You don't need an array, and your "base" pin is wrong - you start at pin 1, not pin 0. Also pins A6 and A7 can only be analog inputs, not digital outputs.
It's simpler to write:
void setup() {
    for (uint8_t i = 0; i < NUM_DIGITAL_PINS; i++) {
        pinMode(i, OUTPUT);
        digitalWrite(i, HIGH);
    }
}

void loop() {
}

That will work correctly on all Arduino boards regardless of the number of pins, since the board definition defines how many pins there are, and pins are always contiguously numbered from 0.

Thanks for the answer (btw, as a side question, I noticed there is not a NUM_ANALOG_PINS declared). Why not? (and also I thought analog pins could be used as digital pins, but not the other way around).

It's defined as NUM_ANALOG_INPUTS not NUM_ANALOG_PINS.

And the NUM_DIGITAL_PINS incorporates all the analog pins that can be digital inputs and outputs.

thanks (quite confusing to be honest, but at least now it's more clear). However, I rather have it this way... initially I thought my soldering work was a mess ;-)

https://arduino.stackexchange.com/a/36683/37523

@MichelKeijzers Well, an analog input may not be a physical pin. There are chips around that have temperature sensors (for example) built in that connect to the ADC MUX - so an analog input exists that connects to that sensor, but it doesn't have a "pin" as such - so calling them analog pins is a misnomer.

@Majenko ok clear (and sounds logical), I just have Arduino's and STMs ;-) ... Btw, just tested and in NUM_DIGITAL_PINS are all digital pins and analog pins [A0..A5] Pins A6 and A7 are analog only (or at least not in the range of NUM_DIGITAL_PINS).


text:
ESP8266-01 Does not receive or respond to AT Commands
I have an ESP8266 wifi module that I want to test, to use it later. I uploaded the original Espressif AT firmware "ESP8266 AT Bin V1.7.0" from: https://www.espressif.com/en/support/download/at.
FTDI seems to be connected to the ESP all properly, since firmware upload successfully finished and prompted:

Leaving...
  Hard resetting via RTS pin...

I use the Arduino IDE's serial monitor at 115200 baud rate set to "both NL & CR", to send the commandS "AT", "AT+GMR" e.t.c.
No response ever returns. I have no idea about what am I doing wrong, or why esptool.py can connect to the board smoothly but there is a problem with sending AT commands to it.
Thanks for all suggestions in advance. Please comment if you need any other information about the issue.
P.S: I have two modules bought at different times. Both of them wont work with AT commands.

Try 76800 baud rate - A couple of my esp boards needed this - You can change the rate permanently if needed

how did you flash it? the bin on the Espressif download is for 2MB module (yes, strange). Flash Download Tool can upload it right to 4 MB module, but esptool can't. and how do you power the module?


text:
Determing approximate bicycle speed for distancemeter
I'd like to build a self-contained bicycle distancemeter similar to those now used by local police, i.e. that measure and display the distance between the bicycle handlebar's end and passing cars and beep when distance is less than 1m on 50-km/h roads. In order to avoid detecting cars when stopped at traffic lights, I need to determine whether the bicycle is moving above a minimum speed, say 10 km/h. How can I do that without having to install additional hardware on the bicyle, like a magnet on the wheel and a sensor on the fork? Accelerometers?

GPS is probably simplest.

Accelerometers are not a good choice for this, since they output nothing on constant speed. Like Majenko wrote, GPS is the simplest

Many GPS modules will directly report your ground speed to you.

I have built many years ago a device nearly identical to what you describe. I did not have the additional requirement of a minimum speed of 10 kph, however. As noted in the comments, that is likely best resolved with GPS as you are detecting motion, not absolute speed figures.
I used "arduino gps library" as the search terms and found many options. One of them, TinyGPS++ appears to have what you require and much more:

TinyGPS++ is a new Arduino library for parsing NMEA data streams
  provided by GPS modules.
Like its predecessor, TinyGPS, this library provides compact and
  easy-to-use methods for extracting position, date, time, altitude,
  speed, and course from consumer GPS devices.
However, TinyGPS++’s programmer interface is considerably simpler to
  use than TinyGPS, and the new library can extract arbitrary data from
  any of the myriad NMEA sentences out there, even proprietary ones.

I would definitely appreciate the "considerably simpler" aspect, as well as the "extract arbitrary data" portion, which seems specific to your project.
There may be other libraries that provide your objective, this was the first on the search returns.
The device I constructed used the common ultrasonic detector with a transmitter and receiver pair, coupled to a set of seven-segment LED display blocks. When the slightly-less-than-one-meter distance was presented, my device would trigger a pair of cameras. For your beep purpose, it would be straight-forward to redirect the camera trigger to a piezo speaker module or any other suitable audio device. I did not require GPS or other speed information.

I realize I already own a self-contained matchbox-sized USB-rechargeable Bluetooth GPS from Globalsat. So it's just a matter of getting a Bluetooth shield or a Bluetooth-equipped Arduino board.

I like your idea of the camera. I gather I then need an SD shield to store photos. No Arduino board has all that?

The cameras I used were off-the-shelf point-and-shoot digital cameras made by Canon. They support CHDK modifications which allow for remote shutter release. I'm unfamiliar with SD/Arduino/cameras.

GPS would be simple in terms of being self-contained, but a GPS module is somewhat expensive, and is also a big power drain.
I'd recommend a wheel sensor. Some modern wireless bike-computers use accelerometer based wheel RPM sensors. You attach them to the spokes and they detect the motion with/against the force of gravity as they travel up and down. They use wireless communication like BLE (Bluetooth Low Energy.) If you added a BLE module to your Arduino you might be able to pair it with a wireless RPM sensor and measure speed that way, with no wires or magnets needed.
EDIT:
I don't know for sure what wireless protocol these accessories use. If it's not BLE then interfacing them with an Arduino might be harder.

Are you sure bike computers use BLE and not some custom wireless link, or ANT, which is not BLE.

No, I don't know which wireless protocol they use. That's why I said "wireless communication LIKE BLE."  I guess I should have been clearer on my lack of specific knowledge."


text:
How to access variables by variable? (I.e. variable variables?)
Can Arduino handle variable variables?

function getLetterCode(char input) {
    int letter_a = 17;
    int letter_b = 42;
    int letter_c = 50;
    return letter_$$input$$; //pseudocode
}

This is just a stripped down code to demonstrate my question. I am aware of arrays, the switch structure and other workarounds, but for my specific need variable variables would save tons of typing.

it would be limited, but you could try using an array with a char index, which is basically a byte ... letter['a']

No, you can't do that sort of thing. That sort of thing is only possible on interpreted languages where the name of the variables is seen at runtime.  In compiled languages you can't see the variable names (they no longer exist) so you can't access them by name like that.
Instead you need to either store your variables in a simple array and access them by index, or create an array of "key/value" pairs (simplest to use an array of a struct) and iterate it looking for the right key to match with your input.  Or, if there aren't too many inputs, simply use a switch to select different values:
int getval(char input) {
    switch (input) {
        case 'a': return 17;
        case 'b': return 42;
        case 'c': return 50;
        default: return 0;
    }
}

Thanks! I just realise how much I am used to those high level languages.

I know. It's not even as if you can use Map in Arduino - the STL is seriously lacking...

Point of order: You could also do it in a compiled language with dynamic dispatch (e.g. Smalltalk or Objective-C.)

@DuncanC I don't count those as real languages.

@Majenko well that's silly. Smalltalk is the mother of all Object-oriented languages. So Python is a real language but Smalltalk isn't?

Python? That steaming heap of rancid badger vomit?!