text:
How to NOT repeat a piece of code again and again?
I have a VERY long code:

Sketch uses 30468 bytes (92%) of program storage space. Maximum is
  32768 bytes.

I've been trying to reduce it's size so i can write more code, one of my main part of code which repeated many times in switch cases or in if statements is related to de-bouncing the buttons.
Here's a piece of my code as an example:
  case 12:
    if ((millis() - millistimer) > BounceD) {
      if (receivedValue == RFb) {
        magnetDistance += 5;
        millistimer = millis();
        receivedValue = 0;
      }
    }
    if ((millis() - millistimer) > BounceD) {
      if (receivedValue == RFd) {
        magnetDistance -= 5;
        millistimer = millis();
        receivedValue = 0;
      }
    }
    break;

The de-bouncing actions happens in each and every case and for each and every button.
There's two buttons which in each case increase/decrease different values.
How to avoid repeating the de-bouncing action for every button?

EDIT:
The recievedValue is updated via RC buttons value once any button is pressed on the remote.

I don't think this is due to long code. You most likely use constructs that are known to have a large footprint like string. Please provide the FULL code to be able to judge the root cause of your high space usage.

Have you heard of functions? That is a cool construct to write a code block once and use it multiple times again.

@Kwasmich i actually have several Strings, i can't just remove them! what do i do with them?

@chrisl so a function for de-bouncing? how do i call it for every button?

Replace C++ ´string´ with C style strings which are arrays of char - char[] and use the corresponding methods for string manipulation.

@Kwasmich can you please provide a link to an article (tutorial) for further reading?

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

@Juraj Thank you.

http://www.cplusplus.com/doc/tutorial/functions/

There are even libraries for debouncing, like the Bounce 2 library

Could you post all the code, or at least some more? As the code doesn't even do a digitalRead, to read the buttons state. Secondly, the second if statement will never evaluate to true, so can be entirely removed.

@Gerben all cases look like the same as i posted, i just removed the lcd.print() part etc...

@Kwasmich i did changed all strings to char but that only reduced the size by 3%

@chrisl i can't use Bounce 2 library because the buttons are remote RF buttons, i'm using RC-Switch library.

If you don't use physical buttons, why do you want to debounce? Bouncing is a property of physical buttons

@chrisl because the remote that i have sends continuous value to the receiver! and when a value is received it'll do the math and change the receivedValue to zero and cycle continues...

In the short example of above, first find out what is a duplicate (the two outer if statements including their body), than the differences:

Rfb versus Rfd
+5 versus -5

