text:
Can I get some help with a metronome code on my arduino uno?
ok so I dont actually know anything about coding or electronics outside of being an electrician. This is something i've been working on for about a month.
I may be asking something dumb but here it is.
also i dont know where to put my code so ill put it in the comments (sorry).
so basically I want a visual metronome. I want to plug a control box into the wall, plug a lamp into the control box to blink at a set interval. the box will have a rotary encoder and lcd display to control the beats per minute. to achieve this im gonna use a SSR and some transformers to achieve a variety of voltages for different led lights. but I want to affect a 120v cct to do it all. but I just want to get the code down before I build it so im trying to blink the onboard led on my arduino uno for now.
I have the code, which is 3 different sketches, frankensteined together. probably poorly.
I added an arithmetic equation to facilitate the metronome timing but I cant transfer that value to the "interval" for the blinking light.
In my serial viewer, the equation works and it gives me the values I desire. I just cant get that into the interval.
the math equation is simple
(60/bpm)1000 = intended interval
example: (60/120)1000 = 500 as the milli interval for the blinking light. 2 blinks per second.
enter code here

// rotary encoder -----------------

int val;
int encoder0PinA = 6;
int encoder0PinB = 7;
int encoder0Pos = 59;
int encoder0PinALast = LOW;
int n = LOW;

// lcd screen ---------------------

     // include the library code:
#include <LiquidCrystal.h>

     // initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// led blink ----------------------

     // the number of the LED pin
const int ledPin =  LED_BUILTIN;

     // ledState used to set the LED
int ledState = LOW;

     // will store last time LED was updated
unsigned long previousMillis = 0;

     // interval at which to blink (milliseconds) --    long interval = ;

// mathssss -----------------------

float a = (60 / encoder0Pos) * 1000;

// on to setup -------------------------------------------------------

void setup() {
      // put your setup code here, to run once:

// rotary encoder ---------------
 pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
  Serial.begin (9600);

  Serial.println ("hi");

// lcd screen -------------------
      // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
      // Print a message to the LCD.
  lcd.print("BeatsPerMinute");

// led blink -------------------
pinMode(ledPin, OUTPUT);

}

// on to loop --------------------------------------------------------
void loop() {
      // put your main code here, to run repeatedly:
      long interval = (60.00 / encoder0Pos) * 1000;

// rotary encoder --------------
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    if (digitalRead(encoder0PinB) == LOW) {
      encoder0Pos--;
    } else {
      encoder0Pos++;
    }

     // serial ----------------------------------------------------------------------
  Serial.println ("BPM");
  Serial.println (encoder0Pos);
  Serial.println ("interval");
  Serial.println (interval);
  Serial.println ("intended interval");
  Serial.println (60.00 / encoder0Pos * 1000, 8);
  Serial.println ("----------------");
     // serial done -----------------------------------------------------------------
  }
  encoder0PinALast = n;

  // lcd screen ----------------

       // set the cursor to column 0, line 1
       // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
       // print the number of seconds since reset:
  lcd.print(encoder0Pos);

  // led blink -----------------

    unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    digitalWrite(ledPin, ledState);

 // serial --------------------

 // done

  }

}

oh no where do i post the code?

Post your code in your question. Copy and paste it, then select the code and press the {} button to format it.

im clearly not formatting the code correctly in this forum. I copy it, then click the dual squiggly brackets and then paste?

No. You copy.  Then you paste. Then you select (highlight your pasted code). Then you press {}.  It should indent all your code 4 spaces.

And why don't you just set the interval varaible with your math formula? Something like interval = <math formula>

as in interval = a?
i tried that and so many other combinations but it just doesnt work

it says 'a' was not defined in this scope. I tried looking up what that meant, and I thought I resolved the issue by putting the arithmetic statement in the beginning of the sketch to make it a global value, but I still get an error message.

so through the help from others on this site I managed to do what I wanted however the interval is one iteration behind the actual value. so if im stepping the encoder up to 120, the value at 119 is 504, and the value at 120 is 500 and so on. the problem is the value shown by the interval is one step behind, so at 120 the value still reads 504, and 121 the value reads 500 and so on.

As I wrote in my comment, you don't actually set the value of interval to the new value, when the encoder position changes. So the blinking interval does not change. You need to use the formula to set the new value to interval. Insert
interval = 60.00 / encoder0Pos * 1000;

before your Serial.print() statements. Also, you need to remove the const keyword at the definition of interval, or you won't be able to change it's value.

Judging from your comments, you misunderstand how variables work. A variable does not save a formula, just a value. a is defined at global scope in your code (outside of any function). That means, that the definition get's executed at the very start of the program. Since encoder0Pos has the value 59 at that time, the value 1016.95 get's assigned to the variable a. This value only ever changes, if you actively assign a new value to that variable (which you never do). The formula is only executed once during the assignment.

ok I think im understanding, ill edit the post to update the code,  but if im understanding you correctly, ive already tried this and it still doesnt give the result i want. how do Ihave variable 'a' change with the encoder reading?
also, I tried adding the
interval = 60.00 / encoder0Pos * 1000;
above the serial.println's but  I got an error message

ok I also added the formula above the serial.println section.
that has provided me with the correct value being returned from the interval in my serial viewer! thats great! but its not affecting the rate of blink of the led still. I updated the code in the OP.

ok I got it. thank you very much for your help!
the math doesnt stay true into the higher values, past around 200 bpm but it will certainly work for my purposes!


text:
Sending more than BUFFER_LENGTH(32) bytes in slave answer I2C
I need to send 259 bytes as answer to I2C master read request. AFAIK there is a buffer limit of 32 bytes in Wire.h and in HW (Arduino Nano). Is there a way sending 259 byte answer, or I have to choose another HW?
The code is:
void serveInitCommunication() {
  Serial.println("serveInitCommunication()");
  static unsigned int counter = 0;
  auto answer = findInitAnswer(counter);

  uint8_t buffer[260]; //maximum size from dataLengths[] in comm_init_data.h
  memcpy_P(buffer, answer.dataPtrProgmem, answer.dataSize);

  Serial.print(" dataSize:");
  Serial.print(answer.dataSize);
  Serial.print(" data:");
  Serial.println(int(buffer[answer.dataSize - 1]));

  auto bytesToWrite = answer.dataSize;
  uint16_t bytesWritten{0};

  while (bytesToWrite > BUFFER_LENGTH) {
    Serial.println("Write part");
    Wire.write(buffer + bytesWritten, BUFFER_LENGTH);
    bytesToWrite -= BUFFER_LENGTH;
    bytesWritten += BUFFER_LENGTH;
  }
  Serial.print("Bytes written:");
  Serial.print(bytesWritten);
  Serial.print(" Bytes yet to write:");
  Serial.println(bytesToWrite);
  Wire.write(buffer + bytesWritten, bytesToWrite);

  counter++;
}

And called is it:
void requestHandler() {
  char buff[100];
  sprintf(buff, "requestHandler addr:0x%x counter:%d", readAddress, msgReadCounter);
  Serial.println(buff);

  if (readAddress == INIT_MSG_ADDRESS) {
    serveInitCommunication();
  }
}

I've tried moving the serveInitCommunication() into void loop() and setting a just a flag in requestHandler() but without success. Sending up to 32 bytes works fine. Tnx
update: uint8_t twi_transmit(const uint8_t*, uint8_t); so twi library self limit data to 255 bytes
update2: there is a hacker way doing it, by replacing the twi.c twi_txBuffer and twi_txBufferLength with buffer from the sketch

The limitation is purely in software. The I2C hardware has a limit of one byte at a time, and the software creates a 32 byte buffer and feeds each byte from that in turn.
While it would be perfectly possible to increase that buffer size, you may find you have other problems when you get above 255 bytes, since lots of parameters and internal variables for the library are limited to 8 bit values.
It would also be considered very "hacky" since you can't easily upgrade the Wire library in future.
A better strategy would be to split your data into chunks and make multiple requests, each one saying "Give me chunk number ..." and then recombine them upon reception.

I have to communicate with existing HW. For now I've passed the data pointer and data size from the sketch into twi.c and using it directly. A "hacky" way indeed. However I'm hoping there is some standard way doing that.

Not using Arduino software, no. It's not designed for that kind of amount of data. Neither, really, was I2C...

source: Stack Exchange

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

sort: votes


text:
Unable to find/connect I2C devices (SHT31 & SGP30)
I have recently purchased an Arduino Nano 33 IOT together with two sensors:

