text:
Measure the duration a pin is in a HIGH state
I'm struggling with getting the button configuration. Simply, I have a LED controlling setup for a button to increase its brightness when pressed. However, I would like to have it setup like this:

When button is pressed.
change the value by 1,
wait for 500ms,
Then go fast (with the usual void loop time).

Is it something to do with interrupts? If I just write it like below, it actually (obviously) goes by +1 by itself, even when button is not pressed.
void loop() {
  if(digitalRead(button_pressed) == HIGH) {
    current_state = current_state+1;
    delay(500);
    current_state = current_state+1;
  }
}

It is not clear to me what you want and what you got.

Simply, as you would imagine volume control for instance. You don't want to have it to randomly detect button presses, I mean - sometimes when you want to press the button just once it would detect it as '3' or more. So generally - when button is pressed and hold - to add "1" by the counter, but if it's pressed >1sec, go with the arduino clock in the void loop, changing the volume fast.

Fairly simple. If thee button IS pressed, increment a button counter, otherwise, reset it. Test the button counter to see if it is bigger than a preset number (that determines how long a long press needs to be). If so, increment volume fast. If not, increment volume slowly.

Non-blocking version.
bool old_button_state = LOW;
void loop()
{
    if(digitalRead(button_pressed) == HIGH)
    {
        current_state = current_state+1

        if( old_button_state==LOW )
            delay(500); // long delay
        else
            delay(100); // short delay

        old_button_state = HIGH;
    }
    else
    {
        old_button_state = LOW;
    }
}

Simplistic version.
void loop()
{
    if(digitalRead(button_pressed) == HIGH)
    {
        current_state = current_state+1
        delay(500);// long delay

        // repeat while the button is being pressed
        while(digitalRead(button_pressed) == HIGH)
        {
            current_state = current_state+1
            delay(100); //short delay
        }
    }
}

Ideally you wouldn't just wait for 500ms, but 'break out' of this delay as soon as the button is released.

Thanks for that, but seems like it's not doing it's job.. not sure why, but it shows blank at first (I've got LCD to show this value), and when trying to go down with the "down" button, it shows the max. value I have set it up to.

That's what you get when you don't post the entire code :-) . The code above will do nothing will the button is being pressed. So while the button is pressed, the LCD will not be updated.

I added a non-blocking version to my answer.

Still something feels not right :) I mean, I would think of something like "check for the HIGH status being ON for 1 sec, add one step, after 1sec, go with the usual clock rate". That's the hard thing here

I don't quit understand. Doesnt the code work? Or do you want something that doesn't use the delay function?

Yes, it seems like it only 'sees' the 1sec delay, and it goes by one up each 1 sec, instead of going by plus one in 1sec and then fast.

1 second?  The delay is 500ms! Seems like your other code is adding an additional delay of 500ms.

Sorry, I have changed to 1sec, but still :)
Simply, as you would imagine volume control for instance. You don't want to have it to randomly detect button presses, I mean - sometimes when you want to press the button just once it would detect it as '3' or more. So generally - when button is pressed and hold - to add "1" by the counter, but if it's pressed >1sec, go with the arduino clock in the void loop, changing the volume fast.

long timenow, timelong=500;
int current_state = 0;
void increase_state()
{
    current_state++;
    Serial.println(current_state);
}

void loop()
 {
    if(digitalRead(button_pressed)) //button is pressed
    {
        timenow=millis();   //get current time
        increase_state(); // increase by 1
        while (digitalRead(button_pressed)) //check if the button is still pressed
            {
                //rapidly increase "current_state" by 1 if button is pressed more than 500ms with interval of 50ms.
                if ((millis()-timenow)>timelong)
                {
                increase_state();
                delay(50);
                }
            }
    }
    delay(500)
 }

The increment of current_state is always by 1. If button is pressed, it will always increase by 1, but if it's not a long press, you have to wait another 500ms to increase it values again.

Could you add a line with Serial monitor to print out the value? As I cannot quite adapt this to my code... let's say that starting value is 0, and then you would add values to it.

answer edited :)

Fairly simple.

I thought I would lay out my code here so it is more clear.
if (BTN_PRESSED()) {            //button is pressed now
    btn_cnt += 1;               //increment button counter
    if (btn_cnt >= BTN_LONGPRESS) {
        volume += VOLINC_FAST;  //btn has been pressed for a long time, so increment volume fast
    } else {
        volume += VOLINC_SLOW;                              //otherwise increment the button slowly
    }
} else btn_cnt = 0;             //button is not pressed so reset the counter

It basically follows what I laid out earlier and is self explanatory, I hope.
Formatting needs more work, obviously.
edit: reformatted the code a little bit to make it more readable.
here is an example of this code at work:

here, the code is used to detect a button press (active low) on RA0. Once the button counter (btn_cnt) has been pressed sufficiently long (set by BTN_LONGPRESS), it increments volume by VOLINC_FAST (=4); otherwise, it increments volume by VOLINC_SLOW (=1).
the simulation shows just that. the value of volume is output on PB0..7, to a dac to show more graphically what happens to volume's value.
1) when the button is high (=not pressed), volume is not changed and you see a flat line on the DAC output;
2) when the button is just pressed (but not sufficient to trigger BTN_LONGPRESS), volume is incremented slowly and you see the DAC's output goes up slowly (1 at a time);
3) when the button is pressed long enough, volulme is incremented fast and you see the DAC's output goes up much steeper.
Obviously, you can modulize the code so it can process multiple buttons and return multiple states - not pressed, pressed, long pressed, double pressed. or if you wish, allow it to process bounces.
all sorts of possibilities but the basic idea is the same.

I see, but thing with arduino is that you have it all in this "big" void loop, so even if you say it to "add 1", it could detect one button press as "5", and in fact add 1 five times.


text:
Problem with tachometer using attachInterrupt and servo
So I am creating a tachometer using black/white detector sensor. Here's the code.
unsigned long WaktuOLD;
unsigned long WaktuNOW;
int Detection = HIGH;
int Counter = HIGH;
float HitungWaktu;
float HitungRPM;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(3), rpm, RISING);
  WaktuNOW = millis();
}

void rpm() {
  Detection = digitalRead(3);
  if (Detection == HIGH && Counter == LOW) {
    WaktuNOW = millis();
    HitungWaktu = WaktuNOW - WaktuOLD;
    HitungRPM = 60 / (HitungWaktu / 1000);
    Counter = HIGH;
  } else if (Detection == HIGH && Counter == HIGH) {
    Counter = LOW;
    WaktuOLD = millis();
  }
}

void loop() {
  Serial.println(HitungRPM);
  delay(5000);
}

The code works well and it can read RPM correctly. And then from the same arduino, I am controlling a servo motor, in this case I am using GWS03N/STD/F, with this code :
#include <Servo.h>

Servo myservo;
int pos = 0;

void setup() {
  myservo.attach(9);
}

void loop() {
  myservo.write(90);
}

And this code works well too.
But, when I am trying to combine both codes, only the servo code is working well. The tachometer reading is not correct (the reading must be around 1000-1500rpm, but now it reads 3000-30krpm). I am already trying to change my tachometer interrupt to pin 2 or 3, and servo to 3, 5, 6, and 9 but still the same.
So what is wrong in here. Thank you so much.
This is my code when combining both codes.
#include <Servo.h>

Servo myservo;
int pos = 0;
unsigned long WaktuOLD;
unsigned long WaktuNOW;
int Detection = HIGH;
int Counter = HIGH;
float HitungWaktu;
float HitungRPM;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(3), rpm, RISING);
  WaktuNOW = millis();
  myservo.attach(9);
}

void rpm() {
  Detection = digitalRead(3);
  if (Detection == HIGH && Counter == LOW) {
    WaktuNOW = millis();
    HitungWaktu = WaktuNOW - WaktuOLD;
    HitungRPM = 60 / (HitungWaktu / 1000);
    Counter = HIGH;
  } else if (Detection == HIGH && Counter == HIGH) {
    Counter = LOW;
    WaktuOLD = millis();
  }
}

void loop() {
  Serial.println(HitungRPM);
  myservo.write(90);
  delay(5000);
}

Your problem is probably that of interrupt conflicts.
The 8-bit Arduinos don't have any concept of interrupt priorities. When one interrupt routine is running it is impossible for any other interrupt routine to run until that first one has finished.
Interrupts have a "natural call priority" in that lower numbered pending interrupts will be called in preference to higher numbered ones, however that doesn't mean that they can interrupt each other.
The problem here is that the servo library uses a timer (and its associated interrupt) to generate the waveform.  That uses a lot of interrupt calls running all the time - and while they are running your external interrupt can't be called - at least not until the currently executing timer interrupt completes, at which point your external interrupt handler will be called since it is the highest priority.
So the results you get with all that delaying are pretty meaningless.
So what can you do?  Well, there's a number of options - all of which involve not using interrupts.

You could not use the Servo.h library and instead reconfigure the hardware PWM to the right frequency and use that for the servo
You could use one of the timers with an external clock source to count your tacho pulses (I think Timer 1 has that ability on the Uno)

Or even better: do both.  That would give you the most efficient system whereby the main CPU is only involved in getting the count from the timer periodically, and adjusting the PWM value for your servo. The rest is then done by hardware completely asynchronously.
Of course, for this you will want to study the datasheet so you know how to configure the various hardware modules.

Are there another libraries instead of "Servo.h", which may solve this issue?

Not that I am aware of, but there are plenty of tutorials around on changing the frequency of the PWM.

This may be of interest to you...

Can we use a PWMServo as same as the Servo.h ?

It depends which timers both are using. If they're on different timers then sure. If not, no.

Can we resolve the issue by using two separate Arduino Uno boards: One for sensor and one for Servo

Sure, as long as the communication between them doesn't impact either, and since that generally uses interrupts too you're probably going to run into some issues.

I must comment :-). This answer is perfect. First when I saw the bounty, I thought Tharindu throw away his points for this bounty. I never worked with servo or encoder interrupts, but I knew that 328p misses the RPM interrupts because the servo library uses interrupts to generate pulses. But I had no solution. And the possibility to substitute both controls with MCU internal peripherals is perfect.

@Juraj Yeah I got a very close idea with the answer. But still, I have no idea how to resolve my problem. Can you suggest a path to start with?

I would start with the tacho. Read the datasheet and learn how to configure timer1 to use the T1 pin as the clock input and count clock pulses.

All of those variables that are accessed inside the ISR need to be declared as volatile.
You are using a RISING interrupt, so there should be no need to test the pin in the ISR.  You can be confident that it went HIGH for the interrupt to be run.

I stand corrected.  I must have misread the pin number somehow.  Still, the variables need to be volatile.

It's a typo on one of the pin number on Detection var, I already correct it now. And I already try to volatile WaktuOLD, WaktuNOW, Detection, Counter, HitungWaktu, and HitungRPM but it still no good. I haven't try to remove Detection var though.

source: Stack Exchange

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

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

sort: votes


