text:
Guru meditation error load prohibited, esp32s. While using Fastled
I am encountering a Guru meditation error, Load prohibited on my current sketch for the esp32s.
Here is the code:
#include <FastLED.h>

#define NUM_LEDS 120
#define LED_PIN 3
CRGB leds[NUM_LEDS];

int H1[12][10] = {
  {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
  {10, 11, 12, 13, 14, 15, 16, 17, 18, 19},
  {20, 21, 22, 23, 24, 25, 26, 27, 28, 29},
  {30, 31, 32, 33, 34, 35, 36, 37, 38, 39},
  {40, 41, 42, 43, 44, 45, 46, 47, 48, 49},
  {50, 51, 52, 53, 54, 55, 56, 57, 58, 59},
  {60, 61, 62, 63, 64, 65, 66, 67, 68, 69},
  {70, 71, 72, 73, 74, 75, 76, 77, 78, 79},
  {80, 81, 82, 83, 84, 85, 86, 87, 88, 89},
  {90, 91, 92, 93, 94, 95, 96, 97, 98, 99},
  {100, 101, 102, 103, 104, 105, 106, 107, 108, 109},
  {110, 111, 112, 113, 114, 115, 116, 117, 118, 119}

};

int connections[7][6] = { // dont forget to change 7 to the number of hubs
  {2,3,4,5,6,7},
  {1,7,3,0,0,0},
  {1,2,4,0,0,0},
  {1,3,5,0,0,0},
  {1,4,6,0,0,0},
  {1,5,7,0,0,0},
  {1,2,6,0,0,0}
};

int const life = 3;
int numHubs = 7;

void setup() {
}

void loop() {
  path_taker(path_picker(numHubs, connections), H1);
  delay(500);
}

int* path_picker(int numHubs,int connections[7][6]){ // dont forget to change 7 to the number of hubs!
  int hub = random(1,numHubs)-1;
  int i = 1;
  int path[life];
  int a = 0;
  path[0] = hub;

  while (i <= life){
    a = connections[hub][random(0,6)];
    if (a != 0){
      path[i] = a;
      hub = a;

      i = i+1;
    }

  }
  return path;
}

void path_taker(int path[life], int H1[12][10]){
    int ini = 0;
    int fin = 0;
    int rod[10];
    for (int i = 0; i < sizeof(path) - 1; i++){
      ini = path[i];
      fin = path[i+1];
      switch (ini){
        case 1:
        switch (fin){
          case 2:
          lightup(arrayBuilder(0, H1, false));
          break;

          case 3:
          lightup(arrayBuilder(4, H1, false));
          break;

          case 4:
          lightup(arrayBuilder(3, H1, true));
          break;

          case 5:
          lightup(arrayBuilder(5, H1, false));
          break;

          case 6:
          lightup(arrayBuilder(8, H1, true));
          break;

          case 7:
          lightup(arrayBuilder(9, H1, false));
          break;
        }
        break;

        case 2:
        switch (fin){
          case 1:
          lightup(arrayBuilder(0, H1, true));
          break;

          case 3:
          lightup(arrayBuilder(1, H1, false));
          break;

          case 7:
          lightup(arrayBuilder(11, H1, true));
          break;
        }
        break;

        case 3:
        switch (fin){
          case 1:
          lightup(arrayBuilder(4, H1, true));
          break;

          case 2:
          lightup(arrayBuilder(1, H1, true));
          break;

          case 4:
          lightup(arrayBuilder(2, H1, false));
          break;
        }
        break;

        case 4:
        switch (fin){
          case 1:
          lightup(arrayBuilder(3, H1, false));
          break;

          case 3:
          lightup(arrayBuilder(2, H1, true));
          break;

          case 5:
          lightup(arrayBuilder(6, H1, true));
          break;
        }
        break;

        case 5:
        switch (fin){
          case 1:
          lightup(arrayBuilder(5, H1, true));
          break;

          case 4:
          lightup(arrayBuilder(6, H1, false));
          break;

          case 6:
          lightup(arrayBuilder(7, H1, false));
          break;
        }
        break;

        case 6:
        switch (fin){
          case 1:
          lightup(arrayBuilder(8, H1, false));
          break;

          case 5:
          lightup(arrayBuilder(7, H1, true));
          break;

          case 7:
          lightup(arrayBuilder(10, H1, true));
          break;
        }
        break;

        case 7:
        switch (fin){
          case 1:
          lightup(arrayBuilder(9, H1, true));
          break;

          case 2:
          lightup(arrayBuilder(11, H1, false));
          break;

          case 6:
          lightup(arrayBuilder(10, H1, false));
          break;
        }
        break;
      }
    }
  }

int* arrayBuilder(int row, int hexigon[12][10], bool reverse){
  int rod[10];
  if (reverse){
    for (int i=9; i>=0;i--){
      rod[i] = hexigon[row][i];
    }
  }else{
    for (int i=0; i<10;i++){
      rod[i] = hexigon[row][i];
    }
  }
  return rod;
}

void lightup(int rod[10]){
  int i = 0;
  while (i<10){
    EVERY_N_MILLISECONDS(50){
      leds[rod[i]] = leds[i] = CHSV(255, 255, 255);
      fadeToBlackBy( leds, NUM_LEDS, 10);
    }
  }

  FastLED.show();
}

Here is the decoded exception from Exception Decoder:
 EXCVADDR: 0x00000000 Decoding stack results 0x400d0cc7:
path_taker(int*, int (*) [10]) at C:\Users\****\Documents\Arduino\Wall_Art_MKI/Wall_Art_MKI.ino line 75

0x400d0d3e: loop() at C:\Users\****\Documents\Arduino\Wall_Art_MKI/Wall_Art_MKI.ino line 44

0x400d1315: loopTask(void*) at C:\Users\*****\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.6\cores\esp32\main.cpp line 23

0x40085d81: vPortTaskWrapper at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/port.c line 143

I posted this on Reddit, and a user suggested that the error was occuring on line 201. The issue being that I am attempting to return a pointer to a local variable within the function, arrayBuilder.
I have been doing research on the topic, but I still can't figure out how to resolve the error.
I would greatly appreciate any advice!

Instead of trying to return a pointer to a local variable (which is always doomed to fail, since you end up with a pointer to rubbish) you should create your array outside the function and pass a pointer to it as a parameter, then fill that array through the pointer:
void arrayBuilder(int row, int hexigon[12][10], bool reverse, int *rod){
  if (reverse){
    for (int i=9; i>=0;i--){
      rod[i] = hexigon[row][i];
    }
  }else{
    for (int i=0; i<10;i++){
      rod[i] = hexigon[row][i];
    }
  }
}

Then...
int rod[10];
arrayBuilder(rownum, myhex, false, rod);


text:
How to prevent replacing of the value for a key in Preferences?
#include <Preferences.h>

Preferences preferences;

const char* roomname_long = "String 1";
const char* roomname_short = "String2";
const char* roomname_long_test = "String 3";
String roomname;

void setup() {
  Serial.begin(115200);
  preferences.begin("app",false);

  preferences.begin("credentials", false);
  preferences.putString("roomname_long", roomname_long);
  preferences.putString("roomname_short", roomname_short);
  preferences.putString("roomname_long", roomname_long_test);

  roomname = preferences.getString("roomname_long", "");

  Serial.println(roomname_long);
  Serial.println(roomname_short);
  Serial.println(roomname);

  preferences.end();
}

void loop() {

}

I try to save some data on my esp32 it works actually but if I try to save another variable with the same key it writes over the String before how can I interrupt that?
on the Serial Monitor I got this:
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1324
ho 0 tail 12 room 4
load:0x40078000,len:13508
load:0x40080400,len:3604
entry 0x400805f0
String 1
String 2
String 3

I want that if I put another variable in "roomname_long" key it must not be overwritten.
So it should be stay on String 1

You can use isKey to test if the preferences key is already set.
preferences.putString("roomname_long", roomname_long);
preferences.putString("roomname_short", roomname_short);
if (!preferences.isKey("roomname_long")) {
  preferences.putString("roomname_long", roomname_long_test);
}

source: Stack Exchange

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

sort: votes


text:
Please help me navigate the stepper motor object definition in the documentation
I am trying to use the stepper library and the stepper object is documented like this

This function creates a new instance of the Stepper class that represents a particular stepper motor attached to your Arduino board.
Use it at the top of your sketch, above setup() and loop(). The number of parameters depends on how you’ve wired your motor, either using two or four pins of the Arduino board.
Syntax
Stepper(steps, pin1, pin2)
Stepper(steps, pin1, pin2, pin3, pin4)
Parameters
steps: the number of steps in one revolution of your motor.
If your motor gives the number of degrees per step, divide that number into 360 to get the number of steps (e.g. 360 / 3.6 gives 100 steps).
pin1, pin2: two pins that are attached to the motor.
pin3, pin4: the last two pins attached to the motor, if it’s connected to four pins.
Returns
A new instance of the Stepper motor class.
Example
Stepper myStepper = Stepper(100, 5, 6);
"""

The problem is that "two pins" and "last two pins" do not tell me anything about which pins go where on the motor driver. I am using a DM320T stepper driver
Can anybody tell me what "pin1 pin2 pin3 pin4" actually correspond to?

The standard Stepper library does not support stepper drivers, which only have a step (in this case labels "PUL" for pulse) and a direction pin (labeled "DIR"). So you need to use a different library. I suggest using the Accelstepper library, which is also more capable than the standard Stepper library. Then you can define the AccelStepper object like this:
AccelStepper stepper(AccelStepper::DRIVER, STEPPER_DIR_PIN, STEPPER_STEP_PIN);

About the connections: The shown driver is meant to be connected with twisted wire pairs, so in this case one wire for signal and the other for ground or 5V. Look at the documentation for your stepper driver. There you should be able to find a wiring diagram.

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


text:
Migrating an Arduino Project to Beetle Bluno
So I have a working project with Arduino Uno. I now want to migrate it to the Beetle Bluno. I tried running the code on the Beetle and it does work. I cannot seem to get the Bluetooth to work though. The code is below:
#include <Bounce2.h>
#include <SoftwareSerial.h>
//#include <Wire.h>
//SoftwareSerial bluetooth_port(10, 11);

// Connect each button with one connection
// to GND and the other to a digital pin.
const byte buttonPinBLE1 = 2;
const byte buttonPinBLE2 = 3;

class Button{

  private:

    byte m_buttonPin;
    byte m_counter = 0;
    unsigned long m_buttonPressTimeout;
    unsigned long m_previousMillis;

  public:

    Button(byte buttonPin):
      m_buttonPin(buttonPin),
      m_counter(0),
      m_buttonPressTimeout(1500), // Button press timeout in ms.
      m_previousMillis(0){}

    void Update(){
      if(m_counter > 0 && millis() - m_previousMillis >= m_buttonPressTimeout)
      {
        //Serial.print("Count from Update() just before it's reset to 0 = ");
        Serial.println(GetCounter());
        m_counter = 0;
      }
    }

    void IncrementCounter(){
      m_counter++;
      if(m_counter > 4){m_counter = 4;}
      if(m_counter == 1)
      {
        m_previousMillis = millis();
      }
    }

    friend void IncrementCounter(Button&);

    void IncrementCounter(Button&){
      IncrementCounter();
    }

    byte GetCounter(){
      return m_counter;
    }

};

Bounce buttonOneDebouncer = Bounce();
Bounce buttonTwoDebouncer = Bounce();
Button ButtonOne(buttonPinBLE1);
Button ButtonTwo(buttonPinBLE2);

void setup(){
  //Serial.begin(9600);
  Serial.begin(115200);
  pinMode(buttonPinBLE1, INPUT_PULLUP);
  pinMode(buttonPinBLE2, INPUT_PULLUP);
  buttonOneDebouncer.attach(buttonPinBLE1);
  buttonTwoDebouncer.attach(buttonPinBLE2);
  buttonOneDebouncer.interval(25);
  buttonTwoDebouncer.interval(25);
}

void loop(){

  // Call the Update function as fast as possible.
  ButtonOne.Update();
  ButtonTwo.Update();

  // Button one pressed.
  if(buttonOneDebouncer.update()){
    if(buttonOneDebouncer.fell()){
      if(digitalRead(buttonPinBLE2) == 0){
        ButtonOne.IncrementCounter();
      }
    }
  }

  // Button two pressed.
  if(buttonTwoDebouncer.update()){
    if(buttonTwoDebouncer.fell()){
      if(digitalRead(buttonPinBLE1) == 0){
        ButtonOne.IncrementCounter(ButtonTwo);
      }
    }
  }
  if(digitalRead(buttonPinBLE1) == 0 && (digitalRead(buttonPinBLE2) == 0))
  {
  Serial.println("9");
  }

}

Does anyone know how I can get the device to communicate with my computer via Bluetooth? I have no experience with the Beetle and I cannot seem to find much help online.

Comments are not for extended discussion; this conversation has been moved to chat.

@VE7JRO Hello. You helped me with the single tap, double tap question (https://arduino.stackexchange.com/questions/69897/detecting-how-many-button-pressessingle-tap-double-tap-etc-with-two-simultane). Thank you so much for that once more. However, it isn't accurate and sometimes if i press the buttons once, it outputs a 2, sometimes it outputs a 4 when i press it twice. Do you know how I can fix this issue?

The original code I provided in the linked Q+A worked perfectly on a Arduino Uno. The sketch you are using in this question is different. I do not have a Beetle Bluno to test with, so I'm sorry, but I can't help you. If I can't test the sketch on the "same" hardware, then I'm just guessing, not answering.

@VE7JRO the code I am using is on an Arduino Uno...it isn't working accurately for some reason on my side. I haven't started using the Beetle as yet so still testing on the Arduino Uno


text:
Triggering a soft reset (Arduino Leonardo)
I want to trigger a soft reset on my Arduino Leonardo, and after some searching settled on using the watchdog timer, as it seemed to be the easiest and cleanest way to do it.
However, I don't think it works as it should. It seems to work fine on the following example:
#include <avr/wdt.h>

int outputPin = LED_BUILTIN;

void setup() {
  MCUSR = 0;
  wdt_disable();
  pinMode(outputPin, OUTPUT);
  digitalWrite(outputPin, HIGH);
  delay(500);
  digitalWrite(outputPin, LOW);
  delay(500);
  digitalWrite(outputPin, HIGH);
  delay(500);
  digitalWrite(outputPin, LOW);
  delay(1000);
}

void loop() {
  wdt_enable(WDTO_15MS);
  while (true) {}
}

The LED blinks continuously,.
But for the following example:
#include <avr/wdt.h>

void setup() {
  MCUSR = 0;
  wdt_disable();
  Serial.begin(9600);
  while (!Serial);
  Serial.println("Hello");
}

void loop() {
  wdt_enable(WDTO_15MS);
  while (true) {}
}

"Hello" only gets printed once (where I would expect it to arrive continuously).
I tried increasing the watchdog timeout to 2 seconds, but that didn't solve the issue.

try for a test a longer time, for example WDTO_2S. some bootloaders don't reset the wdt flag and then the next reset is triggered before the chip enters your setup().

@Juraj changing WDTO_15MS to WDTO_2S in the above example only causes the final state (L on, RX blinking) to set in 2 seconds later, unfortunately it didn't solve the problem.

you test with a sketch without Serial like the sketch in the Question?

Hint: You could define a function to the reset-vector, e.g. void (*RESET)() = NULL; and then call the function when wanted, e.g. RESET();. Please note that all hardware registers are not reset. The sketch setup should not assume a hardware register state.

@Juraj I edited the question. I have since discovered that I was missing pinMode from my original example, and that solved that specific issue. However, for the (now added) Serial example it still doesn't work.

@MikaelPatel do you mean something like this? https://pastebin.com/raw/0UNf3mik This still only prints "Hello" once.

Try the blink led instead. Set registers correctly in the setup.

Oh hold on, I think the problem might just be that after every reset the serial monitor disconnects (even though it doesn't get greyed out), and that's why I can't see the following "Hello"s. I'll investigate a bit further.

Serial (USB) will disconnect and the USB connection to the host is dropped. You will need a much more advanced detect and reconnect on the host :)

Yeah, it looks like that was the only issue. Thanks for the help MikaelPatel and Juraj!

one more thing: the  while (!Serial); stops the sketch if USB connection is not open

So it turns out my code was working correctly, the watchdog performed the reset as it should, the problem was only that I needed to relaunch the serial monitor after each reset.


text:
ESP8266MOD does not respond to my Uno (Custom board) AT+RST command
This is my very first project with a Uno board and ESP module. I have some experience with 8051 uP. I'd like some guidance in addressing my issue.
Objective:
To connect ESP8266MOD to my wifi network and send a TCP message to my HOME_SERVER whenever required.
Hardware Module:
UNO (Induino R5 Arduino R3 USB Clone Board) --> level shifter  --> ESP8266MOD
As a first step, I am trying to send AT+RST command from the Uno to the connected ESP. But there is no response from the ESP. However, I am able to notice a LED blink on the ESP, whenever there is TXD operation in my Uno.
Hardware Connection:
UNO - Uses USB Power supply from laptop
ESP8266MOD- Uses 3 1.5V AA Batteries

                 ||
    UNO PINS       TXD      RXD     5V GND
                    ||      ||      ||
    LEVELSHIFTER     >>RXI   <<TXO  HV,GND
                        ||      ||
                    RXO<<    TXI>>  LV,GND
                    ||      ||      ||
    ESP8266MOD      RXD     TXD     3.3V,GND

ESP8266MOD Settings:
    CH_PD ->> 3.3V
    GPIO2 ->> 3.3V
    GPIO0 ->> GND
    GPIO15->> GND

Uno Code:
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
  delay(3000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  delay(3000);
  ESP8266.println("AT+RST");
  delay(30);
  String response = "";
  while(ESP8266.available()) {
    char c = ESP8266.read();
    response+=c;
  }
  if(response != "") {
    Serial.println(response);
  } else {
    Serial.println("Empty\r\n");
  }
}

Output Video: Output video view
  -->

That yellow PCB, is it possible that it already have the level shift on it ?

@AndreCourchesne No, The RX and TX are directly taken from pinout. I doubt that

Then maybe you have rx connected to rx (same for tx). I would use a continuity tester to make sure of the wirring.

@AndreCourchesne    I interchanged pin from in ESP end already. still no luck. However, with existing connection when there is TX from UNO, I am able to see LED  blink in ESP.

Then the next step to me would be oscilloscope or logic analyser.

@AndreCourchesne : What about my connections. Is it correct ??

Very hard to tell, not sure I understand the way you wrote it. If you could make a drawing would be better. Try using Fritzing to do it.

Couple of ideas... Are all of your GND tied together ? They need to.
What powered your ESP8266 3.3v ? You mention 3x AA batteries, but that totals 4.5v, not 3.3v...

@AndreCourchesne :: Started from step 0 now.. Tried loopback in UNO it worked. But, loopback from level shifter not working. (https://i.sstatic.net/qACko.jpg)

good move. I don't know that level shifter, you got some documentation or the schematic of it ?

@AndreCourchesne : http://www.amazon.in/Generic-Channel-Converter-Bi-Directional-Module/dp/B011ECG2MM?tag=googinhydr18418-21&tag=googinkenshoo-21&ascsubtag=d2f6ed02-1c9d-4c8e-8474-e94a6cb1c3f1 -- This is product info..IS it the right one to use here. my intention to use it here is for converting 232 (5v) to 3.3v (ESP)

Found the original maker of that level shifter (https://www.eprolabs.com/product/logic-level-converter/)
So your diagram looks good as far as how I interpret it. Where do you take your 3.3v from ? And the converter has 2 converter slots maybe one is detective, have you tried the other one ?

@AndreCourchesne : 3.3 V is separate and given from ESP module. I physically checked voltage in multi meter and seems normal

If it is a new ESP module, your problem is quite likely a baud rate mismatch, since you are seeing an LED response but getting no reply.
The last batch of ESP-01s I received defaulted to 115200 baud, but that is too fast for SoftwareSerial (SS). You'll need to change it to 9600. My answer to a related question describes one way to change it.
You could also change it with SS. You'd have to start off SS at 115200 baud, which will usually transmit OK; just ignore the apparent garbage that comes back. Then change SS's baud rate to 9600 to match, and you should have solid communication.
These are the three commands you need to send the ESP to accomplish the change:
AT                             # ESP should respond "OK"
AT+RST                         # Resets the ESP
AT+UART_DEF=9600,8,1,0,0       # Sets ESP UART: 9600,N,8,1,no flow ctl

Note: Your module might have been preset to some other rate than 115200, in which case you'll have to try various rates until you can get an intelligible reply. Once you do, set the default rate to 9600.

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


text:
Extending EEPROM life
I'm working on some software using an Uno (ATmega328P). I have a stage byte that can be 1 of 5 values (0-4) in my code and it will increase by 1 every 2.5 hours. If I lose power I need to ensure that on wake up the stage is the same as it was at the time of power loss, so each time the stage is updated I save it to EEPROM.
To ensure the EEPROM lasts as long as possible I want to write some code that uses more than a single byte which I continually erase and write to. I was wondering if there is any library to do this or if my idea below would work?
I currently don't need to use the EEPROM for anything else so to extend the EEPROM life I was going to section of 1 quarter of it (0-255 bytes) for saving this value. Each time I change the stage I will write 3 bytes to EEPROM which will be:

An index byte (used to shift addresses I write to).
A stage byte (the stage I need to store).
A count byte (the amount of times I have wrote the stage at the current index).

To begin with the index will be written to byte 0 in the EEPROM, the stage to byte 1 and the count to byte 2.
My plan is to allow the stage to be written to byte 1 250 times, then clear the count and shift the index to 3. This will in turn move the bytes that the stage and count are being written to to 4 and 5. I will do this until the index reaches the end of the 255 bytes and then return the index to 0. So in total I should be able to shift 85 times.
Each byte has 100,000 erase/write cycles so this means I can pass through bytes 0-255 400 times, writing the stage 250 times each pass. So instead of having 100K writes I would have about 8.5 million writes.
This is my first idea and I realize there is also some waste in the way I do it. I haven't worked with EEPROM much and I was just hoping for some advice as I'm sure I could be going at this completely wrong.

I don't have much experience with EEPROMS, but maybe even a single byte is written per 'page' (which can be e.g. 256 bytes), so you might have to take this into account when you write your data.

Another tip (if applicable): only write bytes (or a page) when a value is really changed (e.g. check the current value of a byte and only write it when it is unequal to the new value).

That method sound good to me. What I did in the past was to write my single byte (non-zero) value to the first location that was zero/empty. So every write, I moved one over. When I reached the end of the EEPROM I would zero-out the whole EEPROM and start back at index zero. To read the last value on power-up, just keep reading values from EEPROM till you read a zero (/or are at the last location).

Why not use an RTC instead?  If the stage increases every 2.5h you could calculate the stage by `((hours since 1970) \2.5 ) % 5

There are algorithms for extending the life of EEPROM, but is it going to be worth it in terms of processing power expended when the cost of replacing the EEPROM every year or so is only a few quid?

@MichelKeijzers Page Size for the ATMega328Ps EEPROM is 4 bytes. So it would be better to not use byte 1, 2 and 3. So the first page is only uses for the index byte.

@CodeGorilla some RTCs also have some free, battery backed, RAM available that you can write to. This works the same as EEPROM, but doesn't deteriorate, and keeps it's value, as long as the backup battery has enough voltage.

@Gerben thanks for this info ... I only played with SRAM which had a page of 32 bytes if I remember correctly. Guess it depends per storage type/brand/model.

The RTC is the best solution. Avoiding that the Arduino has a power down is the second best. For an algoritme, I would not count up to 250, but use the EEPROM as a ring buffer and continuously write to the next location. The Arduino could be turned off while writing to EEPROM, perhaps the variable has to writting twice and maybe with a checksum. Only two bits needs to be remembered... someone who is more creative than me can do something with that (a protocol to store it, or remember it in a different way).

Also asked at: http://forum.arduino.cc/index.php?topic=523223 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

Hi All, thank you very much for your comments. @Gerben If I go with my Idea I  will ensure I zero out my EEPROM once I reach the last byte I am using, hadn't even thought of that.

@CodeGorilla I do use the RTC technique elsewhere in my code but using the RTC in this case would not be suitable as I need the process to pick up exactly where it left off regardless of how long it is powered off for.

@Jot the ring buffer is a great idea and will further extend the EEPROM life. I was really over complicating it with a count, thank you.

@per1234, apologies for not mentioning the cross post, project is time sensitive and I honestly didn't think I would get such great advice so quickly. I will link in future if I ever cross post

@user1649972 - wouldn't zeroing the EEPROM be wasting a write cycle?  I don't know how you would follow gerban's suggestion without doing that though.  (understand what you mean about the RTC idea not being suitable in this case)

@CodeGorilla it kind of wastes once cycle, but in doing so make the code a bit simpler. Using the full 1k of memory, but writing it twice, will still give you 500 times the number of write cycles (ignoring page size). If that’s enough for the lifecycle of the product...

@CodeGorilla Been trying to think of a way around this as it will mean I write twice for every 1 write each loop around. Unfortunately I have to remove the old data before returning to my start point. My plan is when I reach the end of the EEPROM I will scan through all elements and return them to 0xFF (default value). I need to do this so I can find my last index on wakeup after a power loss. On wakeup I will scan all indexes until I reach one that has the value 0xFF, then step back to the previous index, which will be the last index I have saved. I cant think of a way around this just yet

You can load spread by saving the current value ORred 0x80 or 0x00.
When writing you write to the next memory location and when it wraps you take the other value to OR with.
The values in the eeprom will be
[{0x00|value},{0x00|value},{0x00|value},...,{0x00|value},{0x00|value},{0x00|value},{0x80|value},{0x80|value},{0x80|value},...,{0x80|value},{0x80|value}]

or
[{0x80|value},{0x80|value},{0x80|value},...,{0x80|value},{0x80|value},{0x80|value},{0x00|value},{0x00|value},{0x00|value},...,{0x00|value},{0x00|value}]

Then you read the first and last byte and if the upper bit is equal you take the last value.
If they are not equal you binary search until to the position changes, the most recent value will be the one right before the change.

Also, check that the values you want to write are actually changing. No point in erasing and writing a value that is already there. And you save 3.3 ms by not having to do the write.

Hi Edgar, thank you for the reply. The value will 100% change each time I try to write, the change in value is what prompts the write to EEPROM. Great advice tho, thanks again

There are many ways of achieving what you want. The method I would use would be to use pairs of bytes, but split up differently.
For each 16 bits I would have 13 for a counter, and 3 for a value. The counter, being 13 bits, can count from 0 - 2^13-1, or 0 - 8191.  The 3 value bits can store 0 - 2^3-1, or 0 - 7, which is fine for your 0-4 value.
The size of the counter is important, since it is more than double the number of 16-bit pairs in the EEPROM.  Assuming a 1kB EEPROM that's 512 16-bit values, so you want more than 1024 values available in your counter (if you wanted to change the split to store a larger number...).
The algorithm is simple:

Read through the EEPROM looking at the next counter value. If the count increases by more than 1 the last value read is the current one.
If the count goes from 8191 to 0 then keep going, you have just looped is all.
Increase the counter by 1 and write to the EEPROM addresses where the count jumped by more than 1.

For example, if you have:
78 1
79 2
80 3
8191 7
8191 7
8191 7

you know that the space after 80 hasn't been used (0xFFFF is split as 0x1FFF and 0x7) so you write "81 4" to it.
Another:
8190 2
8191 3
0 4
1 0
2 1
7283 3
7284 4
7285 0

The jump from 8191 to 0 is just a wrap around and can be considered sequential. However the jump from 2 to 7283 isn't sequential, so you can overwrite entry 7283 with "3 2".
When you write, if you are going past the end of the EEPROM's memory space, you just loop back round to the start again.
This gives you 512 * 100,000 writes, or 51.2m writes.

This is excellent and I will 100% use this idea on another project I am working on that uses a larger EEPROM. I will only use 2 bytes as suggested, drop my count sticking with just the stage and index and move the index after every EEPROM write. As I am only planning to use 256 bytes I would not need such a large index to cover them all as 1 byte will do. Again thank you for this it is appreciated and will be used. Using my basic idea I had 28 years, the idea I posted on here would have given me 2425 years and now with using the byte pairs I will get up to 3652 years so I'm well covered.

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


text:
What is an easy way to power a 3.3v BMP-180 barometer board from a 5v Arduino Nano?
Scenario:
I have a functioning weather station (temp/humid, MQ-2 smoke sensor, anemometer), and want to add a barometer.  The weather station is outside, linked to my inside display and RTC by the I2c&Power modules and ethernet cable.  The cable supplies 12v and I use a small converter to provide the 5v to run the I2c&Power board and the rest.
So I have 12v and 5v available out at the weather box.
Inside along with the RTC and LCD display I have a 2-port I2C&Power which will be used in the future (with the new pgpio library) to feed the info to an Rpi3 to create a web page to show changes over time.
The barometer module I bought is the BMP-180.  It is nice and tiny and looks perfect for the job, but the instructions all over the web tell me that it will burn up if powered by 5V.  The Arduino Nano does not have a 3.3v output pin like the Uno does.
Q:  What is the easiest way to accomplish adding this 3.3v board to the weather station?

Use a 3.3V Nano.

Kinda late to consider that.  ;-)

Here is the solution I settled on:  a small part that will step 5 volts down to 3.3 volts.  The price is right, but it will be shipped by the slow boat so will take a month or so to receive.
5Pcs 5V to 3.3V DC-DC Step-Down Power Supply Buck Module AMS1117 LDO 800MA
http://www.ebay.com/itm/5Pcs-5V-to-3-3V-DC-DC-Step-Down-Power-Supply-Buck-Module-AMS1117-LDO-800MA-/261983164332
It has 3 pins - Vin, Vout, GND.    Easy to hook up.
Upvote to everybody for the discussion.

Consider attaching your +5V supply to a USB plug, and using that to power the Nano via its USB socket.
When the Nano is powered via its USB socket, the CH340 or FTDI FT232 supply  up to 50mA of 3.3V power to the 3V3 pin located between Aref and d13.  See for example 3v3 output from FTDI chip on Arduino Nano 3 at arduino.cc.
Actually, that thread apparently says the 3V3 is available no matter how the board is powered; you may want to run some tests and measurements.  The only test I ran was to measure about 3.2 V at the 3V3 pin when a clone Nano 3 with CH340 was connected to a USB-power adapter.

That is interesting.  I sure have noticed that power via USB is not the same as 5v on the Vin pin.  Thanks for the info.  -  However, if you read the OP you will see that I am feeding 12v out to the box where there is a 12-to-5 converter.   It measures at exactly 5v to the Vin and to the other devices (except the anemometer, which uses 12v).  This is a clever solution but might upset the applecart.

I meant to add that the analog input from the anemometer uses a conversion constant in order to convert the readings to MPH.  It took some trial and error to figure it out...  Since it is working I would prefer to leave alone the part that is working.  Still, I will remember what you wrote here for the future.

Just did an experiment where I fed a lab power supply into an analog input, with the Arduino powered by the USB.  I used a voltage divider of 10K/2K  so I can measure up to 24V.  I take 10 readings at 500ms intervals then average them.  When running on USB, the plotter readings are all over the place.  With Vin at +5 it is much more stable - when displayed on the LCD and the USB disconnected.

@Archway, by "running on USB" do you mean USB-from-computer, or USB-power-adapter?  If both USB ways give bad ADC readings [presumably due to noise?], sounds like +5-to-Vin is what you have to use.  But you could still see if a usable 3.3 V is appearing on the 3V3 pin (next to Aref on the Nano) when using +5-to-Vin.

I did mean running on USB from a computer.  But to be sure, I ran the Nano Vin on the lab power supply at a strict 5v and the 3V3 pin measures 2.81 volts.  Interesting.


text:
smaller program bigger sketch

I'm working on a program composed by several classes.
I reduced the size of a single class of (more or less) one hundred lines (4kb of stuff)
I expected a smaller sketch but surprisingly it is increased in size (few bytes).

How is it possible?It's something about the compiler?

if it wasn't using those 100 lines anyway, you won't save anything...

A compiler translates c/cpp to target assembly language.
To keep it short, some c/cpp language statements or keywords can be used to shorten the code (in c/cpp)... but the mechanics behind all that to translate to assembly can generate more instructions than you thought.
It would maybe be easier to explain if you put some example...

Arduino is C++ not C.

yep, true, thanks for pointing that out, i'll correct that (yet, you can code c libraries if you need)... and the generated assembly is even worse!


text:
How to include Voltage code in 4 digit 7 segment dislay
As a continuation of my question. Here's the code for controlling the 4 digit 7 segment display:
int a = 2;
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;
int p = 9;

int d4 = 10;
int d3 = 11;
int d2 = 12;
int d1 = 13;

void setup()
{
  //set all the pins of the LED display as output
  pinMode(d1, OUTPUT);
  pinMode(d2, OUTPUT);
  pinMode(d3, OUTPUT);
  pinMode(d4, OUTPUT);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(g, OUTPUT);
  pinMode(p, OUTPUT);

}
/***************************************/
void loop()

{
  //The 7-segment LED display is a common-cathode one. So also use digitalWrite to  set d1 as high and the LED will go out
  digitalWrite(d1, HIGH);
  digitalWrite(d2, HIGH);
  digitalWrite(d3, HIGH);
  digitalWrite(d4, HIGH);

  switch(x)
  {
    case 0:
    digitalWrite(d1, LOW);//Light d1 up
    break;
    case 1:
    digitalWrite(d2, LOW); //Light d2 up
    break;
    case 2:
    digitalWrite(d3, LOW); //Light d3 up
    break;
    default:
    digitalWrite(d4, LOW); //Light d4 up
    break;
  }
}
//The function is to control the 7-segment LED display to display numbers. Here x is the number to be displayed. It is an integer from 0 to 9
void pickNumber(int x)
{
  switch(x)
  {
    default:
    zero();
    break;
    case 1:
    one();
    break;
    case 2:
    two();
    break;
    case 3:
    three();
    break;
    case 4:
    four();
    break;
    case 5:
    five();
    break;
    case 6:
    six();
    break;
    case 7:
    seven();
    break;
    case 8:
    eight();
    break;
    case 9:
    nine();
    break;
  }
}
void clearLEDs() //clear the 7-segment display screen
{
  digitalWrite(a, LOW);
  digitalWrite(b, LOW);
  digitalWrite(c, LOW);
  digitalWrite(d, LOW);
  digitalWrite(e, LOW);
  digitalWrite(f, LOW);
  digitalWrite(g, LOW);
  digitalWrite(p, LOW);
}

void zero() //the 7-segment led display 0
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(g, LOW);
}

void one() //the 7-segment led display 1
{
  digitalWrite(a, LOW);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, LOW);
  digitalWrite(e, LOW);
  digitalWrite(f, LOW);
  digitalWrite(g, LOW);
}

void two() //the 7-segment led display 2
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, LOW);
  digitalWrite(d, HIGH);
  digitalWrite(e, HIGH);
  digitalWrite(f, LOW);
  digitalWrite(g, HIGH);
}

void three() //the 7-segment led display 3
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, LOW);
  digitalWrite(f, LOW);
  digitalWrite(g, HIGH);
}

void four() //the 7-segment led display 4
{
  digitalWrite(a, LOW);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, LOW);
  digitalWrite(e, LOW);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);
}

void five() //the 7-segment led display 5
{
  digitalWrite(a, HIGH);
  digitalWrite(b, LOW);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, LOW);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);
}

void six() //the 7-segment led display 6
{
  digitalWrite(a, HIGH);
  digitalWrite(b, LOW);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);
}

void seven() //the 7-segment led display 7
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, LOW);
  digitalWrite(e, LOW);
  digitalWrite(f, LOW);
  digitalWrite(g, LOW);
}

void eight() //the 7-segment led display 8
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);
}

void nine() //the 7-segment led display 9
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, LOW);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);

My problem is how to include the voltage code here? Here's the code for voltage code:
    /*
* Display5vOrless sketch
* prints the voltage on analog pin to the serial port
* Warning - do not connect more than 5 volts directly to an Arduino pin.
*/

const float referenceVolts = 5.0; // the default reference on a 5-volt board
const int batteryPin = 0; // battery is connected to analog pin 0

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

void loop()
{
 int val = analogRead(batteryPin); // read the value from the sensor
 float volts = (val / 1023.0) * referenceVolts; // calculate the ratio
 Serial.println(volts); // print the value in volts
 delay(500);
 }

Please help me! Thank you!

Are you sure you want to merge them before they are working? Check them first then try to merge them yourself. How would you go about that? Describe your reasoning. Then and only then ask for help.

Isn't there a library for this, im thinking there is some steps that you need to cover before it will work.

Yes you can display single digits what happen when you want to display double or triple digits. You need a code that can handle that. You need to cut up volts an iterare over it. Anyway create a class that takes volt and return it on the display. That's what you you need to do to merge that code. Are you up for that? Or are you gonna find a library that can handle that?


text:
Using an Arduino on a motorcycle
I want to use the Arduino to control various electronics on my motorcycle. I would need to power the Arduino with the motorcycle battery. So the question is, when the motorcycle is running the alternator will be putting out something like 13v to the battery. So can I still just connect the battery directly to the vIn and ground to power it?

Automotive power has a lot of noise and high transients in them. The Arduino a power circuitry has no protection against this. I'd suggest getting the circuitboard out of a cheap car-sigaret to USB power supply and using that.

an LM7808 would take a lot of pressure and heat off the internal LDO while regulating noisy 12v

Accordly to Arduino Technical Specs:
-Input Voltage (recommended)    7-12V
-Input Voltage (limit)  6-20V
https://www.arduino.cc/en/main/arduinoBoardUno
Another Arduino thread:
https://forum.arduino.cc/index.php?topic=22676.0
I would say a better choice is to use another battery power supply just for Arduino. Is is easy to install, easier to handle and more verstile unless you really needs to use your motorcycle battery. And if you want or need to read your motorcycle battery just use a portable voltage meter plugged onto Arduino with no need to use your vehicle battery to power it.

“Arduino need an DC input of 5 volts”: the Vin input is spec'd to take from 7 to 12 V.

For sure, I misundestood. Vin not USB. Im going to fix my answer

Just add a rectifier diode or two before the vin input. This gives you a 0.7V drop per diode for large currents, for small currents the LDO won't overheat anyway...


text:
Switch on the piezo emitter for a short time
I need a short beep for every minute of change. I wrote a separate function. The signal duration should be 50 ms, the rest of the time the emitter connected to the A1 contact should be silent.
A really working sketch is shown below:
uint32_t mysound; // Variable for storing time (duration of the sound signal)
uint32_t myTimer1;
uint32_t t; //Time that always increases
byte seconds; // Seconds
byte minutes; // Minutes
int k = 1;
void setup()
{
  DDRC = B00000010; // Set pin A1 as output
  //      76543210
  Serial.begin(9600);
  myTimer1 = millis();
}

void loop()
{
  t = (millis() - myTimer1) / 1000; // Time in seconds
  seconds = t % 60; // when 60 seconds are reached, it is reset to zero
  minutes = t / 60 % 60; // Counts the minutes and drops to zero when 60 minutes are reached
  Serial.println(seconds);
  if (seconds == 0 && k)
  {
    sound();
  }
  if (seconds > 0) k = 1;
}

void sound()
{
  mysound = millis();
  while (millis() - mysound < 50)
  {
    PORTC = B00000010; // We set high voltage on pin A1 for a time of 50 ms
  }
  k = 0;
  PORTC = B00000000;
}

doesn't work is a meaningless description of what you observed ... please describe what happens ... also, describe what tests you performed to make sure that the piezo emitter works

does the piezo make sound with pin HIGH?

Yes, if you just raise the pin to a high level, then the piezo emitter beeps

All my attempts end with him either constantly beeping or constantly silent. I was unable to achieve a short-term peak

I assume, you are using atmega328 or atmega2560 when using register PORTC instead of digitalWrite() for generic arduino board. Are you trying to avoid using TIM1 or TIM2? And so maybe there is a reason to avoid using delay() as well. So try this one single line code >>>>  if ((millis() % 60000) < 50) PORTC |= 0x02; else PORTC &= ~0x02;

Your myTimer1 in t = (millis() - myTimer1) / 1000; is not set

In addition to Qareke's answer, you also have a problem with the mysound variable. You only set this timestamp to millis() inside your millis() if statement. mysound is global and thus will be implicitly initialized with zero. So, by the time, that the code reaches the if statement, the difference between millis() and mysound is most likely already too big, thus the timestamp gets never set.
Solution: You need to move 2 lines around in your code:

Move the mysound = millis(); statement up into the if (seconds == 0) statement.
Move the sound(); statement outside of the if statement directly into the void loop() function (for example directly after the if (seconds == 0) statement).

Now the sound() function will always be executed, but it will only do a sound, if the timestamp was set to millis() previously, and then only for 50ms. Now we only need to make sure, that the timestamp variable mysound will only be set once, when the seconds get zero. You could either introduce a new flag variable for that, or you could just use the timestamp itself and check, if more than 1s passed since the last time the timestamp was set. So you need to change
if (seconds == 0)

to
if (seconds == 0 && millis() - mysound > 1100)

I used 1100 (1.1s) here, to make sure, that there is no bad edge case happening. Since seconds will only get zero every minute, that shouldn't be a problem.

Sorry, but I did not understand how you can move a function call out of a condition. Then what remains within the condition?
I fixed the program from above, in this form the squeak starts but never stops

If you read my answer closely, you see, that I instructed you to move the mysound = millis(); statement inside that if statement. But you have put still inside the sound() function. Also you have chosen to use a flag variable (instead of the proposed millis() solution). So you haven't used my solution to the problem. Nonetheless, your current code works perfectly for me. I don't have a piezo at hand, but my logic analyser shows a 50ms long positive pulse every minute. If that doesn't work for you, probably there is something wrong with your wiring


text:
Setting a fixed receiver frequency RDA5807m
I am using the receiver RDA5807m, but I do NOT need to switch the frequency and other parameters during operation.

I noticed that the module continues to work when the programming pins are disconnected during its operation, that is, it remembers the settings until the supply voltage is removed.
Therefore, I want to set the frequency and volume at the beginning of work, so as not to occupy the resources of the microcontroller, but I just understand the registers. Tell me how to write code, the simplest of all possible configurations for this purpose.
Now I am using the following sketch, it works, but it takes a lot of resources, and I don't need it. Help simplify it and free it if possible "void loop()"
#include <Wire.h>

#define RDA5807M_RANDOM_ACCESS_ADDRESS 0x11
// registers
#define RDA5807M_REG_CONFIG 0x02
#define RDA5807M_REG_TUNING 0x03
#define RDA5807M_REG_VOLUME 0x05
#define RDA5807M_REG_RSSI   0x0B
// flags
#define RDA5807M_FLG_DHIZ 0x8000
#define RDA5807M_FLG_DMUTE 0x4000
#define RDA5807M_FLG_BASS 0x1000
#define RDA5807M_FLG_ENABLE word(0x0001)
#define RDA5807M_FLG_TUNE word(0x0010)
//masks
#define RDA5807M_CHAN_MASK 0xFFC0
#define RDA5807M_CHAN_SHIFT 6
#define RDA5807M_VOLUME_MASK word(0x000F)
#define RDA5807M_VOLUME_SHIFT 0
#define RDA5807M_RSSI_MASK 0xFE00
#define RDA5807M_RSSI_SHIFT 9

uint8_t volume = 15; // 0..15
uint16_t freq = 1073; // 107.3FM
uint16_t reg02h, reg03h, reg05h, reg0Bh;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  // Register 02h - enable, settings
  reg02h = RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
  setRegister(RDA5807M_REG_CONFIG, reg02h);

  // And then we decided to further strengthen the bass:
  reg02h |= RDA5807M_FLG_BASS;
  setRegister(RDA5807M_REG_CONFIG, reg02h);

  // Register 03h - radio station selection
  // After reset in register 03h, the default value is 0
  // Thus BAND = 00 (87..108MHz), STEP = 00 (100kHz). Let's leave them as they are
  reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT; // chan = (freq - band) / space
  setRegister(RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);

  // Register 05h. Set the volume, do not change the rest of the beats
  reg05h = getRegister(RDA5807M_REG_VOLUME); // read the current value
  reg05h &= ~RDA5807M_VOLUME_MASK; // Resetting the VOLUME bits
  reg05h |= volume << RDA5807M_VOLUME_SHIFT; // Set a new volume
  setRegister(RDA5807M_REG_VOLUME, reg05h);
}

void loop() {
  // Register 0Bh - status
  reg0Bh = getRegister(RDA5807M_REG_RSSI);
  uint8_t RSSI = (reg0Bh & RDA5807M_RSSI_MASK) >> RDA5807M_RSSI_SHIFT;
  Serial.print("RSSI = ");
  Serial.print(RSSI);
  Serial.println(" (0-min, 127-max)");
  delay(500);
}

void setRegister(uint8_t reg, const uint16_t value) {
  Wire.beginTransmission(0x11);
  Wire.write(reg);
  Wire.write(highByte(value));
  Wire.write(lowByte(value));
  Wire.endTransmission(true);
}

uint16_t getRegister(uint8_t reg) {
  uint16_t result;
  Wire.beginTransmission(RDA5807M_RANDOM_ACCESS_ADDRESS);
  Wire.write(reg);
  Wire.endTransmission(false);
  Wire.requestFrom(0x11, 2, true);
  result = (uint16_t)Wire.read() << 8;
  result |= Wire.read();
  return result;
}

I found a really short sketch that allows you to set the frequency. It remains to set the volume in the same way.
#include <Wire.h>
float f = 104.7;

void setFrequency(float frequency)
{
  unsigned int frequencyB = 4 * (frequency * 1000000 + 225000) / 32768;
  byte frequencyH = frequencyB >>8;
  byte frequencyL = frequencyB & 0XFF;
  Wire.beginTransmission(0X60);
  Wire.write(frequencyH);
  Wire.write(frequencyL);
  Wire.write(0xB0);
  Wire.write(0x10);
  Wire.write(0x00);
  Wire.endTransmission();
}

void setup() {
  Wire.begin();
  setFrequency(f);
}

void loop()
{
}

What resources do you mean? RAM? Flash? Computing time? I don't see anything, that seems really bad here

I do not need the receiver to interfere with the microcontroller during operation. I noticed a significant slowdown in other code when I use it in conjunction with this code. So I need to keep the program as simple as possible

Without seeing the complete code, that slows down, I cannot be sure. But in the code above the biggest slowdown is the delay. You should not use any delay calls. Also: do you really need to read the RSSI continuously? If not, then just don't do it.

It seems to me, that you want to optimize for code length (not size). If you compare the two codes in your question, you see two things: The second code does less things (setting only one register instead of 4) and it doesn't use any defines. The first one is the easiest to optimize (only do things, that you need to do). The second one is an antipattern (meaning not a good coding practice). The code uses hexadecimal values without any description. Defines can give these values names without taking up any extra space in the final program (since they are substituted before compilation)

And the second codes does nothing in loop, which is the same principle as my first point

I just need it to do nothing in the loop!

If you didn't know how to do nothing in loop prior to this question, please write your own answer. I still don't really know, what your actual question was, so maybe an answer from you would enlighten me

I need to set the frequency and volume once; I don't need to change them during operation. As I understand it, I just need to remove everything from the loop of the first given program. Since I did not create it myself, but took it ready, so there is a lot of unnecessary things.


text:
Assign an interrupt to any pin of the atmega328 microcontroller
I need to record the appearance of a signal from the sensor on the PD0 pin. This is the first time in my life that I want to use an interrupt for this.
With your help, I configured the sketch for my pin PD0
#include <avr/interrupt.h>

volatile int value = 0;

void setup()
{
  cli();
  PCICR |= 0b00000100;    // turn on port d
  PCMSK2 |= 0b00000001;    // turn on pins PD0 (PCINT16)
  sei();

  Serial.begin(9600);
}

void loop()
{
  Serial.println(value);
}

ISR(PCINT2_vect)// Port D, PCINT16 - PCINT23
{
  value++;
}

I need to wait and take a certain action when a high signal comes from the sensor. For example, add one to the constant.
I also did not understand when interruptions occur. When the signal changes from bottom to top, when from top to bottom, or no matter how? Can't see if these settings are here? Maybe it is set somehow by default?

It is unclear, what exactly your problem is. In the example the used pin is pinBlink with the value 7. You can change it with the define at the start of the sketch

The pin numbers of the TQFP package are irrelevant here. You just need to know that pin “PD0” of the ATmega328P is “digital 0” of the Arduino Uno and Arduino core library.

PD0 is Serial RX and pin 0 on Uno/Nano/Mini. why do you want use this pin?

why not use "external interrupt" peripheral?

I dont know. It seems that this is how it works, but I don't understand how it works. Which edge of the pulse. I turned on the button instead of the sensor, but I still can't understand

Here is a link to a good tutorial on how to enable, respond to, and clear interrupts on the ATMega328P device:
Arduino Pin Change Interrupts
I'll repeat the overall steps here in case this URL disappears in the future:
First, you must enable pin change interrupts:

Note the use of 3 bits in the PCICR register [0:2].  These enable pin change interrupts on ports B, C, or D in general.  You can choose any combination of these ports or all of the ports as you desire.
Next, you select which pin or pins on the enabled ports that you want to receive interrupts from.  You have control here over each individual port bit:

Then you must write an ISR (Interrupt Service Routine) to handle the interrupt once it occurs.  You have the option of up to THREE ISRs, one to handle each port or you can have a single ISR to handle any pin change interrupt.  The way this works is that when an interrupt happens on an enabled port and pin, the AVR chip calls the ISR that you have configured for that event:

So when an interrupt happens, how do you know which pin(s) caused the ISR?  Let's assume you used a single ISR to handle all 3 ports.  At this point you know only that an interrupt happened somewhere.  That's the purpose of the PCIFR register bits.  From the AVR datasheet we see this:

By checking the status of these bits you can now tell which pin or pins caused the interrupt.  Note that there CAN BE MORE THAN ONE, so it's up to you to decide the priority of each one and handle them accordingly.  Note that you only get ONE chance to read these during any ISR function call since they get cleared when the ISR executes.
One last note.  You MUST call the sei(); function to enable any interrupt to the CPU before any interrupt will happen.
In your example, however, you seem to be attempting to generate a pin change interrupt on an output. This is probably NOT what you want.  Try simply using the existing LED output pin as an indicator and choose a different pin, setup as INPUT, to be your pin change interrupt source.

Thanks! I got something. The counter increases the number when I touch the wire coming out of the PD0 pin with my hand. But I still do not understand on what front or how it works like that

the original question used a library for pin change interrupts. how does this answer answer the question?

@Juraj I see no library being used.

the question was edited


text:
NRF24l01 Channel switching
I have a NRF24L01 radio module. The description indicates that it can work in the ISM frequency range of 2.400 ... 2.525 GHz. The channel step is 1 MHz, and there are 125 channels in total.

The channel number can be set using
radio.setChannel (0x125);
The maximum number is supposedly 125. However, I examined the signal spectrum in Sdrsharp using a radio tuner and it turned out that the frequency at the maximum channel is very low.

I started increasing the number and got to 180 radio.setChannel (125); the frequency was 2525 MHz as stated. It turns out that the number of channels of the radio module is not 125, but 180? I determined the 180 number experimentally. The literature says that it has 125 channels 1 MHz wide.
The most interesting thing is that the Arduino IDE does not give errors when entering a large number of channels. Tell me how you can speed up the process of switching channels in order to understand how they switch. To manually reflash it for a long time when changing each channel.
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

RF24 radio(9, 10); // use 9 и 10 pin arduino uno
byte address[][6] = {"1Node", "2Node", "3Node", "4Node", "5Node", "6Node"};
byte counter = 1;

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

  radio.begin(); //activate module
  radio.setAutoAck(0); //confirmation mode, 1 on 0 off
  radio.setRetries(0, 15); //(time between attempts to reach out, number of attempts)

  radio.setPayloadSize(32); //packet size, in bytes

  radio.openWritingPipe(address[0]); //we are pipe 0, we open a data channel
  radio.setChannel(125); //select a channel (in which there is no noise!) 0 ... 125

  radio.setPALevel (RF24_PA_MIN); //transmitter power level. To choose RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH, RF24_PA_MAX
  radio.setDataRate (RF24_2MBPS); //exchange rate. To choose RF24_2MBPS, RF24_1MBPS, RF24_250KBPS
  radio.powerUp(); //get started
  radio.stopListening(); //do not listen to radio broadcasts, we are a transmitter
}

void loop(void) {
  while (1)
  {
    radio.write(&counter, 1);
    //Serial.println(counter);
  }
}

Is it possible to toggle the channel number radio.setChannel (0x180) sequentially in a void loop?
thanks!
I tried to do this:
void loop (void) {
     for (int n = 0; n <126; n ++)
     {
       radio.setChannel (n); // select a channel (in which there is no noise!) 0 ... 125
       radio.write (& counter, 1);
       delay (1000);
     }
}

However, radio.write (& counter, 1) should work separately from any loops to avoid delays. Otherwise, it doesn't work correctly.

181 != 0x181 - learn your bases.

setChannel expect an single byte value, so your 0x180 get truncated to 0x80 (which is 128 in decimal). The library then lowers this to 125, because it's too high a value.

You're getting confused with number bases. A number prefixed with 0x is hexadecimal. That's base 16 - not base 10.
0x125 is actually 293. If you try squeezing 293 into an 8-bit register it will truncate to 37.
Channel 125 is 0x7D in hexadecimal.
I can't recall off hand how big the register is for the channel number, but either 7 or 8 bits would suffice (probably only 7 bits actually used) so the highest channel number you could possibly enter would be 127, which is 0x7F, after which it will start at channel 0 again for 128 or 0x80.

Thank you, but how can you switch the channels in order automatically?

In the way you are already - but you may need to power down before changing channels.

Is it possible to remove the 0x prefix and enter the channel number from 0 to 125 as a decimal number?  After all, this is much clearer and more convenient.

Of course. It's just a human representation of the number. You could even go as far as to use 0 to 0175 and use octal if you wanted. It's just numbers.

Ultimately it is up to you to follow the rules and regulations set forth by your country’s wireless spectrum regulatory agency. If you are in the RF band, appropriately licenced and at legal power you are OK. From your post you can do that with your Sdrsharp.


text:
Uno R4 WiFi board is online but no OTA option for upload
I have followed these instructions to start using my new Uno R4 WiFi with the Arduino IoT Cloud. Everything works fine (even though sometimes the example screens do not exactly correspond with the actual screens). My Uno R4 WiFi is online and the online dashboard can switch the LED on and off even with the board powered from a battery and not physically connected via USB. The only problem is that I still cannot upload a sketch via WiFi. The instructions say:

Once in the sketch tab, let’s open the board's drop down menu. There,
a new option to connect our board should be available. The name of the
board configured for the cloud will appear, followed by the
Over-the-Air option.

But that drop down menu is not available and if I disconnect the USB I get No associated device found even though in Things-Setup the board is shown as being online.
Can someone explain what I am missing here? Or perhaps the Uno R4 WiFi is not compatible with the IoT cloud or the online IDE but that seems unlikely for a heavily advertised new WiFi product from Arduino.

it is not implemented yet for Uno R4

Where did you get the information that it is simply not implemented? It just seems odd to me as Arduino are adverising this device and its WiFi capabilities heavily yet I have not seen any mention that uploading per OTA is not implemented

@Juraj The Uno R4 WiFi is selectable in both the IoT Cloud and online editor, and sketches can be uploaded to it via USB. Only the OTA port appears to be a problem.

I looked into the library https://github.com/arduino-libraries/ArduinoIoTCloud/tree/master/src/utility/ota


text:
ESP8266 TIMEOUT: 428
this is the code I used:
#include <Wire.h>
#include "WiFiEsp.h"
// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(18, 19); // RX, TX
#endif

char ssid[] = "Vodafone-A61356555";            // your network SSID (name)
char pass[] = "xxxx";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
int reqCount = 0;                // number of requests received

WiFiEspServer server(80);

int MPU = 0x69;
int MPU1 = 0x69;
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
int16_t AcX1, AcY1, AcZ1, Tmp1, GyX1, GyY1, GyZ1;
int gyro_state = 2;
int gyro_state_1 = 3;
int RED_LED = 8;
int GREEN_LED = 9;

void setup(){
  pinMode(gyro_state, OUTPUT);
  pinMode(gyro_state_1, OUTPUT);
  pinMode(RED_LED, OUTPUT);
  pinMode(GREEN_LED, OUTPUT);
  digitalWrite(gyro_state, HIGH);
  digitalWrite(gyro_state_1, HIGH);
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
  printWifiStatus();

  // start the web server on port 80
  server.begin();
}

void loop(){
  // listen for incoming clients
  WiFiEspClient client = server.available();
  if (client) {
    Serial.println("New client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          Serial.println("Sending response");

          // send a standard http response header
          // use \r\n instead of many println statements to speedup data send
          client.print(
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: text/html\r\n"
            "Connection: close\r\n"  // the connection will be closed after completion of the response
            "\r\n");
          client.print("<!DOCTYPE HTML>\r\n");
          client.print("\r\n");
          client.print("
\r\n");
          client.print("Accelerometro X: ");
          client.print(AcX);
          client.print("
\r\n");
          client.print("\r\n");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(10);

    // close the connection:
    client.stop();
    Serial.println("Client disconnected");
  }
  digitalWrite(gyro_state, HIGH);
  digitalWrite(gyro_state_1, LOW);

  do{
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 14, true);       // request a total of 14 registers
    AcX = Wire.read() << 8 | Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    AcY = Wire.read() << 8 | Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ = Wire.read() << 8 | Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp = Wire.read() << 8 | Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX = Wire.read() << 8 | Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY = Wire.read() << 8 | Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ = Wire.read() << 8 | Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

    Tmp = Tmp / 340 + 36.53;

    digitalWrite(gyro_state_1, HIGH);
    digitalWrite(gyro_state, LOW);
    delay(1000);

  }while(digitalRead(gyro_state)== HIGH);

  do{
    Wire.beginTransmission(MPU1);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU1, 14, true);       // request a total of 14 registers
    AcX1 = Wire.read() << 8 | Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    AcY1 = Wire.read() << 8 | Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ1 = Wire.read() << 8 | Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp1 = Wire.read() << 8 | Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX1 = Wire.read() << 8 | Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY1 = Wire.read() << 8 | Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ1 = Wire.read() << 8 | Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

    Tmp1 = Tmp1 / 340 + 36.53;

    digitalWrite(gyro_state, HIGH);
    digitalWrite(gyro_state_1, LOW);
    delay(1000);

  }while(digitalRead(gyro_state_1) == HIGH);
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print where to go in the browser
  Serial.println();
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);
  Serial.println();
}

This is what I see in the serial monitor with a baud of 115200:
[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 1.5.4
Attempting to connect to WPA SSID: Vodafone-A61356555
[WiFiEsp] Connected to Vodafone-A61356555
You're connected to the network
SSID: Vodafone-A61356555
IP Address: 192.168.1.30

To see this page in action, open a browser to http://192.168.1.30

[WiFiEsp] Server started on port 80
[WiFiEsp] New client 0
New client
GET / HTTP/1.1
Host[WiFiEsp] TIMEOUT: 428
Client disconnected
[WiFiEsp] New client 0
New client
GET / HTTP/1.1
Host[WiFiEsp] TIMEOUT: 428
Client disconnected

please add a this is my question section to your post

it is a known problem of the WiFiEsp library which is not maintained anymore. if you can update the AT firmware,, you can use my WiFiEspAT library

I tried to change the library but it tells me to change WiFiEspServer to WiFiServer and for WiFiEspClient it tells me Compilation error: 'WiFiEspClient' was not declared in this scope

of course. it is a different library


text:
TM1637 Decimal points
I am using the following TM1637 board with an Arduino Pro Micro clone.
I am attempting to use the "TM1637Display Library" written by Avishay Orpaz, but I cannot find any way to use the four decimal points on this display (as opposed to the colon appearing on many 4 digit displays).  Is there any way to use this driver to output one of the decimal points to the display?  If not, what is a 1637 driver which will allow me to output a decimal point?  I am going to be reading the voltages on several of the Arduino analog inputs and outputting them to the display in sequence.

There's no documentation provided by the seller, not even a pinout. Don't buy products without documentation. Now your only option is for you to experiment and find out if the decimal dots are even usable. Alternatively, you could return the displays, leave a warning for others in the reviews and buy some that do include documentation.

Additionally you can search and lookup the display's data sheet to find the pin for the decimal point. Next you need to re-engineer the display's board and check whether its control logic controls that pin at all. With some luck, it does.

@StarCat and busybee. TM1637 is a LED Display and Keypad Driver IC with a datasheet. No special pinout just data and clock and the TM1637Display library works for OP.

@Juraj There are four pins on the module without any obvious pin markings (you would at least like to know where to connect Vcc, Gnd, SDA and SCL) and the product description says nothing about I2C. Anyway, it was just an example of the fact that this is a module that is unsupported by its seller and when you buy one, you're on your own.

@StarCat sorry it is not I2C but a similar two wire protocol. I edited the comment. the TM1637  IC has a datasheet

OK, it definitely works.  I found a test sketch that displays all four decimal points.  See my answer.  These boards are extremely common, available on ebay, Amazon, and elsewhere.

I found this (edited for relevance)
#include <Arduino.h>
#include <TM1637Display.h>

// Module connection pins (Digital Pins)
#define CLK 4
#define DIO 3

// Create a new instance of the TM1637Display class
TM1637Display display(CLK, DIO);

// The amount of time (in milliseconds) between tests
#define TEST_DELAY   2000

void setup() {};

void loop()
{
  int k;
  uint8_t data[]  = { 0xff, 0xff, 0xff, 0xff }; // Create an array that turns all segments ON
  uint8_t blank[] = { 0x00, 0x00, 0x00, 0x00 }; // Create an array that turns all segments OFF
  display.setBrightness(0x0f);

  // All segments on
  display.setSegments(data);
  delay(TEST_DELAY);

    // Run through all the dots
    for(k=0; k <= 4; k++) {
        display.showNumberDecEx(0, (0x80 >> k), true);
        delay(TEST_DELAY);
    }
}

The example of  Avishay Orpaz's TM1637Display library has this:
// Run through all the dots
for(k=0; k <= 4; k++) {
  display.showNumberDecEx(0, (0x80 >> k), true);
  delay(TEST_DELAY); // show the dot
}

If you use display.setSegments and encode the segments in the sketch, the dot is the 8 bit in the byte encoding the segments of the digit.
displayData[i] = display.encodeDigit(digit[i])
displayData[i] |= 0x80; // show the dot

from the TM1631Display.h, the showNumberDecEx() method support the dot enable, and it is not exactly the MSB for controlling the dot, but it is bit shift mask depend on the which digit's dot to be enabled.

@hcheung yes. as the answer says

Oops!  I was writing my answer when you posted yours.  Thanks.


text:
Grove relay stuttering
I have bought this Grove relay: Grove - Relais | Kiwi Electronics.
I use it to drive a low-power water pump with a 9v battery. So the pump circuit is isolated from the Arduino circuit.
When the Arduino sends 'high' to the relay, this relay begins to stutter. Contract-release at high frequency. This only happens if the pump is attached. I have bought multiple relays and they all behave in the same way.
When I use a non-grove relay, such as Twee-kanaals 5V relais module | Kiwi Electronics I do not have this issue.
I made a small film of both relays: https://photos.app.goo.gl/szHHE5EGqjHzJy3f7 (shared google photo's album).
Why does this happen? What can I do to correct this issue with the Grove-relais?
I want to use these Grove-relays because they need to be used by students that are used to work with Grove components.
Please help!
The code:
void setup() {
  Serial.begin(9600);
  pinMode(7, OUTPUT);
  Serial.println("start");
  delay(1000);
}

void loop() {
  digitalWrite(7, HIGH);
  delay(2000);
  digitalWrite(7, LOW);
  delay(3000);
}

This is the schema:

Please try the grove relay again with the exact same connections and code as the other relay. If it then still happens, then the relay board is probably broken

I use the exact same code and arduino setup. I tested it with multiple different Grove relays. They all have the same issue.

could be bad code

The circuit works properly when I switch to the non-grove relay. And it's just setting a digital output port high. Can't be much bad about that, i think. :-(

maybe the arduino is resetting

Have you tried triggering the relay by directly attaching the relays input pin with ground and 5V? You need to narrow down the source of the problem. Currently we don't have much to work with. Please also include your code in the question, so that we can check that too.

yes indeed, it is resetting, but I do not understand why. It only happens when I put the load on the high-power side of the relay. Without the pump attached, the relay just functions fine. I tested two relays, both show the same behaviour. So adding a load on the high-power side affects the low-power side?! That should be completely isolated, right?

The Grove relay in your photo (the black one) clearly says DC3V: you are presumably energising the coil, as well as controlling it, with DC5V.
Perhaps you should try their 5V version:

The datasheets says the 3.3v version can be operated both at 3.3v and at 5v. It has a 5-3.3v shifter a board: https://wiki.seeedstudio.com/Grove-Relay/

I would suspect that the switching of the pump motor causes a decently high current spike that messes with your control side. Switching inductive loads always comes with issues.
Try adding a freewheeling diode and bypass cap (1-10µF) to the pump like:

Though If possible, I'd still reccomend using a relais that's less likely to generate interference. With this relais I'd suspect the close proximtiy of input and output traces to be a good part of the reason it's doing what it does.


text:
Why should I put a 10K resistor with an LDR?
I am wondering why should I put a 10K resistor with an LDR.
If I put a "stronger" resistor with another resistor (in this case the LDR), I'd get a lower voltage, and then I'd, too, get a lower value in the analogRead(). I'd like to know in what I'm doing wrong. Can someone help me?

Can you draw a schematic of how you've connected everything?

LDR have a changing resistance, relative the the amount of light. The arduino can't measure resistance, only voltage. So one way is to create a voltage divider. One resistor will be the LDR, the other one will be a fixed value resistor. To value of that resistor depends on the typical resistance of the LDR, the light-level range you'd like, power consumption, and other factors. I don't see why you think you are doing something wrong. With a higher value resistor, you get more precision in dark conditions. (try swapping the resistor an LDR).

LDRs themselves come in a considerable range of resistances. Search LDR specs and you will see what I mean. For example, from eBay I found one:

Bright Resistance(10Lux)(KΩ):20-230
Dark Resistance: 2 MΩ

This particular one, for example, seems to range from around 20k to 2M ohms. A reasonable series resistor would then seem to be somewhere in the middle of that range, otherwise all your readings would be skewed at one end of the scale.
For example, in this case if you used 10k and the LDR had 20 k resistance in very bright light, then the voltage would be 3.33 V
20000 / (20000 + 10000) * 5 = 3.33 V

Then if it got slightly darker and the LDR was 230 k, you would get:
230000 / (230000 + 10000) * 5 = 4.79 V

And if it was really dark you would get:
2000000 / (2000000 + 10000) * 5 = 4.98 V

You can see from those figures that you will never get a reading less than 3.33 V with this particular LDR and a 10k resistor. Thus a higher value resistor would give you a better range of readings.
However this totally depends on what resistance your particular LDR has.

Ok Nick, but I can't understand why a higher resistor gives a higher voltage than a weaker one. Like, if I put a 300 ohms resistor in the place of this 10k resistor I get a minor voltage, and wouldn't have to be the reverse? A higher resistor "returns" a minor voltage and a weaker resistor returns a higher voltage?

It depends on the order of the resistors, basically. If the LDR is R1, and the fixed resistor is R2, you will get an opposite effect than if they are the other way around. You are sampling in the middle, after all.

After you check the LDR specification you can use an online Ohm's Law calculator and calculate the resistance you need.  Be sure the power rating of the resistor is greater then what is shown.  Less it will smoke more is good but size is also important.
Gil


text:
Multiple IDE instances
I recently moved all in for Linux and have no intentions of going back to Windows, but programming for Arduino is a little annoying as I cannot find a way to have multiple instances.
In Windows you create individual shortcuts for several Arduino IDE instances. When you launch these from the desktop they are autonomous, meaning you can set a board/port combination for each one.
I have yet to find a way to do that in Ubuntu. Is there some form of isolation I can use? I tried using workspaces but they all still see just the one setting.
I do not want to have a bunch of VMs and switch from one to the other unless that is the only option left.
Is there some way I can emulate the Windows autonomous shortcut approach in Ubuntu?

Use UECIDE. I specifically created it to address that problem amongst others.

How do we get that, @Majenko?

@SDsolar http://uecide.org/download.php

@Majenko Thanks, I will give that a try and report back.

@Majenko The .deb link returns a 404. I checked the downloads folder and the only.deb is for an earlier version. Should I be using that?

It should be in the preview folder. Same version pre14.

@Majenko Thanks, but it is just too difficult to get working. It cannot find my-own Libraries. I tried every Path and Folder combinations I could think of and it still keeps saying they do not exist.

There is nothing special about it, it just works.
I strongly suggest to remove everything that is Arduino related from the repositories and have a minimal Java environment installed.
It is no problem to have a gcc build environment together with Arduino though. Even a gcc-avr build environment from the repositories is no problem. But don't install any Arduino or Java-rxtx from the repositories.
You can download the linux version and unpack it in a folder.
Go to that folder where you unpacked the Arduino files and right-click on the 'arduino' file to create a shortcut. Move that shortcut to your Desktop.
Depending on the flavor of Ubuntu that you have, you can also create a starter and fill in the whole path of the 'arduino' file.
Then you can start the Arduino IDE, and just click/activate that shortcut or starter again for another instance of the Arduino IDE. They will work independent of each other. You have to set the right board for each instance of course. A third one or more is also possible.
If you have trouble with shortcuts or starters, then you can even open a terminal and go to the unpacked files, type "./arduino" to start it. Open an other terminal (or new 'tab' in the terminal) and do the same.
You don't have to makes copies of the Arduino files, you don't have to make multiple shortcuts or starters. Just start a new instance by activating the shortcut or starter once more.
I recommend to use only the newest version (at the moment 1.8.3). But if you need to run an older version then you can download and unpack older versions in seperate folders. Be careful that you can not run different versions of the IDE at the same time. The Arduino IDE before 1.6.x differs too much from 1.8.x. All of them share the same ~/.arduino15 folder with settings and downloaded files, which can cause trouble when running a new version, then an older version and then a newer version again.

Thanks, I will try UECIDE first then attempt your suggestions, but right now, they sound a little out of my current knowledge level with Ubuntu.

Thanks, I have that working for two version and that will do fine for now. The UECIDE thing is not working at all well and I can't be bothered trying to mess with it any longer.

The term 'version' could be confusing, I have added more explanation in my answer about 'version'.

@LookAlterno ha ha ha, that doesn't make sense at all. Starting a shortcut twice is all that is needed. The rest is explanation how to get the Arduino IDE working in linux properly.


text:
Driving a stepper motor using ESP8266
I have a stepper motor, and a Uln2003a stepper driver, which is connected to an ESP8266.
The ESP8266 is powered via USB, and the stepper motor is powered via the driver, which is then powered by an external power source, providing it a bit more than 12 volt. When powered on the LED D1 and D2 lights red.
Pins D0, D1, D2, D3 are used for input signal for the drive, the stepper board.
Everything should be connected correctly, but for some reason I am not able to make my stepper motor move. It doesn't react on any of my commands - why?
I suspect that the logic level might have to be 5v instead of 3v. But I've seen stepper motors being driven by an ESP before. So why does this not work? Any suggestions?
Any ways to debug?
Code:
esphome:
  name: steppermotor
  platform: ESP8266
  board: d1_mini

wifi:
  ssid: "ssid"
  password: "password"

# Enable logging
logger:

# ESPHome configuration
api:
  services:
    - service: control_stepper
      variables:
        target: int
      then:
        - stepper.set_target:
            id: my_stepper
            target: !lambda 'return target;'

# Example configuration entry
stepper:
  - platform: uln2003
    id: my_stepper
    pin_a: D0
    pin_b: D1
    pin_c: D2
    pin_d: D3
    max_speed: 250 steps/s

    acceleration: inf
    deceleration: inf

Do the pins, that you use for controlling the driver, are set correctly? The datasheet says, that it can work with 3.3V logic input voltage. I'm not familiar with that kind of code. Where are the functions defined, that actually control the output pins?

the code is part of the https://esphome.io/components/stepper/index.html

I am pretty sure about the pins...  I don't know whether picture would help or?

Mhh, I don't think I can help with the code. Haven't seen that before. The pins are just connected straight to the 4 input pins of the driver. Not much to fail there. The LEDs on the driver will light depending on wether there is a HIGH voltage level on that pin. If nothing happens I would think, that either the pins are not set by the code, or your driver is dead. You can test the latter by connecting the 4 phases one by one to 3.3V. If the LEDs light up correctly, the error must be in your code.

From your code I guess, that you try to control the stepper via an API. How do you call to this API? Do you construct your own call string, or do you have some kind of UI on that site of the project (ESPHome)?

I hope there must be an inbuilt pull-up resistance for each GPIO registers of ESP. Test like this and post your observation: 1. Don't connect anything(ULN2003 jumper wires) to your ESP and check the GPIOs you selected whether they are floating or not. If no float in reading then it's fine. 2. Connect the load and test the GPIOs are floating or not.

use a multimeter to see if the pins do what you expect (without connecting a driver).  once you have that, add the driver (but no stepper motor) and see what the pins for stepper coils are doing.  If it passes that, measure which coils are actually connected on the stepper and check that those match the driver.


text:
Connect 9 V battery to Arduino Mega 2560 directly?
Is it safe to connect a 9 volt battery to an Arduino Mega 2560 directly to power it?

What do you mean by "directly"?

Means the +ve terminal of battery attached to vin of arduino and -ve to ground. No extra circuit require for voltage adjustment.

Yes. On this page, you can see that you can safely connect 7-12V to the VIN pin.
Furthermore, you can simultaneously connect the USB; your Arduino will automatically draw power from the appropriate source.
Note that the power supply jack pin is connected to the Vin pin through a diode. Do not connect a battery and an external power supply, since a sufficiently high power supply voltage will try to charge your battery, which may be bad news for the battery.

The Vin pin is NOT the same as the power supply jack pin. They are two separate circuit nodes in the Mega schemating. Diode D1 separates the two nodes, causing a 0.7V drop when forward biased. ..... The Arduino will NOT always draw from the appropriate source. If the battery voltage is greater than the Vjack - 0.7V, the Arduino will draw mostly from the battery instead of the adapter (ac-to-dc converter), which would frequently be the appropriate course. ..... The first sentence is correct though.

Thanks a lot, I overlooked that diode. I just happened to know that the PSU pin could supply for the vin pin.

I don't want to be hypercritical, but I don't want to mislead anyone either. The diode is a smart protection to design in, but the diode itself is not smart. I also find that constantly disconnecting and connecting a header is cumbersome and if plugged into the wrong pins (by a student still learning) it can damage the board. That's why my answer suggested using the power jack. (No one like the sacrificing of an adapter to the cause though. :) )

This answer suggests the power jack as well, noting that it's connected through a diode (which comes at the price of not being able to put a large load in parallel to the arduino due to the heat production in the diode). I still don't understand why you would want to kill a power adapter to get a $1 plug.

@DouglasDaseeco Pin and sleeve diameters are invariably listed, and are easy to measure using a caliper; sleeve length usually matches, and does not really matter. Any decent electronic parts shop has them in stock, starting at around €0.70. I'm not saying you can't destroy your transformers for a simple plug, but I find it ridiculous to state that as a baseline. It's like saying you need to demolish a second hand car to get new brake calipers - it could be useful at times, but it's hardly the 'normal' way of car maintenance.

Yes.
Batteries are acceptable power sources for the Arduino Mega and other Arduino boards.  I've used them for years for various applications where access to AC is inconvenient, impractical, or nearly impossible.
The Mega page on the Arduino site  also explicitly permits battery power.
Helpful Guidelines
Here are some important criteria to meet.

The Voltage is within the published range for the Arduino model you are using, which is 7 to 12 Volts DC for the Mega 2560
The positive of the battery supply connected to Vin (NOT any of the other power pins)
The negative of the battery supply is connected to Gnd
Critical applications don't run under the assumption that the battery will never drop below the required 7 Volts
The header is never plugged in backwards or in the wrong location, which would likely damage the Arduino circuitry

Connection Safety Using Plug and Jack
If you are connecting and disconnecting the Arduino from your battery frequently or you just want .
See the Power section of the page to make sure you never plug in the header wrong, you can connect your battery supply to the Arduino board's existing power jack.  When connecting a battery supply to an Arduino compatible plug, you can ensure that the plug's inner conductor is positive in Voltage relative to the outer sheath using a Voltmeter.
Battery Use in Robotics and Flight Control
A 9V battery will eventually drop in Voltage below 7V, upon which the operation of the board may fail at any time, so you may want to add more 9V batteries in parallel to extend your battery supply's life 1.
Another approach common in robotics or flight control applications, to preemptively avoid erratic behavior as the battery drains below operational thresholds, is to use the low voltage detection features of the CPU.  The Atmel CPU used by the Arduino Mega 2560 has a Brown-Out Detection feature.  The Atmel CPU for the Due and other boards have under-voltage detection too.
A simpler approach for critical applications is a resistor divider on an analog input is another related approach.
.....
[1] Batteries may vary in Voltage when purchased, but some small variance above or below 9V hurts neither the batteries nor the Arduino.  They will equalize themselves without dissipating (wasting) much energy, so you will get close to N times the battery life, where N is the number of 9V batteries in parallel.  See this Electronics StackExchange Q&A and this battery company article for more information.

DO NOT CONNECT IT TO Vcc, CONNECT IT TO VIn.
By connecting it to VIn, your 9V will go from the battery, though the VReg, and then to your Arduino. This is what you HAVE to do. By connecting it directly to the Arduino Vcc pin, you are basicly frying it.
Note that once the battery has gone bellow 7V, it might start getting unsafe because you are not giving the Arduino enough power.

The bit about overclocking makes no sense.

You are not overclocking anything, the clock speed is fixed at 16MHz. You are generating a small amount of heat, but this is produced in the voltage regulator, nowhere near the processor.

@jwpat7, what I really meant was that you are keeping the clock speed at 16MHz, but not supplying enough power to power the Arduino at such speeds. Ain't that somewhat the definition of overclocking?

..No it really isn't xD supplying not enough voltage might heat up an LDO regulator, and if you're really unlucky, it might heat up your MCU, but generally just causes undefined behaviour like random resets. Overclocking is an entirely different thing, and supply voltage is hardly the defining factor there.

@DatHa, overclockers typically raise the cpu voltage, instead of lowering it, and typically run the cpu at a higher frequency than it's rated for.  See eg wikipedia Overclocking article:  “Overclocking is configuration of computer hardware components to operate faster than certified by the original manufacturer [...] Commonly, operating voltage is also increased to maintain a component's operational stability at accelerated speeds.”  Granted, if frequency stays constant as voltage drops, the cpu ends up running faster than rated for given voltage.