text:
SSD1306Ascii Library
Is there any way to add Inverse Text color function into SSD1306Ascii library like which is available in ssd1306 adafruit library ?

Yes, you can edit the library yourself, or copy its functions to your sketch and modify them.
You can also use another library, like u8g2.

Adafruit library uses a buffer and it's using it as a lookup to invert the color. SSD1306Ascii has no buffer, so copying the code over won't work.

@gre_gor I'm not sure I follow your reasoning. The SSD1306Ascii library can be modified to send the right pixels to the display, or you can copy its functions into your sketch and modify them there. As some example starting places, you could add a function similar to SSD1306Ascii::write that inverts the pixel data (b) before sending it to the display; or you could modify the initializer to invert the whole display: change this from SSD1306_NORMALDISPLAY to SSD1306_INVERTDISPLAY.

@Chris Combs Since im mainly looking for low memory space i cant use u8g2. library or ssd1306 adafruit library since they occupy relatively a lot of space.

@DineshKarthie u8g2's page buffer mode only needs 128 or 256 bytes of ram... if you are referring to program size then you can keep it down by including smaller fonts, more details here: https://github.com/olikraus/u8g2/blob/master/doc/faq.txt#L124-L127


text:
Sketch Memory in Pro
    void storedata(File filename ,int type , String data)
{
    if(type == 1){
      Serial.println("Group Creation");
    }
    //Storing Data into file
    pinMode(10, OUTPUT);
    if (!SD.begin(SD_CS_PIN)) {
    Serial.println("initialization failed!");
    return;
  }
    Serial.println("initialization done.");
    filename = SD.open("filename.txt", FILE_WRITE);
    if (filename) {
    Serial.print("Writing to filename.txt...");
    SdFile file("sdfile.txt", O_WRITE | O_CREAT);
    if (!file.isOpen()) {
    Serial.println("filename.txt");
   }
    sdfile.println(data);
    //close the file:
    filename.close();
    Serial.println("done.");
    }else{
    // if the file didn't open, print an error:
    Serial.println("error opening filename.txt");
  }}

Im using this function to write on the Sd card , before calling this function the sketch memory is 28802 bytes ie ) 93% , simply just by calling this function from setup increased the sketch memory to 102% and iam unable to compile is there any unusual memory usage in this code ?

Try shortening the text inside the serial.printf statements. That should already shave off a few bytes, though that's probably not enough.

@Gerben  What i dont Understand is Just this simple Function taking 10 % of memory,Im using functions all over my program , ill still try to reduce the code and optimize it what puzzles me is how could only this function could raise the memory from 93% to 103%?

You're forgetting that you are also calling some functions from the SD library. Those functions also contain a lot of code.

The good thing is that flash memory is instantly to be checked (you get the result after a (succesfull) compilation.
Refactoring you can do to reduce space:

prevent duplicate code; try to make a function from duplicated code and call it whenever needed; this also makes the program much more easy to maintain (bugs in those part have to be solved only once, and changed only adapted once).
If the code is almost the same but not an exact duplicate, use parameters in the function for the differences.
Remove code that does not have a function but still is called. The compiler can automatically delete UNUSED code, but USED code that has no function you have to do yourself.
Normally PROGMEM and F() is used to store arrays/strings in FLASH instead of SRAM, since mostly SRAM is more scarce, in your case you should not use this.
Try to optimize code using less lines. This does not mean you have to remove spaces or make big oneliners; that will not help. But changing code structurally without changing the functionality will reduce flash memory.
Remove unused libraries (although these are probably optimized out by the compiler)
Global variables/structs/arrays and lots of const variables will cost memory to. For const values it might be useful to use #defines, however this will reduce maintainability/type checking.
Remove debugging code (printf's for debugging functionality); I never tried but I think it should be feasible to make unit tests separately from the sketch code.
A tricky way that could help is to optimize the libraries and reducing code there when needed. It is not useful to throw away functions that will not be called though. And debugging information should not be present, but maybe you can remove some conditions or code fragments that will never occur.

If you have a function that isn't called the compiler will just delete it (optimise it out). It also deletes any functions that the function calls that aren't used anywhere else.
By then calling that function the compiler keeps it, along with any other functions it relies on.
That includes the SDFat library code, much of which will have been removed before.
To make it now fit you will have to optimise your program. Look for blocks of code that do the same thing and replace them with calls to a function. Look for parts that could be replaced by a loop and an array instead of discrete calls to the same function(s) over and over again. Things like that.
Either that or use a board that has enough flash for your project.

Im not using SD library , im using Sdfat library since it uses less memory.

It still needs that 512 byte buffer though - there's no getting away from that.

The problem is too little flash memory, not RAM.

Ah. Well, optimise your program then. Get rid of repeated blocks of code by using functions. Either that or use a board with more flash.

I have changed my answer in the light of this new infor,ation.

Actually There is a way to Reduce the Memory Occupancy to a Considerable level ie) upto 10 % . Replace all the if and if else Loops with Switch case , By this we can reduce the memory usage .Or atleast it did in my case in which i have used lots of if and if else Loops @Majenko

source: Stack Exchange

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

sort: votes


text:
Arduino Mega external interrupts fire randomly
I'm trying to solve a nagging issue with external interrupts - this is for a slot car track lap count controller. It uses the Mega's 6 external interrupt lines connected to photo diodes. The HW itself works fine - yes, trust me, it's fantastic.
I have observed the following. The code in the loop() is surrounded with:
detachAllInterrupts();
delay(10);
...
... process any interrupts and/or button presses
...
delay(10);
attachAllInterrupts();

If I omit or reduce the delay amount the random firing gets worse.
The ISR is lean and mean:
void lapDetected1() {
  lane1.lapDetected();
}

calling the method of class Lane:
    void lapDetected() { // called by ISR, short and sweet
      now = millis();
      if ((now - finish) < laneProtectionTime) {
        return;
      }
      start = finish;
      finish = now;
      count++;
      reported = false;
    }

all the variables used are declared volatile.
I don't like to use delay and I'm seeking advice on how to correctly implement ISRs and their handling.
here's the link to the entire code on GitHub: https://github.com/gabe2001/PCLapCounterWithArduino/
Thanks for any advice I can get here!
-gabe

Not related with your problem - but it'd be way shorter with arrays and for each loops. Like for (auto & lane : lanes) lane.reset(); and so on...

Wow. You will need to provide something more. When I opened the github space, I only found some hardware diagram of the wiring. Therefore. Please provide the full code here in Stacktrace, or, in a form where I would not have to sit and guess where you have stuffed the code :-)... I am very experienced in interrupt softwares and such stuff, so I guess that I can help you if you provide me with the complete code you have and explain why it is like it is. FIRST of all, I would guess that you have hardware noise. You could decouple that one nicely, however, you would then first have to provide a d

