message:
How to get data out of loop?

hi i wrote a code(i modified it actually, please forgive me, im in a mess please help me if you can) for my esp8266 to serial communicate with at tiny 85 ,it will monitor switch state and publish accordingly. now i want to write a code where it wont publish but whenever the serial is available i want it to directly take it and digital write in void callback.
```
//ItKindaWorks - Creative Commons 2016
//github.com/ItKindaWorks
//
//Requires PubSubClient found here: https://github.com/knolleary/pubsubclient
//
//ESP8266 Simple MQTT light controller

#include <PubSubClient.h>
#include <ESP8266WiFi.h>

int LED3 = 12;
int LED4 = 14;
int LED2 = 13;
int LED1 = 15;

bool switch1;
bool switch2;
bool switch3;
bool switch4;
char data ;
// the number of the pushbutton pin

//EDIT THESE LINES TO MATCH YOUR SETUP

#define MQTT_SERVER "192.168.0.223"
const char* ssid = "TACHYON_HOME";
const char* password = "qwertyui";

//LED on ESP8266 GPIO2

char* lightTopic = "/test/light1";
char* lightTopic1 = "/test/light2";
char* lightTopic2 = "/test/light3";
char* lightTopic3 = "/test/light4";

WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int length);
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void setup() {
  //initialize the light as an output and set to LOW (off)
  Serial.begin(9600);
  pinMode(LED3 , OUTPUT);
  pinMode(LED4 , OUTPUT);
  pinMode(LED1 , OUTPUT);
  pinMode(LED2 , OUTPUT);

    delay(100);

    // We start by connecting to a WiFi network

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

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected.");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

}

void loop(){
  //reconnect if connection is lost
  if (!client.connected() && WiFi.status() == 3) {reconnect();}

  //maintain MQTT connection
  client.loop();

  //MUST delay to allow ESP8266 WIFI functions to run
  delay(10);
   if (Serial.available()>0) /* If data available at serial port, enter if loop */
  {
    data = Serial.read(); /* Read data present at serial port */
    /* Print string with \r\n */
    Serial.print(data); /* Print data received */
    if (data == 'q') {
      client.publish(lightTopic,"1");

    }
else  if (data == 'w') {
      client.publish(lightTopic,"0");
    }
 else  if (data == 'e') {
      client.publish(lightTopic1,"1");
    }
    else if (data == 'r') {
      client.publish(lightTopic1,"0");

    }
     else if (data == 't') {
      client.publish(lightTopic2,"1");

    }
     else if  (data == 'y') {
      client.publish(lightTopic2,"0");

    }
     else if (data == 'u') {
      client.publish(lightTopic3,"1");

    }
     else if  (data == 'i') {
      client.publish(lightTopic3,"0");

    }

  }
}

void callback(char* topic, byte* payload, unsigned int length)
{
  //convert topic to string to make it easier to work with
  String topicStr = topic;

  //Print out some debugging info
  Serial.println("Callback update.");
  Serial.print("Topic: ");
  Serial.println(topicStr);

 if(topicStr.equals(lightTopic)){

   if(payload[0] == '1'){
      digitalWrite(LED1 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED1 , LOW);
    }
 }
 if(topicStr.equals(lightTopic1)){

   if(payload[0] == '1'){
      digitalWrite(LED2 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED2 , LOW);
    }
 }
 if(topicStr.equals(lightTopic2)){

   if(payload[0] == '1'){
      digitalWrite(LED3 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED3 , LOW);
    }
 }
  if(topicStr.equals(lightTopic3)){

   if(payload[0] == '1'){
      digitalWrite(LED4 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED4 , LOW);
    }
  }

}

void reconnect() {

  //attempt to connect to the wifi if connection is lost
  if(WiFi.status() != WL_CONNECTED){
    //debug printing
    Serial.print("Connecting to ");
    Serial.println(ssid);

    //loop while we wait for connection
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }

    //print out some more debug once connected
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
  }

  //make sure we are connected to WIFI before attemping to reconnect to MQTT
  if(WiFi.status() == WL_CONNECTED){
  // Loop until we're reconnected to the MQTT server
    while (!client.connected()) {
      Serial.print("Attempting MQTT connection...");

      // Generate client name based on MAC address and last 8 bits of microsecond counter
      String clientName;
      clientName += "esp8266-";
      uint8_t mac[6];
      WiFi.macAddress(mac);
      clientName += macToStr(mac);

      //if connected, subscribe to the topic(s) we want to be notified about
      if (client.connect((char*) clientName.c_str())) {
        Serial.print("\tMTQQ Connected");
        client.subscribe(lightTopic);
        client.subscribe(lightTopic1);
        client.subscribe(lightTopic2);
        client.subscribe(lightTopic3);

      }

      //otherwise print failed for debugging
      else{Serial.println("\tFailed."); abort();}
    }
  }
}

//generate unique name from MAC addr
String macToStr(const uint8_t* mac){

  String result;

  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);

    if (i < 5){
      result += ':';
    }
  }

  return result;
}

//////////////////i want to write some thing like///////////////////////////////////////
////////////////////////////////
if(topicStr.equals(lightTopic1)||Serial.available()>0){

   if(payload[0] == '1'|| data =q){
      digitalWrite(LED2 , HIGH);
    }

    else if (payload[0] == '0'|| data = w){
      digitalWrite(LED2 , LOW);
    }
/////////////////////////////////////////
```

body:
So you want your program to react to both MQTT and serial messages. You
wrote this snippet:

```cpp
if (topicStr.equals(lightTopic1) || Serial.available() > 0) {
    if (payload[0] == '1' || data = q) {
        digitalWrite(LED2, HIGH);
    }
    else if (payload[0] == '0' || data = w) {
        digitalWrite(LED2 , LOW);
    }
    // ...
}
```

Other than a couple of syntactic problems (you mean `data == 'q'`, not
`data = q`), the logic is not appropriate. This is because:

* The test `payload[0] == '1'` only makes sense in the context of
  parsing an MQTT message, otherwise `payload` cannot be meaningfully
  defined.
* For the same reason, the test `data == 'q'` only makes sense in the
  context of parsing a serial command.

Since MQTT and serial use completely different commands, you will have
to handle them independently. You can keep the MQTT callback as is, and
implement the parser for the serial commands. Maybe something like:

```cpp
if (Serial.available()) {
    char command = Serial.read();
    Serial.print(command);  // echo to the serial port
    switch (command) {
        case 'q':
            digitalWrite(LED1, HIGH);
            break;
        case 'w':
            digitalWrite(LED1, LOW);
            break;
        // ...
    }
}
```

Alternatively, use an `if ... else if ...` chain if you are not
comfortable with the `switch` syntax.

I personally would rather store the topic names, LED pins and serial
commands in an array of structs, and loop through the array in both the
MQTT callback and the serial parser. But I assume that may be too
advanced for your current programming level, so maybe just stick with
the simple, albeit verbose solution.


sender: user

message:
ESP-01 does not run code after Deep Sleep

When using the deep sleep functionality on several ESP-01 boards, the boards require two resets in order to wake up properly (regardless of whether the resets are done by manually bridging the rst pin or by soldering a wire to do it from an interrupt). The boards do wake up and print some text automatically, but they do not run their firmware/code.

```c
#include <ESP8266WiFi.h>
void setup() {
    Serial.begin(74880);
    Serial.print("\n--------------STARTING----------------\n");

    //pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    //digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off (gpio @ high= off)

    delay(500);
    ESP.deepSleep(2000000, WAKE_RF_DEFAULT );
}

void loop() {
}
```

I have not been able to just wake the board and run the code like most examples on the web intend to work, so I suppose the problem is not with this code.

On a successful wake up, the serial output looks like this:

```
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)
load 0x4010f000, len 3456, room 16
tail 0
chksum 0x84
csum 0x84
va5432625
~ld

--------------STARTING---------------
```

After the first reset, the board does indeed wake up, but it does not run it's code. It only prints this
```
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)
```

And then hangs there. After another reset, it successfully runs it's code.

This issue persists across all the esp 01 boards i own, and i have tried pulling UP and DOWN almost every combination of pins recommended. The line that is printed in the fauly cases does indeed say it is booting in the right mode, but still the code does not run, nor mine nor the one that runs before mine

sender: assistant

body:
What sasso is describing is classic Deep Sleep Zombie mode. There's someone else here with ESP-01 boards with the same issue.  I'd bet you got your boards in blister packs from Inland.  I didn't see any ESP-01 boards from Inland at my local computer store, only ESP-01S, and that one works with Deep Sleep just fine.  I only bought the one for a test.  I believe it's the Flash chip, but we haven't proven that yet.  I have plenty of Winbond flash in case I find a board that goes zombie, and can prove or disprove my theory.  I have 8 different types of boards and modules, and all come out of Deep Sleep correctly.