Than make a function for the duplicated code, and turn all differences into a parameter (I don't know the type of Rfd, so I take an int for it).
You will get:
case 12:
  processButton(&Rfb,  5); // Offset magnet distance by +5
  processButton(&RFd, -5); // Offset magnet distance by -5
  break;

  ...

void processButton(int* rf, int diff)
{
  if ((millis() - millistimer) > BounceD) {
    if (receivedValue == *rf) {
      magnetDistance += diff;
      millistimer = millis();
      *rf = 0;
    }
  }
}

Note that if magnetDistance and millistimer are local variables you also have to pass them (as pointer to change the value), if they are globals you can keep the code as is above.
UPDATE
The way parameter works is as follows. E.g.
processButton(Rfb,  5);

Will call the following function:
void processButton(int rf, int diff)

Where value rf will be Rfb, and diff will be 5 (+5).
Thus when magnetDistance += diff; is executed, diff will be +5 and magnetDistance will be increased with +5. In the next call, magnetDistance will be -5 and thus will be subtracted.
UPDATE 2
To change a variable, you have to pass it as pointer, otherwise the (copied) parameter value will be changed and not return its value to the called function. So you have to give the parameter as an address (& operator), and use -> instead of . to get to the value.

can you please comment that code? does it just increase the value of magnetDistance or decrease it too? because RFb and RFd are two different buttons.

Instead of commenting code (which is more or less trivial), I added an explanation how parameters work, I guess that is the information what you miss. It increases or decreases the value, depending on the value passed to the function (first time +5, second time -5).

thanks but what if we press RFb three times? it will just do +5 and -5 three times instead of just do +5 three times.

I'm not sure what you mean ... my code should do exactly like your code but removing the duplicated code parts (which are changed into a function with parameters)... I suggest you add some Serial.prints's, to see what values are passed, so you can see it for yourself.

since it's a remote RC button the receivedValue should be updated with the value it receives via pressing the button on the remote, in your code it seems the receivedValue is not getting any value from the remote and just doing the math part...

receivedValue is only used for a comparison, it is not updated in your code.

Right, sorry my bad, i'll update the question right now.

You only reset receivedValue to zero, so you can do this inside the function as well

@newbie I changed my answer to accommodate for the zero assignment statement (see chrisl's comment too above).

@newbie I will.


text:
How do I send MIDI properly with ESP8266?
So, I've finally able to send and receive MIDI using Arduino.
My next thing to do was sending 5 pin MIDI to rtpMIDI, and vice versa, using ESP8266, but so far I can't even send MIDI correctly.
So far, I used this library, and it send midi without issues with Arduino Mega. But using Wemos D1, strange thing happens.

this is output of MIDI OX. Pretty sure I wasn't sending MIDI CC.
Here's the code so far :
#include <MIDI.h>

 // Created and binds the MIDI interface to the default hardware Serial port
 MIDI_CREATE_DEFAULT_INSTANCE();

 void setup()
 {
     MIDI.begin(MIDI_CHANNEL_OMNI);  // Listen to all incoming messages
 }

 void loop()
 {
     // Send note 42 with velocity 127 on channel 1
     MIDI.sendNoteOn(42, 127, 1);

     // Read incoming messages
     MIDI.read();
 }

UPDATE : Here goes the settings.

Any reason why this happens? Please help me. Thanks!
Schematics :
Basically I just change the Arduino to Wemos D1 Uno.

how is it wired? MIDI_CREATE_DEFAULT_INSTANCE will use Serial on pins labeled RX, TX on Wemos, but esp8266 outputs some boot log on this RX at start.

@Juraj I updated the screenshot. the old screenshot was me trying to send MIDI using TX1, but still not working. Above screenshot were me trying to run that program, with MIDI  OUT on pin D1 (TX)

Please show a schematic of your circuit.

@CL Edited the answer with schematics. I just realized the title was wrong! :( I'm trying to send MIDI from ESP8266 (Wemos D1 Uno) through serial, to MIDI cable.

Does the Wemos run at 5 V or 3.3 V?

Wemos io pin is 3.3 V only

@CL but I run the wemos with USB cable ... does that mean 5v?

just tested the exact same sketch and schematics using Arduino Mega, and it works.

I just realized that moved the cable from 5V to Vin works! Since I only use USB connection, I don't think it should make any problems. It may broke the MIDI receiver if I'm using external power supply tho ...

NOTE : Probably not the answer you're looking for, but it works for me.

Solution : Move the jumper from 5V to Vin.
Why? I don't know. It just works.

Please notice that this is Wemos D1 Uno, which has adaptor input, which can receive 9-24V.
If you're going to use the adaptor, IT MAY BROKE YOUR MIDI DEVICE!
As far as I know, Vin stands for Voltage Input, and everything from the adaptor is routed there. That means if you use 24v adaptor, Vin is 24v!

I'm only planning to use USB as power supply, so yeah. it works for me.
If you're going to use Vin with external power supply, please use voltage regulator to 5v. Better safe than sorry.

Anyway, since I'm planning to use 6N137 to receive MIDI also on this board, here goes :

Input voltages greater than 7 V must be avoided to preclude damage to
  the gate oxide of the input stage. This damage is not necessarily
  permanent, but will adversely affect the expected lifetime of the
  circuit. The gate oxide of AHC devices is only 200 Å thick. An input
  voltage of 7 V corresponds to a field strength over the gate oxide of
  350 kV/cm. Although breakdown of the oxide is expected only at input
  voltages above 10 V, electrons tunnel increasingly into the gate oxide
  at field strengths greater than 350 kV/cm, influencing characteristics
  of the transistors and causing failure.

Source : this question on electronics stackexchange.

source: Stack Exchange

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

sort: votes


text:
Random lighting for 18 pin LED
I am trying to write code so that 18 LEDs will light up randomly except 2 of them light up together. Am I using random wrong? I initialized it to make the random number random.
Here is my code:
int timer = 1000;

int ranndom;

void setup() {
    // put your setup code here, to run once:
    pinMode(30, OUTPUT);
    pinMode(31, OUTPUT);
    pinMode(32, OUTPUT);
    pinMode(33, OUTPUT);
    pinMode(34, OUTPUT);
    pinMode(35, OUTPUT);
    pinMode(36, OUTPUT);
    pinMode(37, OUTPUT);
    pinMode(38, OUTPUT);
    pinMode(39, OUTPUT);
    pinMode(40, OUTPUT);
    pinMode(41, OUTPUT);
    pinMode(42, OUTPUT);
    pinMode(43, OUTPUT);
    pinMode(44, OUTPUT);
    pinMode(45, OUTPUT);
    pinMode(46, OUTPUT);
    pinMode(47, OUTPUT);

}

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

    ranndom = random(30, 47);

    if (ranndom == 38 || ranndom == 39) {
        digitalWrite(38, HIGH);
        digitalWrite(39, HIGH);
        delay(timer);

        digitalWrite(38, LOW);
        digitalWrite(39, LOW);
        delay(timer);
    }
    else {
        digitalWrite(ranndom, HIGH);
        delay(timer);

        digitalWrite(ranndom, LOW);
        delay(timer);
    }

}

And what is the problem with this code? Is it not working as you intended? If yes, please describe how it behaves and what you expected to do.

It just lights up the lights but does not turn them off. Is the code correct? like was random used correctly?

is the format correct? is the code used correctly?

pin 47 will not light up ever, because the maximum value parameter of random() is exclusive. And you might want to use randomSeed() to get real random numbers (the current way the number row will be equal for every power on of the device). The code itself seems good and should work.

So by changing random() to randomSeed(30,47) It will include 47 and get random numbers that associate with the pin the LED is connected to?

No, randomSeed has another functionality. Please read the documentation for it. And to get 47 into it, you need to specify a maximum value of 48.

when I change it, is it giving me the error of too many arguments. What do I need to change?

See here at the documentation that shows how to use random() and randomSeed()

I went back to random(30, 48) and then plugged it in and the lights are all going on at the same time and not even following the speed

Are you sure, that you uploaded the code correctly? And are the lights connected correctly? You can test with the blink example, that comes with the Arduino IDE. What type of Arduino do you use?

Please post the circuit you are using for the LEDs.

i am using relays. The type is a eledoo mega 2560

So It has started to slightly work for about 2 cylces and then it goes back to all the lights. I am the coder and not doing the circuit.

I redid the code and it works occasionally and then it stops working. here is the code:

int timer = 1000;
long randNumber;
void setup() {
// put your setup code here, to run once:
randomSeed(analogRead(30));
}
void loop() {
// put your main code here, to run repeatedly:
randNumber = random(30,48);
pinMode(randNumber,OUTPUT);
if (randNumber == 38 || randNumber == 39) {
digitalWrite(38, HIGH);
digitalWrite(39, HIGH);
delay(timer);
digitalWrite(38, LOW);
digitalWrite(39, LOW);
}
else {
digitalWrite(randNumber, HIGH);
delay(timer);
digitalWrite(randNumber, LOW);
}
}

It would be best if you improved your question by editing your question to answer what people are asking here in the comments.

Since you are using relay: Do you have complete relay modules or do you connect just the relay directly to the Arduino? And how do you have them connected. This is important for the functionality of the code

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


text:
Refactoring bad design?
Could someone help me how to refactor old very complex code ?
Original used just setup and everything else was in single ISR.
But as it was bigger and bigger, code is quite slow and quite random sometimes, even PC emulator did not helpped much (probably some long operations like printing are sometimes interrupted by next interrupt depending on analog values, buttons, etc.).
Is there any guide how to maintain such a project or is there only way out start again from scratch ?
As there are few important regulations also event queue would be needed, but not sure if there is any pattern or a template to start from in case of restart. A-Star 32U4 Micro has <32kB flash and code is hard to fit in yet (there are also big fonts).
Example of font unpack code, but hope this part is quite ok:
void Adafruit_GFX::drawChar(int16_t x, int16_t y, unsigned char c,
  uint16_t color, uint16_t bg, uint8_t size) {
...
    uint8_t blockSize = 0;
    if(packed) blockSize = pgm_read_byte(&bitmap[bo++]); // for first char pick 1st bit array only
    BitStreamsReader bitStream(&bitmap[bo++], packed?blockSize:0); // ptr, blockSize(if packed)
    BitXorBuffer rowXorBuf(w); // row XOR buffer (each row is XORed with)
    bool chk;
    for(yy=0; yy<h; yy++) {
        rowXorBuf.rewind();
        for(xx=0; xx<w; xx++) {
            chk = bitStream; // read 1b
            if(packed) chk = rowXorBuf.xorMove(chk); // xor with XOR buffer
            if(chk) {
                if(size == 1) {
                    writePixel(x+xo+xx, y+yo+yy, color);
                } else {
                    writeFillRect(x+(xo16+xx)*size, y+(yo16+yy)*size,
                        size, size, color);
                }
            }
        }
    }
...

class BitStreamsReader {
public:
    BitStreamsReader(uint8_t *arr, unsigned int maxSize) {
        blockSize = maxSize;
        bitMask = 0x80;
        bytePtr = arr;
        zerosCount = 0;
        remainingBits = 0;
        markBitInit();
    }
    operator bool() {
        if(!blockSize) { // unpacked stream
            bool retVal = !!(pgm_read_byte(bytePtr) & bitMask);
            next();
            return retVal;
        } else if(remainingBits) {
            bool retVal = !!(pgm_read_byte(bytePtr) & bitMask);
            next();
            if(!--remainingBits) {
                markBitInit();
            }
            return retVal;
        } else if(zerosCount) {
            if(!--zerosCount) {
                markBitInit();
            }
            return 0;
        }
        return 0; //throw "??";
    }
private:
    void markBitInit() {
        if(blockSize) {
            if(pgm_read_byte(bytePtr) & bitMask) {
                remainingBits = blockSize;
            } else {
                zerosCount = blockSize;
            }
            next();
        }
    }
    void next () {
        if(bitMask == 0x01) {
            bitMask = 0x80;
            bytePtr++;
        } else {
            bitMask >>= 1;
        }
    };
    uint8_t *bytePtr, bitMask, zerosCount, remainingBits, blockSize;
};

class BitXorBuffer {
public:
    BitXorBuffer(int bufSize) {
        bufSize = bufSize/8+!!(bufSize&7);
        bitBuf = new uint8_t[bufSize];
        memset(bitBuf, 0, bufSize);
        rewind();
    }
    ~BitXorBuffer() {
        delete[] bitBuf;
    }
    void rewind() {
        bitMask = 128;
        bytePtr = bitBuf;
    }
    bool xorMove(bool by) {
        if(bitMask & *bytePtr) by ^= true;
        *bytePtr |= bitMask;
        if(!by) {
                *bytePtr ^= bitMask;
        }
        nextBit();
        return by;
    }
private:
    void nextBit() {
        if(bitMask > 1) {
            bitMask >>= 1; // move bit in XOR buffer
        } else {
            bitMask = 128;
            bytePtr++;
        }
    }
    uint8_t *bytePtr, *bitBuf, bitMask;
};

Refactor not to use large ISRs. ISRs should be short and quick. "Big ISR" is a fundmental flaw. You want ISRs to take as few cycles as possible (To the point of not using higher-level Arduino functions like digitalRead(). An ISR should be in-and-out in as few instruction cycles as possible.

I have had to do this many times with customers' "code". Step one is to rescue what functionality you can into libraries. Step two is to write a new program using those libraries.

@Majenko you do Arduino development for pay?

I do, though I prefer not to. I usually work with more powerful systems than Arduino.

Set a flag in the interrupt. And make your loop check for this flag to handle the situation. And make sure this loop is as fast as possible by eleminating sleep/delays. This can be done using a state machine.

Looking 4 more constructive answers. Btw things around ISR or security would be nice to have well timed in assembler, but it is not so easy as in Atmel Studio - is it ?

Where is the code to review?

No-one would understand and it is property of inventor I did some maintenance for. Question is are there any "light" design patterns or templates to start with ? Probably only public part is GFX fonts compression (to 1/2 in average), it is on my Github, but probably no need to improve or refactor...

You didn't write anything about security in the question. What do you mean by that. Also: Are you sure the code let's ISRs being interrupted? That would make the program way more difficult to refactor and might be the cause of disfunction. But without posting the code you will only get very vague answers, mostly consisting of "refactor the code to use shorter ISRs"

It is a measuring and regulation project, working even with gas, so security is very important. I think there is some enable interrupt somewhere inside ISR and it does unpredictable things sometimes - printing in random colors / position, etc. And these are very hard or impossible to reproduce out of real environment. Isn't there ready-made "template" or design pattern for something similar to real time OS ;-) ?

I will try to answer your question as good as possible, though it is quite broad.
To my knowing there is no ONE design pattern or template, that fit's all cases. But depending on the actual functions of your code you can go different ways using libraries (which are somewhat like templates in this sense).
You can get easy multitasking by using libraries like FreeRTOS. You might even find a compatible version of SafeRTOS, a sibling of FreeRTOS, which has a bigger focus on security. Though the whole RTOS thing might not be right for you and it needs your code to be mostly rewritten/redesigned.
Depending on what ISRs are used and what they are for, you might really need to use interrupts to let the device react immediately. In that case you basically have not choice, but to refactor the whole code as described in the comments (moving as much code as possible to the main loop, making the ISR drastically smaller). For this here some general advice:

First make a graph of the devices function as it should be. Identify code portions that have a common function, but them into blocks, draw arrows between the blocks to show, how they are connected logically. Then identify which portions are really time critical and what the time contrains are (e.g. Do you need the device to react to an event within a few clock cycles or is it ok, if the reaction comes a few us or ms later?). Mark how often the involved events occur at average and at maximum.
Now look at the code blocks directly. Which of them need interrupts to work and what happens with them, if interrupts are turned of during their operation (since - as you already identified - reactivating interrupts inside an ISR can get very messy). For example with interrupts off, Serial prints will not be send directly (because this relies on interrupts). Instead the libraries buffer will be filled. When the buffer is already full, a print will wait for the buffer to empty a big (which does not happen with interrupts off).
Move all code, that is not really time critical, into an if statement in the main loop function. The if statement should be activated by a flag, that would be set in the ISR (be sure to declare it volatile).
Make sure, that there is nothing blocking in your code (no delay(), no waiting for an event in an infinite loop). That also might require serious refactoring, but it's important if you want a fast reaction also outside of the ISR. You might want to look into Finite State Machines for this (they are quite easy to implement and a very powerful construct).
Keep debug prints small, so that it cannot mess up your timing.
Lastly: Make some documentation. That is mostly reglected, because it is not that rewarding, but it can save many hours for the next programmer, that needs to maintain your code.

That might seem very time consuming, difficult and not like the comprehensive guide you were looking for. That's the reason, why maintaining legacy code is mostly a real pain in the a*** and does cost companies a lot of money.
At one point or another the technical debt has to be paid. The inventor of the code clearly didn't (or he/she would't have written an ISR this big), so now you will most likely have to go the hard way.

Problem is also it has 32kB flash, RTOS would probably not work on or is there some tiny version ;-) ?

The linked site shows this: // Device:   loop() -> FreeRTOS | Additional Program Storage // Uno:         444 ->   7018   |     20%, and the Uno has only 32kB flash. Surely it is questionable, if the rest of your code is fitting on top, but that cannot be said without the actual code.

Sure not - not so long code, but there are 24px GFX & compressed fonts yet, so almost whole is full, suppose fonts consume 1/2 - 3/4 of memory. Uncompressed fonts would fill whole mem, compression makes them 1/2, so 16kB without requested GUI ?

2 compressed GFX fonts used are also in my .Net simulator here https://github.com/eltomjan/ETEhomeTools/blob/master/ArduinoSimulator/Font_big.h and https://github.com/eltomjan/ETEhomeTools/blob/master/ArduinoSimulator/Font_medium.h

So then you are stuck with refactor the ISR to get it smaller


text:
TouchScreen GUI Reference Guide Help
Recently I have gotten some Touchscreens to add to my projects and I am very excited to use them. However, I am not sure where I can find a guide to help me create my own GUI with the touchscreens. The touchscreen I am using right now is the HiLetgo 2.4 inch TFT LCD Display Shield with a ILI9341 Driver. I have experience programming GUI's in Python and I feel fairly confident in myself that I can create the GUI's that I want if I had a resource to learn from. Please Let me know if you'd like anymore information. Thank you!

In general there's very little "GUI" programming functionality in TFT libraries. You have low-level operations mostly - things like line drawing. Making a GUI is a lot of programming.

Of course, it depends what library you are using as to what functionality you have...

Thanks for the quick response! I am nit trying to make a super complex GUI but just one that's my own. I am using the Adafruit_GFX_Library. Are there better libraries out there or is the Adafruit library okay?

You get buttons and canvases as the only "objects" you can work with. Very basic. Anything more than that you have to draw yourself.


text:
EEPROM Esp8266 Memory Issue
I had assembled a board with esp8266ex bare chip with 4MB eeprom for esp and also can be shared with host MCU. I had gone through some googling and found that using eeprom function I am able to write data in eeprom using esp8266ex. But I had seen the limitation of 4KB. Then I had researched more than I found that there is a way to increase that.
So my question is, Is there are any issue if I changed that 4KB to 2 MB or more in esp8266 library?
I am using arduino IDE for Esp programming.

eeprom or flash? only 4kB can be used for EEPROM emulation in esp8266 flash memory layout

flash. I am asking if what will happen if I increase the 4KB to 2MB.

use SPIFFS file system. it can use to 3MB of 4MB. https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html

I tried the spiffs, every time it shows unable to find file, but the file path is right and even the file name.

try more. try the examples. it works.

ok I will check tomorrow for another example for spiffs.

the basic example is called ConfigFile and FSBrowser is a complex example

Actually I tried the basic example in which it will go to the directory, open the file and try to print the file data on serial monitor. But I always for the result as Unable to open the file.

yes. the example is wrong. it expects the SPIFFS initialized. read the doc on the link few comments above


text:
16/2 arduino I2C lcd display not lighting up?
I am working with an I2C lcd display with an arduino uno board I have connected the gnd pin to gnd of arduino uno and the vcc pin to 5V of arduino uno and the display is not even lighting up there is only a red led lighting up on the back so I tryed connecting the rest of the pins and run a code to detect the i2c display and it worked successfully I got the adress but the lcd did not light up. The lcd display is a new one I bought yesterday here are the pictures:
https://photos.app.goo.gl/x9QPAWig98yLg4DW9
The script I tryed to display text was this one with the NewLiquidCristal library:
//Libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the
LCD I2C address, if it's not working try 0x27.

void setup(){
lcd.begin(16,2);   // iInit the LCD for 16 chars 2 lines
lcd.backlight();   // Turn on the backligt (try lcd.noBaklight() to turn it
off)
lcd.setCursor(0,0); //First line
lcd.print("I2C LCD Tutorial");
lcd.setCursor(0,1); //Second line
lcd.print("*Ardumotive.com*");
}

Here is the model nmber of the I2C: PCF8574A And the lcd is a QAPASS Ui also I don't have a spec sheet and the LCD seems to show empty chars when rotating the pot.

There are tons of different variations of LCD modules. It does look like it's an LCD with an I2C "backpack" on it. Post the model number, a link to the spec sheet if you have it, as well as a link to the specific library you're using and the code you are using to initialize it and send data to it.

From the pictures it looks like the I2C "backpack" has both a backlight adjustment pot (potentiometer) and a jumper on it. Sometimes removing/moving the jumper lets you turn the backlight off, but it appears to have the jumper installed. If it came with instructions or a link to the data sheet, see what it says about the adjustment pot. You might try turning the adjustment pot and see if that causes the backlight to turn on.

did you add lcd.begin(); and lcd.backlight(); to void setup?

I have added all the missing information sorry if late

you have an I2C LCD right? use this: LiquidCrystal_I2C lcd(0x27, 16, 2); instead of LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); .