Adafruit SHT31-D (https://learn.adafruit.com/adafruit-sht31-d-temperature-and-humidity-sensor-breakout)
Adafruit SGP30 (https://learn.adafruit.com/adafruit-sgp30-gas-tvoc-eco2-mox-sensor/)

However, so far I have not succeeded in reaching any of these two sensors. For example I connect the SHT31 sensor like this:

+3.3V to Vin
GND to GND
A4 to SDA
A5 to SCL

I have tried the default Adafruit  SHT31-D example without success, the program appears to hang. I have tried a standard I2C scanner but it does not find any devices with the sensor connected. When the sensor is disconnected, it does find two devices (the IMU and something else I guess).
I believe there is something funky going on with the I2C connection of the internal sensors and the external ones but I have no idea how to troubleshoot this issue. I read some stuff about TwoWire (extern TwoWire Wire1; after the #include) but I am having a hard time figuring out if this is what I need and how to implement it.
I found these topics myself:
https://forum.arduino.cc/index.php?topic=639188.0
https://forum.arduino.cc/index.php?topic=658967.0
edit: I haven't had success dealing with these issues so far and I am still looking for some help with my problems!

Did you try to use Arduino Uno (or similar) with these sensors? Nano 33 IOT is a little bit different compare to Uno (and similar) boards. That will verify if your sensors are fine or not.

one can code an I2C sensor (I'm using a SHT31) using custom GPIO ports like so:
    //I2C Bus Pins
    #define SDA 8
    #define SCL 9

    #include "Adafruit_SHT31.h"
    TwoWire I2Cbus = TwoWire(0);
    Adafruit_SHT31 sht31 = Adafruit_SHT31(&I2Cbus);

    void setup(){
      Serial.begin(115200);            // USB communication with Serial Monitor
      Serial.print("Starting serial...");

      Serial.print("Starting SHT31...");
      startSHT();
    }

     // ********************************************************
     void startSHT(){
      I2Cbus.begin(SDA, SCL, 100000ul);
      if (! sht31.begin(0x44)) { // Set to 0x45 for alternate i2c addr
         Serial.println("Couldn't find SHT31");
         while (1)
         delay(1);
      }
    }

I had a similar problem, but the fix turned out to be simple. All the tutorials for SHT3x sensors say to connect the VIN to the 3.3V GPIO. I checked using a test meter, the SHT3x was getting voltage but numerous SH3x libraries didn't seem to work, and a couple of I2C sketches also found nothing. So I tried moving the VIN lead to the 5V GPIO pin - it works perfectly. Perhaps my USB connection lacks enough power, or perhaps my SHT3x needs 5V. Either way it
works - happy now !

Without a schematic I will take a SWAG" For I2C to work it needs a pull up resistor for SCL another for SDA. Both are open drain/collector outputs neither of which can drive a + (logic 1) on the bus.

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


text:
Noise on piezo analog read due to Arduino power supply
I am making a device that measures temperature and vibrations and records the values onto an SD card. It will be a standalone device.
The hardware used:
- Arduino Uno
- PCF8523 RTC clock
- MAX3186 + PT100 RTD temperature sensor
- Adafruit data logger shield
- Typical bare piezo sensor
For the vibrations, a piezo sensor is used. Because it can produce a signal in two directions, I decided to use a voltage divider to offset the signal from GND. Two 5.1K resistors are connected from the piezo negative terminal to 5V and GND. A 1M resistor is placed in parallel with the piezo sensor. The positive terminal is connector to analog input 0.

The sensor is read 100 times per data point, the maximum and minimum values are stored and the final value is set to be the difference between the two (two times the amplitude).
USB

9V wall adapter

When the system is powered via a laptop USB port, the resting value has a jitter of a few bits. When a 9V wall adapter powers the arduino, the jitter is +/- 30 bits. Any small vibrations disappear in the noise.
USB with piezo

9V with piezo

9V without piezo

I would like some help to find the best way forward.
edit 29-10 17:53 Added better plots
edit 30-10 17:53 Added plots for 2.5V and 3.3V lines

Have you got an osci to check if the 5 V from Arduino Vcc is smooth or "rippled"? Did you use the AVRef Voltage reference? This should be stable. How long are your wires? Can you shorten them for the sensor and the resistors to make the antenna minimal? A schematic and a photo of you setup would be helpful. ;-)

@PeterPaulKiefer Sorry I don't have a oscilloscoop to check. I'm using the default analogread, I haven't changed the reference settings. Wire to piezo is roughly 75 cm and shielded, shield is not connected to GND at the moment. Strange thing is that the whole set-up is exactly the same for both plots but when powering the arduino with 9V I get the huge jitter issue. I've added a schematic for the piezo.

The 9V wall adapter is in most cases a switched power regulator with a high frequency. That's like a radio transmitter direct beside the wire. So there is nothing mystical, when the smooth USB Voltage does not show problems but the
"radio transmitter" does.
There are two ways the power supply can impact: over radio wave or as ripples over the regulated Voltage of your Arduino.
I asked myself, which one it is (or even both)? If you use the extra regulated analog voltage reference (AREF) as the +5V on your Voltage divider, it would be more likely that the problem comes through the air. Then it would help if you activate the shield of the wire by connecting it to GND.
If a rippled supply voltage is the problem, you have to smooth it. Perhaps with a low pass filter (a big Elko between Vcc and GND).
Perhaps you have a solenoid iron core. Then you can wrap the wire to the piezo sensor a few times around it (near the A0 Pin). This technique is often used in computer power supplies to prevent the switching frequencies from escaping to the public power lines.

To be clear, I'm using the regular 5V Vcc for the voltage divider. Is there a better, regulated voltage I can use on the board? I was under the impression that the Aref pin can only be used to supply an external reference. Can I use that pin to get a regulated 5V as well or have I misunderstood? How about using the 3.3V?

From my measurements, I know that the regular Vcc  is poorly stabilized. If the power supply has ripples, often I found attenuated ripples in the Vcc also. The VREF is a special pin that be programmed to provide a reference voltage for the ADCs. see https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/ . What I meant was connecting the VCC to VREF and set the analog reference to EXTERNAL. Than the voltage reference and the VCC have ripples. Because the digital value is obtained by comparing both voltages the error might be cleared.  But it is just an idea. ;-)

You can also build a external stabilized voltage add it to VREF and set the reference voltage to EXTERNAL. And you have to use this Voltage for your piezo reference. But it's only needed if the problem is caused by ripples on VCC. If the problem is cause by EMI you must try to filter the piezo voltage before it reaches the A0 input. I'm busy this morning, so I add just two comments. In the evening I'll edit my answer to order the information.  My English is not very well, so I might be fairly unclear. ;-)

Peter, not a problem, you have been very helpful so far! I now get what you mean with supplying Vref with Vcc. I did some tests on the voltages, I connected 5V to A1 and 3.3V to A2 and did the same measurements. I took 100 samples and show twice the amplitude (difference between min and max values).
USB
https://imgur.com/rmhgnRB
9V
https://imgur.com/MQEMvc9. I think a potential solution might be to use the 3.3V from the datalogging shield as it looks to be very stable! Although strangely, the 5V plots don't show a huge difference between the two power sources...

Actually, I have done the plots again and they now look like this. USB: https://imgur.com/ImOdHyC. 9V: https://imgur.com/JWyaxo2. I'm not sure where the difference comes from but these seem to make sense. So judging from these plots, I should have no issues running the piezo with the 5V via a voltage divider. I'll see if I can also measure the voltage after the divider.

Here are some plots of the 2.5V line with and without piezo. USB with piezo: https://imgur.com/mIbWWd4. 9V with piezo: https://imgur.com/JoxX7BS. 9V without piezo: https://imgur.com/buD1Fc0. Strange...

The last plots are definitely a hint, that the problem depends an the long wire to the piezo. If you remove it the signal is smooth. Have you tried to ground the shield?

A new plot gives even more insight... 9V with and without piezo: https://imgur.com/qEnOS7T. I manually connected a new, short wired (40 mm) piezo to the circuit and then disconnected it again. You can see the effect on the 2.5V...

A another plot where I connect and disconnect the long wired piezo, looks very similar. 9V source. https://imgur.com/TK63aF7

Sorry it has been getting late and I'm too tired to edit the Answer as promised. But I'm a bit irritated from what I see in the new plots. Shorten the wires increases the effect. It seems as if the power supply sends out waves and the piezo receives them, Perhaps it acts like a crystal oscillator, I've never heard of such effect before. Perhaps that's a well known behavior or I misinterpreted it wrong, but it's sure, we are beyond my limits. From what we know now, this is a question for the electronics forum in SE.

Peter thank you so much for your patience and help. I have finally found a solution for my problem and it turns out that connecting the shield from the piezo wire to Arduino GND was enough. I feel silly for not trying this before, I set my sights on voltage ripple because the USB connection did not have any problems with noise. I actually made a mistake with the short wired plots, I redid these in a proper way with a connector and didn't see the jitter....

You're welcome. I'd expect that you tried out the grounding, because you did not mentioned it again. So it's a bit of my fault also. I should have asked you one more time. In the beginning that solution was my favorite. But the conversation was very interesting and I had some new ideas of how the used e.g. a second UNO the simulate a very low frequency oscilloscope. I've learn much, and now it's my turn to thank you.

In addition to what Peter Paul Kiefer suggests, you will also want to place an RC low-pass filter, between the piezo transducer, and the analog input.
You mention that you'll be sampling this value 100 times per second. So the cutoff frequency, for the filter, should be set to 50 Hz (the Nyquist frequency).

I don't think the OP takes samles with 100 Hz. He only said that he takes 100 Samples to choose the maximum and minimum values from it. I believe he take it at the highest rate that's possible. I thought about low pass filters too, but as he used the piezo for shock detection I expect a part of the frequency spectrum (of the piezo pulses) in the same range as the EMI. So it's definitely worth a try, but I don't expect good results.


text:
My two ultrasonic sensors are reading inaccurately
I am having trouble getting two of my ultra sonic sensors to read accurate results in cm. I am using a HC-SR04 currently.
I get random numbers at different distances with an object in front (smooth cover book)
Test 1:
Real distance: 10 cm
Sensor 1: 0.00cm
Sensor 2: 82.42
Test 2:
Real distance: 10cm
Sensor 1: 92.11cm
Sensor 2: 95.03
Against the wall with no book:
Test 1:
Real distance: 10 cm
Sensor 1:0.00cm
Sensor 2: 13.20
Test 2:
Real distance: 10 cm
Sensor 1:24.37cm
Sensor 2:26.75
The numbers constantly fluctuate. I am trying to get accurate results.
I am not sure if the sensors are broken or if my code is incorrect.I appreciate any help.
Here is my set up: [
#define trigPin1 13
#define echoPin1 12
#define trigPin2 11
#define echoPin2 10

float duration, distance, duration1, distance1, duration2, distance2;

void setup() {
  Serial.begin (9600);
  pinMode (trigPin1, OUTPUT);
  pinMode (echoPin1, INPUT);
  pinMode (trigPin2, OUTPUT);
  pinMode (echoPin2, INPUT);

}

void loop() {

  FindRange(trigPin1, echoPin1);
  duration1 = duration;
  distance1 = distance;
  FindRange(trigPin2, echoPin2);
  duration2 = duration;
  distance2 = distance;
  Serial.print(distance1);
  Serial.print(" cm  ");
  Serial.print(distance2);
  Serial.println(" cm");
  delay(100);

}

void FindRange(int trigPin, int echoPin) {

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * 0.0345;
  delay(100);

}

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

I am not sure but may be it helps just by checking principle of working of this sensors as it is depicted for low range distance you must be carefull about reflection from other source of ultrasonic. I think it would be a good Idea to place a delay between these two module so to make sure it get less noise from each other
  FindRange(trigPin1, echoPin1);
  duration1 = duration;
  distance1 = distance;
  delay(1000);//add delay
  FindRange(trigPin2, echoPin2);
  duration2 = duration;
  distance2 = distance;
  delay(1000);//add delay

the other reason for getting zero may be your controller could not measure reflection from wall due to lowspeed sampling (if you are polling) or reading time with low precision so I have a suggestion for you if you are familiar with STM32 there is a built-in hardware implementation for measure time of pulse using timers called one-pulse mode it may helps you get precision you need

Where they are plugged in they won't work as the rows (like the other side) are connected. Example: http://wiring.org.co/learning/tutorials/breadboard/imgs/breadboard-02.jpg
They aren't connected to the other pins, and they are connected themselves.

change the MCU, that arduino is a chinese version.
Use a original or other original board.
I had the same problem with two diferents projects, and it happend the same to me. One with ultrasonic and other with RF24 module. In both projects, some really extrange things happens. But when i change for one original arduino, everything works perfect.

In the loop you trigger trgPin1 then trigPin2 but in the first range find you read echoPin2 instead of echoPin1.
void loop() {

  FindRange(trigPin1, echoPin2);
  duration1 = duration;
  distance1 = distance;
  FindRange(trigPin2, echoPin2);
  duration2 = duration;
  distance2 = distance;
  Serial.print(distance1);
  Serial.print(" cm  ");
  Serial.print(distance2);
  Serial.println(" cm");
  delay(100);

}

must be
void loop()
{
  FindRange(trigPin1, echoPin1);
  duration1 = duration;
  distance1 = distance;

  FindRange(trigPin2, echoPin2);
  duration2 = duration;
  distance2 = distance;

  Serial.print(distance1);
  Serial.print(" cm  ");
  Serial.print(distance2);
  Serial.println(" cm");

  delay(100);
}

Thank you I just changed and compile it but, when I use smooth book, The real distance: 15cm sensor 1: 0.00cm and sensor 2: 0.00cm.

What happens if you run the program in the loop and you move the book to and from the sensor. Do the values in the serial terminal smoothly change as you move the book or do they randomly flip around? In the latter case, I would say, there is something wrong with your setup. (broken wires, wrong connection, missing ground or vcc. Can you please add a picture of your setup? (I hope you have access to a smartphone with camera or a digital camera) Without seeing the setup I can not say much more.

When I move the book to and from the sensor the serial terminal it gave me 0cm for both sensors then it only read sensor 1 in random numbers while sensor 2 was still 0cm.

Look at your picture you connected Vcc and GND to the Vcc rail of you breadboard. Sensor one is not grounded. So it's transmitting behavior is not  specified. Perhaps the trigger or echo pin acts as ground when off and the sender speaker sends some weird signals the second sensor misinterprets.

@EmmeS I forgot to precede my last comment with you name. So you might not get informed.  Once again: Look at your picture you connected Vcc and GND to the Vcc rail of you breadboard. Sensor one is not grounded. So it's transmitting behavior is not specified. Perhaps the trigger or echo pin acts as ground when off and the sender speaker sends some weird signals the second sensor misinterprets

I tested your code as it currently is with my own HC-SR04s and a clone Arduino Nano (since that is, what I have here currently). It works like a charm. The values are rather good, maybe accurate about +-1cm. I checked in the change between 10 and 70cm with my desk plate and a wall as obstacle. (I just looked, if the values are plausible. I didn't investigate thoroughly, how accurate the values are).
So I guess, that your sensors are broken.

The working principle of HC-SR04 is based the reflection of ultrasonic wave. Therefore, It measures distance inaccurately in the following case:

The obstacle is something that can adsorbs the ultrasonic wave. For example, cotton wool.
The obstacle is faced in non-90-degree. In this case, the obstacle may reflect the ultrasonic wave to another direction
The obstacle's surface can diffuse the ultrasonic wave

You can see the working principle of HC-SR04 here.
One more thing: two ultrasonic sensor may interfere to each other if they work at the same time. Try to give delay(100); between two reads
void loop()
{
  FindRange(trigPin1, echoPin1);
  duration1 = duration;
  distance1 = distance;

  delay(100);

  FindRange(trigPin2, echoPin2);
  duration2 = duration;
  distance2 = distance;

  Serial.print(distance1);
  Serial.print(" cm  ");
  Serial.print(distance2);
  Serial.println(" cm");

  delay(100);
}

An 100ms delay is included in the FindRange function


text:
Including keypad library removes sound from my piezo element
I am using the keypad library to include keypad and input numbers. when a specific number is entered a sound must be made.
However when I input using the serial monitor , sound is working. But when I include keypad , it only inputs numbers but not sound.
Help please , how can I make both work?
Thanks.
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {12, 11, 10, 9}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8,7,6,5}; //connect to the column pinouts

Then I get the input from keypad and store as result
char guess = 'n';
 char keypressed = keypad.getKey();
  if (keypressed != NO_KEY) {
    char guess = keypressed;
in void loop, it get result(key from keypad) and must play it: Tried separate sketch it works. but with keypad only input is , not sound.
Serial.print("You guessed:");
      Serial.println(guess);
      result = checkYourself(guess);
      Serial.println(result);
      playSound(result);
check yourself takes in guess from keypad ,checks then returns as result.
play sound function works when tried in another sketch( sorry not posting too much code its very long)

it is difficult to determine the problem area without seeing your code ... please include minimal sketch that still exhibits the undesired behavior

I just posted it thanks.

which pin are you using for the buzzer?

using pin 9 ....

which pins does the keypad use?

5,6,7,8,10,11,12 removed pin 9 because not using a row

how di you tell your code that it is not to use pin 9 for the keyboard?

I was able to solve it , piezo dissent work in pin 9 but works when connected to pin 13.

Please make sure that the pin connected to piezo does NOT used by keypad


text:
How do change my Arduino Uno from an unknown device to a port?
I have an Arduino Uno that I have connected to a servo motor. I used an adapter to plug it into my computer and my computer said "Setting up a device, this will only take a minute". When it was done setting up, I downloaded Arduino IDE and I wrote a code. When I clicked "Upload", I was told that a serial port was not selected. I went to Tools>Port>Arduino Uno. The program then uploaded, I unplugged it and began its process. After I uploaded, I wanted to make a change to my code so I plugged it back in and I heard the Windows beepboopbeep sound. I edited the code and tried to upload again and it said that a serial port was not selected. I went to Device Manager and found it under another tab, something like Amtek USB ports. It was labeled as "Unknown Device". I tried to select it but it told me that it couldn't update driver. I looked it up and people said to unplug and replug in another USB port. I tried that 7 times yet it was still "Unknown Device". Am I doing something wrong?
Edit: I am using a HP AMD Radeon 7 Processor laptop running Windows 10 and my Arduino is not a copy, it is authentic.

All USB devices have 1) a manufacture ID & 2) a device ID.  A computer read these and picks a driver to load in.  On a Linux computer (and probably on a Mac) the command "lsusb" will return these ID for all connected devices.  You did not say what type of computer you are using.    Also, you did not say if your Arduino Uno board is  authentic or a copy.   This information may help others find an answer.  Although this is sometimes a tricky subject.  Especially when Windows gets involved.

Does the arduino IDE show a different COM port to select. The time it worked you said you had selected  Tools>Port>Arduino Uno. This is new to me. I would expect a port like COM13 or COM15 or such. Does Windows 10 name their serial ports other than Win7 for example?  What programmer did you choose?  Did you select the right board? (UNO)

I used an adapter to plug it into my computer What kind of adapter? The Ardino Uno just plugs directly into your computer with a USB cable. There should be no "adapter" needed.

@Majenko I used a USB type B to A adapter.

@PeterPaulKiefer i do not remember the COM, the Arduino IDE software that I have open says it is COM3 but won't let me select the port anymore. It automatically chose AVRISP mkll as my programmer.

it started working now that I found a better USB cable, only problem is that now when I upload the code, it does not run

Then,  if the upload ends with no error messages, the code itself may have errors. Do you understand, how the code works? If you copied it from the internet, try to understand, what the code does. Hopefully there is a little explanation coming with it. If you are complete new to programming, look at the basic sides (e.g. https://www.arduino.cc/reference/en/ ). -- Perhaps you'll find the error. If not, it's a good opportunity to ask here a new question. People can help you the most, if you add your code, explain what you've done and say what you expect and what not works as you expected it.


text:
How can i connect 4 stepper motors and 3 sensors to an Anduino?
I have an Arduino AT MEGA 2560 circuit. I want to buy 1 Nema-17 bipolar stepper motors, 3 M49SP-2K stepper motors, 3 KY-032 sensors to do my project but i dont know how to connect them to my Arduino.
Is there any Arduino shield for my purpose? Can I use Ramps 1.4 Arduino shield?

Take a look at the Ramps V1.6, it is what I use. It plugs onto the AT Mega board.
https://reprap.org/wiki/RAMPS_1.6
The 1.6 has a few improvements. I like the solder in power connectors rather than the plug in ones. More reliable.
Because I already had the AT Mega board I decided to try the ramps. There are better boards now, with 32 bit processors. But as a starting point the Ramps combo is the simplest to get going and it does the job.
Other boards may work out a little better, but the firmware is a bigger issue. Still in development.


text:
Can only program Pro Mini board once then error getsync()
I am 100% new to Arduino.  I am using the Pro Mini 328P 3.3v 8mhz board.  I can successfully write to the board once with the Blink program. I set the FTDI to 3.3v jumper. It works.  Then if I try to upload again (I changed the timing on the blink) I get the getsync error.  I tried two boards they both fail after the first upload.  I am using Win 10.
This is the error I see:
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xaf

Can you add a screenshot of the used Arduino IDE settings and how you connect your FTDI (I assume, not FTDL) to the target board?

I can successfully write to the board once with the Blink program ... how do you know this? ... the blink program may have been previously loaded onto the board

Because I have 5 of these 328P boards and I uploaded another program to one of them and it works monitoring a voltage on a FRSky S6R receiver.  But once I upload a program I can no longer upload to the board.

https://imgur.com/zSFHVQt
https://imgur.com/zqdw9Td
It's DTR to DTR, TX to RX, RX to TX, VCC to VCC, GND to GND

Bad link in the previous comment:  IDE screen shot:
https://imgur.com/gallery/zqdw9Td

Have you reconnected the FTDI adapter? Then it could happen that windows choose a new PORT. In that case you have to reset the port to the new one. I've also heard of others, they had problems with the usb driver of the FTDI mod. Could you look into the device manager to see if the USB device FTDI i still working?

The COM port has not changed.  (I confirmed in the device manager) I can take a new unprogrammed Mini Pro and it works fine.  I bought a total of 5 of them.  Does the upload wipe the boot loader?

I got an UNO R3 board.  I was able to take those Pro Mini boards that would not accept a 2nd upload and got them working.  Something on that FTDI board must be wiping the bootloader.


text:
integer overflow in expression [-Woverflow] - TinyCircuit
I have a tiny circuit Bluetooth shield and I was testing out the sample code that was provided by tinycircuit. However, when I tried uploading the sample code into the board, I kept having the following error. How can I solve this error?

this is the piece of code where there error seems to be happening.
#define  ADV_INTERVAL_MIN_MS  50
#define  ADV_INTERVAL_MAX_MS  100

void setConnectable(void)
{
  tBleStatus ret;

  const char local_name[] = {AD_TYPE_COMPLETE_LOCAL_NAME, 'B', 'l', 'u', 'e', 'N', 'R', 'G'};

  hci_le_set_scan_resp_data(0, NULL);
  PRINTF("General Discoverable Mode.\n");

  ret = aci_gap_set_discoverable(ADV_IND,
                                 (ADV_INTERVAL_MIN_MS * 1000) / 625, (ADV_INTERVAL_MAX_MS * 1000) / 625,
                                 STATIC_RANDOM_ADDR, NO_WHITE_LIST_USE,
                                 sizeof(local_name), local_name, 0, NULL, 0, 0);

  if (ret != BLE_STATUS_SUCCESS)
    PRINTF("%d\n", (uint8_t)ret);

}

What is ADV_INTERVAL_MIN_MS ?

50 * 1000 > 32768. 100 * 1000 > 32768. It shouldn't matter, but best force it to a long by appending L to your defined numbers.

You can specify the type of a number using suffixes such as L, LL,
UL and such. If you don't specify the type this way, all integers that
are small enough to fit in an int will be of type int. When you
write
ADV_INTERVAL_MIN_MS * 1000

it gets expanded by the preprocessor to
50 * 1000

Since both arguments are of type int, the compiler will use this type
to compute the result. However, the result is 50,000, and on 16-bit
systems the largest number that can fit in an int is 32,767, thus the
overflow.
As suggested by Majenko, the simple solution is to add the L suffix
(for long) to either operand. The compiler will then do the
arithmetics using the long data type.

Sorry uhm, what do you mean either operand ? I'm a little new on this.

The operands are 50 and 1000. Append the “L” suffix to either (or both) of them.


text:
Multiple data packets with CIPSEND, associate each with pathway
When using a CIPSEND from an Arduino Uno to a ESP8266 connected to the Uno is there a way to associate the data packet sent with a pathway so it can be retrieved at said pathway from the browser?
For example ESP8266WebServer.h has a command like this:
server.on(“/specificArgs”, handleSpecificArg);   //Associate the handler function to the path

where the first argument is the path/filename - what's the equivalent of this using using CIPSEND?

The Arduino sends the CIPSEND to the ESP8266, not the other way around. It's hard to understand quite what you're asking.

I have rephrased the question. Refer to the ESP8266WebServer.h example here https://techtutorialsx.com/2016/10/22/esp8266-webserver-getting-query-parameters/ and you will see what I mean about associating the data packet with a path/filename.

So you are using the Arduino and ESP8266 as a web server?  The browser sends a request with a path in it, and your CIPSEND is what you send in response to that. The "association" is the fact that you are responding to a request.

https://github.com/khoih-prog/ESP8266_AT_WebServer

@Juraj useful as a last resort but I'd prefer to get it working with the AT commands rather than jump from that to a library.

Your "CIPSEND" is already associated with a path.
The sequence is generally:

You configure the ESP8266 as a server, including turning on multiple connections
You browse to the IP
The browser sends a HTTP request including a path. This has a "channel" number associated with it.
You generate a HTTP response and send it to the channel given in 3 using AT+CIPSEND.

The fact that you're sending the response to the browser through the channel that the request came in through "associates" the response with the request.
To do different things depending on the path it's up to you to recognise that path in the request and generate a different response accordingly.

"To do different things depending on the path it's up to you to recognise that path in the request and generate a different response accordingly." - yes how? If i want the first datapacket sent to the esp8266 to be associated with '192.168.4.1/' and the second to be associated with 192.168.4.1/data', how is that done?

When you receive the request to get / you send the response for /.  When you receive the request for /data you send the response for /data.

Ok I think I'm beginning to understand what you mean - If I understand correctly I should be doing a esp8266.find("/"); and esp8266.find("/data"); in my arduino code and then an if () to determine what path has been requested by the esp8266. I need to test this as there is an added complexity I didn't mention in my question. Data packet 1 is a webpage with ajax, data packet 2 is an json string. The json is constantly being updated by the arduino, the ajax webpage is directly requesting the ajax. As far as I understand this doesn't change anything but need to test...


text:
CIPSEND to ESP8266 returning bytes but no content
I am trying to send a GET request from an Arduino Uno connected to an ESP8266 through SoftwareSerial. I can't get it working directly in the code so I've stripped it down to a script that passes serial monitor queries like so:
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial esp8266 (rxPin, txPin);

void setup()
{
  Serial.begin(115200);
  esp8266.begin(115200);
  delay(1000);
}

void loop()
{
  if (esp8266.available()) Serial.write(esp8266.read());
  if (Serial.available()) esp8266.write(Serial.read());
}

I setup and connect the ESP8266 to my router like so from the serial monitor:
AT+RST
AT+CWMODE=3
AT+CWJAP="rwifi name","wifi password"
AT+CIFSR
AT+CIPMUX=0
AT+CIPSTART="TCP","www.abcdefg.com",80
AT+CIPSEND=61
GET /in-progress/ab/i.php?c=20 HTTP/1.0 Host: www.abcdefg.com

Everything works fine up until the CIPSEND, the GET request part, and the serial monitor output the following:
AT+CIPSEND=61

OK
> i.php?c=20 HTTP/1.0

busy s...
Recv 61 bytes
SEND OK

I know there is a 64 byte limit for the serial monitor. my GET is 61 bytes. I'm getting bytes back but not the content from the page (it should be the word "yes") and not even a content from a 404 page. Web side my php page is a counter that adds 1 to a number in a txt file - it doesn't increment (it does work if I call it from the web browser).
Where I am going wrong here with my CIPSEND? It looks like it is correctly formed to me.
-----edit-----
Based on comments below this is the latest GET request I have tried:
AT+CIPSEND=73
GET /i.php HTTP/1.1\r\nHost: www.abcdefg.com\r\nConnection: close\r\n\r\n

I have shortened my pathway to the php file as much as possible, added the carriage returns and newlines between request and each header, added the double carriage return and newline at the end. The request now returns +IPD,919:HTTP/1.1 400 Bad Request. This error 400 is not logged on my website.

GET /in-progress/ab/i.php?c=20 HTTP/1.0 Host: www.abcdefg.com is not a valid GER request. Headers go on separate lines separated by \r\n.

You need to terminate the GET request with proper \r\n, and the http header as well. So it should be GET /in-progress/ab/i.php?c=20 HTTP/1.0\r\nHost: www.abcdefg.com\r\nConnection: close\r\n\r\n. I have an example on my github you might want to take a look.

@garrettlynch, upvote for presenting the correct way of debugging connectivity issue between the arduino and the ESP8266

@hcheung thanks, I've tried it with carriage returns and new lines as instructed. I'm getting +IPD,919:HTTP/1.0 400 Bad Request - I wonder if this is something to do with the AT+CIPSEND=bytecount I'm sending. I'm unclear as to what the count is of. The documentation states it's the "length of the data that will be sent". Does that mean just the pathway sent (i.e. /in-progress/ab/i.php?c=20) or does it include everything else in the line GET /in-progress/ab/i.php?c=20 HTTP/1.0\r\n? I've dug through your libraries code and as far as I can tell you are counting the whole line.

yes, I was sending line by line with multiple AT+CIPSEND commands, the length is included \r\n. Your ESP8266 received 400 Bad Request might be other issues. Do you check your server/php log to see what exactly received and why it is a bad request?

BTW, the last http header should have double \r\n\r\n, which is typically the header for Connection: close\r\n\r\n. Also, make sure you send the correct "Host: hostname\r\n" header, I remember I've see 400 before causing by incorrect host name or missing the http header.

@hcheung the Host: hostname\r\n header seems to be specific to HTTP 1.1 from what I've read. I've tried with HTTP 1.0 as well without hostname and I get the same error 400 so I think I can rule that out as the issue. Yes my last header is using a double \r\n\r\n. I've checked my sites access logs and error logs and there is no trace of any error 400 or requests to that page i.php other than the three I did from a browser today to check it was working.

you can't send a two or more line http request from Serial Monitor. it is not possible. the \r\n are not converted to line ends. they are sent as \ and r and \ and n

Yeah, like someone already said, you can't send CRLF by typing them into the Serial Monitor. Let the serial monitor itself append that for you instead. You have to set the Line Ending at the bottom to "Both NL & CR" and then send your HTTP headers, one line at a time. For each \r\n in your request, you press Enter, type the next line and so on, until the request is complete.

In my experience, the "busy" message appears when you try to start a new AT command or to send data before the ESP8266 is ready. You say that you are running this test with the commands in "a script" which suggests to me that there is no significant delay between lines.
You should either wait between commands until the EXP8266 responds (usually with "OK" or ">") or add a delay of a few seconds between commands.

No I said "I've stripped it [my code] down to a script that passes serial monitor queries" - the AT commands are coming from the serial monitor and the prior commands have completed before the GET request is sent. I have moved beyond this, however, and am getting Bad Request responses now. Please see the edit to my question.


text:
Function parameter of type int not working as expected
I am attempting to write a small sketch with the Arduino IDE (1.8.10) to set the colour of an RGB LED, however my function for setting the colour of the LED is behaving strangely.
Here is the full sketch code:
#define RED 9
#define GREEN 10
#define BLUE 11

void setup()
{
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  digitalWrite(RED, LOW);
  digitalWrite(GREEN, LOW);
  digitalWrite(BLUE, LOW);
  Serial.begin(9600);
}

int gRed = 20;
int gGreen = 21;
int gBlue = 22;

void setRGB(int r, int g, int b)
{
  Serial.println(r);
  Serial.println(g);
  Serial.println(b);
  analogWrite(RED, r);
  analogWrite(GREEN, g);
  analogWrite(BLUE, b);
}

void loop()
{
  //setRGB(gRed, gGreen, gBlue); // WORKS - White-ish
  setRGB(20, 21, 22); // DOESN'T WORK - Blue =/
}

As you may tell from the comments, when I pass "global" variables in to setRGB() the LED lights up the expected colour. But, when I pass literals in it does not.
The Serial monitor shows the following output when using the literals:
20
21⸮20
21
20
21
20
21⸮
etc....

Can anybody help me figure out what I'm doing wrong?
Board in use is a Mega2560.

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

the conclusion in chat was a compiler problem (it over-optimized). with AVR core 1.6.21 which uses older version of avr-gcc the code worked

I'd add some delay between calls. Or even change the values by analogWrite when they changes only.


text:
Problem burning bootloader to ATmega chip using nano/uno
I designed a custom PCB that has the chip, an oscillatorm, decoupling capacitors, and all other connections for the ATmega along with the rest of my circuit. I followed all steps in the tutorial for burning the bootloader to my ATmega chip but when using a nano to program I get an error about getsync() that supposedly means the reset isnt working. I then used the same wiring with an uno like in the examples and I got a different error this time where it goes yikes then something about not recognizing the chip. This is apparently indicative of a wiring or oscillator problem but all those things appear to be correct. I'm not sure what to try next or what could be wrong
Used this tutorial as well as the actual arduino page https://www.electronoobs.com/eng_arduino_tut6.php
Used this tutorial next since I am using ATmega328PB
https://www.circuito.io/blog/atmega328p-bootloader/
Here's the error I get
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "ATmega328, Yes (UART0), 328PB, BOD 2.7V, LTO disabled, 16 MHz external"
\nas01.itap.purdue.edu\puhome\My Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -C\nas01.itap.purdue.edu\puhome\My Documents\ArduinoData\packages\MiniCore\hardware\avr\2.0.3/avrdude.conf -v -patmega328pb -cstk500v1 -PCOM5 -b19200 -e -Ulock:w:0x3f:m -Uefuse:w:0b11110101:m -Uhfuse:w:0xd6:m -Ulfuse:w:0b11111111:m
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch
     System wide configuration file is "\\nas01.itap.purdue.edu\puhome\My Documents\ArduinoData\packages\MiniCore\hardware\avr\2.0.3/avrdude.conf"

     Using Port                    : COM5
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega328PB
     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
       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
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.02s
avrdude: Device signature = 0xffffff (retrying)
Reading | ################################################## | 100% 0.02s
avrdude: Device signature = 0xffffff (retrying)
Error while burning bootloader.
Reading | ################################################## | 100% 0.02s
avrdude: Device signature = 0xffffff
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.
avrdude done.  Thank you.
Here's the PCB schematic and wiring picture

Post a link to the tutorial that you followed.

Edited original post to add tutorial

The tutorial is fine, except for reset pin which he should've used a 10K resistor. post the exact error message(s) and a picture of what you have on breadboard or PCB...

Updated again, added new tutorial I tried and the pictures

I had the same "invalid device signature" problem and using minicore library solved it. if you followed all steps correctly, maybe the chip is damaged.

Yeah I replaced the chip and then was able to burn the bootloader fine. But now when programming I get an error that programmer isn't responding. I'm using this guide: https://www.instructables.com/id/Program-ATmega-328-Using-Arduino-Arduino-As-ISP/


text:
data classification with arduino
I want to classify my data from 3 sensors with arduino so that every time i enter the specific date or hour, or also it can be a period of time like 10 days ago, it shows me the exact data. In other word i want to classify my data so that whenever i want every detail of data, i would be able to get it by entering the information of year,date,time. I also didn't want my data to be in separate files and time stamps. I want to be able to do that within one file and search inside that file...
#include "RTClib.h"
#include <SD.h>
#include <SPI.h>

RTC_DS1307 rtc;
const int chipSelect = 10;

File dataFile;

String print_time(DateTime timestamp) {
  char message[120];

  int Year = timestamp.year();
  int Month = timestamp.month();
  int Day = timestamp.day();
  int Hour = timestamp.hour();
int Minute = timestamp.minute();
      int Second= timestamp.second();

      sprintf(message, "%d-%d-%d %02d:%02d:%02d", Month,Day,Year,Hour,Minute,Second);

      return message;
    }

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

      pinMode(chipSelect, OUTPUT);
      if (!SD.begin(chipSelect)){
        Serial.println("Error: SD card would not initiate.");
      }

      rtc.begin();
      if (!rtc.isrunning()){
        Serial.println("Clock is not running");
      }

      dataFile = SD.open("log0.csv", FILE_WRITE);
      if (!dataFile){
        Serial.println("Could not open file.");
      }

    }

    void loop(){
      Datetime now = rtc.now();
      dataFile.println(print_time(now));

      delay(3000);
    }

Does this answer your question? sending specific date's data from data logger shield to serial port

so this ^ is the new automatic comment for  "possible duplicate"

@Juraj the question you suggested is different from this one. What i mean here is for example a file with 1000 saved data. lets say you want the data from december 2, 10AM untill now. this is the main question... the ability to classify the data and ask the time of saved data. Here i should write a code so that my program understands the TIME i ask it...

If you plan to continuously take data at a fixed rate, I suggest you
don't timestamp the individual records. Instead, store the initial
timestamp and the data sampling period in a binary header, followed by
fixed-size binary records. Then, when you want to retrieve the record
for time t, you can fseek() right to
uint32_t offset = header_size
                + record_size * (t - initial_time) / sampling_period;

If there is a slight chance that you may fail to record some data
points, you may want to have a boolean in each record that tells whether
the data is valid. You can then fill the missing data with invalid
records.
If your Arduino is likely to be turned on and off unpredictably, then
timestamping every record may be a better option, but finding a specific
record will likely be very slow.

Upvoted your answer, indeed if the data comes continuously and at a fixed rate, your solution is better. My solution I assumed data from the sensors could come randomly and possibly unevenly spread.

Create a single file (SD logger?)
When data is received from a sensor, store it in the file, and store this information:

Date/Time stamp
Which sensor
Sensor data

When a request for data is received (probably containing start and end time stamps, parse through the file, and start returning information for those date/time stamps within the requested start/end time stamps.

If step 3 takes too long (and results in missing new sensor measurements), you have to do the read in smaller steps between the reading of sensors.

That's the part i don't understand. How should i write the code... sorry I'm new with arduino... your theory for writing the code is completely what i was thinking but i have trouble writing it...

Split your problem up into smaller pieces (like I showed above. Maybe it's even better to first try the file part on a PC where you have easy debug facilities without using an MCU. Thus try to write a file, add bytes to it pretendin they come from sensors. When you have that working add the MCU specific parts (reading sensor data and use the SD library from the Arduino instead). To write all the code is a bit out of scope for this forum (too broad too).

I wrote a code with timestamp and data. Now can you help me with the next part? How can i ask the arduino to send me the timestamp i want? I uploaded my code. Now i ask the arduino to send me the last 10 timestamps.... any suggestions?

You should add the code to the question, not as answer. How you want to 'ask it to the Arduino'  depends on what you want …  you want to add a keypad, or a set of switches, or a keyboard of some type to the Arduino, or the serial port or another way (WIFI, USB)? I don't know your requirements.

Thank you for the guide. I added the code to my question...  I want to ask the arduino through bluetooth module but i don't know the related code for this purpose... What particular code reads the timestamp for me?

I never used Bluetooth, but I think this is a 'mini project' on its own. Try the following steps: 1.  Make (or better: find) some code that sends something via BT (this is Arduino unrelated). 2. Find code that reads some BT message. 3. Send somethin via BT. 4 Check if it arrives. 5. Change the message that is sent to something that has the start and end timestamp in it. 6. Change the code on the Arduino to parse these time stamps. 7. Retrieve the sensor messages from the SD card. 8. Send it via BT. 9 Do something with it at the receiver side.

How can i do number 5 & 6? can you guide me?

Step 5 The message you sent to the Arduino (in the example probably nothing useful), you add some extra bytes (e.g. year 0-99, month 1-12, day 1-31), thus 3 bytes. Step 6: When you receive the message, you extract these 3 bytes from the message and place it in three (byte) variables: year, month and day. Than you can use these 3 variables to filter the sensor data.

Thank you for your response. So,can arduino understand the timestamp i'm writing as start and stop time?

If you program it to respond on the timestamps, yes.

How can i do it? can you guide me?

Like in 4 comments above (put in variables and respond to it).


text:
Attiny85, high output impedance, dim leds
I designed what I thought should be a very simple badge using the Attiny85 SU, schematic below:
The problem is the tiny doesn't seem to be sinking current properly. For testing I switched to a 20 PU on the breadboard and 100 ohm load resistors. At 3v supply this should give approximately 30 mA per pin, well under the rated 40 mA per pin and 200 mA total. However with the loads connected only pin 6 sinks any significant current, and appears to be higher impedance than it should be (1.6v across the resistor for 16 mA). The other pins seem to be very high impedance, they drop to ~7 mV (70 microamps) when the loads are connected. With the load resistors disconnected they function normally (digitalWrite HIGH = supply voltage - junction drop).
I'm using pinMode [this was a problem] (OUTPUT, N) [/this was a problem, should be (N, OUTPUT)] to set up pin N, and digital writes for on/off. I've been able to drive transistors before using an exactly similar setup, although admittedly these have much lower current requirements.
Anybody know what's going on here?
EDIT: Turns out I had accidentally swapped the order of OUTPUT and N in the pin mode command. Not sure why the compiler had no problems with this, but I am at least getting useful outputs now.
I'm gonna leave this up out of curiosity/etc, because I'm still getting higher impedance than I'd have expected on the outputs. With the 100 ohm load resistor, I'm only getting about 16 mA (expect closer to 25). Supply voltage from the CR2032 is ~2.48v under load.
Based on the graph on the datasheet (figure 22-19, PG 182), at 25 c ambient (currently 20) I should expect a voltage drop from VCC to output somewhere on the lower end between 400 and 600 mV when supplying 15 mA, but my readings at 16 mA above represent a voltage drop of almost 900 mV across the Tiny. Additionally the LEDs drop 2v at 10 mA, for which you'd expect approximately 300 mV drop across the tiny according to the graph, but mine is dropping almost 500 mV. I'm not sure if this is something in my setup or if the characteristic curves on the datasheet simply aren't that accurate for production models.

Note that output pins on most AVR-based Arduinos are supposed to source/sink a max of 20mA, with an ABSOLUTE max of 40mA. 40mA the current level at which you are likely to burn out the output. For normal use you should stick to a 20mA/pin limit (and also watch the total current limit of 200mA as you mentioned.)

The answer to the main problem was that I had used pinMode(mode, number) where the actual syntax is pinMode(number, mode). Presumably modes can be selected by number and the compiler though I wanted to set an undefined pin to mode number.
TL;DR the correct syntax is pinMode(4, OUTPUT) to set PB4 (pin 3) to output.
The problem of higher than expected output impedance remains, though the outputs are now quite usable. As detailed in the edit, I'm still experiencing voltage drops across the microcontroller nearly 2x higher than I'd expect from the graph on the datasheet for a given current.

Thanks for taking the time to post a self-answer after finding the cause of your problem. Not many people do that. (Voted)

You already found your problem. I am answering only to provide some
insight on why you were experiencing the symptoms you had.
pinMode() takes two integer arguments (two uint8_t to be precise).
The names INPUT, OUTPUT and INPUT_PULLUP are just macros for 0, 1
and 2 respectively. This is why the compiler accepts your code with the
arguments swapped.
On the AVR microcontrollers, setting a pin's output register to HIGH
on a pin that is configured as input has the effect of turning on the
internal pullup. Thus
digitalWrite(pin, HIGH);

has the same effect as
pinMode(pin, INPUT_PULLUP);

on an input pin. When you do this, the pin will source (not sink) a very
small current. The pullup resistance is typically of the order of
30 kΩ, and this is why you get such a small current.

Ok, that makes sense. I was wondering why it worked at all. Well reasoned as to why reversing the parameters created a high-impedance output. (Voted)

Awesome explanation, it also explains why PB1 (pin 6) was functioning normally since it would have been getting pinMode(1, 1) with the macro


text:
Arduino Mega Speaker can't play music but noise
I'm struggling that my Arduino doesn't play music. Here is my circuit.
It proforms normally when I only connect this circuit to Arduino UNO. But when I change the whole circuit to Arduino Mega the music trues into noise. I've followed the tutorial to change the SD card adapter pin to the suggested pin.

Is there any possibility that the circuit is obstructed by servo motor which also connected to this Arduino mega? Here's my code.
#include <PS2X_lib.h>
#include <Servo.h>

#include "SD.h" //Lib to read SD card
#include "TMRpcm.h" //Lib to play auido
#include "SPI.h" //SPI lib for SD card

#define SD_ChipSelectPin 53 //Chip select is pin number 53
TMRpcm music; //Lib object is named "music"

Servo MG996;
Servo MG90B;
Servo MG90F;
PS2X ps2x;
int error;

const int enA = 7;
const int In1 = 39;
const int In2 = 41;
const int enB = 6;
const int In3 = 43;
const int In4 = 45;

int MG90B_pos = 90;
int MG90F_pos = 90;

void setup() {
  //music.speakerPin = 4; //Auido out on pin 4
  Serial.begin(9600);

  do {
    //GamePad(clock, command, attention, data, Pressures?, Rumble?)
    error = ps2x.config_gamepad(11, 9, 10, 8, true, true);
    if (error == 0) { Serial.print("Asian Big Cannon is activated!");break; }
    else { delay(100); }
  } while (1);

  pinMode(enA, OUTPUT);
  pinMode(In1, OUTPUT);
  pinMode(In2, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(In3, OUTPUT);
  pinMode(In4, OUTPUT);

  MG996.attach(32);
  MG90B.attach(31);
  MG90F.attach(30);

  MG996.write(90);
  MG90B.write(MG90B_pos);
  MG90F.write(MG90F_pos);

 /*
if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("SD fail");
return;
}
music.setVolume(3);   //   0 to 7. Set volume level
music.quality(2);
*/
}

void mfront(){
  digitalWrite(In1, HIGH);
  digitalWrite(In2, LOW);
  digitalWrite(In3, HIGH);
  digitalWrite(In4, LOW);
  Serial.println("front");
}
void mstop(){
  digitalWrite(In1, LOW);
  digitalWrite(In2, LOW);
  digitalWrite(In3, LOW);
  digitalWrite(In4, LOW);
  //Serial.println("stop");
}
void mback(){
  digitalWrite(In1, LOW);
  digitalWrite(In2, HIGH);
  digitalWrite(In3, LOW);
  digitalWrite(In4, HIGH);
  Serial.println("back");
}
void mright(){
  digitalWrite(In1, HIGH);
  digitalWrite(In2, LOW);
  digitalWrite(In3, LOW);
  digitalWrite(In4, HIGH);
  Serial.println("right");
}
void mleft(){
  digitalWrite(In1, LOW);
  digitalWrite(In2, HIGH);
  digitalWrite(In3, HIGH);
  digitalWrite(In4, LOW);
  Serial.println("left");
  }

void loop(){

  music.play("JC.wav");
  Serial.println("playing....");
  delay(10000);
}

Please include your full code or a working minimal example, that shows your problem. This code wouldn't even compile. 2.  Yes, the servo can interfere with the library, if it also uses Timer1 as the TMRpcm library as default on the Mega

I've updated my code. This is a machine controlled by the PS2 handle. I delete some codes that refer to servo motor control. If it is the TMRpcm library problem, how can I solve it? Thanks!

Where's the circuit? It doesn't show up.

It's not clear whether your arduino UNO is actually plugged into the breadboard, or not.  If it is, then you are shorting all of the pins - not a good idea!

and do you wire it to SPI pins 50, 51, 52 on Mega?


text:
Esp8266 Arduino WiFi Exception Error 29
Background: I know nothing about hardware.
I am writing a small project with Arduino IDE, ESP8266 library, and my board is ESP8266 V3 ESP-12N F NodeMcu Lua CP2102.
Now I get Exception 29 and I don't know why.
Sketch and server code(written in Python) github link (I also posted the client and server code at the bottom)

Module: [NodeMCU 1.0 (ESP-12E Module)]
Flash Size: [4MB]
lwip Variant: [v2 Lower Memory]
Flash Frequency: [40Mhz]
CPU Frequency: [80Mhz]
Upload Using: [SERIAL]
Upload Speed: [115200]

Stack Dump:
Exception 29: StoreProhibited: A store referenced a page mapped with an attribute that does not permit stores
PC: 0x4000e1c3
EXCVADDR: 0x00000018

Decoding stack results
0x40100908: malloc(size_t) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\umm_malloc\umm_malloc.cpp line 511
0x40100b6e: calloc(size_t, size_t) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\umm_malloc\umm_malloc.cpp line 826
0x40100b60: calloc(size_t, size_t) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\umm_malloc\umm_malloc.cpp line 820
0x4020318b: loop_task(ETSEvent*) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 188
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x402109ff: tcp_output at core/tcp_out.c line 1259
0x4020216a: ClientContext::wait_until_sent(int) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 331
0x40100908: malloc(size_t) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\umm_malloc\umm_malloc.cpp line 511
0x402151c0: mem_malloc at core/mem.c line 210
0x4020f104: pbuf_alloc_LWIP2 at core/pbuf.c line 284
0x40214732: ip4_output_if at core/ipv4/ip4.c line 1550
0x4020fe90: tcp_write at core/tcp_out.c line 263
0x402031dc: __esp_yield() at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 100
0x4020378e: __delay(unsigned long) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_wiring.cpp line 54
0x4020230f: ClientContext::_write_from_source(DataSource*) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 464
0x4020239d: WiFiClient::write(unsigned char const*, unsigned int) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 364
0x40204c30: WiFiClient::write(unsigned char) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src\WiFiClient.cpp line 217
0x40201bc4: DataSource::~DataSource() at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/DataSource.h line 12
0x402026c9: WiFiClient::flush(unsigned int) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src\WiFiClient.cpp line 318
0x40201113: loop() at C:\Users\ptq00\Documents\Arduino\sketch_jan03b/sketch_jan03b.ino line 44
0x40100154: ets_post(uint8, ETSSignal, ETSParam) at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x402032f4: loop_wrapper() at C:\Users\ptq00\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 180

Sketch(Client) Code:
#include <ESP8266WiFi.h>

const char ssid[] = "luminous";
const char pass[] = "zxcv78()[]";

//Mac IP 192.168.1.101
//PC IP 192.168.1.103

IPAddress server(192,168,0,103);
int port = 12700;

WiFiClient client;

void setup() {
  // put your setup code here, to run once:

  Serial.begin(115200);
  Serial.println("");

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

  Serial.println("");
  //WiFi is connected

  if(client.connect(server, port)){
    Serial.println("connected to server");
  }

}

// 3s client read timeout. I set this value casually. The server has a 5s timeout when reading data from client.
const unsigned long clientTimeout = 3000;

void loop() {
  // put your main code here, to run repeatedly:

  if(client.connected()){
    client.write(WiFi.RSSI());
    delay(100); // Add for nothing. Not sure if it's useful
    unsigned long timeout = millis();
    //Client timeout, if client can't reach the server, it should start to reconnect the server
    while(client.available() == 0){
      if (millis() - timeout >= clientTimeout){
        Serial.println(">>> Client Timetout !");
        client.stop();
        break;
      }
    }
    //Client is connected and has data to read
    //discard all data
    client.flush();
  }else{
    //Try to reconnect to the server
    client.connect(server,port);
    delay(500); // Add for nothing. Not sure if it's useful
    while(!client.connected()){
       //failed to reconnect
       Serial.println("Failed to reconnect...");
       delay(500);
       client.connect(server,port);
    }
    //succeed reconnecting
    Serial.println("Succeeded reconnecting..");
  }
}

Server Code:
import socket

HOST = '0.0.0.0'
PORT = 12700

catSafeZone = False
serverTimeout = 3

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1);
    s.bind((HOST, PORT))
    s.listen()
    print("Start listening")
    print("Device is not conncted")

    while True:
        conn, addr = s.accept()
        try:
            with conn:
                print("Connected by", addr)
                print("Cat is online")
                conn.settimeout(serverTimeout)

                # client won't try to disconnect on its own.
                # So we only need to capture connection timeout exception
                while True:
                    data = conn.recv(128)
                    if data:
                        if catSafeZone == False:
                            catSafeZone = True
                            print("Cat is in safe zone.")
                        conn.send(b'1')
                    else:
                        print("Unexpected condition")
                        print("Client disconnected on its own.")
                        raise Exception("server data NULL")

                    # Code that is used for wifi signal strength detection:
                    #
                    # if not data:
                    #     break
                    # wifiStrength = int.from_bytes(data, byteorder='big', signed=True)
                    # print(wifiStrength)

        except socket.timeout:
            print("!!!Cat is out of safe zone")
            # Warn user in some ways
            catSafeArea = False

# never reach here
print("Server shutdown")

First: If you haven't already; please change your AP password, as you have included it in the code. Are your neighbors all friends? ;-) It seems as if the MCU tries to store data in a page where it is not allowed. But I confess, I see nothing in the code that could cause this behavior. Does it occur every time you run the code or is it a race condition? From the stack trace it seems as if the stack is used by multiple threads or interrupt routines. Perhaps two allocation accesses disturb each other. Because LUA is active that might also interfere with your code. Just guesses.

Ah, wait I've seen something: I add an answer because I use code to explain.

I fixed the problem. It turned out to be that the flush function in Arduino WiFi library has toally different meaning from the one that defined in ESP8266WiFi librarry.
From https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/client-class.html:

flush() returning true indicates that output data have effectively
  been sent, and false that a timeout has occurred.

This acts more like a flush stdout buffer in a typical C program.
Then I replaced client.flush() with:
 while(client.connected() && client.available() > 0){
    client.read();
  }

And everything works well then.

And I use your code with a little bit modification.
#include <ESP8266WiFi.h>

const char ssid[] = "luminous";
const char pass[] = "xxxxxxxx";

IPAddress server(192,168,0,101);
int port = 12700;

WiFiClient client;

void setup() {
  // put your setup code here, to run once:

  Serial.begin(115200);
  Serial.println("");

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

  Serial.println("");
  //WiFi is connected

  if(client.connect(server, port)){
    Serial.println("connected to server");
  }else{
    Serial.println("Failed to connnect to server at setup().");
  }

}

int needToReconnect = 0;

void loop() {
  // put your main code here, to run repeatedly:
  while(!client.connected()){
       //failed to reconnect
       needToReconnect = 1;
       Serial.println("Failed to reconnect...");
       delay(500);
       client.connect(server,port);
  }

  // Use a flag to indicate if client was in reconnect procedure
  if(needToReconnect){
    Serial.println("Succeeded reconnecting...");
    needToReconnect = 0;
  }

  client.write(WiFi.RSSI());
  delay(100); // Add for nothing. Not sure if it's useful

  while(client.connected() && client.available() > 0){
    client.read();
  }

}

In your code there is a possibility that you stop the client and then flush it after. That could lead to the observed error.
// Client timeout, if client can't reach the server,
// it should start to reconnect the server
while(client.available() == 0)
{
  if (millis() - timeout >= clientTimeout)
  {
    Serial.println(">>> Client Timetout !");
    client.stop(); // <----- HERE is the STOP !!!!!!
    break;
  }
}
//Client is connected and has data to read
//discard all data
client.flush(); <-- Then a flush on a stopped client !!!!!

I have no chance to try the following code, so use it as an example of what I would suggest you could try out. Attention: I've grayed out the last IP number and the SSID and the password.
#include <ESP8266WiFi.h>

const char ssid[] = "XXXXXXXXXXXXXXX";
const char pass[] = "XXXXXXXXXXXXXXX";

IPAddress server(192,168,0,XXX);
int port = 12700;

WiFiClient client;

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

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

  // New line after .../.../...
  Serial.println("");

  if( client.connect(server, port) )
  {
    Serial.println("connected to server");
  }

}

// 3s client read timeout. I set this value casually.
// The server has a 5s timeout when reading data from client.
const unsigned long clientTimeout = 3000;

void loop()
{
  while( ! client.connected() )
  {
     //failed to reconnect
     Serial.println("Failed to reconnect...");
     client.connect(server,port);
     delay(500);
  }

  client.write(WiFi.RSSI());

  // Add for nothing. Not sure if it's useful
  // PPK: Me too ;-)
  delay(100);

  unsigned long timemark = millis();
  // Client timeout, if client can't reach the server,
  // it should start to reconnect the server
  while( client.available() == 0 )
  {
    if (millis() - timemark >= clientTimeout)
    {
      Serial.println(">>> Client timed out !");
      client.stop();
      break;
    }
  }

  if ( client.connected() && client.available() > 0 )
  {
    // remove bytes in the read buffer
    client.flush();
  }
}

I still get Exception 29 error with your code

Thank you @Peter. I fixed the problem by checking the 8266 documentation and the source file shown in stack dump. And I use your code which is better than mine. :p

Oh. I also delete the whole client timeout procedure, which I think that while(client.connected()) has already done the work.

@Rick Your welcome. As I said, I could not try the code, I had just an idea ;-). I appreciate your answer. I confess I did not realize that you have to use read instead of flush. So I learned a bit more, thank you. I hope you check your answer as the accepted one when it is possible.


text:
Error to work in reverse VNH2SP30
ım building a rover and ı using Johson 12v Dc motor and VNH2SP30. My code and motor works perfectly but my motor driver works only one way. It cant go to reverse and motor starts buzzing when it tries to go in reverse. Here is the code ım using for testing.
#define BRAKE 0
#define CW    1
#define CCW   2
#define CS_THRESHOLD 15   // Definition of safety current (Check: "1.3 Monster Shield Example").

//MOTOR 1
#define MOTOR_A1_PIN 7
#define MOTOR_B1_PIN 8

#define PWM_MOTOR_1 5

#define CURRENT_SEN_1 A2

#define EN_PIN_1 A0

#define MOTOR_1 0

short usSpeed = 150;  //default motor speed
unsigned short usMotor_Status = BRAKE;

void setup()
{
  pinMode(MOTOR_A1_PIN, OUTPUT);
  pinMode(MOTOR_B1_PIN, OUTPUT);

  pinMode(PWM_MOTOR_1, OUTPUT);

  pinMode(CURRENT_SEN_1, OUTPUT);

  pinMode(EN_PIN_1, OUTPUT);

  Serial.begin(9600);              // Initiates the serial to do the monitoring
  Serial.println("Begin motor control");
  Serial.println(); //Print function list for user selection
  Serial.println("Enter number for control option:");
  Serial.println("1. STOP");
  Serial.println("2. FORWARD");
  Serial.println("3. REVERSE");
  Serial.println("+. INCREASE SPEED");
  Serial.println("-. DECREASE SPEED");
  Serial.println();

}

void loop()
{
  char user_input;

  while(Serial.available())
  {
    user_input = Serial.read(); //Read user input and trigger appropriate function
    digitalWrite(EN_PIN_1, HIGH);

    if (user_input =='1')
    {
       Stop();
    }
    else if(user_input =='2')
    {
      Forward();
    }
    else if(user_input =='3')
    {
      Reverse();
    }
    else if(user_input =='+')
    {
      IncreaseSpeed();
    }
    else if(user_input =='-')
    {
      DecreaseSpeed();
    }
    else
    {
      Serial.println("Invalid option entered.");
    }

  }
}

void Stop()
{
  Serial.println("Stop");
  usMotor_Status = BRAKE;
  motorGo(MOTOR_1, usMotor_Status, 0);
}

void Forward()
{
  Serial.println("Forward");
  usMotor_Status = CW;
  motorGo(MOTOR_1, usMotor_Status, usSpeed);
}

void Reverse()
{
  Serial.println("Reverse");
  usMotor_Status = CCW;
  motorGo(MOTOR_1, usMotor_Status, usSpeed);
}

void IncreaseSpeed()
{
  usSpeed = usSpeed + 10;
  if(usSpeed > 255)
  {
    usSpeed = 255;
  }

  Serial.print("Speed +: ");
  Serial.println(usSpeed);

  motorGo(MOTOR_1, usMotor_Status, usSpeed);
}

void DecreaseSpeed()
{
  usSpeed = usSpeed - 10;
  if(usSpeed < 0)
  {
    usSpeed = 0;
  }

  Serial.print("Speed -: ");
  Serial.println(usSpeed);

  motorGo(MOTOR_1, usMotor_Status, usSpeed);
}

void motorGo(uint8_t motor, uint8_t direct, uint8_t pwm)         //Function that controls the variables: motor(0 ou 1), direction (cw ou ccw) e pwm (entra 0 e 255);
{
  if(motor == MOTOR_1)
  {
    if(direct == CW)
    {
      digitalWrite(MOTOR_A1_PIN, LOW);
      digitalWrite(MOTOR_B1_PIN, HIGH);
    }
    else if(direct == CCW)
    {
      digitalWrite(MOTOR_A1_PIN, HIGH);
      digitalWrite(MOTOR_B1_PIN, LOW);
    }
    else
    {
      digitalWrite(MOTOR_A1_PIN, LOW);
      digitalWrite(MOTOR_B1_PIN, LOW);
    }

    analogWrite(PWM_MOTOR_1, pwm);
  }
}

Looks like you're controlling it right at first glance. Care to share your wiring?

swap the wires between pin 7 and pin 8

hi i just added to wires but ıts not perfectly same


text:
Extra `eecfbba=.@aa` file in sd card
I am doing a project, and I need an SD card. Everything worked well, but after a while when I read the SD card from my PC(Windows 10 64 bit, Intel Core), I found a file called eecfbba=.@aa. It's so big that it almost ate up one GB storage of my SD card. But when I tried to open it with notepad, notepad tells me that there is actually no such file, and asks me if I want to create it. I tried to delete it, but file explorer also told me there is no such file. What is it?
This is my code:
#include <ArduinoJson.h>

// Version 0.20.1.19.3.7:
// 2020/01/19, 16:10, button record test, 7th version.

#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#include <Wire.h>
#include "RTClib.h"
//#include <string.h>

RTC_DS1307 rtc;
String strdoc;
char daysOfTheWeek[7][2] = {"su", "mo", "tu", "we", "th", "fr", "sa"};
#define SD_ChipSelectPin 10  // 如果使用 arduino nano 328 可使用Pin4

TMRpcm audio;
void setup() {
  audio.speakerPin = 8;
  Serial.begin(9600);
  pinMode(25, INPUT_PULLUP);
  pinMode(7, INPUT_PULLUP);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  else
  {
    Serial.println("rtc started");
  }

  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("SD Fail");
    return;
  } else {
    Serial.println("SD OK");
  }

  audio.setVolume(6);
  audio.CSPin = SD_ChipSelectPin;

  StaticJsonDocument<200> doc;
  doc["sensor"] = "gps";
  doc["time"] = 1351824120;
  JsonArray data = doc.createNestedArray("data");
  data.add(48.756080);
  data.add(2.302038);
  serializeJson(doc, strdoc);
}
bool isrecording = false;
bool recordButtonPressed()
{
  return (digitalRead(25) == LOW);
}
bool playButtonPressed()
{
  return (digitalRead(7) == LOW);
}
void loop() {
  delay(200);
  // Below is the formatted datetime.
  DateTime now = rtc.now();
  // Below is the serialized datetime.
  String filename = (String)(now.unixtime() % 10000000) + ".j";
  //  Serial.println(filename);
  if (recordButtonPressed())
    if (!isrecording)
    {
      isrecording = true;
      audio.startRecording("test.wav", 16000, A0);
      Serial.println("stt");
    }
    else
    {
      isrecording = false;
      Serial.println("stp");
      audio.stopRecording("test.wav");
    }
  Serial.println("sdsad991===`=`");
  if (playButtonPressed())
  {
    audio.play("test.wav");
    Serial.println("ply");
  }
  String dataString = strdoc;
  if (!isrecording)
  {
    File dataFile = SD.open(filename, FILE_WRITE);

    if (!dataFile) {
      Serial.println(F("Failed to create file"));
    }
    else
    {
      dataFile.println(dataString);
      Serial.println("Wrote string.");
      dataFile.close();
      Serial.println("Closed file.");
    }
  }
  /* Please ignore this line */
  //  //    audio.play("test.wav"); break;audio.volume(1); break;audio.volume(0); break;audio.stopPlayback(); break;
}

P.S. I'm using Mega 2560, so MISO, MOSI, SCK and CS pins are different.(Which is 50,51,52,10).
Edit 2020/1/25, 14:15(Beijing Time) At 1/20 I have bigger problems. There are more and more big files. All of them are the same situation. For details, take a look at this photo(ignore selected files): Imgur or 咱们中国人上不去imgur，用这个：File-up（直接下载）

@ jsotola thank you for your quick reply. But now I have bigger problems: there are tons of other files! Screenshot of my SD card (P.S. Ignore the selected ones, they're what I want. Focus on the others)

I want to know whet are they and do I need to do anything?

don't use String class

@Juraj thank you I will try that out. But can you please tell me the real reason , why String class would produce such files?

https://majenko.co.uk/blog/evils-arduino-strings

Ok, thank you very much.

Thanks to @Juraj, I fixed the problem. Deleted those files by manually formatting the SD card.
This is not really the answer, you can see the answer in this comment under the question.


text:
Communication between Arduino and python: serial port sending empty data
Arduino code:
this code is provided communication between sensor gy-521 and arduino. I read data by the command "1", after 1000 samples arduino is waited for new command for read data.
Arduino code works well in arduino port.
#include<Wire.h>
const int MPU=0x68;
int16_t AcX,AcY,AcZ;
unsigned long time;
bool allow = false;
//int incom = 0;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(19200);
  while (!Serial);// wait for serial port to connect. Needed for native USB port only
}

void loop(){
  if (allow){ //if allow == true, read data

    for (int i = 0; i < 1000; i++){
      Wire.beginTransmission(MPU);
      Wire.write(0x3B);
      Wire.endTransmission(false);
      Wire.requestFrom(MPU,12,true);
      AcX=Wire.read()<<8|Wire.read();
      AcY=Wire.read()<<8|Wire.read();
      AcZ=Wire.read()<<8|Wire.read();

      time = millis();
      Serial.print(time);Serial.print(",");Serial.print(AcX);Serial.print(",");Serial.print(AcY);Serial.print(",");Serial.println(AcZ);
      delay(0);
    }
    Serial.println(0); //see UPD.3
    allow = false;
  }
}

void serialEvent() {
  while (Serial.available()){ //wait for command
    int incom = Serial.read() - '0';
    Serial.println(incom);
    if (incom == 0){ //if 0 - stop
      allow = false;
      delay(100);
    }
    if (incom == 1){ //if 1 - read data
      allow = true;
      delay(100);
    }
  }
}

Python code:
    def sensors(self):

        self.arduino_port_sensor.reset_input_buffer() #clear buffer

        self.arduino_port_sensor.write(str(1).encode()) #send command to arduino - read data

        main_array = []

        pbar = tqdm(total=self.time_observation) #just to see the progress

        while True:

            values = self.arduino_port_sensor.readline().decode().rstrip().replace(" ", "") #read data, some manipulation for cleaning
            main_array.append(values)

            pbar.update(1)

            if values == '': #if data is empty
                print('!!!!')
                continue
            if values == '0': #see UPD.3
                break

        pbar.close()
        ...bla bla...

I call this function time to time, then in some step, arduino stops sending data -- it sends empty string.
It looks like:
PS. In this code I use 2 ports: for sensor and for motor, 2 different arduino. The principe of working second arduino with motor the same, but it works without any problem (I just send command with "action" to arduino with motor, and then receive answer "received back")

Question: what's wrong with python? how to fix this problem?

UPD
Initialization:
arduino_port_sensor = serial.Serial('/dev/tty.usbmodem143101', 19200, timeout = 1)

UPD.2
It receive command - "1" - read data, the interruption occurs while reading data:

UPD.3
Also i changed the code of arduino -- added the "0" after loop.
UPD.4
If I recall this function after arduno stopped sending data, I get this:

How did you initialize the PySerial? Your python code doesn't show that.

There can be different issues:

Are you sure Arduino is sending something? For example, when you say you stopped getting gata, check if the TX LED on the Arduino board is blinking or not.
Did Arduino actually receive "1" before you stopped getting data?
What's the timeout of the PySerial? Are you trying to read faster than Arduino can provide?

I added initialization 1) yes, because it works some iterations (the most long work about 39 iterations). My program wont work if arduino not sending data. 2) yes, I checked this. Before getting data I always have "1" in the beggining. 3) timeout = 1, btw how it can work in some iterations and not working after?