edit: If the pic at Ali is correct, the Puya Flash shouldn't be causing an issue, presuming it's real and not a clone.  Half the time the pics are only 'representative examples' of what they ship.  The ESP8266 Arduino core has supported Puya for a while now.  Also, on sober reflection the Inland package I bought said ESP-01S, and it's actually an ESP-01 (false advertising).  I looked closer and didn't see the pull-up resistors. :-(

If you're powering it from that USB programmer board, it should work.  If you have a separate 3.3V supply, I'd be suspicious of the supply.  The current spikes as the ESP is booting will cause many switching supplies to drop below 2V briefly, and the ESP goes insane.  Without having a zombie in front of me, I'm at a loss to go a lot further as my 'scope leads aren't that long.


message:
Add char at intervals in a String

I'm trying to create a function that will take a String as an input, and at every 20 characters, it will instert "\n" so that the string doesn't go off the side of my screen (I'm using an oled with the [SSD1306Ascii library][1]).

This is my code so far, but when I run it nothing appears on the screen (I have another part of the code which passes the string to the funtion):

    String message = "";
    String newMessage = "";

    void printMessage(String message) {
      oled.clear();
      if(message.length() > 20) {
        current = 20;
        while(current < message.length()) {
          newMessage = message.substring(current-20, current) + "\n";
          newMessage = newMessage + message.substring(current+1);
          current+20;
        }
        oled.println(newMessage);
      }
      else {
        oled.println(message);
      }
    }

  [1]: https://github.com/greiman/SSD1306Ascii

body:
I think that your implementation is fundamentally flawed. In the while loop, when you assign `newMessage` to a `message.substring` you are discarding all the work done in the previous iterations.

Also I would recommend keeping the splitting and the printing separated. The `operator +=` also is very handy here. This code (untested) should implement your original idea in a correct way

    String splitMessage( const String & message, const unsigned limit) {
      String newMessage = "";
      unsigned i = 0;
      while ( i+limit < message.length() ) {
        newMessage += message.substring(i, i+limit);
        newMessage += '\n';
        i += limit;
      }
      newMessage += message.substring(i);
      return newMessage;
    }

Then you can do:

    whatever.println(splitMessage(myMessage, 20));

----

Note that I retained the use of `String` from your original implementation, although, being in an embedded environment, it is likely better to avoid it in favor of stack-allocated c-strings.

I have found a substantial amount of pretty enlightening information in the various answers to this question: https://arduino.stackexchange.com/questions/682/is-using-malloc-and-free-a-really-bad-idea-on-arduino


body:
One issue with both your failed implementation and the previous answer
is that they do loads of dynamic allocations and copies. Every time you
use the String’s `+` or `+=` operators you are allocating heap memory
for a brand new String, copying the original character data into the
newly allocated space, and eventually destroying the original Strings
when you don’t need them anymore.

The simplest way to avoid all these copies and allocations is to _not_
build the String you want. Instead, just `write()` the pieces one after
the other on the display. Here is a zero-copy, zero-dynamic allocation
solution:

```cpp
void printMessage(const char *message) {
    size_t length = strlen(message);
    while (length > 20) {
        oled.write(message, 20);
        oled.write('\n');
        message += 20;  // point to the rest of the message
        length  -= 20;  // remaining length
    }
    oled.write(message);
}
```

Note that the method `Print::write(const char *, size_t)` is used here
to print a slice of the message without ever building it as a string in
memory.

On these memory-constrained devices it is always preferable to avoid
heap allocation, and thus `String` objects. However, if for whatever
reason you _really_ need to print a `String` object, then you can use
the following overload to print it’s internal buffer without making any
extra copy:

```cpp
void printMessage(const String &message) {
    printMessage(message.c_str());
}
```


message:
Connecting microSD reader and e-paper display to Nano at the same time?

Pretty much as the question states, I'm wondering if it's possible to connect (this: https://www.waveshare.com/7.5inch-HD-e-Paper-HAT.htm ) 7.5" e-paper display that has raspberry pi HAT and an SD card reader to Arduino nano/micro for reading images off SD and displaying on the screen. I'm an novice and a not sure if i can use the same pins for multipurpose

Thanks!

body: No. Even the e-Paper alone is not usable by an Arduino Nano.


message:
How to use capactive touch on Adafruit board in Arduino mode?

I have a Trinket M0 which has three pins capable of capacitive touch, A0, A3, and A4. When using CircuitPython on these boards you can use the [CapTouch](https://learn.adafruit.com/adafruit-trinket-m0-circuitpython-arduino/circuitpython-cap-touch-2) Library. But as far as I can tell this does not exist for use in Arduino mode. Does anyone know how to get these pins to pick up capacitive touch? I've tried the Adafruit_FreeTouch library, but with zero documentation, it's not very user friendly. I thought I had it working with two pins, but whenever both pins detect capacity, the capacity is divided between them, so both pins report about the same capacity.

Any help would be greatly appreciated.

This question does seem like a duplicated of https://arduino.stackexchange.com/questions/43663/built-in-capacitive-touch-detection-with-samd21-development-board-arduino-zero but there was never a solution.

Thanks!

body:
Example code for capacitive touch on Trinket M0.  Note: make sure to install the Adafruit FreeTouch library.

    // touch - Capacitive touch demo using FreeTouch. Trinket M0 version.
    // Note: the pin silkscreened 1 is Analog Pin 0.

    #include "Adafruit_FreeTouch.h"

    Adafruit_FreeTouch qt_1 = Adafruit_FreeTouch(A0, OVERSAMPLE_4, RESISTOR_50K, FREQ_MODE_NONE);

    void setup()
    {
      // Initialize A0 as a touch sensor
      if (! qt_1.begin())
        Serial.println("Failed to begin qt on pin A0");
    }

    void loop()
    {
      int counter, result = 0;
      counter = millis();
      result = qt_1.measure();
      Serial.print("QT 1: "); Serial.print(result);
      Serial.print(" (");  Serial.print(millis() - counter); Serial.println(" ms)");
      Serial.println("\n*************************************");
      delay(200);
    }

Information about the parameters for the constructor can be found at: https://forums.adafruit.com/viewtopic.php?f=8&p=610501  and are paraphrased below incase the link goes dead.

The parameters for the constructor are:

p - The input pin connected to the sensor.

t - How much to oversample the input.  One of the following:

    OVERSAMPLE_1
    OVERSAMPLE_2
    OVERSAMPLE_4
    OVERSAMPLE_8
    OVERSAMPLE_16
    OVERSAMPLE_32
    OVERSAMPLE_64

Oversampling is a process of taking several measurements, finding the average, and reporting that instead of the actual readings. It's way of reducing noise, but also improves the accuracy of the measurement. The average value of noise is zero (if it wasn't, it would be a source of free energy), so the more readings you add together, the closer the noise error in the measurements approaches zero.

There's another side-effect of adding noise to measurements though: it dithers the sensor output around the real input value. If I have a window comparator that only measures "below 1v" and "above 2v", and feed it a signal at 1.1v plus a couple of volts of noise, I can expect to see about ten "below 1v" outputs for every one "above 2v" output. The noise pushes the signals above and below the thresholds, but vanishes if I take the average of a large enough sample. Statistically, getting a 10:1 improvement in resolution like that would take about 64 readings to make the noise error small enough to ignore.

Oversampling takes longer though, so there's always a tradeoff between how much you can do and how long the signal will remain stable.

r - The value of the resistor that will discharge the touch pad.  One of the following:

    RESISTOR_0
    RESISTOR_20K
    RESISTOR_50K
    RESISTOR_100K

f - Frequency mode.  One of the following:

    FREQ_MODE_NONE
    FREQ_MODE_HOP
    FREQ_MODE_SPREAD
    FREQ_MODE_SPREAD_MEDIAN

For systems that take repeated measurements, there's one kind of noise that doesn't average to zero: noise that occurs at the same frequency as the sampling rate. There are all sorts of videos that show the effect of a camera being in sync with the thing it's recording.. this one is especially nice:   https://www.youtube.com/watch?v=uENITui5_jU

For capacitive sensors, things like induced signal from fluorescent lights can create noise, and if the lamp frequency is just slightly off of your sampling frequency, the touch system will think it looks like a series of touches.

(If you have an oscilloscope, hold the tip of a probe between your fingers and put your hand within a foot or so of a fluorescent light.)

One way to prevent that is to change the sampling frequency. You can shift it up and down in a predictable pattern, hop from one frequency to another, or add some random jitter. Atmel's QTouch library supports all those options, but 'NONE' (fixed frequency readings) is the simplest.


message:
Circuit not working with 9 volt battery

I have made a simple circuit having an IR receiver and a Servo motor. Here is the diagram:

[![arduino circuit][1]][1]

Red wire: power

Black wire: ground

Orange wire: digital signal

And here's the code:
```
#include <Servo.h>
#include <IRremote.h>
int receiver = 13;
IRrecv irrecv(receiver);
decode_results results;
Servo myServo;
int pos = 0;
void setup() {
  // put your setup code here, to run once:
  myServo.attach(9);
  Serial.begin(9600);
  irrecv.enableIRIn();
  myServo.write(0);
  delay(200);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (irrecv.decode(&results)){

    if (results.value== 0xC0000C){
      for (pos = 0; pos <= 90; pos += 10) {
        // in steps of 1 degree
        myServo.write(pos);
        delay(15);
      }
      for (pos = 90; pos >= 0; pos -= 10) {
        myServo.write(pos);
        delay(15);
      }
    }
  }
  irrecv.resume();
  delay(100);
}
```
It rotates the motor 90 degree and back when a button on a remote is clicked.

Here comes the problem: This is working perfectly when connected to my PC, but it doesn't when I connect it with my 9-volt (cuboid shaped) battery. The lights on the Arduino board still light up, but the circuit does nothing when I press the remote button.

I have also observed that the servo vibrates a little bit, but doesn't move.

Is this a problem in my circuit, or is it just that my battery power is low?

[1]: https://i.stack.imgur.com/bPCPN.png

body:
A 9V battery has both low peak current and low total power (low mAh rating). It is not a good choice for any circuit that draws more than ≈100 mA. (I pulled that number out of thin air, but it's probably a decent guess)

Build a battery pack from 6 AA alkaline cells instead. That will provide enough peak current. Or for much longer run-time, use 6 D sized cells.


message:
Problem on interfacing 3 flame sensors and servo to Arduino Fire Fighter

I had been trying to make Arduino Fire Fighter Robot but facing several problems in interfacing 3 flame sensors and servo together. When I upload the following code( Which I had posted at the end of my writing) my robot goes backward and detects flame at the front sensor and displays " Flame on Front" on 16x2 LCD display and the 5v  pump pumps out water and the red LED blinks. But I want that my robot will work in the following way- Initially, my robot will be at rest. There are 3 sensors attached at the front part of the robot. And there is a SG90 servo for rotating the water tank( in this tank there is a 5v pump motor and the pump motor will pump out water from this tank). When any one of the three flame sensors  will detect flame then the servo will rotate in that direction and when the front flame sensor detects fire , the servo will be in 90-degree angle and water will be pumped out. LCD will display the status of the flame sensors. But the robot is not working properly. I am not able to interface 3 flame sensors and servo together. My robot is not working according to my expectation as I had said before.

    int pos = 0;
    boolean fire = false;

    #include <LiquidCrystal.h>
    int Contrast=20;// for adjusting the brightness of the LCD , 20 is selected for the contrast of LCD
    LiquidCrystal lcd(30,31,32,33,34,35);
    int buzz= 38; //for led or buzzer
    #define Left_S 9 // left sensor
    #define Right_S 8     // right sensor
    #define Forward_S 23  //forward sensor
    #define LM1 52 //for pump motor
    #define LM2 53 //for pump motor
    #define IN1 5   //for motor
    #define IN2 4  // for motor
    #define IN3 3      //for motor
    #define IN4 22     // for motor
    //int flame_pin1 = HIGH ;
    int LEDR= 36; // for danger signal
    int LEDB=37;// for safe signal

    void setup ( )  {
       analogWrite(6,Contrast);
         lcd.begin(16, 2);
          pinMode(Left_S, INPUT);
      pinMode(Left_S, INPUT);
      pinMode(Right_S, INPUT);
         pinMode (Forward_S,OUTPUT);
         pinMode (LEDB,OUTPUT);
     pinMode(LM1, OUTPUT);
     pinMode(LM2, OUTPUT);
      pinMode(IN1, OUTPUT);
      pinMode(IN2, OUTPUT);
      pinMode(IN3, OUTPUT);
      pinMode(IN4, OUTPUT);
      pinMode( buzz,OUTPUT );
      pinMode(LEDR,OUTPUT);
      pinMode(LEDB, OUTPUT);
     // pinMode ( flame_sensor_pinM , INPUT );
      //Serial.begin ( 9600 );
       myservo.attach(25);
      myservo.write(90);
    }
     void put_off_fire()
    {
        delay (500);

        digitalWrite(IN1, HIGH);
        digitalWrite(IN2, HIGH);
        digitalWrite(IN3, HIGH);
        digitalWrite(IN4, HIGH);

       digitalWrite(LM1, HIGH);
       digitalWrite(LM2, LOW);
       delay(500);

        for (pos = 50; pos <= 130; pos += 1) {
        myservo.write(pos);
        delay(10);
      }
      for (pos = 130; pos >= 50; pos -= 1) {
        myservo.write(pos);
        delay(10);
      }

      digitalWrite(LM1,LOW);
      digitalWrite(LM2,LOW);
      myservo.write(90);

      fire=false;
    }

    void loop ( ){
       myservo.write(90); //Sweep_Servo();

        if (digitalRead(Left_S) ==1 && digitalRead(Right_S)==1 && digitalRead(Forward_S) ==1) //If Fire not detected all sensors are zero
        {
        //Do not move the robot
        lcd.setCursor(0, 1);
          lcd.print("No flame");
        digitalWrite(IN1, HIGH);
        digitalWrite(IN2, HIGH);
        digitalWrite(IN3, HIGH);
        digitalWrite(IN4, HIGH);
        digitalWrite(LEDR,LOW);
        digitalWrite(LEDB,HIGH);
        digitalWrite(buzz,LOW);
        }

        else if (digitalRead(Left_S) ==0) //If Fire is straight ahead
        {
        //Move the robot forward
        lcd.setCursor(0, 1);
          lcd.print("Flame on Left");
        digitalWrite(IN1, HIGH);
        digitalWrite(IN2, LOW);
        digitalWrite(IN3, HIGH);
        digitalWrite(IN2, LOW);
        digitalWrite(LEDR,HIGH);
        digitalWrite(LEDB,LOW);
        digitalWrite(buzz,HIGH);
        fire = true;

        }
        else if (digitalRead(Forward_S) ==0) //If Fire is straight ahead
        {
        //Move the robot forward
        lcd.setCursor(0, 1);
          lcd.print("Flame on front");
        digitalWrite(IN1, HIGH);
        digitalWrite(IN2, LOW);
        digitalWrite(IN3, HIGH);
        digitalWrite(IN2, LOW);
        digitalWrite(LEDR,HIGH);
        digitalWrite(LEDB,LOW);
        digitalWrite(buzz,HIGH);
        fire = true;

        }

        else if (digitalRead(Right_S) ==0) //If Fire is to the right
        {
        //Move the robot right
        lcd.setCursor(0, 1);
          lcd.print("Flame on Right");
        digitalWrite(IN1, HIGH);
        digitalWrite(IN2, HIGH);
        digitalWrite(IN3, HIGH);
        digitalWrite(IN4, LOW);
        digitalWrite(LEDR,HIGH);
        digitalWrite(LEDB,LOW);
        digitalWrite(buzz,HIGH);
        fire= true;
        }

         delay(300); //Slow down the speed of robot

         while (fire == true)
         {
          put_off_fire();
         }
    }

body:
If you format your code correctly, the code becomes less cluttered and the problem becomes more visible.

Also, if you think about the `if` statements, there is no need to check for `no fire` for all three sensors at the same time. If none of the three sensors see fire, then the only possibility that is left, is `no fire`.

Another thing, you have no `digitalWrite(IN1, LOW);` and no `digitalWrite(IN3, LOW);` in your code. You could put `digitalWrite(IN1, HIGH);` and `digitalWrite(IN3, HIGH);` in `setup()`

Here is your code rewritten and formatted.

Couple of unnecessary duplications are tagged.

There is no reason to use `while (fire == true)` because `put_off_fire()` clears the `fire` flag

Also, for future programs, `while (fire == true)` is a redundant form because it is same as `while (fire)`

Have a really close look at the `if` statement blocks.

You used copy&paste when writing the code, but you forgot to make changes.

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(30, 31, 32, 33, 34, 35);

    #define Left_S       9                       // left    sensor
    #define Right_S      8                       // right   sensor
    #define Forward_S   23                       // forward sensor

    #define LM1         52                       // for pump motor
    #define LM2         53                       // for pump motor

    #define IN1          5                       // for motor
    #define IN2          4                       // for motor
    #define IN3          3                       // for motor
    #define IN4         22                       // for motor

    //int flame_pin1 = HIGH ;

    int LEDR     = 36;                           // for danger signal
    int LEDB     = 37;                           // for safe signal
    int buzz     = 38;                           // for led or buzzer
    int pos      =  0;
    int Contrast = 20;                           // for adjusting the brightness of the LCD , 20 is selected for the contrast of LCD

    boolean fire = false;

    void setup() {

        analogWrite(6, Contrast);

        lcd.begin(16, 2);

        pinMode( Left_S            , INPUT  );
        pinMode( Left_S            , INPUT  );
        pinMode( Right_S           , INPUT  );

        pinMode( Forward_S         , OUTPUT );
        pinMode( LEDB              , OUTPUT );   // xxxxxxxxxxxxx        duplicate

        pinMode( LM1               , OUTPUT );
        pinMode( LM2               , OUTPUT );

        pinMode( IN1               , OUTPUT );
        pinMode( IN2               , OUTPUT );
        pinMode( IN3               , OUTPUT );
        pinMode( IN4               , OUTPUT );

        pinMode( buzz              , OUTPUT );

        pinMode( LEDR              , OUTPUT );
        pinMode( LEDB              , OUTPUT );   // xxxxxxxxxxxxx        duplicate

    //  pinMode( flame_sensor_pinM , INPUT  );

    //  Serial.begin ( 9600 );

        myservo.attach(25);
        myservo.write(90);
    }

    void put_off_fire() {

        delay (500);

        digitalWrite(IN1, HIGH);
        digitalWrite(IN2, HIGH);
        digitalWrite(IN3, HIGH);
        digitalWrite(IN4, HIGH);

        digitalWrite(LM1, HIGH);
        digitalWrite(LM2, LOW );
        delay(500);

        for (pos = 50; pos <= 130; pos += 1) {
            myservo.write(pos);
            delay(10);
        }

        for (pos = 130; pos >= 50; pos -= 1) {
            myservo.write(pos);
            delay(10);
        }

        digitalWrite(LM1, LOW);
        digitalWrite(LM2, LOW);

        myservo.write(90);                       // xxxxxxxxxxxxx        duplicate

        fire = false;                            // xxxxxxxxxxxxx        not needed
    }

    void loop() {

        myservo.write(90);                       // xxxxxxxxxxxxx        duplicate
    //  Sweep_Servo();

        lcd.setCursor(0, 1);

        fire = true;                             // preset the state (gets cleared when no fire is detected

        if (digitalRead(Left_S) == 0) {          // If Fire is straight ahead

            lcd.print("Flame on Left");

            digitalWrite(IN1 , HIGH);            // Move the robot forward
            digitalWrite(IN2 , LOW );
            digitalWrite(IN3 , HIGH);
            digitalWrite(IN2 , LOW );
        }

        else if (digitalRead(Forward_S) == 0) {  // If Fire is straight ahead

            lcd.print("Flame on front");

            digitalWrite(IN1 , HIGH);            // Move the robot forward
            digitalWrite(IN2 , LOW );
            digitalWrite(IN3 , HIGH);
            digitalWrite(IN2 , LOW );
        }

        else if (digitalRead(Right_S) == 0) {    // If Fire is to the right

            lcd.print("Flame on Right");

            digitalWrite(IN1 , HIGH);            // Move the robot right
            digitalWrite(IN2 , HIGH);
            digitalWrite(IN3 , HIGH);
            digitalWrite(IN4 , LOW );
        }

        else {                                   // fire was not detected by any of the sensors

            fire = false;

            lcd.print("No flame");

            digitalWrite(IN1 , HIGH);            // Do not move the robot
            digitalWrite(IN2 , HIGH);
            digitalWrite(IN3 , HIGH);
            digitalWrite(IN4 , HIGH);
        }

        delay(300);                              // Slow down the speed of robot

        if (fire) {

            digitalWrite(LEDR, HIGH);            // do fire lights
            digitalWrite(LEDB, LOW);
            digitalWrite(buzz, HIGH);

            put_off_fire();
        }

        else {

            digitalWrite(LEDR, LOW );            // do nofire lights
            digitalWrite(LEDB, HIGH);
            digitalWrite(buzz, LOW );

        }
    }


message:
Dragino lg01-p problem with serial monitor

i have a dragino lg01-p lora gateway to which i successfully communivate through lora with an arduino and i can program it through network as expected and seen in its manual with the demo client-server code. However, when i try to open the serial monitor on the side of the dragino, i get this:

Unable to connect: retrying (1)...

Unable to connect: retrying (2)...

Unable to connect: retrying (3)...

Unable to connect: retrying (4)...

Unable to connect: is the sketch using the bridge?

I need to have the serial communication cause i made a little app in C# which gets the data from a COM port. I also tried with Console instead of serial, but still didn't get any results back. This is the code, exactly as is in the examples no the manual

```
#include <SPI.h>
#include <RH_RF95.h>

// Singleton instance of the radio driver
RH_RF95 rf95;

int led = A2;
float frequency = 868.0;

void setup()
{
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  while (!Serial) ; // Wait for serial port to be available
  Serial.println("Start Sketch");
  if (!rf95.init())
    Serial.println("init failed");
  // Setup ISM frequency
  rf95.setFrequency(frequency);
  // Setup Power,dBm
  rf95.setTxPower(13);
  // Defaults BW Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on
  Serial.print("Listening on frequency: ");
  Serial.println(frequency);
}

void loop()
{
  if (rf95.available())
  {
    // Should be a message for us now
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    uint8_t len = sizeof(buf);
    if (rf95.recv(buf, &len))
    {
      digitalWrite(led, HIGH);
      RH_RF95::printBuffer("request: ", buf, len);
      Serial.print("got request: ");
      Serial.println((char*)buf);
      Serial.print("RSSI: ");
      Serial.println(rf95.lastRssi(), DEC);

      // Send a reply
      uint8_t data[] = "And hello back to you";
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent a reply");
      digitalWrite(led, LOW);
    }
    else
    {
      Serial.println("recv failed");
    }
  }
}
```

body:
Found it so i will share my problem here to help someone else!

Apparently ```Bridge``` funcions work better for this device if you include ```Process.h``` rather than ```Bridge.h```.


message:
How can I make my Arduino Uno press Space on my laptop keyboard?

So I wanna build something which, when it receives a remote signal, presses the spacebar on my laptop keyboard. I tried using the Keyboard.press() but it is available only for Leonardo. Is there any way I can use it in my Uno, without having to mess with the firmware?

If not, what else can I use to accomplish my goal?

body:
if you have some knowledge in Java or Python you can interface your Arduino board to PC, through Arduino's SerialPort.
When Arduino sends a byte, for example, 0xAB, your Java or Python script sends a fake key-press event.
I hope this can help. Good luck!


body:
On Windows you can use a serial to keyboard redirector like [this one][1]

It can start with windows, Im using it for a long time without any issues.
[![enter image description here][2]][2]

  [1]: http://www.priority1design.com.au/datasnip.html
  [2]: https://i.stack.imgur.com/I8YhV.png


message:
Junk values in EEPROM. while writing large values

Facing an issue while writing a large value *(like 2000-5000)* to EEPROM using `EEPROM.put().`

For example, While writing 2000 values to address 5 of EEPROM. Some junk values are written automatically to a nearby address (address 4, 6, 7...).

*Note : Not trying to write an array of 2000 elements*

Board Used : Arduino Uno (Atmega328P)

Q1 : What is the typical range of a each address by using `EEPROM.put()` . Like `EEPROM.write()` has range limit of 0-255.

Q2 : How to write large value EEPROM addresses without effecting the nearby address.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/QVF7b.jpg

body:
It depends on what type of variable you have.  If you have single byte variables like byte or char then it is one value to one address.  But if you have an int value like:

    int x = 2000;

then try to store that in EEPROM that will take 2 bytes because an int is 2 bytes in size.  So if you write that to address 5 it will take 5 and 6 to write it.

If you write a long or a float, they are 4 bytes, so they will take 4 address slots in the EEPROM each.

If you just write EEPROM.put(5, 2000); then the 2000 gets seen as either int or long depending on how the code is written.  I don't remember.  But you certainly can't fit 2000 into a byte so it's going to have to take more than one.


message:
Uno went in washer and when I shake I hear something shaking around. What do I hear?

My friends Uno went in washer. I gave it a week to dry and when i plug it in, it works. But when I shake I hear something shaking around inside it. What do I hear shaking around?

body: It could be the USB port, barrel jack port, or most likely the pin header. The pin headers are a plastic shell with a two-point prong thing that goes in it. the pin could have desoldered when in the washer. check the pin headers. It might also be the inside of capacitors but that is highly unlikely.


message:
How to use Atmega328p-PU from an Uno, on a breadboard without a crystal

How do you use Atmega328p-PU from an Uno, on a breadboard without a crystal?

body: You can use another IC like the 555 timers as an external oscillator.


body:
If you buy your ATmega as supplied by Microchip, through one of the
large electronic parts resellers, it will come with its default fuse
configuration:

* clock source: internal 8 MHz RC oscillator
* clock prescaler enabled at ÷8, yielding a 1 MHz system clock
* bootloader disabled

You could use it in this configuration, but you will probably want to
disable the prescaler. This can be done by changing the right fuse or,
alternatively, by some code running early in `setup()`. Note that, with
no bootloader, you will need an ISP programmer in order to load the
code. If you want the convenience of serial downloading (i.e. you would
use an FTDI cable rather than an ISP programmer), you will have to burn
the bootloader using an ISP programmer, and adjust the fuses to enable
it and set its size.

If you take the ATmega from an existing Uno board, or buy one
preconfigured with the bootloader, the fuses will be set differently:

* clock source: external crystal
* clock prescaler disabled
* bootloader enabled and sized to 0.5 KiB

In this case you will have to change the clock source.

In any case, you would tell the IDE you are using an Arduino Fio, or a
Pro or Pro Mini with a 328P clocked at 8 MHz. And you will need an
ISP programmer to load either your program or the bootloader. You could
use an Arduino running the “Arduino as ISP” firmware for this.

Check the datasheet for the details on configuring the fuses. You can
also use one of the online fuse calculators, like [this one][1] or [this
one][2].

[1]: https://www.engbedded.com/fusecalc
[2]: https://eleccelerator.com/fusecalc/


message:
Is it possible to send data from internet server to ESP8266 behind proxy or regular requests from ESP8266 are required?

It would be kind of push notification or something like that probably.
I can first connect to server and send it any data for "registration"...

I found many examples with websockets but all of them was about ESP8266 is like "server". That's not this case...

body:
It seems evident that you don't want your ESP8266 running as a server of any kind. That's understandable given that server programs consume a fair amount of system resources (CPU, RAM, etc.) that are in short supply. That means you'll have to use your ESP8266 as a **client** and this means either

1) **Polling** - where the ESP8266 repeatedly connects to your "internet server" to explicitly ask for information at frequent intervals. Your internet server would have to be able to collect information in batches and hang onto it until your ESP8266 connects again to request the information.

2) **Socket connections** - where your ESP8266 maintains a consistent [socket connection](https://en.wikipedia.org/wiki/Network_socket) to your "internet server." Note that the HTTP protocol relies on socket connections, but clients open a socket connection, request a web page and its images, CSS, etc., then disconnects the socket. You can also use sockets at a more basic level as a bytestream. This programming can be tricky, but ESP8266 does have examples of TCP socket communication like [WiFiClient](https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino) and [ethernet client](https://github.com/esp8266/Arduino/blob/master/libraries/Ethernet/examples/TelnetClient/TelnetClient.ino).

Client approaches have a variety of headaches:
* server has to hang on to information until the client comes back to retrieve it
* you have to work up some kind of data structure to track which information has been handled and which work must still be done
* latency issues -- i.e., what happens when there's a delay in processing information.

Server approaches also have challenges:
* server programs can be tricky to write so that they keep running. a single exception or fatal error can crash the program
* server programs are vulnerable to DDoS or other attacks, and can easily overwhelm a small device like ESP8266
* firewall and networking issues -- depending on how this device connects to the internet, it may or may not have a consistent IP address where it can be found, the ISP that connects it may not allow incoming connections for the ports that it listens on, etc.


message:
What do you do when you finish a project?

I have just about completed my first Arduino project using an Arduino Uno board, but is that what I use inside the finished device? I figured I’d keep the Uno for future projects and have something else controlling the finished product. Are you supposed to just keep purchasing the Uno board every project?

I just got it a couple of days ago so I’m not very familiar with any of it. If that is the case do you use the batter for power since I can’t have it connected to my laptop once it’s done.

body:
What you can do is:

- Buy the main IC (Atmel 328P)
- Use some external components to get it working (like a crystal). Check this on a breadboard to see if it works (and check.
- Buy a case to put it in
- Buy some protoboard or PCB to solder it on (or use a footprint)
- For power, use some components (voltage regulator) or an adapter, or battery, whatever you need. Make sure you check this on a breadboard before you solder it.

If you want to read more about the subject, search for 'prototyping'.


body:
There are many options, so it all ends up depending on your personal
preferences:

* You could indeed dedicate this Arduino to this project, and buy a new
  one for the next project. This may be the simplest solution, if not
  the cheapest. Just make sure you are not using a breadboard for the
  other parts. A “proto-shield” may be a good option for soldering the
  rest of your circuit in a permanent form.

* You may replace the Uno with a smaller Arduino, like the Micro (but
  beware it uses a different MCU) or a Pro Mini clone (same MCU). These
  smaller boards can then be soldered onto a PCB using standard 0.1” pin
  headers.

* You could buy a cheap clone, test it to make sure it works as intended
  on this particular project, and dedicate the real one for further
  prototyping.

* You could get a bare ATmega328P plus crystal and caps and put them,
  together with the rest of your circuit, onto a perf-board or a
  strip-board. C.f. Michel Keijzers’ answer. Note that if your program
  can run happily off a somewhat inaccurate 8 MHz clock, you can
  use the MCU's internal oscillator instead of a crystal.

* If your program is far from using all the resources of the Uno, you
  may consider a smaller MCU. The ATtiny85 is a popular “minimalistic”
  choice. Make sure an Arduino core is available for it, unless you want
  to program all low-level.

* For the most professional result, you could design and order a real
  PCB for your whole circuit, including the MCU.


message:
How to program ATmega4809 from Raspbeery GPIO

From this [tutorial][1]  I'm able to nicely program an ATmega328 using SPI raspberry GPIO pins. However, when I try the same steps with  ATmega4809, `avrdude` seems not having instructions and outputs the following:

    program enable instruction not defined for part "ATmega4809"

So, how do I program ATmega4809 chip from Raspberry?

  [1]: https://learn.adafruit.com/program-an-avr-or-arduino-using-raspberry-pi-gpio-pins

body:
The ATMega4809 uses UPDI (Unified Programming and Debugging Interface) for programming, not ICSP like the older ATMega328P. You need a UPDI programmer.

There is a project [jtag2updi](https://github.com/ElTangas/jtag2updi) which you can run on an Uno that turns it into a JTAG to UPDI adaptor which is then compatible with `avrdude -c jtag2updi ...`.


message:
i2c high speed and pull-up resistors

hello guys i want to ask about 2 things
first one is i'm connecting and arduino uno attached to a usb host sheild and transferring data of a mouse coordinates to 10 arduino leonardo
i'm using the standard speed 100
normal mode
my wires is all about 10 cm long
1) i need to speed up the comm to fast mode
how to make this ? and the line of code where to put it in the code and in the master or slave ?

2) what about the pull-up resistors ? does arduino uno includes built in pull-up resistors ? does it needs to disable it and put my own pull up resistors ?
i’m using wire library

body:
> i need to speed up the comm to fast mode how to make this

```
Wire.setClock(400000);
```

> and the line of code where to put it in the code

Just after `Wire.begin()` in `setup()`.  `Wire.begin()` sets the speed to 100,000 and you need to then override that afterwards to set it to 400,000 (or whatever speed you want to run at).

> and in the master or slave ?

In the master, since it's the master that generates the clock.

> what about the pull-up resistors ? does arduino uno includes built in pull-up resistors ?

Yes, but they're too high for reliable I2C operation. You should add your own resistors in the region of 1kΩ.

> does it needs to disable it and put my own pull up resistors ?

No, yours will just be in parallel with them, with the net result of a small reduction of overall resistance.


message:
Continuous voltage on IO Pins while 5V is not Connected?

i have a small project where i just sucessfully destroyed my frist of 5 Digisparks (Attiny85).
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/SEG3m.jpg
In the Picture you see the Cirucit. I have 2 Liion cells connected in series to get high enough voltage to step it down to constant 5V. To these 5V some Neopixels and a Digispark controller are connected which will set the color for the Neopixels. A0 and A1 measure the Voltage of the Cells to signal the user if the Voltage is to low so it can manually be switched of.
While prototyping it i didnt have the 10k resistors in there.

Now what happend: While connecting the cells after each other the Controllers LEDs already lit up with the Frist cell. I guess it was powered trough the A0 pin (again i didnt have the 10k resistor in there),  so i guess the internal IO Protection diodes conductet the voltage trough and this way the controller got damanged. Since this happend it wont turn on Anymore.

The problem: since i have really small space i cant use a multiple pole switch to also remove the voltage from the IO pins and therefore i will always have voltage von A0 and A1 while there is no 5V Supplyvoltage. I would guess that the Series resistance on the pin would be enough to Limit the current trough them and this way protect the controller from damange. But i dont really have experience with that and hope that you guys can give me some hints what could also be a problem or what could help :) I really dont want to destroy a second one xD

Thanks in advance and have a nice day :)

body:
As a general rule, you should not apply a higher voltage to the logic pins of digital ICs than you do to their power pin. This means that if you disconnect power, you must also shut off voltage to the logic pins.

Failure to follow that rule will often destroy an IC.

I don't know about the specifics of the inputs on your DigiSpark. 10K resistors will certainly lower the current that is able to flow into those pins, but you would still be breaking the "don't put more voltage into an input pin than you put into the VIN pin" rule.


body:
For this I would recommend isolating the power from the batteries with P-channel MOSFETs and only switching them on when you want to sample the voltage. This means that there is no power consumption at all (aside from an absolutely minuscule leakage current) when turned off.

The whole setup would require 4 MOSFETs - two P-channel and two N-channel. They don't need to be big, since the currents involved are very small, but they do need to have "logic level" thresholds, ideally < 1.5V (-1.5V for the P-channel).

The basic circuit looks like this:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/hHWrO.png)

