text:
Can a 12V sensor connected to a 5V output signal of an Arduino Uno
I am doing a project for object detection. But my problem is I'm using a 12V photoelectric OMRON sensor to connect with 5V Digital PWM port 3 on Arduino using normal coding. Do I need an extra circuit to step down the voltage to 5V? Can it work because the only connection between the sensor and Arduino is the output signal, the VCC and Ground are from external power. Link to the datasheet Please help me

sensors are not connected to outputs ... inputs are used for that

Can you share the Omron datasheet also so we can suggest to you the circuit required

I have shared the datasheet sir @Maaz Sk

Yes you need to step down the sensor voltage using any external circuit. Arduino GPIOs cannot bear that much voltage.

My favorite solution for such an application is to use an optoisolation module. In this case, the signal can have a voltage of 12 V and the output of the optoisolation module can be connected to the input of the Arduino, where the input is configured as INPUT_PULLUP.
Example of the optoisolation module:

In this way it is possible to connect other types of sensors and switches and the solution is universal also for other development kits, e.g. with 3V3 logic.

TQ so much. But can you explain it to me more detail sir. Are you implying i have to connect the 12V sensor to arduino port 3 normally, with the optoisolator is connected to the arduino input port? How does that works? Sorry for my bad understanding

@DeSafa Connect the sensor to the input of the optoisolator module (2 pos. terminal) – signal and GND. Connect the Arduino to the 3 pos. terminal – 5V pin, input pin (e.g. D2), and GND.

TQ sir for your help. May i have the source code? Or just copy online anywhere

Just google and use digitalRead() function.

Thank you so much again @JSC

For one, you need to connect the two grounds together.
Secondly, the 12V signal will indeed fry your Arduino. Lower the voltage to just below 5V, using a voltage divider circuit. You could for example use a combinations of a 2.2kOhm and a 1.5kOhm resistor, to get around 4.9V.

Don't use a voltage divider circuit whatsoever, you will probably damage the chip. Use a transformer or buck converter. Unless you calculate the load induced that will be induced on the voltage divider, you cannot guarantee the voltage divider will provide a steady 5v, as load changes the output voltage of a voltage divider.

@JamesBarnett I was talking about converting a 12V signal to a 5V signal. Not converting 12V to 5V, to be used to supply power. Since the output of the voltage divider goes into an Arduino INPUT pin, the current will be next to nothing, and will not affect the voltage.

Oh, makes sense. Sorry!


text:
Drawing a line at a given angle
Im attempting a device that measures lean angle. I have an ESP8266 + MPU6050 + SSD1306 setup, and I've managed to build a shaky but somewhat functioning device.
What Id like to do is use the Adafruit_SSD1306 library to call the display.drawLine(x, y, x1, y1, color) function and have the line drawn to the measured angle output of the MPU6050.
The screen I'm using is 128 X 64
The MPU6050 is initially laying flat at 180 degrees, but is set and displayed as 0 degrees of tilt. The line is drawn vertically on the screen and pivots around x1 and y1 at 64, 64 respectively in the middle at the bottom of the screen.
If the MPU6050 pivots left like in the picture, the angle measurement itself is roughly correct, but the line indicator is showing more like 30 degrees than 45, and gets worse the larger the angle value.

My code:
#include <Adafruit_MPU6050.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>

const int MPU_addr=0x68;
int16_t axis_X,axis_Y,axis_Z;

Adafruit_MPU6050 mpu;
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);

int minVal=265;
int maxVal=402;

double x;
double y;
double z;
int tiltAngle;
double y2;

void setup(){
  Serial.begin(9600);
  Serial.println("MPU6050 OLED demo");

  if (!mpu.begin()) {
    Serial.println("Sensor init failed");
    while (1)
      yield();
  }
  Serial.println("Found a MPU-6050 sensor");

    // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64
    Serial.println(F("SSD1306 allocation failed"));
    for (;;)
      ; // Don't proceed, loop forever
  }

  display.display();
  delay(500); // Pause for 2 seconds
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setRotation(0);
}
void loop(){
  display.clearDisplay();
  display.setCursor(0, 0);

  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);
  axis_X=Wire.read()<<8|Wire.read();
  axis_Y=Wire.read()<<8|Wire.read();
  axis_Z=Wire.read()<<8|Wire.read();
    int xAng = map(axis_X,minVal,maxVal,-90,90);
    int yAng = map(axis_Y,minVal,maxVal,-90,90);
    int zAng = map(axis_Z,minVal,maxVal,-90,90);

     x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
     y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
     z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

     tiltAngle = (int) x - 180; // we want the tilt angle to be 0 degrees
     display.println(" ");
     display.println(" ");
     display.println(" ");

     // display only positive angle values for either direction of tilt
     if(tiltAngle > 0){ display.print(tiltAngle);}
     else if (tiltAngle < 0) { display.print(tiltAngle * -1);}
     else {display.print(tiltAngle);}

     display.drawLine(-tiltAngle + 64, 0,64,64,WHITE);
     display.display();
     delay(100);
}

Im aware that for my first y co-ordinate I will need to use some kind of formula to get the line to move down from 0 (the top of the screen) as the lean angle gets greater. I'm hoping someone could point me in the right direction for drawing the line at the angle given by the MPU6050.
I did consider using case statements for each angle value and drawing the line with fixed co-ordinates based on each angle value. But that seems too compute intensive and could take up too much of the DRAM. Is anyone aware of a simple formula I could use? Thanks for reading.

Use trigonometry (sin() and cos()) functions to get the right x and y coordinates.
I would consider replacing your drawLine() command with something like this (untested) assuming the tiltAngle is in degrees from -90 to +90 (with 0 degrees is straight up) and you want to draw a line at this angle from the origin (63, 63) with a radius of 64.
float tiltAngleRad = tiltAngle * DEG_TO_RAD; // convert angle to radians
int xEnd = 63 + 64 * sin (tiltAngleRad); // Ending x-coordinate offset & radius
int yEnd = 63 - 64 * cos (tiltAngleRad); // Ending y-coordinate offset & radius
display.drawLine (63, 63, xEnd, yEnd);

You might have to experiment with the offset and radius but I believe this will get you close yo what you want.

Hi, thanks for this, I'm gonna have to educate myself more on the trig involved here, but thanks again it seems to work!

source: Stack Exchange

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

sort: votes


text:
Building a VU meter
I am building a VU meter with two 5v neopixel rings, two potentiometers, a headphone jack and an Arduino nano. Will 5 volts 1 amp cut it, or do I need more power? FYI I'll be powering it via a DC jack once I get it working.

How many LEDs are in each of the Neopixel rings?

It should be enough if you avoid white and use single-color zoned metering.

they each have 24 led's on each ring and what is single-color zoned metering?

Normally the maximum amount of current a typical LED can withstand is 20 mA. This means per color and per LED.
So if you have 60 LEDs, than you get 60 (leds) * 3 (R/G/B colors) * 20 mA = 3,600 mA.
To give some headroom I would use a 4A or 5A adapter.
However, note that probably 5 mA or 10 mA per LED would be enough to be very good visible, unless you want it to be as bright as possible.

4A or 5A at 5V?

4A will give 10% 'headroom', 5A even more. In electronics it is better to be safe, probably 4A will be ok, if you want to be sure/safer, use 5A. You could do some tests when switching all LEDs on, under different temperatures, and find out the worst case. If you don't want to do such testing, use 5A.

so i would need 5A if i want to power the nano off of the same supply?

@taran i don't know how much the nano used, but i think it's not much... Add it up to the LEDs per usage and use some headroom.

total A with per io pin 3,640 so i would need a 5v 4a power supply, correct?

yes, but if you want to be sure, use an oscilloscope or multimeter and round up.

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


text:
ESP8366: ets Jan 8 2013,rst cause:4, boot mode:(1,7)
I am trying to control esp8266 esp 01 with Alexa
This is my code:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "fauxmoESP.h"

