text:
How to rotate a servo motor on a specific angle?
I am trying to rotate a top on a specific angle after every 1 second. For example: 1 degree/second. I have two question:

Can I achieve this with servo motors?
If not, what motor should I use?

I know this question has very little description. I am mainly a programming guy. I don't much about arduino stuff. It's actually a hobby project for me.
Thanks in advance.

The kind people who have written the Arduino libraries include software drivers for servo control.  These drivers abstract the hardware from the programmer of the sketch software (the sketch is application software you write in C or C++).  It is unnecessary to understand the driver in detail.  However the servo driver software (likely written in C++) can been examined here.
To move a normal servo to a particular position, make a call to the Arduino Servo Driver using the function write(angle) passing an angle value from 0 to 180.  The value is an approximation of degrees and the value type is of type integer.
In the above links you will find this example of sweeping the servo motor across its range:
/* Sweep
 by BARRAGAN <http://barraganstudio.com>
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Proceed to that page for more details including a schmatic (diagram) of how the servo is connected to an Arduino Uno board.

One more question: can I use small arduino's like nano instead of mega/uno?

The deal w/using different platforms can generally be boiled down to 2 issues.  One, to make sure the HW is there to deal with the application.  In this case the Arduino servo libraries use the PWM HW inside the processor.  And both the Uno and Nano use the ATmega328P processor.  So that should work.  Two, the library has been ported to the different processor and board.  In this case the processor is the same.  So it is likely you can use a Nano instead of the Uno.

If not clear, @PotatoMan is correct.  Normal servos have a limited rotation (less than one complete revolution).  As you said, your end-goal is not clear.  So we can not help in picking out an alternative motor.

thanks man. I will work on it and find out more. I have got my starting point. Thanks for clearing things up. Have a nice day :)

You can rotate the servo motor per degree, but it has it's limitations, it only has 0-180 degrees of movement. If you need to rotate beyond that, I would recommend using Stepper motors, they can be very precise, but they don't have a potentiometer, like a servo does, so, after resetting the system, the motor won't comeback to the starting position.

Thanks man. However, @st2000 gave a far more detailed example.


text:
Arduino DUE- flash space for user
I need for my project to save only 32bit in non-volatile storage.
What is the easiest/cheapest way to do that in Arduino DUE?
ArduinoDUE is Atmel SAM3X8E so according to the attached table (from Atmel DS)

In the chip I have 4KB of NFC SRAM. NFC = Nand Flash Controller, so I have 4KB of internal flash in the internal SRAM?
Thanks,

You'll probably need to "walk" the value through at least one erase block worth of program flash.  Beware some flash architectures with ECC do not permit overwriting unprogrammed bits in a partially programmed word; which may be several bytes long.  So it's best if you can define the erase value as "unused" and simply search until you find the last unerased value, appending any new values on the end.

It looks like there's at least one library out there to emulate EEPROM functionality in the DUE using Flash.
https://github.com/sebnil/DueFlashStorage

ROM is not good for me. I need to be able to READ and WRITE, but the data should survive power loss

you misunderstand what is meant by EEPROM... it is READ / WRITE

source: Stack Exchange

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

sort: votes


text:
Why am only hearing noise or no sound?
Alright, there is something missing in the question, I was able to hear one sound of the files and the others apply to the question I asked and that is why I am wondering. what is happening!
Here is the code:
#include <SD.h>                      // need to include the SD library
#define SD_ChipSelectPin 4  //using digital pin 4 on arduino nano 328, can use other pins
#include <TMRpcm.h>           //  also need to include this library...
#include <SPI.h>

TMRpcm tmrpcm;   // create an object for use in this sketch

void setup(){

  tmrpcm.speakerPin = 9; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc

  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
    Serial.println("SD fail");
    return;   // don't do anything more if not
  }
  tmrpcm.play("music.mp3"); //the sound file "music" will play each time the arduino powers up, or is reset
}

void loop(){

  if(Serial.available()){

    if(Serial.read() == 'p'){ //send the letter p over the serial monitor to start playback

      /* These are spkean Numbers */

     // tmrpcm.play("1-24bit.wav");
     // tmrpcm.play("1-16bit.wav");
     // tmrpcm.play("200-insane.mp3");
     // tmrpcm.play("music.mp3")       // Strangely this is the working perfectly with good sound
     // tmrpcm.play("200-standard.mp3");
        tmrpcm.play("200.wav");        // from https://evolution.voxeo.com/library/audio/prompts/numbers/index.jsp
    }
  }

}

Everything is good when I play this tmrpcm.play("music.mp3"); but the others I hear aliens sounds expect this tmrpcm.play("200.wav"); which I can hear the number two hundred but I feel the sound is 4-bit depth which very noisy. The files used in the code are here
For clarification previously, I thought it was amplifying issues which then I had to used LM386 but the sound was the same noise with tmrpcm.play("200.wav"); and later when I tried this tmrpcm.play("music.mp3"); I was shocked it worked perfectly like what I need it to be!  so I was curious I removed the LM386 and played this tmrpcm.play("music.mp3"); again and worked alright just maybe less volume.

Should I try to record a sound again with a lower pitch?

you renamed the sample file "music" to "music.mp3"? the library can play only prepared sound files https://github.com/TMRh20/TMRpcm/wiki

Yes, that is correct and it was working. I made to music.mp3 and  music.wav because I just was curious. I was going to rename 200.wav to 200 but did not know how my Mac was not allowing me.

So how I do play spoken numbers from 1 to 100 as prepared sound files? Can I record them?

@Juraj I'm so dumb that link you sent has the solution... I will try it when I go home... sorry I just hate to read so that why I skip links. They are a smaller version of books.

@Juraj - Alright, I guess since that time I been trying to follow the author instructions but as always l have to struggle... So I tried to create wav same as the one working https://imgur.com/a/TuMAYQa but  I can not get close to that info as seen here https://imgur.com/a/NjnggDd

@Juraj I guess I will stick with this one tmrpcm.play("200.wav"); and get over the noise I tried low pass filter but not working. I don't know!!

@Juraj - will you upload sample .wav has a spoken number and upload it to your Github because I'm frozen in this step and can not search further

This wonderful site https://www.online-convert.com/ doing what I need, just need to store a file to SD and test the sound!

Oh yeah, I am hearing my sound there now!

As @Juraj mentioned it was solved by changing the setting and I was able easily to play the sound when I matched the setting to this file:

So, I could not create one from scratch matches above setting but I was able to convert existing sound through this site
which allowed me to convert with desire setting and here finally the exiting sound has matched the setting:

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


text:
Low voltage security
I'm building a circuit with a GPS sensor and an esp32. My input voltage is designed to be 5V but I experienced some issues where people put lower charger in input (<4V). As a result my esp32 will boot but will functions erratically.
As I'm quite new with components and circuits, I was wondering if there was a way to ensure no current will go to my esp32 unless the input voltage is at least 5V?
Board being used: Espressif esp32 devkitc 4
https://docs.espressif.com/projects/esp-idf/en/latest/get-started/get-started-devkitc.html
Thanks for your help

What you are looking for is a power-on-reset generator. A workaround in software could be to wait some ms before initializing any peripheral device. How do you know your esp boots and in which way does it behave erratically? Usually the esp's brownout detector triggers a reboot when the voltage drops too far

As far as I can see, you can set the brownout detection to a higher value. Default is CONFIG_BROWNOUT_DET_LVL_SEL_0 which is 2.4V. You can change it upto CONFIG_BROWNOUT_DET_LVL_SEL_7 which is 2,74V. But I think the issue might be with the voltage regulator that converts the 5V down to 3.3V.


text:
LED not blinking when using a transistor
I want to control an led using a transistor. The led gets it‘s power from an external 5v dc power supply.
For the transistor I use an 1kΩ base resistor. The transistor is a BC547C (npn). The datashet is available here.
The led is red (3mm), draws 20mA of current and needs 2V.
I‘ve got a very simple Arduino sketch and wiring setup:
Code:
#define ledPin 6

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

void loop() {
  digitalWrite(ledPin, HIGH);
  delay(1000);
  digitalWrite(ledPin, LOW);
  delay(1000);
}

Wiring diagram:

Problem:

The led is not blinking but shining at full power constantly.
Disconnecting ledPin 6 from the Arduino (to mimic digitalWrite(ledPin, LOW)) still lets the led shine, just not as bright. The LED should be off in that case, not just dimmed to 50% brightness.

What I tried so far:

I tried using different base resistors. I tried 2kΩ, 3kΩ, 2.5kΩ, 470Ω, 1.5kΩ. The behavior did not change.
I tried using different leds. Same behavior. LEDs are shining constantly, not blinking, and are dimmed when disconnecting pin 6.
I used another BC547C to see if the first one was broken. It wasn’t. I still got the same behavior.
Connecting the led directly to the Arduino without the transistor and external power supply let’s the led blink exactly how it was defined in code.

Any ideas?
I several-times-checked the wiring in my setup. It should not be the problem.

You need to provide common ground. Add wire connecting negative '-' connector of your battery with GND in your Arduino.

@smajli that doesn't explain why the led stays on when the base is not connected to the gpio...

@WalterBeiter could you post a picture of your setup? Are you sure that you have assigned the correct pins at the BC547? From the info you provided and the troubleshooting you already did I don't see anything that could be wrong.

@Sim Son I agree, but we have to start somewhere...

https://majenko.co.uk/blog/importance-sharing-grounds

Is there something special about the diode? You seem to use a varactor in your schematic.

Nothing special with my diode. Varactor? No idea what that is.

@WalterBeiter So why have you drawn it with two dashes instead of one? See for example this image.

Sorry, didn’t know it better. Thanks for pointing it out.

Without a common reference (ground) between the Arduino power supply and the external power-supply, again, you have a floating base, as you can't know what the Arduino's 5v output (or local ground) looks like to the external circuit.
Connect the two grounds. That should correct the LED brightness with respect to the Arduino output pin level. Then, if you need the external circuit to behave in a specific way when the base is disconnected from the Arduino, add a 10K resistor from the transistor base to the external +5 if you want the LED to be on, or to ground, if you want it to be off. Again, I'm guessing at both the pullup/pulldown value (but 10K should be in the ballpark) and the switching sense ('On' or 'Off' for base at +5), but from the expectation state in your point (2.), I think I have it right.
Update: But see @EdgarBonet's comment to me about BJT's. I'd still avoid leaving an input floating as a matter of practice, but it seems not relevant in your circuit.

Re the floating base: The OP is using an BJT. Unlike a FET (which is voltage controlled), the control variable for a BJT is the current fed to its base. Leaving the base floating is a legitimate way of setting that current to zero.

I hadn't known that about BJTs, @EdgarBonet, so thanks for that. Fixing my answer...

Common reference ground fixed all the issues!


text:
Does LabVIEW Linx affect the communication speed with Arduino?
I am using LabVIEW to connect to Arduino Mega. I control a logic gate to switch the current On/Off and at the same time there is an I2C connection with a sensor. It came to my attention that the sensor time resolution is very low and I cannot get enough data points from the sensor (I know that the sensor is capable of much better resolutions). My question, is this a problem inherent to LabVIEW and Linx module or my program in LabVIEW? Should I turn to coding with Arduino programming language or C?
note! My reason for using LabVIEW is that I need to sync timing of data aqcuisition with another device which is connected through another VISA port.