<!-- End schematic -->

The circuit is made up of two identical segments - M1+M3 and M2+M4.  The operation is fairly straightforward:

* M1 (M2) is kept in the OFF state by R1 (R2) pulling the gate up to source.
* M3 (M4) can pull the gate of M1 (M2) LOW turning it on and allowing current to flow
* Any GPIO pin (D7 in this example) can control both M3 and M4 together
* R5 keeps M3 (M4) off when there is no power - otherwise it floats.
* R3/R4 are your existing voltage divider.

The purpose of M3 and M4 is to both turn the GPIO (D7) into "open drain" so that it's either pulling down or floating high (rather than driving high at 5V) and to isolate the two pullup gate voltages. The same effect could be achieved by two diodes and one MOSFET but it's simpler to just use two MOSFETs and not have to get diodes as well.


body:
If all you are doing with A0/A1 is 'signalling the user that the voltage is too low for continued operation', then consider the following:

 - remove the lead from the top of the lower battery entirely
 - instead of the 1/1 voltage divider, use something like 10/1 (i.e. a 680K on top and a 68K on the bottom to provide a large series resistance (making the steady-state current drain on the battery negligible).  This will also put the nominal full-charge voltage as measured at the ADC input well within the DC voltage range of the Digispark at a small cost in accuracy.  The specs for the ATiny85 ADC input impedance is something like 100 MegOhms, so the accuracy drop from using a 680K series resistor shouldn't be more than a few percent.  Use a variable power supply to calibrate the A/D setup so your controller will alert the user when the battery stack gets low.  If you don't have a variable power supply, consider something like [this][1]

Frank

  [1]: https://www.fpaynter.com/2020/06/lab-power-supply/


message:
TI ADS7250 Read From SPI and SPI1 Simultaneously

I'm so confused by the ADS2750 [datasheet][1] here, I can't seem to figure the proper bit shift to read data from bits 15-27 properly. I'm not even sure what some of the acronyms mean on page 23 table 1. I get that the first 15 bits are empty while the ADC takes a reading and then the last 12 bits for the 12 bit ADC are the value from that ADC that matches the SPI A or B input. Would someone be willing to explain to me how you would read data based on this datasheet using information from table 2 page 24?

My hardware set up to ADC7250
VCC 5 Volts

 - D5 SS fro Both SPI & SPI1
 - D13 SCK for Both SPI & SPI1
 - D11 MISO SPI_A from ADC
 - D4 MISO SPI_B from ADC
 - No MOSI connected

I'm not sure what to send in the `SPI.Transfer(0x00)`. I'm also not sure if I'm setting up the modes properly, `SPISettings settings(24*MHZ, MSBFIRST, SPI_MODE1);` as I not 100% on the clock speed. I also I'm confused if this is LSB or MSB as the datasheet has two conflicting notes, the transfer function used LSB and then two paragraphs say "MSBs of ADC_A and ADC_B are output"

I'd love some help decoding this data sheet and getting a script that can read data from this chip using both SPI and SPI1 simultaneously.

Working on only reading SPI first the will add SPI1.

    unsigned int readRegister(byte thisRegister, int bytesToRead);

    const int CS_ADC_ISOLATOR = D5;
    __SPISettings settings(24*MHZ, MSBFIRST, SPI_MODE0);
    const int buffersize = 30;
    unsigned char dataBuffer [buffersize];
    const byte READ = 0x22;

    // setup() runs once, when the device is first turned on.
    void setup() {
      Serial.begin(115200);
      pinMode (CS_ADC_ISOLATOR, OUTPUT);
      digitalWrite (CS_ADC_ISOLATOR, HIGH);
      SPI.begin();
      SPI1.begin();
    }

    // loop() runs over and over again, as quickly as it can execute.
    void loop() {
        digitalWrite (CS_ADC_ISOLATOR, LOW);
        SPI.beginTransaction(settings);
        for(unsigned char i = 0; i < buffersize; i ++)
        {
            dataBuffer[i] = SPI.transfer(0x00 << 14);
        }
        digitalWrite (CS_ADC_ISOLATOR, HIGH);
        SPI.endTransaction();
        for(unsigned char n = 0; n < buffersize; n ++)
        {
            Serial.print(dataBuffer[n]);
        }
        Serial.print("::");
    }

  [1]: https://www.ti.com/lit/ds/symlink/ads7250.pdf?ts=1593499080691&ref_url=https%3A%2F%2Fwww.ti.com%2Fproduct%2FADS7250%3Fdcmp%3Ddsproject%26hqs%3Dsw%26

body:
You can't use the normal SPI library for communicating with this device properly. Well, you *can*, but you will only be able to use one channel - the other will be completely ignored.

SPI only works on one MISO pin - you need two.  There are two other types of "SPI" that are used by devices, most notably SPI flash chips: DSPI and QSPI (dual SPI and quad SPI). You want DSPI.

Unfortunately the Arduino doesn't do DSPI, so you will have to "bit bang" it, which means manually manipulating the IO pins to create your own SPI signals in software.

Now... on to the datasheet:

The important part is the timing diagram on page 9. From that you can see that you just send 32 clock pulses and the chip responds, after 15 pulses, with the data.

So if you just do 4 8-bit transfers back-to-back then you get the data. It doesn't matter what you "send" in those transfers since the MOSI pin isn't connected to anything.

As far as speed goes, 24MHz is the *maximum* speed that it will run at. The actual speed is dictated by the Arduino and how fast you manipulate the SCK pin. That can be as slow as 1x10<sup>-1000</sup>Hz if you really want.

Data should be read on the falling edge of SCK.

So you could write a little routine that looks like:

```
uint32_t resa = 0;
uint32_t resb = 0;

pinMode(SCK, OUTPUT);
pinMode(SDI_A, INPUT);
pinMode(SDI_B, INPUT);
pinMode(CS, OUTPUT);
digitalWrite (CS, HIGH);

digitalWrite (CS, LOW);
for (int i = 0; i < 32; i++) {
    digitalWrite(SCK, HIGH);
    digitalWrite(SCK, LOW);
    resa <<= 1;
    resb <<= 1;
    resa |= digitalRead(SDI_A);
    resb |= digitalRead(SDI_B);
}
digitalWrite (CS, HIGH);

Serial.print("A: "); Serial.println(resa);
Serial.print("B: "); Serial.println(resb);
```

So for 32 iterations you pulse the clock HIGH then LOW, then shift each result 1 bit to the left, and then add in the newly read bit into the lowest bit position.

You could speed up operation by using [direct port manipulation](https://www.arduino.cc/en/Reference/PortManipulation) and avoiding the slow `digitalWrite()` and `digitalRead()` functions.


message:
What are the traditional ways to optimize program memory usage?

While doing big projects using Arduino boards (Uno, Atmega328P MCU). I used to get warnings like this

    Sketch uses 13764 bytes (44%) of program storage space. Maximum is 30720 bytes.
    Global variables use 1681 bytes (82%) of dynamic memory, leaving 367 bytes for local variables. Maximum is 2048 bytes.

    Low memory available, stability problems may occur.

 - What are the generally practiced methods for the optimization program memory usage?
 - Is there any difference in memory usage if the variable is declared globally or locally.
 - Will it matter what the control statement/selection statements are (like `if`, `switch` )
 - Usage of Serial monitor. `Serial.print()`
 - ......

>Low memory available, stability problems may occur.

How bad are these warnings?

Before marking it duplicate, I have referred the following. But it wasn't satisfactory

https://arduino.stackexchange.com/questions/30290/most-memory-efficient-way-to-program

https://arduino.stackexchange.com/questions/39176/what-are-safe-memory-usage-limits

body:
> What are the generally practiced methods for the optimization program
> memory usage?

First, note you are searching for ways to lower SRAM memory. This contains global (variable) memory and heap space (dynamic memory + stack memory).

- Avoid memory gaps, by not using dynamic memory (with free/malloc/new).
- Avoid using the `String` class.
- Avoid global memory in SRAM by using `PROGMEM`, `F(..)` if possible.
- Use the smallest variable size (e.g. `uint8_t` instead of `int`).
- Store arrays of booleans into bits (8 booleans per byte).
- Use bit flags if applicable.
- Use some compressed type of memory internally (affects performance), e.g. if you have many 6 bit values to store, store them not in separate bytes but use 6 bytes for 8 times 6 bit values).
- Avoid passing arrays by value.
- Avoid a deep call stack with many (big) variables. Note this affects your design, so use it as a last resort.
- If you need a calculatable table, calculate each value instead of storing it as a table.
- Do not use longer arrays than needed, and think about reasonable maximum array sizes otherwise (see hcheung's comment below).
- (this is not a complete list).

> Is there any difference in memory usage if the variable is declared
> globally or locally.

Yes, local variables are added to the stack, but are removed after the function ends, global variables stay (but are only created once).
Note that variables on the stack (and also dynamic memory) are NOT taken into account in the memory calculated in the warning message during compiling.

> Will it matter what the control statement/selection statements are
> (like if, switch )

No, this will only affect the program memory.

> Usage of Serial monitor. Serial.print()

Probably yes, the serial monitor probably reserves (quite?) some memory as a buffer.

> Low memory available, stability problems may occur.
> How bad are these warnings?

How bad it is, depends on how much memory is used which is not calculated, which is dynamic memory, and stack memory.

You can calculate it manually (which can be quite cumbersome for a big program), you can also use the GitHub library for this:

[Arduino MemoryFree][1]

If you know how much heap memory you use worst case, than add it to the calculated global variables memory. If this is less than your maximum available SRAM memory, you are safe.

  [1]: https://github.com/mpflaga/Arduino-MemoryFree


body:
I just want to add a single bullet to Michel Keijzers’ excellent answer:

* think about every single item you are storing in memory and ask
  yourself the question: do I really need to keep this in RAM?

It may sound silly to state what many would consider obvious, but we
have seen here many instances of novices who do not take this into
consideration. As a simple example, consider this function that averages
500 analog readings:

```cpp
int averageAnalogReading()
{
    // First take and store the readings.
    int readings[500];
    for (int i = 0; i < 500; i++)
        readings[i] = analogRead(inputPin);

    // Then compute the average.
    long sum = 0;
    for (int i = 0; i < 500; i++)
        sum += readings[i];
    return sum / 500;
}
```

Storing all those readings is completely useless, as you can just update
the sum on the fly:

```cpp
int averageAnalogReading()
{
    long sum = 0;
    for (int i = 0; i < 500; i++)
        sum += analogRead(inputPin);
    return sum / 500;
}
```

For the same reason, if you need some kind of running average to smooth
data, you should consider using an exponentially-weighted running
average, which can be incrementally updated without storing the
readings.


body:
> What are the generally practiced methods for the optimization program memory usage?

(nb. as per Edgar's comment I emphasise that this is about using PROGMEM more efficiently.)

* ### If you can replace code with a table whose size is ≤ the lines of code, do it.
  * Instead of using a sequence of ifs, find a way to collapse the procedure into a table
  * Use tables of function pointers if it makes sense
  * Sometimes you can come up with a mini-language that is much more dense than AVR instructions, for example encoding robot logic into 16 commands, and then you can pack two commands *per byte*. This could collapse your memory usage 50-fold.
* Use functions instead of repeated code—this may sound obvious but there are often subtle ways of rewriting code (but bear in mind that function calls have overhead)
* Use hash tables rather than tables with big gaps
* Use fixed point rather than floating point (e.g. you can take a byte and interpret its value as ranging from 0.00 to 2.55, instead of using a 4-byte float)

> Is there any difference in memory usage if the variable is declared globally or locally.

Let's talk about the stack.

    void A() {
        byte a[600];
        ...
    }
    void B() {
        byte b[400];
        ...
    }
    void loop() {
        byte xxx[1000];
        ...
    }

This program will firstly use at least 1000 bytes of RAM all the time. There is no real difference compared to declaring xxx globally. But then what is critical is which function calls which.

If loop() calls A(), and then loop() calls B(), the program will not use more than 1600 at any time. However, if A() *calls* B(), or vice versa, the program will use 2000. To illustrate:

    loop() [1000]
      └──── A() [1600]
      │    [1000]
      └──── B() [1400]
      └──── A() [1600]
      └──── B() [1400]

versus

    loop() [1000]
      └──── A() [1600]
            └──── B() [2000]
      │    [1000]
      └──── A() [1600]
            └──── B() [2000]

> Will it matter what the control statement/selection statements are (like if, switch )

Not much difference for a small number of cases. Otherwise it depends on your code. The best way is to just try both and see which is better. But:

`switch`es usually use jump tables which are quite compact if you cover nearly every case in a range (0,1,2,3,4,..,100). `if`s usually use a sequence of instructions, which take up more bytes and cycles than a jump table entry, but it makes more sense if you don't have a consecutive stretch of cases.

> Usage of Serial monitor. Serial.print()

I don't believe that makes a lick of difference. Serial buffers are tiny (say [64 bytes][1], or [128][2] for a bigger board) <strike>and I believe they are allocated whether or not you use Serial.</strike>

Of course "literal strings like this" and char[] buffers consume memory. You can comment them out (or use `#ifdef`s) when you don't need them.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/3055c1efa3c6980c864f661e6c8cc5d5ac773af4/firmwares/atmegaxxu2/arduino-usbserial/Lib/LightweightRingBuff.h#L47
  [2]: https://github.com/arduino/ArduinoCore-avr/blob/2f67c916f6ab6193c404eebe22efe901e0f9542d/cores/arduino/HardwareSerial.h#L46


body:
Since you asked for **traditional ways**, I am going to raise a traditional method.  In this case, more than 50 years old.

Generate and analyze a listing.

Methodology:

 1. Compile all the code with debugging turned on (add `-g`).
 2. Link the code with debugging turned on, producing an ELF executable.  Do NOT convert to an image loadable on the arduino.
 3. use `objdump` to make a listing.  My usage of this read:

        ( avr-objdump --headers --source --disassemble --syms program.elf ; \
          avr-objdump --full-contents --section=.final_progmem program.elf ) > program.lst
    Your usage may vary based on what you prefer to see.

The point of this is that this allows you to see exactly what is using every byte of your memory.

You may want to play around with different optimizations, until you understand what you are seeing.  `-O0` produces the most comprehensible disassembly, while `-Os` makes the smallest.

One tip based on having done this:  The Arduino libraries are designed for generality, not speed and memory efficiency.


message:
3.3V to 5V PWM level shift

I need to shift a PWM signal from a ESP32 (3.3V) to receiver that supports 5V. The signal is at maximum of 400Hz. Can this shifter do the job ? [![SparkFun shifter][1]][1]

  [1]: https://i.stack.imgur.com/Sck9z.png

body:
That should work, but it's overkill. Those devices are made for bidirectional signaling. You should be able to use a single transistor that is driven to saturation at 3.3V. A Suitable "logic level" MOSFET with a 3.3 gate voltage should do the trick.

And, as Chris L said in his answer, you may be able to drive an input on a 5V Arduino directly with 3.3V. That's a high enough voltage to be read as a logic level 1.


message:
ESP32: How to run two independent PID controllers, one per core?

I want to control 2 independent processes with 2 PID controllers. Is it possible to run each controller on a separate core? I'm using [this][1] PID library. According to its [documentation][2], the `PID::Compute()` function should be called once every `loop()`. How can this be achieved when using RTOS tasks (for multi core execution)?

  [1]: https://github.com/br3ttb/Arduino-PID-Library/
  [2]: https://playground.arduino.cc/Code/PIDLibraryCompute/

body:
Sure. The existing Arduino setup and loop are just executed in their own task:
```
void loopTask(void *pvParameters)
{
    setup();
    for(;;) {
        if(loopTaskWDTEnabled){
            esp_task_wdt_reset();
        }
        loop();
    }
}

extern "C" void app_main()
{
    loopTaskWDTEnabled = false;
    initArduino();
    xTaskCreateUniversal(loopTask, "loopTask", 8192, NULL, 1, &loopTaskHandle, CONFIG_ARDUINO_RUNNING_CORE);
}
```

So there's no reason not to replicate that to give yourself an entire new setup and loop, or just a single function that does it all if you prefer.

```
TaskHandle_t secondPidTaskHandle;

void secondPidLoop() {
    // setup code here
    for (;;) {
        // PID loop code here
    }
}

void setup() {
    xTaskCreateUniversal(secondPidLoop, "secondPidLoop", 8192, NULL, 1, &secondPidTaskHandle, 0);
}

void loop() {
    // First PID code
}
```

The last parameter to `xTaskCreateUniversal()` is the core to execute on. The default setup/loop runs on core 1:

```
#define CONFIG_ARDUINO_RUNNING_CORE 1
```

So just use `0` and it'll run it on core 0.


body:
esp32_technical_reference_manual_en.pdf

Page 620

As mentioned before, only an elevated process with PID of 0/1 can initiate a process switch. The new process
may have any PID from 0 ~ 7 after the process switch. The key for successful proactive process switching is that
Espressif Systems 620
Submit Documentation Feedback
ESP32 Technical Reference Manual V4.3
29. PID Controller
when the last command of the current process switches to the first command of the new process, PID should
switch from 0/1 to that of the new process.
The software procedure for proactive process switching is as follows:
1. Mask all the interrupts except NMI by using software.
2. Set register PIDCTRL_NMI_MASK_ENABLE_REG to 1 to generate a CPU NMI Interrupt Mask signal.
3. Configure registers PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG.
4. Configure register PIDCTRL_PID_NEW_REG.
5. Configure register PIDCTRL_LEVEL_REG and PIDCTRL_FROM_n_REG.
6. Set register PIDCTRL_PID_CONFIRM_REG and register PIDCTRL_NMI_MASK_DISABLE_REG to 1.
7. Revoke the masking of all interrupts but NMI.
8. Switch to the new process and fetch instruction.
Though we can deal with interrupt nesting, an elevated process should not be interrupted during the process
switching, and therefore the interrupts have been masked in step 1 and step 2.
In step 3, the configured values of registers PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG will
affect step 6.
In step 4, the configured value of register PIDCTRL_PID_NEW_REG will be the new PID after step 6.
If the system is currently in a nested interrupt and needs to revert to the previous interrupt, register
PIDCTRL_LEVEL_REG must be restored based on the information recorded in register PIDCTRL_FROM_n_REG
in step 5.
In step 6, after the values of register PIDCTRL_PID_CONFIRM_REG and register
PIDCTRL_NMI_MASK_DISABLE_REG are set to 1, PID Controller will not immediately switch PID to the value of
register PIDCTRL_PID_NEW_REG, nor disable CPU NMI Interrupt Mask signal at once. Instead, PID Controller
performs each task after a different number of clock cycles. The numbers of clock cycles are the values specified
in register PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG respectively.
In step 7, other tasks can be implemented as well. To do this, the cost of those tasks should be included when
configuring registers PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG in step 3.
Espressif Systems 621
Submit Documentation


message:
What else is consuming Data Segment reported by avr-size?

I am facing a low memory available problem in arduino. I am compiling a big sketch for arduino mega 2560.

Analysing a .elf file, the avr-size tool gives:

    text    data     bss     dec     hex filename
    68524   4392    2560   75476   126d4 C:\Users\LEAN...

And the avr-nm ([avr-nm doc][1]) shows only variables with t, T, b, d and B. The following is how the command is executed (the output is being saved in a file called test.txt).

       avr-nm -a -td -C -l --size-sort -r x.elf >> test.txt

Then, I perform a sum to confirm the avr-size result using this Python script:

    f = open("test.txt", "r")
    lines = f.readlines()
    f.close()

    su = 0
    dsum = 0
    bsum = 0
    tsum = 0
    gsum = 0
    for line in lines:
        #print(line, end="")
        s = line.split()
        try:
            val = int(s[0])
            su = su + val
            if(s[1].lower() == 'b'):
                bsum = bsum + val
            if(s[1].lower() == 'd'):
                print(line)
                dsum = dsum + val
            if(s[1].lower() == 't'):
                tsum = tsum + val
            if(s[1].lower() == 'g'):
                gsum = gsum + val
        except:
            print("ERR: ",s[0])
    print("\n\nSIZE: ", su)
    print("SIZE d/D: ", dsum)
    print("SIZE b/B: ", bsum)
    print("SIZE t/T: ", tsum)
    print("SIZE g/G: ", gsum)

and the sum result of each var type is:

    SIZE:  71015
    SIZE d/D:  135
    SIZE b/B:  2560
    SIZE t/T:  68320
    SIZE g/G:  0

The question: Here d/D sums is 135 bytes. So, why the data segment reported by avr-size is 4392 bytes? how to find out what is occupying this space?

Best Regards.

**EDIT**

It must be a Joke!

I have a lot of like this in the code:

    Serial.print("QTDE REG: ");

Just changing for this:

    Serial.print(F("QTDE REG: "));

I have reduced by 10 the .data size!

So, in this way ```Serial.print("QTDE REG: ");``` "QTDE REG: " is stored as a global variable?? I thought the compiler would save locally.

**EDIT 2**

I have an advance running ```avr-objdump -s -j .data x.elf``` as suggested by Edgar below. Now I see that all my string literals are in data! For example:

```C
void myFunction(){
    ...
    sprintf(buf, "{\"name\":\"Intervalo de Registros\",\"value\":\"%d\", \"unit\":\"C\"},", (int)settings.treg);
    ...
}
```

```avr-objdump -s -j .data x.elf``` shows:
```
 800660 2c007b22 6e616d65 223a2249 6e746572  ,.{"name":"Inter
 800670 76616c6f 20646520 52656769 7374726f  valo de Registro
 800680 73222c22 76616c75 65223a22 2564222c  s","value":"%d",
 800690 2022756e 6974223a 2243227d 2c007b22   "unit":"C"},.{"
```

**EDIT 3**

As commented, all string literals are saved in the (SRAM). So, the problem is, I have a lot of strings literals spread across different functions. How to save this amount of SRAM? Note that using F() for sprintf gives compilation error.

Is there any way to put the literal in stack (release memory when function returns) and not in the global area? Is F() the only solution?

**============ SOLUTION ============**

For now, I have found this solution: use ```sprintf_P``` with ```PSTR(...)``` in the same way of ```F(...)```:

    sprintf_P(buf, PSTR("{\"name\":\"Intervalo de Registros\",\"value\":\"%d\", \"unit\":\"C\"},"), (int)settings.treg);

I will test more...

Thanks for all clarification!

Best Regards!

  [1]: https://linux.die.net/man/1/avr-nm

body:
Most of the missing data section is probably made of string literals.
When you write something like

```cpp
Serial.println("Hello, World!");
```

the string `"Hello, World!"` is implemented by the compiler as an
_anonymous_ array of characters, and the address of this array is
provided to the `println()` method. Since the array is anonymous, it
doesn't show up in the output of `avr-nm`. You can check that this is
the case by looking at the actual contents of the section:

```shell
avr-objdump -s -j .data x.elf
```

And you can avoid this by wrapping the strings in the `F()` macro:

```cpp
Serial.println(F("Hello, World!"));
```

This has the effect of keeping the string in flash, and passing the
_flash address_ to the `println()` method. Note that this is actually a
different, overloaded method, that knows how to retrieve the character
data from flash.

------------------------------------------------------------------------

**Edit**: Adding some clarifications.

All this complexity about flash vs. RAM storage comes from the fact that
the AVR uses a [Harvard architecture][Harvard], where RAM and flash are
in different address spaces, accessed through different memory buses
using different [machine instructions][lpm]. [Unlike C][spaces], the C++
language has no notion of address spaces, and the compiler simply
assumes that any pointer to function holds a flash address, whereas any
pointer to data holds a RAM address.

Per the rules of the language, a string literal has the type
`const char *`, and a function that should be able to accept a string
literal should take a `const char *` parameter. Since these are pointers
to data, when you dereference them the compiler emits the machine
instructions that are appropriate for reading RAM. This is why the
compiler puts all string literals in the .data section of the flash: at
program startup, the C runtime copies them to the .data section of the
RAM, making them accessible to those machine instructions.

The current solution to avoid this useless copy involves a bunch of
preprocessor macros like `F()`, `PSTR()`, `PROGMEM`,
`pgm_read_byte()`... that expand to compiler extensions or inline
assembly. These allow you to pass around the flash addresses of string
literals disguised as regular data pointers. These pointers should never
be dereferenced with the regular operators of the language (`*` and
`[]`), but only through the `pgm_read_*()` macros. And they should only
be given to functions that do expect these kind of pointers, like
`sprintf_P()` or `Print::println(const __FlashStringHelper *)`, which is
the `println()` that gets invoked when using the `F()` macro.

> Is there any way to put the literal in stack

Yes, there is, but it has to be done explicitly:

```cpp
PROGMEM const char greeting[] = "Hello, World!";

void say_hello() {
    char stack_copy[strlen_P(greeting)+1];
    strcpy_P(stack_copy, greeting);
    Serial.println(stack_copy);
}
```

As you have already noticed, it is preferable to not put the strings in
RAM at all, and instead use functions like `sprintf_P` that expect
flash-based strings. However, if you need to use a library function that
expects a RAM-based string, you can use this trick to avoid permanently
committing it to RAM.

[Harvard]: https://en.wikipedia.org/wiki/Harvard_architecture
[lpm]: http://ww1.microchip.com/downloads/en/devicedoc/atmel-0856-avr-instruction-set-manual.pdf#_OPENTOPIC_TOC_PROCESSING_d94e24678
[spaces]: https://gcc.gnu.org/onlinedocs/gcc/Named-Address-Spaces.html


message:
Why is my passive buzzer clicking instead of buzzing when set to HIGH?

everyone. I am working on learning Arduino from scratch and I am on the buzzer lesson. The tutorial I am following consists on writing a code to get an input from the user in the form of an integer number, and, if it is greater than 10 (or whatever threshold you set it to) it will buzz.

I wrote the code exactly as the tutorial said but the buzzer would not buzz, it would do a weird clicking sound instead. I searched for a reason everywhere and could not find an explanation. Most questions in forums were solved by changing the positive wire from the 5V to a regular pin on the board, and those problems were due to the fact that the people asking the questions were not aware that the buzzer was a passive one.

Anyway, I managed to get a buzz by switching from digital to analogWrite and typing a value less than 255. It seemed weird that 255 and HIGH would produce the click, but values less than 255 would buzz, so I tried several analogWrite values:

 - At 255 the buzzer does the weird clicking.
 - At 254 the buzzer does a very faint buzz.

The buzzing got louder as I wrote lower numbers until it got stable at around 250, and then got less loud as I decreased the number.

Does anyone know why that is? Is the voltage too much for the buzzer at 255/HIGH? I tried a resistor but still got nothing but clicking with the program set to 255/HIGH.

This is mostly out of curiosity, but I'd still appreciate it if you could answer it.

Here is the code ("Numero" means "number" and "Dame un número" means "Give me a number":

    int Numero;

    int buzz=10;

    int DLY=2000;

    String msg="Dame un numero.";

    void setup() {

    Serial.begin(9600);
    pinMode(buzz,OUTPUT);

    }

    void loop() {

    Serial.println(msg);
    while (Serial.available()==0){

    }

    Numero=Serial.parseInt();

    if (Numero>25){

      Serial.println(Numero);

      analogWrite(buzz,10);

      delay(DLY);

      digitalWrite(buzz,LOW);

    }

    }

body:
> those problems were due to the fact that the people asking the questions were not aware that the buzzer was a passive one.

You seem to know, that you have a passive buzzer, but you don't know, what that means for you.

A buzzer consists mostly of a piezo element, which vibrates and thus makes a sound, if you provide it with an alternating voltage. Here we have 2 types of buzzers:

- The ones, that generate the alternating voltage themselves, thus only demanding a simple constant voltage from you to operate (these are the active buzzers)
- and the ones, that only have the piezo and thus demand to be provided with an alternating voltage by you (these are the passive buzzers).

You have the second type, a passive buzzer. The following is happening:

`digitalWrite(pin, HIGH)` will only set the pin to HIGH. On the transition from LOW to HIGH, you get a click, because the piezo in the buzzer is reacting to that change. `analogWrite()` on the other hand generates a PWM signal, which is an alternating voltage (alternating between LOW and HIGH).

When changing the number for `analogWrite()`, you are not changing the frequency, but only the duty cycle (the ratio of HIGH and LOW times in one period of the signal).

- `analogWrite(pin, 255)` means 100% duty cycle and thus a constant HIGH signal. Actually it is equivalent to `digitalWrite(pin, HIGH)`, because `analogWrite()` is doing exactly that, if you provide 255 (similarily it uses `digitalWrite(pin, LOW)`, if you provide 0). Thus you again hear the same click.
- As the piezo in the buzzer needs to oscillate to make a sound, you need to give him time for getting back to the LOW state. With the analog value 254 the LOW time of the signal is rather small, so that the piezo cannot reach its complete LOW state again. The oscillation amplitude is rather small that way. Thus you only hear a very faint buzz.
- With `analogWrite(pin, 250)` you reached the maximum, because now the piezo has enough time to get to its LOW state again. The amplitude is at its maximum here, thus it is the loudest value.
- When going lower than 250 towards zero, you are also reducing the amount of energy, that you give to the buzzer, thus the volume will reduce (though this is certainly not a linear process and depends also on the characteristics of the buzzer).

---

Just as Juraj already wrote in the comments, a passive buzzer can be interfaced with the `tone()` function. It will generate the alternating voltage for you and you can even set the frequency to your liking, so that you get tones with different pitches. There are tons of tutorials about the `tone()` function on the web.


body:
As chrisl explained, a passive buzzer needs a switched signal of the desired frequency in order to produce a tone of a specific pitch. It's going to produce the best/loudest output with a square wave (50% duty cycle.)

The analogWrite function outputs a PWM (pulse-width modulation) signal. That is a signal of a fixed frequency but varying duty cycle (The ratio of on time to off time.) At 50% (value 128) you should be able to get a decent tone out of it. (It looks like the PWM frequency varies by [**Arduino model**][1]: )

If you want to produce tones of varying frequncies, use the Arudino library's `tone()` function, documented here: https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/

With the `tone()` function you provide the pin number and the desired frequency, and it does the rest. As mentioned in the docs, the tone function interferes with PWM output on boards other than Mega.

You could also get a tone with code like this:

    bool state = HIGH;
    int buzz=10;
    unsigned long time = 0;

    void setup() {
        pinMode(buzz,OUTPUT);
    }

    void loop() {
       if (millis() > time) {
          state = state == HIGH ? LOW: HIGH;
          time = millis() + 2;
          digitalWrite(buzz, state);
       }
    }

If you loop does nothing else, that should give you a tone of roughly middle C. (250 hz, if my math is correct.)

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/


body:
A passive Piezo buzzer needs excitation to make sound, from your code you have a delay time of 2000 ms.
2000ms means a frequency of 0.5 Hz thats not enough.for my YL-44 Passive buzzer
even the smallest possible number allowed by the arduino delay(ms) function wich is 1 ms isn't enough to hear a clear sound. A frequency of 2000 Khz was good with delayMicroseconds(us).

    double outPin = outPin;
    double freq_Hz = freq_Hz;
    double period_s = 1 / m_freq_Hz;
    double period_ms = m_period_s * 1000;
    double period_us = m_period_ms * 1000;
    void loop() {
     digitalWrite(m_outPin, HIGH);
     delayMicroseconds(period_us / 2);

     digitalWrite(m_outPin, LOW);
     delayMicroseconds(period_us / 2);
    }


message:
Serial broken into two shorter shorter strings

I'm trying to do a serial read:

        if (Serial.available() > 0) {
      int inputValue = Serial.read();
      Serial.println();
      Serial.println("I got this:");
      Serial.print(inputValue, BIN);
    }

However, it seems that what I receive is always 6 bits first and then followed by 4 bits. I'm really confused. I used a different board just to be sure that it's not just a problem with the board. Could it be the serial monitor I'm using? I'm using the Arduino serial. This is an example of the output:

    21:31:02.021 ->
    21:31:02.021 -> I got this:
    21:31:02.021 -> 110101
    21:31:02.021 -> I got this:
    21:31:02.021 -> 1010

Can anyone shine a light as to what is happening here?

body:
I guess you are sending `5` and have the line ending set to newline only. Then everything is correct and as expected. You see 2 bytes, that are transmitted. `Serial.print()` will cut out the leading zeros of the byte, so all other digits before that are just zero.

The first byte is the character `5` encoded in ASCII (53 is the decimal representation of the ASCII value here). The second byte is the newline character `\n`, which marks the end of a line or the end of the data message (depending on the interpretation of the data). If you don't want to send the newline character, select Nothing for the line ending (My Arduino IDE is in German, so I don't know, what exactly is the term in the english version here, but you need to set it for not using any line ending).

As it seems, that you don't know that currently: When you write a number into the serial monitor, you are not sending the direct binary value of that number. You are sending the ASCII representation of the individual digits. ASCII is a system, where the values of a byte represent a character. That includes decimal digits, the alphabet and some special characters. So when you type "255", you are not sending `0b11111111` (1 byte with all bits set --> decimal 255), you are sending 3 bytes with the ASCII byte value for the characters `2`, `5` and `5`. You can read the byte values for all the characters in tables, just by googling for "ASCII" and looking at the images found.


message:
I can't run shell commands on Linux through AVR sketch (Arduino Yun)

I'm a little confused with some Process.h methods.
I'm trying to run the command "nc 192.168.1.15 9911" to the Linux processor through a sketch.
The appropriate netcat listener is waiting on another computer. Arduino Yun is on the same network with thie computer via WiFi.

When I execute this command through SSH connection on Arduino Yun it works fine, but I can't figure out how it's done through a sketch.

This is my code:

    #include <Process.h>

    Process p;

    void setup() {
       Bridge.begin();
       Serial.begin(9600);
       delay(2000);
       p.begin("nc");
       p.addParameter("192.168.1.15 9911");
       p.run();
       //while (!p.running()) {};

     }

     void loop() {
        if (p.available() > 0) {
        Serial.println("test");
     }
    }

This code doesn't seem to work, p.available() nerver executes even if I send data packets.
I also tried **p.runShellCommand("nc 192.168.1.15 9911");** with no luck.

It seems that the commands never reach the Linux command line.

Any insights?

body:
There's a few things wrong with your program, some more obvious than others.

First, you have to put each parameter to your shell command in a separate `addParameter()` call. Otherwise it treats all the parameters as a single parameter and tries to connect you to an address of `192.168.1.15 9911` instead of to port 9911 of address 192.168.1.15.

Secondly you should use `runAsynchronously()` instead of `run()` otherwise your sketch blocks at that point until `nc` terminates. If that never happens then your sketch never gets to the point where it can read the data.

Here is an adaption of your sketch that works for me:

```
#include <Process.h>

Process p;

void setup() {
 Bridge.begin();
 Console.begin();
 p.begin("nc");
 p.addParameter("192.168.1.15");
 p.addParameter("9911");
 p.runAsynchronously();
}

void loop() {
 static uint32_t ts = millis();

 if (millis() - ts > 1000) {
  Console.println(millis());
  ts = millis();
 }

 if (p.running()) {
        while (p.available()) {
            Console.write(p.read());
        }
 } else {
  Console.println("Restarting process");
        delay(100);
  p.begin("nc");
  p.addParameter("192.168.1.15");
  p.addParameter("9911");
  p.runAsynchronously();
 }
}
```

It also re-runs `nc` if / when it terminates. There's also a "heartbeat" printing of millis() so that you can see the sketch is running.  It uses the console, not Serial, for its output, so SSH in to the Yun and `telnet localhost 6571` to view the output.


message:
Cannot send any UDP packets from ESP8266 Wemos D1

I am attempting to send sensor data from a battery-powered device using UDP. The goal is to send a datagram immediately after the wifi station awakes from sleep then immediately go back to sleep after writing the datagram to a given IP address or hostname.

I can send data to Thingspeak's API using their library so I know the device works, but when attempting to use the WiFiUDP library to send a datagram to an IP address on the same LAN I see nothing happen. My device is getting on the wifi and the `udp.endPacket()` command is returning successful, but I am not receiving the packets on the server. I know the server works because I can use `nc` to send UDP packets from other machines on the LAN.

Here is my sketch with the irrelevant bits redacted.

```cpp
// https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html
#include <ESP8266WiFi.h>
// https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/udp-examples.html
#include <WiFiUdp.h>

// Create udp class instance
WiFiUDP udp;

void setup() {
  Serial.begin(115200);
  Serial.print("Connecting to WiFi");
  WiFi.mode(WIFI_STA);
  WiFi.hostname(hostname);
  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.print("SSID:\t");
  Serial.println(WiFi.SSID());

  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());

  Serial.print("Gateway:\t");
  Serial.println(WiFi.gatewayIP());

  uint8_t buffer[50] = "hello world";
  char message[] = "hello world 2";

  IPAddress staticIP(192, 168, 1, 118);
  udp.beginPacket(staticIP, 3381);
  udp.write(buffer, 11);
  //udp.write(message);
  udp.endPacket();

  // Calculate required sleep time and go to sleep
  long sleepTime = measurementInterval - millis(); // in milliseconds
  if (sleepTime < 100) sleepTime = 100; // set minimum sleep of 0.1 second
  Serial.print ("Going to sleep now for ");
  Serial.print((float)sleepTime / 1000, 3);
  Serial.println (" seconds.");
  Serial.print ("Time going to sleep=");
  Serial.print ((float)millis() / 1000, 3);
  ESP.deepSleep(sleepTime * 5000); // convert to microseconds
}
```

And my node server just to be complete here:

```js
const dgram = require('dgram')
const server = dgram.createSocket('udp4')

server.on('error', (err) => {
  console.log(`server error:\n${err.stack}`)
  server.close()
})

server.on('message', (msg, rinfo) => {
  console.log(`got message from ${rinfo.address}:${rinfo.port} - ${msg}`)
})

server.on('listening', () => {
  const address = server.address()
  console.log(`server listening ${address.address}:${address.port}`)
})

server.bind(3381)
```

I've also tried adding delays between each function to no avail.

body: Per the esp8266 subreddit, you need to add a sufficient `delay()` of 50-100 milliseconds (not microseconds) before going to sleep as none of the udp functions are blocking.


message:
Computer doesn´t recognize MKR1010

I´m learning how to use the Arduino MKR1010. When I wrote a program for controlling LEDs and to read a BMP280 sensor with a web aplication, and I uploaded the program to the board, suddenly the computer did not recognice the board.

The power LED of the board works, but I can't access the board with my computer, and I can't see in the COM ports list, and neither as a "unrecognised device" to reinstall the drivers.

I have tried with a few others USB cables and with another computer, but I still have the same problem. I have also tried to press the reset button reset and I still have the same result. What can I do to make my board work?

body:
The MKR board connects to computer over native USB support of the MCU. The handling of the USB is done by Arduino core functions linked at build to your sketch.

A consequence of using the native USB port is, if your sketch has a problem, it influences the USB communication. In this case you can activate the bootloader to handle the USB port and the upload. It is done by **double clicking the reset button on board**.

This applies to other SAMD boards (Zero, M0) and to AVR boards with native USB port (Leonardo, Micro) too.


message:
Simple serial message not consistent (sometimes jumbled up)

I have the following code, it works (most of the time) - yet it's not 100% reliable and now and then will send through a double message on one line or 2 subsequent alpha characters:

    const byte interruptPin0 = CONTROLLINO_IN0;
    const byte interruptPin1 = CONTROLLINO_IN1;
    int counter1 = 0;
    int counter2 = 0;
    unsigned long previousMillis = 0;
    unsigned long interval = 2000;
    int a = 60;
    char buffer1[256];
    char buffer2[256];

    void setup()
    {
      pinMode(interruptPin0, INPUT_PULLUP);
      pinMode(interruptPin1, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(interruptPin0), pin1Fired, RISING);
      attachInterrupt(digitalPinToInterrupt(interruptPin1), pin2Fired, RISING);
      Serial.begin(9600);
    }

    void loop()
    {
      unsigned long currentMillis = millis();
      if (currentMillis - previousMillis > interval) {
        previousMillis = currentMillis;
        sprintf(buffer1,"A%d",counter1);
        Serial.println(buffer1);
        sprintf(buffer2,"D%d",counter2);
        Serial.println(buffer2);
        counter1 = 0;
        counter2 = 0;
      }
    }

    void pin1Fired()
    {
      counter1 = counter1 + 1;
    }

    void pin2Fired()
    {
      counter2 = counter2 + 1;
    }

Result:

[![enter image description here][1]][1]

This later causes a problem when my code on the other end of the serial comms expects [LETTER][NUMBER].

What have I missed here? I'm relatively new to C for Arduino so quite possibly took a bad approach here?

I've tried to avoid sending serial comms from the interrupt, I read that was risky - hence me tracking the interrupt counts separately.

Can also confirm baud rate matches.

EDIT
-------

To confirm MCU resets I have printed in setup - note: no interrupts firing, still the same issue:

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/f71ua.png
  [2]: https://i.stack.imgur.com/f4Kk8.png

body:
My guess is that an interrupt is occurring *during* your reading or writing of the counter variables.

Since the variables are bigger than the native size of the registers in the CPU multiple instructions are required to work with them, and an interrupt can occur right in the middle of that work which changes the values it's working on. That can cause a mess (though I wouldn't expect it to make that kind of mess, TBH).

You should wrap all accesses to the counters that aren't in the interrupts inside a *critical section*. This is a segment of the code where interrupts are *not* allowed to happen. For obvious reasons you want to keep that code as short as possible.

Also in the code you have given there is no need for your buffers and sprintfs. You can just use multiple Serial.prints to achieve the same result with a much smaller code/memory footprint.

Here's an example:

```
void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;

    // Copy and reset the counter values in a critical section
    noInterrupts();
    int nowCounter1 = counter1;
    counter1 = 0;
    int nowCounter2 = counter2;
    counter2 = 0;
    interrupts();

    Serial.print("A");
    Serial.println(nowCounter1);
    Serial.print("D");
    Serial.println(nowCounter2);
  }
}
```

Also your counter variables should be `volatile` since they are accessed from both the interrupts and the main loop:

```
volatile int counter1 = 0;
volatile int counter2 = 0;
```


body:
This is not an answer, but showing a way to make your code more clean.

Use the critical sections as proposed by Majenko.

You can rewrite

    sprintf(buffer1,"A%d",counter1);
    Serial.println(buffer1);
    sprintf(buffer2,"D%d",counter2);
    Serial.println(buffer2);

as

    sprintf(buffer, "A%d\r\nD%d", counter1, counter2);
    Serial.println(buffer);

Also, an unsigned long int can be maximum around 10 characters (2^32), so including the 'A', 'D', extra new line and \0, a single buffer of around 30 characters will suffice, instead of 2 buffers of 256 bytes (which takes 25% of an Arduino UNO's SRAM).

Also you can rewrite

    counter1 = counter1 + 1;

as

    counter1++;

which increases a variable with 1.

Also `counter1` and `counter2` should never be negative so an `unsigned` type is better.


body:
This isn't meant to be a solution; it's more of a workaround.

To avoid repeated letters, you could use code to make sure that each alpha character isn't the same as the one before, and if so, delete the current character before printing.

Then to tackle doubling, if the string has an even number of characters, split the string in half, and if both halves are equal, remove one of them from the string.

This isn't exactly what you wanted but it's more of a worst-case scenario kind of thing.


body:
Very frustrating time trying to diagnose this.

All credit to Controllino for their support when looking into whether it was a hardware/code issue (it wasn't!).

The problem turned out to be the recipient of these messages. The performance of the PC the Controllino was plugged into was really bad. I noticed what you've seen in the screenshots I've shared every time I'd open a new app or dragged a window.

The serial monitor in the Arduino IDE would lock up for a few seconds and so would miss the serial messages (and have to catch up).