Continuing David's comment: `iagram for me, not a hardwire-picture like the one on GITHUB. We electronic engineers use diagrams and then I can tell you what you may have to do, to avoid hardware noise.
Untied inputs can produce noise in certain environments. If that is not the case, we will look into other possibilities - but then you will have to provide the entire code block.`

If you are IN DOUBT of if the input produces noise, then again - give me the diagram, then I will go through your wiring to reveal if there are places which are actually prone to making noise. IF we are in doubt then we can actually probe into it, but that would require that we build some more electronics on to the construction.

first - many many thanks for your reactions!
second - apologies for the delay (and counting...) - I will provide more details the coming months.
What I can say now is this: it's most likely an environmental issue. After the guys grounded most of the track the stray interrupts have become less. The more people are in the room, the more likely we see stray interrupts. The track is surrounded by a synthetic curtain to hide the posts and other stuff under the track. The floor is covered with carpet tiles. The combination is a perfect source for static charges all around.
more to come...

Now, you write the following:
detachAllInterrupts();
delay(10);
...
... process any interrupts and/or button presses
...
delay(10);
attachAllInterrupts();

I understand that you put this stuff into the loop, such that the loop in effect looks like this:
void loop() {
    detachAllInterrupts();
    delay(10);
    ...
    ... process any interrupts and/or button presses
    ...
    delay(10);
    attachAllInterrupts();
}

Assuming that the above is correct, then you will be enabling and disabling your interrupts in one long stream. You would often NOT disable your interrupts, because you don't know when the are available or not, then.
You should typically ENABLE the interrupts in the startup code, and then in the loop() you can have any Other processing you want, but not any processing referring to the interrupt processing.
The interrupt processing would take care of the button pressed etc. So - in the lane.lapdetected1() algorithm, you would take care of reading buttons pressed etc., and, you would have to attach the interrupt itself directly to your algorithm. I cannot see that you have told that when an interrupt has been happening, then the code execution goes to the ISR lane.lapdetected1() algorithm?
What you would want to do, is to setup an interrupt in the setup(), which is run once upon start of the program in the arduino, and then, providing that you want the interrupt on pin 2 (external pin), and the algorithm to run while you receive falling signals on the pin 2 is lapdetected1, then you could use the following:
void setup() {
  attachInterrupt(digitalPinToInterrupt(2), lapdetected1, FALLING);
}

Thereby you would remove the detachAllInterrupts(), and all the way down to attachAllInterrupts() from the loop construction and thereby you would be able now to process interrupts within the lapdetected1-algorithm and run what ever you would want to run, normally, from within the loop-construction.

The code in the loop() is surrounded with:

it doesn't make much sense for you to "process the interrupts" in the loop(). Use ISR instead.

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


text:
How to implement elapsed millis as the timer for my motor spinning time?
I have been using delay() as the function for my motor spinning time. However, at the same time, I need to calculate the rpm of my motor. Delay() function have to make it impossible for me to get the rpm whilst the motor spin. I have learned that I needed to use Elapsed millis as a replacement for delay() for my timing.
I have tried it and to no avail, I did not get the result in wanted. Yes, the motor spin according to the speed that I desired, however, it does not spin according to the time I wanted. It kept on spinning non-stop till I have to disconnect the power supply.
So, my question is, how do I implement the elapsed millis as my timer for my spinning motor?
please, guys, help me with this... Just guide me through and give me guidance.
This is my code that I have tried using elapsed millis. Any suggestion is welcome.
#include <elapsedMillis.h>
#include <Keypad.h>
#include <Wire.h>  // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
Servo myservo;
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address
elapsedMillis timeElapsed;

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] =
{
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {9,8,7,6}; //row pinouts of the keypad (L1, L2, L3, L4)
byte colPins[COLS] = {5,4,3}; //column pinouts of the keypad (R1, R2, R3)
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{

  Serial.begin(9600);
  lcd.begin(20,4);
  myservo.attach(11);

   lcd.setCursor(0,0);
  lcd.print("S=");
  lcd.setCursor(0,1);
  lcd.print("T=");
  lcd.setCursor(0,2);
  lcd.print("S=");
  lcd.setCursor(0,3);
  lcd.print("T=");
  lcd.setCursor(10,0);
  lcd.print("S=");
  lcd.setCursor(10,1);
  lcd.print("T=");
  lcd.setCursor(10,2);
  lcd.print("RPM");

}

 void loop()

{

  int stage1speed = getTheNumber();
  lcd.setCursor(2,0);
  lcd.print(stage1speed);
  lcd.print("sv");
  int stage1time = getTheNumber();
  lcd.setCursor(2,1);
  lcd.print(stage1time);
  lcd.print("sec");

  int stage2speed = getTheNumber();
  lcd.setCursor(2,2);
  lcd.print(stage2speed);
  lcd.print("sv");
  int stage2time = getTheNumber();
  lcd.setCursor(2,3);
  lcd.print(stage2time);
   lcd.print("sec");

  int stage3speed = getTheNumber();
  lcd.setCursor(12,0);
  lcd.print(stage3speed);
  lcd.print("sv");
  int stage3time = getTheNumber();
  lcd.setCursor(12,1);
  lcd.print(stage3time);
  lcd.print("sec");

   if ( stage1speed > 0 && stage1time > 0 && stage2speed > 0 && stage2time > 0 && stage3speed > 0
        && stage3time > 0 )

   {

    if(timeElapsed <= 1000*stage1time)

    {

     myservo.write(stage1speed);

     }

    if(timeElapsed <= 1000*stage2time)

    {

     myservo.write(stage2speed);

     }

    if(timeElapsed <= 1000*stage3time)

    {

     myservo.write(stage3speed);

     }
  }

}

int getTheNumber()
{
    char buffer[4];
    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
           int value = atoi(buffer);  // Convert to an integer
            break;
        }

    }
    return atoi(buffer);
    }

delay() is only the tip of the iceberg. The problem with delay() is
that it is a blocking function: nothing else can be done during the
delay. If you want to control your motor and at the same time be
responsive to the user, you must avoid blocking your program. This means
not only getting rid of delay(), but also getting rid of any blocking
function.
Here your problem is on getTheNumber(). This function blocks until the
user is done typing the number. Try to rewrite it in a non-blocking
fashion. For example, it could return -1 on every call as long as the
user is not done typing the number. On the first call after the user is
done it would return the valid value. If you manage to write everything
non-blocking, then you loop() will restart very often, and the program
will work with no significant latency.
As for managing the servo stages, simplest thing  would be to write a
finite state machine. I would write it with four states: IDLE,
STAGE1, STAGE2 and STAGE3. The transitions STAGE1 → STAGE2 → STAGE3 →
IDLE would be time-based, using the elapsedMillis object to track the
time spent in each state. The transition IDLE → STAGE1 would be
triggered by the user input.
static enum { IDLE, STAGE1, STAGE2, STAGE3 } state;
switch (state) {
    case IDLE:
        if (userRequestedToStartAgain()) {
            myservo.write(stage1speed);
            state = STAGE1;
            timeElapsed = 0;
        }
        break;
    case STAGE1:
        if (timeElapsed >= stage1time) {
            myservo.write(stage2speed);
            state = STAGE2;
            timeElapsed = 0;
        }
        break;
    case STAGE2:
        if (timeElapsed >= stage2time) {
            myservo.write(stage3speed);
            state = STAGE3;
            timeElapsed = 0;
        }
        break;
    case STAGE3:
        if (timeElapsed >= stage3time) {
            myservo.write(idleValue);
            state = IDLE;
        }
        break;
}

Thank you sir for your suggestions... I really appreciate it.  I 'll give it a try based on your suggestions.thanks so much ..

Sir, I have to build userRequestedToStartAgain() function?? I don't understand that..care to elaborate it for me..

@rjadkins: You may consider that call to userRequestedToStartAgain() as pseudo-code. It means you have to decide when the cycle is supposed to start, presumably on the basis of some user input. Then you write the if (...) condition for the IDLE → STAGE1 transition.

how do I do that?? I'm very confused right now. Forgive me, sir, I'm new to Arduino programming and this finite state machine is new to me. I am trying to understand the state machine. The transition from state to state really confuses me. In a typical switch statement, I understand that we can choose the cases in the switch statement, however, trying to move case to case or state to state in the switch statement is really new to me. So the transition part is a bit hard for me. Please help me, sir, trying to understand this transition.

@rjadkins: Then you should probably take some time to study the subject. See this Wikipedia article for a general background on the concept of FSM, and Majenko's tutorial for an introduction of the FSM as an Arduino programming technique.

I don't know if I even have time Sir, this project is due soon.  I have been using delay() for this project without out realising  that delay() pause the whole programming, thus unable for other function to work. The delay() have made my program unable to read the rpm function whilst the motor spin when I use delay() as the timer.

Mr. Edgar Bonet, can you give a suggestion regarding the userRequestedToStartAgain() ?? I find it hard trying to understand the state machine.

@rjadkins: It could be something like userJustTyped('*') or similar.

I'm using a 4x3 keypad. How do I put it in the code??  is it just like this:  if (userJustTyped('') ? or   if (key== '')? so far i have tried the key=='*' , nothing happen. Forgive me, sir, I am totally having trouble understanding this.


text:
How to change this function in to a non-blocking function?
How do I modify the getTheNumber() function to satisfy the statement below??
"
This function blocks until the user is done typing the number. Try to rewrite it in a non-blocking fashion. For example, it could return -1 on every call as long as the user is not done typing the number. On the first call after the user is done it would return the valid value. If you manage to write everything non-blocking, then you loop() will restart very often, and the program will work with no significant latency."
Here is the code:
int getTheNumber()
{
    char buffer[4];
    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
            int value = atoi(buffer);
            break;
        }
    }
    return atoi(buffer);
    }

I have a post about doing serial input without blocking.
Example code:
/*
Example of processing incoming serial data without blocking.

Author:   Nick Gammon
Date:     13 November 2011.
Modified: 31 August 2013.

Released for public use.
*/

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

make buffer[] and i static.
get rid of the while() loop.

Like this:
int getTheNumber()
{
    static char buffer[4];
    static int i=0;
    // Input up to 3 numbers until we find a * or #
    char key = keypad.getKey();

    // If it's a number AND we have space left, add to our string
    if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
            return(-1)
        }
        // If it's a * or #, end
    else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
            int value = atoi(buffer);
            i=0;
            return atoi(buffer);
        }
}

make buffer() and i static ? I don't understand that Sir. How do i do that?

please show me sir..

He typed the word static as you can see in the posted code. Did you not see that?

@rjadkins static variables keep their values from one function call to another. They're basically like global variables, but they can't be accessed outside the function they're declared in (if that makes any sense).

Thanks for the reply, really appreciate it. Now, why is the value I enter does does not follow this sequence when the function ic being called:
        int v = getTheNumber();
        lcd.setCursor(2,0);
        int y = getTheNumber();
        lcd.setCursor(2,1);
        int x = getTheNumber();
        lcd.setCursor(2,2);                                                                                Why does the output in the lcd screen does not follow the setCursor stated in the code?


text:
How to make HC05 bluetooth module undiscoverable or limited discoverable
I want my HC05 module to be pairable only within a time window of pressing a button (connected to an Atmega328 which talks to the HC-05). This is a pretty normal way for most bluetooth devices i've used like headsets etc. Is there a way to make this happen with HC05?
Scrounging the net, I found that it is called LDM (Limited Discoverability Mode). But i couldn't find anything that told me how to get it done on HC05. I scanned through the AT commands set too, with no luck.

You could power-off the module, until the button is pressed? Then check if a connection is made within the timeframe, and otherwise power off again

That should work i guess. Will implement it and see.


text:
Reading Json object name in arduino
How do I read the Json object name in arduino? For { "pi" : "3.14" }, I want the arduino to automatically read the object name "pi" and then th value "3.14"
I'm using arduino Uno.

There is a brilliant JSON library called ArduinoJSON. It can be installed using the arduino library manager.
See https://bblanchon.github.io/ArduinoJson/doc/decoding/ for further details.
To loop through the keys, you can use:
https://bblanchon.github.io/ArduinoJson/api/jsonobject/begin_end/
or if you know the key, you can do jsonObject["pi"] to get the value


text:
Writing a custom character on an lcd
I am using a 16*2 lcd display as a dashboard computer.
I want it to display a logo at the very beginning of the code, but some letters occupy the space of 4 characters, and are using both lines of the display, and creating those letters character by character (some actually require 6 characters) is very difficult.
Is there anyway i can address the lcd as a big matrix ?
there would be 16 lines ( the oringinal 2 lines * 8 lines of each character) and 80 columns (the original 16 columns * 5 columns each character has).
This would make it A LOT easier.

Model of the display and links to technical documentation?

The display:http://www.ebay.com/itm/1602-16x2-Character-LCD-Display-Module-HD44780-Controller-Blue-Arduino-/171983948287?hash=item280b0ac9ff:g:RsQAAOSwtnpXmusW
Data:
https://www.sparkfun.com/datasheets/LCD/HD44780.pdf

In the character generator RAM, the user can rewrite character patterns by a program.  Page 13 of the datasheet.

If I remember correctly, you can create up to 8 custom characters (custom bitmap). You can then use those characters anywhere on the display. There is no way to directly set pixels.

some letters occupy the space of 4 character

use CGRAM to define 4 characters and display them over two lines.


text:
ESP8266 sometimes stuck on AT+CIPSEND with "busy s..."
I'm using an ESP8266-01S Wi-Fi module on an Arduino UNO.
When I use AT+CIPSEND=4 and then type test it successfully sends that message to my laptop. However, sometimes the module returns a busy s... after typing the message... Then the module board is "frozen" for a couple of seconds to a full minute before accepting other commands.
What's a way to make sure the message gets send without getting that busy s... response. Or how do I catch it and reset the board or something like that?


text:
Connect two or more modules sharing the same pins?
I've found some separate instructions for connecting an SD reader/writer and also instructions for connecting a RFID reader and Piezo Buzzer.  I would like to use both modules and the piezo buzzer together on the same Arduino. See below for the pin wiring details from each instruction I found:
SD Reader/Writer

3.3v goes to 3.3v on the Arduino UNO (for power)
GND goes to Ground on Arduino UNO
D0 goes to pin 12 on Arduino UNO
D1 goes to pin 11 on Arduino UNO
CLK goes to pin 13 on Arduino UNO
D3 goes to pin 10 on Arduino UNO

RFID Reader

SDA - Digital 10
SCK - Digital 13
MOSI - Digital 11
MISO - Digital 12
IRQ - unconnected
GND - GND
RST - Digital 9
3.3V - 3.3V

Piezo Buzzer

Red - Pin 8
Black - GND

Is using the same pin for more that one module ok?

What RFID reader do you have / what interface does it use? SPI?

(1) I'm currently using this RFID reader, but I'm going to change to ID-20LA which has a better range
(2) I'm thinking of buying this SD module

pins 11 MOSI, 12 MISO and 13 SCK are SPI bus. You can connect more devices to the bus. A 'slave select' ('cable select') pin determines which device will communicate. In your table both devices use pin 10 for this. You must change one.
I recommend to wire SD reader D3 to pin 4 and in sketch use SD.begin(4).
Note: some cheap SD card adapters block other devices on the bus and can be used only as single device on the bus

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


text:
How do I connect Arduino to RS232 via USB?
I have a device that takes commands in the form of RS232 communication. I've connected the Arduino's USB port, through an adapter, to the device's 9-pin serial port, but no communication has happened.
The full chain of adapters is a printer cable (which would connect the Arduino to a computer), a female-to-female usb adapter, and a Sabrent USB to serial adapter.
I made sure the communication wasn't happening using the code while (!Serial) and blinked an LED in a certain pattern.
Is there something I'm missing? How do you get the devices to communicate?

This sounds a lot like an April fools joke.

That is rather inconvenient. In this case, though, Arduino is just not my strong suit.

This is effectively not workable.  USB is not a peer-to-peer standard, but a host/device one.  Both your Arduino and the USB-serial converter are intended to be devices, so they cannot communicate.  While it would be possible to use another microcontroller acting as a host to bridge to serial that would be pointless, as the actually central problem of RS232 vs. logic level serial would still need to be solved.
Instead, what you want is an inverting serial level shifter - essentially a board with an IC like a MAX232 or one its many successors.  You would either connect this to arbitrary digital pins of the Arduino and use a Software Serial instance, or decide that it is okay to block usage of the USB port by a computer while this is being operated, in which case you could connect it to the D0 & D1 pins used by the on-board USB interface (there are typically resistors in between the chips on the board to support this overriding).
Ironically, in a way what you want is one of the original Arduino boards that had a serial level shifter and 9-pin connector in place of the USB chip and USB connector of modern boards.  But then, you probably want something with an ATMega328p rather than the earlier, more primitive ATmega chips used on the original boards.  If you can still find a board of the original design, upgrading the chip may be an option, or it may be that your task is simple enough not to require it.
There have been many other non-Arduino embedded controller boards released with native RS232 ports as well, especially those dating from around a decade ago might give a good combination of fairly modern capability with not yet having abandoned RS232 in favor of USB.

Any network of USB devices involves a single host talking to many slave devices. The typical connection to program an Arduino board is, on the USB side:
PC (USB Host) <-> USB Cable <-> Arduino (USB Device)

On the Arduino board you have the serial side of this communication:
USB Serial Adapter <-> TTL serial lines <-> Microcontroller (RX/TX on D0/D1 pins)

The microcontroller itself has no idea that any USB communication is involved. The USB serial adapter functions as a device only, not a host, so plugging it into another USB device (though a cable with device connectors on both ends, rather than the usual host connector on one end) will not do anything.
(There are some Arduino boards, such as the Leonardo and the Micro, that use an ATmega32U4 microcontroller with a USB device interface built in. These work in substantially the same way as above except with the without the serial adapter and TTL serial link. The built-in USB interface also cannot be used as a USB host.)
Arduino USB Host Shield
If you really want to use USB communication, SparkFun sells as USB Host Shield that you can add to a standard Arduino Uno or similar device. The library for it apparently supports USB serial, though you'd want to confirm that before buying the shield. This would leave the Arduino's USB/Serial interface used for programming free to remain hooked up when using the USB host shield, making development easier.
Direct Serial Connection
A better method (IMHO) is to drop the USB stuff altogether and, as Chris Stratton describes in his answer, have the Arduino talk TTL serial directly to a level shifter (e.g., this breakout board or this shield) that is connected to your RS-232 device. I would go with communications on non-programming pins (i.e., not digital pins 0 or 1) using the SoftwareSerial library or the AltSoftSerial library. (You don't mention the speed of the link, but software serial is generally ok up to 57,600 bps and, depending on the device and what else you're doing, even 115,2000 bps.) This will let you use the serial link to the computer for debugging while running your application.
If you need to work at higher speeds or you just prefer to use a UART (hardware serial), you have two options:

Use the USART on digital pins 0 and 1, and be unable to talk to the computer while you're using it to communicate with your RS-232 device.
Use an Arduino board with more UARTs or USARTs on it, such as the Mega.


text:
Open source PLC Wifi
I'm working on a project that involves a device called the plduino (aka Open Source PLC). This is the website for the device:
https://www.digital-loggers.com/plc.html
and the GitHub:
https://github.com/digitalloggers/PLDuino
Using the examples on the GitHub, I've been able to figure out other parts- storing on the SD card, the GUI, digital IO, etc. But I haven't been able to figure out the WiFi module (which seems to be through a ESP8266 device). I looked through the libraries directory on the GitHub link, but didn't find anything that looked like it connected to the internet or could send or receive data. The documentation says the device can connect to wifi, but is otherwise very little help.
Has anyone used this before? How do I make this device connect to wifi?

Fuses on the relays... cowardice.

This is not particularly easy to figure out. The ESP8266 is addressable via a serial port. The ESP8266 firmware is called NodeMCU, which sits on top of the ESP8266 firmware and allows you write Lua code to implement custom Wifi functions. The PLC comes with example Lua that starts a webserver and publishes a webpage that allows you to check and set the status of the PLC (but only if you connect to the PLC, which is in access point mode.)
If you want it to behave like wifi on a normal desktop computer, you have to do some Lua programming (I could not find any Lua code online that did basic things out of the box, but there are a fair number of examples and snippets on the NodeMCU sites.)
In spite of how cool this device is, I ultimately decided it was just too much work to get the Wifi integration working (the Arduino stuff is of course pretty easy). You also have the problem of how to get your data logs somewhere. Since the data is on the Duino and the ESP8266 is the web interface, you either have to poll the Duino (which the example code does) and upload to a site (e.g. AWS), or log the data on the Duino, then send it over the serial port for upload -- MORE Lua and Duino coding. Plus if you want to put your data on AWS IoT (for example) the Duino/NodeMCU technically does not support the TLS 1.2 and X.509 cert handling you need to register (although they are apparently some workarounds now.) Life. Is. Too. Short. For. That.
I switched to Raspberry Pi, which is about 1000 times simpler, even though it does not have the cool features like open collectors and optical isolators. I'm now looking at Pi enclosures, such as the nice BC packaging from Phoenix Contacts. I decided it was simpler to make my own custom PLC for my home HVAC automation project than it was to code the DL-PLC. Bummer. Maybe they'll do a Pi version of this someday.
The repositories for my DL-PLC and RPi projects are on GitHub (https://github.com/dglcinc/HVAC-plc and https://github.com/dglcinc/HVAC-pi), you may find my Lua code and implementation notes useful if you want to get the wifi working on the DL-PLC. I did get it working in station mode (so you can join it to your home access point, address it with a DHCP IP, etc.) but that's about as far as I got.

What does your controller drive? What sensors do you use, and how do they report to the controller?


text:
How do I power an arduino without USB?
I'm working on a project where my arduino talks to another device that uses serial communication. I've connected my USB cable to a USB-to-serial adapter, so it can communicate with the device.
The problem I'm running into is powering the device: if I'm using the USB for serial, I can't use it for power. I have made sure that the device isn't turning on by putting
pinMode(13, OUTPUT);
for (int i = 0; i < 10; i ++) {
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);
}

at the start of the setup function: if it works, it should start by blinking LED 13.
I tried powering it with a 5V power supply through the power jack, next to the USB connector, but that didn't work. Is there something I'm missing? Do I need a different type of power supply?

The documentation is quite explicit about this.

In that case, can you point me to what you're referring to? I don't think I found that page.

https://www.arduino.cc/en/main/arduinoBoardUno

my arduino talks to another device that uses serial communication

What other device? You haven't said which Arduino, but Arduinos are generally "devices" which talk to a "controller" (host) which is generally a PC / Mac.
The host has the job of supplying power (via the USB cable) to the device. Thus your Arduino will be powered by the device it is plugged into.
Disregarding this issue for the moment, you can supply regulated 5V power directly to the 5V pin on the Arduino. On the Uno (and many others) this is labelled "5V".
The power jack is to supply 7V to 12V (eg. from a wall-wart) which then goes through the voltage regulator on the Arduino (depending on the model in question).
There is quite a discussion about this on https://www.arduino.cc/en/main/arduinoBoardUno. On that it mentions:

Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

This is true. Directly supplying 5V to the 5V pin bypasses the regulator and also bypasses the reverse-voltage protection diode. However it is possible to do it.

What about the Vin pin?

For a Uno you can see from the reference schematic what happens:

The power jack (on the left) goes into the reverse-voltage protection diode (D1). The other side of that becomes Vin. Then it goes into the 5V voltage regulator (U1). The other side of that becomes the 5V line.
Thus to supply 5V you can provide 5V power to the pin marked 5V. It is probably not ideal, because the voltage regulator may not be designed to have power applied on its "output" side.
There is more circuitry to decide whether to use the USB power or the Vin power (not shown above).

The Vin pin bypasses the reverse-protection diode but still goes into the voltage regulator. See my amended answer.

I suppose the Vin pin is to let you "get at" the input voltage. For example, if you supplied 9V to the power jack them 8.3V would be available at Vin, for example to power a motor. (It is less than 9V because of the diode).

I agree it can power the board, providing you supply 7V to 12V to it. The only difference between that and the power jack is that it bypasses the protection diode.

The kind of voltage regulator on the Arduino board will need about 7v to give 5v out to the board. If you trust that your 5v supply is well regulated - at least that it won't exceed 5v, no spikes, etc. - you can connect it directly to the 5v pin on the board edge. Just be aware that you'll be bypassing the protection of the voltage regulator so it will be on you to make sure you're providing the proper polarity, well regulated 5v. Exceed that value and you'll stand a good chance of damaging the board.


text:
Arduino voltmeter maximum amp input
I made a programmable Arduino that measures an input voltage. The Arduino will close or open an inverter using a relay to prevent the set of batteries from dropping below 50% to keep the batteries healthy. I currently have a set of 8 6V batteries configured to supply a total of 12V to one inverter. I used a set of 10k ohm and 100k ohm to safely measure the 12 volt input from the batteries. In the current configuration the total Amperage provided by the set of batteries is 400 amps. Is it safe to measure the voltage from a 12V/400A input or do I need some kind of protection?

measuring 12 volts is easy, measuring 400 amps is not.

It is perfectly safe.
The Arduino will see the voltage reduced by the divider you have. It will see whatever current it needs to see in order to sense the voltage - which is a tiny amount.
Remember: Current is drawn on demand by the load. It is never pushed by a supply.

Why do some DMM have a maximum input of 10A when measuring? Also, why Hall-Effect is used to measure high amp current if it's safe to directly measure it using resistance devider?

That is for the current measurement mode. Measuring current and measuring voltage are two very different things.

You measure voltage across something, but measure the current through something. When measuring current that current has to pass through the DMM. When measuring voltage the only current that flows through the DMM is that drawn by the measuring device.

Thank you, I understand now. So basically a hall-effect sensor is to measure the amperage (current) that a component is drawing.


text:
Digital Pins reads 1 when configured with internal_pullup
I work with Arduino DUE. I would like to configure few of my digital pins as INPUT pins. When the µc sets these particular 4 pins , the DUE must be activated. Something like a DATAREADY pin in the SPI,where the data will be sent to the slave only,when it sets the pin to 1.
According to the datasheet , the external µC would set the pin state from 0 to 1. I tried this program for experimenting the effect of digital pins,
int RDY = 52;
void setup() {

 Serial.begin(9600);
pinMode(RDY,INPUT_PULLUP);
pinMode(50,INPUT);
digitalWrite(RDY,HIGH);

}

void loop() {

digitalRead(RDY);
digitalRead(50);
digitalRead(11);
digitalRead(12);

Serial.println(digitalRead(RDY));
Serial.println(digitalRead(50));
Serial.println(digitalRead(11));
Serial.println(digitalRead(12));

delay(100);
}

Results obtained are; 1,1,0,0 as expected. I cannot find a proper way to detect the change of state of the pin (from 0 to 1). To make detect changes, I connected/disconnected the 5V output pin of DUE to the particular digital pins. The results never changed with connection and disconnection of the 5V wire for any pin.
Is there any possible way to detect the change of the pin state as in INPUT mode in Arduino DUE?
Most examples are dealing with switches,but in my case I need a pin as a input.
Thanks

I connected/disconnected the 5V ... your experimentation lacks some steps.

Should i add the ground?

if you are doing "experiments" by applying a logic 1 (+5V), why did you not apply a logic 0 (gnd)? ....  if you were a biologist that is studying how frogs react to coloured light, would you use blue light only?

https://www.electronics-tutorials.ws/logic/pull-up-resistor.html

pinMode(50,INPUT); digitalWrite(RDY,HIGH);  with this I tried pinMode(50,INPUT); digitalWrite(RDY,LOW); Then later I realised ,that Input will always only stay high(becoz of oull-ups) , as writing LOW on the input is not affected.  I realised I had messed it !

There is no difference between a switch and a "pin" for input. All are either HIGH or LOW. You tie it HIGH with the pullup, and then try giving it a HIGH with +5V (Caution: The Due is a 3.3V device, not 5V!).
At no point do you ever give it a LOW signal (connect the input to GND), so how can it ever read LOW?

So should I add ground to the external µc too??

You mean connect the grounds of both MCUs together...? Erm.... yes?   https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/

Oh that link was excellent,and I was silly ! So for experiment , I connected the pin 52 with GND from the DUE board. It read 0 when connected. I will connect the DUE's GND with the external µc's GND , for the actual program.


text:
Best Bluetooth module for the Lilypad?
So I'm trying to work on a project and need to include bluetooth. The latest problem I have is I'm using a Lilypad Arduino and need to keep the project in the same round area. I was looking at this: https://www.sparkfun.com/products/12580 however I'm not sure how I would make it smaller? Does it have to clip on or can I simply solder it in a way that it's resting directly above/below the Lilypad?

you need to electorally connect the pins, how that's arranged is up to you.

@dandavis Thanks so basically if I simply just solder it with wires or something and hold it in a casing it'll be fine?

yes, provided static/water/smooth protection...

@dandavis Well it's not gonna be exposed to any water or such. Just a very basic case to attach to a person. Thank you though :)


text:
How to load program into Arduino pro mini using FTDI cable?
Do we need a ftdi basic board to connect a ftdi 232R USB - TTL serial level converter cable via a 6 pin 0.1" male header into an Arduino pro mini/ nano 328 to upload the sketch?

you can use an UNO instead, most of us have a few laying around...

For the Arduino Nano:
NO, the Nano already includes the USB-to-TTL conversion circuitry. Just use the USB connector as you would with a Uno.
For the Arduino Pro Mini:
YES, you need an external breakout board to perform USB-to-TTL conversion. This board may use the FT232RL chip, but also any other equivalent one like the CH340G. You only need to have the adequate driver in your computer and you'll be set.
NOTE:
If you have "converter cable" you might not need a breakout board because this kind of cable already includes the FT232R (or equivalent). You don't need to use this cable with the Nano.

Note that you need the DTR signal available for board reset. Some boards or chips don't provide that. Some, like the MCP22xx only provide RTS and may not be usable without knowing how to get the RTS pin to toggle for you. UECIDE provides direct support for that though.

Well seen. But then it's all down to being careful enough as to select a breakout board whose chip implements all the required functionality, right? FT232RL or CH340G would be OK, whereas MCP2200 and others wouldn't (at least straight away, as you say).

Correct. It's all about attention to detail.


text:
LED does not light when inserted into round Lilypad board
Title: LED does not light when inserted into round Lilypad board.
very simple goal here: i want to plug in a blinking LED [or 10] into a round circuit board [then solder them], then power those LEDs. when i touch the - and + battery wires to the loose LED it lights. as soon as i insert the LED into the Lilypad round prototype board, those same battery wires will not light the LED. of course when i solder the LED in, then touching the battery - and + to two of the outer board contacts, nothing lights. the board is, "LilyPad Prototype Board ProtoBoard by AMX3d - Round Prototype Board for all DIY Electronics project", and the LEDs are, "100pcs 3mm Flat Top Water Clear Fast Rainbow Flash RGB flashing LED Diodes USA". it is like the board thwarts conductivity. thoughts?
board - https://www.amazon.com/gp/product/B01L9B9RSY/ref=oh_aui_detailpage_o03_s00?ie=UTF8&psc=1
LEDs - https://www.ebay.com/itm/121752435838

and the resistor? https://www.arduino.cc/en/Tutorial/Blink

How is it actually wired?

wow glad u can get ur "eyes" on this. i have no resistor, why would i need one? one per LED? i literally hold the LED, touch black and red wires to the short and long LED legs, it lights. i then insert it into the board, then w the wires still on the legs, as it is lit, when it goes into the board, it stops lighting. i had soldered a tiny dab on the same edge as where the outer pwr pads show circuit paths going towards center of board, so i think it's soldered on the right side. but then i discovered, merely inserting the LED stops the conductivity. i thought it could NOT be simpler lol.

https://arduino.stackexchange.com/questions/54771/what-happens-if-you-supply-too-much-voltage-to-an-led?answertab=oldest#tab-top

That board looks to me like every pin is connected to every other pin. You will have to isolate the pins you want to use. I have never seen a board like that before...

the question remains ....  @dcparham, why do you not see that all the pads are connected together on that board?

well, being an uber noob, i am only now tuning into the context of how the boards work. Majenko below highlighted what i had just found when going back to RTM.

Your board has every pin directly connected to every other pin.
As it states in the description:

10 mil traces connect holes, cut the ones you do not need to create a breadboard with infinite possibilities

(Highlighting by me).

hah, NOW it's making a micron of sense.... so need to use a razor or clippers to isolate away the holes i will not be using; then the board will look strange, parts of it being cut away, right? my original goal was to have a bank of LEDs in a circle, beneath a 1" circle hole in wood, to produce a sparkling effect. i had thought the board would remain circular. anyway, thx much!

You don't need to cut the board - only the thin tracks that join the holes. Just scape them with a craft knife until they break.

ah i see, isolate the row and column that lead to their respective outer pad [one -, the other +], by breaking the other connections. new to this, thx much! [but of course let me know if i misinterpreted your notes]

Sounds right, yes. If you look at the rear you can see that there are 4 traces coming from each pad, north, south, east and west. Should be easy enough to cut them.

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


text:
(Why is) getLocalTime() on ESP32 taking several seconds to complete successfully
This is a cross-post from https://github.com/espressif/arduino-esp32/discussions/8653 as it didn't yield any results there.
I noticed that getLocalTime() is consistently taking 5-10+ seconds to complete. So far I haven't been able to find the root cause.
I am testing on a ESP32-WROVER-B module. On startup the device first connects to WiFi and then tries to sync time.
boolean initTime() {
  struct tm timeinfo;

  log_i("Synchronizing time.");
  // Connect to NTP server with 0 TZ offset, call setTimezone() later
  configTime(0, 0, "pool.ntp.org");
  // getLocalTime uses a default timeout of 5s -> the loop takes at most 3*5s to complete
  for (int i = 0; i < 3; i++) {
    if (getLocalTime(&timeinfo)) {
      log_i("UTC time: %s.", getCurrentTimestamp(SYSTEM_TIMESTAMP_FORMAT).c_str());
      return true;
    }
  }

  log_e("Failed to obtain time.");
  return false;
}

  ...
  10:12:28.118 > [  3634][I][connectivity.h:17] startWiFi(): ...done. IP: 192.168.0.57, WiFi RSSI: -55.
- 10:12:28.118 > [  3700][I][util.h:25] initTime(): Synchronizing time.
|
->10:12:34.025 > [ 11572][I][util.h:37] initTime(): UTC time: 2023-09-19 08:12:34.
  10:12:34.037 > [ 11572][I][util.h:60] setTimezone(): Setting timezone to 'CET-1CEST,M3.5.0,M10.5.0/3'.
  10:12:34.042 > [ 11574][I][main.cpp:175] syncTime(): Current local time: 2023-09-19 10:12:34
  ...

In the above example it took ~6s for a "valid" timestamp to become available.

Have you tried a different NTP server? 2) Why is it important to synchronize your local clock in as few seconds as possible?

Try replacing pool.ntp.org with (one of) its IP addresses eg. 159.196.3.239

@st2000 I tried different servers but all by-name so far (i.e. implicitly using DNS). I want this to be done as quickly as possible as it's part of the setup() sequence. The sketch should only proceed with an accurately synced clock.

@NickGammon thanks, didn't try that yet.

it should connect to the server just once at boot, and then every so often, which is the 4th argument to the NTPClient constructor (the refresh time in ms). On the ESP32, every 15 mins is fine to keep well under 1s drift, which is the resolution of the interface anyway.

try sntp_set_sync_mode(SNTP_SYNC_MODE_IMMED);

Based on the wording in the question, it appears you are requesting an NTP re-synchronizing event often.  Perhaps as often as possible.  Consider that most Arduino projects request an NTP re-synchronizing event once to set the local RTC.  Then perhaps once a day to check if the RTC is accurate.
Keep in mind that many NTP servers defend them selves from attack by throttling the service from an IP address who utilize them excessively. This quote:

The NTP  server may throttle traffic, especially for clients making
frequent requests.

... is from this web site.

In case you are not aware, if time is important for your Arduino project, consider adding RTC hardware.  This can be set to the the local time just after the NTP re-synchronizing.  From that point forward, the local RTC can provide the time.  Later, it may be prudent to check the local RTC against the NTP reported time.  But this is usually not necessary for days at a time for the vast majority of Arduino projects.

That is a very plausible explanation, thanks! While working on a new sketch I go through the compile-upload-reboot loop (far to) often. Since my initTime() is triggered from setup(), requests from my IP address hit the NTP servers very frequently. I guess I should consider running my own NTP server (e.g. a cturra/ntp Docker container) and rewire my sketches to hit that one.

Thanks.  I am curious.  If you do not make an NTP request for, say 24 hours.  Do you see an improvement in NTP response time?

Appears indeed to have been the root cause. Being away from sketch development for a couple of days solved it.


text:
Serial Communication - strtok() issue
I'm working on UART communication between an ESP32 (sender) and ESP8266 NodeMCU board(receiver).
The host is sending out the following character string:
Serial.println("2753192144$1&");

The 2753192144 is the payload. The $1& is the trailer of the packet - $1 signifies a particular option for the receiver and & is the termination character to signify that the packet is complete.
On the receiver end - this is what I have:
#define MAX_REC_STR_SIZE 10
#define REC_TRAILER_SIZE 4 // $1& and string terminator
#define TRUE_TRAILER_SIZE 2 // option size really

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

void loop() {
    if(Serial.available()){
    char data [MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1];
    Serial.readBytesUntil('&', data, MAX_REC_STR_SIZE + REC_TRAILER_SIZE); // data does not contain termination &
    data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1] = 0; // adding null terminator

    // Tokenizing
    char *payload = strtok(data, "$"); // getting payload
    char opt = strtok(NULL, "$")[0]; // getting option - 1 in our sample

    // Print
    Serial.println(payload);
    Serial.println(opt);
  }
}

This code results in a stack exception error in the serial monitor. If I remove the last line which prints opt, the payload print works fine and I get 2753192144in the serial output.
I tested this exact code out in a standard C compiler, except instead of the serial read part - I defined a character array with 2753192144$1& and used printf instead of Serial.println. See the code below
#include <stdio.h>
#include <string.h>

int main()
{
    char data[] = "2753192144$1";

    char *payload = strtok(data, "$");
    char opt = strtok(NULL, "$")[0];
    printf("Payload is %s and opt is %c", payload, opt);

    return 0;
}

This code outputs
Payload is 2753192144 and opt is 1

This works fine. Any ideas why the Arduino sketch isn't working?

There are a number of "handy" functions, for example the readBytesUntil. They have a timeout. You can use those once, when you are a beginner. But after that you have to move on and place the characters in a buffer as soon as a character is available. One character at a time for every iteration of the arduino loop. Check if the buffer has enough data en then process the data in the buffer. When you expect 16 bytes, make a buffer of 40 bytes and prevent that it overflows. Your code is dangerous in a number of ways.

println sends two additional characters that will mess with your fixed message size. Also you have a buffer for 13 character, but put a limit on readBytesUntil to 14 characters.

@gre_gor Ah yes. That REC_TRAILER_SIZE in the readBytesUntil() should be TRUE_TRAILER_SIZE since the & itself isn't meant to be read.

@Jot Yeah. I noticed that a lot of people in other threads were manually reading data and was wondering why not many people were using this readBytesUntil() function.

data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1] = 0; // adding null terminator

That line places a 0 in the byte following the array.
If you define an array of size [x] you have slices [0] to [x-1] available. If you try accessing [x] you will be altering other items on the stack after the array.
That's called a buffer overrun and is one of the most common causes of programs crashing.
If you want to put a 0 at the end of the array, you should use
data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE] = 0; // adding null terminator

You should also check that the strtok() calls actually return a valid pointer. If the incoming string is not in the right format and strtok() can't split the string up, it will return NULL. If you then try and access that NULL pointer as if it were a valid array you will have a nasty crash.

Ah yes. My mistake sorry. Let me make some amendments to the code to take into account all the comments.

I made that change. Didn't change anything. I added a check to see if a NULL was being returned by either other of the two strtok() commands. Code runs fine I use the char opt = strtok() line without doing any operations with it. But even checking if it's NULL crashes the program.

I printed out the strlen() of data and it's 12 so that must mean that includes the 10 digit payload and the $1. Not sure why the second strtok() is giving me so much trouble. Technically, the second strtok() should only be returning 1 character - the '1'.

UPDATE: char opt = strtok(NULL, "$")[0]; to char *opt = strtok(NULL, "$") seems to have fixed it some how. Not entirely sure why the first didn't work. Any ideas?

Could be something strange in the c library for the ESP8266. I don't know which it uses, but it certainly won't be the same as your PC...

Very well could be. It's really weird. Printing it as opt[0] works too with my new line of code. For some reason, I just can't assign it like this - char opt = strtok(NULL, "$")[0]; Thanks for the help though. I appreciate it


text:
is it possible to write two threads in arduino & switch between data & AT command mode dynamically?
I need to recieve data from a android phone and also estimate distance of phone from the HC 05 module , So i want to write two threads or functions. In one part i want recieve data from android phone store it in a variable and in other enter AT command mode to see RSSI of the phone.

Receiving serial characters is partially done in hardware and partially in the Arduino firmware.
The only thing you need to do here is:
- check if you've received a full message.
- handle the message (if a full message has been received)
For the ultrasonic sensor, you'll have to:
- Start a measurement.
- wait for a response.
- convert the response.
You can't do these exactly at the same time. But none of these will/should take up 100% of your "processor time".
So we'll have to "share the time" of your microcontroller.
Though, timing may be critical in some of these parts. So for this, we will have to make sure that there is no delay in, for example, handling the ultrasonic sensor.
(I'm not sure, and can't check since I'm on my phone, if Arduino uses interrupts for receiving characters from serial, which may mess up my logic below if these interrupts aren't prioritized well or the time an arduino RX interrupt takes so long it will influence your ultrasonic sensor readings significantly.)
But, you'll want to handle the ultrasonic responses as fast as possible, since this timing indicates the distance between an object. And you don't want to use processor speed while waiting for the result.We will probably want to use an interrupt here (if polling doesn't give a good enough result). See the Arduino page in interrupts, or use a HC-sr04 library that is non-blocking or interrupt/event-based
Now you can, if the ultrasonic sensor doesn't require any attention. Check and handle your serial buffer. (I believe there even is an option in the Arduino library to set a callback for a line end).
By doing the above. You can be sure that your ultrasonic readings are stable. And as long as the ultrasonic routines don't consume all processing time (which they shouldn't), you'll have time to handle your serial messages.
Also have a look at state machines and non-blocking code, to avoid making your "subroutines" block eachothers execution while waiting for a result.

You can switch between command and "online" modes, but you cannot use both at once. While in command mode you can't be receiving data, and while in online mode you can't be sending commands.
You would have to periodically switch between the two in your program at a time when you know you won't be receiving data (or you don't mind losing that bit of data).
And no, the Arduino doesn't have the concept of threads. There are a number of libraries that do emulate threads to a certain extent, but they are (usually) cooperative multi-tasking (one "thread" has to manually "yield" to another) and as such are pretty pointless, since you can get the same effect with a decent finite state machine.


text:
How Arduino IDE works?
You know , a simple arduino sketch has no main function , no include preprocess cmds,so I just want to know how arduino IDE convert a sketch to normal C/C++ source code,and what is the source code looks like.
If possible,I also want to use cmd like  g++ -E   to see the .i file genetated after preprocess.How to do it?
ps: my English is poor.

https://www.youtube.com/watch?v=V-K9tzRqCqM I think this video is the best answer

You can turn on verbose compiling.
This will show all the compiler commands used by Arduino IDE.
The ino file is converted to a .cpp file (which you can see in the verbose output). Basically the conversion is as follows:

merge all .ino files into one big .ino file with the [project].ino
file first
Add arduino.h
Add all function declarations of methods defined in the .ino files
Save as .cpp file

As to the lack of main method.
The core contains a main.cpp file which defines main in avr world this looks like
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

yes,I get it!  I post a brief artical abouts this.link thx :)

I'm not entirely sure what the arduino-builder does, but it should be similar to the traditional method.
Given the "bare minimum" sketch of:
void setup() {
}

void loop() {
}

First the IDE combines all .ino and .pde files together into one large one. I believe the order of concatenation is:

Start with the "main" INO file (the one named the same as the folder it's in).
Append to that each other .ino or .pde file in alphabetical order.

Then the IDE will add the required #include <Arduino.h> and function prototypes for any functions found - so it would end up as:
#include <Arduino.h>

void setup();
void loop();

void setup() {
}

void loop() {
}

Finally it runs normal gcc and g++ commands on the generated file(s).  You can find the generated file(s) in the build folder. Where that is depends on the operating system you are using.  Turn on verbose compilation in the preferences and you can see the gcc and g++ commands that are being executed, and as well the paths for the files involved, which lets you then see where the preprocessed files are stored.
Another important step the IDE performs, which doesn't modify the files themselves, is to look for any #include entries that match libraries and add -I <path> to the compilation commands for those libraries. It also then finds any source files associated with those libraries and compiles them. It also compiles all the core source files, which is where the main() functions is (see @jantje's answer for details on how the main() function is formed).
Once the IDE has finished with its parsing and processing it's all standard gcc and g++.

you beat me ;-)

your answer is helpful! thx! :)


text:
Problem with reading series of bytes over serial port
I'm writing a program to read bytes from serial channel, copy those into an array and then do some verification on those copied numbers.
I'm able to read and copy bytes into an array of bytes.
However, I'm facing an issue with the verification of those bytes.
Here's the code I've written:
#include <SoftwareSerial.h>

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

void loop()
{
    char charRead = 0x00u;
    byte byteArray[10];
    int i=0 , j=0;

    //Clear the array contents
    for(j = 0; j < 10u; j++)
    {
       byteArray[j] = 0x00u;
    }

    //Wait for data on serial channel
    while(Serial.available() > 0)
    {
       //Copy bytes received into array
       charRead      = Serial.read();
       byteArray[i] = (byte)charRead;
       i++;
    }

    //Just for the sake, print the array contents
    for(j = 0; j < i; j++)
    {
       Serial.print(byteArray[j],HEX);
    }

    //Check for first two bytes
    if( (byteArray[0] == 0x31) && (byteArray[1] == 0x32) )
    {
        Serial.println("Verified.");
    }
}

To test this program, I entered "12345" (without quotes) on the serial monitor which gave me an output as "3132333435" since I'm printing the contents of the array in HEX format.
What I'm not being able to understand is even if this output shows that the first two bytes in the array are 0x31 & 0x32 respectively, why not the verification logic of those two bytes is getting executed? If it would, then the string 'Verified' would get printed on the output.
Am I doing something wrong here with Serial.read() or some typecasting?
I'm running this on an Arduino Uno

You are continuously resetting i to 0, thus always writing into the first cell of your array.

You are probably reading one character per loop() run and your array has never more than one characters in it, so your comparison for two elements always fails.

So, as result of Edgar Bonet's good remark, change
int i=0 , j=0;

to
int j = 0;

and define
int i = 0;

Outside the loop (as a global variable).
Also it is quite dangerous to define the length of the array as 10, while not checking for writing over the boundary of the array. What if you receive more bytes? The application might crash or give unpredictable behavior.

The problem is not the size of the array. 10 bytes may be just fine for the intended application. The problem is not checking for overflow.

@EdgarBonet That was also what I meant, so I rephrased the line. Thank you for the notification.

I made some more mistakes too - declaring the array local inside loop() and also clearing it every time the loop runs. Thanks all.


text:
Can Arduino Mega ADK charge connected smartphone?
I suppose Arduino Mega ADK acts as the USB host for the connected smartphone.
Is it capable of providing power to the smartphone?

If you read the documentation, you will see this paragraph:

NB: Because the MEGA ADK is a USB Host, the phone will attempt to draw power from it when it needs to charge. When the ADK is powered over USB, 500mA total is available for the phone and board.The external power regulator can supply up to 1500mA. 750mA is available for the phone and MEGA ADK board. An additional 750mA is allocated for any actuators and sensors attached to the board. A power supply must be capable of providing 1.5A to use this much current.

So yes (though slowly), if you connect it to a suitable power supply.


text:
ESP8266 not sending temperature data to text message
i am trying to use a ESP8266 module to send temperature data using twilio and send it to my phone via text message. However it does not send the sensor data but the text i placed. Is it possible if i can get it to send sensor data instead? If so how can i do this?
strcat(data,"From=");
    strcat(data,PHONE_FROM);
    strcat(data,"&");

    strcat(data,"To=");
    strcat(data,PHONE_TO);
    strcat(data,"&");

    strcat(data,"sid=");
    strcat(data,TWILIO_ACCOUNT_SID);
    strcat(data,"&");

    strcat(data,"token=");
    strcat(data,TWILIO_TOKEN);
    strcat(data,"&");

    strcat(data,"Body=");
    const char TEXT_MESSAGE_BODY []  = "temperature", temperature;
    strcat(data,TEXT_MESSAGE_BODY);

    wifi.httpPost("iot-https-relay.appspot.com","/twilio/Messages.json",data);

temperature should be getting sensor raw data and paste it after the "temperature" but it is not working.

Do you know that you can get values from the sensor correctly?

Not 100% sure what you are trying to do with the line:
const char TEXT_MESSAGE_BODY []  = "temperature", temperature;

This will not assign the value in temperature to TEXT_MESSAGE_BODY, it will create a variable of type char called temperature.
You will need to get your temperature value into a string (array of char) using sprintf() or similar to convert from the base type (float, double?).
Replace const TEXT_MESSAGE_BODY [] ... etc with :
strcat(data,"temperature");

char temperature_s[20];
sprintf(temperature_s, "%f", rawTemperature);
strcat(data,temperature_s);

Above assumes rawTemperature is a float holding the value read from the sensor, but the same idea applies for other data types..  There is no checking for buffer overflow etc, but you get the idea.


text:
Programming stepper motor move a fixed step till it reach the target
I have a stepper motor and try to program it like this but I kinda stuck since I'm new to Arduino.
1. The target is set to 2048, means motor have to move 2048 steps.
2. I program the motor to run 200 steps each time, every 200 steps will stop for a sec until it reach 2048.
I've been using AccelStepper library to program my motor, I found out it is very hard for me to program like this. I'm not asking to do my homework but I dunno where to start. Just wanted to ask what method can I use to program the motor to work like this. Thank you.

Have you tried modifying one of the examples provided with the library?

I would start with the Blocking example provided with the library. Add the delays you need, the steps/distance you want. The following is simple but crude. It is call blocking code. It can only do the following sequence, but sometimes that is good enough.
A bit better would be to have a conditional loop to get to the final target. The loop would move 200, then delay 1 second, subtract the amount moved. Loop until you use up all the required distance. But initially I suggest to keep it simple and just make it work with inline sequences.
#include <AccelStepper.h>
// Define a stepper and the pins it will use
AccelStepper stepper; // Defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5
void setup()
{
    stepper.setMaxSpeed(200.0);
    stepper.setAcceleration(100.0);
}
void loop()
{
    stepper.runToNewPosition(0);
    delay(1000);
    stepper.runToNewPosition(200);
    delay(1000);
    stepper.runToNewPosition(200);
    delay(1000);
    stepper.runToNewPosition(200);
}

Thanks! I will read first. Appreciate it!


text:
Arduino loop over a function is always displaying 0 as final values
I trying to loop over a function in arduino to get values for 2000 times, and then divide it by 2000 to get an average offset:
int16_t x_offset = 0;
int16_t y_offset = 0;
int16_t z_offset = 0;

And inside setup():
for(int i=0; i<2000;i++)
  {
    GetXYZ(x_offset, y_offset, z_offset);
    x_offset += x_offset;
    y_offset += y_offset;
    z_offset += z_offset;
    Serial.println(x_offset);
    delay(3);
  }
  x_offset /= 2000;
  y_offset /= 2000;
  z_offset /= 2000;
  Serial.println(x_offset);Serial.println("...");Serial.println(y_offset);Serial.println("...");
Serial.println(z_offset);Serial.println("...");

Here is the GetXYZ() function:
void GetXYZ( int16_t &x, int16_t &y, int16_t &z) {
  // Get the gyro values
  Wire.beginTransmission(MPU);
  Wire.write(0x43);     // first register of gyro values
  Wire.endTransmission(false);

  Wire.requestFrom(MPU,6);
  x = Wire.read() << 8 | Wire.read();
  y = Wire.read() << 8 | Wire.read();
  z = Wire.read() << 8 | Wire.read();
}

The values printed in the serial of x_offset, y_offset and z_offset are always 0.

There's a couple of things wrong here:

You are just getting the last read value doubled:
x_offset += x_offset;

However x_offset is always replaced with the lates reading.  You're not summing anything.

To get anything other than 0 out of dividing an integer by 2000 the value stored in the integer would have to be > 2000. But since you can only store a maximum of 32767 in your int16_t variables, even if you didn't have the problem in point 1, the variables would overflow and the results would be meaningless.

You need to:

Use a second variable per axis to store your total
Ensure that it is big enough to store the maximum reading × 2000.  I'd suggest a long or int32_t.

For instance:
int16_t x_offset = 0;
int16_t y_offset = 0;
int16_t z_offset = 0;
int32_t x_total = 0;
int32_t y_total = 0;
int32_t z_total = 0;

And inside setup():
for(int i=0; i<2000;i++)
  {
    GetXYZ(x_offset, y_offset, z_offset);
    x_total += x_offset;
    y_total += y_offset;
    z_total += z_offset;
    Serial.println(x_offset);
    delay(3);
  }
  x_total /= 2000;
  y_total /= 2000;
  z_total /= 2000;
  Serial.println(x_total);Serial.println("...");Serial.println(y_total);Serial.println("...");
Serial.println(z_total);Serial.println("...");

Oh, I didn't noticed that. Thanks it works now.


text:
Ethernet nodemcu
I have a question that might be a #noob question but I am wondering if there is a board similar to the nodemcu in size that runs arduino code but instead can use ethernet to connect to the network instead of the wifi? I have already seen the connections to use one of the pins and such to connect that way but I am looking to see if there is a board that has the rj45 connection on it already.

closest I found is MKR Zero with MKR ETH shield

while I can't categorically rule it out, I've never seen such a device after hundreds of hours shopping different sites and buying about 15 different models of ESP boards over 2 years...

I don't think you'll find a single off-the-shelf product.  The closest I have managed to come to it is a Teensy 3.2 plus a WIZ820io & Micro SD Card Adaptor and a WIZ850io module, all stacked together.  Footprint-wise it's around the same as (or smaller than) many ESP8266-based boards - however it's considerably chunkier when all combined:

Awesome. Thanks all of these are great staring places for me. Thanks so much

"it's considerably chunkier". it is only the RJ-45 connector.

Yes one does exist that I know of. It's called the EtherTen and is made by an Australian company called Freetronics.

It uses the ATMega328P microcontroller that is used on the Arduino Uno. It is 100% Arduino compatible with onboard (RJ45 wired) Ethernet.
It can be purchased from Freetronics.com.au or from Roboshop.com.
Freetronics provides a number of documents and resources on the page linked above.

this is Arduino Ethernet clone. how is this similar to NodeMCU? it is not 32bit and is large.

The requirement was that it runs Arduino code. There was no requirement that it had to be 32-bit nor be compatible with NodeMCU (except for size).


text:
Custom atmega32u4 board crystal issue
So I built an custom board based on the Atmega32u4. Schematics attached.
I managed to burn a bootloader for Pro Micro using Arduino Uno as an ISP.
The issue I have is that the board is dead when powered and to bring it to life I have to short pin1 of my crystal with VCC for a second. I discovered it by mistake..
The crystal I'm using is an Epson X1G004451000212.
Any idea why is this happening?

That's a Crystal Oscillator, not a crystal. Take the 22pF caps off to start.
Did you set the fuses to use an external clock source, vs a crystal with the internal oscillator driver (where the caps would be needed)?
Is the part oriented the correct way so it receives power and Gnd correctly?
Also, is it's performance any better than if you had just used a crytal?
https://support.epson.biz/td/api/doc_check.php?dl=brief_SG7050CAN&lang=en
vs these with +/- 10ppm stability (is that the same +/- 10 x 10 ^ -6 ?, which would b be better than 25 to 100 x 10 ^ -6)
https://www.digikey.com/products/en/crystals-oscillators-resonators/crystals/171?k=crystal&k=&pkeyword=crystal&pv1989=0&pv183=6185&pv2150=u16MHz&pv253=19&FV=ffe000ab&quantity=0&ColumnSort=0&page=1&stock=1&pageSize=25

Note also that pin 1 of the oscillator is the standby pin.  Shorting it is probably starting the signal.

Why should I remove the caps? According to a atmega32u4 documentation, those are required for a typical bus powered application.
My fuses looks like this: lfuse: 0xff, hfuse: 0xd8, efuse: 0xcb.
I didn't know that there is a difference between crystal and crystal oscillator. I'm a total electronics noob and this is my first more complex design..

ok, I educated myself and now I know the difference and I know why you suggested removing the caps..If I replace my crystal oscillator with a crystal unit (this one https://uk.rs-online.com/web/p/crystal-units/9047516/) it should work fine? Off course I will remove the C5 and connect pads 2 & 4 of the crystal unit to ground as the documentations recommends. I will also change the caps to 10pf to match the CL of this crystal. Does it make sense?

eureka! I removed the caps as suggested and it's working without the magic jump of the oscillator stby pin. I will however redesign the board as above


text:
Checking a jumper between two pins on Arduino
I'm in the process of making a tag scanner (which transfers the tag ID to the computer), and I figured I'd use an Arduino Micro for that and just use the keyboard function on it to save myself a whole lot of hassle. From what I've read, however, having the keyboard open all the time can make it tricky to program it.
I figured my solution would be to use two of the pins as a jumper check, and have some code in the setup to read the input pin; if the circuit is closed between them, the keyboard function never activates, and if it's open, the Arduino will act as a keyboard. That way I should be able to put the jumper on if I need to program it, and leave it off if I just want it to run.
Unfortunately, I've never really done anything like this before, and I don't really want to just start plugging things around and run the risk of damaging my board. I've read around a bit, but I figured I wanted to bounce my ideas off of someone before I try it.
First, would you recommend a different approach? I did see a question that used the internal pullup resistor to check if a jumper connected it to ground, but since I only want to make this check once, is that a good route to go?
Secondly, if I connect it between two pins, am I correct in thinking I'd need a resistor between them (the Arduino website suggested 470ohm to 1kohm when connecting to other devices, so I'm guessing this would be a good number)? How would I set the pins up to make this work; should I put one pin as output and the other as input, and just read the input pin (after which I'd simply turn the output pin off), or would I need to add additional connections?
Thirdly, since this will use the USB port on the Arduino that is used to program it, is there a way to wipe the code from the Arduino in case of Serious Bugs, or is it possible to "brick" the board by tying up the USB permanently? I mean, I'll definitely make use of the Serial connection to test the output (and also to test the above jumper), so I think the odds are small enough to try it anyway, but... better safe than sorry?

why on-hold as too broad? there are two perfect answers

I had voted to close because multiple questions were asked in one question. I think Juraj is right, there are two great answers so I'm voting to re-open. +1 for each of the answers.

First of all, welcome here. Usually questions should contain, well, only one question ;)
In any case the usual circuit with buttons (a jumper can be seen as a button) are these ones:

simulate this circuit – Schematic created using CircuitLab
In the left case, usually the arduino pin is "pulled down" by the resistor when the button is not pressed (or the jumper is not present), so it will read "LOW". When the button is pressed, the arduino will see a "HIGH" value, since the button is "stronger" than the resistor and is able to force its value. The resistor is called "pull-down".
In the right case, the voltages are inverted. You read a "HIGH" value when the button is not pressed, and a "LOW" value when it is. The resistor is called "pull-up" for obvious reasons.
The resistor is needed because you need to have a "weak" component that can pull the arduino pin to a voltage value; it needs to be weak, so the button can override it.
The arduino, however, as a very common feature, called "internal weak pull-up" on the digital pins. This means that internally there is already the possibility to enable a weak resistor pulling the voltage to +5V. For this reason, what you need is to just connect the jumper to ground and read it.

simulate this circuit
You will need, in your setup, to set the pin as INPUT_PULLUP, and then check the value you read:
const byte jumperPin = 2;

void setup() {
  pinMode(jumperPin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(jumperPin) == LOW)
  {
    // Jumper is inserted
  }
  else
  {
    // Jumper is not inserted
  }
}

This is what the DigitalInputPullup example is for...
Regarding your other question, there is a connector on every board named ICSP (of if there isn't, you should have access to the ICSP pins from somewhere else). This connector is used to flash the bootloader again (or to flash a program with an external programmer). You will need a atmel programmer to restore the original bootloader and "unbrick" it.
Luckily any arduino board can be used for this task; you will just need to download on another board the sketch ArduinoISP (already included in Arduino IDE) and you can use it to flash. There is plenty of tutorials online to do it. So to "unbrick" it you will just need another arduino board

First off, the premise:

having the keyboard open all the time can make it tricky to program

is completely false.
The problems that people experience with programming are when the Arduino is sending keystrokes all the time without external stimulus.  This makes it tricky to do anything - not just program. Just like it's hard to write a letter when you have a cat walking all over your keyboard.
So as long as you aren't just sending keypresses all the time, and only send them when you actually read a card, there is no problem for you to try and fix.
Secondly, the idea:

use two of the pins as a jumper check, and have some code in the setup to read the input pin; if the circuit is closed between them, the keyboard function never activates, and if it's open, the Arduino will act as a keyboard.

is overly complex and meaningless.  If all you want to do is check a state of "set" or "not set" using some external "device", what you're talking about is a button, or a switch.  You don't need two pins for that - only one. And there's a myriad of tutorials available on the internet showing you in detail how to read the state of a button (or switch). (Hint: use a pin set to INPUT_PULLUP and connect that pin to GND to "activate" it. Include a small [100Ω] resistor for safety if you like).
So in summary:

Unless you're being really daft in your program, there is no problem to solve.
You are over-thinking your solution.


text:
Are these relays connected correctly?
I currently have limited electronics experience. I am planning to use mains power through relays for climate control, so considering the risk, I would like to check to see if these relays are appropriately connected to receive mains power.
I have two relays. One relay will take 600W (a heater) while the other will have 50W/0.2A (a fan).
The relay module is: https://www.auselectronicsdirect.com.au/assets/files/(ST1080)5V%20Relay%20module.pdf
There seems to be a resistor inbuilt into the casing, and according to the packet (but not the PDF) there is inbuilt Back-EMF protection.
My concern is that it may not be protected against inrush, uses screw terminals, and may not be isolated.
Diagram is:

Any advice will be appreciated. Once again, I will not run mains power through it until I am sure of it being safe.

The pins of the module are labeled "S + -", you have connected them in the right way. They could be very cheap or counterfeit relays, and the contacts could melt. A heater can have some inductance, that could cause sparks between the contacts. The module is not according to the specifications for the mains voltage. When looking at the back side here: http://openplatform.cc/index.php/home/index/details/apiid/115 the pin of the diode (low voltage) is very close the pin of the screw terminal (mains voltage).

The relay on that board (on the photo in the datasheet), is only rated at 125V AC, while you seem to be living in a 220V country. Double check the markings on the (blue) relay on your board. Your wiring looks fine. There is indeed a flyback diode on the board, and a transistor to drive the coil in the relay.

Yes, your relays are hooked up the right way. I'm using the same modukes to drive a fan 75W and a HPS-Lamp with 400W. As long as you drive the heater with AC voltage, you're in the specs (different than stated in previous comments).
But the humidity sensor (a DHT11/22) isn't, as far as I remember its pinout...
And could you explain what the Transistor is for (if it is a transistor, I'm curious what you want to achieve with this wiring)?

The wiring was more just the best I could get with Fritzring - it didn't have the actual modules I used.
The DHT22 is this: https://www.auselectronicsdirect.com.au/temperature-and-humidity-sensor-module-for-arduino (pins are GND, VCC, DATA as shown in the image).
The transistor looking thing is actually a three-pin LDR module (could only find a 2-pin one in Friztring so used something else). Link is: https://www.auselectronicsdirect.com.au/photosensitive-ldr-sensor-module-for-arduino-proje

Okay, sorry then! I thought of the raw version of the DHT22 which has 4 pins. Didn't look to your picture well enough...


text:
Reasons Flash Page is Locked Due
Using the Arduino Due on a project, I have found that I commonly run into the issue Flash Page is Locked when attempting to upload.
I have used the library write functions of DueFlashStorage that lock and unlock addresses on each write. I believe a combination of this locking/unlocking and power loss during writes has caused my woes. This lib has added functions that avoid locking/unlocking memory on each write so this problem could be averted in that way.
My question is, are there other common actions that can cause the flash to lock? If I ran blink on a Due for a long period of time power cycling it randomly would the same error eventually occur? This seems to be a common issue with the due but beyond this library I have not found other causes.

the count of writes to flash si limited. with the flash library you can write data to flash. did you do many writes to flash?

For my current setup I do write to flash but not close to 10,000 times before the flash page locks and it becomes complicated to reprogram the due. I'm using 10,000 as a conservative maximum. If I did not write to flash in my program is there any reason why the flash would become locked?


text:
How is it possible to access the CPU registers using memory addresses?
The following is taken from ATmega328-328P Data sheet.

According to this, I can access all the 32 registers in CPU using memory addresses. For example:
 unsigned char *register = 0x0;

will access the first register. Is this true? if so, then is this also possible to do on regular CPUs (like my laptop), since I thought you can only use a pointer to access memory and not CPU registers.
Is the register mapped into the SRAM in this case?

I figured it out, they are mapped. explained here: https://stackoverflow.com/questions/3022046/is-it-possible-to-access-32-bit-registers-in-c

Microcontrollers tend to be simple compared to processors like you would find in your laptop. Most operating system make use of the higher security features that can prevent user programs from straying where they shouldn't be.
As far as registers being memory mapped, it really depends on the particular architecture, each CPU. They are not all the same.

Is the register mapped into the SRAM in this case?

The data address space maps the 32 general-purpose registers, all the I/O registers (including those also accessible through the I/O address space), and the RAM


text:
comprehensive list of common library methods that do not work in interrupt service routines
Where is a comprehensive and authoritative list of commonly used library or built-in methods (functions) that do not work properly in Arduino interrupt service routines?
I am aware of the following:

do not use delay()
do not use Serial print methods

which are part of Nick Gammon's advice linked here. His TLDR summary is:

TL;DR :
When writing an Interrupt Service Routine (ISR):
Keep it short
Don't use delay ()
Don't do serial prints
Make variables shared with the main code volatile
Variables shared with main code may need to be
            protected by "critical sections" (see below)
Don't try to turn interrupts off or on

however, I am looking for, as I said, a list that is more comprehensive and authoritative.

An authoritive list (for example by the Arduino foundation) would only be able to include libraries developed by this authority. That wouldn't include most of the available libraries. Nobody wants to garantee for a library, of which he is not an author.

... that do not work properly in Arduino interrupt service routines ...

A much safer approach would be to ask what does work properly in an ISR. Considering that my advice was to "keep it short" that would tend to exclude calling any functions except ones which are known to be OK. For example, calling millis() or micros() to find out the current timer values would be OK (bearing in mind that the figures returned by millis() will not increment).
Anything complex enough to be placed in a library would tend to be excluded simply based on that, in my opinion, unless specifically documented otherwise.
So, I wouldn't try to write files, do serial output, do I2C output, drive motors, etc.
Really, what an ISR should be doing is one or more of:

Setting a flag (eg. "key has been pressed")
Note the time (eg. "Pulse received at this moment")
Retrieve some value (eg. what number is in a timer register)

Then the main code, not in an ISR, does something lengthier with that data.
The other thing to be concerned about is: Is a function re-entrant?
Just as an example, if you are doing strcpy in an ISR, is the strcpy function coded to be re-entered? (I don't know the answer just now). If it is not re-entrant, and you happen to be doing a strcpy in the main code, and the ISR also does a strcpy then one of them will be corrupted.

In terms of getting a comprehensive list, that would be almost impossible. Some libraries are no longer maintained. Others might be maintained but change from one month to the next, and the change might affect how they work inside an ISR. This is like the question people ask about "which libraries use which timers or pins?". These questions are difficult or impossible to adequately answer.

The basic rule is quite simple, but the list is practically impossible to produce.
The rule is:

You cannot use anything that relies on an interrupt to function from within an interrupt service routine.

AVR chips only have one interrupt priority. Only one interrupt routine can function at a time. If an interrupt fires whilst an ISR is currently executing that interrupt will be delayed until the ISR finishes.  If that ISR relies on a function that itself needs an ISR to fire (such as millis(), or serial transmission), then it will never get to finish.
A partial list of things to know:

You cannot transmit serial more than there is room in the TX buffer for, or it blocks.
The time generated by millis() (which delay() relies on) never changes.
Servo motors cannot be controlled and will jitter if an interrupt routine takes too long.
tone() generated sounds will also jitter since the ISR is delayed while another ISR is executing

And basically anything else that uses interrupts.


text:
Arduino on Windows vs Ubuntu
I have some code that works fine on Windows but is giving me errors on Ubuntu. I noticed that while Windows is running the code using avr-gcc, Ubuntu is trying to make it run using avr-g++. Any functions not defined within void setup() comes up as "was not declared in this scope". Is there a way to force it to use avr-gcc ?

What version are you running on Ubuntu? Did you install it from apt, perchance?

avr-gcc automatically called on arduino-builder binary, let i see what the output of your console log after your compile/upload sketch file and what your the steps tried?

In my case, i would tell you compile/upload your sketch Arduino on Ubuntu 17.10 like my owned.
I have

Wemos D1 MINI Board based ESP8266 chip.
Define ttyUSB0 port like my Owned.

Before upload your sketch, you need Arduino Package for Ubuntu in Arduino Official Pages or if you have Arduino Package on your Aptitude Source list / PPA Repository of Arduino with following sudo apt-get install -y arduino. that's same to me.
After your Arduino Package installed, try to following commnand :
cd /path/installation/package/ //for change directory to Arduino Package

ARDUINO-DIR(pwd) //for make environment of Arduino directory

cd $HOME/Arduino/sketch/ //for change directory to your Arduino sketch

ls -l //for list all items in your folder

$ARDUINO-DIR/arduino --verify sketch.ino --board (board) --port (port) --verbose //for compile your sketch

$ARDUINO-DIR/arduino --upload sketch.ino --board (board) --port (port) --verbose //for upload your sketch

NOTE:
e.g --board esp8266:esp8266:d1_mini //for WemosD1Mini board or
e.g --board arduino:avr:uno //for ArduinoUNO board.
e.g --port /dev/ttyUSB0 or /dev/ttyACM0 //if your define ttyUSB0 or ttyACM0 port you have.
See Below to my verbose log appears a avr-gcc and a avr-g++ automatically called in arduino-builder binary to compile all my library defined.

Hope you can get it.

I figured it out. Ubuntu arduino IDE was missing a library. Thank you for helping out

@JustCurious glad to hear that.

@JustCurious which library? It would be nice if you posted the solution as an answer for future visitors.