text:
Radio Issues with RF69HW
I am working through this tutorial on using the RF69HW. The RF69HW datasheet can be found here. I am using an Eegoo Uno R3 and yes I am aware that the Arduino is a 5v and the RF69HW is a 3.3v board. I am using some voltage dividers to get the voltage to 3.3v via the circuit shown below, at end of question.
I would use a level shifter but I only realized this mistake today and I am trying to get this working ASAP. The radio does not appear to be working. In fact the program seems to get caught on it. I introduced:
radio.sendACK();
Serial.print(" - ACK sent");

After the button has been pressed. This is the output I get:
Listening at 915 Mhz...
Button pressed!

So it gets to the line before it where the button is pressed but then gets stuck attempting to sendACK. I don't know what to make of this. Any help getting these two to communicate is appreciated. Code and pictures below.
Here is the code I am using as the sender:
#include <SPIFlash.h>
#include <SPI.h>
#include <LowPower.h>
#include <RFM69.h>
#include <RFM69_ATC.h>
#include <RFM69_OTA.h>
#include <RFM69registers.h>

//*********************************************************************************************
// *********** IMPORTANT SETTINGS - YOU MUST CHANGE/CONFIGURE TO FIT YOUR HARDWARE *************
//*********************************************************
//This part of the code simply sets up the parameters we want the chip to use
// these parameters allow you to have multiple networks, channels, and encryption keys
#define NETWORKID     100  //the same on all nodes that talk to each other
#define RECEIVER      1    //unique ID of the gateway/receiver
#define SENDER        2    // you could for example, have multiple senders
#define NODEID        SENDER  //change to "SENDER" if this is the sender node (the one with the button)
//Select your frequency by uncommenting
#define FREQUENCY     RF69_915MHZ
#define ENCRYPTKEY    "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
#define IS_RFM69HW    //uncomment only for RFM69HW! Remove/comment if you have RFM69W!
//*********************************************************************************************
#define SERIAL_BAUD   9600

//This part defines the LED pin and button pin
#define LED             9 //LED on D9
#define BUTTON_INT      1 //user button on interrupt 1 (D3)
#define BUTTON_PIN      3 //user button on interrupt 1 (D3)
#define RX_TOGGLE_PIN   7 //GPIO to toggle on the RECEIVER

RFM69 radio;

// the setup contains the start-up procedure and some useful serial data
void setup() {
  Serial.begin(SERIAL_BAUD);
  radio.initialize(FREQUENCY,NODEID,NETWORKID);
#ifdef IS_RFM69HW
  radio.setHighPower(); //only for RFM69HW!
#endif
  radio.encrypt(ENCRYPTKEY);
  char buff[50];
  sprintf(buff, "\nListening at %d Mhz...", FREQUENCY==RF69_433MHZ ? 433 : FREQUENCY==RF69_868MHZ ? 868 : 915);
  Serial.println(buff);
  Serial.flush();
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  attachInterrupt(BUTTON_INT, handleButton, FALLING);
  pinMode(RX_TOGGLE_PIN, OUTPUT);
}

//******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
#define FLAG_INTERRUPT 0x01
volatile int mainEventFlags = 0;
boolean buttonPressed = false;
void handleButton() {
  mainEventFlags |= FLAG_INTERRUPT;
}

byte LEDSTATE=LOW; //LOW=0

void loop() {
  //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
  if (mainEventFlags & FLAG_INTERRUPT) {
    LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_ON);
    mainEventFlags &= ~FLAG_INTERRUPT;
    if (!digitalRead(BUTTON_PIN)) {
      buttonPressed=true;
    }
  }
  if (buttonPressed) {
    Serial.println("Button pressed!");
    buttonPressed = false;
    radio.sendACK();
    Serial.print(" - ACK sent");
    if (radio.sendWithRetry(RECEIVER, "All About Circuits", 18)) //target node Id, message as string or byte array, message length
      delay(100);
  }
  //check if something was received (could be an interrupt from the radio)
  if (radio.receiveDone()) {
    //print message received to serial
    Serial.print('[');Serial.print(radio.SENDERID);Serial.print("] ");
    Serial.print((char*)radio.DATA);
    Serial.print("   [RX_RSSI:");Serial.print(radio.RSSI);Serial.print("]");
    Serial.println();
    if(LEDSTATE==LOW) LEDSTATE=HIGH;
    else LEDSTATE=LOW;
    digitalWrite(LED, LEDSTATE);
    digitalWrite(RX_TOGGLE_PIN, LEDSTATE);
    //check if sender wanted an ACK
    if (radio.ACKRequested()) {
      radio.sendACK();
      Serial.print(" - ACK sent");
    }
  }
  radio.receiveDone(); //put radio in RX mode
  Serial.flush(); //make sure all serial data is clocked out before sleeping the MCU
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_ON); //sleep Arduino in low power mode (to save battery)
}

And the receiver:
#include <SPIFlash.h>
#include <SPI.h>
#include <LowPower.h>
#include <RFM69.h>
#include <RFM69_ATC.h>
#include <RFM69_OTA.h>
#include <RFM69registers.h>

//*********************************************************************************************
// *********** IMPORTANT SETTINGS - YOU MUST CHANGE/CONFIGURE TO FIT YOUR HARDWARE *************
//*********************************************************
//This part of the code simply sets up the parameters we want the chip to use
// these parameters allow you to have multiple networks, channels, and encryption keys
#define NETWORKID     100  //the same on all nodes that talk to each other
#define RECEIVER      1    //unique ID of the gateway/receiver
#define SENDER        2    // you could for example, have multiple senders
#define NODEID        SENDER  //change to "SENDER" if this is the sender node (the one with the button)
//Select your frequency by uncommenting
#define FREQUENCY     RF69_915MHZ
#define ENCRYPTKEY    "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
#define IS_RFM69HW    //uncomment only for RFM69HW! Remove/comment if you have RFM69W!
//*********************************************************************************************
#define SERIAL_BAUD   9600

//This part defines the LED pin and button pin
#define LED             9 //LED on D9
#define BUTTON_INT      1 //user button on interrupt 1 (D3)
#define BUTTON_PIN      3 //user button on interrupt 1 (D3)
#define RX_TOGGLE_PIN   7 //GPIO to toggle on the RECEIVER

RFM69 radio;

// the setup contains the start-up procedure and some useful serial data
void setup() {
  Serial.begin(SERIAL_BAUD);
  radio.initialize(FREQUENCY, NODEID, NETWORKID);
#ifdef IS_RFM69HW
  radio.setHighPower(); //only for RFM69HW!
#endif
  radio.encrypt(ENCRYPTKEY);
  char buff[50];
  sprintf(buff, "\nListening at %d Mhz...", FREQUENCY == RF69_433MHZ ? 433 : FREQUENCY == RF69_868MHZ ? 868 : 915);
  Serial.println(buff);
  Serial.flush();
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  attachInterrupt(BUTTON_INT, handleButton, FALLING);
  pinMode(RX_TOGGLE_PIN, OUTPUT);
}

//******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
#define FLAG_INTERRUPT 0x01
volatile int mainEventFlags = 0;
boolean buttonPressed = false;

void handleButton() {
  mainEventFlags |= FLAG_INTERRUPT;
}

byte LEDSTATE = LOW; //LOW=0

void loop() {
  //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
  if (mainEventFlags & FLAG_INTERRUPT) {
    LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_ON);
    mainEventFlags &= ~FLAG_INTERRUPT;
    if (!digitalRead(BUTTON_PIN)) {
      buttonPressed = true;
    }
  }
  if (buttonPressed) {
    Serial.println("Button pressed!");
    buttonPressed = false;
    radio.sendACK();
    Serial.print(" - ACK sent");
    if (radio.sendWithRetry(RECEIVER, "All About Circuits", 18)) //target node Id, message as string or byte array, message length
      delay(100);
  }
  //check if something was received (could be an interrupt from the radio)
  if (radio.receiveDone()) {
    //print message received to serial
    Serial.print('['); Serial.print(radio.SENDERID); Serial.print("] ");
    Serial.print((char*)radio.DATA);
    Serial.print("   [RX_RSSI:"); Serial.print(radio.RSSI); Serial.print("]");
    Serial.println();
    if (LEDSTATE == LOW) LEDSTATE = HIGH;
    else LEDSTATE = LOW;
    digitalWrite(LED, LEDSTATE);
    digitalWrite(RX_TOGGLE_PIN, LEDSTATE);
    //check if sender wanted an ACK
    if (radio.ACKRequested()) {
      radio.sendACK();
      Serial.print(" - ACK sent");
    }
  }
  radio.receiveDone(); //put radio in RX mode
  Serial.flush(); //make sure all serial data is clocked out before sleeping the MCU
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_ON); //sleep Arduino in low power mode (to save battery)
}

Here is a link to project pictures: imgur.com/a/sFW88
Here is my circuit diagram:

Please edit your question and add circuit diagrams.  Did you implement both 3.3-to-5V and 5V-to-3.3V interfaces, or just the latter?

@jwpat7 Here is a circuit diagram. I apologize, I know its not great. First attempt doing this online. I only implemented the latter with 1k and 2k resistors.

The circuit diagram shows several resistive voltage divider circuits, each made up of a 1KΩ in series with 2KΩ.
When 5 V goes into the top of such a divider, about 3.3 V appears at the resistor junction.  (And 0 V in gives 0 V out.) This is suitable for a 5 V output pin connected to a 3.3 V input pin.
For connecting RF69HW 3.3 outputs (eg MISO) to 5 V Uno inputs, ideally one would step up 3.3 V to 5 V.  Instead, MISO goes to the resistor junction of what resembles a resistive voltage divider but in fact is not.
Consider a low output on MISO; then the 1K-2K junction goes to zero; so the Uno reads 0 on D12, as it should.
Now consider a high output on MISO.  The 1K-2K junction goes to 3.3 V, driving about 1.65 mA to ground through the 2KΩ resistor.  Presumably the SPI library uses pin 12, MISO, as an input, so current through the 1KΩ resistor is specified to be at most 10 μA (per Table 29-14 in ATmega328 datasheet) and is quite likely to be at most a few nanoAmps.  In any case, the voltage at pin 12 will be quite close to 3.3 V, which will register as a high input.  (Figure 31-72 in ATmega328 datasheet shows a 2.6 V threshold when Vcc is 5 V.)
This is more of a long comment than an answer, because although the MISO circuitry is problematic, it appears that it should work anyway.

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


text:
Arduino Due connection with FLIR Lepton
I'm trying to connect a FLIR Lepton to an Arduino Due. A thread by pureengineering talks of rerouting some pins. I am not sure what they precisely mean.

Does this rerouting mentioned in the link also apply to Arduino Due?

According to the highlighted part of Due schematics it'd be better to connect 3.3V to the AREF pin as there might be some significantly big resistor between AREF and 3.3V source. So it might not be needed but one never knows.
Edit: Looking at the DUE board, there is "jumper" resistor, so you can choose 3V3 or AREF, that means AREF is not connected to anything by default. So if you connect 3v3 to AREF, it should be fine (even 5V, if you didn't changed anything on board yet
)