As far as I know, VIs are kind of compiled into c/c++ under the hood. It might help us if we could see your LabVIEW program and know which sensor it is. How do you connect to the arduino? I2c as well?

For specific timing requirements, my recommendation is to write your own Arduino code.
The Linx module deploys its own ino program to the Arduino and uses serial IO to send it commands and receive data from it. Open NI I/O Trace to observe that traffic.

Thanks for the answer, I exactly did that.
Linx communicate every command to the arduino and wait for the answer, the loop frequency with linx drops as the linx blocks increases in the loop. it droped to 10Hz for me. I am now using the arduino code and send the data back to labview using serial communication. Its much faster (Up to 300Hz loop frequency).


text:
Arduino wrap or subclass print() to work with multiple Serial
I am writing an Arduino program that uses Bluetooth on Serial1 to print text to a Bluetooth terninal on an Android phone and also normal Serial to print text to the serial monitor on a laptop. I would like to wrap the Serial.print() and Serial.println() functions so that they work with either or both Serial and Serial1. For example the code below works fine depending on the values of the global variables. But this only works for single chars, but print() and println() can take a very wide variety of datatypes. If I also define overloading functions for int and String types it works fine, but that is a very verbose and maybe fragile solution, it also ignores the optional inputs to the underlying functions. What is the proper way to do this ?
void print(char x) {
  if (g_use_Serial)
    Serial.print(x);
  if (g_use_Serial1)
    Serial1.print(x);
}

void println(char x) {
  if (g_use_Serial)
    Serial.println(x);
  if (g_use_Serial1)
    Serial1.println(x);
}

I have implemented the solution suggested and it works nearly perfectly. There seems to be a problem with the new line characters on the bluetooth (Serial1) connection.
The code is:
class DualPrint : public Print
{
public:
    DualPrint() : use_Serial(false), use_Serial1(false) {}
    virtual size_t write(uint8_t c) {
        if (use_Serial) Serial.write(c);
        if (use_Serial1) Serial1.write(c);
        return 1;
    }
    bool use_Serial, use_Serial1;
} out;

void setup()  {
  Serial.begin(9600);
  Serial1.begin(9600);
  delay(1000);
}

void loop() {

  out.use_Serial = true;
  out.print("Printed to USB only.\n");
  out.use_Serial1 = true;
  out.print("Printed to both USB and BT.\n");
  out.use_Serial = false;
  out.print("Printed to BT only.\n");
  out.use_Serial1 = false;

  delay(3000);
}

The output on the USB Serial monitor is as expected:
Printed to USB only.
Printed to both USB and BT.
Printed to USB only.
Printed to both USB and BT.

The output on the Bluetooth terminal is not as expected, the new lines are not in the right position:
Printed to both USB and BT.Pri
nted to BT only.
Printed to both USB and BT.Pr
inted to BT only.
Printed to both USB and BT.Pr
inted to BT only.
Printed to both USB and BT.Pr
inted to BT only.

Any suggestions on how to fix this. Are there other function members that need to be re-implemented to make this work properly?
Many thanks for high quality answers so far.

No. The general technique should work OK. Perhaps the Bluetooth can't handle more than 30 bytes before throwing in a newline of its own. In any case, why not use println rather than print and then supplying your own newline?

I tried with both println("...") and print("...\n"), same behavior with both. I hard coded the same outputs with Serial and Serial1 and it works fine so nothing to do with Bluetooth. It is something to do with the new class.

The Bluetooth link should see the exact same byte stream whether you print through Serial1 or this class. Only the timing will be slightly different, so it could be that whatever receives the data is sensitive to the timing of the incoming bytes. This could be mitigated by overriding virtual size_t write(const uint8_t *buffer, size_t size).

Should that look like this:     virtual size_t write(const uint8_t *buffer, size_t size) {         if (use_Serial) Serial.write(buffer, size);         if (use_Serial1) Serial1.write(buffer, size);         return 1;     }

I doubt the timing will matter. Those bytes will be buffered and sent out by an interrupt service routine.

The Bluetooth terminal might not recognize newlines. Can you prove it does?

Some LCD screens don't recognize newlines for example. You have to explicitly tell them to go to a new line and/or column.

@NickGammon. Update. If I insert a 100ms delay before using Serial1 the problem goes away. But that is not acceptable for the final program. The problem seems to be the same with direct use of Serial1 as it is with DualPrint so the original question is answered. A new question is how to control the position of new line characters in the Bluetooth terminal.

You can create a class derived from Print that forwards its output to
either or both Serial and Serial1. The only method you need to
implement for this to work is write(uint8_t):
class DualPrint : public Print
{
public:
    DualPrint() : use_Serial(false), use_Serial1(false) {}
    virtual size_t write(uint8_t c) {
        if (use_Serial) Serial.write(c);
        if (use_Serial1) Serial1.write(c);
        return 1;
    }
    bool use_Serial, use_Serial1;
} out;

You would use it like this:
out.use_Serial = true;
out.println("Printed to Serial only");
out.use_Serial1 = true;
out.println("Printed to both Serial and Serial1");
out.use_Serial = false;
out.println("Printed to Serial1 only");

Note that with this approach, unlike yours, printing number will format
them as text only once, and the underlying Serial and Serial1 will
only handle the resulting characters.

Edit: To answer the question in OP's comment, the construct
class ClassName
{
    ...definition...
} classInstace;

is a shotcut for
class ClassName
{
    ...definition...
};
ClassName classInstace;

A very similar construct exists in plain C:
struct struct_name {
    ...the struct fields...
} struct_instance;

for advanced users I would override availableForWrite() and flush() too

@Edgar Many thanks for this, very helpful. One request, I am more experienced at C than C++ so the class definition is unfamiliar. In the usage example out is an instance of DualPrint, is that right? How is it declared? DualPrint out;??

@HubertB: Yes, out is an instance of DualPrint. See expanded answer.

Edgar & @Juraj I have updated the question with a progress report on implementing the suggested solution. It works almost perfectly except for new lines in wrong sequence in BT terminal. Any suggestions? Is this related to flush() or other functions that also need to be re-implemented?

I have implemented this, thank you (in this case to write to a SD error file) and noticed that the Serial.write() is much slower on the serial monitor than Serial.print() - any reasons for this and is this an issue?

@CestLaGalere: No idea why. It would be difficult to answer that question without more details on what you are doing, and a minimal testable example.

Having created a sample that just logs to Serial there is no slowdown, the conclusion is that writing to the SD card to log to a file is still going on whilst trying to write the Serial data, slowing the Serial write down.  I am not sure if a worked example would therefore help as needs a SD card attached to the ESP to recreate. Thanks for the feedback

@CestLaGalere: It may well be the case that writing to the SD card is slow if done one character at a time, but is faster if a whole “message” is written at once. To test this idea you may want to implement virtual size_t write(const uint8_t *buffer, size_t size) in DualPrint that just does write(buffer, size) to the underlying streams. See if that speeds things up.

Thanks @edgar-bonet, that certainly seems to be the case, having implemented this it is much faster.


text:
green house vent servo based reading a sensor wrong
I am trying to make a green house vent that will open based on the temperature, however in my code the thermometer is not reading correctly, I've been designing it  in tinkercad and heres the link
https://www.tinkercad.com/things/fxhHvZCoqmQ
when the thermometer is on A0 i9t reads 14, if its on A3 it is 17.
I am very new at this so please help.

post your code in the question directly.

what is your question?

What is the problem with the code, because I can't see any problems.


text:
Sending data through esp8266 using arduino
I'm trying to send GPS data using esp8266 using Arduino board. I've used neo-6m receiver and esp8266-01 module. Below is my program using AT commands. The program is successfully compiled and loaded to the Arduino board, but the only output it gives on serial monitor is a simple begin. None of the AT commands are being executed. Not even the module connects to wi-fi. I can't point the error in my code. Please help me find the possible error.
Thank you

#include <TinyGPS++.h>
#include <SoftwareSerial.h>

TinyGPSPlus gps;

String ssid = "JioFi_244DB1D";

String password = "q52fq74c9s";

SoftwareSerial esp(6,7);

SoftwareSerial ss(8,9);

char Lat[12], Lon[12], alt[12],ch;

byte NOS;

byte l;

String webpage;

void reset(){

  esp.println("AT+RST");

  delay(1000);

  if(esp.find("OK"))

    Serial.println("Module Reset");

    }

    void ConnectWifi(){

      esp.println("AT+CIPMUX=1");

      esp.println("AT+CWMODE=1");

      String cmd = "AT+CWJAP=\""+ssid+"\",\""+password+"\"";

      esp.println(cmd);

      delay(4000);

      if(esp.find("OK"))

      Serial.println("Connected!");

      else {

        ConnectWifi();

        Serial.println("Connecting..");

        }

      }

void setup(){

  esp.begin(9600);

  Serial.begin(9600);

    Serial.println("begin");

  reset();

  ConnectWifi();

  esp.println("AT+CIFSR");

  while(esp.available()>0){

  if(esp.find("STAIP"))

  {Serial.println("IP Address:");

  while(esp.available()>0)

  {ch=esp.read();

  Serial.print(ch);}

  }}}

void loop() {

    ss.listen();

    delay(2000);

    while(ss.available()>0)

    {

    gps.encode(ss.read());

    {

      if(gps.location.isValid()){

           // dtostrf(gps.location.lat(),1,6,Lat);

      //dtostrf(gps.location.lng(),1,6,Lon);

      webpage = "<!DOCTYPE html><form method = \"post\" action =\"http://localhost/php/esppost.php\">Latitude:<\label><input type=number id = \"latitude\" name= \"latitude\" readonly value=";

        //                L = Lat.length();

      l= webpage.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(9+l+5);

      esp.println(webpage);

      esp.print(gps.location.lat(),6);

      esp.print("\">");

      delay(500);

      webpage = "Longitude:<input type = \"number\" id = \"Longitude\" name = \"Longitude\" readonly value =\"";
      l=webpage.length();

      //L = Lon.length();

      esp.println("AT+CIPSEND=0,");

                        esp.print(9+l+5);

      esp.println(webpage);

      esp.print(gps.location.lng(),6);

      esp.print("\">");

      }

      else

      webpage="Location Invalid";

      l=webpage.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(l+2);

      esp.println(webpage);

      delay(500);

      if(gps.altitude.isValid()){

      dtostrf(gps.altitude.meters(),1,6,alt);

      webpage = "Altitude:<\label><input type = number id=\"Altitude\" name=\"Altitude\" readonly value=";

      l=webpage.length();

      //L= alt.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(9+l+2);

      esp.println(webpage);

      esp.print(gps.altitude.meters(),6);

      esp.print("\">");

      }

     if(gps.satellites.isValid()){

        NOS= gps.satellites.value();

        webpage= "<lable for = \"NOS \"> Number of Satellites:<\label><input type=number id=NOS name= NOS readonly value =";

        l= webpage.length();

        esp.println("AT+CIPSEND=0,");

        esp.print(2+l+22);

        esp.println(webpage);

        esp.print(gps.satellites.value());

        esp.print(">");

        delay(500);

     }}

    esp.println("AT+CIPCLOSE");

      }
}

?do you have RX to TX for esp?