#define ssid "admin"
#define pass "admin0000"

#define device1 "arduino"

fauxmoESP fauxmo;

void wifi()
{
  WiFi.mode(WIFI_STA);

  WiFi.begin(ssid,pass);
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print("not connected\n");
    delay(100);
  }
    Serial.print("1");

}

void setup()
{
  Serial.begin(115200);
  wifi();
  fauxmo.createServer(true);
  fauxmo.addDevice(device1);
  Serial.print("device added\n");
    fauxmo.setPort(80);
   fauxmo.enable(true);

  fauxmo.onSetState([](unsigned char device_id, const char * device_name, bool state, unsigned char value) {
  Serial.printf("[MAIN](%s) state: %s\n",device_name, state ? "ON" : "OFF");
    if (strcmp(device_name, device1) == 0)
    {
      if (state)
        Serial.print("3");
      else
        Serial.print("2");
    }

  });
}

void loop()
{
  fauxmo.handle();
}

And I am getting an error after 10 - 20 sec
ets Jan  8 2013,rst cause:4, boot mode:(1,7)

wdt reset

Anyone please help me to solve this issue

Looks like a watchdog timer reset. You could try to "feed" the watchdog by adding a yield(); command inside loop();, for example.

you have io 0 LOW so on watchdog reset the exp8266 goes into flashing mode

@StarCat adding a yield() call to that loop() won't do anything. loop() has an implicit yield() when it returns. Give that there's only one line of code inside loop(), adding a yield() would be pointless.

@romkey correct, but there’s still a watchdog timeout.

@StarCat yes but adding a yield() as you suggested won't fix that in this case - there's already an implicit yield() as soon as loop() returns. It already happens, and doesn't solve the timeout.

@romkey, yes, I already agreed with you.


text:
Unable to make a really basic sketch work
I've been learning how to encapsulate my code within functions, and one of the examples I worked on is a simple INPUT_PULLUP button. When I upload the sketch from the arduino website everything works, so I know it's not a hardware issue. However, with the code below the button will just not go LOW.
I just don't see what the issue is, and I'm feeling really hopeless that I can't even get the simple thing done. I would be grateful for any advice.
int button_pin = 2;
int button_state = 0;

void setup() {
  Serial.begin(9600);
  pinMode(button_pin, INPUT_PULLUP);
}

void loop() {
  Button();
}

void Button() {
  // Read button(s)
  button_state = digitalRead(button_pin);
  if (button_state = LOW) {
    Serial.println(button_state);
  };
};

You have an error in the if statement. For checking equality, you need to use == (double equal sign). A single = is an assignment. So you are actually assigning the value LOW to button_state. And an assignment will return the value, that you assigned, in this case LOW, aka 0, aka false. Thus the if statement will never be entered

Thanks Chris, I will try this and report. I don't know what I would do without you people. I wasted several hours on this yesterday trying everything I could think of with no success.

#define button_pin 2  //defining button pin as pin 2
bool button_state = 0; //button state is either 0/1 so using bool
void Button();
void setup()
{
    Serial.begin(9600);
    pinMode(button_pin, INPUT_PULLUP); //Setting input as input pullup
}

void loop()
{
    Button();
}

void Button()
{

    button_state = digitalRead(button_pin); //Read button state
    if (button_state == LOW)
    {
        Serial.println(button_state); //print button state when it is low
    }
}

In your code, you have used = operator in place of == in the if loop. Just if you change it, it will start working also you can use my above code it is same as yours just I have made some minor changes such as using bool in place of int and use of #define in place of pin declaration where you used int

Thank you very much for taking the time to answer. It's really helpful and I appreciate it.

@ZhelyazkoGrudov I am glad it helped you out. Good luck :)


text:
ESP-32 Upload Files to SPIFFS via browser
I am using ESPAsyncWebServer Library in a ESP32 DevKit. I want to make a form in the browser in order to upload files in SPIFFS.
I have to notice that the whole device works perfectly. I connect to Wi-Fi, it uploads files via IDE etc.
Through searching in the net, I found this part of code that does not work.
server.on("/upload-file", HTTP_GET, [](AsyncWebServerRequest* request) {
    String html = "
<form method='post' action='/upload-file'><input type='file'><button>Send</button></form>
";
    request->send(200, "text/html", html);
    });

server.on("/upload-file", HTTP_POST, [](AsyncWebServerRequest* request) {
    AsyncWebServerResponse* response = request->beginResponse(200, "text/html", "hello world");
    response->addHeader("Connection", "close");
    request->send(response);
    }, handleUpload);
server.onFileUpload(handleUpload);

The handleUpload function:
void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
if (!index) {
    request->_tempFile = SPIFFS.open("/" + filename, "w");
}
if (len) {
    request->_tempFile.write(data, len);
}
if (final) {
    request->_tempFile.close();
    request->redirect("/files");
}
}

It shows the form but the file doesn't upload.
Is there any idea on how can I make it work?

how far along does it get? Does the browser re-direct after upload? I would add Serial.println("saw1") (and 2 and 3, etc) statements to each function to trace the flow.  If it makes it all the way through, or in the last working part's code, start logging the function's arguments to see where things are not as expected.

I had the same problem and thanks to you, I did solve the problem!
Here is the full code,
My html code for the upload page, the form is in the  tag:

<!DOCTYPE html>

  <title>File Upload Example</title>

File Upload Example

<form method="POST" action="/upload" enctype="multipart/form-data" target="iframe"><input type="file" name="upload"><input type="submit" value="Upload"></form>

code for ESP:

void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
if (!index) {
    request->_tempFile = SPIFFS.open("/" + filename, "w");
    Serial.println("1");
}
if (len) {
    request->_tempFile.write(data, len);
     Serial.println("2");
}
if (final) {
   Serial.println("3");
    request->_tempFile.close();
    request->redirect("/");
}
}

 controlserver.on("/upload", HTTP_POST, [](AsyncWebServerRequest *request) {
        request->send(200); }, handleUpload);

  controlserver.on("/UPL", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/html", upl);
  });

  readFile(SPIFFS, "/11.txt"); // show the content of the uploaded file, obviously you should know the name of the uploaded file!

you can write a function like this to make sure the file was delivered:
  readFile(fs::FS &fs, const char * path){
  Serial.printf("Reading file: %s\r\n", path);
  File file = fs.open(path, "r");
  if(!file || file.isDirectory()){
    Serial.println("- empty file or failed to open file");
    return String();
  }
  Serial.println("- read from file:");
  String fileContent;
  while(file.available()){
    fileContent+=String((char)file.read());
  }
  file.close();
  Serial.println(fileContent);

}


text:
What motor to move a small telescope?
i just bought a hobby telescope, it works well for being nothing much than a toy, the very problem is that the gesrs that should keep it stable are all plastic and very hard to tighten while keeping it steady.
So I thought to let the gears wide open and move it with arduino: you point the object manually then with 4 buttons move it by small steps.
I've tried to use a couple of servos i had at home, mg90s 2kg 180°; while 180° is enough for the purpose, first i don't think 2kg is enough for the X axis motor, second one is not very precise (using the default library).
I know I can achieve better results calibrating the pulse manually, but maybe is better if I use better motors.
What motors (and why) would you reccomand?
Servo or stepper?
Being for a hobby the budget is low, so very max 50$?

It's really not an easy task to build a stable mount control on an unstable platform. There are good reasons why reasonable quality telescope mounts are in the $500+ price range. Will you be using it for astonomical objects (i.e. tracking)?