What I actually meant, WHEN it stopped working, it can be either your Python or the Arduino. It worked for 39 iterations. So Arduino was sending data during those 39 iterations. But when it stopped working, is it because of Arduino is not sending anymore or 'for some reason' Python is not able to read it. One way to verify is, check the Tx LED on the Arduino board WHEN your system stopped working. If the LED still blinks as it was, when the system was working, then we know for sure its the Python we need to fix.

Same for this too, did you receive '1' in the Arduino right before it stopped working? One way to check this is when it stops working print the main_array. If main_array doesn't have '1', that means your Arduino never sent '1' i.e. it never received '1'.

I showed this in UPD.2: arduino receives command - read data - but then something happens 1) YES! Thanks, i didn't really notice this. You are right - when it works (python read data) the  Tx LED blinks. But then I see "!!!!" - empty string - Tx LED is not blinking. So, the problem in arduino?

There can be different reasons for your issue. But from the update you added later, we can at least say that your Arduino sometimes doesn't receive the character "1". And when that happens, your Python gets stuck in the infinite loop of trying to read something from the serial port.
As your Arduino responds with "1" when it receives "1", you can base your application on that i.e. if Arduino doesn't respond with "1", keep sending "1".
I wrote a sample program based on your code. I removed the "Wire" part in the Arduino code as I don't have your sensor. I would urge you to test with this Arduino code to make sure that Your sensor is not blocking your Arduino. Wire read can be blocked forever depending on the IC you are trying to read (and if you don't have a timeout).
int16_t AcX,AcY,AcZ;
unsigned long time;
bool allow = false;

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

