text:
MAX7219 and Arduino
I am getting started in running this 8x8 led on an Arduino. Regardless of which tutorial sketch I attempted, I never got a scrolling text that I expect. What happens seems to be only a single (out of four) led module being addressed at a time, resulting in, for example, the message being scrolled on one module at a time, but all four in succession. Could it be a module problem?

Got it somewhat working by changing:
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
to:
#define HARDWARE_TYPE MD_MAX72XX::ICSTATION_HW
But still a little problem with the last character in a message not showing all leds lit until it starts to scroll after the initial program delay. Then all is fine.
Anyone want to address that issue? My sketch follows:

{    // Use the Parola library to scroll text on the display
//
// Demonstrates the use of the scrolling function to display text received
// from the serial interface
//
// User can enter text on the serial monitor and this will display as a
// scrolling message on the display.
// Speed for the display is controlled by a pot on SPEED_IN analog in.
// Scrolling direction is controlled by a switch on DIRECTION_SET digital in.
// Invert ON/OFF is set by a switch on INVERT_SET digital in.
//
// UISwitch library can be found at https://github.com/MajicDesigns/MD_UISwitch
// MD_MAX72XX library can be found at https://github.com/MajicDesigns/MD_MAX72XX
//

#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

// set to 1 if we are implementing the user interface pot, switch, etc
#define USE_UI_CONTROL 0

#if USE_UI_CONTROL
#include <MD_UISwitch.h>
#endif

// Turn on debug statements to the serial output
#define DEBUG 0

#if DEBUG
#define PRINT(s, x) { Serial.print(F(s)); Serial.print(x); }
#define PRINTS(x) Serial.print(F(x))
#define PRINTX(x) Serial.println(x, HEX)
#else
#define PRINT(s, x)
#define PRINTS(x)
#define PRINTX(x)
#endif

// Define the number of devices we have in the chain and the hardware interface
// NOTE: These pin numbers will probably not work with your hardware and may
// need to be adapted
//#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
//#define HARDWARE_TYPE MD_MAX72XX::GENERIC_HW
#define HARDWARE_TYPE MD_MAX72XX::ICSTATION_HW
#define MAX_DEVICES 4
#define CLK_PIN   13
#define DATA_PIN  11
#define CS_PIN    10

// HARDWARE SPI
MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
// SOFTWARE SPI
//MD_Parola P = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

// Scrolling parameters
#if USE_UI_CONTROL
const uint8_t SPEED_IN = A5;
const uint8_t DIRECTION_SET = 8;  // change the effect
const uint8_t INVERT_SET = 9;     // change the invert

const uint8_t SPEED_DEADBAND = 5;
#endif // USE_UI_CONTROL

uint8_t scrollSpeed = 25;    // default frame delay value
textEffect_t scrollEffect = PA_SCROLL_LEFT;
textPosition_t scrollAlign = PA_LEFT;
uint16_t scrollPause = 2000; // in milliseconds

// Global message buffers shared by Serial and Scrolling functions
#define BUF_SIZE    75
char curMessage[BUF_SIZE] = { "" };
char newMessage[BUF_SIZE] = { "Got Signals?" };//{ "Hello! Enter new message?" };
bool newMessageAvailable = true;

#if USE_UI_CONTROL

MD_UISwitch_Digital uiDirection(DIRECTION_SET);
MD_UISwitch_Digital uiInvert(INVERT_SET);

void doUI(void)
{
  // set the speed if it has changed
  {
    int16_t speed = map(analogRead(SPEED_IN), 0, 1023, 10, 150);

    if ((speed >= ((int16_t)P.getSpeed() + SPEED_DEADBAND)) ||
      (speed <= ((int16_t)P.getSpeed() - SPEED_DEADBAND)))
    {
      P.setSpeed(speed);
      scrollSpeed = speed;
      PRINT("\nChanged speed to ", P.getSpeed());
    }
  }

  if (uiDirection.read() == MD_UISwitch::KEY_PRESS) // SCROLL DIRECTION
  {
    PRINTS("\nChanging scroll direction");
    scrollEffect = (scrollEffect == PA_SCROLL_LEFT ? PA_SCROLL_RIGHT : PA_SCROLL_LEFT);
    P.setTextEffect(scrollEffect, scrollEffect);
    P.displayClear();
    P.displayReset();
  }

  if (uiInvert.read() == MD_UISwitch::KEY_PRESS)  // INVERT MODE
  {
    PRINTS("\nChanging invert mode");
    P.setInvert(!P.getInvert());
  }
}
#endif // USE_UI_CONTROL

void readSerial(void)
{
  static char *cp = newMessage;

  while (Serial.available())
  {
    *cp = (char)Serial.read();
    if ((*cp == '\n') || (cp - newMessage >= BUF_SIZE-2)) // end of message character or full buffer
    {
      *cp = '\0'; // end the string
      // restart the index for next filling spree and flag we have a message waiting
      cp = newMessage;
      newMessageAvailable = true;
    }
    else  // move char pointer to next position
      cp++;
  }
}

void setup()
{
  Serial.begin(57600);
  Serial.print("\n[Parola Scrolling Display]\nType a message for the scrolling display\nEnd message line with a newline");

#if USE_UI_CONTROL
  uiDirection.begin();
  uiInvert.begin();
  pinMode(SPEED_IN, INPUT);

  doUI();
#endif // USE_UI_CONTROL

  P.begin();
  P.displayText(curMessage, scrollAlign, scrollSpeed, scrollPause, scrollEffect, scrollEffect);
}

void loop()
{
#if USE_UI_CONTROL
  doUI();
#endif // USE_UI_CONTROL

  if (P.displayAnimate())
  {
    if (newMessageAvailable)
    {
      strcpy(curMessage, newMessage);
      newMessageAvailable = false;
    }
    P.displayReset();
  }
  readSerial();
}

}

I suggested an edit to format the code but is this your final answer to the question? If this code still has problems you might be best adding a description of what's wrong and editing it into your question instead.

"Somewhat working?"

Yes, the change to ICSTATION corrected the problem. Thanks for your interest.


text:
Is there a way to get my MacBook's date and time into Arduino IDE?
I am using a DS3231 RTC module. It requires to set the time every time it is reset. I was wondering if I could read my MacBook's time and date and feed into the module at the setup stage. Is this possible?
P.S. I do not have to use a battery.

Actually the whole point of an RTC is that it has a battery backed up clock that does NOT reset on power loss.

Yes. But due to some reason, I have a RTC without a battery backup. I had myself opened the Amazon packing today and unboxed the module. And the bottom side has no battery.

So.... attach a battery?

without the battery you don't need the RTC module. you can use the TimeLib

Please note that some of these modules have a (badly designed) charging circuit, and thus require a rechargeable coin cell (LIR2032). Or you can remove the charging resistor from the board.

What I've do with one of my clocks if create an interactive serial console, where I could type the current time, when the code saw that the RTC was reset. There is no way to get the time from the USB host without some software running on the host, or like I did, some manual serial data entry.

You can use __DATE__ and __TIME__ compiler time constants in IDE and do check inside of your setup() function if the RTC clock is zeroed then parse and set compile time values.
char cr[] = __DATE__;
char ct[] = __TIME__;

At the compile time these macros will be replaced with text constants "Apr  4 2019" and "10:35:22" respectively.

You could use softRTC library to get date/time from your system. So program flow could be get date/time from softRTC library during setup part and then use those variables in loop set your DS2321 RTC which will always be running till you poweroff.

softRTC is relying on the preprocessor. So each time you want to set the time you will have to open ArduinoIDE and compile+upload the sketch. This is not going to work in stand alone. Beside Atmel only guarantees 10.000 write cycles when uploading code.

I can't find softRTC library. how does it solve the use of DS3231 without battery?

source: Stack Exchange

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

sort: votes


text:
How to stabilize magnetic levitation system?
I followed everything from this project but still, the magnet is not levitating - https://www.hackster.io/jsirgado/magnet-levitation-with-arduino-eeeee4
The best I can do is to make the magnet jump up and down fast but it never levitates. Have tried changing PID setting from the project as aggressive and mild but still didn't achieve the final result.
I need advice from an expert to tell me what I am doing wrong here. All components are in good condition and 5v electromagnet is strong enough.
So what am I missing here? will implementing fast PWM mode be helpful?

I'd try to hold the magnet in your hand, and hold it at different positions, and feel if the system is trying to move the magnet, like you want it to. There't to many factors that could be different to the hackster project, like magnet strength, weight, coil strength, coil diameter, coil resitance(, your latitude on the planet).

I tried that and for me, it vibrates up-down and even sideways. How do I dampen this vibration to make it stable? Will the fast PWM mode help here?

That sounds like it's over-correcting. Not sure what to do about that. I'm not that familiar with PID.

@suu if it vibrates my guess is that your PID gains are to strong. What happens when you experiment with the gains while holding the magnet? Have you tried changing the position of the hall sensor? I don't think changing to fast pwm will make a change...

Maybe the magnet has an inductance too high to adjust the magnetic field fast enough. You would then loose resolution which is already very limited on an uno and which will worsen the quality of your control loop. The same applies to the analog measurement, you should try to use the 10 bits you get from the arduinos adcs as good as possible. For debugging you can monitor the dutycycle and the analog reading.

I tried lower PID gains and changed the position of the sensor below & above the permanent magnet also. I will check about resolution thing.

I'd look into the update time of the PID code versus the time constant of the physical system.  If your PID is sampling and adjusting much faster or slower than the physical system responds, then you could get oscillations.  The article recommends that "Heavy objects are more stable", so maybe the electromagnet is too strong for the control system.  Maybe try increasing the mass of the magnet or reducing the voltage/power to the electromagnet?

The answer to the solution was quite simple. I just had to comment out all serial port reading and Arduino processing became 60 times faster which helped to levitate the magnet. Thanks to everyone who helped me here :)

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


text:
How to generate .a and .so files to add in arduino project
I know to make a library on arduino ide with source codes, but I cant send my source code to another users who want to use my lib.
So I need to make a library with precompiled=true info at library.properties. And I need to put my .a and .so files at src/{build.mcu} (in my case, src/avr/mylib.a and mylib.so).
But, where is that files (.a and .so)?!
Does the arduino compiler generate this files? If so, where? If dont, how compiler I need to use?
I found the .o file at appData\local\Temp\arduino_build_XXXX\libraries\mylib\
Thank you very much and sory about my english.

[library] = library name
1) edit the [library] library.properties file and add dot_a_linkage=true to the end ... (/home/name/Arduino/libraries/[library]/library.properties)
2) build the example ...
3) After the build is complete navigate to the build folder (In Linux it's located in the /tmp/arduino_build_xxxxxx folder) then copy the dot_a file from under library folder (libraries/[library].a) to the arduino library folder for the [library] library (/home/name/Arduino/libraries/[library]/src/esp8266/lib[library].a)
4) edit the [library] library library.properties file again and remove dot_a_linkage=true and add precompiled=true and ldflags=-l[library] to the end of the file ...
5)  build the example ... this time it links to the dot_a file ...

Note: I have never done this with the Arduino IDE, so I don't know if the resultant file will be of any use to you.

A .a file (you don't want a .so file - that's a shared library that makes no sense on a platform without an OS) is merely an archive (ar archive, specifically) that contains one or more .o files.
You create one simply enough using:
avr-ar rcs myLib.a myLib.o