text:
How can configuration values be stored on an ESP8266?
I have a project that uses an MQTT service, and I'm wondering how to best store the configuration settings (server, user, password, port) for the service as right now they are just hard-coded into some constants.
I saw that EEPROM can be used for this but I'm not sure it is the best way. I went to look at the code for WifiManager to see how it accomplishes this task for the SSID and password since it works so well and it removed its EEPROM dependency back in 2015: https://github.com/tzapu/WiFiManager/commit/659df9cb277c5f93946d9d8795e39a5ae5863ab1
I can't figure out how those settings are persisted.
If EEPROM is the best way for storing something like this, I'd like to write my values without overwriting/corrupting existing values, is that possible? How can I set the initial values of the EEPROM to the constants that I need?
Edit: well after digging into the esp8266/Arduino repository I found that the WiFi.SSID() and WiFi.psk() settings come from wifi_station_get_config and stored with wifi_station_set_config although I haven't found how those work so I think EEPROM might be the way to go here, I just need a bit of guidance and clarification on the right way to use it.

as an alternative, have you considered looking into using SPIFFS (but EEPROM is fine - the parts that were removed in WifiManager had to do with storing the SSID/password - the ESP8266 already does this "natively" (don't ask, I don't know the details of where)

https://github.com/tzapu/WiFiManager/tree/master/examples/AutoConnectWithFSParameters

@JaromandaX I haven't used SPIFFS before, I'll look into that.

+infinity for SPIFFS over EEPROM. use SPIFFS, it's easy and great.

Thanks to Jaromanda X and Juraj for the SPIFFS recommendation. I was able to use this block of SPIFFS code as an example and safely store settings in my project outside of the compiled source.
To upload files to my ESP8266, I followed the installation and usage instructions for the ESP8266 filesystem plugin for the standard Arduino IDE.
First, I created a .gitignore file and added this so that none of the actual values would get added to the repository:
# MQTT config info
data/config.json

Then I created a data folder and added a config.json file that had all the configuration properties that I need to reference:
{
  "cloudmqtt_server": "***.cloudmqtt.com",
  "cloudmqtt_user": "********",
  "cloudmqtt_pass": "************",
  "cloudmqtt_port": 10000
}

Following the example above, I added #include <FS.h> at line #1 (as well as #include <ArduinoJson.h> for parsing the JSON) and have this block to instantiate the variables with dummy values that will be replaced by the actual values from the JSON file:
// MQTT pub/sub for the servo functions
#define CLOUDMQTT_CONFIG  "/config.json"
// these values are loaded from a config.json file in the data directory
char cloudmqtt_server[18] = "***.cloudmqtt.com";
int  cloudmqtt_port       = 0;
char cloudmqtt_user[9]    = "********";
char cloudmqtt_pass[13]   = "************";

Then in the setup I have this block to load the values from the config:
if (SPIFFS.begin()) {
  Serial.println("mounted file system");

  // parse json config file
  File jsonFile = GetFile(CLOUDMQTT_CONFIG);
  if (jsonFile) {
    // Allocate a buffer to store contents of the file.
    size_t size = jsonFile.size();
    std::unique_ptr<char[]> jsonBuf(new char[size]);
    jsonFile.readBytes(jsonBuf.get(), size);

    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.parseObject(jsonBuf.get());
    if (json.success()) {
      strcpy(cloudmqtt_server, json["cloudmqtt_server"]);
      cloudmqtt_port = json["cloudmqtt_port"];
      strcpy(cloudmqtt_user, json["cloudmqtt_user"]);
      strcpy(cloudmqtt_pass, json["cloudmqtt_pass"]);
    } else {
      Serial.println("failed to load json config");
    }
    jsonFile.close();
  }
}

I'm not sure if there's a better way, but this way works for me:
https://github.com/dieseltravis/esp8266-projects/tree/master/servo-demo

If you use WiFiManager you could also ask for the MQTT parameters directly from the captive portal, then save to SPIFFS.


text:
HTTP request not sending
so I have a wifi shield and I am sending a web request, but its not going through. I know it's not the server because the other function of the program works properly. My code is available on pastebin
EDIT:
The request that is not working is on line 318

This is a meaningless question for Stack Exchange. You don't mention what shield, and you haven't posted any code (that will survive if Pastebin goes down. I'm closing it as not a real question.

You are lacking a space:
client.println((String)"GET /msg.php?action=send&ID=2&message=" += currentMessage += "HTTP/1.1");
                                                                                ^

Your HTTP is running in to the content of your message ending up with a corrupt request. Also you are doing appending within your strings (+=) when you don't need to (+ is all that is needed). In fact, you don't even need that - just do multiple prints and reduce the hammering your heap is getting. Oh, and don't forget to use F():
client.print(F("GET /msg.php?action=send&ID=2&message="));
client.print(currentMessage);
client.println(F(" HTTP/1.1"));


text:
Hooking up LCD screens reclaimed from old camcorders to Arduino
Has anyone had any luck using LCD screens reclaimed from old electronics with Arduino, such as camcorders etc?
My 8 yr old has an old sony handycam (dcr-trv103) in bits and now wants to use the LCD screen with the arduino. I'm not even sure how I would go about this. Any tips? How do I figure out 'what does what' in terms of the inputs? How would I drive this thing / what do I need to do to send visual images to it via an Arduino?
Here's the front and back panels of the LCD screen, and their hookups.
The Screen

Screen hookup

I'm assuming this is the backlight

backlight hookup

Note: someone identified this as a duplicate of another question about reusing a cellphone LCD screen. This question is specifically about reusing an older camcorder LCD screen. Also that other question has very little answers. I found the answers below useful and educational. Thanks all.

Not trivial to say. You need a driver board for this, the signals in the flex cable won't be of much use to you in your Arduino, I think. Might be some parallel interface instead of an easy SPI interface. I would start by identifying where the signals in the flex cable go to on the original board, then identify chips and datasheets for them, and from there find out what protocol the display speaks. Also you might find https://www.youtube.com/watch?v=6SOXMDb4cjI interesting. It's an interesting advanced project though, would like to see the results of that.

Possible duplicate of Can I control a cellphone's lcd (+touch screen)?

@gre_gor Not a cellphone lcd, it's from a camcorder. Different question.  Anyhow that previous questions answers were not helpful. the answers below are educational. Thanks.

I'm voting to close this question as off-topic because it is about undocumented and unidentified displays, and not at all about Arduino.  Only once you have full documentation of the display requirements could you possibly then have a valid Arduino question, but probably still not a practical one.

@AgentZebra doesn't matter what kind of unknown LCD it is. The answer is  still the same.

@ChrisStratton well I'll just save the answers before you do then :D  It was a valid arduino question as it involved arduino :) Anyhow, these are some useful answers for my son, so maybe they'll be useful for someone else too.  It literally asks the question "Is this worth trying  to do with an old LCD screen and an arduino?" The answer is no, which is a great answer, as it saves time :)

@gre_gor not according to Maximilian Gerhardt's answer above "Might be some parallel interface instead of an easy SPI interface", sounds like it does make a difference what kind it is.

@MaximilianGerhardt Thank you for your helpful answer.

@AgentZebra the same can also be said for that LCD. You can guess for both of them. That dupe gives you the same answer. And the answer would be the same, regardless if an Arduino is involved, so it is not about Arduino.

it's possible, just usually too complex. strip the case apart, google the inner part numbers. you might get lucky and it's a common interface, or one that someone else has made an arduino library for, or maybe an arduono lib for the base controller that will allow it to be mounted, even if the custom commands are unknown. if nothing, just buy a new LCD; they are under $10, and it could takes weeks to reverse-engineer an in-the-wild LCD

@gre_gor Either which way, we have been helped by these answers. So I appreciate that.

Question locked cant figure out if DMing is a thing here so adding this as a comment for future peeps linked here from a search. Ok, so, I recently broke down my 103, and if you have not acquired the service manual yet I HIGHLY suggest you do. The schematics sections make reverse engineering dang near trivial. From what I have gathered there is some sort of I2C/SPI bus for the back LCD and a "Y/U" video pair from the main board. Also a 15v rail but I dont know if its vital. Basically its easier to go back a step and interface with the pcd it was connected to. The LCD itself is 12bit ... 1/2

2/2 12bit color in 4:4:4 format, IIRC. The service manual schematics lay out the signal paths pretty well, but I wouldn't know where to begin trying to bit bang an image to it. I believe the LCD uses that signaling format that is across like 4 or 6 lines and the R G and B bytes are sort of jumbled across them.....like I said, itd be easier to just interface with the PCB in the flip out bit that has the signal conversion IC on it. Also, fun fact, the eyepiece CRT (bw version) only takes 5v and a standard composite signal like the one that the RPi puts out...(rca plug or 4th pin on new boards)

3/2 hit me up if you need more info or want the manual. How to hit me up through here.... I have no idea..... my desktop is off at the moment, but will edit/clarify those posts as needed when its back up. So.... Yeah.

This is likely a type of TTL LCD interface.  But it is nearly impossible to describe more as there are so many variations both in hardware and in timing.
Likely a steady stream of Red Green & Blue binary data way faster than an Arduino Uno could possibly manage is required to create an image.  For the necessary processing power, you would have to utilize one of the top end Arduino boards.  Even then, software to create the steady stream of binary data for this particular LCD is still required. Also, there are hardly no standards beyond saying the LCD is a TTL or LVDS.  Which means hours spent on developing software for this LCD will likely only work for this LCD.
It would be far easier to just buy an LCD and interface board known to work together.  If you are using an Arduino Uno, there is not much processing power beyond saying "I want a circle here" or "I want a line there".  Fortunately, there are such COTS parts available.  Here is a tutorial describing such a device connected to an Arduino Uno.


text:
Why is sensitivity (threshold) parameter ignored
Analog pontentiometer connected to an Arduino. simplest possible setup.
The goal is to send a message over Serial whenever the value changes.
I do not want to spam the Serial connection to much, so the value has to change by at least 20 (sensitivty threshold) before a message Packet is sent.
However, in reality a message Packet is sent even if the value changed only by 1. Why is sensitivity parameter ignored?
edit: After debugging I can see that it enters the first IF-statement in read(). The IF statement evaluates to 0 which is super weird. It shouldn't have entered that IF statement!
MagicPot.h:
#define MAGIC_POT_MAX_RAW_VALUE_10B     1023
#define MAGIC_POT_MAX_RAW_VALUE_12B     4095
#define MAX_RAW_VALUE_DEFAULT           (MAGIC_POT_MAX_RAW_VALUE_10B)

class MagicPot
{
    public:
        typedef void (*callback_fn)();
        MagicPot(uint8_t pin, uint16_t minRead = 0, uint16_t maxRead = MAX_RAW_VALUE_DEFAULT, uint16_t maxRawRead = MAX_RAW_VALUE_DEFAULT): pin(pin), minRead(minRead), maxRead(maxRead), maxRawRead(maxRawRead) {};
        void begin();
        bool read(uint8_t sensitivity = 5);
        uint16_t getValue();
        uint16_t getRawValue();
        uint8_t pin;

    private:
        uint16_t minRead;
        uint16_t maxRead;
        uint16_t maxRawRead;
        callback_fn onChangeCallback;
        uint16_t value;
        uint16_t rawValue;
};

MagicPot.cpp:
void MagicPot::begin()
{
    this->onChangeCallback = nullptr;
    this->value = 0;
    this->rawValue = 0;
    pinMode(this->pin, INPUT);
    this->read(0);
}

bool MagicPot::read(uint8_t sensitivity)
{
    this->rawValue = analogRead(this->pin);

    uint16_t value = map(this->rawValue, 0, this->maxRawRead, this->minRead, this->maxRead);

    if (abs(value - this->value) > sensitivity)
    {
        this->value = value;
        return true;
    }
    else if (value < sensitivity && this->value != this->minRead)
    {
        this->value = minRead;
        return true;
    }
    else if (value + sensitivity > maxRead && this->value != this->maxRead)
    {
        this->value = this->maxRead;
        return true;
    }
    return false;
}

Arduino code:
MagicPot analogPots[] =
{
    MagicPot(A0),
}

void setup() {
  for (MagicPot& x : analogPots) //arr only contains 1 element
    x.begin();
}
void loop() {
  for (MagicPot& pot : analogPots) //arr only contains 1 element
  {
    if(true == pot.read(20))
      {
        CPPacket* analogPotChangedPacket = new CPPacket(HWEvent::Switch, pot.pin, pot.getValue());
        SendPacket( &myPacketSerial, analogPotChangedPacket);
        delete analogPotChangedPacket;
      }
  }

}

Actual Output: (read from computer(conn via Serial))

Type
Error
Target
Value

Switch
NONE
54
516

Switch
NONE
54
515

Switch
NONE
54
514

Switch
NONE
54
513

Expected Output:

Type
Error
Target
Value

Switch
NONE
54
516

Switch
NONE
54
496

Switch
NONE
54
456

Switch
NONE
54
436

you subtract two unsigned types so the result is stored in an unsigned temporary too. try abs((int16_t) value - this->value)

@Juraj: It should be either abs((int16_t) (value - this->value)) or abs((int16_t) value - (int16_t) this->value). Or, better yet, make everything signed. Otherwise, if only one term of the subtraction is signed, the unsigned type wins the “usual arithmetic conversions” game.

@EdgarBonet  Thank you, the weird behaviour was caused by uint16. I tested running the code (with uint) in VisualStudio and there it worked. Do you know why it worked in VS/Win11 but not in Arduino?  Is the c++ version different? Compiler?  And why didn't the compiler warn me? Ps, I am a complete beginner in c++

Consider this subtraction:
value - this->value

Like in any arithmetic operation, the operands undergo integral
promotion, then usual arithmetic conversions.
Oversimplifying a bit, “integral promotion” means that types smaller
than int get promoted to int, whereas “usual arithmetic conversions”
mean the smaller operand gets promoted to the type of the bigger one. If
both types have the same size, the unsigned one wins.
On the Arduino Mega, and int is 16 bits. Since the operands of the
subtraction are both uint16_t, the types are not changed by these
implicit conversions. The subtraction is performed with the uint16_t
type and wraps around modulo 216. If you expect −1, you get
65535.
If you cast one of the operands to int16_t, then it will be implicitly
converted back to uint16_t by the usual arithmetic conversions, and
you get the same result.
On your PC, an int is 32 bits, thus both operands get implicitly
converted to int by integral promotion, and you get the expected
signed result.
The simple solution to your problem is to turn all your variables to
int16_t. I suggest you always use signed types by default, and revert
to unsigned types when you do need the wraparound semantics of the
arithmetic operations (it is useful sometimes).

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


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

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

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

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

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

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

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


text:
Sorting voltage data from pin A0 to 3 variables (ranked)
I don't have any code for this yet but I would like some ideas on coding it.
I have a directional antenna that is rotating at a slow speed and a ham radio connected to the antenna.  I have an output port on the radio that will put a voltage out from 0 to 5 volts for signal strength.  I also have the rotational degree data that is captured.  The question I have is do I try to do a long if then else statement to capture the 3 highest voltages and directions as variables for later processing or is there a better way.   An example would go a long way as well.

you need to think about what you are asking .... radio signal strength varies almost continuously ... the three highest voltages could come from only one source

That is true, That would be ok until I got closer with my vehicle where there would be more separation with the micro transmitters.  If the 1st, 2nd and 3rd highest signals were the same bearing, that would actually be a bonus because I would know the transmitters were further away.  When I get closer they would separate.

do you know how to read the analog pin in Arduino sketch? I am sure you do. The rest of your question is about common coding in C++, so take a coding course, if you don't know how to code what you want

It needs a bit more work but I would suggest using arrays to store the signal and positions something like this..
From (G7WJD) EXPIRED!
#define signalPin A0
#define degreePin A1
int signalStrength;
// STORE DATA IN ARRAY
// 0 [strength, direction]
// 1 [strength, direction]
// 2 [strength, direction]
int signals[3][3];
int degree;
bool positionSavedFlag = false;
void setup() {

}

void loop() {
 signalStrength = analogRead(signalPin);
 degree = analogRead(degreePin);
 // comapare with previous data
 for (int x = 0; x < 3; x++) {
  // have we saved data for this position before?
  if (degree == signals[x][1]) {
    // yes
    positionSavedFlag = true;
    // is it stronger than previous signal at this position
    if (signalStrength > signals[x][0]) {
      // yes so save / update it
      signals[x][0] = signalStrength;
    }
  }
 }
 // now since position not already stored , store it

 }

Thank you Brian, this helps a beginner at coding very nicely.  Kudos to you!


text:
Encoder code using interrupts design question
I have an Arduino Mega 2560, an Omron Optical encoder with an Index (360 steps), a 60 led NeoPixel ring (no Clk wire) and another Arduino Uno.
Here is my question, I have some code written that works with the Arduino Mega and optical encoder outputting decently to the serial monitor for diagnostic purposes.
When I add the additional code to run the Neopixel ring I get a terrible response on the ring.  I have tried the NeoPixel and FastLED libraries with the same terrible success.  It even states in their documentation that they don't work well with interrupts.  I started thinking about sending the 3 digit output to a Direct Pin output from the Mega to be read by another Mega/Uno to run the Neopixel Ring and a 4x20 LCD screen. Does anyone else have any ideas on this.  Below is my code for the Mega and the Encoder.
    // Wiring connections for my encoder:
    // Brown : VCC = 5V
    // Blue + Shield : 0V = GND
    // Black : ENCODER0PINA, Pin 18
    // White : ENCODER0PINB, Pin 17
    // Orange : ENCODER0PINI, Pin 19

    #define ENCODER0PINA         18      // this pin needs to support interrupts
    #define ENCODER0PINB         17      // no interrupt required
    #define ENCODER0PINI         19      // this pin needs to support interrupts

    // variables modified by interrupt handler must be declared as volatile
    volatile long encoder0Position = 0;
    volatile long interruptsReceived = 0;
    volatile byte INTFLAG1 = 0;

    // track last position so we know whether it's worth printing new output
    long previousPosition = 0;

    void setup()
    {
      // inputs
      pinMode(ENCODER0PINA, INPUT);
      digitalWrite(ENCODER0PINA, HIGH);  // turn on pullup resistor
      pinMode(ENCODER0PINB, INPUT);
      digitalWrite(ENCODER0PINB, HIGH);  // turn on pullup resistor
      pinMode(ENCODER0PINI, INPUT);
      digitalWrite(ENCODER0PINI, HIGH);  // turn on pullup resistor

      // interrupts
      attachInterrupt(5, onInterrupt, RISING);  // encoder track A on interrupt 3 - pin 18
      attachInterrupt(4, onReset, RISING);  // encoder Index track on interrupt 4 - pin 19

      // enable diagnostic output
      Serial.begin (115200);
      Serial.println("Ready.");
    }

    void loop()
    {
      // only display position info if has changed
      if (encoder0Position != previousPosition )
      {
        Serial.println(encoder0Position, DEC);

        previousPosition = encoder0Position;
      }
    }

// interrupt function needs to do as little as possible

void onInterrupt()
{
  // read both directional inputs
  int a = digitalRead(ENCODER0PINA);
  int b = digitalRead(ENCODER0PINB);

  if (a == b)
  {
    // b is leading a (counter-clockwise)
    encoder0Position--;
    if (encoder0Position < 0)
    {
      encoder0Position = ((encoder0Position + 360) % 360);
    }
  }
  else
  {
    // a is leading b (clockwise)
    encoder0Position++;
    if (encoder0Position >= 360)
    {
      encoder0Position = ((encoder0Position - 360) % 360);
    }
  }
}

void onReset()
{
  // read Index input
  int i = digitalRead(ENCODER0PINI);
  if (i == 1)
    {
  encoder0Position = INTFLAG1;
    }
}

i would use the ESP32, which can drive the WS2812b in hardware using the IR remote control functionality, and had a whole 2nd core if that's somehow not good enough. Also, try to avoid analogRead() in the ISR, that takes quite some time, and with 360 clicks, you're going to be quite busy with any kind of rapid twisting.

Will the ESP32 be good for taking the 3 digit integer reading from the encoder to other devices as well?  My complete goal would be to use the ESP32 for the 60 NeoPixel Ring, monitoring signal strength (0 to 5 V, pin input) and output some results to a 4x20 LCD screen.  Lastly rectifying the 3 digit reading from the encoder with the ultimate compass from AdaFruit.?

yes, it would be great for that, being hundreds of times faster and dozens of times more memory, with many hardware-accelerated interfaces to reduce core resource usage. might also grab a few level-shifters; sometimes the ESP32 doesn't like 5v devices, though many, such as neopixels, work fine as-is...


text:
GSM librarys Software Serial conflicts with I2C pins 2 and 3 for Arduino Micro
The GSM library apparently uses the Software Serial library to perform the communication. The Arduino Micro specified pins for the serial connection to the GSM is pin 2 and 3 (doc says, but see def of RXPIN below?). I would like to shift this to pin 7 and 8 , with 8 as Rx (has interrupt). However: Changing the definition of TXPIN in GSM3IO.h does not appear to give a working sketch. Also: The pin "number" here, does it refer to PDxx number or other (a bit confused by all the pin names )
.
.
#elif defined(__AVR_ATmega32U4__)
#define __TXPIN__ 7
#define __RXPIN__ 8  /* Previous 3,8,3 ,... but */
#define __RXINT__ 8
#endif

If the pins aren't changing when you change them is it possible that (AVR_ATmega32U4) isn't defined?

How do I check for defines way down in the .h  tree? I tried just printing RXPIN in the sketch source (assuming it would be part of the GSM.h includes), but it appears to be undefined. Strange. The GSM library docs suggest this to be the way of changing the pin number.. I do not understand the specification of the interrupt pin not being the same as the receive pin though...  (other places I note that somebody suggest this define to be set to a non-valid value....and with apparent success)..Meanwhile i tried using pin 7 and 8 using the SoftwareSerial library with AT commands. It worked.


text:
EtherCard library without TCP
I have connected some sensors to an Arduino Uno (but the final code should run on a Pro-Mini) with an ENC28J60 shield. The sensor code works fine - until I add EtherCard. I tried UIPEthernet first, but it's even worse. The problem is the memory footprint. The ethernet libraries are consuming so much memory that random malfunctions do occur.
So I was thinking about removing TCP from the EtherCard library, because I don't need it anyway. I only need IP, ARP, UDP, and based on that DHCP, DNS and NTP.
Has someone already done this?
Is there a stripped-down library?
The file tcp.cpp is pretty big (the biggest in this lib). Is it safe to remove all methods with "tcp" in their name?
Or is there a better solution for this situation?

try my EthernetENC with custom settings https://github.com/jandrassy/EthernetENC/wiki/Settings

@Juraj: Thanks. That looks promising.

Setting uno.build.extra_flags= -DUIP_CONF_MAX_CONNECTIONS=0 in "boards.txt" in the arduino IDE folder reduced program memory usage by 2442 bytes and dynamic memory usage by 290 bytes. BTW changing the #define in "uipethernet-conf.h" has had no effect. However, thank you for the great work :-)

My EthernetENC library based on the original UIPEthernet library by Norbert Truchsess has settings to balance performance and memory usage. These settings are in utility/uipethernet-conf.h file or can be specified as -D parameters for compilation.
UIP_CONF_MAX_CONNECTIONS is a maximum number of connected EthernetClient connections. The default value s 4. You can set it to 0 if you don't use EthernetClient TCp connections. It will save a lot of dynamic memory.
Arduino IDE doesn't have the possibility to set defines for a sketch (For example Sloeber has it). As some workaround to set the defines for different boards for Arduino IDE, you can create a file boards.local.txt next to boards.txt file in hardware package. Set build.extra_flags for individual boards.
comment by OP:

Setting uno.build.extra_flags= -DUIP_CONF_MAX_CONNECTIONS=0 in "boards.txt" in the arduino IDE folder reduced program memory usage by 2442 bytes and dynamic memory usage by 290 bytes.


text:
exit status 1 'mcpButtonState' cannot be used as a function
I keep getting this error and I don't know why.
mcpButtonState is an array, and I would like to change one of its values using a line like this:
mcpButtonState(thisPin) = 0;

(it's inside of a for loop looping trough all my pins).
This is my complete code:
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h
#include <Wire.h>
#include "Adafruit_MCP23017.h"
SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);
Adafruit_MCP23017 mcp;

int mcpButtonPins[] = {0,1,2,3,4};
int mcpButtonCount = 5;
int mcpButtonState[5];

int analogButtonPins[] = {0};
int analogButtonCount = 1;
int analogButtonState[1];

int potiPin = A2;
int soundVolume = 15;

void setup() {
  mySoftwareSerial.begin(9600);
  //Serial.begin(115200);
  mcp.begin();
  for (int thisPin = 0; thisPin < mcpButtonCount; thisPin++)
  {
    mcp.pinMode(thisPin, INPUT);
    mcp.pullUp(thisPin, HIGH);
    mcpButtonState(thisPin) = 0;
  }
  //ANALOG BUTTON SETUP
}

void loop() {
  int potiValue = analogRead(potiPin);
  int newVolume = (potiValue / 1023 * 30);
  if(newVolume != soundVolume)
  {
    soundVolume = newVolume;
    myDFPlayer.volume(soundVolume);
  }
  for (int thisPin = 0; thisPin < mcpButtonCount; thisPin++)
  {
     if(mcp.digitalRead(thisPin) == 0 and int mcpButtonState(thisPin) == 0)
     {
      mcpButtonState(thisPin) = 1;
      myDFPlayer.play((thisPin + 1));
     }
     else if(mcp.digitalRead(thisPin) == 0 and int mcpButtonState(thisPin) == 1){}
     else {
      mcpButtonState(thisPin) = 0;
      }
  }
  //ANALOG BUTTON PLAYING
}

Use [] not ():
 if((mcp.digitalRead(thisPin) == 0) && (mcpButtonState[thisPin] == 0))

Note the use of && instead of the word and.


text:
How to convert serialized JSON string back to JSON object?
How to convert JSON String for example
{"f0":100,"f1":100,"f2":100}

It is what I get from my esp01 side from I2C communication
Now I want it to get it back to my Arduino side variables int f0 ,int f1 ,int f2
But example shown in web site uses kind of different serialized JSON
Example shown,
char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
Can I convert the data I got from I2C communication for using in the method for deserializeJson(jsonobj, stringofdata)
I2C communication side of arduino looks like,
void receiveEvent(size_t howMany) {
  String datain = "";
  while (0 < Wire.available()) {
    char c = Wire.read();
    datain += c;
  }
  Serial.println(datain);
//be careful can't send too much json data I2C crash!
  Serial.println(datain.length());
  DynamicJsonDocument datajson(100);
  if (deserializeJson(datajson, datain)) {
    Serial.print("deserialization ok ");
    digitalWrite(13, HIGH);
    delay(250);
    digitalWrite(13, LOW);
    f0 = datajson["f0"];
    f1 = datajson["f1"];
    f2 = datajson["f2"];

    Serial.println(String(f0) + " " + String(f1) + " " + String(f2));
  }

}

In serial monitor I only see this no deserialization worked
{"f0":0,"f1":0,"f2":0}
22

the return value of deserializeJson is not boolean.

You cannot concatenate string literals (" ") with +. That just adds the pointer addresses together.

I tried with DeserializationError error error inside if condition still no luck

Debug errors like that:
if (err) { Serial.print(F("deserializeJson() failed: ")) Serial.println(err.c_str())
} else { //your code
}

@Juraj I believe you almost answered my question it is not a Boolean  but however it works as Boolean however for a correct deserialization I need to take the inverse of it that, It was my mistake I first thought that gives a Boolean  as correct deserialization as true its not;

The mistake I did was thinking deserializeJson(datajson, datain) gives a Boolean as true for correct deserialization but accually it gives an object of DeserializationError err so need to check if there is no error thus
The new code
// need ! here
  if (!deserializeJson(datajson, datain)) {
    Serial.println("yay it worked");
    Serial.print("deserialization ok ");
    digitalWrite(13, HIGH);
    delay(250);
    digitalWrite(13, LOW);
    f0 = datajson["f0"];
    f1 = datajson["f1"];
    f2 = datajson["f2"];

    Serial.print(f0);
    Serial.print(" ");
    Serial.print(f1);
    Serial.print(" ");
    Serial.println(f2);

//also tested this way and it works too
    Serial.println(String(f0) + " " + String(f1) + " " + String(f2));
  } else {
    // I was coding here thinking its Boolean before
    //error
  }

For reference, here is the documentation of deserializeJson().


text:
const int re-declaration - memory leakage
I am re-declaring a const int variable a few times in a switch-case statement of a function as shown following:
void functionB(type param1, type param2, ..., const int paramConstInt = 100);

void setup() {
    ...
}

void loop() {
    ...
    functionA();
}

void functionA() {
    ...
    switch(var) {
        case 0: {
            const int paramConstInt = 200;
            ...
            functionB(param1, param2,..., paramConstInt);
            break;
        }
        case 1: {
            const int paramConstInt = 300;
            ...
            functionB(param1, param2,..., paramConstInt);
            break;
        }
        case 2: {
            functionB(param1, param2,...);
            ...
            break;
        }
        ...
        default:
            // if nothing else matches, do the default
            // default is optional
            break;
        }

}

void functionB(type param1, type param2,..., const int paramConstInt) {
    ...
}

Does standard C++ allow for it? I am asking so because, if I try to change one of the paramConstInt inside a switch case to 1000 or so I have a strange behaviour similar to that given by a memory leakage. I think anybody willing to replicate this oddity can do it and report.
If const int is replaced by just int, the problem seems to disappear.

Are you using paramConstInt somewhere else ? If now why not simply call functionB(param1, param2,..., XYZ); where XYZ is the value. For example functionB(param1, param2,..., 300); ?

yes, using paramConstInt in the switch-case block as well before passing it as an argument; so the pseudocode above should more precisely be: const int paramConstInt = 200; ...; functionB(param1, param2,..., paramConstInt);

Then your const is not a constant, it's variable. I suggest defining it as such.

What you describe, along with the posted code, has no issue in C++ whatsoever. If you have a strange behavior when setting paramConstInt to 1000, then this is probably due to what functionB does with that argument value.

You have to show us the code of functionB to check what could explain that odd behavior.

The core of the matter is that by changing "const int" to "int", everything runs smoothly. I cannot say that functionB is clear but the matter around "const int" sounds strange to me and I wanted to let you know - that is the main reason why I posted it here.

Does changing const int to int in just the variable declaration, or in both the variable and functionB fix it?

Also, don't you need the paramConstInt to be before the variadic placeholder?

I just changed "const int paramConstInt = 200;" to "int paramConstInt = 200;" - for example - and it fixed it.

"before the variadic placeholder" ?

I had to look that up, too. :) A variadic function is one that takes a variable number of arguments. I assumed your use of , ...,  was meant to imply "maybe some other arguments here, how many of them isn't important to the example", and not "this function takes a variable # of arguments"?