yes, m using the similar connections

write a minimal test sketch

thank you. I changed the baud rate to 115200 and now it's working well.

SoftwareSerial can't listen on two instances. There is a .listen() function to switch between SoftwareSerial instances.
The esp8266 AT firmware doesn't wait until you listen on the SoftwareSerial instance. If there is a connection to the server it sends +IPD and data. If the SoftwareSerial instance doesn't listen the information about client connection is lost.
You must listen to esp8266 all the time, so you can't use two SoftwareSerial instances.
You could use the RX pin of Uno to receive data from GPS module over hardware Serial.

I've made some changes to my program. I connected GPS Tx to Rx of my UNO board, replaced ss with Serial and removed ss.listen(). but still m getting the same result as before. Can you please suggest me what's the error I m still doing?

@user3185742, did this answer help? which interface's baud rate did you change?


text:
Locate devices that can move among multiple connections
I don’t know if this is even doable, but the idea is to have a large board with many (500+) locations where I objects can connect, each object having a single LED, and be able to illuminate the LED on any object, no matter where it is connected on the board.  So the requirement is that the objects can be moved to any of the connections on the board and and that the board can have any number if it’s connections occupied.
It seems obvious that each object would have to be able to identify itself and that each connection would have to be able to supply both a signal both ways and and provide power to light the LED.  On the code side, I’d need to be able to iterate through the connections and identify the desired object by some unique identifier and send a signal to turn the LED on and off.  I’m a .Net developer with little knowledge of electronics, but I’m willing to learn if it’s possible to do this.  I haven’t been able to find any arduino examples similar enough to provide some idea of where to start.  I don’t know if this is something that can even be done with Arduino or what components would be required if it is possible.
I’d appreciate any guidance on how this could be done or even suggestions as to what might be a better approach toward finding the guidance necessary to build this.

Please add some more requirements. Examples, max number of devices connected, power limit, total cost of device, more on the algorithm when connecting, timing of algorithm, respons time, etc. And last but not least, budget of project and max cost of board.

what is "the object" and what signal should it get? is it only some plastic shape with a LED that should be turned on and off?

are the objects addressable? . .. are the locations addressable?

Does the object (or main controller) need to know where it's pushed in? Your question is way too vague, but I was thinking of using audio sockets for the 500 locations and an audio jacks attached to the objects. Some of these jacks have ways to pass though a signal if no jack is inserted. So you could use Addressable LEDs in the objects, and have the sockets wired so the data goes to the led if the jack is inserted, or pass though if not.

The "objects" could be anything - even a block of wood.  Anything that would serve as an object upon which I could mount whatever components that would allow me to   flash an LED on the object no matter where it was located on the board.  I would need to have boards of various sizes, each having a different number of potential locations in a grid layout upon which these objects could be placed and moved from one location on the board to another.  I would need some means of being able to flash the LED of a specific block no matter where that block was attached on the board.

is LED "the object" or "the object" can have two LEDs and a temperature sensor. do you want to create a LED matrix or a network of sensor nodes?

Your question is awfully vague.
There is a protocol called I2C that's commonly used for microcontrollers. It's a serial bus that has a data line, a clock line, power, and ground. That might meet your needs.
Each device on an I2C bus is supposed to have a unique address. You send commands to it using that address, and it doesn't matter where it is located physically.
I2C is designed to be a chain, and each device has 2 connectors that pass the connection on to the next device on the chain.
I2C also uses a byte address, so you could only have 255 unique devices.

This sounds promising except that I would need more than 255 potential addresses.  I would need to be able to have a boards with grids of up to 100 columns and 50 rows where objects could be attached, so such a board would have to be able to support up to 5,000 objects with LEDs that could each be individually flashed no matter where they were on the board.


text:
Problem Writing/Reading EEPROM on MEGA
I want to make a program that writes on the EEPROM some structs, the final device will take structs of RGB LED data:

typedef struct{
    unsigned char r;
    unsigned char g;
    unsigned char b;
} led_color;

I will have 16 LEDS and I need to keep the RGB data of each LED despite of powering off the Arduino, I have developed this functions:
void getColorValuesFromEEPROM(led_color *colorStructArray) { // Here I need to read all the data and store it in an array of structs with 16 positions
  int eedirection = 0;
  int i = 0;
  while (eedirection <= 16 * sizeof(led_color)) {
    EEPROM.get(eedirection, color[i]);
    i++;
    eedirection *= i * sizeof(led_color);
  }
}

void getSingleColorValueFromEEPROM(led_color *sing_color) { //Here I want to read only one struct that is stored in an arbitrary position(3700) the position could be anyone that doesn't interferes with the array data
  EEPROM.get(3700, sing_color);
}

void writeColorValuesToEEPROM(unsigned char led_number, led_color *color) { //Here I need to write the struct data of the led_number given(from 1 to 16);
  int eedirection;
  eedirection = led_number * sizeof(led_color);
  EEPROM.update(eedirection, color);
}

void writeSingleColorValueToEEPROM(led_color *single) { //Here I want to write only one struct of data in the arbitary direction(3700)
  EEPROM.update(3700, single);
}

The problem is that my Arduino freezes when I try to read/write data with the functions above, here I paste the full code, it freezes in the setup():
ddj.c
#include "ddj.h"
#include <EEPROM.h>
#include <RotaryEncoder.h>
#include <MIDI.h>
#include <Adafruit_NeoPixel.h>

#define DATA_PIN 6  //DATA PIN OF THE RGB LEDS

#define runEvery(t) for (static uint16_t _lasttime;\
                         (uint16_t)((uint16_t)millis() - _lasttime) >= (t);\
                         _lasttime += (t))

RotaryEncoder encoder(18, 19); //Encoders are connected to pins 18-19 and 2-3 (A and B of each encoder)
RotaryEncoder encoder1(20, 21);
Adafruit_NeoPixel strip = Adafruit_NeoPixel(16, DATA_PIN, NEO_GRB + NEO_KHZ800);

MIDI_CREATE_DEFAULT_INSTANCE();

led_color color[16];
led_color single_color;
unsigned char ledMode = 0;
bool ledState = LOW;
unsigned int interval = 500; //Interval in milliseconds of the Led Blinking mode
int potenciometro[6] = {A0, A1, A2, A3, A4, A5};  //The potentiometers are connected to A0, A1, A2 and A3
int valpot[6] = {0, 0, 0, 0, 0, 0};
int lastval[6] = {0, 0, 0, 0, 0, 0};
bool state[44] = {0};
bool laststate[44] = {0};

void getColorValuesFromEEPROM(led_color *colorStructArray) {
  int eedirection = 0;
  int i = 0;
  while (eedirection <= 16 * sizeof(led_color)) {
    EEPROM.get(eedirection, color[i]);
    i++;
    eedirection *= i * sizeof(led_color);
  }
}

void getSingleColorValueFromEEPROM(led_color *sing_color) {
  EEPROM.get(3700, sing_color);
}

void writeColorValuesToEEPROM(unsigned char led_number, led_color *color) {
  int eedirection;
  eedirection = led_number * sizeof(led_color);
  EEPROM.update(eedirection, color);
}

void writeSingleColorValueToEEPROM(led_color *single) {
  EEPROM.update(3700, single);
}

void setLedMode(unsigned char n) { // 0 - All On; 1 - All Off; 2 - Blink With Delay; 3 - On When Pressed
  ledMode = n;
}

void setSingleLed(unsigned char led_number, led_color colorStructArray) {
  strip.setPixelColor(led_number, colorStructArray.r, colorStructArray.g, colorStructArray.b);
  strip.show();
}

void setAllLeds(unsigned char mode) { // 0 - All On; 1 - All Off;
  if (mode = 0) {
    for (int i = 0; i < 16; i++) {
      strip.setPixelColor(i, single_color.r, single_color.g, single_color.b);
      strip.show();
    }
  } else if (mode = 1) {
    for (int i = 0; i < 16; i++) {
      strip.setPixelColor(i, 0, 0, 0);
      strip.show();
    }
  }
}

void pushbuttonsRead() {
  for (int i = 2; i < 14; i++) {
    state[i + 30] = digitalRead(i); //This statement read the state of the digital pin
    if (state[i + 30] != laststate[i + 30]) { //This two if conditionals make the interrupt and "debounce" the button so it only will send data when the state changes, and that state is LOW
      if (state[i + 30] == 0) {
        MIDI.sendNoteOn(i + 30, 127, 1); //This send the MIDI data---  NOTE 56, VELOCITY 127, CHANNEL 1
      }
    }
    laststate[i + 30] = state[i + 30];
  }
  for (int i = 22; i < 54; i++) { //32 BUTTONS
    state[i - 22] = digitalRead(i); //This statement read the state of the digital pin
    if (state[i - 22] != laststate[i - 22]) { //This two if conditionals make the interrupt and "debounce" the button so it only will send data when the state changes, and that state is LOW
      if (state[i - 22] == 0) {
        MIDI.sendNoteOn(i - 21, 127, 1); //This send the MIDI data---  NOTE 56, VELOCITY 127, CHANNEL 1
        if ((ledMode == 3) && (i >= 22 && i <= 38)) {
          setSingleLed(i - 22, color[i - 22]);
        }
      }
    }
    laststate[i - 22] = state[i - 22];
  }
}

void potentiometersRead() {
  for (int i = 0; i < 6; i++) {   //Here you read the potentiometers data, convert them from 10 bit(Arduino's ADC read resolution) to 7 bit (MIDI protocol resolution) and send them
    valpot[i] = analogRead(potenciometro[i]) >> 3;
    if (valpot[i] != lastval[i]) {
      MIDI.sendControlChange(i + 1, valpot[i], 1);
    }
    lastval[i] = valpot[i];
  }
}

void setup()
{
  //MIDI.begin(MIDI_CHANNEL_OMNI);  //Here the MIDI communication starts
  strip.begin();
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  for (int i = 30; i < 46; i++) {
    pinMode(i, INPUT_PULLUP);  //Set the pushbuttons pins as input with a PULLUP resistor
  }
  getSingleColorValueFromEEPROM(&single_color);
  //getColorValuesFromEEPROM(color);
}

void loop()
{
  if (ledMode == 0 || ledMode == 1) { //ALL ON AND ALL OFF MODES
    setAllLeds(ledMode);
  } else if (ledMode == 2) { //BLINK WITH DELAY MODE
    runEvery(interval) {
      if (ledState == LOW) {
        ledState = HIGH;
      }
      else {
        ledState = LOW;
      }
      setAllLeds(ledState);
    }
  }

  pushbuttonsRead();

  potentiometersRead();

  static int pos = 60;
  encoder.tick();

  int newPos = encoder.getPosition(); //Here you read the encoder position and if it has changed from the last time, you send it
  if (pos != newPos) {
    if (pos < newPos) {
      MIDI.sendControlChange(15, 1, 2);
    } else if (pos > newPos) {
      MIDI.sendControlChange(15, 127, 2);
    }
    pos = newPos;
  }
  static int pos1 = 60;
  encoder1.tick();

  int newPos1 = encoder1.getPosition();
  if (pos1 != newPos1) {
    if (pos1 < newPos1) {
      MIDI.sendControlChange(16, 1, 2);
    } else if (pos1 > newPos1) {
      MIDI.sendControlChange(16, 127, 2);
    }
    pos1 = newPos1;
  }
}