You will find the avr-ar program in the tools installation within your Arduino IDE somewhere.

As an aside, UECIDE (which I wrote) uses library files like these to cache its libraries and other compiled code. You can use UECIDE to directly grab a .a file for your library, which you would find in the cache folder of the UECIDE data folder (find it through the Help -> Debug menu).

Thank you Majenko!
But, the program is not avr-ar for me, I use the avr-gcc-ar.
After that, I must to dot_a_linkage=true in my library.properties and manually add mylib.a at AppData\Local\Temp\arduino_build_115676\libraries\mylib\
I dont know why, but this help for me.
I hope help other.
Best regards.


text:
how to use AckPayload correctly
i'm trying to send String from an Arduino(Uno) using the Serial. to an another Arduino(Uno). using nRF24l01+. and I'm using the library RF24.h
the String is sended correctly but I have some problems with the acknowledgement.
This is my Rx code.
#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
const uint64_t pipe[1]= {0xF0F0F0F0E1LL};
RF24 radio(9,10);
char buf[32]= "";
char false_buf[32]= "MKJK212U1H7";
void setup()
{
  Serial.begin(115200);
  radio.begin();
  radio.setChannel(0x35);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  radio.openReadingPipe(1,pipe[0]);
  radio.startListening();
  radio.setRetries(1,15);
  radio.writeAckPayload( 1, false_buf, sizeof(false_buf) );
}
void loop()
{
int OkMsg;
  while(!radio.available()){};
  if ( radio.available() > 0) {
    radio.read(&buf,sizeof(buf) );
    Serial.println(buf);
    radio.writeAckPayload( 1, buf, sizeof(false_buf) );
      while(!radio.available()){};
  if ( radio.available() > 0) {
    radio.read(&OkMsg,sizeof(OkMsg) );
    Serial.println(OkMsg);
    if(OkMsg == 1){Serial.println("OkMsg's true!");}
    else {Serial.println("OkMsg's false!");}
    }}
  }

and this is my Tx code
#include <SPI.h>
#include <RF24.h>
#include <nRF24L01.h>
RF24 radio(9, 10); // CE, CSN

const uint64_t pipe[1]= {0xF0F0F0F0E1LL};

char CharToSend[32]= "" ;
char Ack[32]= "" ;
String inputString = "";
String Allconfiguration = "";
boolean stringComplete = false;
char  inChar;
boolean isConnected = false;
int OkMsg = 0;

void setup()
{
  SPI.begin();
  Serial.begin(115200);
  RadioSetupTransmiter();
}

void loop()
{
  if(stringComplete)
  {
         if(Allconfiguration.startsWith("\n")){Allconfiguration.remove(0,1);}
     Allconfiguration.remove(Allconfiguration.length());
    inputString = "";
    Serial.print("Allconfiguration : ");
     Serial.println(Allconfiguration);
    int counter = 0;
    for(int i=0; i<Allconfiguration.length(); i++)
    {
      if((Allconfiguration[i] == '\n')&&(i!=Allconfiguration.length()))
      {
        int pre_counter = counter;
        counter = i+1;
        inputString = Allconfiguration.substring(pre_counter, counter);
        if(inputString[0]!='$'){inputString.toCharArray(CharToSend,32);}

        if(radio.write(&CharToSend, sizeof(CharToSend)))
        {CheckData();
       Serial.print("inputString : ");
         Serial.print(CharToSend);}
      }
       if(i == Allconfiguration.length()){
        const char EndChar[2] = "$";

       }
        inputString = "";
    }
    Allconfiguration = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
  char inChar = (char)Serial.read();
    Allconfiguration +=inChar;
     if (inChar == '$'){stringComplete = true;
    }
    }
}

void RadioSetupTransmiter(){  radio.begin();

  radio.setChannel(0x35);
  delay(100);
  radio.setAutoAck( true ) ;
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  // radio.printDetails();

  radio.stopListening();
  radio.openWritingPipe(pipe[0]);

  radio.setRetries(1, 15);
 }

void CheckData(){
  int OkMsg = 0;
    while (!radio.isAckPayloadAvailable()){};
      if(radio.isAckPayloadAvailable())
      {
       radio.read(&Ack,sizeof(Ack));
       //Serial.println(Ack);
       if(strcmp(CharToSend,Ack) == 0){
        OkMsg = 1  ;
        Serial.println("AckRecived");
        radio.write(&OkMsg,sizeof(OkMsg));}
    }
}

I have not used the RF24 libary, but below are the register settings that should be written during void setup() to use the ACK_PAYLOAD functionality (N.B. nRF24L01+ only, does not exist on nRF24L01.  Check you are using the right version of the radio!)
TX:

0x00 CONFIG = PTX mode
0x0B RX_PW_P0 = Number of data bytes in pipe 0
0x1C DYNPD = 0x01. Enable dynamic payload on pipe 0 (set DPL_P0 bit)
0x1D FEATURE = 0x06 (set bits EN_DPL and EN_ACK_PAY).

RX

0x00 CONFIG = PRX mode
0x0B RX_PW_P0 = Number of data bytes in pipe 0
0x1C DYNPD = 0x01. Enable dynamic payload on pipe 0 (set DPL_P0 bit)
0x1D FEATURE = 0x06 (set bits EN_DPL and EN_ACK_PAY).
Finally, load an initial payload using the W_ACK_PAYLOAD instruction 0xA8, i.e. SPI.transfer(0xA8); SPI.transfer(payload);.


text:
How to compare a string
How to compare a string coming from serial monitor with some predefined text stored  as a local variable?
If I say:
int led = 2;
String a = " abcds";

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

void loop() {
  String b = Serial.read();
  Serial.println(b);

  if (b != a) {
    digitalWrite(2,LOW);
  }
  else
  {
    digitalWrite(2,HIGH);
  }
}

just as an example, this code will not compile because on the serial I receive bytes and I want to compare with a string.
So my question is...
how should be done?

For which arduino board? Most of us try to avoid the String class for the arduino uno. As soon as a character is available, you add it to a buffer or to a String. Sometimes the data from the serial port is closed with a linefeed, then you can process the text in the buffer or in the String when a linefeed is read.

version using String (not recommended, but it makes simpler to understand the following C-string version)
#define LED 2
const char* a = "abcd";

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    String s = Serial.readStringUntil('\n');
    s.trim();
    if (s == a) {
      digitalWrite(LED, HIGH);
    } else {
      digitalWrite(LED, LOW);
    }
  }
}

the version with C-string:
#define LED 2
const char* a = "abcd";
char buffer[32];

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    size_t l = Serial.readBytesUntil('\n', buffer, sizeof(buffer - 1));
    if (buffer[l - 1] == '\r') {
      l--;
    }
    buffer[l] = 0; // the terminating zero
    Serial.println(buffer);
    if (strcmp(buffer, a) == 0) {
      digitalWrite(LED, HIGH);
    } else {
      digitalWrite(LED, LOW);
    }
  }
}

As I already commented on VE7JRO's post, Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

The String version works perfectly, but I can't get the C-string version to work. For me, the serial monitor shows "abcd" written out to 2 lines: line 1 prints "ab", line 2 prints "cd". Perhaps it's the old version of the IDE I'm using (1.0.6.2). I like that you provided 2 example sketches so the OP can see the difference in compile size: String 4364 bytes VS C-string 2746 bytes.

@EdgarBonet, it will wait only if terminating character is not present. the timeout can be set to for example to 10 milliseconds with setTimeout. in many cases it is better to wait for the stream as continue with other things in loop and then return to read an overflowed buffer

If your loop() takes so long that the serial buffer overflows, then you have probably done something very wrong. You can only afford to wait for the whole message to be received if you have no time-sensitive code outside of interrupt context. Stream::readBytesUntil() and delay() work in the same team: they can help you write simpler code if you can afford keeping the CPU busy doing nothing, but their use is not a good programming habit in general.

@EdgarBonet, if the gaps between the received bytes are microseconds small, but available() would sometimes return 0, what is a good way to read a command from Stream? the sketch has nothing to do, until this command is received. Other case:  with networking done in external modules and with Arduino libraries you can't have a 'real-time' loop. it could take some seconds until a web server sends a response, but then the bytes go in fast and always more than the serial buffer size.

If you do a Google search on "Arduino String" you should find a class reference on the String class. https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/
It has a function compareTo() that should do what you need.

C has strcmp() function that is used to compare two strings. It will return zero if two strings are equal non zero when not.

I started to suggest the same thing, and then noticed that the OP is using Arduino String objects, not C strings.

Here is the loop() code from the SafeString_ReadCmdsTimed.ino example in the SafeString library available from the Arduino library manager.  It is non-blocking, i.e. no delays.
There is an extensive tutorial and examples available for SafeStrings.
SafeStrings has built-in error checking and debugging.  SafeStrings provides the functionality of Strings without the memory fragmentation problems of dynamic memory allocation.
If you are reading from telnet there is also a processbackspaces() method in SafeStrings to handle terminal typing corrections.
The delimiters are whatever you would like.  The example handles Windows, Unix and Mac end-of-lines.
char delimiters[] = " .,\r\n"; // space dot comma CR NL are cmd delimiters

void loop() {
  if (input.read(Serial)) {  // read from Serial, returns true if at least one character was added to SafeString input
    input.debug("after read => ");
    timeout.start(TIMEOUT_MS); // restart a 0.1sec timer every time something is read
  }

  if (input.nextToken(token, delimiters)) { // process at most one token per loop does not return tokens longer than input.capacity()
    token.debug("after nextToken => ");

    if (token == startCmdStr) {
      running = true;  Serial.print(F("start at ")); Serial.println(loopCounter);

    } else if (token == stopCmdStr) {
      running = false; Serial.print(F("stop at ")); Serial.println(loopCounter);

    } else if (token == resetCmdStr) {
      loopCounter = 0; Serial.print(F("reset Counter:")); Serial.println(loopCounter);

    }// else  // not a valid cmd ignore
  }
  if (timeout.justFinished()) { // nothing received for 0.1secs, terminated last chars so token will be processed.
    input += delimiters[0]; // any delimiter will do
    SafeString::Output.print(F("Input timed out"));
  }
  // rest of code here is executed while the user typing in commands
  if (running) {
    loopCounter++;
    if ((loopCounter % 100000) == 0) {
      Serial.print(F("Counter:")); Serial.println(loopCounter);
    }
  }
}

Please disclose your affiliation, you appear to be the author of the site you've linked multiple times.

Sure will add a 'my' to future posts.  There are a number of other free libraries/tutorials on my site, but that specific link is to the detailed tutorial for SafeString.which I am putting forward as a 'safe' replacement for Arduino Strings.  Check out the tutorial for all the reasons you should be using SafeString instead of Arduino Strings


text:
Ardunio Mega/ATmega2560: Using Port F or K for both analog inputs and digital outputs
On an ATmega2560, can ports have some pins used for analog inputs but others as digtial i/o? Specifically, I only need to use 3-5 analog inputs but have many digital inputs. I would like to use the remaining 3-5 pins as digital outputs if possible.
Additionally, does it make a difference if the port in question is Port F vs. Port K? For Port F, the datasheet seems to imply that all 8 of the pins are analog only if the ADC is enabled:

Port F serves as analog inputs to the A/D Converter.
Port F also serves as an 8-bit bi-directional I/O port, if the A/D Converter is not used.

For Port K, however, the datasheets port description does not have the distinction:

Port K serves as analog inputs to the A/D Converter.
Port K is a 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit).

It seems that this is definitely possible for the Arduino Uno/ATmega328P ADC port (except for the ADC6/7 pins for 32-pin form factors), but I can't seem to find anything confirming for the Arduino Mega/ATmega2560 or distinguishing between whether this is done on Port F or Port K

please provide a link to the datasheet that you are reading ..... also, which section in the datasheet are you referring to regarding port F?

Datasheet: https://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf
I was looking at section 2.3.8

On an ATmega2560, can ports have some pins used for analog inputs but others as digtial i/o?

Yes, the ADC MUX controls the selection of the pin that is connected to the converter. This is independent of the digital pin control.
Cheers!
PS: See the Arduino core source code for further details on the ADC MUX control registers.

Are you afraid to say that the datasheet is wrong? The part "if the A/D Converter is not used" for port F should not be there.

@Jot The ports (F and K) are digital but may also be selected to the ADC via the MUX and sample-and-hold. I guess that you interpret the datasheet as "to use port F for digital IO the ADC module must be turned off"? The is unfortunately wrong IMHO.

The digital input buffer (per pin) can be turned off when used for an analog input signal. The control register DIDRx controls this functionality. It is used to "reduce power consumption in the digital input buffer".

That is indeed how I read it. They can be used at the same time and the datasheet tells otherwise. Matthew had a good reason to ask this question. Even more so, because sometimes the digial pins are disconnected. For example for a atmega328p, when the x-tal is selected, the digital pins are disconnected for those x-tal pins. Beside the jtag, I think the description for the F and K port should be the same. @Matthew please mark the answer as a good answer.


text:
Notoriously unstable ESP8266 MQTT-client
I am doing a project where an ESP8266 receives data from an Arduino Uno and publishes it via MQTT. After a random amount of time, it will stop sending data to my MQTT broker. It might be an hour, it might be a day or two.
It's set up to send data every second, and I made a debug output telling me the WiFi signal quality as well. Seems like that's not it.
I have tried making checks that will reconnect to MQTT if it looses connection, and that it resets itself if it looses WiFi connection. I'm out of ideas right now, any help appreciated!
Here's my MQTT reconnnect function

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("pressure/debug", "ESP8266: reconnected!");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

and here's where it checks for WiFi
void checkWifiConnection() {
  if (WiFi.status() != WL_CONNECTED)
  {
    int countdown = millis() + 15000;
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      if (countdown > millis()) {
      delay(500);
      Serial.println("Connecting to WiFi..");
      } else {
        Serial.println("Timed out! Restarting...");
        ESP.reset();
      }
  }
  }
}

Both are run every loop.
The arduino sends the data like it's supposed to, and I've lowered the connection speed to 19200bps in order to ensure a more stable connection, using SoftwareSerial. Any more things i could monitor? I tried it with two different ESP8266MOD/"ESP07" boards with the same result.
Here's a debug output:
09:13:05.039 -> unpub data 0/ AP:Akvasafe/ RSSI:-69 dB / Vcc:3519mV / free heap:49440 / fragmentation:1%

use esp8266 arduino core 2.4.2

Have you tried a more stable MQTT library? You haven't said which one you're using now.

@Juraj I'm using 2.5.0, is it not advisable?

@JaromandaX I'm using PubSubClient, it seemed to me like it was the most popular one out there.

2.5.0 has many problems

Popular doesn't mean stable :p but that one, when I used to use it, was fine

I use adafruit mqtt library. After a few fixes, it is running very stable.
Tips:
1) Make sure you put subscribe line BEFORE connecting to mqtt (you can put it in setup and connect to mqtt in loop)
Like:
Setup: mqtt.subscribe(&motor);
Loop: MQTT_connect();
Yes, you can both publish and subscribe at the same time.
2) IN THE LINE: Adafruit_MQTT_Client(server,port,user,pass)
CHANGE TO THIS: Adafruit_MQTT(server,port,clientid,user,pass)
Use this with client id (MUST BE UNIQUE (EG: Different for all clients))
or your client will be kicked off when other client with same id connects.
3) Convert value.lastread from char* to int : int val = atoi((char *)sensor.lastread);
More about ESP8266 & ESP32 : http://github.com/ajaybnl


text:
Esp32 sending a wav file to API via POST
I'm trying to send a .wav file to an API with an ESP32 using a HTTP Post request with a multipart/Form-data content type.
I can already send the API Key as it is a plain key and get a return from the server, but I fail on how to add the .wav file into the post request.
I am currently reading the wav file from an sd card, it's 5 secs long 16 bit,11025Hz. and about 400 kb.
If anyone have experience with this, your help would be greatly appreciated!
This is the code snippet where I send the key and where the data should come;
I tried putting the code into a buffer as and concatting the data but I'm not sure if this is the right way to do it
char buf[1024];
 if (https.begin(client, host, port, path)) {

   //https.addHeader("Content-Type", "multipart/Form-data");
   //int httpsCode = https.POST("apikey = XXX");
Serial.println(WavFile);
     https.addHeader("content-type", "multipart/form-data; boundary=----123");
    String HTTPSPost ="------123\r\nContent-Disposition: form-data;
`

----------

name=\"apikey\"\r\n\r\XXX\r\n------123--\r\nContent-Disposition: form-data; name=\"wav\"; filename=\"test444.wav\"\r\nContent-Type: audio/x-wav\r\n\r\n\r\n";
  `
    //wav recording Comes here
    String WavData ;
   // for (int i = 0; i < 1024; i++) WavData.concat(buf[i]);; // Tried to put Wav file in a buffer
  // Serial.println(WavData);

    String End = "------123--";
    String full = HTTPSPost + WavData + End;
    int httpsCode = https.POST(full );
        if (httpsCode > 0) {
              if (httpsCode == HTTP_CODE_OK) {
                res =  https.getString();
                JsonObject& obj = jb.parseObject(res);

                String token = obj["error"];
                if (obj.success()) {

                } else {
                    res = "failed to parse json";
                }
              }
        } else {
            res = "failed to Post";
        }
   } else {
    res = "failed to connect to server";
   }