yes, I meant "maybe some other arguments here, how many of them isn't important to the example"

Sorry for alerting the community for one of my faults. I'll try to explain what happened in my code and why "const int" made a difference against just "int".
In my code, functionA() is not being called by loop() as sketched above but it is actually repeatedly called by a third function, say functionAcaller(), which keeps control while in a millis-interval.
Moreover, functionB being called by functionA in turn, has several parameters among which an array vital to the correct functioning of the program, name it MAIN_ARRAY. I didn't notice up to the time I started debugging the "const int" issue that MAIN_ARRAY is local and declared (not initialized) within each switch case (same array size for all switch cases) though every time I enter again one of the switch-cases I actually need to change the values the array contained in the previous run. In spite of the fact that I (re)declared MAIN_ARRAY every time I entered functionA() switch-cases, things were fine since the previous values were not probably cleared by the micro. Well, there was in reality a problem given by "const int paramConstInt". When I set it too big, the program lagged. I guess it had to do with its default value being only 100. Another problem was possibly the order of (re)declaration: whether the first variable being (re)declared was MAIN_ARRAY or const int paramConstInt. Anyway, even when MAIN_ARRAY was (re)declared as first thing once back to functionA() switch-cases, a too big const int paramConstInt caused problems while int alone of the same value was just fine. Sorry again for not having delved into this issue more deeply in advance but since everything was all right except for "const int" I really thought that was the problem.