my adress is actually 0x3F

take a look at the answer.

Try this:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// LiquidCrystal_I2C lcd(0x27, 16, 2);
// OR
LiquidCrystal_I2C lcd(0x3F, 16, 2);

void setup(){
lcd.begin();
lcd.backlight();
lcd.setCursor(5,0);
lcd.print("TA DAA...!");
}
void loop{
// do nothing here
}

If that didn't work probably your LCD have a different address than 0x27 which in that case you should run a I2C scanner to show you the addresses of I2Cs that connected to your Arduino:
#include <Wire.h>
// I2C scanner

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  Serial.println("\nI2C Scanner");
}

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

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

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

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

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

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

Check the jumper behind the I2C module (plug it out and in again).
Check the voltage of LED using a multimeter if there's no voltage there, maybe it's just a "bad LCD" try replacing it.

Thanks this worked for me!!


text:
Float to String Convert in Udp.write() in esp8266
I want to convert float value to String for send Udp.Write()
 method
 and receive another side (esp) with Udp.read()
and
Copy in the one Variable for use ..
please help me
Thanks for every answer ^__^
code :
void loop () {
    int signal = analogRead (A0) ;
    float Adc = (signal * 3.3) / 4096 ;
    Udp.beginPacket ({192,168,4,1} , 1234) ;
    Udp.write ( " please help me fill this section ") ;
    Udp.endPacket () ;
}