https.end();
return res;
}
`

better code because httpclient can't do sd cards, but wificlient can;
File file = SD.open("/xxx.wav");

if (!client.connect("XXX", 443)) {
  Serial.println("Connected FAILED!");
  return;
}

Serial.println("Connected ok!");

client.println("POST  HTTP/1.1");
client.println("Host: ");
client.println("Cache-Control: no-cache");
client.println("Content-Type: multipart/form-data; boundary=----123");
client.println();
client.println("------123");
client.println("Content-Disposition: form-data; name=\"grant_type\"");
client.println();
client.println("client_credentials");
client.println("------123");
client.println("Content-Disposition: form-data; name=\"apikey\"");
client.println();
client.println("XXX");
client.println("------123");
client.println("Content-Disposition: form-data; name=\"wav\"; filename=\"xxx.wav\"");
client.println("Content-Type: audio/wav");
client.println("");
client.print("Content-Length: ");
client.println(file.size());
//client.println();
//while (file.available()){
//      client.write(file.read());
//}
client.write(file);
client.println("------123--");
Serial.println(">>><<<");
if (client.available())
    {
      String serverRes = client.readStringUntil('}');
      Serial.println(serverRes);
    }

what is HTTPSPost+buf[1024]+End? you can't put binary data into a String. a 0 would be end of the data

You're right, it's a leftover from me trying to put the buffer into the string... the Full string should be placed into it, edited that part.

Is there a way to convert it, or how to make it 'correct'? I guess that is my question

The esp32 only has 512kb of RAM. Putting a 400kb wave file, plus some HTTP headers, in memory will probably not fit.

you can't do it with HTTPClient. use WiFiClient. if the file is in SPIFFS you can use client.write(file) for the binary part of the POST request

Thanks! I tried using it with WiFiClient now, can you client.write(file); for a file on an sd?

yes you can use client.write() for SD card file too

Thanks for all the input Juraj! I edited the Q an added the better code, but there seems to be a problem with the apikey still, is it the correct way to implement it? Can I still ask this question here? I don't want to overload the question :)

try to add content-length to every part


text:
Hand-held programmable device needed
Hopefully this question is not too off-topic for this board. I need a ready-made programmable hand-held device with an ethernet-connection. Something like an Arduino with batteries and display and some buttons in a box.
This is for my company so a complete ground-up assembly is too expensive and time-consuming in this case. Any hints to companies that produce something like this are welcome. And yes, I tried searching with different search-engines already. :-)
Thanks for your time!

And what is the purpose of this device? Connect to ethernet and.... intercept and analyse the traffic? Why does it need to be handheld when it is going to be wired? With PoE you don't even need a battery.

A Leonardo ETH with a keypad shield and a printed box perhaps?
Use PoE or two 18650 cells for power supply.

Use a cheap or preowned laptop with linux and wireshark.

try raspberry pi 3, it comes with all the features you needed. You need to take care of battery part.

I have no opinion about this hardware (I don't own it) so please treat my answer as information only. When I was searching through web I found M5Stack
It looks like hardware made for IoT development.
It has a LCD and 3 buttons and think it can be programmed using ArduinoIDE.
It's designed that you can design any hardware you want and "stack" the device on top of it. Found if available to buy from China for below 30USD.

https://www.youtube.com/watch?v=U2es-l4z2Zg

That's a really nice find, and what looks to be a fantastic module. I'm going to have to get myself one to play with and port DisplayCore to - and of course provide full support in UECIDE...

I thought that there might be an Arduino-based solution for my task, that's why I chose this board for my question. I'm sorry if I wasted a bit of you time and will take the answers I got so far as a starting point. Thanks to those who commented!


text:
Send ECG signal with NRF24L01 from Arduino to Raspberry Pi 3
I'm using nRF24L01 to send ECG samples from an Arduino to Raspberry Pi, the type of sample is double after denoising, and I stock them in a byte[8] to send 8 by 8 sample. When I print the sample before stockage that show the good results, but if I print data stored in the byte the signal show a lot of fluctuations. In Raspberry Pi, I can read correctly byte data like transmitted, but if I send them in a vector of double or int in reception (python) don't give the same frame transmitted.
#include <IIRFilter.h>
#include <FIRFilter.h>

#include <SPI.h> // Call SPI Library
#include <nRF24L01.h> // Call NRE Version Library
#include <RF24.h> // RF24 Header File

#define CE_PIN  9
#define CSN_PIN 10
const uint64_t pipe = 0xF0F0F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);

const int ECG_samplefreq  = 200;//sampling frequcy
const int DC_offset = 511;

const double b_lp[] = {0.0026, 0.0155, 0.0388, 0.0517, 0.0388, 0.0155, 0.0026};
const double a_lp[] = {1.0000, -2.3797, 2.9104, -2.0551, 0.8779, -0.2099, 0.0218};

IIRFilter lp(b_lp, a_lp);
unsigned int i = 0;

void setup() {
  Serial.begin(9600);
  radio.begin();//Intializing NRF24L01 Module
  radio.setPALevel(RF24_PA_MAX);
  radio.setChannel(0x76);
  radio.openWritingPipe(pipe);// For Transmitting Operation, Must OpenWritingPipe
  radio.enableDynamicPayloads();
  radio.powerUp();
  pinMode(7, INPUT); // Setup for leads off detection LO +
  pinMode(8, INPUT); // Setup for leads off detection LO -

}
void loop() {
  const static unsigned long ECG_interval  = round(1e6 / ECG_samplefreq);  //sampling period = 5000 ms => 200 sample by 1 seconde
  static unsigned long ECG_prevmicros = micros();
  byte  s[8] = {0};

  if ((digitalRead(7) == 1) || (digitalRead(8) == 1)) {
    Serial.println('!');
  }

  else {
    for (int i = 0; i < 8; i++)
    {

      if (!Serial) {
        ECG_prevmicros = micros();
      }
      else if (micros() - ECG_prevmicros >= ECG_interval)
      {
        int value = analogRead(A5);
        double filtered = lp.filter( value - DC_offset);

        filtered = round( filtered + DC_offset);
        s[i] =  filtered
        Serial.println( s[i]);
        ECG_prevmicros += ECG_interval;

      }
    }
    radio.write(&s, sizeof(s) ); // sending in real time ECG sample. 8 sample by transmission . 8 => 4 oct of one sampe = 32 oct by transmission.

  }
}

the problem thant i put in s[i] a double of four octs. im searching how can i send them whithout byte array, and receive the correctly. So thankful for your help

I am not a math genius but when I get you right you are trying to send 8 double values as a series of 8 x 8 bytes. My calculator tells me the result is 64 but you can only transmit 32 bytes at once using nRF24L01+. So maybe you should provide us some code and describe its function to us so we will be able to understand your problem and provide some help.

Even if the OP is trying to send one double value per message (8 x 8 bytes), does one really need all that precision?  Perhaps they can round off the double values to fit more data values within a 32-byte data packet.  Show the code and explain a little more what is going on.

I see multiple flaws in your code:

radio.write(&s, sizeof(s)); does not what you think it would. The correct statement would be radio.write(s, sizeof(s)); without the ampersand.
You are using double. Not using floating point numbers at all would be preferable.
Your s is of type byte. Thus it only holds 8 bytes. So your floating point calculations are being truncated to the range [0, 255]. From your problem description this is not what you are trying to achieve, I think.

Yes you're right. I mislaid in the storage in the byte variable s[8]; I changed the type of samples to int32_t; similarly the type of byte emission vector to int32_t s[8]. the problem now at the raspberry level I get a 32-bit list instead of 8 samples int32_t


text:
Arduino and SIM900 unavailable all the time
I have the a problem with my arduino MEGA 2560 and the SIM900 module.
I want to save the outputs of the AT commands, but I never get a chance. If I print mySerial.available() I only get 0.
Sending SMS works fine on the other hand.
Initializing...
AT+CMGF=1
AT+CNMI=2,2,0,0,0

OK
Done
AT+CMGL="REC UNREAD"

OK
0
0
0
0
0
0
0
0
0
0
0

This is the sketch I use:
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(11, 10); //SIM900 Tx & Rx is connected to Arduino #7 & #8
String incoming="";
String incoming2="";
String messages="Test";
String auth_num="+49xxxxxxxxx";
char incoming_char=0;

String response = "";

const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;

int period = 6000;
unsigned long time_now = 0;

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT+CMGF=1");
  mySerial.println("AT+CNMI=2,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
  //mySerial.println("ATE0");
  updateSerial();
  Serial.println("Done");

  //sms_versenden("xxxxxxxx", "text");
}

void loop()
{
  updateSerial();
  Serial.println(mySerial.available());
  if(millis() - time_now > period){
    time_now = millis();
    if(sms_erhalten()){
      sms_autorisiert();
    }
  }
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

void sms_versenden(String rufnummer,String text)
{
  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  if(rufnummer.startsWith("0")){
    rufnummer.remove(0,1);
    mySerial.print("AT+CMGS=\"+49");
    mySerial.print(rufnummer);
    mySerial.println("\"");
  }else if(rufnummer.startsWith("+49")){
    mySerial.print("AT+CMGS=\"");
    mySerial.print(rufnummer);
    mySerial.println("\"");
  }else{
    return;
  }
  updateSerial();
  mySerial.print(text); //text content
  updateSerial();
  mySerial.write(26);
}

boolean sms_erhalten()
{
  mySerial.print("AT+CMGL=\"REC UNREAD\"\r");
  //recvWithEndMarker();
  Serial.println(mySerial.available());
  delay(30);
  while (mySerial.available()){
    String inData = mySerial.readStringUntil('\n');
    Serial.println("Got reponse from SIM900: " + inData);
  }
  /*if(mySerial.available()>0){

    incoming = mySerial.readString();
    Serial.print(incoming);
    delay(10);
  }*/
  updateSerial();
  if(incoming.startsWith("+CMGL:"))
  {
    return true;
  }
  else{
    return false;
  }
}

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;

    while (mySerial.available() != 0 && newData == false) {
        rc = mySerial.read();
        updateSerial();
        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(receivedChars);
        newData = false;
    }
}
String getResponse() {
    while(mySerial.available()>0){
        response += mySerial.read();
    }
    return response;
}

Thanks in advance for every idea.
Bravodelta

if you turn on echo, it doesn't print the commands back? check the wiring

@Juraj The echo is on and as you can see in the first code block I get an answer, but I can't save it in a String.

try mySerial.println("AT+CMGL=\"REC UNREAD\"");

@Juraj Sadly this doesn't work either

Rather than creating your own function used SerialEvent function in arduino. It acts as a serial interrupt in arduino. For example:
String inputString;
void serialEvent() {
      while (Serial.available()) {
        // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag so the main loop can
        // do something about it:
        if (inChar == '\n') {
          Serial.Println(inputString);
        }
      }
    }

don't use serialEvent. it has no advantage. it is the same as checking Serial.available() in loop

The serial event system does not act as an interrupt. It is no different to adding if (Serial.available())... in your loop() function.  I wish Arduino had never implemented it - it's a stupid idea.

@Juraj why no for using serialevent function? What harm does it causes?

@Majenko had you tried serialevent function?

@Vaibhav Worse than that - I have had to implement it on a compatible platform, and had to take a shower in sodium hydroxide afterwards to get the taint off my skin...

it gives a false expectation that it will be executed no matter what you do in the loop(): delays, endless loops


text:
How to Connect TFT LCD display with NodeMCU?
I am doing this project wherein I want to display some image on the LCD screen. I am having a problem with the connecting nodemcu with my TFT LCD screen. I cannot find any references. Does a TFT screen go well with a NodeMCU? if yes, please help
I tried taking refrence from this website but i ended up damaging my nodeMCU
http://nobrok.com/connecting-tft-lcd-touch-screen-with-nodemcu-esp8266/
Also attaching images of TFT display and my NodeMCU.

It would be great if you can help. Thanks :)

please provide a link to the display datasheet ...... from the picture, it looks like the display has SPI interface  ( the four SD_ pins )

it's of some chinese vendor i looked up on their website:   http://www.mcufriend.com/main.html But can't find datasheet for this specific device. But i think it's a modified version of the ILI9341 as mentioned on their website.

According to its web site, the TFT module does have SPI interface. https://www.jixin.pro/product/717.html
The site is in Chinese though.

That kind of TFT doesn't work well with the NodeMCU (or the ESP8266 in general).
Simply put: that TFT requires a lot of GPIO pins - 10 at an absolute bare minimum, but better if you have more available.  The ESP8266 doesn't have many IO pins - and some of them are very sensitive about what they can be connected to without affecting the boot process.
It is better to choose a TFT screen with an SPI interface, which uses far fewer pins - although is slower to refresh the screen data.
If you are careful with your GPIO selection it may be possible to work with that screen. There are no specific requirements for what pins need to be connected to where (as far as hardware functionality goes), so it's up to you to find the right combination that doesn't cripple the boot process (stay away from GPIOs 0, 2 and 15 if you can).

Thanks for the reply! I tried the connections given on this link   https://forum.arduino.cc/index.php?topic=500773.0  but could not get it to work. If you find something or do have knowledge about it please share. Thanks again!


text:
RFID Door Lock Coding Errors
I am trying to recreate an RFID door lock that I saw on the Arduino project hub but have ran into several issues. I had to manipulate the code slightly to make sure it was including the correct libraries and I think that solved some issues but not all. If anyone could take a look at my code and help me out that'd be awesome, I am pretty new with coding and need all the help I can get.
Thank you!
Here are the error messages I receive when trying to upload the code to my arduino:
Arduino: 1.8.8 (Mac OS X), Board: "Arduino/Genuino Uno"
rfid_based_door_automatic_management_system:66:17: error: expected unqualified-id before numeric constant
 #define SDA_D1O 9
                 ^
/Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino:70:9: note: in expansion of macro 'SDA_D1O'
 MFRC522(SDA_D1O, RESET_D1O);
         ^
rfid_based_door_automatic_management_system:66:17: error: expected ')' before numeric constant
 #define SDA_D1O 9
                 ^
/Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino:70:9: note: in expansion of macro 'SDA_D1O'
 MFRC522(SDA_D1O, RESET_D1O);
         ^
/Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino: In function 'void setup()':
rfid_based_door_automatic_management_system:120:10: error: expected unqualified-id before '.' token
   MFRC522.initial();
          ^
/Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino: In function 'void loop()':
rfid_based_door_automatic_management_system:137:12: error: 'class MFRC522' has no member named 'isCard'
   if( rfid.isCard() )
            ^
rfid_based_door_automatic_management_system:141:16: error: 'class MFRC522' has no member named 'readCardSerial'
       if( rfid.readCardSerial() )
                ^
rfid_based_door_automatic_management_system:152:33: error: 'class MFRC522' has no member named 'serNum'
               Serial.print(rfid.serNum[i], HEX);
                                 ^
rfid_based_door_automatic_management_system:154:30: error: 'class MFRC522' has no member named 'serNum'
               lcd.print(rfid.serNum[i],HEX);
                              ^
rfid_based_door_automatic_management_system:165:42: error: 'class MFRC522' has no member named 'serNum'
               if( My_RFID_Tag[i] != rfid.serNum[i] )
                                          ^
rfid_based_door_automatic_management_system:274:8: error: 'class MFRC522' has no member named 'halt'
   rfid.halt();
        ^
Multiple libraries were found for "LiquidCrystal.h"
 Used: /Users/gavinmiles/Documents/Arduino/libraries/LiquidCrystal
 Not used: /Applications/Arduino.app/Contents/Java/libraries/LiquidCrystal
Multiple libraries were found for "Servo.h"
 Used: /Users/gavinmiles/Documents/Arduino/libraries/Servo
 Not used: /Applications/Arduino.app/Contents/Java/libraries/Servo
exit status 1
expected unqualified-id before numeric constant
/Users/gavinmiles/Downloads/untitled_file.ino

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
/*
 *  RFID Module RC522
 *  Simple Project:- Arduino will read RFID Tag and Display To the Serial Monitor!
 *
 *  RFID RC522 and Arduino Uno Pin Configuration
 *
 *  RFID RC522          Arduino Uno
 *  SS/SDA              D10
 *  SCK                 D13
 *  MOSI                D11
 *  MISO                D12
 *  IRQ                 Not Connected
 *  GND                 GND
 *  RST                 D9
 *  3.3V                3.3V
 *
 *  //Note: We connected LCD to the Analog Pins.
 *  Remember, Analog Pins can be act as a Digital Pins,
 *  But Digital Pins CAN NOT be act as a Analog Pins.
 *
 *  LCD(16x2) Connections
 *
 *  VSS pin to GND
 *  VCC pin to 5V
 *  //We are connecting "Contrast pin to GND for Maximum Brightness"
 *  //You can also connect it to 10K Pot if you wish to change the Brightness Of LCD.
 *  VEE pin to GND
 *  RS pin to Analog pin A0
 *  R/W pin to ground
 *  Enable pin to Analog pin A1
 *  D4 pin to Analog pin 5
 *  D5 pin to Analog pin 4
 *  D6 pin to Analog pin 3
 *  D7 pin to Analog pin 2
 *  LED+ pin to POWER
 *  LED- pin to GND
 *
 *  Servo is Connected to Digital Pin 5
 *
 *  RGB LED
 *  From RGB LED, We need Only Red and Green Color,
 *  So we are not connecting Blue pin of the RGB.
 *
 *  Red pin to Digital pin 6
 *  Green pin to Digital pin 7
 *
 *  Buzzer to Digital pin 8
 *
 *
 *  Note:- RFID uses SPI Protocol to transfer the information.
 *  I took the Melody(for the Buzzer) from,
 *  File -> Examples -> Digital -> ToneMelody
*/

//Include sections
#include <MFRC522.h>
#include <SPI.h>
#include <LiquidCrystal.h>
#include <Servo.h>
#include "pitches.h"

//Define Component to Arduino Pins
/* Define the DIO used for the SDA (SS) and RST (reset) pins. */
#define SDA_D1O 9
#define RESET_D1O 8

/* Create an instance of the RFID library */
MFRC522(SDA_D1O, RESET_D1O);
#define SS_PIN 10
#define RST_PIN 9

#define SERVO_PIN 5

#define Red_LED 6
#define Green_LED 7

#define Buzzer 8

//initialize the library with the numbers of the interface pins
LiquidCrystal lcd(A0, A1, A2, A3, A4, A5);
Servo DoorLock;
MFRC522 rfid(SS_PIN, RST_PIN );

//Unique ID of RFID Tag, which you want to give access.
int My_RFID_Tag[5] = {0x58,0x76,0x17,0x10,0x29};

//variable to hold your Access_card
boolean My_Card = false;

// notes in the melody, taken from:
//File -> Examples -> Digital -> ToneMelody
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup()
{
  // put your setup code here, to run once:
  //set the pins as an input/output
  pinMode(Red_LED,OUTPUT);
  pinMode(Green_LED,OUTPUT);
  pinMode(Buzzer,OUTPUT);

  //Servo Connnected to pin Digital Pin 5
  DoorLock.attach(SERVO_PIN);
  //open the serial port at 9600 baudrate.
  Serial.begin(9600);
  //Initialise the LCD to 16x2 Character Format
  lcd.begin(16,2);
  //Initialise Servo and RFID
  SPI.begin();
  MFRC522.initial();
}

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

  //First Assume detected card(Or tag) is My_Card,
  //Then later we will check is it My_Card or not!
  My_Card = true;
  DoorLock.write(0); //Servo at 0 Position, Door is Closed.
  lcd.clear();
  lcd.print("Robodia Technology");
  lcd.setCursor(0,1);
  lcd.print("gy Solutions!");

  //Check if any RFID Tags Detected or not?
  if( rfid.isCard() )
  {
      //if RFID Tag is detected, check for the Unique ID,
      //and print it on the Serial Window
      if( rfid.readCardSerial() )
      {
          lcd.clear();
          lcd.print("UNIQUE ID is:- ");
          delay(500);
          lcd.setCursor(0,1); //Set LCD Cursor to Second Row, First Character

      //Unique id is 5 Digit Number.
          //Printing in HEX for better Understanding
          for( int i = 0; i < 5; i++ )
          {
              Serial.print(rfid.serNum[i], HEX);
              Serial.print(" ");
              lcd.print(rfid.serNum[i],HEX);
              lcd.print(" ");
          }
          delay(500);

      //Compare this RFID Tag Unique ID with your My_RFID_Tag's Unique ID
          for(int i = 0; i < 5; i++)
          {
              //if any one Unique ID Digit is not matching,
              //then make My_Card = false and come out from loop
              //No need to check all the digit!
              if( My_RFID_Tag[i] != rfid.serNum[i] )
              {
                My_Card = false;
                break;
              }
          }
          Serial.println();
          delay(1000);

          //If RFID Tag is My_Card then give access to enter into room
          //else dont open the door.
          if(My_Card)
          {
            Serial.println("\nWelcome To Your Room, Robodia!");
            lcd.clear();
            lcd.print("Welcome to Your");
            lcd.setCursor(0,1);
            lcd.print("Room, Robodia!");
            delay(2000);

            //Turn on the Green LED as an indication of permission is given
            //to access the room.
            digitalWrite(Green_LED,HIGH);

            //Buzzer Config, taken from:
            //File -> Examples -> Digital -> ToneMelody
            // iterate over the notes of the melody:
            int i = 0;
            while(i < 2)
            {
              for (int thisNote = 0; thisNote < 12; thisNote++)
              {
                // to calculate the note duration, take one second
                // divided by the note type.
                //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
                int noteDuration = 1000 / noteDurations[thisNote];
                tone(8, melody[thisNote], noteDuration);
                // to distinguish the notes, set a minimum time between them.
                // the note's duration + 30% seems to work well:
                int pauseBetweenNotes = noteDuration * 1.30;
                delay(pauseBetweenNotes);
                // stop the tone playing:
                noTone(8);
              }
              i =  i + 1;
              delay(500);
            }
            delay(1000);

            //Now, Open the Door with the help of Servo Motor
            DoorLock.write(180);
            delay(200);
            lcd.clear();
            lcd.print("Door is Open");
            lcd.setCursor(0,1);
            lcd.print("Now!");
            delay(2000);
            lcd.clear();

            //Give 10 Sec delay to enter into room
            //After that door will again closed!
            for(int i = 10; i > 0; i--)
            {
              lcd.print("Door will close");
              lcd.setCursor(0,1);
              lcd.print("in ");
              lcd.print(i);
              lcd.print(" Sec.HurryUp!");
              delay(1000);
              lcd.clear();
            }

            //Now,Door is closed and Green LED is Turned-Off.
            DoorLock.write(0);
            digitalWrite(Green_LED,LOW);
            delay(200);
            lcd.clear();
            lcd.print("Door is Close");
            lcd.setCursor(0,1);
            lcd.print("Now!");
            delay(2000);
          }

          // If RFID Tag is not My_Card then
          // Do not open the Door and
          //Turn-On Red LED and Buzzer as an indication of Warning:
          //Somebody else is trying to enter into your room.
          else
          {
            Serial.println("\nGet Out of Here !");
            lcd.clear();
            lcd.print("Card isNOT FOUND!");
            lcd.setCursor(0,1);
            lcd.print("Get Out of Here!");

            for(int i = 0; i < 7; i++)
            {
              digitalWrite(Buzzer, HIGH);
              digitalWrite(Red_LED,HIGH);
              delay(500);
              digitalWrite(Buzzer, LOW);
              digitalWrite(Red_LED,LOW);
              delay(500);
            }
            delay(1000);
          }
      }
   }
  //Put RFID Reader into Halt, untill it not detects any RFID Tag.
  rfid.halt();
}

How about adding a link to the original project and some more information of a) your modifications and b) your issues? "Here's my code, tell me what's wrong" isn't really nice - and it does not comply to the rules of this forum.

you say RFID Door Lock Coding Errors and solved some issues but not all..... are we supposed to guess what the errors and the issues are?

I will find the original post and post the link. Sorry for the lack of information, I'm new to the site. Sorry if the original post came off as rude mic those weren't my intentions. Just looking for help and thought I'd ask if anyone could take a look at it and see what I missed. Thank you

https://create.arduino.cc/projecthub/user8523373/rfid-based-automatic-door-system-7b2065?ref=platform&ref_id=424_popular__intermediate_&offset=30 here is the link to the original project. All I've done is change out the rfid library for the MFRC522 library.

I had seen many errors in your code. Some of them are as follows

MFRC522.initial(); replace it with rfid.initial();
Libraries such as liquidcrystal, servo are default libraries in arduino so if you had download them from external source and copied them in your library folder please remove them.
This logic won't help as if the first id didn't match it will break the loop and and comparison won't go further with other and your will always find false as a result in this case.
      for(int i = 0; i < 5; i++)
  {
      //if any one Unique ID Digit is not matching,
      //then make My_Card = false and come out from loop
      //No need to check all the digit!
      if( My_RFID_Tag[i] != rfid.serNum[i] ) // suggested change if( My_RFID_Tag[i] == rfid.serNum[i] )
      {
        My_Card = false;//My_Card = true
        break;
      }
  }

Library functions used in code are different from those available in library, open library file and search for those function used for same purpose.
Remove them
#define SDA_D1O 9
#define RESET_D1O 8
MFRC522(SDA_D1O, RESET_D1O);

you are already defining them and using them here in your code
#define SS_PIN 10
#define RST_PIN 9
MFRC522 rfid(SS_PIN, RST_PIN );


text:
Digispark Micro (ATTINY85) not working on Macbook Pro 2016
I just bought 2 Digispark Micro to start learning some Arduino things.
But when I try to upload the code to my Digispark, it just send me an "Device search timed out" error.
My Digispark is plugged with an USB-C to USB connector and the Red dot on the Digispark is working. The connector is working well with any other device.
Arduino app (1.8.9) settings:

Tools

Board → Digispark (Default - 16.5 mhz)
Programmer → Micronucleus

I tried using the micronucleus CLI, but, even if I try plug/unplug several times (~10s between each unplug/plug) I got this :
> Please plug in the device ...
> Press CTRL+C to terminate the program.

Digisparks are known to have problems with USB3 ports (which your USB-C adaptor probably provides). Try using a cheap USB2 hub between the DigiSpark and the adaptor.
It's always a good idea to use a cheap USB hub between whatever experimental device you want to connect and your machine, so that if you wire something up incorrectly you don't end up frying an expensive laptop. This is particularly true for a device such as the digispark which does not have a real USB interface but really bit-bangs the protocol out of ordinary I/O pins.
There is no guarantee that the hub will protect you from all wiring mistakes, but it's an added level of protection.

Hi @JayEye ! Thanks for those information. I'm already using this device (https://www.apple.com/fr/shop/product/MJ1M2ZM/A/adaptateur-usb-c-vers-usb?afid=p238%7Cs4VqawkmI-dc_mtid_187079nc38483_pcrid_102671600198_&cid=aos-fr-kwgo-pla-btb--slid-----product-MJ1M2ZM/A-FR). Isn't it enoough?

Good thing I speak French :)
No, this will not be enough; this just converts the physical connector (USB-C to USB-A). You need something like https://www.amazon.com/Black-4-Port-High-Speed-USB/dp/B002FFT8Z6 between the adaptor you have and the digispark


text:
How can I send AT commands to HM-10 module from my android phone?
Earlier today, I was able to connect flawlessly to my HM-10 module via the Arduino serial monitor. I think I then changed some settings without thinking and now I can no longer connect to it. No errors, nothing. I have tried every baud setting but to no avail. I am able to connect to it through my Android phone but is there an app where I can send AT commands just like the Arduino serial monitor. I'm thinking I could do this to run the at+reset command to factory reset it? Are there any other ways of resetting the module?

what does this mean? changed some settings

No. You are the wrong end of the connection. Like trying to turn a light on by squeezing the bulb (sorry, I'm usually the king of analogies, but I have come down with a cold and I can't come up with anything even remotely realistic...)

@jsotola Through the arduino serial monitor, I was playing with at+type, at+baud and at+mode.

@Majenko So is there a way of hard resetting the board then?


text:
Can someone help me to change this code to u8g2
I would like to change this clock to u8g2.
It works fine with the esp8266 and oled 128x64.

I would start by including the u8g2 library with #include
and all display. with u8g2. replace.
What else should I consider.?
Thanks Else
This is my Code
#include <ESP8266WiFi.h>
#include <WifiUDP.h>
#include <String.h>
#include <Wire.h>
#include <SSD1306.h>
#include <SSD1306Wire.h>
#include <NTPClient.h>
#include <Time.h>
#include <TimeLib.h>
#include <Timezone.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
// Define NTP properties
#define NTP_OFFSET   60 * 60      // In seconds
#define NTP_INTERVAL 60 * 1000    // In miliseconds
#define NTP_ADDRESS  "ca.pool.ntp.org"  // change this to whatever pool is closest (see ntp.org)

// Set up the NTP UDP client
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, NTP_ADDRESS, NTP_OFFSET, NTP_INTERVAL);

// Create a display object // SSD1306 display(0x3c, SDA, SCL);
SSD1306  display(0x3c, D2, D1); //0x3d for the Adafruit 1.3" OLED, 0x3C being the usual address of the OLED

//U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4, /* reset=*/ U8X8_PIN_NONE);

const char* ssid = "my ssid";   // insert your own ssid
const char* password = "my password";    // and password
String date;
String t;
const char * days[] = {"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"} ;
const char * months[] = {"Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"} ;

void setup ()
{
  Serial.begin(115200); // most ESP-01's use 115200 but this could vary
  timeClient.begin();   // Start the NTP UDP client

  Wire.pins(4, 5);
  Wire.begin(4, 5);
  display.begin();
  display.flipScreenVertically();

  // Connect to wifi
  Serial.println("");
  Serial.print("Connecting to ");
  Serial.print(ssid);
  display.drawString(0, 10, "Connecting to Wifi...");
  display.display();
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi at ");
  Serial.print(WiFi.localIP());
  Serial.println("");
  display.drawString(0, 24, "Connected.");
  display.display();
  delay(1000);
}

void loop()
{
  if (WiFi.status() == WL_CONNECTED) //Check WiFi connection status
  {
    date = "";  // clear the variables
    t = "";

    // update the NTP client and get the UNIX UTC timestamp
    timeClient.update();
    unsigned long epochTime =  timeClient.getEpochTime();

    // convert received time stamp to time_t object
    time_t local, utc;
    utc = epochTime;

  /*  // Then convert the UTC UNIX timestamp to local time
    TimeChangeRule usEDT = {"EDT", Second, Sun, Mar, 2, -0};  //UTC - 5 hours - change this as needed
    TimeChangeRule usEST = {"EST", First, Sun, Nov, 2, -60};   //UTC - 6 hours - change this as needed
    Timezone usEastern(usEDT, usEST); */

    TimeChangeRule CEST = {"CEST", Last, Sun, Mar, 2, 60};     //Central European Summer Time
    TimeChangeRule CET = {"CET ", Last, Sun, Oct, 3, 0};       //Central European Standard Time
    Timezone CE(CEST, CET);

    local = CE.toLocal(utc);

    // now format the Time variables into strings with proper names for month, day etc
    date += days[weekday(local)-1];
    date += ", ";
    date += day(local);
    date += " ";
    date += months[month(local)-1];
    date += " ";
    date += year(local);

    // format the time to 12-hour format with AM/PM and no seconds
    if(hour(local) < 10)  // add a zero if houre is under 10
      t += "0";
    t += hour(local);
    t += ":";
    if(minute(local) < 10)  // add a zero if minute is under 10
      t += "0";
    t += minute(local);
    t += ":";
    if(second(local) < 10)  // add a zero if minute is under 10
      t += "0";
    t+= second(local);

    // Display the date and time
    Serial.println("");
    Serial.print("Local date: ");
    Serial.print(date);
    Serial.println("");
    Serial.print("Local time: ");
    Serial.print(t);

    // print the date and time on the OLED
    display.clear();
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.setFont(ArialMT_Plain_24);
    display.drawStringMaxWidth(64, 10, 128, t);
    display.setFont(ArialMT_Plain_10);
    display.drawStringMaxWidth(64, 48, 128, date);
    display.fillRect(1, 0, 126*timeClient.getSeconds()/59, 2);
    display.display();
  }
  else // attempt to connect to wifi again if disconnected
  {
    display.clear();
    display.drawString(0, 10, "Connecting to Wifi...");
    display.display();
    WiFi.begin(ssid, password);
    display.drawString(0, 24, "Connected.");
    display.display();
    delay(1000);
  }

  delay(1000);    //Send a request to update every 10 sec (= 10,000 ms)
}

Without really looking at your code: You will have to replace all code, that does something with the display, with code for the new display library. Have you tried that? What was your problem there?

So I have a litle problem with:
display.fillRect(1, 0, 126timeClient.getSeconds()/59, 2); old
u8g2.fillRect(1, 0, 126timeClient.getSeconds()/59, 2); -> new
'class U8G2_SSD1306_128X64_NONAME_F_SW_I2C' has no member named 'fillRect'
and
display.drawStringMaxWidth(64, 48, 128, date); -> old
u8g2.drawStringMaxWidth(64, 48, 128, date); -> new

Please edit your question do add these information. 2. Since these are completely different libraries, the functions won't be the same. You cannot just rename the display object for the new library. You have to go through the code line by line and replace each call to the former library by a suitable call to the new library, that will reach the goal of that line. Changing between different libraries is mostly a complex task (unless they are really designed for being exchangeable for one another. Have you searched the documentation of the new library for a fitting function?


text:
Interrupt triggering using DHT-11
I am new at arduino.
I want to write a sketch that would print the message if the temperature grows greater than 30 C.
Here is my sketch can you please tell me what's wrong with it
#include "DHT.h"
#define DHTTYPE DHT11
#define dht_dpin D3

DHT dht(dht_dpin, DHTTYPE);

void setup()
{
 Serial.begin(9600);
 }
void loop()
{
 float t = dht.readTemperature();
 Serial.print("temp=");
 Serial.println(t);
 attachInterrupt(dht_dpin, IntCallback, CHANGE);
}
void IntCallback()
{
  float t = dht.readTemperature();
  if(t>30)
  {
    Serial.print("Alert");
  }
}

remove lines starting from the line with attachIterrupt until the line before if (t > 30)

You can't use an interrupt the way you are attempting to. Attaching an interrupt to a pin like that will cause the interrupt to trigger any time the digital pin's value changes. The DHT11 uses serial communication to send temp values to the Arduino. Serial communication uses lots and lots of on/off pulses on the signal line to send characters of data. Your interrupt will fire every time the DHT11 toggles the signal line.
You need to read the temp from the DHT11 in your loop, and then add an if statement that does what you want when the temp exceeds your threshold. (It looks like you just need to get rid of the attachInterrupt() call, and instead call IntCallback() every couple of seconds.

Hi.Thanks for helping but i am a noob in this. I don't know much about Interrupt and callback. So if you don't mind can you please modify the sketch for me. That would a great help.

You don't even need an interrupt.Modification:
#include "DHT.h"
#define DHTTYPE DHT11
#define dht_dpin D3

DHT dht(dht_dpin, DHTTYPE);

void setup()
{
 Serial.begin(9600);
 }
void loop()
{
 float t = dht.readTemperature();
 Serial.print("temp=");
 if(t>30)
  {
    Serial.print("Alert");
  }
}

Let me explain my whole situation. My project is to make a gps tracking system plus using dht11 to give an alert through GSM if the temperature grows above 30 C. But the problem is after 1st or 2nd output, the dht11 is not giving any reading it shows "Nan" in serial monitor. It taking 28 to 30 seconds to give another reading. So I thought may be using Interrupt will work. Any suggestions for this??

try using other library for DHT11 then.


text:
Arduino serial read data conversion, getting garbage values
I am developing code on Arduino to read 9 bytes of data from other controller.
I am getting same arrya elements which is transmitted from controller, but when I convert the same it gives me garbage values, Please help.
Below is my code snippet:
int Test::ID_001(void) {
  int result = 1;
  int i = 0;
  char FWV_AB[84];
  digitalWrite(DIR485,HIGH);
  delay(100);
  delay(10);

  int res = proto485Write(RS485_ADDRESS, CMD_COMMAND_FW_AB, CMD_ACTION_FW_AB, 0x0000);      // Send msg to controller board

  Serial.print("msgsend: ");
  Serial.println(" ");
  Serial.println("Received message from controller is: ");

  int  bufferIn1[9] = { int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00) };
  digitalWrite(DIR485,LOW);
  delay(100);
  delay(10);

  delay(DELAY);
  if (Serial2.available()== 0) {Serial.print("Error01 "); result = 0;} // Error for response timeout
  while(Serial2.available() > 0)
   {
   bufferIn1[i] = Serial2.read();

   Serial.print(bufferIn1[i],DEC);     // PRINTS CORRECT VALUES HERE SAME AS SENT BY CONTROLLER
   Serial.print(" ");
   i++;
   if(i == 9){
   Serial.println("Controller board version is: ");
   for(int j=3;j<7;j++){
    Serial.print(int(bufferIn1[j]-48)); } // HERE I AM CONVERTING VALUES INTO READABLE FORM
   }
   }
  digitalWrite(DIR485, HIGH);
  delay(100);
 return result;
}

GETTING VALUES AS "9 49 51 48 48 48 50 48 54" while serial read takes place.
MY DATA is "48 48 48 50" i.e. START FROM 3rd POSITION TO 6th POSITION OF RECEIVED BYTE. IT SHOULD PRINT AS "0002" but it gives me "GQQQ" some times "s)))" and such garbage data instead of 0002 value. Kindly guide.
Thanks you

@Juraj thank you for reply.... by using Serial.write it gives same results as before.

my conclusion is that the output is from a different version of the sketch. sketch doesn't upload?

@Juraj I am able to upload the sketch, can be some issue related to time delay? I am not able to figure it out. As when I read the serial input using "Serial.print(bufferIn1[i],DEC);" line it gives perfect results. but I need to separate the data from that array & convert into readable form. But after first read even if I am trying to read it for second time the same values it gives garbage data. Plese guide

the snippet in Question can't print nothing else then numbers. print(int( ) ) will never print G or Q

after writing line as "Serial.print(int(bufferIn1[j]-48));" it should give number as 0002 but it gives some random number like "20187"

I suggest using a termination character (usually \n is used) and only using an input buffer after the command is complete. Otherwise the content in the input buffer might not be deterministic. E.g. if polling the input buffer (locally, at if (Serial.available()) and writing by the external device do not happen synchronously, then the bytes in the buffer will not be at the intended positions.


text:
Arduino IDE + Metro + I2C device (Grideye) + Code for Uno = weird results?
I have been working successfully with the arduino uno and a thermal camera device called grid eye. There is a board available at the popular suppliers of arduino addons.
For the uno, the code looks something like this and works.
// Load Grideye Library
#include <SparkFun_GridEYE_Arduino_Library.h>
uint8_t pixelTable[64];
void setup() {
    grideye.setI2CAddress(104); //This means, that one pin of the device is pulled up
    grideye.begin();
    Serial.begin(115200);
}
void loop() {
// loop through all 64 pixels on the device and map each float value to a number
// between 0 and 15 using the HOT and COLD values we set at the top of the sketch
  for (unsigned char i = 0; i < 64; i++) {
    if (i % 8 == 0) {
      Serial.print("\n");
    }
    pixelTable[i] = grideye.getPixelTemperature(i);
    Serial.print(pixelTable[i]);
    Serial.print(" ");
  }

For the Metro I use Arduino IDE with the Libraries installed and the board selected. But all I get is an Array full of '0'.
Connected, both times, to the designated SDA and SCL pins, as well as the 3.3V and GND Pin.
Any Ideas?

does I2CScaner sketch find the device?

what is the correct GridEye I2C address? ...... btw, do not use decimal numbers for the address, it can cause errors because all of the documentation is in hex or in binary

Thank you for your comments and sorry for initially posting in the wrong community.  I downloaded I2Cscanner, which does not find any devices. This, I don't understand, the UNO works fine with the same setup..   The Correct ist either 0b1101000 or 0b1101001, depending on whether one Pin is connected to GND or pulled up. MIe is connected to GND, so 0b1101000 or 104, or 0x68 it shold be  I changed to hex btw, also no effect.


text:
May mulitple sensor connect to one arduino uno board since they shared same pin?
i am a Arduino beginner here. I start knowing about Arduino since my supervisor give me this project. In my project , i need to invent a car safety system to avoid animal hurting that hide under vehicle and solve drowsy driving problem. In sensor requirement, i choose to use PIR motion sensor (HC-SR501) to sense the movement of living things under the car, for the drowsy driving i choose to use pulse sensor and eye blink sensor to detect whether the driver is sleeping or not, it the driver is sleeping then it will activate alarm and led light on. But during research, i found that these 3 sensor have sharing the same pin with is the pin 2 (picture attach). So may is ask is possible to connect these all 3 sensor in one board ?? May i ask how can i do it if i connect the pins to the breadboard ??
Last question is do i need have MEMS MPU -6050 sensor in my project since i found this is with the eye blink sensor in other person research. Thank for accepting my question.

you can use pin 3 the same way as pin 2 for interrupt.  the display can use any other pin instead of pin 2

@Juraj Ok thanks.

Your drawing seems to show plenty of pins available, with only pin 2 in common. If the pin is being used for an Interrupt, then one device can use a different pin instead and the code adapted to use PCINT for the interrupt.
I would suggest the PIR does not even need an interrupt, it is slow changing and polling it for activity would be just as effective.
Add some current limit resistors to your LEDs so you don't damage the IO pins.

@ CrossRoads Ok Thanks a lot.

You did not provide a picture, or any other information.
Given how little info you provided, the answer is "it depends".
PIR sensors tend to use digital lines that change state when they detect motion. You would not want to share an input line with such a PIR. (I couldn't find a spec-sheet on your PIR with a quick search.)
For devices that use serial communication, the I2C interface standard is designed for connecting multiple devices on the same serial bus. If you have multiple I2C devices, you should connect them all to the same pins, and it works great as long as they have different device addresses on the I2C bus.
Other types of serial interfaces are only designed for 2 devices to communicate with each other, and cannot be shared.

pin 2 is interrupt pin

@ Duncan C thanks


text:
Clock cycle count count for the same command is not equal in ESP32
I am using ESP32 Pico Kit with Arduino Ide. I want to measure operation cycle for a few commands.
The code is so simple as below:

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

void loop() {
  unsigned long count = 10000;
  unsigned long i = 0;
  unsigned long _start;
  unsigned long _end;
  _start = ESP.getCycleCount();
  while(i < count)
  {
    i++;
  }
  _end = ESP.getCycleCount();
  Serial.println(_end - _start);
}

When I run the code, the result is 13.
Then, I changed the counter variable to different values and ran it again (values: 10, 100, 1000, 10000, ...).
The result is always 13!
Why the execution cycle does not change and it seems that the code is compiled as just one loop and the loop count is not important?
Am I missing something?

I think the compiler sees what you are doing, and just replace the while loop with i=count. The compiler tries to optimize your code.

try using the volatile keyword in the i variable declaration  ....  volatile unsigned long i = 0;

Not only does the compiler remove the loop, it also removed the variables i and count altogether. Or at least any decent optimizing compiler would do so.

Thank you all. I did it an it is working perfect. How should I mark it as answered?! :)


text:
Sporadically corrupted data returned from ESP8266
I have an Arduino Uno connected to an ESp8266 via an ESP-01 adapter.  The Adapter is powered from the Arduino 5v and Gnd pins and the Tx/Rx to the Adapter use Arduino pins 2/3. I have basic code which sets the ESP8266 as an access point and I am able to connect to the AP from my phone, send a message and receive a reply from the ESP8266.  This works fine for 75% of the time.  other times, the message received by ESP8266 ( and printed on the serial monitor for debug ) is truncated, and/or corrupted.
I have tried a different ESp8266 and a different adapter; I don't get corruption errors with other programs run on the Uno; I have dropped the communications speed between the Uno and ESp8266 to 9600 baud.
What could be the cause of the corruption I am seeing in the data ? Thanks
I have updated my app an no longer get corrupted data, but there are characters data missing from the returned data stream.
Here is my sketch :
#include <SoftwareSerial.h>

//
// ESP8266 interface
////////////////////

SoftwareSerial wifiSerial(2, 3);            // RX, TX for ESP8266

#define TICK  100

bool DEBUG = true;
int responseTime = 1000;

#define ESP8266CMD_SET_UART_9600            "AT+UART_CUR=9600,8,1,0,3"
#define ESP8266CMD_SET_UART_38400           "AT+UART_CUR=38400,8,1,0,0"

#define ESP8266CMD_ECHO_OFF                 "ATE0"
#define ESP8266CMD_ECHO_ON                  "ATE1"
#define ESP8266CMD_SET_WIFI_STATION_MODE    "AT+CWMODE=1"
#define ESP8266CMD_SET_WIFI_SOFTAP_MODE     "AT+CWMODE=2"
#define ESP8266CMD_GET_IP_ADDRESS           "AT+CIFSR"
#define ESP8266CMD_CONFIG_AP_LIST_ALL       "AT+CWLAPOPT=1,2047" // Sort and display all netwroks
#define ESP8266CMD_CONFIG_AP_LIST           "AT+CWLAPOPT=1,3"    // Sort and display ECN / ESSID only
#define ESP8266CMD_LIST_AVAILABLE_APS       "AT+CWLAP"

#define ESP8266CMD_SEND_DATA                "AT+CIPSEND=0,"     // required data length to be appended
#define ESP8266CMD_CLOSE_ALL_CONNECTIONS    "AT+CIPCLOSE=5"

//
// LCD interface
////////////////

#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

#define I2C_ADDR                            0x27
#define BACKLIGHT_PIN                       3
#define En_pin  2
#define Rw_pin  1
#define Rs_pin  0
#define D4_pin  4
#define D5_pin  5
#define D6_pin  6
#define D7_pin  7

LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

//
// S E T U P
////////////

void setup()
{
  Serial.begin(115200);
  Serial.println("Initialising...");

  lcd.begin( 16, 2 );                                 //  LCD is 16x2

  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);        // Switch on the backlight
  lcd.setBacklight(HIGH);

  lcd.home();
  lcd.print("Initialising...");

  wifiSerial.begin(9600);

  sendToWifi( ESP8266CMD_ECHO_OFF, responseTime, DEBUG );
  sendToWifi( ESP8266CMD_SET_WIFI_STATION_MODE, responseTime, DEBUG );

  sendToWifi( ESP8266CMD_CONFIG_AP_LIST, responseTime, DEBUG );

  Serial.println("Wifi connection is running!");

  lcd.clear();
  lcd.print("Ready");

  pinMode(13,OUTPUT);  //set build in led as output
}

//
// L O O P
//////////

void loop()
{
String APList = sendToWifi(ESP8266CMD_LIST_AVAILABLE_APS, responseTime, DEBUG);

  Serial.println(APList);

  delay(100 * TICK);
}

/*
* Name:         sendToWifi
* Description:  Send data to ESP8266.
* Params:       command - the data/command to send
*               timeout - the time to wait for a response
*               debug - print to Serial window?(true = yes, false = no)
* Returns:      Response from the esp8266 (if there is a reponse)
*/
String sendToWifi(String command, const int timeout, boolean debug){
 String response = "";

 if(debug)
    Serial.println( "Command[" + command + "]" );

 wifiSerial.println(command);       // send string esp8266

 long int time = millis();
 while( (time+timeout) > millis())
 {
   while(wifiSerial.available())
   {
   char c = wifiSerial.read();      // read resonse

    response += c;
    time = millis();                // data received - reset timeout
   }
 }
 if(debug)
    Serial.println( "Response[" + response + "]" );

 return response;
}

..and here is output debug data from a sample run.
Initialising...
Command[ATE0]
Response[
OK
]
Command[AT+CWMODE=1]
Response[
OK
]
Command[AT+CWLAPOPT=1,3]
Response[
OK
]
Wifi connection is running!
Command[AT+CWLAP]
Response[]

Command[AT+CWLAP]
Response[+CWLAP:(4,"VM2293456_EXT")
+CWLAP:(3,"NVR9ca3a92708f2")
+CWLA]
+CWLAP:(4,"VM2293456_EXT")
+CWLAP:(3,"NVR9ca3a92708f2")
+CWLA
Command[AT+CWLAP]
Response[+CWLAP:(4,"VM2293456_EXT")
+CWLAP:(4,"VM2293456")
+CWLAP:(5,"]
+CWLAP:(4,"VM2293456_EXT")
+CWLAP:(4,"VM2293456")
+CWLAP:(5,"

As well as the two networks VM2293456 and VM2993456_EXT there are a number of other netwroks available, and on some runs I see those networks shown. In any case, there are missing characters from the response text.

you have AT firmware in esp-01? how long is the message and how do you read it? show your sketch.

Thanks for coming back to me.  I do have firmware in the esp and I'm happy to share my sketch, but as a newbie here I can't see how to share the code.

I have added the sketch and sample output data to my question. Thanks

ESP-01 is a 3.3v device.

Thanks Robert. I beleive that the adapter I'm using steps 5v down to 3.3v

AT firmware writes the data to Serial without any control. If the data are not read fast the Serial buffer overflows. If you count the bytes read by your sketch (including 2 not visible line ending characters per line) you count 64 bytes. That is the size of the RX buffer of SoftwareSerial. SoftwareSerial can tell you if the buffer overflowed. Call wifiSerial.overflow().
The CWLAP takes time to execute on esp8266 side and then the AT firmware puts out the complete listing to Serial. Reading it byte by byte and storing millis() in-between is then too slow. You need to read it faster with a buffer.
I use readBytesUntil to read a line into buffer. This function waits for the next byte if there is a gap between bytes and stops reading if terminator is received or it times out. Default timeout is 1000 millis. It can by set with setTimeout(t).
In your sketch you use String. I do not recommend it for a project, but in a test you could use:
result += wifiSerial.readStringUntil('\n');

to read and append a whole line.

Thanks, that makes a lot of sense - I'll modify my code and try again. Cheers

So I have now modified my receive fundtion to this :
{
int l, j = 0;

    do {
      l = wifiSerial.readBytesUntil( '\0', &Buffer[j], BUFFER_LEN );
      j += l;
      Buffer[j] = '\0';
    } while( l > 0 );
}

.. but I am still getting 64 characters of data only.  Note I am using 'SoftwareSerial', and in that case I can't see why the readBytesUntil() function is available to me.  Where am I going wrong ?

AT firmware never sends \0. line ends with \r\n. and to read into buffer readBytesUntil('\n', &Buffer, BUFFER_LEN) https://arduino.stackexchange.com/questions/63106/how-to-compare-a-string/63116#63116

@Juraj: you'll need to append the '\n' manually - result += wifiSerial.readStringUntil('\n') + "\n";

@SBF, we want the data only

Taking the information that people have kindly offered to me, I have re-written my code to use the AltSoftSerial library and I now have my small app working fine.  Thanks.  AltSoftSerial uses pins 8/9 in an interrupt driven manner, leaving the 'standard' pin 1/2 serial comms for a debug channel.  I have it running at 19200 baud.
I have remove String variable from the code and my final improvement will be to use malloc() to allocation data buffer in place of the current statically declared buffer.
The purpose of my test app is to connect to my home wifi network a to print out the IP address allocated.  All output goes to an LCD display, but the serial monitor could be used instead.
Here's my code :
#include <AltSoftSerial.h>
#include "ESP8266_cmd.h"

//
// Connect to home WiFi network using AltSoftSerial via pins 8/9 to ESP8266
///////////////////////////////////////////////////////////////////////////

//
// ESP8266 interface
////////////////////

AltSoftSerial wifiSerial;                   // RX, TX for ESP8266

#define TICK  100

#define DEBUG                               false
#define ResponseTime                        1000

#define NW_CREDENTIALS                      "\"VM2293456\",\"----------\""

//
// LCD defines
//////////////

#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

#define I2C_ADDR          0x27
#define BACKLIGHT_PIN     3
#define En_pin  2
#define Rw_pin  1
#define Rs_pin  0
#define D4_pin  4
#define D5_pin  5
#define D6_pin  6
#define D7_pin  7

int n = 1;

LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

//
// Buffer for ESP8266 data
//////////////////////////

#define BUFFER_LEN    512
char Buffer[BUFFER_LEN];

//
// State Machine
////////////////

enum {
 STATE_INIT_WIFI = 0,
 STATE_WIFI_CONNECT,
 STATE_WAIT_FOR_CONNECTED,
 STATE_GET_IP_ADDRESS,
 STATE_WAIT,

 STATE_ERROR,
} State;

int MachineState = STATE_ERROR;
int ErrorCode = 0;

void setup()
{
String response;

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

  lcd.begin( 16, 2 );                                 //  LCD is 16x2.  Cmd is Column, Row

  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);        // Switch on the backlight
  lcd.setBacklight(HIGH);

  lcd.clear();
  lcd.home();
  lcd.print( "Network Connect " );

  wifiSerial.begin(19200);

  MachineState = STATE_INIT_WIFI;
}

void loop()
{
String response;
char cmd[64];

  switch( MachineState )
  {
  case STATE_INIT_WIFI:
    lcd.setCursor( 0, 1);
    lcd.print("Initialising    ");

    sendToWifi( ESP8266CMD_ECHO_OFF, ResponseTime, DEBUG );
    if( strcmp( Buffer, "OK" ) != 0 )
    {
      ErrorCode = 1;
      MachineState = STATE_ERROR;
      break;
    }

    sendToWifi( ESP8266CMD_SET_WIFI_STATION_MODE, ResponseTime, DEBUG );
    if( strcmp( Buffer, "OK" ) != 0 )
    {
      ErrorCode = 2;
      MachineState = STATE_ERROR;
      break;
    }
    MachineState = STATE_WIFI_CONNECT;
    break;

  case STATE_WIFI_CONNECT:
    lcd.setCursor( 0, 1);
    lcd.print("Connecting           ");

    strcpy( cmd, ESP8266CMD_CONNECT_TO_AP );
    strcat( cmd, NW_CREDENTIALS );
    sendToWifi( cmd, ResponseTime, DEBUG );
    MachineState = STATE_WAIT_FOR_CONNECTED;
    break;

  case STATE_WAIT_FOR_CONNECTED:
    lcd.setCursor( 0, 1);
    lcd.print("Wait for connect");
    readFromWiFi( ResponseTime );
    if( strstr(Buffer, "WIFI GOT IP") != NULL )
       MachineState = STATE_GET_IP_ADDRESS;
    else
       delay( 1000 );
    break;

  case STATE_GET_IP_ADDRESS:
    lcd.setCursor( 0, 1);
    lcd.print("Getting IP Addr ");

    sendToWifi(ESP8266CMD_GET_IP_ADDRESS,ResponseTime,DEBUG);

    MachineState = STATE_ERROR;   // prime for error case
    ErrorCode = 3;

    if( strstr( Buffer, "OK" ) != NULL )
    {
      if( strncmp( Buffer, "+CIFSR:STAIP", 12 ) == 0 )
      {
        lcd.setCursor( 0, 1 );
        lcd.print( "                " );
        lcd.setCursor( 0, 1 );
        for( int i = 15; i < strlen(Buffer ); i++ )
        {
          if( Buffer[i] == '"' )
            Buffer[i] = '\0';
        }
        lcd.print( &Buffer[14] );   // Display extracted IP address
        MachineState = STATE_WAIT;
      }
    }
    break;

  case STATE_WAIT:
    delay(10000);
    MachineState = STATE_GET_IP_ADDRESS;
    break;

  case STATE_ERROR:
  default:
    lcd.setCursor( 0, 1 );
    lcd.print( "                " );
    lcd.setCursor( 0, 1 );
    strcpy( cmd, "Err " );
    itoa( ErrorCode, &cmd[strlen(cmd)], 10 );
    lcd.print( cmd );
    delay(10000);
    break;
  }
}

/*
* Name:         readFromWiFi
* Description:  Read data from ESP8266.
* Params:       timeout - the time to wait for a response
*               debug - print to Serial window?(true = yes, false = no)
* Returns:      Response from the esp8266 (if there is a reponse) in Global Buffer
*/
void readFromWiFi(int timeout)
{
int l = 0;
long int t = millis();

    while( ( t + timeout ) > millis() ){
      while( wifiSerial.available() > 0 ) {
        Buffer[l++] = wifiSerial.read();
        t = millis();
       }
    }

    Buffer[l] = '\0';

    trimRight( Buffer );
    trimLeft( Buffer );
}

/*
* Name: sendToWifi
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
void sendToWifi( const char *command, const int timeout, boolean debug){

 if(debug)
 {
    Serial.print( "Command[" );
    Serial.print( command );
    Serial.println( "]" );
 }

 wifiSerial.println( command );       // send string esp8266

 readFromWiFi( timeout);

 if(debug)
  {
    Serial.print( "Response[" );
    Serial.print( Buffer );
    Serial.println( "]" );
  }
}

void trimRight( char *src )
{
  int i = strlen(src)-1;

  for( ; i >= 0; i-- )
  {
    if( (src[i] != ' ' ) && ( src[i] != '\t' ) && ( src[i] != '\n' ) )
      break;
  }
  src[i] = '\0';
}

void trimLeft( char *src )
{
  int i, l = strlen(src);

  for( i = 0; i < l; i++ )
  {
    if( (src[i] != ' ' ) && ( src[i] != '\t' ) && ( src[i] != '\n' ) && ( src[i] != '\r' ) )
      break;
  }
  memmove( src, &src[i], l);
}

and here is the ESP822_cmd.h header file that I created :
// ESP82266_cmd.h
//
// #defines for ESP8266 interface
//

#define ESP8266CMD_SET_UART_9600            "AT+UART_DEF=9600,8,1,0,0"
#define ESP8266CMD_SET_UART_19200           "AT+UART_DEF=19200,8,1,0,0"
#define ESP8266CMD_SET_UART_38400           "AT+UART_CUR=38400,8,1,0,0"

#define ESP8266CMD_ECHO_OFF                 "ATE0"
#define ESP8266CMD_ECHO_ON                  "ATE1"
#define ESP8266CMD_SET_WIFI_STATION_MODE    "AT+CWMODE=1"
#define ESP8266CMD_SET_WIFI_SOFTAP_MODE     "AT+CWMODE=2"
#define ESP8266CMD_GET_IP_ADDRESS           "AT+CIFSR"
#define ESP8266CMD_CONFIG_AP_LIST_ALL       "AT+CWLAPOPT=1,2047" // Sort and display all netwroks
#define ESP8266CMD_CONFIG_AP_LIST           "AT+CWLAPOPT=1,3"    // Sort and display ECN / ESSID only
#define ESP8266CMD_LIST_AVAILABLE_APS       "AT+CWLAP"

#define ESP8266CMD_SEND_DATA                "AT+CIPSEND=0,"      // required data length to be appended
#define ESP8266CMD_CLOSE_ALL_CONNECTIONS    "AT+CIPCLOSE=5"

#define ESP8266CMD_CONNECT_TO_AP            "AT+CWJAP_CUR="      // required essid and password to be appended
```