Once inside the scope of a switch-case, the first memory allocations carried out are for statics and constants. If there are any, any allocation from a previous run must be shuffled. However, I still don't understand why a small-value const int was just fine.

Essentially the poster was (unknowingly) relying on the old contents of then retracted stack still being there when the stack subsequently grew back into that region.  That's an extremely unsafe assumption easily broken by minor code changes or differences in compiler behavior.  It's possible the small value was being optimized out and directly inserted where needed, while the large value may have required stack manipulation.  One would have to read the disassembled output of the compiler to know; of course the only real answer is not to violate the contract of the programming model!


text:
bridge messes up serial.print
EDIT
I am using an Genuino Uno & Yun Shield
I am a complete arduino noob
I am creating something where I need a process to execute a command on my yun shield but when I use Bridge.begin(); It scrambles all text to something like this

.ÿš2%š%šr%š%š%šr%š2%š2%º%š%š%š2%º2%º2%ºr%š2%º2%šr%šr%š%š2%šþøøþøøþúøøýýøþþþýþþøøøøúýøþÿøøþþøúýþúøøøþøýøþýúøþþøüþþøýþþøýøúø

and it just keeps adding characters. if I don't use Bridge.begin(); then it correctly prints.
I wrote this short program to replicate the bug:
#include <Process.h>