I wouldn't use a servo for this. You don't have very fine control over the angle with a servo. Also with a typical telescope the focus is more on rather slow and precise movements, instead of fast ones.
Instead I would use a stepper motor. Depending on your exact requirements, these can be rather cheap to rather expensive.
Here also the mechanics come into play. The motor should not be attached directly to the axis, but instead through some gears (the axis of the telescope having the larger gear). That will allow for smaller, more precise movements and also lower the needed torque for the motor. Of course this depends on your actual telescope hardware, meaning if you can put a gear right to the axis. If not, you could limit the motor driven movement a bit and install a level, which then could be pushed or pulled by a nut on a threaded rod, which gets driven by the servo motor. This would be rather easy to implement, though you may need to correct for the different rotation behavior, when you get to the outer sides of the movement (for the actuator being linear, while the resulting movement is circular), by some mathematics in your code.
Since you want to keep your costs very low, you might wanna use the 28BYJ-48 stepper motor (including the fitting driver). In terms of stepper motors they are rather bad, but they are really really cheap and - depending on the gear ratio/level length/thread pitch - it might not matter that much for you. You could always update to a better stepper motor in the future.

I agree with using a stepper motor. Some commercial telescope mounts use a normal gear motor with feedback from an opical encoder.

Thank for your reply. The main idea is to build something with a rotating plate (this way can be paired with some lights and become a quick tool to take pictures of small items, for example), and since here no problem i could use the cheapest motor with a gear and a belt, easy to do and to keep stable. For the up/down movement, considering that has to lift the weight of the telescope, I'll try your suggestion. I need to make some prototypes with the structure becouse would be nice to have a full 160° rotation.

For the vertical motion a stepper motor would also be better than a servo. It ca give you more torque. Also: When you are using a gear or threaded rod with nut on it, the actual force is also multiplied. The mentioned stepper motors have a bit of slack, but I used them for a self build laser engraver and had OK results. Make sure, that you provide enough power to the motors, or you will have less torque


text:
Is it possible to write data to a fat file system on SPI flash using an arduino?
I have an SPI flash based mp3 module and was wondering whether its possible to write to the flash chip using a microcontroller(arduino). the IC supports FAT16/FAT32 file systems. I have researched arduino and the fat file system but they are all in relation to SD cards which operate differently as far as i understand. Is it possible to write data to a fat file system on SPI flash using an arduino?

Isn't that SPI flash on this board already connected to the boards controller? I think SPI not multi-master capable. So you would need to disconnect the flash from the boards controller

yes it is. but i wanted to load new content onto it using a MCU.

But that means, that the first important question is, how to communicate with the flash chip, without conflicting with the boards MCU. At that point the filesystem is irrelevant.

I'd thought that since its possible to write files onto the chip from a computer it might be possible to do the same thing with an external MCU

Most likely the USB port connects to the boards MCU, which then in turn connects via SPI to the flash chip. So for the flash chip it is equal if you write data via USB or play music on the board. Both are only SPI communications with the boards MCU. My guess is, that you either need to extract the flash chip from the board and add some kind of multiplexer to it (so that you can switch between the SPI connections to the internal MCU and your external one), or that you need to use an USB host board with your external MCU to write data through the USB interface.

hmmm yes that makes sense. usb host boards is an interesting thought, new concept to me, i will look into that.(and update if there is any success) thanks very much for the help.

The first and most important problem is not the filesystem. Currently on the board the USB port is connected to the internal MCU, which in turn is connected via SPI to the flash chip. The internal MCU is the master on the SPI bus. But the SPI bus does not support multiple masters on one bus. So just connecting the external MCU to the SPI lines as master would not work.
I see 2 possible ways to go here:

You can unsolder the flash chip from the board and add a fitting multiplexer chip, which can switch the SPI lines between the two masters. That effectively gives you only one master on the SPI bus at any time. This way would be rather hacky and difficult for a beginner. It might also be important to keep an eye on the capacitance of the bus, since it might run with rather high speed. A too high capacitance (for example through using a breadboard) might result in erroneous communication.
Then you could use one of the FAT libraries. I don't know them in detail, but I think you could also use them for a simple SPI flash chip. You just would need to implement the lower level access functions, that the FAT library needs.

Or you could try to use a USB host board with your external MCU and try to write data through the USB port. I don't have much experience with USB host boards, so I cannot really tell you, if and how exactly this is possible with the available hardware (the board will most likely implement an USB interface like a simple flash USB stick).

All in all I think, this would be rather hacky. Your board is not really made for changing the data through another microcontroller. Depending on what exactly you want to achieve, you might want to go to a different hardware setup.

Thanks very much for taking the time to answer. much appreciated.


text:
IRremote and PCM sound libraries interfering
I have a simple sketch which sends IR codes, plays a sound and toggles an LED when you press a button and toggles another LED when it receives that code. The idea is that I have two Arduinos with this same sketch and when you press the button on one, the LED is toggled and so is another LED on the other Arduino. This program works as intended when the sound is not included.
Here is the sketch:

#include <IRremote.h> // For the IR transmition and receiving
#include <PCM.h> // For the audio output

IRsend irsend; // Setup the IR transmitter
const int receiver = 8; // Initialize pin 13 as recevier pin.
IRrecv irrecv(receiver); // Create a new instance of receiver
decode_results results;

// Declare arrays to hold sound notes to play
const unsigned char gunShot[] PROGMEM = {}; // There is a huge list of numbers in this array, but I removed them to make the code easier to read

const unsigned char gunClick[] PROGMEM = {}; // There is a huge list of numbers in this array, but I removed them to make the code easier to read

// declare consants
const int button = 13;
const int greenLight = 7;
const int yellowLight = 2;
const int timeBetweenTransmittion = 800; // At least 800 milliseconds between two transmissions
// The speaker is fixed on pin 11

// declare variables
bool toggleGreen = true; // Bool variables to toggle the lights
bool toggleYellow = true;
long int previousTransmittion = 0; // Long int to store the timestamp in millis of the previous transmission

// put your setup code in here, to run once:
void setup()
{
  pinMode(button, INPUT_PULLUP); // Setup the button with an internal pullup resistor
  Serial.begin(9600);
  irrecv.enableIRIn(); // Enable the receiver
  Serial.println("start");
}

// put your main code in here, to run repeatedly:
void loop() {
  if (not digitalRead(button) && millis() > previousTransmittion + timeBetweenTransmittion) // If the button is pressed and it's been enought time since the last transmittion
  {
    Serial.println("send!");

    // Different orders of these lines of code were tried:

    //startPlayback(gunShot, sizeof(gunShot)); // Play shot before sending the code and enabling the receiver (play command 1 for reference)
    //delay(250);

    irsend.sendNEC(1367857, 32); // Send the code

    //startPlayback(gunShot, sizeof(gunShot)); // Play shot between sending the code and enabling the receiver (play command 2 for reference)
    //delay(250);

    irrecv.enableIRIn(); // Sending ir stops the receiver so start the receiver again

    startPlayback(gunShot, sizeof(gunShot)); // Play shot after sending the code and enabling the receiver (play command 3 for reference)
    delay(250);

    // Toggle the yellow light
    digitalWrite(yellowLight, toggleYellow);
    toggleYellow = not toggleYellow;

    previousTransmittion = millis(); // Set the record for latest transmittion to the currnt time
  }

  if (irrecv.decode(&results)) // If we have received an IR signal
  {
    Serial.println (String(results.value, HEX)); // Display HEX results
    if (String(results.value, DEC) == "1367857") // If the code is the right one
    {
      Serial.println("correct code");

      // toggle the green light
      digitalWrite(greenLight, toggleGreen);
      toggleGreen = not toggleGreen;
    }
    irrecv.resume(); // Prepare the receiver for the next code
 }
}

// End of sketch
As you can see, I tried putting the play sound line before, between and after the IR transmission lines of code. The delays are there so I can see if the audio starts to play and stops or if it just never plays. Here is what I found from all the combinations:

In all the combinations (play command 1, 2 and 3), The IR receiver worked as intended if used BEFORE ever pressing the button.

None of the combinations stop the loop as if I put <Serial.println("loop");> at the start of the loop() routine, it continues to print "loop", regardless of what I do.