text:
Using 2 serial ports on NodeMCU
I am using a NodeMCU ESP 12E board which will be programmed using the Arduino IDE. I intend to use it to send GPS data to the Blynk app server. I also want to interface a Bluetooth module HC-05 to the board along with the GPS module. I am also interfacing a L239D motor driver IC to the NodeMCU in order to control two DC motors. I am also using a metal detector module with analog output which is connected to the A0 pin of the board. Motor driver inputs are given using D0,D1,D2 and D3 pins set as digital out.
I need the NodeMCU to receive data from the GPS module and also send and receive data through the Bluetooth module. So I need 2 UART serial ports. I understand that the UART0 port can be used as the Serial port using Serial.begin(BAUD-RATE). UART1 can be used only for transmission. UART2 can be configured on GPIO13 and GPIO15 as Rx and Tx using Serial.swap(). But this cannot be used along side the UART0 port.
So is there a way I can implement Software serial in the Arduino IDE in order to set 2 ports, one for receiving only and other for both sending and receiving serial data ?

the Arduino esp8266 boards package has a SoftwareSerial library. a new one in the 2.5.0 version

Consider upgrading to the ESP32. It has bluetooth built in, and far more GPIO and analog facilities. Not to mention much much much more power in general.


text:
How can I make a data logging multimeter?(harvesting energy from human motion)
I’m an industrial design major working on a studio project that involves electronics that are kind of out of my league. I have a few low power generators like piezos, thermoelectric (peltier) tiles etc... In order to progress with my project I need a way to measure the output of each one individually when harvesting human motion. As far as I know, I need a multimeter to hook up directly to these devices, and then I think there may be a way to record the results with an arduino. My question is more about specifically how to do this, or even if this is a feasible plan. Are there any plans for this sort of thing already out there? Any feedback will be greatly appreciated!

If these electronics are out of your league, how would adding more electronics (Arduino) aid on achieving your goal?

I think using a regular multimeter (potentially with logging capacity) will be easier than making such a thing yourself...

I'd suggest starting with an oscilloscope. Use that to examine the patterns of signals you're getting from each sensor, and then you might need help from somebody with a decent understanding of analog circuit design to design circuits to measure the inputs from the various sensors.

you could use an INA219 to measure voltage with an ardunio, like a DMM but for voltage and current only.