ddj.h
typedef struct{
    unsigned char r;
    unsigned char g;
    unsigned char b;
} led_color;

void getColorValuesFromEEPROM(led_color colorStructArray[]);

void getSingleColorValueFromEEPROM(led_color *sing_color);

void writeColorValuesToEEPROM(unsigned char led_number, unsigned char red, unsigned char green, unsigned char blue);

void writeSingleColorValueToEEPROM(unsigned char red, unsigned char green, unsigned char blue);

void setLedMode(unsigned char n);

void setSingleLed(unsigned char led_number, led_color colorStructArray[]);

void setAllLeds(unsigned char mode);

void pushbuttonsRead();

you can do EEPROM.put(0, color); and EEPROM.get(0, color); where color is your array of structs

I can not find code that freezes. I can not find stack overflow or array out of bounds. There is something going on with EEPROM.get. You may not use a pointer there, only a full variable/struct/anything because it uses the size of that full variable/struct/anything. The color[i] might work but not the led_color *. Something else is perhaps a voltage drop when the led strip is initialized. What is the voltage of the 5v pin?


text:
Arduino RS485 shield to RS485 temperature & humidity sensor
I’m try to get data from rs485 is not work please advise to me.
1.  Try to connect PC usb485 to DY-MD02 is work.
    Send command “AUTO” or “READ”

2.  Try to Arduino rs485 shield to DY-MD02 is not work.
    Send command “AUTO”

my code
''''
char command[4] = {'A', 'U', 'T', 'O'};

int n = sizeof(command)/sizeof(command[0]);   // Number of elements in an array

String incoming = "";   // for incoming serial string data

void setup()

{

      // initialize serial ports
      Serial.begin(9600);
      pinMode(EN,OUTPUT);
      digitalWrite(EN,HIGH); //Enable high, RS485 shield waiting to transmit data
      Serial.write(command,n); //Test send command Auto,Read to RS485
      delay(500);
}

void loop()

{

      String temp;
      digitalWrite(EN,LOW); //Enable low, RS485 shield waiting to receive data

      while(Serial.available() > 0 )
      {
          temp=Serial.read();
          Serial.println(temp);
          delay(1000); //Delay for some time, waiting for data transmitted
      }

}

''''

if change code to = Serial.readString() not show anything.
please help me
Thank

to Juraj
Maker tell me can connect with Arduino uno and send manual to me.
see in attach file.

exact model or datasheet of shield please? does it communicate with Uno over hardware Serial?

model of the shield?

it looks like your serial input doesn't provide end of line characters (\r\n) at the end. readString function fetch the character value step by step and store them in buffer till EOL character are received. After receiving EOL character it returns the string.

@Vaibhav, readString doesn't care about line ends. it returns after timeout

I want details about the RS485 shield

To Juraj = https://github.com/DFRobot/DFRobotMediaWikiMarkDown/wiki/Arduino_RS485_Shield_SKU__DFR0259

your shield on the photo is different

i'm tray change this code to readStringUntil, is OK
if(Serial.available() > 0)
  {
    temp = Serial.readStringUntil('\n');
    Serial.println(temp);
    delay(1000); //Delay for some time, waiting for data transmitted
  }

Thank all for help me
^^

I will suggest try to use Modbus Master library it will help you get the data from sensor. The issue with the code is you are only sending the command but while interfacing with modbus there is a packet/ frame which you need to form and then send it the packet/frame format is in the below diagram
I will prefer use an Arduino Mega or other arduino which have more than 1 Serial port for communication. I also faced a similar issue but it was resolved after digging a little bit you can have a look at the issue here


text:
Creating WebServer ip:port on esp8266 module
I creating Clever House with wifi. For this I'm using ESP8266 as module connected to Arduino. They communicate with SoftwareSerial. And there's a problem with global webserver on ESP8266. That I think to do it I must do this:
1.Create Webserver on another port(Neither 80 nor 443) Or Host will be in this model: https://ip:port/
2.Open port forwarding for port.
3.Almost done.
So how can I do it with AT commands?

http://www.martyncurrey.com/arduino-esp8266-web-server/

Thanks a lot. But this is not solvution of my problem. I want to start webserver and its url should be for example 192.168.0.102:5000 -> ip:port

AT+CIPSERVER=1,5000. IP is IP of the esp8266, reserve it on router or use the AT command to set static IP

what exactly is step number three?

Nothing :) step 3 is nothing

THANKS!! It worked

As @Juraj mentioned, martyncurrey.com/arduino-esp8266-web-server , I need to start server with command: AT+CIPSERVER=1,5000, IP is IP of the esp8266 and reserve it on router or use the AT command to set static IP.


text:
Run a loop for only 60 secondes
How do run a code on arduino for only 60 secondes and than shut it down? I know I have to use the millis() function, but I do not know how to it in my code. Sorry if it looks unclear, but I only need to know how to program the millis() function. This is my first code so I have no experience.
int main(void)
{
pin_mode(A13,INPUT);
pin_mode(A12,INPUT);
pin_mode(A11,INPUT);
pin_mode(A10,INPUT);
pin_mode(A15,INPUT);
pin_mode(D0,OUTPUT);
pin_mode(D1,OUTPUT);
pin_mode(D2,OUTPUT);
pin_mode(D3,OUTPUT);

while (1)
{
    int potmeter1 = read_analog_pin(A13);
    if (potmeter1 >= 1000 && potmeter1 < 1100){
    gen_pwm(D0, 1000, 100);

        int potmeter2 = read_analog_pin(A12);
        if (potmeter2 >= 2000 && potmeter2 < 2050){
        gen_pwm(D1, 1000, 100);

            int potmeter3 = read_analog_pin(A11);
            if (potmeter3 >= 500 && potmeter3 < 525){
                gen_pwm(D2, 1000, 100);

                    int potmeter4 = read_analog_pin(A10);
                    if (potmeter4 >= 3500 && potmeter4 < 3510){
                        gen_pwm(D3, 1000, 100);

    {
        int lichtsensor = read_analog_pin(A15);
        if (lichtsensor >= 2000 && lichtsensor < 3500 && potmeter1 >= 1000 && potmeter1 < 1100 && potmeter2 >= 2000 && potmeter2 < 2050 && potmeter3 >= 500 && potmeter3 < 525 && potmeter4 >= 3500 && potmeter4 < 3510){
            gen_pwm(D0, 1000, 100);
            gen_pwm(D1, 1000, 100);
            gen_pwm(D2, 1000, 100);
            gen_pwm(D3, 1000, 100);
            _delay_ms(250);
            gen_pwm(D0, 1000, 0);
            gen_pwm(D1, 1000, 0);
            gen_pwm(D2, 1000, 0);
            gen_pwm(D3, 1000, 0);
            _delay_ms(250);

        }
    }
                }else{
                gen_pwm(D3, 1000, 0);
                }
            }else{
            gen_pwm(D3, 1000, 0);
            gen_pwm(D2, 1000, 0);
            }
        }else{
        gen_pwm(D3, 1000, 0);
        gen_pwm(D2, 1000, 0);
        gen_pwm(D1, 1000, 0);
        }
    }else{
    gen_pwm(D3, 1000, 0);
    gen_pwm(D2, 1000, 0);
    gen_pwm(D1, 1000, 0);
    gen_pwm(D0, 1000, 0);
    }

                }
            }

I have merged my program with your program and I have added the #include "Arduino.h". The millis() function is colored now and works. My code still won't stop at 60 secondes, did I do something wrong?
#include "hva-xmega.h"
#include "Arduino.h"

unsigned long EndTime;

void setup()
{
    pin_mode(A13,INPUT);
    pin_mode(A12,INPUT);
    pin_mode(A11,INPUT);
    pin_mode(A10,INPUT);
    pin_mode(A15,INPUT);
    pin_mode(D0,OUTPUT);
    pin_mode(D1,OUTPUT);
    pin_mode(D2,OUTPUT);
    pin_mode(D3,OUTPUT);

    EndTime = millis() + (60*1000L);
}

void loop() {
    if( millis() < EndTime ){

while (1)
{
    int potmeter1 = read_analog_pin(A13);
    if (potmeter1 >= 1000 && potmeter1 < 1100){
        gen_pwm(D0, 1000, 100);

        int potmeter2 = read_analog_pin(A12);
        if (potmeter2 >= 2000 && potmeter2 < 2050){
            gen_pwm(D1, 1000, 100);

            int potmeter3 = read_analog_pin(A11);
            if (potmeter3 >= 500 && potmeter3 < 525){
                gen_pwm(D2, 1000, 100);

                int potmeter4 = read_analog_pin(A10);
                if (potmeter4 >= 3500 && potmeter4 < 3510){
                    gen_pwm(D3, 1000, 100);

                    {
                        int lichtsensor = read_analog_pin(A15);
                        if (lichtsensor >= 2000 && lichtsensor < 3500 && potmeter1 >= 1000 && potmeter1 < 1100 && potmeter2 >= 2000 && potmeter2 < 2050 && potmeter3 >= 500 && potmeter3 < 525 && potmeter4 >= 3500 && potmeter4 < 3510){
                            gen_pwm(D0, 1000, 100);
                            gen_pwm(D1, 1000, 100);
                            gen_pwm(D2, 1000, 100);
                            gen_pwm(D3, 1000, 100);
                            _delay_ms(250);
                            gen_pwm(D0, 1000, 0);
                            gen_pwm(D1, 1000, 0);
                            gen_pwm(D2, 1000, 0);
                            gen_pwm(D3, 1000, 0);
                            _delay_ms(250);

                        }
                    }
                    }else{
                    gen_pwm(D3, 1000, 0);
                }
                }else{
                gen_pwm(D3, 1000, 0);
                gen_pwm(D2, 1000, 0);
            }
            }else{
            gen_pwm(D3, 1000, 0);
            gen_pwm(D2, 1000, 0);
            gen_pwm(D1, 1000, 0);
        }
        }else{
        gen_pwm(D3, 1000, 0);
        gen_pwm(D2, 1000, 0);
        gen_pwm(D1, 1000, 0);
        gen_pwm(D0, 1000, 0);
            }
        }
    }
}
 else {
     // Time is up! Hang here
     for(;;)
     ;      // infinite loop here stops further processing
    }
 }

look at the BlinkWithoutDelay example code in the Arduino IDE

It doesn't look like you are using an Arduino core. What framework are you using? Does it provide something similar to millis()?

note: the long if statement is unnecessarily long ... you are testing values that were tested already

My university designed his own board, but it uses a atxmega256a3u microcontroller. I do not know if it provide something similar as millis().

@DennisdeKruijf, it is not Arduino. it is a proprietary board and library. we can't help you

I can use the same libraries as arduino so I think it's about the same idea. But maybe I am wrong. I am using C to program with the program Atmel Studio and it look like the same environment as arduino.

Your indentation is completely messed up, and it would seem you have unbalanced braces.

Note that in an Arduino environment, main() is already provided for you. It calls your function void setup(void){ ... } once, then loops forever, calling your function void loop(void){ ... }. Either function may be empty but both must be present.
Without going into the specifics of your code, here is a program that fits the Arduino conventions, and will execute some procedure for 60 seconds, then hang, doing nothing:
unsigned long EndTime;