void setup() {
// put your setup code here, to run once:
// Start the bridge and serial port.
Bridge.begin();
Serial.begin(9600);

 while(!Serial){

 }
}

void loop() {
// put your main code here, to run repeatedly:
Serial.println("test");
}

So this will give the scrambled text and when you remove the Bridge.begin(); it will show the text but I really need to use a Process in my other program so as I understand I need Bridge.

Did you really follow the "Arduino - Process - Tutorial" ?

If I use that code I get a SerialUSB not declared in this scope on the last line but if change all of them to Serial then it still gives the scrambled output

This may well not be workable with an Uno as the host, unless you do some serious revision to the behind-the-scenes code, as it probably assumes that there is UART for communication with the Linux module that is distinct from the USB channel to the serial monitor.  That would be true on the Leonardo type system this originated with, but not on an Uno.  Hence your probably probably comes from the Bridge code setting the single serial port to a different rate than you intended to use.

So @ChrisStratton do you maybe have an idea how I could make it work

You need to use the Console class instead of Serial. Official example here.

How can I then view my console because I constantly get "Connection closed by foreign host" on my serial monitor when I connect to the yun shield port in the ide (because it said to do that in the example)

Have you shorted the two pins on Arduino Board? If you don't know what I'm talking about I will give more information.

No I have not I was really hoping I wouldn't need to do that where can I find something to sort them?

And maybe also what pins do I exactly need to sort?

Well, I realized that wouldn't probably be the problem (I had to do it, but I have the old Dragino Yun Shield, so it doesn't matter in your case, probably). But make sure you are not connected to the Arduino by USB cable, but via WiFi.

Well that's a little bit of a problem considering that is my power source

Ok, but make sure in your Arduino IDE you have the Network Port (with IP address) selected, NOT the COM ports.

Yes I am connected through the network

I found this: https://www.arduino.cc/en/Guide/ArduinoYunShield#toc10. So if you are using Arduino UNO or MEGA, you need to short the pins indeed.

How can I sort these then? they say with a jumper but when I google them I only find jumper wires?

In my case the shunt jumpers were included with the shield, but here are some places where you can get one: https://www.sparkfun.com/products/9044, https://www.pololu.com/product/968, http://www.digikey.com/product-detail/en/sullins-connector-solutions/STC02SYAN/S9000-ND/76372. I hope they are the right dimension.

But if I read that text it says I would still be able to work without the jumper. But my problem is that it says Connection closed by foreign host

I found a jumper in an old pc thanks for the help

Great, does it work correctly now?

Bridge and Serial both use the same pins. You cannot use them both.
Bridge runs at a much higher baud rate (230400 IIRC) than Serial, which is why it all messes up.

Do you maybe have an idea why my console says Connection closed by foreign host when I try to view it.


text:
Arduino Uno with PWM driven motor and 433 MHz wireless receiver don't work
I am fairly new to the Arduino topic and I'm trying to get a few things to work together.
At the moment I'm using an Arduino Uno board, but planning to use an Arduino Nano for this.
First I tried setting up a DC motor that can be controlled via PWM, which works perfectly when used standalone. I can start/stop the motor and change speed depending on the value I send to the PWM pin.
Next, I tried to use an RF-5V wireless receiver to work with a remote control from remote switched power outlets. For this one I followed the instructions on how to build a 433 MHz sniffer. This all by itself works as well. I can receive different codes depending on which keys on the remote I am pressing.
Now the fun part started: I wanted to integrate both projects into one, so I could use the remote to start/stop the motor. So I came up with the following circuit:

(The sketch is updated so it shows the right pins matching the code)
And the following code (which is partly from the instructions mentioned above):
#include <RCSwitch.h>

// init 433MHz lib
RCSwitch mySwitch = RCSwitch();
unsigned long lOldValue=0;  // to check for consecutive reads on 433MHz
int motorPin = 5; // PWM-Pin to use for motor

void setup() {
  pinMode(motorPin, OUTPUT);
  Serial.begin(9600);
  // set-up rf receiver
  mySwitch.enableReceive(0);
  // 433MHz Receiver on interrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    int value = mySwitch.getReceivedValue();
    // only react, if at least two times same value received
    if (value == lOldValue) {
      if (value == 0) {
        Serial.print("Unknown encoding");
      } else {
        Serial.print("Received ");
        Serial.print( mySwitch.getReceivedValue() );
        Serial.print(" / ");
        Serial.print( mySwitch.getReceivedBitlength() );
        Serial.print("bit ");
        Serial.print("Protocol: ");
        Serial.println( mySwitch.getReceivedProtocol() );
        // One of the keys on the remote
        if (value == 274393) {
          Serial.println("got start code, starting motor");
          analogWrite(motorPin, 100); // start the motor
        }
        // another key on the remote
        if (value == 270384) {
          Serial.println("got stop code, stopping motor");
          analogWrite(motorPin, 0); // stop the motor
        }
      }
    }
    lOldValue = value;
    mySwitch.resetAvailable();
  }
}

When I run the code and click on the remote, I get different values shown depending on the key I press. So the wireless receiver works as expected.
When I receive the right value for starting the motor, the motor really begins to turn, so this works as well.
And here the fun part starts:
As soon as I use the analogWrite function to send data to the PWM port the motor is connected to, the wireless receiver stops working (or at least I do not get any more values when pressing a key on the remote).
I found a few similar posts/problem descriptions on the net which said to try the following:

Use another pin for PWM (due to possible interrupt conflicts). I tried that as well, same behaviour.
Use external power supply instead of USB-Cable, which helped somebody resolve this issue. Not here. Does not work either.

So the question is:
Does anybody know how to combine those two things together so I can use the wireless receiver to get commands and switch on/off the motor with it on an Arduino Uno?
And would this solution probably work with an Arduino Nano as well?
Update:
I changed the motor against a LED, same behaviour. So its not related to the motor itself.
I found out that when i use some timers to set the motor pwm to 0 with the analogWrite function, that the wireless receiver starts working again.
So it really looks like there is no way to use PWM and the wireless receiver together.
I also changed the pin for the receiver from 2 to 3 (and of course changed the code to use the right pin) and used other PWM pins for using with the motor. But still to no success.
Does anyone have an idea on how to bring both the wireless receiver and PWM driven things to work together? Might this be an hardware issue (due to interrupts) or a library issue for the rcswitch?

Most likely it is interference from the motor. You can add some EMI dampening capacitors (small, say 10nF) between the motor's pins and the metal body of the motor.

Double check pin assignments. Your circuit does not match sketch pin assignments.

@MikaelPatel Yes, you are right. I did not pay the neccessary attention when drawing the circuit. But even with the cables attached to the right pins as mentioned in the sketch, it did not work.

You are asking too much from the Arduino if you expect it to drive a motor with only the on-board 5V regulator AND the radio. Eliminate at least the motor connection to the 5V and use a MOSFET to drive the motor with a stand-alone power source like an alkaline battery pack of at least 6V - You need current to drive a motor and the UNO is limited to 500mA. Once you PWM the MOSFET, it should handle the motor with ease. A IR510 is good for this use. You will need a 10K pull-down resistor to the Gate Pin to keep it LOW when no signal is present.  This should get you going in the right direction. 0.01 ceramic filter capacitors to the - and + leads to ground around the motor is also helpful. Look up on-line how others do this.

That's for sure.  The radio itself requires at least 100 mA.


text:
Problem in getting the output (language: Processing and Arduino IDE)
I am working on a small project with Processing and Arduino, in which, depending upon the value of a photoresistor, it displays whether it is day/night/evening.
I read the value from the photoresistor and write the value to the serial port. Then in Processing I read the value from the serial port and display depending on the value.
But I get a very flickery output, and there is always a -1 imprinted on the screen as shown in the video.
Please help me out.
link to the video
Code for Arduino:
int ldr1 = A0;
int x,y;

void setup() {
  pinMode(ldr1,INPUT);
  Serial.begin(9600);
}

void loop() {
  x = analogRead(ldr1);
  Serial.write(x);
  delay(100);
}

Code for Processing:
import processing.serial.*;
Serial port;
int x,y;

void setup() {
  size(640, 320);
  port = new Serial(this, "COM3", 9600);
}

void draw() {
  background(0);
  x = port.read();
  text(x,100,100);
  if(x < 400 && x > 200) {
    textSize(32);
    fill(0,0,255);
    text("it is evening",200,200);
  }
  if(x < 200 && x > 20) {
    textSize(32);
    fill(0,255,0);
    text("it is night",200,200);
  }
  if(x > 400 && x < 900) {
    textSize(32);
    fill(255,0,0);
    text("it is morning",200,200);
  }
}

Is the Arduino actually on COM3? If serial read returns -1, then you did not receive a byte. You should check for if read >= 0 before entering your "if x < ... " etc.

If you read the documentation for Serial::read() at https://processing.org/reference/libraries/serial/Serial_read_.html
it says:
"Returns a number between 0 and 255 for the next byte that's waiting in the buffer. Returns -1 if there is no byte, although this should be avoided by first cheacking available() to see if data is available."
Either before calling "Draw" function, or inside "Draw", you should first check:
if(port.available()){
  //do your checking for X value and set text as you are doing before

}

IMPORTANT - you are only ever sending the lower byte (values 0-255) from Arduino when you do Serial.write(x). That is only 1 byte. The "int" return from an analogue read is 10 bits, and needs 2 bytes to store the information from 0-1023.
You should use the Arduino function Map() to scale it down from 0-1023 to 0-255. It looks like your application should be okay with this, in terms of resolution.
  int val = analogRead(ldr1);
  val = map(val, 0, 1023, 0, 255);
  Serial.write(val); //now you will not lose information