In play command 1 and 2, the sound plays when I press the button, but stops after the 250ms delay. Once the button has been pressed once, it doesn't do anything when I press it again (doesn't print "send!" or toggle the light). The receiver receives one more code after pressing the button, but always prints the code "2a", regardless of what button on my tv remote I press (the tv remote usually prints a 6 character hex code). After it prints "2a", it doesn't receive any more codes.

Play command 3 plays the full sound and sends the right code, and allows me to do it as many times as I want (the button still works after pressing it more than once). However the receiver still no longer works after the first time I press the button. It doesn't receive "2a" the first time after pressing the button unlike the first 2.

I am using the libraries IRremote by shirriff, z3t0 and ArminJo (VERSION 2.6.1) and PCM by David Mellis, Michael Smith (VERSION 1.0.0) (http://highlowtech.org/?p=1963). I don't know if there is a simple way around this problem or if these libraries just cannot be used together.
I have the speaker on pin 11.
If you need anything clarifying please ask. Any help would be appreciated, thanks in advance.

The PCM library uses timer 1, and timer 2. The IRremote library uses timer 1. So they both need timer 1. So there's a conflict. So you can't use both libraries at the same time, unfortunately.

Okay, thanks. Do you know of any other libraries that I could use together that would allow me to use IR and sound which don't conflict?

Easiest would be to offload the sound playback to a different chip, like the dfplayer mini (which carries a micro SD card)

Okay, thanks. I've had a brief look and that looks like a good solution.

It works for me if i put a delay after startPlayback followed by a irrecv.enableIRIn();
startPlayback(sample, sizeof(sample));
delay(1000); // delay needed as long audio is playing
irrecv.enableIRIn(); // enable input from IR receiver after using PCM library startPlayback


text:
SG 90 not working
I have tried almost everything but the servo is not moving at all
here is my schematics
https://create.arduino.cc/projecthub/arcaegecengiz/how-to-use-servo-motors-with-arduino-b02bed
Here is my code
#include <Servo.h>

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

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

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

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

I cannot see your schematics, since they seem to be in fritzing format (fzz?) and I don't have that program. So please include the schematic as image in your question. Also, since that is a schematic from a tutorial, a good quality, in focus picture of your actual setup (where we can see the actual connections) might be good. Your code seems to be the standard sweep example. I don't see much to troubleshoot there


text:
Multiple IR Sensors with Arduino
I am fairly new to working with sensors and Arduino. I am working on a project using Max MPS to control the volume of three audio files. There will be three framed photos, each having its own IR sensor and audio file. So when someone gets closer to the sensor, the volume of the corresponding file gets louder. Is this doable? The samples I have seen with the board I have and an IR sensor only use one. I'm assuming I'll be able to use the breadboard I have to add more sensors like I've done in the past with photocell sensors but I have yet to test it since it's in the mail. Just hoping to get ahead of any issues I may face and see if I should order any other equipment.
I ordered 3 of these IR sensors and this is the Arduino kit I am working with.
Sorry if I may not be describing it in enough detail, but thanks in advance!

Yes, doable. Though the range will depend on the sensors. Do you have any other question, that is not just a yes-no question?

technically yes, there is no reason you can't do that project but the issues will come in how complex you wish to make system. For example, it shouldn't be too hard to hook up the three sensors to three analogue Pins on the Arduino and then have the Arduino constantly loop to check the voltage of the sensors, from which, you would tell it to 'do something' when one of the IR sensors voltage is above or below a certain value. What you then choose to do is up to you, if it's just to turn on a light then it can be done fairly quickly once you have all the components. For controlling the Audio in the file, I personally have no experience with this.
What might be better is first checking to see if you can Adjust the audio in one of your files using an Arduino (you may need to use bluetooth or have something on your PC communicate with your Arduino via UART through the USB).
Generally, with new projects, it's a good idea to figure out a solid plan for exactly what you want to do, so I would write down in detail what you want the system to do and then go through each part to see if it's possible


text:
Ultrasonic HC-SR04
Having trouble with arduino
Ultrasonic Sensor  Module
HC-SR04
I'm sure when you read this you're going to say how stupid can he be and you're probably right but I'm 82 years old and I'm trying very hard. They say you're never too old to learn I hope they're right
This sensor model is driving me crazy I have tried and written two or three sketches and I cannot get it to work I know how simple it is for wires big deal but when I tried to read it through my serial monitor I get this a bunch of backward ? A C S A ? But the question are backwards . I have used two different boards new ones and tried three Ultrasonic Sensor hope you can help me thank you Dennis

you said absolutely nothing about the hardware, how it is connected, the program and the problem you are having

It sounds like an incorrect baud rate setting to me.

With such question please always include your code and your wiring. But I second Majenko with that it sounds like a wrong baudrate. In the Serial Monitor you need to select the same baudrate, that you used in your sketch with Serial.begin().


text:
What happens when you call malloc()/free()/new/delete?
So I understand that generally speaking, dynamic allocation should be avoided. My question isn't how or why, but what happens when you call a function that allocates memory?
On Windows or Linux, when a program allocates memory, a whole bunch of stuff happens, things like virtualisation and security related features that have no relevance to arduino, and the bit that I'm interested in, memory management:
There will be some code, that will look at the alignment and size requirements of the allocation request, look at the pool of memory it has access to, find a space big enough, make a note of the allocation (which also uses some amount of memory) and then return a pointer to the allocated space back to the calling function.
Is there a custom malloc implementation for each device, or does it come with the arduino toolchain (and does that mean Arduino has a different implementation from Teensy, or avr from sam?), or is there some magical default implementation supplied by the compiler? What kind of memory overhead is incurred with every allocation? How easy is it to override this functionality and implement your own (out of morbid curiosity or tendency towards masochistic endeavours)?

For an overview of malloc() on AVR, see this page of the avr-libc documentation.

Regarding "each device" vs "Arduino toolchain" and malloc:, largely neither.  It's part of a libc implementation that typically covers many devices. Customizing the libc malloc in an algorithmic way usually means patching building libc yourself. There are a few Arduino specific stubs e.g. for new/delete and moving the stack/heap break, but the bulk of what you're asking about (which is a lot) has really not much to do with Arduino.

The four or so non-AVR malloc() implementations that I've looked at, including Due and ESP8266 ones use same the basic scheme described in EdgarBonet`s link and are tunable in roughly the same ways.

The "avoid dynamic allocation" afaik is an MCU thing, I asked a pro (non-embedded) C++ dev about it and he looked puzzled but agreed that it should be avoided if the coder doesn't know what they are doing. Without an OS, the MCU cannot clear garbage, so mistakes matter a lot more than on a PC, but dynamic allocation certainly can be done, and done reliably, on an MCU, as long as the system parameters are understood and respected.

I'm sorry @dandavis but I see "MCU" and all I can think of is a certain comic book movie franchise.

We tend to use MCU for microcontroller, some people use just micro for short. A bit confusing at first.

There are some hardware-specific abstractions (they mostly define the maximum memory available), but otherwise these are functions are implemented by the C/C++ runtime (on arduinos an implementation called "NewLib") and usually "just work". You might want to take a look at this question, where quite a bit of background is given on the SAM implementation of the hardware abstractions (because it's broken).
And yes, of course using malloc/free has some considerable overhead, which is one reason why it's not the recommended way of allocating memory on microcontrollers. But the logic behind it is mostly the same whether there's 2k of memory or 2G. And the memory model of modern microcontrollers (at least the 32 bit ones) is very similar to the one seen in 32 bit Windows or Linux apps.


text:
How to unbrick an Arduino Mega+ESP8266 Wifi
I have a Jaycar XC4421 - Arduino Mega + Wifi which I think have somehow managed to screw up the boot loader.
I have an XC4627 USP-ISP Programmer (and the XC4613 adaptor) which I have previously used to successfully burn boot loaders and update sketches in the past using the Arduino IDE.
However, on this occasion, after trying to reset the bootloader from the IDE, i can no longer upload sketches from the IDE using the inbuilt "upload" function of the IDE (I get timeouts) nor can I upload the sketch using the USB-ISP Programmer.
The symptoms as they currently stand with the USB connected to the 2560 (switches 3 & 4 on, all others off):

If I burn the bootloader (selected board in IDE is "Arduino Mega or Mega 2560"), this appears to work, but uploading sketches still does not work. After burning the bootloader, the builtin LED blinks at an odd cycle of roughly 400ms off, 400ms on, 200ms off, 200ms on.
The board is recognised in the IDE and appears as COM12
If try to upload the "blink" sketch (ctrl-U), I get timeout messages (see transcript below)
If I connect the USB-ISP and upload the blink sketch (ctrl-shift-U), the upload appears to work, but the sketch is never run (i.e. the builtin LED doesn't blink).
After uploading the blink sketch (via the USB-ISP programmer) the aforementioned odd blinking of the builtin LED completely stops (i.e. no blinking at all).
There is no hardware other than the USB-ISP programmer connected to the ICSP pins on the Arduino.
If I reset the DIP switches so that just 5 & 6 are on (USB->ESP) I am able to interact just fine with the "AT program" that was originally supplied on ESP side of the board.

My suspicion is that the Arduino Mega 2560 bootloader code is not completely compatible with the Arduino Mega + WiFi board. I don't think that suspicion makes much sense, but I'm out of ideas!
Where can I get the correct bootloader for this device? Alternatively, how can I correctly unbrick this?
Transcript from "upload blink sketch" showing timeout:
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\gmc\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\gmc\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\gmc\Documents\Arduino\libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\gmc\AppData\Local\Temp\arduino_build_510155 -warnings=none -build-cache C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -verbose C:\Users\gmc\AppData\Local\Temp\arduino_modified_sketch_481876\Blink.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\gmc\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\gmc\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\gmc\Documents\Arduino\libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\gmc\AppData\Local\Temp\arduino_build_510155 -warnings=none -build-cache C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -verbose C:\Users\gmc\AppData\Local\Temp\arduino_modified_sketch_481876\Blink.ino
Using board 'mega' from platform in folder: C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3
Using core 'arduino' from platform in folder: C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3
Warning: Board arduino:avr:ATmega328p-8 doesn't define a 'build.board' preference. Auto-set to: AVR_ATMEGA328P-8
Detecting libraries used...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE
Generating function prototypes...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\preproc\\ctags_target_for_gcc_minus_e.cpp" -DARDUINO_LIB_DISCOVERY_PHASE
"C:\\Program Files (x86)\\Arduino\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\preproc\\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core: C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521\core\core_arduino_avr_mega_cpu_atmega2560_995451215dbc0ff7e2274fbcd94e62ea.a
Linking everything together...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega2560 -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp.o" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/..\\arduino_cache_341521\\core\\core_arduino_avr_mega_cpu_atmega2560_995451215dbc0ff7e2274fbcd94e62ea.a" "-LC:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155" -lm
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.eep"
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.hex"
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-size" -A "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf"
Sketch uses 2684 bytes (1%) of program storage space. Maximum is 253952 bytes.
Global variables use 194 bytes (2%) of dynamic memory, leaving 7998 bytes for local variables. Maximum is 8192 bytes.
C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega2560 -cwiring -PCOM12 -b115200 -D -Uflash:w:C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM12
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

avrdude done.  Thank you.

An error occurred while uploading the sketch

Transcript from "Upload blink sketch using programmer":
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\gmc\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\gmc\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\gmc\Documents\Arduino\libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\gmc\AppData\Local\Temp\arduino_build_510155 -warnings=none -build-cache C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -verbose C:\Users\gmc\AppData\Local\Temp\arduino_modified_sketch_753905\Blink.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\gmc\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\gmc\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\gmc\Documents\Arduino\libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=1A86_7523 -ide-version=10813 -build-path C:\Users\gmc\AppData\Local\Temp\arduino_build_510155 -warnings=none -build-cache C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.3.0 -verbose C:\Users\gmc\AppData\Local\Temp\arduino_modified_sketch_753905\Blink.ino
Using board 'mega' from platform in folder: C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3
Using core 'arduino' from platform in folder: C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3
Warning: Board arduino:avr:ATmega328p-8 doesn't define a 'build.board' preference. Auto-set to: AVR_ATMEGA328P-8
Detecting libraries used...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE
Generating function prototypes...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\preproc\\ctags_target_for_gcc_minus_e.cpp" -DARDUINO_LIB_DISCOVERY_PHASE
"C:\\Program Files (x86)\\Arduino\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\preproc\\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\cores\\arduino" "-IC:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\hardware\\avr\\1.8.3\\variants\\mega" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp" -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core: C:\Users\gmc\AppData\Local\Temp\arduino_cache_341521\core\core_arduino_avr_mega_cpu_atmega2560_995451215dbc0ff7e2274fbcd94e62ea.a
Linking everything together...
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega2560 -o "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155\\sketch\\Blink.ino.cpp.o" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/..\\arduino_cache_341521\\core\\core_arduino_avr_mega_cpu_atmega2560_995451215dbc0ff7e2274fbcd94e62ea.a" "-LC:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155" -lm
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.eep"
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf" "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.hex"
"C:\\Users\\gmc\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-size" -A "C:\\Users\\gmc\\AppData\\Local\\Temp\\arduino_build_510155/Blink.ino.elf"
Sketch uses 2684 bytes (1%) of program storage space. Maximum is 253952 bytes.
Global variables use 194 bytes (2%) of dynamic memory, leaving 7998 bytes for local variables. Maximum is 8192 bytes.
C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega2560 -cusbasp -Pusb -Uflash:w:C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\gmc\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega2560
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
           flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9801 (probably m2560)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: reading input file "C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex"
avrdude: writing flash (2684 bytes):

Writing | ################################################## | 100% 1.69s

avrdude: 2684 bytes of flash written
avrdude: verifying flash memory against C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex:
avrdude: load data flash data from input file C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex:
avrdude: input file C:\Users\gmc\AppData\Local\Temp\arduino_build_510155/Blink.ino.hex contains 2684 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 1.43s

avrdude: verifying ...
avrdude: 2684 bytes of flash verified

avrdude done.  Thank you.

Well after "working" on this all day, it turns out that the solution was to use the "Arduino as an ISP" solution as described on the arduino.cc website.
Why the USB-ISP solution did not work is not immediately obvious as I have used it successfully before - just not with this board!
FWIW, the blinking sequence I observed when burning the bootloader via the USB-ISP programmer also occurred after loading the bootloader via the "Arduino as ISP" solution. I don't know if the sequence was identical, but it certainly was similar. I then tried uploading the blink sketch using the "inbuilt" upload (ctrl-U) and the inbuilt LED blinked "correctly" at a 1s on 1s off cycle as per the standard blink sketch is programmed to do.
Oh well, hopefully this "answer" will help others.


text:
Is it bad practice to multitask without timing constraints
Going through resources such as several things at the same time and with some greatly appreciated assistance on here I'm finally getting a grasp on how to multitask a microcontroller.
Most examples use the millis() approach to nonblocking programming. However, even in the link above the button state is being polled every loop (from what I understood).
So what confuses me is: is it bad practice to write functions, which poll sensor(s) and input(s) without timing constraints, i.e. at every iteration of loop?
Is this still consider nonblocking programming?
I've written some mock code to better illustrate what I mean. Thank you very much for reading through.
void loop() {
    Button();
    Sensor();
    LED();
    // ...
}

void Button() {
  // Read button(s)
  button_state = digitalRead(button_pin);
  if (button_state == LOW) {
    // ...
  };
};

void Sensor() {
  // Read sensor
  int sensor_state = analogRead(sensor_pin);
  if (sensor_state >= 150) {
    // ...
  };
};

Everything blocks a little bit, right? The point is that a delay() is (usually) a pointless blocking that could be better handled. It's better to use interrupts to monitor sensors, when practical. That gets by some of the "single thread" limitations of a sketch and lets the MCU do >1 things at a time.

Like often, the answer is: It depends.
Generally it is non-blocking programming, when you do only short things on each loop. What exactly can be considered short depends on the situation, meaning, what else you want to do.
For example: You are reading an analog value on every loop. The analogRead() will take about 100us (reference). I assume, that your sensor value is rather slow (so the time of signal above 150 would be rather long). Also you are reading a button with digitalRead(). The read takes about 3.6us (reference). So in total you have a loop of - lets say - 150us (with overhead and loop() iteration included). But the event, that you want to catch - the button press - will be in the ballpark of 100ms, which is a factor 667 greater, than the total time of your loop() (when no event happened). So in relation to the shortest event (the button press) all the reads can be considered non-blocking. (Though you could still get blocking through the code inside the if statements. Thats on you to investigate)
Non assume, that you don't have a button, but a digital signal, and you want to sense pulses down to 80us. Then your analogRead() would take too long and you could miss a pulse event. In this case analogRead() might be considered blocking.
So, to check if you are really using non-blocking code, you would need to ask yourself: Am I giving every code part enough time to execute right and to catch all the intended events? If yes, then you are non-blocking. If no, then you are blocking.

As a side note: Often polling is described as bad, but it really depends on the situation. In your case you poll the inputs sequentially, so every input gets polled at the same (total) rate at which your loop() runs. You are doing nothing else, so why should you lower the processing time by not use polling? The saved time cannot be used better on a microcontroller (in contrast to a PC, where the saved CPU time could be given to a different program).

Hi Chris, thank you for the answer. It was very clear and helped me understand the thought process behind the decision-making so now I have a better framework to work off of.

If you are running off battery, then you should consider having the
microcontroller sleep as much as possible, and not poll the sensors more
often than needed. AFAIK, the Arduino core library provides no facility
for managing sleep, but some third-party libraries are available for
that purpose.
If you project runs off mains power, then there is no point in adding
the complexity of sleep management. Unless your sensors are really slow,
polling them at each loop iteration is generally fine. Specifically, for
a push button, the documentation of the Bounce2 library states that
the button update method should be called on every loop iteration.

Hi Edgar, thanks for responding again. It's going to be running off of a battery so I will have a think about how to implement.

@ZhelyazkoGrudov: Achieving low power consumption is a vast subject. I suggest you start by reading Power saving techniques for microprocessors, by Nick Gammon.

Oh sweet! Thanks for the pointer, I'm sure I would have had another great moment just starting in the middle of nowhere otherwise.


text:
random() Function isn't random at all
I'm using the random() to generate random coordinates for coins in a simple game console. The problem here is that the random() function is not generating random numbers, since the coin is at the same coordinates every single time I upload it. I am using the Adafruit GFX library with the Adafruit 1.44" Color TFT LCD Display. Here is my code (sorry, it's kind of long).
//necessary libraries
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

//colors
#define BLACK    0x0000
#define BLUE     0x001F
#define RED      0xF800
#define GREEN    0x07E0
#define CYAN     0x07FF
#define MAGENTA  0xF81F
#define YELLOW   0xFFE0
#define WHITE    0xFFFF

//pins
#define TFT_CS  10
#define TFT_RST  9
#define TFT_DC   8

//joystick variables
const int VRxPin = A1;
const int VRyPin = A0;
const int SWPin  = 7;
bool mov = false;

//data read from joystick pins
int x = 0;
int y = 0;
int SW = 0;

// X and Y coords for entities
int playerx = 50;
int playery = 50;

long coinx;
long coiny;

//game variables
int score = 0;

//defining the tft class
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

//useful text function
void output(char *text, int x, int y, uint16_t color, bool wrap = 0){
  tft.setCursor(x, y);
  tft.setTextColor(color);
  tft.setTextWrap(wrap);
  tft.print(text);
}

//there is probably a better way to do this but im too lazy to find it
void num_output(int text, int x, int y, uint16_t color, bool wrap = 0){
  tft.setCursor(x, y);
  tft.setTextColor(color);
  tft.setTextWrap(wrap);
  tft.print(text);
}

//clears screen
void clear() {
  tft.fillScreen(BLACK);
}

//setup (lcd init & startup screen)
void setup() {
  Serial.begin(9600);
  pinMode(SWPin,INPUT_PULLUP);
  tft.initR(INITR_GREENTAB);

  long coinx = random(20, 100);
  long coiny = random(20, 100);

  clear();
  output("RAMBUTAN", 40, 60, RED);
  delay(1000);
  clear();
  tft.fillRect(playerx, playery, 5, 5, WHITE);
  tft.fillCircle(coinx, coiny, 5, YELLOW);
}

void loop() {
  //reads data from joystick pins every single tick
  int VRx = analogRead(VRxPin);
  int VRy = analogRead(VRyPin);
  int SW = digitalRead(SWPin);

  //converts joystick pin data into directions
  if (VRx > 250 && VRx < 750 && VRy > 250 && VRy < 750) {
    // middle
  } else if (VRx > 511.5 && VRy < 750 && VRy > 240) {
    // right
    playery -= 5;
    mov = true;
  } else if (VRx < 511.5 && VRy < 750 && VRy > 240) {
    // left
    playery += 5;
    mov = true;
  } else if (VRy > 511.5 && VRx < 750 && VRx > 240) {
    // up
    playerx += 5;
    mov = true;
  } else if (VRy < 511.5 && VRx < 750 && VRx > 240) {
    // down
    playerx -= 5;
    mov = true;
  } else {
    mov = false;
  }

  if (mov == true) {
    clear();
    tft.fillRect(playerx, playery, 5, 5, WHITE);
    num_output(score, 10, 10, WHITE);
    tft.fillCircle(coinx, coiny, 5, YELLOW);
    mov = false;
  }
  delay(100);
}

Have you read the documentation to the Arduino random() function? Especially the section "Notes and Warnings"? A microcontroller cannot easily generate random numbers without a good source of randomness.

Most pseudo-random libraries (like the one in python) at least seems to be random, so I thought I could just use this :/

The random libraries on a PC will also pull randomness/entropy from some sure. On a PC there are many factors, which could be used for that. On a microcontroller the resources are much more limited. Here you need to dedicate an analog input for that (which might or might not be acceptable for you).

Does this answer your question? Getting a truly random number in Arduino

You are correct, random() isn't random - it's pseudo random. It returns successive results from a mathematical formula which, to all intents and purposes, is random. It's also predictable, as you have seen.
The formula has a starting value, called the seed, which you can choose your self. Changing that seed gives you a different sequence of random-like numbers.
So the trick is to set the seed to something that is truly random. One common source of randomness, or entropy, is an unconnected ADC input:
randomSeed(analogRead(A3));

You can read more about the randomSeed() function here.

This seems to work better, but when I move, it automatically goes to the corner like it did before... I'm not sure what's happening.

@jort57 You aren't calling randomSeed() over and over again are you? You only want to call it once in setup().

randomSeed(analogRead(A3)); is better than nothing but, in my experience, it has very little entropy (a couple of bits or so). Unless of course you connect a hardware entropy source to A3.

A trick that has worked for many of my projects requiring randomness is to include some sort of a "start" trigger. This could be a network communication response, a push button (e.g, a "go" button), or some other event that will occur at a random point in time. After observing the "start" trigger, call millis() and use the return value as the random seed. You could probably also use micros() in place of millis() if the start trigger may occur quickly (e.g. a local network communication).

.... or perform analogRead() a few times in sequence and join the last few bits of each call.

a floating pin will usually hover within a few levels read after read, so more of the same isn't really a big help with randomness. Having a few set patterns is better than 1, but not much. In contrast to @Majenko advice, calling randomSeed() at additional indeterminate points (ex if(analogRead(A0)%2)) throughout the sketch would remedy the "Hey I know this pattern" problem that a PRNG poses. Only calling it once means that there could be 4 or 8 or 13 or so persistent and predictable patterns, re-seeding makes it more like a CSPRNG where past result don't imply future results.

If you have input from a human, network or other non-MCU source, reseed with micros() when said input happens, like a button press of wifi connection establishment; since those happen at unpredictable times, they are ideal for PRNG seeding.

As an alternative to Majenko's answer, this is how I generate random n-bit-numbers: for each of the n bits I read the chip temperature (which is pretty noisy), take the least significant bit of the reading and assign it to the corresponding bit in the number. The results are sufficiently random for my purpose at least.


text:
Is it possible for the Arduino's digital pin mode to flip from OUTPUT to INPUT unexpectedly?
I have an Arduino project (data logger intended to sample 100 samples per second for months) with firmware that is too long to post. It mostly works as supposed to, but I have a confusing issue I can't figure out: rarely, the indicator LEDs (driven by digital pins) stop working. By rarely, I mean if I run 20 devices for two weeks, maybe one will develop the issue, so it's very hard to test empirically but it's frequent enough that it matters. I know it's not a hardware problem because they start again after a reset. The device apparently continues working fine apart from the LED issue when this happens.
I have three hypotheses:

There's a logic problem in my firmware code. I'm skeptical because the relevant block of code is pretty simple.
A memory overflow or some similar problem causes the program to fail at this one particular task but not others. I'm a little skeptical because the device reports free stack in the metadata every second and it's always over 40 bytes; I may be misunderstanding memory use though.
Somehow, the digital pin (4) driving the LED gets flipped from OUTPUT to INPUT. There's definitely no pinMode(4, INPUT) command anywhere in my code though, so if this is happening it's not my code doing it.

Let's suppose it isn't #1. Considering #2: is it likely that a weird memory issue is causing a very specific failure while not affecting core functions of the device?
Considering #3, is there anyway the register setting a pin to INPUT or OUTPUT could be flipped unexpectedly? It sounds crazy to me but I want to rule it out.
The platform is similar to the Arduino Pro (3.3V, 8 MHz, ATMEGA328p) and I'm running the current IDE version (1.8.13). Thanks for any help.

of course pins can flip unexpectedly ... you just have to make sure that your program does only expected actions

Is the LED going off or going to Input? You normally see that because if a LED is attached to an input pin, it is glimming instead of on or off (because there's some current going out of an input pin).

The LED stops blinking, although it seems very unlikely to me that the relevant code stops running. The pin getting set to INPUT could explain how the LED could stop blinking visibly while the code is still running as normal. The LED's series resistor is only 470 ohms which is much less than the pin's high-impedance state, so even if it did supply some current it probably wouldn't be enough for short-blink visibility in daylight.

Concerning 2.: it's not trivial to get information about free ram on a non-multitasking system, because it will only give you the free ram at the point at which you call the corresponding "get_free_ram()" function. If you call this function in a high scope (e.g. in loop()) it will return something completely different than when you call it in deeper scope, where local variables, return addresses, etc. are also stored in ram. If you don't use dynamic memory allocation, it will always give the same result, but that probably is not the "high-water-mark" of ram usage.

The fact that it is possible to set them incorrectly is why, in some projects where I'm concerned about this, I'll add a small series resistance to an inbound signal.  Should the pin become OUTPUT and driven in an opposing direction to the signal, the resistance serves to prevent a short through both devices.  The possibility is always there, whether you have an outright bug, or instability, or flash corruption.
With pinMode the opportunity to accidentally set your port to the wrong direction is maybe a bit worse than for code that directly manipulates the data direction register.  pinMode calls typically don't get inlined, because pinMode on the Arduino is a fairly complicated function at runtime for what it actually does.  So, there's this generic code that can be jumped to that will set various ports to either direction, as opposed to smaller chunks of code that contain instructions that set specific ports to specific settings.
INPUT roughly takes your digital pin out of the circuit.  And INPUT_PULLUP sort of does that, with the exception that internal to the AVR there's going to be 20k - 50k of resistance going to "5V".  Knowing that, you can test your hypothesis three.  When you find your project in the state where the LED isn't lit, take some some resistance (say 1K) and use it to pull the pin toward "5V".  Then pull it to GND.  Watch the voltage at the pin with a meter.  Based on what you have attached and what you see for a voltage, you can determine whether it has entered the INPUT or INPUT_PULLUP state.  You'll also be able to see if it's just being driven to whatever state you're calling "not working" ("off" I'm guessing).
You can take all the guess work out of what voltages to see in each scenario if you upload a sketch that sets the pin in question to the INPUT, INPUT_PULLUP, OUTPUT/HIGH, and OUTPUT/LOW states and measure the voltage at the pin when you pull it to each rail with your resistor.  Later you can consult the table you've built to see what has happened.
There's only so much to say about this, particularly your first two ideas, without seeing the code and other details.  Just that sometimes otherwise simple code has bugs in it.  In an ATMega328P project, 40 bytes is not a lot of free space at all.  To give you an idea what sort of problem this can trigger: The Arduino implementation of new that's in the 1.8.3 core will happily blow away your register file and whatever else it can get to after that, if the underlying malloc reports not enough memory.  Basically new continues to initialize the object it thinks was allocated even when the pointed returned is nullptr.  The __malloc_margin is 128 in the 1.8.3.  So if you try to malloc with 40 bytes distance between the stack and heap, you will trash your program state, perhaps even setting a data direction register in the process.


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

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

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

BluetoothSerial SerialBT;
int speedsend = 9600;

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

void loop() {

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

}

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

This might help you

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

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

Device transmits HEX values like in table

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

@chrisl I have full edited the question now

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

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

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

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

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

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

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

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

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

I am receiving value 2 gets as 32 to int i

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

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

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

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

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


text:
Switching time of a multiple input switch
I basically have two switches
Both switches will be pressed simultaneously in different order
I want to know which switch was pressed first

Please include in your question a description of what exactly is your problem with doing that. You can edit your question (this information belongs into the question, not in the comments)

simultaneously and different order are mutually exclusive ... you either press them at the same time, or you press them sequentially ... you can't do both

Use External Interrupts is the short answer.
Longer version:
You probably want to make a buzzer system like what in family feud game show.
I assume you are using Arduino UNO/MEGA and or having experience with programming.
1/ Use INT0 and INT1 for button 1 and button 2.
When an interrupt is raised, the mcu jumps to a specific address to run the interrupt service routine. INT0 and INT1 vectors are pointing to two distinctive addresses to run 2 different functions. For this, mcu takes the least amount of CPU clock to capture which button press first.
2/ Use PCINT vectors which is PinChange Interrupt. But personally I prefer to call it PortChange Interrupt.
There are 3 PinChange interrupt vectors PCINT0, PCINT1, PCINT2 to run 3 distinctive service routines. But this kind of interrupt doesn't know which pin is changed.
So inside the interrupt service routine, you have to check for that specific pin. You can do this the arduino way digitalRead(button1) or capture the whole port register, ie. PORTB, PORTC or PORTD.
In a nutshell, PORTB holds values of digital pin 8 to 13 while port D hold values of digital pin 0 to 7 and PORC for A0 to A7.
You can shave off some CPU clocks (3-10 clocks probably) by put 2 buttons different PCINT vectors. So that each button still triggers distinctive function.
In 3 cpu clocks (or around 180 ns) a lot of things may change and you may not get the correct result.
3/ Polling in main loop()
This is the worst way to do it. Nevertheless, it still gives good result.
if (digitalRead(button1)==LOW) {
// do something
}

if (digitalRead(button2)==LOW) {
// do something else
}

The simple version: check continuously for the state of the digital inputs the switches are connected to. When one is HIGH that is the switched pressed first.
The intermediate version: check the 'blink without delay' example to make sure you don't get too many false positives.
The advanced version: use interrupts when one of the two switches gets 'HIGH', using the 'blink without delay' to prevent false positives.

If you want to know if both are pressed at the same time, but one is pressed first, use variables to keep track on it.
like two variables:
bool button1Pressed = false;
bool button2Pressed = false;

Set them accordingly (depending on which of the 3 possibilities you use). Then when you know a button is changed, you can easily check the booleans to know which was already pressed.
Or you can use an enum that combines the state of both:
enum EState { ALL_OFF, BUTTON_1_PRESSED, BUTTON_2_PRESSED, BOTH_BUTTONS_PRESSED };

EState buttonState;


text:
Portenta pinouts for ADC
I wanted to have your comments about one of my questions.
I am currently working on the sketch for the Arduino Portenta H7. However, due to my poor electrical background, I would like to ask your opinion about the pinouts.   Below you can find the pinout diagram from the document page 1 available at the below link.
https://content.arduino.cc/assets/Pinout-PortentaH7_latest.pdf
I am a bit confused about the analog pins. As the diagram and color-coding show ADC A0 ( available on the high-density connector)  and analog pin A0 both separately.   What can be the difference between them ? or maybe I am interpreting wrong.
Because, on an ordinary Arduino board ( as far as I found), we have the Analog pins which are used for the ADC too. However, here in the Portenta pinout diagram, we have ADC A0 and analog A0 separate?
I thank you for your time and opinion.

it is the same pin of the MCU

Hello Juraj. Could you please elaborate a bit more, please

MCU stands for MicroController Unit. here it is the STM32H747XIH chip

The "high density" connectors expose every pin of the MCU. The pins around the edge of the board duplicate just the immediately useful ones.
Every pin that is on the edge of the board is also on the high density connectors somewhere.
Why have the pin on both connectors? Simple: if you want to use it in a breadboard or with jumper wires then you want the useful pins on the edge. If you want to use a plug-in board then you don't want to have to connect to both the high density connectors and the breadboard connectors, that would just be really awkward (since both have completely different height profiles). So everything is on the high density connectors for plug-in boards, and the useful ones are also on the breadboard headers.
A0 is the Arduino name for the pin. ADC is the function of the pin. The A of ADC stands for Analog. It's a pin that Converts Analog to Digital. It's an Analog to Digital Conversion pin - ADC.

It is just the one pin that they marked two times as A0. I think they just wanted to make clear it's the same pin, maybe that people don't get confused, but in my opinion it's just more confusing.

Hello. I have added a new figure in my question. The pin marked ADC A0 is a separate pin A marked as high-density connector pin 73 of J2. So I guess probably both A0 and ADC A0 are different pins?

@BasitAli I think in the lower picture ADC A0 is used to describe that the pin is both of it as I can't see any other A0 description.


text:
I have a problem trying to limit motor speed to a certain RPM using a MOSFET trigger switch module

I am using the potentiometer to control the duty cycle of a PWM signal to the MOSFET trigger switch module, thus controlling the motor speed.
In my code, I have used the map function to utilize the full resolution of my potentiometer (0 - 1023) and thus create a proportional PWM signal using analogWrite function (0 - 255).
However, in my setup I want to limit the speed of the motor from going beyond a MAX_RPM value, despite any further increase in analog value input from the potentiometer.
This means I have to continously check the RPM value (the RPM code works fine, so I will not include it).
If the motor speed hits the MAX_RPM value, any further potentiometer input should be ignored. To achieve this, I figured I need to hold the analogWrite function value constant thus holding the speed constant.
In the event that I turn the potentiometer in the reverse direction, this should decrease the PWM value thus also decreasing the speed.
I have written the code to achieve the process described above to no avail i.e., increasing potentiometer input causes the speed to go beyond the MAX_RPM value which is undesired.
In this project, I am developing a rev limiter of sorts.
Please help me figure out the problem in my code.
#define MAX_RPM 500
    #define MAX_RPM_PWM_MAPPED_VALUE 15

    //In this case, I first ran the motor while monitoring the speed and the potentiometer value
    //While doing this, I noted the potentiometer value at which the MAX_RPM is obtained
    //I then defined this potentiometer value as MAX_RPM_PWM_MAPPED_VALUE
    //With MAX_RPM_PWM_MAPPED_VALUE, I would directly limit the value written to the analogWrite function
    //

    MOSFETMODULE = 4;
    potentiometer = AO;

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

    void loop()
    {
        val = analogRead(potentiometer);  //Read potentiometer value - represents accelerator input
        mappedValue = map(val, 0, 1023, 0, 255); //Map the 10 bit value to 8 bit equivalent

        if(RPM >= MAX_RPM)
        {
            analogWrite(MOSFETMODULE, MAX_RPM_PWM_MAPPED_VALUE);
        }
            else
            {
              mappedValue = constrain(mappedValue, 0, MAX_RPM_PWM_MAPPED_VALUE);
              analogWrite(MOSFETMODULE, mappedValue); //Output a PWM signal to the MOSFET trigger module
            }
    }

Note the the actual RPM doesn't just depend on the PWM duty cycle, but also the load on the motor. Just like pressing the gas pedal on a car. If you don't change the gas pedal position, but you suddenly go up a hill, your speed will decrease.

Thanks, I totally understand the loading scenario. In fact, my setup aims to mimic a car operation - throttle position and engine speed. I aim to create a device that restricts the motor speed from exceeding various max speed levels depending on the load condition.

Try using analogWrite(MOSFETMODULE, 0); when the RPM exceeds the maximum value. Of maybe use 1 instead of 0. That way the code will throttle way back, if the RPM ever exceeds it's maximum. If will return to using the pot value, when the RPM goes back down. It may result in some weird oscillations, but cars make some weird noises too, when they are at their max RPM, so +1 for realism.

To clarify why your code isn't working. Currently, it's mapping the value of the pot (0-1023) to the 0-15 PWM duty cycle. But when the RPM exceeds it's limit you set the PWM to 15, which is the same value you get when you turn the pot to it's maximum. You want to turn down the PWM duty cycle, instead of setting it to it's max. (Imagine going down hill in a car. You don't press the throttle, but due to going downhill the RPM exceeds 500. Now your car will set it's throttle to full. Oops ;-p )

I agree with both responses, they totally make sense. Lemme try to implement them in my code. This problem makes me think deeply about how electronic throttles work in modern cards. Thank you.

Your problem is that you don't know what ADC value maps to the maximum RPM. If you did you wouldn't need to know the RPM.
What you have here is a "feedback loop", and what you need is some method of using the detected RPM to control the speed of the motor.
You need to decouple the potentiometer from the analogWrite completely - the potentiometer should be setting the desired RPM, not the value being sent to set the RPM.
So if you want an RPM range from, say, 0 to 100RPM you can map() the analogRead() to the values 0-100. Then you can examine the actual RPM and adjust the value you send to the PWM accordingly - if the motor is too fast then slow it down. If it's too slow then speed it up.
There's a special method that is used for this: PID. And there's a library that does it for you too:

https://playground.arduino.cc/Code/PIDLibrary/

The potentiometer provides the "set point", the RPM detection provides the "input", and the PID library gives you the "output" to feed to the analogWrite().  You need to then provide the special magic "tuning" parameters to give the best control over your motor.

Thank you for the detailed response. In this setup, I am aiming to mimic a car driving scenario, whereby the potentiometer is the gas pedal, while the MOSFET reps the fuel injector, and the motor speed reps engine speed. In essence, I wanted a setup that would restrict the motor/engine speed from exceeding a certain point i.e., the MAX RPM, regardless of an increasing input rather than holding the speed constant. As the pot is reversed/pedal released, I also want the motor/engine speed to drop appropriately. I just want to set an engine speed limit. A PID holds a constant speed value instead.

am trying to develop a rev limiter of sorts

@Curiousone maybe something like if (rpm>max) analogWrite(mosfet, PID_output); else analogWrite(mosfet, analogRead(pot_pin)>>2) could work