i have one more problom . . .
and in the other side:
i want take theAdc value from esp1 and convert char to float for Dac
(digital analog converter) with MCP4725 ..
** i just need put in float value of Adc in a variable for convertation use ..**
code:
void loop ( ) {
int noBytes = Udp.parsePacket();

String received_command = "";

if ( noBytes ) {

  Udp.read(packetBuffer,noBytes);

  for (int i=1;i<=noBytes;i++){

  received_command += char(packetBuffer[i - 1]);
}

Serial.print("packaet receive: ");

Serial.println(received_command);

float Adc_value_received = float(received_command); //*helpppp please char-to-float convert*

}
thanks from everyone ^__^

Have you considered reading the documentation for String?  https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/

Or even googling it? Normally you find various examples when googling for "Arduino convert X to Y"

Try something like: String msg = String(Adc, 3); Udp.write(msg.c_str());

Special thanks to Mikael Patel .^___^

The Arduino String class can be used to convert to a character string.
void loop () {
    int signal = analogRead (A0) ;
    float Adc = (signal * 3.3) / 4096 ;
    String msg = String(Adc, 3);

    Udp.beginPacket ({192,168,4,1}, 1234) ;
    Udp.write(msg.c_str());
    Udp.endPacket () ;
}


text:
Writing to sd card with a sampling rate 50ms or less? I have a sketch that writes to sd every 1s but jams at faster sampling rates. Please help?
My code below reads data from an ADC and 3 digital pins via a Mega and prints to an SD Shield (Deek Robot). I want to be able to read the data every 50ms (20ms ideally). I can't get below 250ms.
I've read countless forum posts regarding the same issue and understand that I need to create 2x 512 byte buffer, store data to one while the other is being written to the SD card. A forum post mentioned using the Adafruit GPS library for an example of double-buffering but I can't seem to find it. Another suggests changing the internal buffer from 64bytes to 256bytes in hardwareserial.cpp but I can't even navigate to it on my w***ows laptop.
I've run dataString.Length and the max length is 38 for the 8 columns of data, plus a long (for recording ms) another byte for the "\t" and 3 bytes of headroom = 46bytes in all, round it up to 50bytes/sample at a 50ms sampling rate is 1000bytes/second. Darn it, I forgot to add the separating-commas between the columns = plus another 7 bytes; call it 55 in total = 1100bytes/second. I know it can be done but I can't do it; not at my current knowledge/skill level.
Thank you in advance for your help.

//include relevant libraries
#include <EnableInterrupt.h>
#include <SPI.h>
#include <SD.h>

//globally define pins
#define BUSY 3    //purple*
#define RD 4      //yellow* RD+CS tied together
#define RESET 5   //grey*
#define CONVST 6  //green* CONVSTA+CONVSTB soldered together on the board
#define RANGE 7   //blue*   *not permanent - double check!!!*

#define DB0 22
#define DB1 23
#define DB2 24
#define DB3 25
#define DB4 26
#define DB5 27
#define DB6 28
#define DB7 29
#define DB8 30
#define DB9 31
#define DB10 32
#define DB11 33
#define DB12 34
#define DB13 35
#define DB14 36
#define DB15 37

//byte statusLed       = 13;
byte sensorPin1       = 38;
byte sensorPin2       = 40;
byte sensorPin3       = 42;

int sensorValue[8];
int rawData[16];
//change the size  of these arrays to match the amount of channels being read by the ADC
int adcChannel[5];
int adcData[5];
int channelCount=5;

volatile byte pulseCount1;
volatile byte pulseCount2;
volatile byte pulseCount3;

int pulses[3];

// cs pin for sd-shield *NB 53 for Mega
const int chipSelect = 53;
// SCK 52
// MISO 50
// MOSI 11

unsigned long oldTime;

void setup() {             //set up the hardware

  Serial.begin(9600);
  //sd card.....
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

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

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

  enableInterrupt(BUSY, bitBang, FALLING);

  oldTime            = 0;

  pinMode(DB0, INPUT_PULLUP);
  pinMode(DB1, INPUT_PULLUP);
  pinMode(DB2, INPUT_PULLUP);
  pinMode(DB3, INPUT_PULLUP);
  pinMode(DB4, INPUT_PULLUP);
  pinMode(DB5, INPUT_PULLUP);
  pinMode(DB6, INPUT_PULLUP);
  pinMode(DB7, INPUT_PULLUP);
  pinMode(DB8, INPUT_PULLUP);
  pinMode(DB9, INPUT_PULLUP);
  pinMode(DB10, INPUT_PULLUP);
  pinMode(DB11, INPUT_PULLUP);
  pinMode(DB12, INPUT_PULLUP);
  pinMode(DB13, INPUT_PULLUP);
  pinMode(DB14, INPUT_PULLUP);
  pinMode(DB15, INPUT_PULLUP);

  pinMode(RESET, OUTPUT);
  pinMode(CONVST, OUTPUT);
  pinMode(RD, OUTPUT);
  pinMode(RANGE, OUTPUT);
  pinMode(BUSY, INPUT);

  //reset ADC to begin conversion
  digitalWrite(RESET, HIGH);
  delayMicroseconds(10);
  digitalWrite(RESET, LOW);

  digitalWrite(CONVST, LOW);
  digitalWrite(RD, HIGH);
  digitalWrite(RANGE, LOW);
  digitalWrite(BUSY, LOW);

  delayMicroseconds(100);

  // Set up the status LED line as an output
//  pinMode(statusLed, OUTPUT);
//  digitalWrite(statusLed, HIGH);  // We have an active-low LED attached

  pinMode(sensorPin1, INPUT);
  digitalWrite(sensorPin1, HIGH);

  pinMode(sensorPin2, INPUT_PULLUP);
  digitalWrite(sensorPin2, HIGH);

  pinMode(sensorPin3, INPUT_PULLUP);
  digitalWrite(sensorPin3, HIGH);

  pulseCount1        = 0;
  pulseCount2        = 0;
  pulseCount3        = 0;

  oldTime            = 0;

  // the hall effect sensors are configured to trigger on a FALLING state change
  // (transition from HIGH state to LOW state)
  enableInterrupt(sensorPin1, pulseCounter1, FALLING);
  enableInterrupt(sensorPin2, pulseCounter2, FALLING);
  enableInterrupt(sensorPin3, pulseCounter3, FALLING);

}

void loop() {

  //change this value to preffered sampling rate
  if ((millis() - oldTime) == 50) {

    oldTime = millis();

    //Serial.print(millis());
    //Serial.print("\t");

    //tell ADC to start read (converting analogue input to digital output)
    delayMicroseconds(10);
    digitalWrite(CONVST, LOW);
    delayMicroseconds(10);
    digitalWrite(CONVST, HIGH);
    //when read-conversion is complete ADC sends the BUSY pin low triggering the bitBang ISR

    //print ADC data from array within the bitBang ISR to a string
    String adcString = "";
    for(int thisChannel=0; thisChannel<channelCount; thisChannel++){
      adcString += String(adcData[thisChannel]);
      adcString += ",";
    }

    //disable interrupt to access current pulse count
    disableInterrupt(sensorPin1);
    disableInterrupt(sensorPin2);
    disableInterrupt(sensorPin3);
    //grab current pulse count and store in a variable
    pulses[0] = pulseCount1;
    pulses[1] = pulseCount2;
    pulses[2] = pulseCount3;
    //reset pulse count
    pulseCount1 = 0;
    pulseCount2 = 0;
    pulseCount3 = 0;
    //enable interrupt and start incrementing pulse count again
    enableInterrupt(sensorPin1, pulseCounter1, FALLING);
    enableInterrupt(sensorPin2, pulseCounter2, FALLING);
    enableInterrupt(sensorPin3, pulseCounter3, FALLING);

    String pulseString = "";
    for(int i=0; i<3; i++){
      pulseString += String(pulses[i]);
      if (i<2) {
        pulseString += ",";
      }
    }

   String dataString = String(adcString + pulseString);
  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("dataLog.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.print(millis());
    dataFile.print(",");
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    //Serial.println(dataString);
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening dataLog.txt");
  }

 //Serial.println(dataString);

  }
//start again
}

//grabbing ADC data ISR (for n channel)
void bitBang ()  {
  //a for loop to bitbang the values fom the analogue (ADC) channels (maximum 8) sequentially storing them in a variable array (equal to the channels of the ADC)
  for(int thisChannel=0; thisChannel<channelCount; thisChannel++){
  //send ADC read pin low to bitbang the first channel
  digitalWrite(RD, LOW);
  //read the state of the 16 pins and store in a variable
  rawData[0] = digitalRead(DB15);
  rawData[1] = digitalRead(DB14);
  rawData[2] = digitalRead(DB13);
  rawData[3] = digitalRead(DB12);
  rawData[4] = digitalRead(DB11);
  rawData[5] = digitalRead(DB10);
  rawData[6] = digitalRead(DB9);
  rawData[7] = digitalRead(DB8);
  rawData[8] = digitalRead(DB7);
  rawData[9] = digitalRead(DB6);
  rawData[10] = digitalRead(DB5);
  rawData[11] = digitalRead(DB4);
  rawData[12] = digitalRead(DB3);
  rawData[13] = digitalRead(DB2);
  rawData[14] = digitalRead(DB1);
  rawData[15] = digitalRead(DB0);
  //convert into 16bit 2s compliment and store in a variable array
  adcData[thisChannel] = rawData[0] | (rawData[1] << 1) | (rawData[2] << 2) | (rawData[3] << 3) | (rawData[4] << 4) | (rawData[5] << 5) | (rawData[6] << 6) | (rawData[7] << 7) |  (rawData[8] << 8) | (rawData[9] << 9) | (rawData[10] << 10) | (rawData[11] << 11) | (rawData[12] << 12) | (rawData[13] << 13) | (rawData[14] << 14) | (rawData[15] << 15);
  //send ADC pin high to say we have read the first channel
  digitalWrite(RD, HIGH);
  //repeat for n channels
  }
}

//counting pulses ISRs
void pulseCounter1(){
  // Increment the pulse counter
  pulseCount1++;
}
void pulseCounter2(){
  // Increment the pulse counter
  pulseCount2++;
}
void pulseCounter3(){
  // Increment the pulse counter
  pulseCount3++;
}

if ((millis() - oldTime) == 50) { .... what happens if the program briefly hangs up and misses the 50ms difference?

Did you think about jsotola's comment? If not, I suggest you think about it very very carefully. The advice in the answer below is good advice, but it might just be the comment  that saves you - and exposes a new problem when you realise the answer....

I'm running tests on it now. Do you know what? As little as 10 days ago that part of code said if ((millis() - oldTime >= 50) { and it has said that for months. I don't know when or how the double equal crept in. I'll let you know the outcome soon. Thanks

Yeah, that seems to have fixed the issue. Absolutely kicking myself for somehow  adding in the bug without realising it, oh well, humanum est errare as the old saying goes. Thank you for everyone for your help, especially to the person that voted my question up thus awarding me enough reputation to comment everywhere - a very special day for me. What is the etiquette here? I can't accept a comment as an answer so should I accept the @Michel Keijzer one? thanks again

So it turns out the actual problem was this line of code
if ((millis() - oldTime) == 50) {
it needed to be changed to
if ((millis() - oldTime >= 50) {
I really appreciate all the help everyone gave me to get to the bottom of it and especially thankful to @Michel for handing some solid advice to someone who isn't in the know.
Hopefully I will be able to repay in kind to another learner one day.
:D

Some tips:

Do not open the open and close the file in every loop sequence (I think you can use the flush command to save/update the file.
Do not save strings, but save the raw data and pulse string. This will take 16 * 2 (raw data + 3 bytes for the pulse data = 35 bytes per 16 samples, meaning 35 bytes/samples * 20 samples/s = 700 bytes (I think your calculation of 1100 bytes is incorrect).
Try to avoid string, and even more string concatenation. I don't know if this will be the bottleneck, but in any case String operations are expensive and for concatenation there is a chance (or is always the case) that memory needs to be allocated dynamically. Use a string buffer instead.

Thanks for your suggestions. I have read about strings being problematic, and the C string class should be used instead. I will implement the first 2 bulletpoints today but will have to do a bit of research before taking on the third. i will kyp.

File I/O operations are normally quite expensive, so it's good to keep them to a minimum. The third point might be a bit more work, but except for very simple sketches, try using C string (char* instead). Tip: to test with the C strings, do not use an Arduino, but do it on a PC, that's much more quicker, than if the code works or you know how c strings work, move it to the Arduino IDE.

OK, so I use command prompt on my laptop?

No, I suggest you install either Visual Studio 2019 or Eclipse C(++) ... both are free. You create your non Arduino specific code on the PC with either those two IDEs, and when it works you copy it to the Arduino IDE. The advantage is that you can use debugging and you don't have to upload the program/sketch every time.

That's great advice, I'm definitely gonna take it :) Thanks again.

@Microk It's especially useful if you make large programs.

UPDATE: I have got rid of all the strings completely. I can't seem to initiate the flush without the sd card crashing after a short while, 0-2 mins. But I have stable code that does exactly what I wanted to. So thanks again for all the help

You're welcome ... and if the program works stable, don't change it (you always can add a remark/todo  for the flush in case you run in problems next time).


text:
Software I2C - sending data
I'm trying to read a voltage in from a power supply to an Arduino Micro, then send it to an oscilloscope through an I2C (MCP4725). I would use the default pins on the Micro but I want to wire three I2C and the default bus only allows two. As such, I'm trying to use the SoftI2CMaster library
I've looked through examples and documentation but I can't seem to get it to send any data. I've been successful scanning (from examples) and finding the I2C addresses, so I assume that the trouble is at the end of my code.
Any tips would be greatly appreciated!
#define SDA_PORT PORTD
#define SDA_PIN 4 // = A4
#define SCL_PORT PORTC
#define SCL_PIN 6 // = A5
#include <SoftWire.h>

#define I2C_7BITADDR 0x62 //MCP4725

SoftWire Wire = SoftWire();

int aPin;

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

void loop(void){
  aPin = analogRead(A0); //read in from power supply
  Wire.beginTransmission(I2C_7BITADDR);
  Wire.write(aPin); //send voltage to osc.
  Wire.endTransmission();
}

The main problem seems to be, that you are not adhering to the MCP's communication protocol. You just try to directly and only send the pure analog measurement to it.
Look at this image from page 18 of the MCP4725's datasheet:

It describes the operation is Fast Mode, which seems to be the correct mode for this. (Similar descriptions for the other modes can be found below that image). The first byte is done by the SoftWire library, but the following is your responsibility. The
next 2 bytes consist (in this order) of 2 bit's setting the Fast Mode, 2 bit's for the devices power down select (both zero for normal DAC operation) and then the 12 bits of the actual voltage value for the DAC.
At this point I will show another problem with your code. You read an analog voltage with the Arduinos ADC, which is a 10 bit number (of type int) and use it in
Wire.write(aPin);

But the parameter for Wire.write() is defined as uint8_t (see line92 in SoftWire.h of the Softwire library), which means, that your int value get's casted and you loose all bits above 255 (the lower byte), because uint8_t just cannot store more.
What you have to do: You should put the I2C data bytes together in your code and then send them. This may look like this:
byte byte1 = (aPin & 0x0F00) >> 8;
byte byte2 = (aPin & 0xFF);

This code uses bitwise operators. The & will do an AND operation, the >> shifts the bits to the right by the amount after the operator. The 0x denotes a value in hex representation (binary representation would be 0b). So for the first byte we are doing an AND with the value 0x0F00, which will give us a value with only the first 4 bits of the second byte of aPin. Then we shift the result 8 bits to the right, so that the remaining data is nicely aligned to the right of your byte. We don't need to include the mode bits and power down select bits here, since they are zero anyway. If you want to set them non-zero you could bitwise OR them (of course with the correct shift, so that the bits have the correct position in the resulting byte):
byte mode_bits = 0b10;
byte power_down_bits = 0b11;
byte byte1 = (mode_bits << 6) | (power_down_bits << 4) | (aPin & 0x0F00) >> 8;

Then you can send these bytes out with I2C:
Wire.beginTransmission(I2C_7BITADDR);
Wire.write(byte1);
Wire.write(byte2);
Wire.endTransmission();

That should work, though note, that I have not tested this. I just read the datasheet, which is always a must read.
What happened with your original code: The datasheet states for the command "Write DAC Register" (which uses 4 bytes including the address byte) the following:

The device ignores any partially received data  bytes  if  the  I2C
  communication with the Master ends before completing the 4th byte.

So it just drops any I2C messages, that are not complete. Though it is not stated clearly, we can be pretty sure, that the same happens also for the other operation modes. You were sending only 1 byte, so the MCP found the message incomplete and ignored it.

That said, there is a principle to work around the limit of only 2 devices on the same bus, which I also only learned recently about. You might not wanna go this way here, but it's a great idea and a valid solution to the problem with the limit.
Every MCP has 1 address pin A0, which set's 1 bit of the address, resulting in 2 possible addresses. On an I2C bus there must not be more than 1 device with the same address. But if that doubled address is never called, the bus doesn't have a problem.
You would connect the A0 pins of each MCP to one digital output pin of the Arduino each. By setting the state of these output pins you can change the address of the MCPs (requirement is, that the MCP actually checks the A0 pin during operation, but the datasheet seems to suggest this). Now you keep every A0 pin on one level, so that all MCPs have the same address. To communicate with one, you would change the state of it's A0 pin to change it's address. Now this MCP is the only MCP with this address (all other MCPs have the other address). You can now communicate with it. When you want to communicate with another MCP, you reset the first MCPs A0 pin and then change the next MCPs A0 pin.
That way you make sure, that on one of the two addresses, there will always be 1 MCP at maximum, while you never use the other address. You can use as many MCPs, as you have digital output pins to change their addresses.

yes! you legend! worked perfectly. thank you so much for the well written response. i really appreciated the breakdown of why my code wouldn't work.


text:
How can I use a transistor to "press" a button?
I have a heater remote that I want to press the buttons of with my Arduino. I am powering both the remote and Arduino from an external 5V source so both grounds are connected.
Currently I have tried using an NPN transistor(TIP122) and it does work but is not very reliable. It probably works 80% of the time but isn't good enough for my purpose. Sometimes nothing happens and sometimes the button is pressed twice for no reason.
These are my connections.
I have the emitter connected to ground, collector connected to the button and the base connected to the Arduino with a 1k resistor. Are my connections OK?
I've also tried using a PNP transistor but pulling LOW instead of HIGH and LOW instead of HIGH.
The code is very simple, in the setup I have:
pinMode(4, OUTPUT);
digitalWrite(4, HIGH);
delay(20);
digitalWrite(4, LOW);

Therefore when I restart the Arduino it should press the button, right?
I also have IRLZ44N and IRF540N, would either of these work better?

you have to press the button longer than 1/50th of a second

I have tried altering this. I've tried everything from 20-1000ms and they have all given similar results.

Are you sure, that the button simply pulls a pin to low? That might not be the case. I have solved a similar problem once by using a NPN transistor to bridge the button, instead of pulling it low. That seem to work pretty well, though I haven't tested it thoroughly.

When I tap the ground of the remote on a pin of the button, it "presses it". While I was testing and just doing this with a jumper wire, it seemed to work almost every time.

why do you use a transistor to pull other 5 V logic pin LOW?

When given an unknown circuit to control the buttons of I find it's usually better to go for full isolation and use an optocoupler.

However certainly an N-channel FET is far better than an NPN transistor - you don't get the voltage drop from a FET that you get with a BJT.

How would I wire a MOSFET to the button. Do I connect the gate to the Arduino with a resistor, source to ground and drain to the button?

Sounds right to me, yes.

A PNP transistor has fairly high "on" resistance. It might be too much. You should try using a variable resistor and see what level of resistance triggers the switch reliably, and then try a timing circuit to see how long you have to hold that resistance before it registers. (Start at 1 second and work backwards.) A MOSFET has much lower on resistance, and you can get them that can be fully switched on from a 5V logic signal.

You've already opened the remote, so you need to check whether the button connects the remote controller chip's input pin to GND or to its own VCC or maybe something else. Should not take long with a multimeter in "beep" mode. If there are lots of buttons they could be multiplexed, so check that. A picture of the remote pcb would help. Also you need to check what the VCC is on that chip, it probably isn't running on 5V so might want to be careful to not output some 5V from the arduino in there.

A glance at the TIP22 datasheet shows that this is a Darlington pair transistor, which means that it has very high DC gain (good), but at the cost of a very high Vbe_ON (bad).  The datasheet shows that the Vbe_ON is 2.5V, which means that the voltage across the 1K is only 2.5V max, which limits the base current to around 2mA.  This is probably not enough for good saturation.  In addition, the Vce_SAT for this device is about 2.0V, which may or may not be enough to look like a good GND to the button circuit.
I think a MOSFET like the IRF540N, connected as shown here (substitute button circuit for motor) might be a better choice
YMMV

You really only need one wire and no resistors or mosfet.
I see many answers including expensive mosfets and relays to answer this question. There is a much simpler solution requiring no glue logic or interfacing circuitry. I recently had to install an off-the-shelf ultrasonic humidifier in an incubator/brooder. It is the cheap little home-use aromatherapy type diffuser. It had to be controlled by a relay to turn on and off. The catch is that the control circuit and firmware used in nearly all of these is the same, it can be turned on by a relay in the PID incubator controller but requires a single button press once power is supplied to start the ultrasonic humidifier and fan. three button presses turns the humidifier off and returns it to standby and turns off automatically when it runs out of water. using the arduino to control only the button to bring it out of standby would not lead to reliable operation. I searched for an answer but found none that I could make given I had few parts and was working on a remote farm. This is my solution.
The science behind this and how it works is that the microcontroller does not sense the press of a button, it detects a state change. You may familiarize yourself with this in the arduino tutorials for reading a button press.
Tie the arduino ground to ground in the circuit you want to control. find a 5v rail and power the arduino. no extra power required. There is usually a test pad that will be ground and 5v close to the button you want to control. if not, find the regulator for the microcontroller that you are trying to trigger by tracing the circuit and attach the power rails. I used Digital Pin 2 for the trigger signal. connect d2 to a point near the switch. Ensure there is a resistor of about 600-1000ohm in the circuit between the point and the microcontroller. This should be present on the circuit you are triggering already simply because this is how microcontrollers detect state changes without sinking or sourcing infinite current.
This code will trigger once and then go to sleep. The long delays are to allow for expected debounce code in the microcontroller and allow for boot time. put simply, it switches PD2 between high and low states in high impedance and low impedance states and basically all a switch does is switch between high impedance and low impedance states. This code should trigger pretty much any microcontroller regardless of the specific state required once and then go to sleep.
#include <avr/sleep.h>
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  pinMode(PD2, INPUT_PULLUP);
  digitalWrite(PD2, HIGH);
  delay(2000);
  pinMode(PD2, OUTPUT);
  digitalWrite(PD2, HIGH);
  digitalWrite(13, HIGH);
  delay(300);
  digitalWrite(13, LOW);
  pinMode(PD2, INPUT_PULLUP);
  digitalWrite(PD2, HIGH);
  delay(300);
  pinMode(PD2, OUTPUT);
  digitalWrite(PD2, LOW);
  digitalWrite(13, HIGH);
  delay(300);
  digitalWrite(13, LOW);
  pinMode(PD2, INPUT_PULLUP);
  digitalWrite(PD2, LOW);
  delay(500);
  sleep_enable();
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_cpu();
}


text:
Servo PWM Pin seems to be interfering with Wire.onRequest i2C function
A newbie here. I am thinking of interfacing Raspberry Pi with Arduino via I2c to control a few servo motor (as RPi have limited PWM pins). Meaning I would send input from RPi to Arduino to allow to the Arduino to control the servo.
The problem is this: When I was testing the I2C communication alone, it worked fine. The RPI can send a char, and the Arduino Uno can receive and recognize it.
However, when I added in the function to get the Arduino to send PWM signals to the servo, then the program becomes wonky (e.g. when I send over "0x1", the Arduino led should light up, when I send "0x2", the led should turn off. However, once I tried to PWM the servo, it flickers a while and does no light up when I send the signals, and the servo just vibrate a bit, instead of turning to intended position).
And the funny thing is, the code runs (meaning the LED turns on/off accordingly) as long as I do not plug in the servo's signal pin to the Arduino.
What am I missing? Why does the PWM seems to interfere with the I2C, and is there a way to get around this?
My code is below, do pardon me if anything is unclear, I will be more than happy to clarify.
Thanks guys!

#include <Wire.h>
#include <Servo.h>

Servo myservo_1; // create servo object to control lift servo
Servo myservo_2; // create servo object to control entry servo
Servo myservo_3; // create servo object to control exit servo
// twelve servo objects can be created on most boards

int statusLED = 0;
int statusServo = 0;
int pos;

const int ledPin = 13; // onboard LED
const int servo_1 = 3;
const int servo_2 = 5;
const int servo_3 = 9;

static_assert(LOW == 0, "Expecting LOW to be 0");

void setup() {
  Wire.begin(0x8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent);   // register event
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);     // turn LED off

  myservo_1.attach(servo_1);  // attaches the servo on pin 3 to the servo object
  myservo_2.attach(servo_2);  // attaches the servo on pin 5 to the servo object
  myservo_3.attach(servo_3);  // attaches the servo on pin 9 to the servo object

  //Serial.begin(9600);
}

void loop() {

  if (statusServo == 1){
    myservo_1.write(90);
    delay(15);
  }

  else if (statusServo == 2){
    myservo_1.write(0);
    delay(15);
  }

  else {
    myservo_1.write(45);
    delay(15);
  }

}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {

  int c;

  while (Wire.available()) { // loop through all but the last
    c = Wire.read(); // receive byte as a character
  }

  //Serial.println(c);

    if (c == 0x1){
          digitalWrite(ledPin, HIGH); // turn it on
          statusServo = 1;

    }

    else if (c == 0x2){
          digitalWrite(ledPin, LOW); // turn it on
          statusServo = 2;
    }

}

current draw? underpowered?

Make sure, that the servo gets enough power. Also don't power it through the arduino. Instead connect the power source directly to the servo

Hi. I am powering the servo using 4x AA Battery (6V), so it doubt its a power issue. Also, according to my code, the interrupt function should turn the LED on/off cleanly, depending on the byte sent. However, the LED flickers instead when I send a single byte, so I am quite perplexed.

I see you have a Serial print inside the ISR, thats currently commented out. Have you confirmed, that you are receiving the correct data? The symptoms really look like a power issue. Servos can draw much power. Is the Arduino powered from another source (for example USB)? If it's also connected to the same battery pack: how is it connected? Vin normally needs a nit more than 6V max to correctly output 5V


text:
Rate of serial communication (UART) of a sensor is faster than speed of processing of microcontroller
I have a Vector Nav VN100 IMU sensor that sends data serially UART. I have interfaced it with ATmega32. It receives data (ROLL angel) from the sensor and according to the ROLL angel, it controls a servo motor.
My question, if the sending rate is faster than processing speed of the ATmega32, then  some data from the sensor will be dropped. How to overcome this problem?

If the data is coming faster, that it can be processed and you cannot change the rate, you have to drop data or use a faster board

@chrisl Is not there any other way such as using  buffer instead of dropping data?

Even if you use a buffer. When it is full you need to drop data. What are your exact requirements? Reading data contineously? Or just for a limited time period?

@chrisl just for a limited time

What is your incoming data rate? That is what baud rate will you be using? How frequently will the "roll angle" be sent? And how big is each message (in bytes)?

@GMc Baudrate is 921600

There were three questions there... how frequently will messages be sent? And how long is each message in bytes? If the baud rate is 921600 but you only receive 1 message per second that is just 2 bytes long and you are using a UART (for example) then probably the answer is "you will be ok". On the other hand if there is a continuous sustained stream of data at that baud rate with no pause in between messages then probably the answer is "you have no chance". There are multiple factors that determine the answer to your question.

When using an embedded processor's hardware implemented UART, it is often the case that the rate at which the software processes the data is a fraction of the Gross bit rate some times referred to as the Baud rate.  If the UART is configured to handle 8 bit RS-232 where the Gross bit rate is 10000 bits per second, the processor only has to handle data at a faction of that rate.  Perhaps 1/10 given several bits of over head and space between characters.
Processor intervention can be further reduced if the hardware UART contains several bytes of buffering.  For every doubling of the number of hardware supported bytes of buffering, processor interventions events are cut in half.
Beyond this, there are embedded processors in which the UART supports DMA or Direct Memory Accessing.  This is where the hardware UART will write the received data directly into the processor's memory with out need of processor intervention.  This feature is usually only found on feature rich embedded processors.
Study this PDF to understand the abilities and limitations of the ATmega32 processor.  Specifically the USART section starting on page 140.


text:
Trouble with setting the PWM frequency for Arduino Due
I'm using Arduino Due and I set the analog read and write resolution to 12-bit for better resolution. Basically all I do is to vary PWM duty cycle by controlling analog DC input voltage from 0 to 3.3V. The simple code as it is now works fine as follows:

int pwmPin9 = 9;
int analogPin0 = 0;
int val = 0;

void setup() {

  Serial.begin(9600);

  pinMode(pwmPin9, OUTPUT);  // sets the pin as output
  analogWriteResolution(12);
  analogReadResolution(12);

}

void loop() {

  val = analogRead(analogPin0);  // read the input pin
  Serial.println(val);
  analogWrite(pwmPin9, val);

}

My problem is I need to set the frequency of the PWM output to 25kHz or at least something nearest above 25kHz.
I have been searching forums hours and couldn't find any solution. Here I came across a way but there is no library called variant.h in my folders. And that code if I include in my script doesn't change anything.
What could be a workaround for this?
(I used to achieve this via this site by using Arduino Uno but for Due couldn't find any working solution)
Edit: I found the file and made the following change in variant.h:
 * PWM
 */
#define PWM_INTERFACE       PWM
#define PWM_INTERFACE_ID    ID_PWM
#define PWM_FREQUENCY       20000
#define PWM_MAX_DUTY_CYCLE  4095
#define PWM_MIN_DUTY_CYCLE  0
#define PWM_RESOLUTION      12

/*
 * TC
 */
#define TC_INTERFACE        TC0
#define TC_INTERFACE_ID     ID_TC0
#define TC_FREQUENCY        20000
#define TC_MAX_DUTY_CYCLE   255
#define TC_MIN_DUTY_CYCLE   0
#define TC_RESOLUTION       8

But it only works for 20kHz. If I set to 25kHz or 30kHz I don't get any error but also don't get any output :((

There are a few things to do. I've used this successfully in the past with older projects.
As a side note one can very easily change PWM settings on pins with the esp32, a single line of code being ledcSetup(PWM_Channel_Number, Frequency, resolution) without ever having to actually dive into modifying variant.h
To Quote Kerry D. Wong:

If you take a look at the function PWMC_ConfigureClocks in pwmc.c, you will see that the highest PWM frequency can be accommodated as the function input is 42 MHz, this is because inside the function it calls FindClockConfiguration which in turn ensures that the frequency parameter passed in is less than the MCK frequency. Thus for integer dividers, the highest frequency we can pass in is 42 MHz (with divider 2).
To achieve the highest output frequency, we can use a one bit PWM which essentially just outputs a square wave with a duty cycle of one. We can then set the prescaler to 2 to obtain an 84 MHz waveform.

#include <Arduino.h>

uint32_t pwmPin = 8;
uint32_t maxDutyCount = 2;
uint32_t clkAFreq = 42000000ul;
uint32_t pwmFreq = 42000000ul;

void setup() {
  pmc_enable_periph_clk(PWM_INTERFACE_ID);
  PWMC_ConfigureClocks(clkAFreq, 0, VARIANT_MCK);

  PIO_Configure(
    g_APinDescription[pwmPin].pPort,
    g_APinDescription[pwmPin].ulPinType,
    g_APinDescription[pwmPin].ulPin,
    g_APinDescription[pwmPin].ulPinConfiguration);

  uint32_t channel = g_APinDescription[pwmPin].ulPWMChannel;
  PWMC_ConfigureChannel(PWM_INTERFACE, channel , pwmFreq, 0, 0);
  PWMC_SetPeriod(PWM_INTERFACE, channel, maxDutyCount);
  PWMC_EnableChannel(PWM_INTERFACE, channel);
  PWMC_SetDutyCycle(PWM_INTERFACE, channel, 1);

  pmc_mck_set_prescaler(2);
}

void loop()
{

Note that VARIANT_MCK is defined in /arduino-1.5.7/hardware/arduino/sam/variants/arduino_due_x/variant.h as 84000000. PWM_INTERFACE_ID and PWM_INTERFACE are defined in variant.h as ID_PWM and PWM which in turn are defined in /arduino-1.5.7/hardware/arduino/sam/system/CMSIS/Device/ATMEL/sam3xa/include/sam3x8e.h.
So as the conclusion, the highest stable frequency we can generate using an Arduino Due is 84 MHz. The pictures below show the captured waveforms under different frequencies. For the 21 MHz waveform, pwmFreq is set to 21000000, no prescaler is used. For the 42 Mhz waveform, pwmFreq is set to 420000 with no prescaler. The 84 MHz waveform is generated with set to 42000000 and the prescaler set to 2.

Hope this helps.

Did you read what I was asking? My question is "But it only works for 20kHz. If I set to 25kHz or 30kHz I don't get any error but also don't get any output :(( " This does not set to PWM freq, to 25kHz.

Yes, but following the methods i said, should allow you to achieve the pwm setting you want...does it not do so? Can you set to any other freq above the khz range? Or does it just fall apart at anything above 25khz?

No that doesnt work. And your answer is not an answer at all. Im looking for a solution not advice. This is bounty question. Please delete your answer otherwise I will have to delete this question. You are not even using Due but attempting to answer such a technical specific question about it.

If you want a solution to ‘why doesnt the technical solution work with my hardware that i have no errors except it doesnt work to help with trouble shooting’ then you should delete this question, and re ask with useful information than ‘it doesnt work!!!!!’ :)

@user16307, you can wait for another answer. if you delete the question, you loose the bounty points. this answer will not get bounty points without at least two upvotes.


text:
Update `char* `
I have a class containing few char* variables:
char* msgTopic     = "myHome/MSGS";
char* groupTopic   = "myHome/All";
char* errorTopic   = "myHome/Err";

but, I wish to have it defined outside the class and not hardcoded (update only prefixTopic outside the class,
char* prefixTopic  = "myHome";
char* msgTopic     = ""; // also tried-->  char* msgTopic = "AAAAAAAAAAA";
char* groupTopic   = "";
char* errorTopic   = "";

and then, down the code to have it defined as:
sprintf(msgTopic  ,"%s/Messages",prefixTopic);
sprintf(groupTopic,"%s/All",prefixTopic);
sprintf(errorTopic,"%s/Errors",prefixTopic);

BUT
both ways ( when defining variables as "", or just filled it up with chars to allocate space) caused topics to be defined with errors ( mostly - one variable contained both topics ).
Appreciated any help
( I don't think context of class is relevant )

Not a duplicate, but the answers to “deprecated conversion from string constant to 'char*'” should provide the answer you are looking for (and more).

First, you have to think about using dynamic or pre-allocated strings. Dynamic memory is not recommended for Arduino, so I will use pre-allocated strings.
In that case you need to think about the maximum length, I will take 32 for now:
#include <stdio.h>

class YourClass
{
  static const int MaxTopicLength = 32;

  char _msgTopic[MaxTopicLength];
  char _groupTopic[MaxTopicLength];
  char _errorTopic[MaxTopicLength];

  void FillStrings(const char* prefixTopic);
};

Than create in your class a function to fill the strings (untested):
void YourClass::FillStrings(const char* prefixTopic)
{
  snprintf(_msgTopic  , MaxTopicLength, "%s/Messages", prefixTopic);
  snprintf(_groupTopic, MaxTopicLength, "%s/All"     , prefixTopic);
  snprintf(_errorTopic, MaxTopicLength, "%s/Errors"  , prefixTopic);
}


text:
Timer Countdown to control relay (multiple functions in void loop)

I'm trying to build this project with a simple code.
Object is to hit up button to increment minutes or down to decrement minutes then hit start to start countdown,
while its counting relay will turn On light till counting is done will turn light off and if I hit end button while counting it will end counting and turn off relay.
Here is my try I would appreciate if you could support me.
i can not move to countDown() function in the loop if i press start
I need help to figure out a good technique of declaring functions in void loop in arduino

#include <LiquidCrystal.h>

LiquidCrystal lcd(1,2,4,5,6,7);

#define numberOfSeconds(num) ((num/1000) % 60 )
#define numberOfMinutes(num) (((num/1000) / 60) % 60)

//unsigned long timeLimit = 3600000; // 1000 ms in 1sec, 60secs in 1min, 60mins in 1hr. so , 1000x60x60 = 3600000ms = 1hr

const int upBtn = 8;
const int downBtn = 9;
const int startBtn = 10;
const int endBtn = 11;

int btnPushCounter = 0;
int minutes;
int seconds;
unsigned long minutesGiven;
unsigned long timeLimit;
unsigned long timeRemaining;

int upBtnState = 0;
int lastUpBtnState = 0;

int downBtnState = 0;
int lastDownBtnState = 0;

int startBtnState = 0;
int lastStartBtnState = 0;

int endBtnState = 0;
int lastEndBtnState = 0;

bool bPress = false;

void setup() {

 lcd.begin(16,2);
 pinMode(upBtn, INPUT_PULLUP);
 pinMode(downBtn, INPUT_PULLUP);
 pinMode(startBtn, INPUT_PULLUP);
 pinMode(endBtn, INPUT_PULLUP);

 lcd.clear();
 lcd.setCursor(0,0);
 lcd.print("Minutes : ");
 lcd.print(btnPushCounter);
}
void loop() {

    checkUp();
    checkDown();
//    countDown();
    if(bPress){
      bPress = false;
      displayNumber();
    }
}

void displayNumber(){
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Minutes : ");
    lcd.print(btnPushCounter);
}

void checkUp(){
  upBtnState = digitalRead(upBtn);
  // compare the buttonState to its previous state
  if (upBtnState != lastUpBtnState) {
    // if the state has changed, increment the counter
    if (upBtnState == HIGH) {
        bPress = true;
      btnPushCounter++;
    }
    delay(50);
  }
  // save the current state as the last state, for next time through the loop
  lastUpBtnState = upBtnState;
}

void checkDown(){
  downBtnState = digitalRead(downBtn);

  // compare the buttonState to its previous state
  if (downBtnState != lastDownBtnState && btnPushCounter != 0 ) {
    // if the state has changed, increment the counter
    if (downBtnState == HIGH) {
        bPress = true;
      btnPushCounter--;
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  // save the current state as the last state, for next time through the loop
  lastDownBtnState = downBtnState;
}

void checkStart(){
  startBtnState = digitalRead(startBtn);
  if(startBtnState != lastStartBtnState){
    if(startBtnState == HIGH){
      bPress = true;
//      lcd.
    }
  }
}

void countDown() {
//  unsigned long timeLimit = 3600000;
  minutesGiven = btnPushCounter;
  timeLimit = minutesGiven * 1000 * 60;
  timeRemaining = timeLimit - millis();
  while(timeRemaining > 0){
    seconds = numberOfSeconds(timeRemaining);
    minutes = numberOfMinutes(timeRemaining);
    lcd.setCursor(2,7);
    lcd.print(minutes);
    lcd.print(" ");
    lcd.print(seconds);
    delay(50);
    timeRemaining = timeLimit - millis();
  }
}

what is your question?

just updated have a look please , thanks

still no question being asked .... let me say it differently .... you posted i am working on project ABC, here i my code .... we need to see something like this  i am working on project ABC, here i my code. i expect the program to do XYZ, but it does ZYX. how do i debug a problem like that?

I think you are not searching for a way to declare function, but for the logic code, that you need to call them in the right situations. Is that correct?

And why don't you simply put countDown() into checkStart()?

moving functions above setup solved the issue , Thanks a lot guys

I think what you're looking for is to declare your functions near the top of your file, usually before the first function you write, setup(), in this case. So add this just above your setup() function:
// Forward function declarations
void displayNumber(void);
void checkUp(void);
void checkDown(void);
void checkStart(void);
void countDown(void);

C compilers (and thus, C++ because it was derived from C) read the source code only once through, so any function must become known to the compiler ahead of where it is first called. This would require you to place all low-level functions first, then all functions that call those, then the functions that call those, ..., etc. And there are some cases that even this arrangement won't solve, e.g., functions that call each other (oww, my brain hurts!!). So function declarations are used to avoid this inconvenience.
Declaring a function just means informing the compiler of its name, the parameter types, and the return type -- the actual function code isn't required at this point.


text:
Arduino digital pin status not transmitting via NRF24L01 where as analog pin status is getting transmitted ,Why?
I am currently working with a project using NRF24L01 which I integrated with my Joystick so that I can make it wireless.While transmitting the information in my Joystick to the receiver only analog pin status is getting transmitted where as digital pin status is not getting transmitted.
Transmitter Code:

#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include <Wire.h>

//Define the digital inputs
#define tGL1 7
#define tGL2 6
#define b1 5
#define b2 4
#define b3 3
#define b4 2

const int MPU = 0x68; // MPU6050 I2C address
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float accAngleX, accAngleY, gyroAngleX, gyroAngleY;
float angleX, angleY;
float AccErrorX, AccErrorY, GyroErrorX, GyroErrorY;
float elapsedTime, currentTime, previousTime;
int c = 0;

RF24 radio(9,10);
const byte address[6]="00001";

struct Data_Package {
  byte j1PotX;
  byte j1PotY;
  byte j2PotX;
  byte j2PotY;
  byte button1;
  byte button2;
  byte button3;
  byte button4;
  byte tSwitch1;
  byte tSwitch2;
  byte pot1;
  byte pot2;
};

Data_Package data;

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

  radio.begin();
  radio.openWritingPipe(address);
  radio.setAutoAck(false);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_LOW);

  pinMode(tGL1, INPUT_PULLUP);
  pinMode(tGL2, INPUT_PULLUP);
  pinMode(b1, INPUT_PULLUP);
  pinMode(b2, INPUT_PULLUP);
  pinMode(b3, INPUT_PULLUP);
  pinMode(b4, INPUT_PULLUP);

   data.j1PotX = 127; // Values from 0 to 255. When Joystick is in resting position, the value is in the middle, or 127. We actually map the pot value from 0 to 1023 to 0 to 255 because that's one BYTE value
   data.j1PotY = 127;
   data.j2PotX = 127;
    data.j2PotY = 127;
//  data.j1Button = 1;
//  data.j2Button = 1;
  data.pot1 = 1;
  data.pot2 = 1;
  data.tSwitch1 = 1;
  data.tSwitch2 = 1;
  data.button1 = 1;
  data.button2 = 1;
  data.button3 = 1;
  data.button4 = 1;

}

void loop() {
  // put your main code here, to run repeatedly:
  data.j1PotX = map(analogRead(A2), 0, 1023, 0, 255); // Convert the analog read value from 0 to 1023 into a BYTE value from 0 to 255
  data.j1PotY = map(analogRead(A1), 0, 1023, 0, 255);
  data.j2PotX = map(analogRead(A3), 0, 1023, 0, 255);
  data.j2PotY = map(analogRead(A0), 0, 1023, 0, 255);
  data.pot1 = map(analogRead(A7), 0, 1023, 0, 255);
  data.pot2 = map(analogRead(A6), 0, 1023, 0, 255);

  data.tSwitch2 = digitalRead(tGL2);

  data.button1 = digitalRead(b1);
  data.button2 = digitalRead(b2);
  data.button3 = digitalRead(b3);
  data.button4 = digitalRead(b4);

  if (digitalRead(tGL1) == 0) {
    read_IMU();    // Use MPU6050 instead of Joystick 1 for controling left, right, forward and backward movements
  }

  radio.write(&data, sizeof(Data_Package));
}

This is the Reciever Code
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10);   // nRF24L01 (CE, CSN)
const byte address[6] = "00001";
unsigned long lastReceiveTime = 0;
unsigned long currentTime = 0;
// Max size of this struct is 32 bytes - NRF24L01 buffer limit
struct Data_Package {
  byte j1PotX;
  byte j1PotY;
  byte j2PotX;
  byte j2PotY;
  byte pot1;
  byte pot2;
  byte tSwitch1;
  byte tSwitch2;
  byte button1;
  byte button2;
  byte button3;
  byte button4;
};
Data_Package data; //Create a variable with the above structure
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setAutoAck(false);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_LOW);
  radio.startListening(); //  Set the module as receiver
  resetData();
}
void loop() {
  // Check whether there is data to be received
  if (radio.available()) {
    radio.read(&data, sizeof(Data_Package)); // Read the whole data and store it into the 'data' structure
    lastReceiveTime = millis(); // At this moment we have received the data
  }
  // Check whether we keep receving data, or we have a connection between the two modules
  currentTime = millis();
  if ( currentTime - lastReceiveTime > 1000 ) { // If current time is more then 1 second since we have recived the last data, that means we have lost connection
    resetData(); // If connection is lost, reset the data. It prevents unwanted behavior, for example if a drone has a throttle up and we lose connection, it can keep flying unless we reset the values
  }
  // Print the data in the Serial Monitor
  Serial.print("j1PotX: ");
  Serial.print(data.j1PotX);
  Serial.print("; j1PotY: ");
  Serial.print(data.j1PotY);
  Serial.print("; button1: ");
  Serial.print(data.button1);
  Serial.print("; j2PotX: ");
  Serial.println(data.j2PotX);
}

When I print the status of the buttons and Joystick in my transmitter(Joystick) I get the correct status of my push button when I press but the status of my push button remain unchanged in the Serial monitor of my Receiver despite there is change other values (I mean the analog value is transmitting correctly)
This the screenshot of my both serial Monitor

Hint: A common header file with the message struct would help avoid this issue. The layout of the struct's are not the same :)

As Mikael Patel mentions in the comments: your structures do not match between the transmitter and receiver.
Transmitter               Receiver
=====================     =====================
struct Data_Package {     struct Data_Package {
      byte j1PotX;    ->      byte j1PotX;
      byte j1PotY;    ->      byte j1PotY;
      byte j2PotX;    ->      byte j2PotX;
      byte j2PotY;    ->      byte j2PotY;
      byte button1;   ->      byte pot1;
      byte button2;   ->      byte pot2;
      byte button3;   ->      byte tSwitch1;
      byte button4;   ->      byte tSwitch2;
      byte tSwitch1;  ->      byte button1;
      byte tSwitch2;  ->      byte button2;
      byte pot1;      ->      byte button3;
      byte pot2;      ->      byte button4;
};                        };

With structures, what matters is not what each field is called. What matters is the position of the fields in the list.  When you compile your code all the names are lost. All that is left is where in the list each entry is.
The best way of avoiding this problem is to have a single header file (make it a library so it's easy to share) that contains the packet structure. Then if you ever make any changes to the packet all the sketches that use it see that change the next time you compile them.

Does that mean I have to make an file with .h extension and then import them using #include

Yes. If you make that file as Documents\Arduino\libraries\PacketFormat\PacketFormat.h then you can just #include <PacketFormat.h> in any sketch to get the structure.


text:
RTC timer set point problem
This is the timer part of my code:
int onHourONE = 11;
int onMinuteONE = 00;
int offHourONE = 23;
int offMinuteONE = 00;
byte PWMstatus = 0;

void setup{}

void loop{
    if ((now.hour() >= onHourONE) && (now.minute() >= onMinuteONE)) {
      PWMstatus = 1;
    }
    if ((now.hour() >= offHourONE) && (now.minute() >= offMinuteONE)) {
      PWMstatus = 2;
    }
    if (PWMstatus == 1) {
      // do this
    }
    if (PWMstatus == 2) {
      // do that
}

It's working just fine but the problem is if i set the offhourONE less than onhourONE it will keep the LED OFF.
for example the time is now 14:00
onhourONE and offminuteONE is also set on 14:00
offhourONE and offminuteONE is set on 13:00
So in this case it should keep the LED ON until tomorrow 13:00 but it stays OFF obviously because of this statement:
if ((now.hour() >= offHourONE) && (now.minute() >= offMinuteONE)) {}

I can change that to this:
if ((now.hour() == offHourONE) && (now.minute() == offMinuteONE)) {}

But then it will only turn OFF the LED at that specific time, in this case if i restart the Arduino like 1 minute after it turned OFF it will turn on again while it should stay off until it reaches the set point of turn ON.
I know it sounds simple but seems confusing to me, any guidance appreciated...

i was writing as i was thinking ... 37:00 = 13:00 + 24:00 ... add 24 hours to turn off time

you can figure this out by drawing a diagram ... circle ... 0 at top 12 at bottom ... that is 24 hours ....  add 24 hours to stop time .... then use something like this pseudo code  if (T>=14 && T+24 <=37) then ON else OFF

You need to add more logic to your program.
As mentioned in another answer you really want to be working with just the highest resolution time interval that matters to you - that is minutes in your case.  Convert your hour and minutes of the day into the number of minutes since midnight:
onTime = onHourONE * 60 + onMinuteONE;
offTime = offHourONE * 60 + offHourONE;

And convert the current time to minutes since midnight:
timeNow = now.hour() * 60 + now.minute();

Now comes the tricky bit, but since you are now just working with single numbers it's far easier.  You now need to work out what you are doing.
You have a couple of scenarios:

onTime < offTime - eg: 12:00 to 17:00
onTime > offTime - eg: 21:00 to 03:00

You need to make your decision in a different way depending on which scenario you are in - and comparing a single number with a single number is so much easier than messing with hours and minutes.
So, you can do something like:
if (onTime < offTime) {
    if ((timeNow >= onTime) && (timeNow < offTime)) {
      // On!
    } else {
      // Off!
    }
} else {
    if ((timeNow >= onTime) || (timeNow < offTime)) {
      // On!
    } else {
      // Off!
    }
}

In English:

If the start time is before the end time:

If the time is both greater than the start time and less than the end time, then it's on.
Otherwise it's off.

Otherwise, of the start time is after the end time:

If the time is greater than the start time, or it's less than the end time, then it's on.
Otherwise it's off.

thanks for the detailed answer, that now after first if is timeNow, right?

Yes, that's right. I edited my answer. Well spotted.

I just tested it and it's working. thanks again. quick question; can i combine that if after else together like this else if(){}?

Possibly, but it's more logical laid out the way I have it. You can instantly see the meaning, and it won't make it any more or less efficient to run.

If it overly complicated to use a combination of seconds, minutes and hours for comparisons. For this you can use the time in seconds, as you get it with now.secondstime() or now.unixtime(). If you don't want to look at the seconds (so only values multiple to 60), you can do an integer division to get the minutes now.secondstime()/60.
To calculate the needed limit values from the combination of hour and minutes, just multiply according to the unit. For seconds (hour*60+minutes)*60. For minutes hour*60+minutes.

unixtime for a time in current day? and how does using minutes of day solve the question?


text:
Serial.println() cuts off characters
I want to print a string together with number. My code is
Serial.println("Test " + index++);

(In setup() I initialized variable index to 0.) In Java it would output
Test 0
Test 1
Test 2
Test 3
...

But I get this output instead:
Test
est
st
t

Can anybody explain it to me please?

Serial.println() prints the value of one expression. The expression you passed it was `("Test " + index++).
In C/C++ a character literal such as "Test " evaluates to the memory address its first character. Adding 1 to that address gives the address of the next (or 2nd) character. Adding 2 to it gives the address of the 3rd character, and so on.
To get what you were expecting, the value of the literal, AND the value of the index, you would write:
Serial.print("Test ");
Serial.println(index++);

If you had created a String variable with the value "Test ", then the String expression, ("Test " + index++) would have been evaluated differently: The "+" operator would have concatenated the String "Text ", with the String equivalent of the current value of "index"; but that isn't the way a character literal is treated. There is a C++ String library among the Arduino libraries but it's use is not recommended because Strings get reallocated and copied when they get concatenated, resulting in excessive memory use, and the Arduino has very little memory.

JRobert explains very well why it does not work.
Instead of the Serial.print you also can use the sprintf function in case you need a more complicated string to build, or in case you want to mix two different types in one line:
char str[100];
int index = 0;
sprintf(str, "Test %d", index++);
Serial.println(str);

Make sure the buffer (100) is big enough to store the full string including the end symbol ('\0').
For safety you also can use:
snprintf(str, 100, "Test %d", index++);

This will make sure max. 100 characters are filled in (and the remainder is clipped).


text:
I want to code a depth sensor for arduino
I want to code a depth sensor for a little sub that i am working on. I want it to submerge to a any certain depth  for example 2ft. The speed of the motor is to increase by 5 until it reaches the set point given. The problem that I am facing is: whenever it reaches the set example point of 2ft the motor turns off and the sub resurfaces to the top and doesn't hold the depth .
What I want is that for whatever speed the motor is at for 2ft depth, to maintain its speed and keep the sub submerge at 2ft.
#include <MS5837.h>
#include <Wire.h>
#include "MS5837.h"
#include <Servo.h>
MS5837 sensor;
Servo vertical_thruster;

float x;
float error;
int pwm = 1525;
float currentdepth = sensor.depth();
float recquireddepth = -0.4;  //  set depth u wish to maintain in meters

void setup() {
      Serial.begin(9600);
     vertical_thruster.attach(6);
     vertical_thruster.writeMicroseconds(1500);
 /////////////////////////////////////////////Bar 30 Configuration ////////////////////////////////////////
  Serial.println("Starting");
  Wire.begin();
 while (!sensor.init()) {
    Serial.println("Init failed!");
    Serial.println("Are SDA/SCL connected correctly?");
    Serial.println("Blue Robotics Bar30: White=SDA, Green=SCL");
    Serial.println("\n\n");
    delay(2000);
  }
  sensor.setModel(MS5837::MS5837_30BA);
  sensor.setFluidDensity(997); // kg/m^3 (freshwater, 1029 for seawater)
}

void loop() {

  sensor.read();
  Serial.print("Depth: ");
  Serial.print(currentdepth);
  Serial.println("m");
error = (currentdepth) - (recquireddepth) ;

if ( error!=0)
  { pwm +=5;
    vertical_thruster.writeMicroseconds(pwm+=5);
    Serial.println( pwm+=5);
    Serial.print ( " Submerging ");
  }
if ( error=0){
  vertical_thruster.writeMicroseconds(pwm);
  Serial.print ( "  At Depth");
}
else if ( error >-0){
  vertical_thruster.writeMicroseconds(1400);
  Serial.print ( "resurfacing");
  delay(1000);
}
}

Help with what? What is not working as expected and what is the expected result? Are you getting any errors or is something else happening?

The code compiles and work yes but when it reaches its set value it dont hold the speed to keep it at the depth set

Please, edit the question to add all the relevant information. One should not need to read all the comments to understand a question. Re “it dont hold the speed”: what does it do instead? You should try to give a complete description of the problem.

question has been edited.

#include <MS5837.h>
#include <Wire.h>
#include <Servo.h>

MS5837 sensor;
Servo vertical_thruster;

// Variables

float current_depth ;
float set_depth = 0.30 ; //  depth u wish to go in meters
float PID_error = 0;
float previous_error = 0;
float elapsedTime,  Time , timePrev;
float pwmvertical_thruster;
int PID_value = 0;
int PID_p = 0;
int PID_i = 0;
int PID_d = 0;

//PID constants
float kp = 4.1;
float ki = 0.03;
float kd = 1.8;

void setup() {
  Serial.begin(9600);
 vertical_thruster.attach(6);
 Time = millis ();
 vertical_thruster.writeMicroseconds(1500);

///Bar 30 Configuration

 Serial.println("Starting");
 Wire.begin();
while (!sensor.init()) {
Serial.println("Init failed!");
Serial.println("Are SDA/SCL connected correctly?");
Serial.println("Blue Robotics Bar30: White=SDA, Green=SCL");
Serial.println("\n\n\n");
delay(2000);
 }
 sensor.setModel(MS5837::MS5837_30BA);
 sensor.setFluidDensity(997); // kg/m^3 (freshwater, 1029 for seawater)
}

void loop() {

// First read the current value of the depth sensor
sensor.read();
current_depth = sensor.depth();

timePrev = Time;
Time= millis();
elapsedTime = ( Time - timePrev) / 1000;

// calculate the error between the set depth and current depth
PID_error =  set_depth - current_depth ;

// Calculate the P Value
 PID_p = kp * PID_error;

// Calculate the i value in a range on +-0.3

 if (-0.3 < PID_error < 0.3 )
  {
  PID_i = PID_i + (ki * PID_error);
  }

// Calculate the d value
PID_d = kd*((PID_error - previous_error)/elapsedTime);
// The total PID value
PID_value = PID_p + PID_i + PID_d;

// range for the blue robotics esc

 if ( PID_value < -400)
 {
 PID_value = -400;
  }
  if( PID_value >400)
  {
 PID_value = 400;
  }
// calcualte the pwm
 pwmvertical_thruster = (1500 + PID_value) || ( 1500 - PID_value);
if(pwmvertical_thruster < 1500)
 {
  pwmvertical_thruster= 1500;
  }
 if(pwmvertical_thruster > 1900)
  {
   pwmvertical_thruster=1900;
   }
    Serial.print("Depth: ");
    Serial.print(sensor.depth());
    Serial.println(" m");
    vertical_thruster.writeMicroseconds(pwmvertical_thruster);
    Serial. println ( "t\t");
    Serial. println ( pwmvertical_thruster);
     previous_error = PID_error;

   }`

Is this the working code? Is it behaving correctly? (Since you now marked it as correct answer)

@chrisl it works but I need to get my values right the esc correct . The esc that I am using has 2 Maximum with 1500 equals to stop . 1500 -1900 is Min to Max clockwise and 1500-1100 is min to max counter clockwise.

Your code has several problems:

You are including the MS5837 library twice. That just doesn't pose a problem, because the library has include guards, that make sure it is only included once.
At global scope you use float currentdepth = sensor.depth();, which calls the function sensor.depth(). This will be done before the setup() function, so at that time the sensor library does not have any valid depth data. So it's useless. You can just set it to zero.
In your loop() you are doing sensor.read(), but then you are never actually getting the new depth value from the library. You are just again using currentdepth without changing it ever. You should set the variable to the new value by using currentdepth = sensor.depth(); after the sensor.read().
You are using the statement if ( error=0). Using only a single = means an assigment. So here the variable error get's set to zero and the if statement will not compare it so zero. You have to use a double =: if(error == 0).
if( error >-0): Why are you checking for error being greater than MINUS ZERO. Sure, -0 is a valid integer, but mostly senseless. Also it is questionable, if the logic is correct here, since first you check for error being different than zero. Then you check for it being zero and then (if it is not equal zero) you check for it being greater than zero. If error really happens to be greater than zero, you will first write pwm to the servo and then directly 1400, which is submerging and resurfacing directly after another in only one loop.
The whole if structure seems quite off. You should rethink the logic of the program.

That said, for reaching a set point of whatever kind it is good to use a PID controller, that will get you to the setpoint rather fast and will keep you there. A PID controller can be done in hardware or software. For implementing a software PID controller on Arduino you can use one of the various PID libraries, for example this one. Most libraries also contain examples, that show how to use them.

Good, through answer. (Voted) I was going to suggest a PID also. You need something that will "hone in on" the target depth and then keep it there. You'll have to tune the PID with the right control values though.

@chrisl @ Duncan C  I have updated and fixed the code. can you take a look at it ?


text:
Adding WiFi to my Arduino Keypad Lock
I'm a really passionate beginner with arduino and electronics and I've built a Keypad lock for my room's door (inside the house).
I've used an arduino that activates a motor using a transistor to open the door if the correct pin is entered.
I want to add wifi control to my project. I have a few transistors, relays and ESP01s lying around for the upgrade. I want to use the blynk app and use the ESP01 independently without disturbing or modifying the arduino code. I'll program the ESP01 directly.
These are my requirements:
-A failsafe so I can open the lock via blynk if I forget the pin
-A kill switch that will turn off the arduino if I suspect somebody knows my PIN.
These are my ideas:
-Can I directly connect an ESP GPIO pin to the base of the transistor where the arduino is connected? By doing this can I control the transistor to switch the motor via both the arduino and the ESP 01?
-Can I put a relay module between the arduino and the battery pack and connect it to the ESP? I will connect the relay so that it will disconnect power to the arduino only when powered on. Is this a viable solution for a kill switch?
Any suggestions and ideas about how to go about this will be highly appreciated.

Can I directly connect an ESP GPIO pin to the base of the transistor where the arduino is connected?

No. You will effectively be connecting two outputs together, and that is very bad.
Instead you will need to add a second transistor in parallel to the first - one controlled by the Arduino and one controlled by the ESP-01.

Can I put a relay module between the arduino and the battery pack and connect it to the ESP?

Sure. No problem with that.

I will connect the relay so that it will disconnect power to the arduino only when powered on. Is this a viable solution for a kill switch?

As long as the kill switch doesn't also shut off power to the ESP-01 - otherwise it will just switch on again straight away...

Thanks a lot. Can you please tell me about the parallel transistor arrangement in more detail? Also, how do I operate a 5V relay using 3.3v ESP01? Is it ok if I power the relay separately from the battery pack and only connect the signal pin to the ESP8266?

You can't drive a 5v relay from any microcontroller. If you have a relay module, not a relay, then it will most probably work. Otherwise you will be building a transistor driver circuit regardless of the voltage.