On the Processing side, you would then look at values from 0-255 to determine daylight/times of day.

Map is great if you need to do a linear interpolation but in a situation like this it's complete overkill. Rather than using map you could just divide the value by 4 or shift it right by 2 bits using 'val = val >> 2'. Either of these options are both far smaller and faster.

@Andrew you are correct, it's handy that it's a factor of 2 so shifting or division is fine.


text:
Send values to a PHP page using Arduino ESP8266
I still a noob, and I'm learning Arduino. I built a PHP page to send values using GET parameters.
I would like to send a specific value from Arduino to that PHP page. I bought an ESP8266, and I would like to see it working.
I found this code and I made some changes there, but the the code is not working. I don't receive any value on my database. Can you guys help me?
#include <SoftwareSerial.h>

SoftwareSerial esp8266(10, 11);
String cmd;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Started");
  // set the data rate for the SoftwareSerial port
  esp8266.begin(115200);
  esp8266.write("AT\r\n");
}

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

void teste(){
  // Connect to the server
  esp8266.write("AT+CIPSTART=\"TCP\",\"http://bubu.esy.es\",80\r\n");
  //make this command: AT+CPISTART="TCP","192.168.88.35",80
  //wait a little while for 'Linked'
  delay(300);

  //This is our HTTP GET Request change to the page and server you want to load.
  cmd = "GET /teste.php?test=5 HTTP/1.0\r\n";
  cmd += "Host: http://bubu.esy.es\r\n\r\n";
  //The ESP8266 needs to know the size of the GET request
  esp8266.write("AT+CIPSEND=");
  esp8266.write(cmd.length());
  esp8266.write("\r\n");
  esp8266.write("GET /teste.php?test=5 HTTP/1.0\r\nHost: http://bubu.esy.es\r\n\r\n");
  esp8266.write("AT+CIPCLOSE\r\n");
}

Maybe you should tell the ESP8266 to connect to your WiFi access point. You have about 10% of the required code there.

teste.php?test=5 - does this works (writes to DB) when opened by browser?

Host: http://bubu.esy.es needs to be Host: bubu.esy.es.

Why build up cmd and then write the string out rather than cmd??  i.e. esp8266.write("GET /teste.php?test=5 HTTP/1.0\r\nHost: http://bubu.esy.es\r\n\r\n"); should be esp8266.write(cmd);

authors: Сергей Малюгин


text:
Yikes! Invalid device signature. Fail to burn bootloader and read fuses
I know this problem is kinda common but I had to post it anyway.
Before anything, I would like to inform you guys that I changed the fuse of my Arduino Pro 3v3 @ 8MHz to allow 1.8 V brownout and also programmed CKDIV8 AND CLKOUT. In other words, the fuse configuration is this: E:FE, H:DA, L:3F.
The programmer is the Arduino 2009 running as ISP programmer. The target is Arduino Pro Mini 3V3 @ 8Mhz.
I also used a 0.1uF cap between reset and ground in the Arduino programmer.
After a good time using the Arduino Pro without problems, some random problems began to appear when I tried to upload a program with the programmer (Arduino as ISP). So I tried to burn the bootloader again and the following message appeared ""avrdude: Yikes! Invalid device signature."
The same occurs when I try to communicate with avrdude using this command "avrdude -c arduino -p m328p -P COM3 -b 19200 -v".
Some tests I did:

Continuity test directly at uC pins between those signals: SCK, MISO, MOSI, (/SS - /RESET). No problem good connection.
Verified the clock in XTAL1 and XTAL2. No problem 8MHz.
Verified the clock in CKOUT (Arduino Pro pin 2) and measured 1MHz.
I also tried to delay the avrdude using -B5, B10 and another values. With a quick search on Google some people are saying that those delays don't work with the Arduino as ISP.
I used some sketches for slow clocks, which I don't remember, and no luck.
External power and no luck again.

What am I missing? Do I need to change something to communicate with Arduino Pro running at 1MHz?

If you are burning the bootloader through the IDE it won't expect the CKDIV8 fuse to be set.
I have a bootloader programmer which you could use to reprogram the bootloader. You just need another Arduino (eg. Uno, Mega) and connect 6 wires between each of them like this:

The sketch for programming the bootloader is available on Github:
https://github.com/nickgammon/arduino_sketches
You want the one in the "Atmega_Board_Programmer" subdirectory.


text:
3D printer Arduino sketch
I'm building an automatic warehouse system using 3 nema17 stepper motor. My problem is to move the motors with precision, since I do not have any kind of encoder on the motor and so I cannot know the position of the axes. I tought that the system could be similar to a 3d printer, since neither 3d printers have encoder on the motor. Where can I find a sketch for Arduino of a 3d printer, to understand how they work? How do they move with such precision without any kind of sensor?

With stepper motors you don't need any form of encoder. Only a limit switch.
A stepper moves in steps - you tell it how many steps to move. As long as you know where you started from (which is what the limit switch is for) then you can always know exactly where you are.
If you told the stepper to move 10 steps clockwise you know the stepper has moved 10 steps clockwise. If you then move 10 steps anti-clockwise, you will be back where you were.
All you need to do is count.


text:
Run exe or apk on Arduino
how to run exe file or apk file on Arduino UNO?
Please suggest me any way to execute both file. Thank you.

You're really not getting what an Arduino is, are you?

What is Arduino?

If a PC or Smartphone is akin to a family car, an Arduino is akin to one of the wheel bolts holding the wheels on.

@Majenko: but sir, we run c program on arduino. So IDE creates exe and run it on device. How that happened?

No, the IDE does NOT create an EXE. It creates a HEX. Embedded programs are vastly different to executables that run on an operating system.

@Majenko ok sir thank you for clearing concept

You cannot.  An APK is an Android package, and an EXE is a Windows executable.  Neither can run on an Arduino,

authors: Калоян Георгиев


text:
How to read incoming HEX values from Serial.read() method?
Brief description about the problem History
Communicating with a old VersaStat II used GPIB port but the GPIB ports PCI card stopped working but there was a another port 25 pin rs232 Serial communication port but even now, too bad computers are abending the Serial port luckily there is still virtual Blutooth COM port which can be used with a modern laptop so ESP32 microcontroller was selected to communicate with this device wirelessly (might later go for HC05 module etc.).
Fixing the voltage difference problem
Now there is a big problem the esp32 Serial uses +3.3 V or logic 1 &  0 V for logic 0 But in the rs232 port logic 0 is +3 V ~ +12 V and logic 1 is -3 V ~ -12 V  also ± 3V  undefined region. To overcome this problem I have used the following circuit with optocouplers.
Here is the circuit diagram

The following code was used to communicate with the device easy as seems
Code
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;
int speedsend = 9600;

void setup() {
  Serial.begin(speedsend);
  Serial2.begin(speedsend);
  SerialBT.begin("ESP32SERIAL");
  delay(500);
}

void loop() {

  if (Serial2.available()) {
//incoming data from the device
    int i = Serial2.read();
    SerialBT.write(i);
    Serial.println(i); // To check what is coming as output
  }
  if (SerialBT.available()) {
    Serial2.write(SerialBT.read());
  }

}

But I see no meaningful characters in putty (Bluetooth COM port) in Arduino Serial I see some numbers in HEX representation. Is this the way old devices communicate?
This link show how HEX numbers correlate with ASCII characters
https://www.rapidtables.com/convert/number/hex-to-ascii.html
How to fix this issue am I doing something wrong in here the circuit parameters etc.
Communication Example with device
For a start the ID command should give a number as 2532 according to book after the conversion it gives me 32 32 34 32 0 0 , 2242 looking at the Arduino Serial numbers with the help of the converting web site shown in above url. That's how I noticed It gives me HEX numbers.
Here is the PDF rs232c Interface section PDF the original Book came with ID command page too.
https://drive.google.com/file/d/1BHhIsloF4voMxoFeSlz1GsjwfgHwgsPJ/view?usp=sharing
Another book looks same but not from the book came with
https://drive.google.com/file/d/1z0NUOe17SpVYTIBfEE8s0EKStfLKKv_-/view?usp=sharing

This might help you

your question is unrelated to the arduino ... it is a general programming question

your problem is not hex to ascii coversion ... it is hex text to decimal coversion

Device transmits HEX values like in table

@Avon97 If you can provide a link for the manual of the device, we could check ourselves, what exactly gets send. In a short google search I only found manuals for version 3 or 4, but not for 2.

@chrisl I have full edited the question now

 in Arduino Serial I see some numbers in HEX representation. -- No you don't. You're using println() on an integer which gives a decimal representation. To get HEX you have to specifically request a HEX representation. Your numbers are decimal. 32 is a space.

You have miss understand @Majenko the Arduino Serial is used see What is coming to i variable because in putty Bluetooth Serial has no meaningful result and you are correct 32 is space I see that in Bluetooth Serial in putty it goes like __"_  as I remember. ( underscore is a space)

Firstly you don't need that really complex optocoupler circuit. You just need a run-of-the-mill MAX3232 chip (note the extra 3 in there: it's the 3.3V version), that's what they're designed for: RS232 to 3.3V logic level conversion. You can pick up breakout modules for pennies on your favourite marketplace (ali-express, ebay, etc).
As for your reading, your assumption that your numbers are hexadecimal is completely wrong. They're decimal, not hexadecimal.
You read the data from the remote device and store each byte in an integer variable. Then you print that integer variable using Serial.println(). That will always give you a decimal representation of the numeric integer variable.
Your response of 32 32 34 32 0 0 , 2242 to my trained eye looks like bad communication. Maybe caused by your optocoupler circuit (change that for a MAX3232 immediately), or maybe caused by a mismatch in your baud rate, bit count, or parity settings.

Thank you, I have to check the communication first with my old core 2 duo computer first, it has a built in Serial port Yeah you may be right it has do something with communication error

Indeed it was bad communication error I did connect it to the computer (COM port) directly now it works fine

Your problem is, that you try to provide a HEX value, but you are actually providing a decimal value.
When you just write a whole number like 32, it will be interpreted by the compiler as a decimal number. The decimal number 32 is equal to HEX 20, which is a space character in ASCII.
Solution: Write your number as decimal value like this:
int i = 0x32;

The 0x preceding the value will mark it as a hexadecimal representation.

But I get 32 from the method int i = Serial2.read(); if i is 32 how to fix this

Are you getting a byte with the decimal value 32, or are you receiving ASCII encoded hex data (That would be 2 characters, one '3' and one '2')? If the device send the decimal value 32 in one byte, why would it mean hexadecimal 32 with that? So what exactly are you receiving?

I am receiving value 2 gets as 32 to int i

You didn't really answer my question. Are you receiving the ASCII character '2'? How exactly did you check, that i is 32 (hex or decimal?) for you?