void setup()
{
   // Any setup code you need goes here.

   EndTime = millis() + (60*1000L);
}

void loop() {
   if( millis() < EndTime ){
      // Do your processing here
   }
   else {
      // Time is up! Hang here
      for(;;)
         ;      // infinite loop here stops further processing
   }
}

My setup codes are the pin_modes right? and everything below is my
  processing?

Update:
Correct - Put pin modes and anything else that needs to be done once, at the beginning of the run in setup(). Everything else goes in loop().
Or if you're more comfortable writing your entire program starting with main() (as we do in other environments than Arduino), you can use the setup() function exactly as you would use main(), and leave loop() empty. The idea of a loop function is that embedded programs are typically not meant to end as long as the device has power. There are instances when this isn't strictly true and you seem to have one example.

I have
  to remove the int main(void) from my code when I use your code right?

Correct - the Arduino environment provides a main() function, so writing your own - within that environment - would result in a multiple-definition error.
Update 2:
"WProgram.h" is obsolete. Instead, use: #include <Arduino.h>. There is no function called elapsedMillis(), just millis(). You won't need an include statement for it, or any of the other standard or common stuff: Serial I/O, digital I/O, analog I/O, pin definitions for specific boards, etc. 'Arduino.h' pulls in all that stuff. Your university should have add a description of the proprietary board to the Arduino's board description file.
(But if you/they are not using standard Arduino libraries, board descriptions, etc., then there is a lot of behind-the-scenes "housekeeping" you may be responsible for. That isn't something we can know; you may have to ask those kinds of questions of others more familiar with your university's programming environment. I think it is unlikely they would abandon the existing/working resources, but it's something to keep in mind.)

Alternatively, if (millis() >= 60000) exit(0);.

My setup codes are the pin_modes right? and everything below is my processing? I don't have much knowledge about programming ^^ . I have to remove the int main(void) from my code when I use your code right? @JRobert

problem is, it is not Arduino, so the answer is not applicable

I have done exactly what you said and my program still works fine, except the millis() function. I have added the #include "elapsedMillis.h" library, but the millis() function stays as a normal text, so my program doesn't stop after the 60 secondes. Furthermore it can't find the WProgram.h: file or directory. Do you maybe know how to fix that? @JRobert


text:
Arduino Uno does not detect the GPS module
I am trying to start the GLONASS NEO-7M-C module using TinyGPS++ liblary, but in the serial monitor I receive a message all the time that the module is not detected.
My connection:

PPS - None
RX - 4
TX - 3
GND - GND
VCC - 5V

is RX wired to TX?

What exactly do you mean? I connected the RX to pin 4 and TX to pin 3

Don't post screen shots of your code, post it within your question.

but 4 is RX of SoftwareSerial in your code or not? so receive to receive, transmit to transmit?

Yes you are right. Everything works well already. Thank you for your help!


text:
External Interrupt Pins on Nano Clones
Long time lurker, first time poster here.
Do the cheap Arduino Nano clones such as this one have external interrupt pins?
For example, the original Nano has pins 2 and 3 usable for interrupts. Do clones tend to incorporate this feature? If so, can anyone recommend one which does?
I'm planning on using an encoder for my next project and want to make sure I can use interrupts so my code doesn't skip over encoder counts.
Thank you!

I understand your doubt. In a world where Uno WiFi i not Uno it is better to ask. And the Wawgat boards which are named Uno but use a different 8-bit MCU are a trap too.
The Nano in your link has Atmega 328p and interrupts are a feature of the MCU. There is no reason for the clone manufacturer to not use the standard Nano pinout as specified in Open Hardware Nano schematics. Then the board is compatible with Arduino Nano as defined in Arduino AVR boards package.
The clones usually use a cheaper chip for USB. You will maybe need to install a driver for the CH340.
In a few days Nano Every will be available and I expect clones of it in a short time because it is a very simple board. It will use the ATmega 4809 and Arduino advertises exact pin compatibility with old Nano. But I expect in details problems similar to Uno WiFi R2 versus classic Uno problems. One of the problems could be the mapping of interrupt pins.
And later this year Nano 33 will be released. It is a Nano format board with SAMD or nRF52 MCU so 3.3 V (the 33 in name).


text:
Error with AT+CIPSEND in ES8266 with arduino
I'm making simple web-server on esp8266 module connected to Arduino. And when +IPD,0,GET... I'm sending AT+CIPSEND=0,16. Then I write HELLOMYDEARFRIDE.
It says : send 16 bytes recived. OK. But in browser it says me that server haven't given any right response. What is problem in?
Code:
#include <SoftwareSerial.h>

SoftwareSerial softSerial(10, 11);
String ssid = "***";
String password = "***";
String _response = "";
#define DEBUG true
void setup()
{

  Serial.begin(115200);

  softSerial.begin(115200);
  connectWifi();
}

void connectWifi() {

  do {
    sendData("AT+RESTORE\r\n", 5000, DEBUG);
  } while (softSerial.find("OK"));
  do {
    sendData("AT\r\n", 2000, DEBUG);
  } while (softSerial.find("OK"));
  do {
    sendData("AT+CWMODE=1\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));
  do {
    sendData("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"\r\n", 5000, DEBUG);
  } while (softSerial.find("OK"));

  do {
    sendData("AT+CIFSR\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));
  do {
    sendData("AT+CIPMUX=1\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));
  do {
    sendData("AT+CIPSERVER=1,5000\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));

}

String sendData(String command, const int timeout, boolean debug)
{

  String response = "";

  softSerial.print(command);        long int time = millis();
  while ((time + timeout) > millis())
  {
    while (softSerial.available())
    {
      char c = softSerial.read();
      response += c;
    }
  }

  if (debug)
  {
    Serial.print(response);
  }

  return response;
}
int connectionId,pin;
void loop()
{
    if (softSerial.available()) {
    Serial.write(softSerial.read());
  }
  if (Serial.available()) {
    softSerial.write(Serial.read());
  }

}

what is the browser expecting to receive?

Google Chrome is expecting reciving

you misunderstand what i asked .... the browser expects the web page to have a specific format .... investigate what the required format is ..... start by saving a simple web page to your computer and then examine the saved file with a text editor

you must return a valid HTTP protocol response

Browser receive a "Hello World!" as html code. And it can be showed as page.

Juraj how can I do It?

"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n" but you need to send this line by line (without \r\n) if you send it from Serial Monitor

Thank you. Juraj it didn't worked.


text:
LED array flashes once before being lit
I've built this simple Arduino controlled led-array. The Arduino sets a 5v pin on a relay to connect the high current power supply to a led array.
However, just before the led array is being fully turned on I'm getting this fast flash of the led array. I really would like to have the led working in an "on/off" manner.

I remember that working with some motors one have to use capcitator in parallel because of resistence drop. Is it also the case with led array? And if it is why so, and why a capcitator would help?
Thank you very much.

Does this flash only happen once each time the Arduino is 'booted'? If so, the issue may be the "power on" disposition of the Arduino pin that allow the LEDs to come on for a bit before the Arduinos pin is "configured".

Hi Wendeall,
No it happens every time to pin connected to the realy is set to "HIGH".

What led array are you using? What power supply are you using for this array?

The relay information shows this relay requires over 70ma to latch at 5 volts. The Arduino can only -maybe- provide half of that. Why it is working at all I don't know. Just as  Duncan C suggested, you are going to have to use a driver circuit (there are many designs, search for "Arduino relay driver") to correctly operate the relay. Then the "flash" will probably go away too.

Don't you use the matrix' SPI? If so, how do you know that it is supposed to work without, have you tried? Even if it's simple code you should add it, so we don't have to guess if there are mistakes. Also a link to the led matrix might be helpful

As Wendall says in his comment, you probably have an issue with the power-on state of your logic pins before the Arduino finishes booting up.
In addition to that, you should not drive a relay directly from an Arduino logic pin, for a couple of reasons:

It can't provide enough current to drive a relay coil.
The relay emits a strong surge of reverse current when you switch it off. This will likely destroy the logic pin you are using to drive the relay, or it might even destroy the whole Arduino board.

For these reasons you should drive the relay using a transistor, and you should put a properly sized diode wired across the relay coil backwards from the flow of current when the relay is energized. The diode bleeds off the reverse current from the relay coil.

Thanks a lot Duncan.
I'm using this relay:
http://www.circuitbasics.com/wp-content/uploads/2015/11/SRD-05VDC-SL-C-Datasheet.pdf
Which suppose to be activated using a 5V pin. I would definitely try adding a diode to stop the reverse current.
However, the fast blink happens every time I close the relay circuit (turn on the led). There's one fast blink before the led is being activated.

Ok, it sounds like you're using a "solid state relay", which has built-in circuitry to drive the relay coil from a low power logic line, while protecting the logic line from the "raw" relay. (If so it might have a transistor and protection diode in it already.) You might want to edit your question and post details on the type and setup of the relay you're using.


text:
Unexpected results when creating 32-bit int from byte array
I'm having problems creating a 32-bit integer from a 4-byte array. In the following complete, minimal, and verifiable example, converting a byte array containing 0x00, 0x04, 0x04F, 0x45 results in 4F45 (expected result would be 44F45). I must be overlooking something fundamental here.... can anyone see where I went wrong?
void setup()
{
    Serial.begin(9600);
    while(!Serial);
}

void loop()
{
    uint8_t bytes[4] = {0x00, 0x04, 0x4F, 0x45}; //00044F45
    int32_t theInt = byteArrayToInt32(bytes);
    Serial.println(theInt, HEX); //Print 4F45
    delay(250);
}

uint32_t byteArrayToInt32(uint8_t* bytes)
{
    uint32_t i = 0;
    i |= bytes[0] << 24;
    i |= bytes[1] << 16;
    i |= bytes[2] << 8;
    i |= bytes[3];
    return i;
}

@jsotola in what way?

@jsotola I went ahead re-tested with it as uint32_t, no difference :(

The problem is that you are trying to shift uint8_t more than 8 bits and then OR it with int32_t.
You have to cast the uint8_t to int32_t before doing the shift.
void setup()
{
    Serial.begin(9600);
    while(!Serial);
}

void loop()
{
    uint8_t bytes[4] = { 0x00, 0x04, 0x4F, 0x45}; //00044F45
    int32_t theInt = byteArrayToInt32(bytes);
    Serial.println(theInt, HEX); //Print 4F45
    delay(1000);
}

int32_t byteArrayToInt32(uint8_t* bytes)
{
    int32_t i = 0;
    i |= (int32_t) bytes[0] << 24;
    i |= (int32_t) bytes[1] << 16;
    i |= (int32_t) bytes[2] <<  8;
    i |= (int32_t) bytes[3];
    return i;
}

Note that if the most significant bit of bytes[0] is set, then (int32_t) bytes[0] << 24 will shift it into the sign bit, which is undefined behavior. It is safer to cast to a uint32_t, which can in turn be safely assigned to an int32_t.

Hmm, so doing as you suggested fixes the problem, however I'm very perplexed as to why the left shift by 8 bits worked originally, then?

it appears that the left shift function uses a 16 bit buffer .... possibly because it uses the same code for 16 bit shifts


text:
Calculate pullup resistor, cat5e ftp
let me describe my schema, i got one arduino and one esp32 connected over i2c using 30m cat 5e ftp cable, I'm using 12v to power up both devices, each of them have dc-dc converter that convert to 5V, there is two P82B715P extenders, controllers i2c bus is wired with 10K pullups to P82B715P , i2c bus between P82B715P is wired with 1K pullups on master device side. On 30M cable it works only if I transmit SDA, SCL in twister pair with ground, no power voltage (+12V) is on the cable. When I place +12V on the cable, I2C bus stop working, tried to decrease pullups to 0.4K no effect, since I do not understand can only make try/fail tests. Question is do I need to adjust pullups beween P82B715P only,  or I need to change pullups between P82B715P and esp/arduino? Perhaps for calculation of pullups I must mention that i2c bus work on 10KHz

Can you post a schematic? Your question is a little hard to understand. Help us to help you. :)

Well I do not have schematic, gonna try to draw one later

Check VCC and pullup calculation. http://www.ti.com/lit/ds/symlink/p82b715.pdf

Using the formula and the remark in the datasheet (8.1.1), I get between 330 and 660 Ohm for the 30m cable. Are you getting a stable 5V on the otherside of the cat5 cable; from the dc-dc converter?

yes voltage is stable, just I2c not working if +12V is on same cable where data is.

you run the 12 V twisted with SDA?

I tried all combination, with GND with 12V nothing make it work, and decide to stop trying and go to RS485

@user3503519 did you put adequate capacitors on the 12V line, on both sides? This looks like interference between the 12V noise and the data wires..

DC DC convertors include capacitors


text:
Start / end events using milis
I want to start a relay, have it run for 3 seconds, stop for 10 seconds, repeat.
I can't use delay, because I have a motor driver starting / stopping every 100 milis.
So I put together this code, but it does not work. Any help appreciated.
There's a 500ms delay to stop too much debugging info.
Also for some reason, tenSecondsBool switches to true as soon as you run the code.
unsigned long threeSeconds=3000; // the time we need to wait
unsigned long threeSecondsMillis=0; // millis() returns an unsigned long.
unsigned long fourSeconds=7000; // the time we need to wait
unsigned long fourSecondsMillis=0; // millis() returns an unsigned long.

unsigned long previousMillis=0; // millis() returns an unsigned long.
bool ledState = false; // state variable for the LED
bool led2State = false; // state variable for the LED
unsigned long tenSecondMilis=0; // millis() returns an unsigned long.
unsigned long tenSeconds=10000; // the time we need to wait

unsigned long paliGasiMilis=0; // millis() returns an unsigned long.
unsigned long paliGasi=1000; // the time we need to wait

unsigned long ventMilis=0; // millis() returns an unsigned long.
unsigned long ventInt=100; // the time we need to wait

bool threeSecondBool = false;
bool tenSecondBool = false;

int Fin1 = D7;

#define enA D1
#define in1 D2
#define in2 D3
#define button 4

int rotDirection = 0;
int pressed = false;

void setup() {
  Serial.begin(9600); // send and receive at 9600 baud
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(button, INPUT);
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  pinMode(Fin1, OUTPUT);
  digitalWrite(Fin1, HIGH);
  threeSecondBool = false;
  tenSecondBool = false;
}

void loop() {

 unsigned long currentMillis = millis(); // grab current time

 if ((unsigned long)(currentMillis - tenSecondMilis) >= tenSeconds) {
    Serial.print("---------------\n");
    Serial.print("10 second end\n");
    Serial.print("---------------\n");
    tenSecondBool = true;
    tenSecondMilis = millis();
}

Serial.print("10 second bool = ");
Serial.print(tenSecondBool);
Serial.print("\n");
Serial.print("3 second bool = ");
Serial.print(threeSecondBool);
Serial.print("\n");

 if (tenSecondBool) {
  if ((unsigned long)(currentMillis - threeSecondsMillis) >= threeSeconds) {
   Serial.print("---------------\n");
   Serial.print("3 second end\n");
   Serial.print("---------------\n");
   threeSecondBool = true;
   threeSecondsMillis = millis();
  }
 }

if (!tenSecondBool && threeSecondBool){
  Serial.print("Both triggered!\n");
  digitalWrite(Fin1, HIGH);
}

if (!tenSecondBool && !threeSecondBool){
  Serial.print("Both triggered!\n");
  digitalWrite(Fin1, HIGH);
}

if (tenSecondBool && threeSecondBool){
  threeSecondBool = false;
  tenSecondBool = false;
  digitalWrite(Fin1, LOW);
}

delay(500);

  if ((unsigned long)(currentMillis - ventMilis) >= ventInt) {
    digitalWrite(in1, HIGH);
    digitalWrite(in2, LOW);
    ventMilis = millis();
  } else {
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
  }

}

If you want a timer with millis with different intervals, then you can change the interval.
I use the Blink Without Delay to start with, and I borrow the 'relay_is_on' from the answer by Edgar Bonet.
unsigned long previousMillis;
unsigned long interval;
bool relay_is_on;

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    if (relay_is_on) {
      // Relay was on, now turn it off.
      interval = 10000;
      digitalWrite (relayPin, LOW);
      relay_is_on = false;
    } else {
      // Relay was off, now turn it on.
      interval = 3000;
      digitalWrite (relayPin, HIGH);
      relay_is_on = true;
    }
  }
}

The global variables can be set to a value to start with (for example 3000 for the interval) or they can be set in the setup() function. You have to choose what you want to start with. For example one second or one minute delay before it starts is also possible.

Your code is somewhat confusing, probably because it has too many
variables. For doing what you describe, the program only needs to
remember two things:

is the relay in the ON state or in the OFF state?
when was the last time the relay changed state?

These can be represented as follows:
bool relay_is_on = false;
unsigned long last_relay_change = 0;

Then, I recommend you use descriptive names for your variables and
constants. Calling a constant threeSeconds is not useful. It has no
added value over just typing 3000. Having the constant named
RELAY_ON_TIME makes it a lot clearer what it is intended for. It is a
common convention to name the constants with all caps to make them stand
out relative to variables:
const uint8_t RELAY_PIN = ...;
const unsigned long RELAY_ON_TIME  =  3000;  //  3 s ON
const unsigned long RELAY_OFF_TIME = 10000;  // 10 s OFF

With this in place, periodically switching the relay on and off can be
achieved as follows:
void loop()
{
    unsigned long now = millis();
    if (relay_is_on && now - last_relay_change >= RELAY_ON_TIME) {
        // Turn off.
        digitalWrite(RELAY_PIN, LOW);
        relay_is_on = false;
        last_relay_change = now;
    }
    if (!relay_is_on && now - last_relay_change >= RELAY_OFF_TIME) {
        // Turn on.
        digitalWrite(RELAY_PIN, HIGH);
        relay_is_on = true;
        last_relay_change = now;
    }
}


text:
How does the dual 5V and 3.3V output on the Uno R3 work exactly?
I'm constructing a circuit that needs both voltage supplies (for 3.3V RFID and 5V relay, GPS and screen) but the Uno is physically too big so I need to use a nano or mini pro, both of which I can only get in 5V. I understand how to use a regulator to drop 5V to 3.3V for the RFID-IC power but I keep seeing instructions to use a level shifter between the IC outputs and arduino input pins. I was just wondering if the Uno has a built-in level shifter for all pins or some other method as the I/O pins do not have specified voltages or uses.
Thanks for your time.

Pins of the UNO/Nano/Mini/Mega board are connected to GPIO pins of the MCU without any additional circuit. The ATmega MCU running at 5 V will sense 3.3 V as HIGH because of the threshold level to convert voltage to logic state.
ATmega will read the pin HIGH from 0.6 * Vcc, so at 5 V Vcc the threshold is 3 V.
Sources:

Schematics of Arduino Uno
Datasheet of ATmega328p (28.2 DC Characteristics)

There are no built-in level shifters on the Uno; it doesn't need them. Uno's 3.3v pin is merely a convenience for supplying a low-current 3.3v device but there is no provision made for level shifting if/when that is necessary.
Genuine Uno's can deliver a max of 150mA to the 3.3v pin, so plan your current-budget conservatively. In my dual-voltage designs (2 voltage rails on a board with 3.3v & 5v parts), I reduce the "raw" 5v with a 3.3v regulator (typically an LM1117-3.3 part) rather than drawing it off of the regulated 5v power. (I put "raw" in quotes because I usually supply the board with a pre-regulated 5 volts (USB or wall-wart).
For I/O levels, a 3.3v part's HIGH level is within the range of what Uno will read as HIGH. In the other direction, Uno's HIGH level is too high for a 3.3v part and needs to be shifted down to 3.3v. If there are only one or two such signals (Uno -> 3.3v device), a voltage divider circuit would be less expensive and use less board space than a level-shifter. The level-shifter board would be an extra purchase but it is a quick and dirty solution if you have the space for it.

You can get pro-mini in 3.3V, but this has little to do with your problem.
The nano runs on 5V, but has an on-board regulator which supplies 3.3V power, although the logic I/O is 5V.
Level shifters can be used to perform logic level translation, but are not always needed.
The output of a 3.3V logic circuit will drive the INPUT of a 5V logic circuit (technically this is marginal, but works in practice).
5V logic outputs can be connected to 3.3V inputs with a simple voltage divider (you can use level shifter or other methods). Without some means of limiting voltage there is a risk of damaging the 3.3V logic.
Without more detail of exactly what you are planning it is not possible to be more precise.

Thanks, my question was mainly to clarify my own understanding of why a 5V nano or pro-mini would need a level shifter but the Uno does not.

I am building an e-bike security system. Part 1 is a rfid reader embedded in the handle bar which the arduino uses as a test for the presence and ownership (via nfc ring) of the rider, driving a relay to connect the accelerator while authorised user is present. Part 2 is a GPS tracker which disables all of the bike functions when activated. Part 3 is a possible future addition which will be a display unit replacing the current factory unit.

@DanBailey, "why a 5V nano or pro-mini would need a level shifter but the Uno does not". not one of them needs logic level conversion from 3.3 V on input pin and any 3.3 V input controlled by them and not 5 V tolerant should have a logic level conversion


text:
How to independently control two lights with a single button and a menu system?
I'm stuck and don't know how to get over it.
The problem: i want to use a push button for a menu with 2 screens(frames)
Frame1: if i push the button i want to turn on the light from the room1
        if i press it again i want to turn the light off in the room1
Frame 2: using the same button: i want to turn on the light in the room2
         pressing it again i want to turn the light off in the room2
Now.. the problem i encounter...
if i'm in frame 1 and press the button then the light from room1 will turn on but also the light from the room2 will turn on. and i don't want that.
All i want is to tell somehow to uC that in the frame1 it should turn on only the light from the room1
Please, someone smarter than me ..give me an ideea how can i do that.
i cannot post the code because there are over 3000lines and would be time consuming for you to read it all.
for the buttons i use a counter to see if the state has changed and if so then increment and do what it has to do.
Also i think that the problem is here because i use the same counter in both functions.

int btn1 = 46,starebtn1, stareVechebtn1 = 0, btn2 = 50, starebtn2, stareVechebtn2 = 0;
int btn3 = 42, starebtn3, stareVechebtn3 = 0,btn4 = 40, starebtn4, stareVechebtn4 = 0,btn5 = 44, starebtn5, stareVechebtn5 = 0;
int cntbtn1 = 0, cntbtn2 = 0,cntbtn2_1 = 0, cntbtn3 = 0, cntbtn4 = 0, cntbtn5 = 0;
int soilMoisture = A0;
int buzzer = 3;
boolean frame1 = false, frame2 = false;
int procentajUmiditate(){
  int mSensorValue = analogRead(soilMoisture);
  mSensorValue = map(mSensorValue,0,1023,180,0);
  return mSensorValue;
}
void setup()
{
  Serial.begin(9600);
  dht.begin();
  rtc.begin();
  pinMode(ledVerde,OUTPUT);
  pinMode(buzzer,OUTPUT);
  pinMode(soilMoisture,INPUT_PULLUP);
  pinMode(btn1,INPUT);
  pinMode(btn2,INPUT);
  pinMode(btn3,INPUT);
  pinMode(btn4,INPUT);
  pinMode(btn5,INPUT);
  imagineSistemDomotic();
  delay(3000);
  imagineCasaWifi();
  delay(4000);
  tone(buzzer,1000);
  delay(500);
  noTone(buzzer);
  delay(500);
  digitalWrite(ledVerde,HIGH);
}

void loop()
{

  starebtn1 = digitalRead(btn1);
  starebtn2 = digitalRead(btn2);
  starebtn3 = digitalRead(btn3);
  starebtn4 = digitalRead(btn4);
  starebtn5 = digitalRead(btn5);
  int h = dht.readHumidity();
  int t = dht.readTemperature()-2;
  int f = dht.readTemperature(true);
  temp = t;
  hum = h;
  houR = rtc.getTimeStr();
  dateR = rtc.getDateStr();

//conditii procentaj umiditate si pornire automata irigare
if(procentajUmiditate()<20)
{
  //relayOn
}
else
{
  //relayOff
}

//btn1
 if(starebtn1 != stareVechebtn1)
  {
    if(starebtn1 == HIGH)
    {
      Serial.println(cntbtn1);
      cntbtn1++;
    }
  stareVechebtn1 = starebtn1;
  }//end btn1

//btn2
 if(starebtn2 != stareVechebtn2)
  {
    if(starebtn2 == HIGH)
    {

      cntbtn2 = cntbtn2+1;

    }
    stareVechebtn2 = starebtn2;
  }//endbtn2

//btn3
 if(starebtn3 != stareVechebtn3)
  {
    if(starebtn3 == HIGH)
    {
      cntbtn3 = cntbtn3+1;
    }
    stareVechebtn3 = starebtn3;
  }//endbtn3

//btn4
 if(starebtn4 != stareVechebtn4)
  {
    if(starebtn4 == HIGH)
    {
      cntbtn4 = cntbtn4+1;
    }
    stareVechebtn4 = starebtn4;
  }//endbtn4

//btn5
 if(starebtn5 != stareVechebtn5)
  {
    if(starebtn5 == HIGH)
    {
      cntbtn5 = cntbtn5+1;
    }
    stareVechebtn5 = starebtn5;
  }//endbtn5

//ecran1
     if(cntbtn1 == 1)
    {
     displayInteriorTempHum();
     //u8g.drawStr(23,58,temp.c_str());
    // u8g.drawStr(99,58,hum.c_str());
    }
//ecran2
     if(cntbtn1 == 2)
    {
     displayInteriorLights();
    }

//ecran3
      if(cntbtn1 == 3)
    {
     displayExteriorValues();
    }

     if(cntbtn1 == 4) cntbtn1 = 0;
     if(cntbtn2 == 3) cntbtn2 = 1;
     if(cntbtn2_1 == 3) cntbtn2_1 = 1;
     if(cntbtn3 == 3) cntbtn3 = 1;
} //end loop

void imagineSistemDomotic()
{
  u8g.firstPage();
  do{
    u8g.drawFrame(0,0,128,64);
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(0,30,"Sistem Domotic");
    }while(u8g.nextPage());
}

void imagineCasaWifi()
{
   u8g.firstPage();
   do{
    u8g.drawFrame(0,0,128,64);
    u8g.drawBitmapP( 0, 1, 16, 64, CasaDomoticaImage2);
     }while(u8g.nextPage());
}

void tempInterior()
{
   u8g.firstPage();
   do{
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(32,10,"Interior");
    u8g.drawFrame(0,15,128,49);
    u8g.setFont(u8g_font_5x7);
    u8g.drawStr(2,24,dateR.c_str());
    u8g.drawStr(101,24,houR.c_str());
    u8g.setFont(u8g_font_courB10);
    u8g.drawBitmapP( -3, 4, 16, 64, Temp1);
    u8g.drawCircle(40,46,1);
    u8g.drawStr(23,58,"26");
    u8g.setFont(u8g_font_10x20);
    u8g.drawStr(43,58,"C");
    u8g.setFont(u8g_font_courB10);
    u8g.drawBitmapP( 66, 10, 16, 64, UmidLogo);
    u8g.drawStr(99,58,"57");
    u8g.drawStr(117,58,"%");
     }while(u8g.nextPage());
}

void displayExteriorValues()
{
       frame1 = false;
       frame2 = true;
  u8g.firstPage();
      do{
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Exterior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);

       if(cntbtn2 == 1)
       {
        //u8g.drawBitmapP( 15, 30, 16, 64, robinetApaOprita);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(78,23,"Irigare");
        u8g.drawStr(78,30,"pornita");
        u8g.drawBitmapP( 72, 8, 16, 64, robinetApaPornita);
        u8g.setPrintPos(15,40);
        u8g.setFont(u8g_font_courB10);
        u8g.print(procentajUmiditate());
        if(procentajUmiditate()<100)
        {
          u8g.setPrintPos(34,40);
          u8g.print("%");
        }
        else
        {
          u8g.setPrintPos(44,40);
          u8g.print("%");
        }

       }

  else{

      //u8g.drawBitmapP( 15, 30, 16, 64, robinetApaOprita);
      u8g.setFont(u8g_font_5x8);
      u8g.drawStr(78,23,"Irigare");
      u8g.drawStr(78,30,"pornita");
      u8g.drawBitmapP( 72, 8, 16, 64, robinetApaPornita);
     // u8g.drawBitmapP( 20, -20, 16, 64, LightOff);
    // valoare buna FanOffLOGO   u8g.drawStr(10,23,"Ventilatie");
   // valoare buna FanOffLOGO    u8g.drawStr(20,30,"oprita");
    //  u8g.drawBitmapP( -15, 24, 16, 64, fanOffLogo);
       u8g.drawStr(10,23,"Umid. Sol");
       u8g.drawBitmapP( 12, -1, 16, 64, UmiditateSol);
       }
       }while(u8g.nextPage());
    cntbtn2 = 0;
}

void displayInteriorLights()
{

   u8g.firstPage();
      do{
      u8g.setFont(u8g_font_courB10);
      u8g.drawStr(32,10,"Interior");
      u8g.drawFrame(0,12,128,51);
      u8g.drawLine(64,12,64,62);
      u8g.setFont(u8g_font_5x8);

      if(cntbtn2 == 1)
      {
      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.aprinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
      }
      else if(cntbtn2 == 2)
      {
      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.stinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
      }
      else{
      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.stinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
      }

      if(cntbtn3 == 1)
      {
      u8g.drawStr(10,23,"Sufragerie");
      u8g.drawStr(15,60,"L.aprinsa");
      u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
      }
      else if(cntbtn3 == 2)
      {
      u8g.drawStr(10,23,"Sufragerie");
      u8g.drawStr(15,60,"L.stinsa");
      u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
      }
    //else if(digitalRead(relay)

    else{
      u8g.drawStr(10,23,"Sufragerie");
      u8g.drawStr(15,60,"L.stinsa");
      u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
    }
      }while(u8g.nextPage());

}

void displayInteriorTempHum()
{
      u8g.firstPage();
      do{
      u8g.setFont(u8g_font_courB10);
      u8g.drawStr(32,10,"Interior");
      u8g.drawFrame(0,15,128,49);
      u8g.setFont(u8g_font_5x7);
      u8g.drawStr(2,24,dateR.c_str());
      u8g.drawStr(101,24,houR.c_str());
      u8g.setFont(u8g_font_courB10);
      u8g.drawBitmapP( -3, 4, 16, 64, Temp1);
      u8g.drawCircle(40,46,1);
      u8g.drawStr(23,58,temp.c_str());
      u8g.setFont(u8g_font_10x20);
      u8g.drawStr(43,58,"C");
      u8g.setFont(u8g_font_courB10);
      u8g.drawBitmapP( 66, 10, 16, 64, UmidLogo);
      u8g.drawStr(99,58,hum.c_str());
      u8g.drawStr(117,58,"%");
      digitalWrite(ledVerde,LOW);
        }while(u8g.nextPage());
}

Sorry, but  your question is very unclear. Can you edit your post using correct prepositions? Like: "IN the kitchen", "IN the bedroom". Also, "SWITCH ON the light bulb". Remember, saying "switching light FROM x room" means: "Switching light by pressing button which is located IN room x".

whenever the button is pressed, check the room number that it is operating on, then act accordingly

Difficult to advise without more clear information but here's a couple of ideas to play around with (currently typing on my phone, will edit later).
If using a physical menu and buttons then you need some way to track location. You could try adding proximity sensors to check physical location/proximity to the light source and let that be the deciding variable for which bulb gets activated. You could use a "universal remote" approach, using separate arduinos (per light) with IR receivers.
If using an app menu, like on a phone, try declaring a variable "room" and have the button pass the frame name or ID number based on the frame ("bedroom" or "kitchen", "1" or "2" etc) as that variable via your communication line to the arduino. On the arduino side, declare the same variable and process the received data from the app i.e. String room = your-room-ID. Ensure you have separate pinout declarations for each bulb you want to control i.e. #define kitchen 14 # define livingroom 15... setPin(output, kitchen), setPin(output, livingroom) then modify your bulb activation line to be pinout(room, HIGH);

Reading your answer i understand mostly that i was not so clear in my post. And i am agree with you on that. Now.. imagine that i have an glcd which is divided by 2. On the left is room 1 light and on the right is ventilation for room1.  That in the Frame 1. In the Frame 2(btw i scroll into the frames using another button) so, in Frame 2 the image is also divided by 2. On the left light for room2 and on the right is the temp for room2. Now, besides the button that i use for switching the frames, i have another 2 that i want to use for "current" frame that i am in.

So.. if i press the button wich is positioned under the left side lf the screen. I could turn on or off the light in the room 1. But the problem is that the light will be turned on even in the room 2

My app code notes still apply, you are controlling the glcd with the same arduino? If so then just add an extra line of code to set your room variable when the frame is changed and use the rest of the pin coding as I described. This is all assuming there are no errors in your current coding that are making this result happen, without your sketch we will never be able to tell.

here is a part of it

It's really very simple, I think...  If I understood properly...
global frame, lightRoom1, lightRoom2

function changeFrame ( ) {

// if frame == 1, change it to 2

    if ( frame == 1 ) {
        <commands to refresh display>;
        frame = 2;
    } else {
        <commands to refresh display>
        frame = 1;
    }

}

function switchLight ( ) {

// roomno = frameno.
// if light on, switch off; if off, switch on.

    if ( frame == 1 ) {

        if ( lightRoom1 == false ) {
            <code to switch light on >;
            lightRoom1 == true;
        } else {
            <code to switch light off >;
            lightRoom1 == false;
        }

    }

    if ( frame == 2 ) {

        // same as above but for room 2.

    }

}

if ( digitalRead ( framePin ) == LOW ) {
    changeFrame ( );
}

if ( digitalRead ( lightPin ) == LOW ) {
    switchLight ( );
}

The code you show is indeed too long. However, a cursory look seems to
indicate that you are not using any debouncing library. This is then the
first thing you should do. There are probably many options. I will
suggest Bounce2 which, in addition to debouncing, handles the edge
detection. Then you have the fell() method that tells you whether the
input signal just fell since the last time it was tested, which is a way
to detect the button press.
Then, within loop(), you would add something like this:
if (mainButton.update() && mainButton.fell()) {

    // Find the pin that controls the appropriate light.
    uint8_t lightPin;
    if (currentFrame == FRAME1) {
        lightPin = PIN_LIGHT_ROOM_1;
    } else {  // FRAME2
        lightPin = PIN_LIGHT_ROOM_2;
    }

    // Toggle the light.
    if (digitalRead(lightPin) == HIGH) {
        digitalWrite(lightPin, LOW);
    } else {
        digitalWrite(lightPin, HIGH);
    }
}

The assumptions I am making should be pretty obvious:

currentFrame is a variable updated by your menu system. Its value
can only be one of the constants FRAME_1 or FRAME_2
PIN_LIGHT_ROOM_1 and PIN_LIGHT_ROOM_2 are constants holding the
pin numbers which control the corresponding lights.


text:
OTA updating the ESP32 from a separate server
I have an ESP32 project which I'd like to be able to update OTA. The trouble is that it is in deep sleep for approximately 15 minutes before waking up, connecting to WiFi sending an MQTT packet then going back to sleep.
I would like to be able to have a webpage hosted on a Raspberry Pi with a repository of datestamped .bin files that the ESP32 can connect to, check it's current version against the available options, if there is an applicable update, go through the standard OTA update protocol, or if there is no new available version, don't check again for 24 hrs.
How do I go about this?

HttpUpdate library. the esp32 version is without a documentation, but here is the similar esp8266 HttpUpdate library doc https://arduino-esp8266.readthedocs.io/en/latest/ota_updates/readme.html#http-server

I remember seeing something about this a while ago and it must have stuck in my head, but I hadn't thought about using it for ESP32.
Do you know if the ESP32 version will work by using the ESP8266 documentation?
I can't imagine they'd be too different

the esp32 version has examples too

I used the library mentioned by Juraj some time ago on an ESP32 in the exact way you described. I remember that it was straight forward to use. Looking at examples is all you need to do

Thank you very much :) I will try it all out


text:
Arduino Mega not recognized on Raspberry Pi 3b+
I'm developing an interactive LED table for an university assignment that is being controlled by an Arduino Mega2560 which gets the information about which LEDs should be lit in which colour from a Java application that runs on a Raspi 3b+. So far everything is almost finished and the program is running quite smoothly.
The whole time I've been developing the Java application on a PC and it worked just perfect. Now I wanted to move the application to the Pi to have a runnable demo for a meeting with my advisor. Therefore I wanted to check on which USB port the Arduino connects to the Pi so I can setup the corresponding part of the Java code correctly. As I also wanted to set a specific descriptive port name on which the Arduino is always accessible for the Java application I followed this tutorial.
In a previous attempt where I still used 2 Arduino Duemilanove that step worked however when I now try to find the Arduino Mega with dmesg | grep ttyUSB I get no results and ls -l /dev/ttyUSB* only tells me that there is no such path or directory. I also retried that with one of the Arduino Duemilanove in case the USB cable was defective but in that case it returned a valid result.
As the code that I need to run on the Arduino is too extensive for using 2 Arduino Duemilanove (due to the array size to represent the table) I definitely need to run this on the Mega. After many attempts to find a solution I didn't find anything that helps me in my situation as every thread on a similar topic was about a board that wasn't recognized on any machine (whereas my Mega gets recognized on my normal Windows PC). As the Duemilanoves get recognized seamlessly I conduct that it's probably not a problem caused by the Pi (or at least not only the Pi).
I read that using a powered USB hub could be a possible solution. However, as the Arduino itself is powered by a power supply  I suppose that using a powered USB hub would not help much in this case? However I'd be happy if someone proved me wrong in this case and solving the issue was as easy as that.

Did you try /dev/ttyACM0?

I didn't until you mentioned it as I'm not really familiar with Linux systems. But it seems that it found something. I'll have a look into what that ttyACM is exactly and will provide more information as soon as possible.

@Edgar Bonet Thank you so much, it works perfectly now. If you want to make your post an official answer I can mark it as accepted answer.

The newer Arduinos, like the Uno or Mega 2560, have a different way of managing the Serial ↔ USB translation, compared with the older Duemilianove. From the Linux side, you shouldn't see much difference, except that the device is now /dev/ttyACM0 instead of /dev/ttyUSB0.


text:
Adafruit Micro-SD breakout not initializing on MEGA 2560
]
[I am having quite a bit of trouble trying to get my Arduino MEGA 2560 to read my micro-SD card. My wiring is as follows:
Breakout    Arduino
5v            5v
Gnd           Gnd
CLK           52
DO            50
DI            51
CS            53
CD            Was not connected and then connected to 47 (neither worked)

Here is my code:

#include <Wire.h> //library necessary to use I2C communications bus
#include <Adafruit_Sensor.h>
#include <Adafruit_BME680.h>
#include <SD.h>
#include <SPI.h>

const uint8_t chipSelect = 53; //chipSelect pin for the SD card Reader
const uint8_t cardDetect = 47;

File CO2Data; //Data object you will write your sensor data to

void setup() {
Serial.begin(115200);//"begins" the serial monitor so you can print stuff out when connected to the computer (set baud rate to 115200)
Wire.begin ();//begins the I2C communications bus so it can talk to the K33

Serial.print("Initializing SD car...");
pinMode(53, OUTPUT);

if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1) ;
}
Serial.println("card initialized.");
File CO2data = SD.open("datalog.txt", FILE_WRITE);
if (! CO2data) {
Serial.println("error opening datalog.txt");
// Wait forever since we cant write data
 while (1) ;
}}

The SD card is formatted to FAT32.
Thank you for any help!

try the CardInfo example

I did try to cardinfo example and came up with the following message:Initializing SD card...initialization failed. Things to check:

is a card inserted?
is your wiring correct?
did you change the chipSelect pin to match your shield or module?

Update: I set chipselect  to 10 in the Cardinfo example and card is found and present. However, it still won't run in my sketch. I have gone through trying different pin combinations.

do you have some shield on the Mega or some other devices wired to it?

I do, I have a couple of things wired to the MEGA: Adafruit BME680 (temp pressure) using the I2C interface (SCL wired to 21 and SDA wired to 20) and a KC-30 CO2 sensor wired to pins 10 and 9.

SOLVED: The non-analog ground line attached to the micro-SD was pulling down my voltage. Just hardwired to different ground and problem solved!  (Check your voltages)

what is a non-analog ground in this case?

From what I could gather. the ground pin on the MEGA inline with the digital pins was a different ground source (digital ground). I literally took the ground lead from the SD board and just touched it to the housing of the USB connector on the MEGA and my voltage came back.

did you try one of the ground pins between 5 V pin and Vin pin?

I tested the Vin on the micro-SD between the ground on my voltage regulator board (which drops battery incoming from 12 and outputs 5 to the MEGA), it read fine. But when measuring between the Vin pin on the Micro-Sd and the ground on the micro-Sd my voltage was only 1.5.  So I just reran that ground wire.

The non-analog ground line attached to the micro-SD was pulling down my voltage. Just hardwired to different ground and problem solved! (Check your voltages).
From what I could gather. the ground pin on the MEGA inline with the digital pins was a different ground source (digital ground). I literally took the ground lead from the SD board and just touched it to the housing of the USB connector on the MEGA and my voltage came back.

It's OK to accept your own answer as the solution to the problem.


text:
'myservo' does not name a type
I keep getting 'myservo' does not name a type as an error message, I have already looked other solved questions like this one but I can´t find the mistake. I would be very glad for your help.
/*********************************************************
 * Bot control
 * By soleil_zero
 * Based on code by
 * MSc. Fausto M. Lagos S.
 * @piratax007
 * V2.0.0 - 2019
 * GNU GPLV3+
 *
 * Hardware:
 * Arduino Mega2560
 * Adafruit Motor Shield V1.2
 * Bluetooth module H6
 * 1 Servo
 * 2 DC Motor
 *********************************************************/

// Librería para Adafruit Motor Shield V1.2 y Servo
#include "AFMotor.h"
#include "Servo.h"

// Motores conectados en los puertos 1 y 2
AF_DCMotor leftMotor(1, MOTOR12_64KHZ);
AF_DCMotor rightMotor(2, MOTOR12_64KHZ);

Servo myservo;
myservo.attach(9);

// Variable para el paso de mensajes vía Bluetooth
char message;
//ángulo de rotación del servo
int angle = 0;

void setup() {
  // Velocidades en los motores
  leftMotor.setSpeed(150);
  rightMotor.setSpeed(150);

  /* Debido a que el Adafruit Motor Shield V1.2 ocupa los pines digitales 0 y 1 para la conexión del módulo HC05
     bluetooth deben utilizarse cualquiera de los otros disponibles: 14 (TX3) y 15 (RX3) o 16 (TX2) y 17 (RX2) o
     18 (TX1) Y 19 (RX1). De acuerdo a cuál de los cuatro pines se utilicen deben modificarse las líneas
     relacionadas a la comunicación Serial e.g si se utilizan los pines 18 y 19 la instrucción será Serial1 */
  Serial3.begin(9600);
  myservo.write(angle);
}

void loop() {
  // Verificación de mensaje en el puerto Serial
  if (Serial3.available() > 0) {
    message = Serial3.read();
  }

 if (message == 'F') {//Forward
    leftMotor.run(FORWARD);
    rightMotor.run(FORWARD);
  } else if (message == 'B') {//Backwards
    leftMotor.run(BACKWARD);
    rightMotor.run(BACKWARD);
  } else if (message == 'L') {//Left
    leftMotor.run(FORWARD);
    rightMotor.run(BACKWARD);
  } else if (message == 'R') {//right
    leftMotor.run(BACKWARD);
    rightMotor.run(FORWARD);
  } else if (message == 'S') {//stop
    leftMotor.run(RELEASE);
    rightMotor.run(RELEASE);
    Serial3.print("stop");
  }
  } else if (message == 'U') {//down
    angle = 0;
    servo1.write(angle);
  }else if (message == 'D') {//up
    angle = 90;
    servo1.write(angle);
  }
}

this has been asked a lot ... please do research before posting your question

In C and C++ languages we write statements inside functions. That myservo.attach(9); is a statement. You can't just write it in the middle of the file. It has to reside inside a function.
In your code myservo.attach(9); just sits in the middle of nowhere. You had enough sense to put leftMotor.setSpeed(150); inside setup(). Why did you suddenly decide to place myservo.attach(9); outside of any functions?
Function setup() would be an appropriate place for this statement.