void loop()
{
  if (allow) //if allow == true, read data
  {
    for(int i = 0; i < 10; i++)
    {
      AcX = 1;
      AcY = 2;
      AcZ = 3;

      time = millis();
      Serial.print(time); Serial.print(",");
      Serial.print(AcX);  Serial.print(",");
      Serial.print(AcY);  Serial.print(",");
      Serial.println(AcZ);
    }
    Serial.println('0');
    allow = false;
  }
}

void serialEvent()
{
  while (Serial.available()) //wait for command
  {
    int incom = Serial.read() - '0';
    Serial.println(incom);
    if (incom == 0)          //if 0 - stop
    {
      allow = false;
      delay(100);
    }
    if (incom == 1)          //if 1 - read data
    {
      allow = true;
      delay(100);
    }
  }
}

In the Python code, I checked if I received "1" from Arduino. If not I kept trying.
import serial
import time

def sensors():
    # Clear receive buffer
    arduino_port_sensor.reset_input_buffer()

    while True:
        # Send command to arduino to send data
        arduino_port_sensor.write('1'.encode())

        # As arduino send LF and CR at the end, let's strip those from the end
        response = arduino_port_sensor.readline().rstrip(b'\r\n ').decode()

        # Arduino should respond with the cmd that it received,
        # if not, send cmd again
        if response == '1':
            # Arduino acknowledged
            break
        else:
            print('Did not receive 1. Retrying...')

    main_array = []

    while True:
        values = arduino_port_sensor.readline().rstrip(b'\r\n ').decode()

        if values == '':
            print('!!!!')
            # This should never happen, but if it does happen, try to read again
            continue
        elif values == '0':
            # print(main_array)
            # We are done receiveing packets
            break
        else:
            # We are still receiving packets
            main_array.append(values)

arduino_port_sensor = serial.Serial('COM50', 19200, timeout=3)

# Let PySerial get ready
time.sleep(3)

while True:
    sensors()
    time.sleep(1)