When I send the ID command from putty I get values 32 32 34 32 0 0 in read() method
one by one for variable i when I convert it is 2 2 4 2 or 2242 book says I should get something like  2532 representing the VersaStat 2 TM with Arduinos int to ascii conversion this has no meaning at all. Also if I send wrong commands a error light turns on in the device it turns off after I send a correct command. That's how I though this has to be character 2 for 32

How is Putty involved?  Can you show more of your code?  If 32 -> '2' then it looks like you are looking for a decimal to ASCII conversion.  A hex to ASCII conversion of 0x32 would get you ' '.

@DaveX its something like this if (Serial2.available()) { int i = Serial2.read(); Serial.println(i); }

You could use Serial.println(i,DEC);, Serial.println(i,HEX); or Serial.write(i);Serial.println(); to echo what you receive on Serial2 out on Serial in different formats.


text:
Read and write on the same node (central) using an RF24 network on Arduino
I want to send and receive on the same node using the RF24Network library, but I'm unable to do so even when I use radio.StopListening().
Here is the code:
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(9,10);
RF24Network network(radio);
struct payload_t{unsigned long int code; unsigned long int message;};

void setup(void) {
  Serial.begin(9600);
  SPI.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.setAutoAck(false);
  network.begin(108, 0);
}

void loop(){
  network.update();
  RF24NetworkHeader header;
  payload_t payload;
  if(network.available()) {
    network.read(header, &payload, sizeof(payload));
    Serial.println(payload.message);
    // I WANT HERE TO SEND BACK TO THE TRANSMITTER but I'm unable to do that
    radio.stopListening();
    payload_t payload = { 2000, 15444452 };
    RF24NetworkHeader header(2);
    network.write(header, &payload, sizeof(payload));
  }
}

Second Node:
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(9,10);
RF24Network network(radio);
struct payload_t{unsigned long int code; unsigned long int message;};
firstExec = 1;

void setup(void) {
  Serial.begin(9600);
  SPI.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.setAutoAck(false);
  network.begin(108, 2);
}

void loop() {
  network.update();
  if(firstExec) {
    radio.stopListening();
    payload_t payload = { 2000, 5555555 };
    RF24NetworkHeader header(0);
    network.write(header, &payload, sizeof(payload));
    radio.startListening();
    firstExec = 0;
  }
  RF24NetworkHeader header;
  payload_t payload;
  if(network.available()) {
    network.read(header, &payload, sizeof(payload));
    Serial.println(payload.message);
  }
}

Could you post the part of your code you are having problems with?

How about including your attempt to send data so we can see where you went wrong?

Sorry for that, here is the full script with the sending code.

How about the code for the other node?

Sorry for missing the network.update() because i copied just the necessary code and as I always put this in the top of the loop I missed it up when I copied

I'm voting to close this question because it has been abandoned in unanswerable form for over a year.

The library says you must include network.update() in loop() for the nodes to be in sync. Place that call at the top of loop() in both nodes.


text:
Why does the serial monitor output show some unidentified symbols?
#define LED 13
#define BAUDRATE 9600
#define DEBUGOUTPUT 0
#define LED 13
#define powercontrol 10

// checksum variables
byte generatedChecksum = 0;
byte checksum = 0;
int payloadLength = 0;
byte payloadData[64] = {0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;

// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;

//////////////////////////
// Microprocessor Setup //
//////////////////////////
void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(BAUDRATE); // USB
}

////////////////////////////////
// Read data from Serial UART //
////////////////////////////////
byte ReadOneByte() {
  int ByteRead;
  while(!Serial.available());
  ByteRead = Serial.read();
  #if DEBUGOUTPUT
  Serial.print((char)ByteRead);
  // echo the same byte out the USB serial (for debug purposes)
  #endif
  return ByteRead;
}

/////////////
//MAIN LOOP//
/////////////
void loop() {
  // Look for sync bytes
  if(ReadOneByte() == 170) {
    if(ReadOneByte() == 170) {
      payloadLength = ReadOneByte();
      if(payloadLength > 169)
      //Payload length can not be greater than 169
        return;
      generatedChecksum = 0;
      for(int i = 0; i < payloadLength; i++) {
        payloadData[i] = ReadOneByte();
        //Read payload into memory
        generatedChecksum += payloadData[i];
      }
      checksum = ReadOneByte();
      //Read checksum byte from stream
      generatedChecksum = 255 - generatedChecksum;
      //Take one's complement of generated checksum
      if(checksum == generatedChecksum) {
        poorQuality = 200;
        attention = 0;
        meditation = 0;
        for(int i = 0; i < payloadLength; i++) {
          // Parse the payload
          switch (payloadData[i]) {
            case 2:
              i++;
              poorQuality = payloadData[i];
              bigPacket = true;
              break;
            case 4:
              i++;
              attention = payloadData[i];
              break;
            case 5:
              i++;
              meditation = payloadData[i];
              break;
            case 0x80:
              i = i + 3;
              break;
            case 0x83:
              i = i + 25;
              break;
            default:
              break;
          } // switch
        } // for loop

        #if !DEBUGOUTPUT
        // *** Add your code here ***
        if(bigPacket) {
          if(poorQuality == 0) digitalWrite(LED, HIGH);
          else digitalWrite(LED, LOW);
          Serial.print("PoorQuality: ");
          Serial.print(poorQuality, DEC);
          Serial.print(" Attention: ");
          Serial.print(attention, DEC);
          Serial.print(" Time since last packet: ");
          Serial.print(millis() - lastReceivedPacket, DEC);
          lastReceivedPacket = millis();
          Serial.print("\n");
          switch(attention / 10) {
            digitalWrite(LED, HIGH);
            digitalWrite(LED, LOW);
          }
        }
        #endif
        bigPacket = false;
      } else {
        // Checksum Error
      } // end if else for checksum
    } // end if read 0xAA byte
  } // end if read 0xAA byte
}

A snapshot of the output would be quite helpful...

It time to start stroking our crystal balls, what symbols?
Actually it doesn't really matter, ReadOneByte() is the cause, you are printing ByteRead without checking that it is printable.  Character greater than 127 will look strange when you print them out, only 32-126 are printable (127 is backspace) see http://www.asciitable.com/ for more details.  In this case I would print the value as a hex number, Serial.println(ByteRead, HEX);
If you are still getting symbols after changing that there may be other prints that have the same problem

select the same serial Baudrate in the select which is in the bellow of the serial monitor window as you have put in the code.


text:
Reading multiple cases on Serial
I am using a Leonardo board and am testing the APIs in the Serial type. The board is talking to a screen using serial.
The pseudo code is as follows (I show code relevant to Serial):
void setup(void) {
    Serial.begin(115200);
}

void loop(void) {

    if(Serial.available())
    {

        if (Serial.find(0x30))
        {
             func1();
        }

        if (Serial.find(0x31))
        {
             func2();
        }

    }

 }

 void func1()
 {
      // Serial.print() used multiple times

      asm volatile ("  jmp 0");
 }

 void func2()
 {
      // Serial.print() used multiple times

      asm volatile ("  jmp 0");
 }

I test using the Arduino IDE (1.8.0) and its Serial Monitor. When I send 0x30 over serial, the first if case gets triggered to invoke func1, but when I send 0x31, I cannot get the second if case (func2) to get triggered. This even happens when I test 0x31 first; the second if case never gets triggered. Can someone tell what I am doing wrong here and what is the right way to use serial ?
Edit For testing, one can use the pseudo code itself; I tested using different number of LED blinks in func1 & func2, and the problem still holds.
Edit 2 Based on Dave's answer, I tried a test with serial using sample code from
I did another test where I used the sample loop code for read (https://www.arduino.cc/en/Serial/Read) and tried typing 0 or 1 through serial monitor. I observed the following:
// Typed 0
I received: 48
I received: 13
I received: 10
// Typed 1
I received: 49
I received: 13
I received: 10

It is looping faster than the serial is delivered, so each time there is a byte delivered, it tests it against 0x30 until nothing is left, and then drops out, leaving nothing .available() for the next if(), so it fails out as well and starts up the loop() again.
I'd read a byte at a time and work with that:
int incomingByte = 0;   // for incoming serial data

void loop(void) {

if(Serial.available())
{
    incomingByte=Serial.read();

    if (incomingByte == 0x30)
    {
         func1();
    }

    if (incomingBute == 0x31)
    {
         func2();
    }

}

I tried your approach. Now I can trigger either case, but only once. So after uploading the code, I can try 0 or 1, and either case run fine. But on second try, none of the cases get triggered.

Check my edited question. I did another simple test to see behavior.

I tried removing the asm volatile statements from func1 and func2, and the original pseudocode now works. But I need a way to reset the program to the beginning. So I guess my question is whether there is a more stable way to reset the program to PC 0.

That's a different question.  Maybe http://playground.arduino.cc/Main/ArduinoReset would help.


text:
How to store an RFID tag number in a string
I want to send RFID tag number to PHP page. So far I have sent a fixed string to php and it worked, now I am not getting data in string when i scan rfid tag. I want to store every RFID tag number in a string when it is scanned, so that I can send it to php page.
if (rfid.isCard()) {

    String rfid_uid = "";
    if (rfid.readCardSerial()) {
        String rfid_uid = "";
        for (int i = 0; i < 4; i++) {
            Serial.print(rfid.serNum[i], HEX);
            rfid_uid = rfid.serNum[i];
        }

        Serial.println();
    }
    //delay(7000);
    Serial.print("User ID \n");
    Serial.println(rfid_uid);
    make_request(rfid_uid);
}

This is the path to php page
         String method = "GET /ethernet/data.php?rfid_uid=";

String rfid_uid = "";
if (rfid.readCardSerial()) {
    String rfid_uid = "";
    for (int i = 0; i < 4; i++) {
        Serial.print(rfid.serNum[i], HEX);
        rfid_uid = rfid.serNum[i];
    }

    Serial.println();
}

This code has multiple problems:

the variable rfid_uid is defined twice, they are overshadowing each other. The inner part only assigns a value to the rfid_uid delcared in the inside of the if statement, the outer rfid_uid will remain empty
As you can see with Serial.print(rfid.serNum[i], HEX);, the element rfid.serNum[i] is an integer, which is printed as hex. (e.g. 123 = 7B), in rfid_uid = rfid.serNum[i]; you however assign the direct numerical value, without converting it to hex

You can try the following, if you want the serial number as a 4 byte hex string:
String rfid_uid = "";
if (rfid.readCardSerial()) {
    for (int i = 0; i < 4; i++) {
        String uid_part = String(rfid.serNum[i], HEX);
        Serial.print(uid_part);
        rfid_uid += uid_part;
    }

    Serial.println();
}
//rest as before

This should construct a String object from the integer in HEX format and append (using the += operator it to the rfid_uid string). Thus, after 4 iterations, the String value is built up and can be used in the request.

https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

do not use String
char url[64];
sprintf(url, "GET /ethernet/data.php?rfid_uid=%02x%02x%02x%02x", rfid[0], rfid[1], rfid[2], rfid[3]);