text:
Measuring the battery level powering the arduino
I would like to power my arduino nano with a 9V battery, but I would also like to measure the voltage of the battery to know its charge level.
Can I use the MAX471 Voltage Current Sensor module by connecting the VIN pin to my battery and VOUT to my arduino ?

https://hackaday.io/project/25461-reading-the-max471-sensor-module, also https://github.com/wisewolf/Arduino-Power-Meter.

what kind of a 9 V battery?

If you only need to measure voltage, why not use an Arduino A/D input?  All you need to do is connect a voltage divide across the 9V terminals to divide down to the A/D range.  Use big resistors in the 100K to 1Meg range for low drain.

@Boggyman: If there are other analogRead channels active, 100k to 1M might be a bit high to load the ADC in time. An additional capacitor in parallel to the voltage divider low side might help...

@jsotola This is a 9V GF22

@Boggyman when you talk about ADC you refer to this module : ADS1015 ?

No, I'm referring to the analog inputs that are already included on the Arduino, that you can read with analogRead

@Boggyman Do you think this setup is correct? R1 = 9kΩ, R2 = 1KΩ https://ibb.co/BqGZCBS

That would work, but it's not optimal.  It would divide the 9 V battery down to 1 V, which is wasting 4/5 of the 5 V A/D range.  Also, the total resistance is only 10 K, which is a continuous drain on the battery.  I'd suggest something like R1 = R2 = 100 K to give 4.5 V and drain less current.  Depending on your overall application, you may be able to use 1 Meg as long as you are not using multiple A/D channels as @DataFiddler mentioned.


text:
Listening Serial Ports
guys. I need your help. I have 6 Serial Channels and I need to listen this channel and be sure which channel is working? How can I do that? Can I listen this channel by using digital inputs? Or Do I have to use a devices which has a 6 Serial ports? Like 2 Arduino Mega?

Are they TTL UART or true RS-232?

They are working on RS-232 level. I am going to use RS-232 TTL Converter

And you don't care about what the data is, only if there is data?

Yes, exactly. I just need to check is there data

Possibly a better way to ask the question - is all that is necessary it to see electrical activity on the RS232 Data Receive line?  No matter if it makes sense?  Even if it is noise?   Then the answer might be to use external latching registers and sample the registers using an Arduino. But if we need to make sense of the data, then it may be best to use 6 Arduinos to monitor 6 RS232 serial inputs using the HW UART in each Arduno.  Which is it?

For your needs you don't need actual UARTs. You can do it all with normal GPIO pins and one (or more) interrupts.
UART communication is characterised by having a "start bit" at the beginning of all bytes. That is, in TTL terms, a transition from HIGH to LOW. You just need to look out for that transition.
You could:

Use Pin Change interrupts on 6 pins to monitor for any FALLING transistion, or
Use one interrupt pin with a wired OR of all the signals along with individual pins for each signal to determine which triggered the interrupt.

To determine "is it active" you just need to know that an interrupt has occurred and which pin triggered it, and has that been seen within a certain time period (to be decided by you).

source: Stack Exchange

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

sort: votes


text:
Serial communication detect
guys.
I am workin on a project. I have two channel for Serial RS232 communication. Main and Stand-By channel. If Main channel has some problem and, cannot communicate for 15 seconds then I want to start Stand-By channel communication. How can I do that? I want to listen to channel's RX with Arduino. I think I can use MAX 232 for Serial to TTL convert. Can I listen to channel's RX with Arduino then Can I decide which channel should work?
Thank you,guys..

You could look to see if the signal is toggling. If it hasn't toggled, i.e. flatlining at logic 1 or logic 0, for more than 15 seconds, then switch to the other comms link.

If it is important to get information from one point to another, you might try a physical layer and protocol layer that is more robust than RS232.  However, if you are in the mind set of learning, the I encourage you to design in layers or robustness on top of RS232.  Such as constant pining, error detection, error correction and protection switching.

Assuming there are not large groups of data but mainly control have you looked at CAN, it is a very robust interface.

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


text:
Convert float to byte, from Arduino to Raspberry Pi i2c
I'm trying to send the temperature value from the DHT sensor to a raspberry pi through I2C.
Which is the best way to do it?. The temp value is a float, and I think I have to convert it to byte and send that with Wire.write() to the raspberry, is that right?.
Right now I'm sending bytes from the raspberry (with Python) to the Arduino (C++):
Python:
from smbus import SMBus
import time

address = 0x8
bus = SMBus(1)

While True:
  bus.write_byte(address, 4)
  time.sleep(1)
  print(bus.ready_byte(address))

Arduino code:
#include <Wire.h>
#include <DHT.h>
...

void setup() {
  dht.begin();
  Wire.begin(0x8);
  Wire.onReceive(receiveEvent);
}

void receiveEvent () {
  float temp = dht1.readTemperature();
  delay(1000);
  byte tempByte[4] = {temp, 0, 0, 0};
  Wire.write(tempByte[0]);
}

So the raspberry is printing 0.
Thanks for any help.

Please remove the delay from the onReceive callback function. It is executed inside an ISR. Delay doesn't work there

First of all, if you want the Arduino to send data as a slave, it should
do so onRequest(), not onReceive(). Thus:
void setup() {
    Wire.begin(0x08);
    Wire.onRequest(handleRequest);
}

Next, as pointed out by chrisl in a comment, you should not delay within
the onRequest handler. I would go further and say that you should not
even call dht1.readTemperature(), as that could take too much time to
be done in interrupt context. Instead, have the main loop query the
sensor periodically, and have the latest reading always available:
volatile float temperature;  // latest valid reading

void loop() {
    float new_temperature = dht1.readTemperature();
    noInterrupts();
    temperature = new_temperature;
    interrupts();
    // ...
}

Note that the latest value is updated with interrupts disabled. This is
to avoid a data race that could happen if the Arduino receives a request
while it is in the middle of updating the value. Notice also that
interrupts are disabled during a very short time: just the time needed
to update the variable.
Lastly, to send the data, you can use the version of Wire.write() that
accepts a buffer of arbitrary length:
void handleRequest() {
    Wire.write((uint8_t *) &temperature, sizeof temperature);
}

The temperature will be sent LSB-first, as a float, formatted as per
IEEE 754. The Raspberry Pi should be able to digest it in this very same
format.

Thank you very much Edgar!!!.
I'm trying now to read the IEEE 754 value from the Raspberry Pi, using Python3, but no success so far. I'm new to these technologies so sorry for my ignorance. With Python 3 I'm reading this from the bus with:
float bus.read_byte_data(address, 4)  # this returns an array like: ["205","104"] when the temperature value is 25.20  float bus.read_byte(address)  # this returns random numbers of 3 digits, like 204, 104, etc.
Not sure if Python3 is the right choice here, maybe you could recommend something else better. Thanks again.

I don't know Python, and it's off-topic here. If you forcibly set temperature to 25, you should read the bytes 0x00, 0x00, 0xc8 and 0x41, in this order. How you reassemble these on the PC is a question for another site.


text:
64 led strips and 8 shift registers (connected to 64 sensors) connected to 5V and ground of arduino
I have connected 64 led strips and 8 shift registers (connected to 64 sensors) to 5V and ground of arduino. Voltage received at led strip is 3.1V and at registers is 3.2V. I plan to add an led display as well a small buzzer to it. Can I connect it to the same 5V? What should I make sure in this in terms of voltage supply so that there is no less supply as well loss of power? What if I add a 9V battery instead?
Note: I am just a beginner in this topic.

How big are the LED strips? You do know you can't draw more than 500-800mA from the 5V pin, don't you?

I guess you are currently powering all this through a USB port on your PC. You are lucky if you haven't fried anything on the Arduino. When the 5V pin goes down to 3.1V this means that either you have fried the power electronics or you are currently totally stressing the power supply out. Power supplies, which are overloaded often drop the voltage significantly, or just fail outright.
All the LEDs, shift registers and sensors draw current. With this much LED strips you can easily get into the territory of many amps of current needed for driving them (depending on the number of LEDs and the current draw of each LED). A PC USB port will only provide 500mA by default. An Arduino can handle a current output from the 5V pin of about 1A, including the current, that the Arduino itself needs. So lets say 800mA. When you provide power through the barrel jack this also depends on the voltage of your power supply. The linear voltage regulator dissipates the voltage difference to 5V as heat, so supplying a higher voltage means more heat, means it can handle less current.
What to do now:

You need to power your LED strips, shift registers and sensors directly from your power supply. The current for them should not go through the Arduino. If you use a power supply with a higher voltage than 5V, you need to buy a voltage regulator for 5V that is capable of providing the total needed current (+ at least 20% headroom to be safe and reduce heat). Go for a switching "buck" converter type, not for a linear converter. They are way more efficient and provide less heat. There are ready-to-use modules available on the typical sides (for example the one named like the biggest river). Often they have a small potentiometer on them, which you can spin with a small screwdriver to set the wanted output voltage (here 5V).
Make sure, that the used power source is actually capable of providing the total needed current. For this you first need to calculate how much current the project will draw. For example: Standard addressable LED strips with WS2812 will draw 60mA per LED when on full brightness white. Multiply with the number of LEDs to get the total current for them. GO through all components of your project and write down the current draw (look at the datasheet for such info). Add it all up. Then get a power source (and if needed voltage regulator) that can handle at least 20% more than that.

What if I add a 9V battery instead?

As written above you will need an external voltage regulator for your project. Also: If you mean the standard 9V block batteries, then just forget it. They are not meant for high power applications and can only provide very low current. You should look in the direction of LiIon or LiPo batteries. When you use them please also buy a fitting charger module (since these are rather particular about how they want to be charged).
But before choosing a battery you first need to know how much current your project draws. Then you need to set a time range how long the project should run on the battery without charging. Then you can choose a battery based on that.

Then as per your suggestions, total current supply or Icc of each component used in this project adds to 4436mA. Should I multiply it with 4 to be able to run the circuit for 4 hours?

Yes, then you have the needed battery capacity in mAh. Also adda bit headroom on top

By headroom on top, do you mean some extra mAh of battery for better life? 5V needs to be supplied to the circuit which buck converter will do the job. Is output current of battery a factor too or just voltage and mAh are required to decide a battery for this project.

Yes, I mean some extra mAh. You need a buck converter which can take the batteries voltage, can convert it to 5V and can provide the needed current. Thats enough info to find a fitting one. You can even use multiple of them if you don't find one which this current rating. Make sure its current rating is higher than needed (you don't want to drive it at its limit the whole time).

About battery current: you need to transmit power, meaning voltage multiplied by current. With lets say 5A at 5V you have 25W to transmit. When the battery is higher voltage than it need to provide less current. For example: if the battery is 10V, then for 25W you only need 25W/10V=2.5A. The battery needs to be able to provide at least that amount of current without dipping the voltage too much.


text:
How can I clear two FastLEDs strip ws2812b separately? One strip is connected to pin 7 of UNO and other strip to pin 6 of UNO
The power supply is external. I want to clear one strip say pin 7, and meanwhile i dont want other strip say pin 6 to switch off...I use
FastLED.clear();
FastLED.show();
But it clears all the led strips connected to pin6 and pin7. What is the code to switch off only one strip?

You can use two CLEDController instances, which you can control separately, and by using the clearLedData you can clear either one or the other LED strip (depending on the CLEDController instance).
Below is the code I copied from
https://forum.arduino.cc/t/xrads-fastled-fastled-clear-question/693569/8
which contains more info:
#include <FastLED.h>

#define COLOR_ORDER GRB
#define LED_TYPE WS2812B

#define DATA_PIN 9
#define NUM_LEDS 26
CRGB leds[NUM_LEDS];

#define HEADLIGHTS 10   //headlight led pin
#define NUM_HEADLIGHTS 2
CRGB leds2[NUM_HEADLIGHTS];

CLEDController &ledController = FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
CLEDController &headlightController =   FastLED.addLeds<LED_TYPE, HEADLIGHTS, COLOR_ORDER>(leds2, NUM_HEADLIGHTS);

void setup() {
  ledController.setCorrection(TypicalLEDStrip);
  headlightController.setCorrection(TypicalLEDStrip);

  ledController.clearLedData();
  headlightController.clearLedData();
  FastLED.show();
}

void loop() {
}

Thanks a lot Michel it worked wonderful!!


text:
Arduino uno spi sck not working
I am trying to verify sck output on my arduino uno. I don't have oscilloscope so I loopbacked miso to sck and tried Executing int rx0=SPI.transfer(5) while printing this using Serial.printrx0) it is giving 255.Whether this is expected output?

I'd expect you'll get all bit with the same value. You can try other SPI_MODES and you probably get 0x00 for two of them..  However you could use loopback between MOSI a MISO (you can expect 1B delay)

Hi KIIV, THANKS for responding.. I tried all the SPI mode and I got 255 as output, means all the bit as 1 in the byte. Whether it is right result?whether I can say my sck output is normal? Thanks

You could instead send SCK to T1 (pin 5), configure Timer 1 as a counter, and use it to count the clock pulses.

As suggested by KIIV and myself, you can test the SPI port by:

connecting MOSI to MISO and checking if you receive what you send
connecting SCK to the timer input T1 and counting the clock pulses.

Below is a sketch that performs both tests:
/*
 * Test the SPI port.
 *
 * Connect:
 *   MOSI (11) to MISO (12)
 *   SCK (13) to T1 (5)
 */

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

    // Configure SPI port.
    DDRB |= _BV(PB2)   // SS (digital 10) as output
          | _BV(PB3)   // MOSI (digital 11) as output
          | _BV(PB5);  // SCK (digital 13) as output
    SPCR = _BV(SPE)    // enable port
         | _BV(MSTR);  // master mode

    // Configure Timer 1.
    TCCR1A = 0;          // normal mode
    TCCR1B = _BV(CS10)   // count rising edges of T1 = digital 3
           | _BV(CS11)   // ditto
           | _BV(CS12);  // ditto
}

void loop() {
    TCNT1 = 0;  // clear timer
    uint8_t data = random(256);
    Serial.print(data);
    Serial.print(" -> ");
    SPDR = data;  // send
    delay(1);
    if (bit_is_set(SPSR, SPIF)) {  // transfer complete?
        Serial.println(SPDR);
    } else {
        Serial.println("nothing received");
    }
    Serial.print("    clock pulses: ");
    Serial.println(TCNT1);
    delay(1000);
}

It should print:
167 -> 167
    clock pulses: 8
241 -> 241
    clock pulses: 8
217 -> 217
    clock pulses: 8
[...]


text:
I can't show the button pressed on the GLCD ST7920?
I have a small project that i want to show my keypad pressed on my GLCD but when i pressed keypad, even on serial it is fines but on GLCD it can't show my characters. Could you tell me what the problem and what should i do to solve!.  my GLCD library is BasicGLCD!

#include <Keypad.h>
#include <EEPROM.h>
#include <basicGLCD.h>
basicGLCD GLCD;
/*long four = 0;
long three = 0;
long two = 0;
long one = 0;
*/
int adress = 0; // gia tri dia chi luu du lieu
const byte rows = 4; //so hang
const byte columns = 4; // so cot

int holdDelay = 100; // thoi gian tre de xem la nhan 1 nut de tranh nhieu~
int n = 3; //
int state = 0; // neu state=0 khong nhan, state=1 nhan thoi gian nho , state = 2 nhan giu lau
char key = 0;
int i=1;
//dinh nghia cac gia tri tra ve
char hexaKeys[rows][columns] =
{
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'},
};

byte rowPins[rows] = {4, 5, 6, 7}; // cách nói chan Arduino
byte columnPins[columns] = {12, 13, 2, 3};// cách nói chan Arduino

//cài đặt thư viện keypad
Keypad keypad = Keypad(makeKeymap(hexaKeys), rowPins, columnPins, rows, columns);
//////////////////////////////////////////////////////
void setup() {
  Serial.begin(9600);//bật serial, baudrate 9600

 // GLCD.setCursor(4, 0);
  //GLCD.sendString("WELCOME....");

  //////
  GLCD.setDataPins(23,25,27,29,31,33,35,37);
  GLCD.setRSPin(A2);
  GLCD.setCSPins(A0, A1);
  GLCD.setENPin(A4);
  GLCD.setRWPin(A3);
  if(GLCD.init() != 1) {
    Serial.println("You have to set all pins");
    return 0;
  }
  else {
  GLCD.sendString("   WELCOME  ");
  GLCD.setCursor(10, 0);
  delay(500);
  GLCD.clear();}
  //////////////////////////////////////////

 GLCD.setCursor(0, 1);
 GLCD.sendString("Loai IVT: ");
 GLCD.setCursor(0, 2);
 GLCD.sendString("TG mau : ");
 GLCD.setCursor(0, 3);
 GLCD.sendString("CSCD :");

}
//////////////////////////////////////////
void loop()
{
  char temp = keypad.getKey();
  if ((int)keypad.getState() ==  PRESSED) {
    if (temp != 0) {
      key = temp;
    }

    //xem kq
  if(temp)
    {if(temp == '+')
    {GLCD.clear();}
    if(temp == '=')
    {i=i+1;}
    GLCD.setPage(RIGHT);
    GLCD.setCursor(5,i);
    GLCD.sendData(temp);
    ;
    }
 delay(500);
}
}

do you see the word WELCOME on the LCD?

Yes, it shows WELCOME first and "Loai IVT", "TG mau","CSCD " after, but when i press keypad to sent the number in each parameters  but it doesn't work.  it just shows any dot in the GLCD

add debugging code to your sketch ... use Serial.print() to determine what the code is doing

Well , in serial i don't see anything, the keypad code is from example it work well when indepentdent but when it has GLCD , i can't see anything on Serial monitor


text:
Grove LCD display not working with arduino rev 2 wifi (Unknown error at address 0x3E)
I am trying to connect Grove 16x2 LCD (White on Blue) to my Arduino uno rev 2 wifi.
So far, I've tried hd44780 library's ioClass examples, but nothing worked. I've then decided to scan ports and when LCD was connected to rev 2 SDA/SCL pins I've got (Unknown error at address 0x3E). So it recognizes that something is connected, but doesn't recognize the LCD. I've also tried to run I2CexpDiag, which also returned "Unknown error at address 0x3E".
I tried the same LCD with Arduino UNO and mkr1010, both work flawlessly. I've also tried connecting the SDA/SCL pins to A4/A5, but nothing there either.
Any ideas what could be the problem?

https://wiki.seeedstudio.com/Grove-16x2_LCD_Series/ > Step 1. Download the Grove-LCD RGB Backlight Library from Github.

Just tried it, tried a couple of examples, but nothing comes up on the screen.

Uno WiFi has some on-board I2C devices. run the I2CScanner sketch

Yes, it does recognize something on 0x60

does the scanner show the address of the LCD?

Yea, like I've mentioned, I get an error "Unknown error at address 0x3E", which is the address of the LCD. However the LCD works with other boards flawlessly

You are not alone https://forum.arduino.cc/t/issue-with-i2c-between-arduino-uno-wifi-rev2-and-grove-16x2-lcd/609423/2 Except for the base shield switch, no answer is there. Here https://forum.arduino.cc/t/surenoo-rgb-i2c-lcd-unstable-i2c-communication-solved/666902/67 a VERY long thread on a similar LCD/problem. Maybe worth trying this library https://werner.rothschopf.net/202009_arduino_liquid_crystal_wire_en.htm with the Grove settings.

Yea, have tried that library, but no luck


text:
Digispark Rev.3 Kickstarter ATTiny85 using all 6 pins
i have some trouble to use i2c and the other pins at the same time.
im tring to control the attiny over i2c with a arduino and the attiny should control a 28byj-48 stepmotor.
i started to setup the i2c connection pin 0 and pin 2 is use for that. it is working fine but then i connected the stepmotor driver on pin 1,3,4,5 after connecting the 5 pin i lose my i2c connection.
here is the code from the attiny, nothing special
#include <TinyWireS.h>                // wrapper class for I2C slave routines

#define I2C_SLAVE_ADDR  0x29            // i2c slave address (38)
#define A 1
#define B 3
#define C 4
#define D 5
#define NUMBER_OF_STEPS_PER_REV 512

void setup(){
  pinMode(1,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  TinyWireS.begin(I2C_SLAVE_ADDR);      // init I2C Slave mode
}

void loop(){
  byte byteRcvd = 0;
  if (TinyWireS.available()){           // got I2C input!
    byteRcvd = TinyWireS.receive();     // get the byte from master
    //Blink(byteRcvd);           // master must wait for this to finish before calling Wire.requestFrom
    //byteRcvd += 10;                                                    // add 10 to what's received
    //TinyWireS.send(byteRcvd);           // send it back to master

    //             Blink(1);                  // show we transmitted
  }
}

There is no such Digispark board as the Rev 3. There was going to be, but there was a mistake, so they went straight from Rev 2 to Rev 4. However unscrupulous Chinese counterfeiters are making "Rev 3" boards.
So... your mileage may vary since the components used on there could be of any dubious quality.
But to your problem: P5 is also the RESET pin.  If the fuses on that chip are set correctly then it can be used as an IO port. But being a counterfeit, who knows what they set the fuses to?
But if you do change the fuses you will have to rely on the power-on reset (plugging it in) to trigger uploads.

As an addition to Majenko's answer I can report having used many of the "Rev.3" counterfeits, every single one came with chip default fuses thereby reset enabled.
You can set the RSTDISBL fuse with your Arduino, plus update the micronucleus bootloader in the process (freeing 0.4k).
Keep in mind setting this fuse will disable ISP programming, so you will need a working bootloader to reprogram the chip unless you revert it via HV programming.


text:
How to avoid stepper motor to revert its spin direction from code
I'm working with an Arduino UNO and a stepper motor NEMA 17. I would like to know how to avoid the stepper motor to revert its spin direction when I apply a load in the shaft. The motor works as I spect without any load, here is the code I'm using.
I think I'm missing something in the code, not in the connections.
// Define pin connections & motor's steps per revolution
const int dirPin = 2;
const int stepPin = 3;
const int stepsPerRevolution = 45;//115

void setup()
{
  // Declare pins as Outputs
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
}
void loop()
{

if(true){
    // Set motor direction counterclockwise
  digitalWrite(dirPin, HIGH);

  // Spin motor quickly
  for(int x = 0; x < stepsPerRevolution; x++)
  {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(700); //670
    digitalWrite(stepPin, LOW);
    delayMicroseconds(700); //670
  }

  }
}

External voltage: 12 v 3A max
Motor's datasheet: 17HS4401S
Driver: DRV8825
Guide:https://lastminuteengineers.com/drv8825-stepper-motor-driver-arduino-tutorial/
Sketch

What's the load on the motor? Did you set the current limit? Have you checked the fault pin?

The load on the shaft is 0.3 kg cm, I’ve already set up the potentiometer (this is why the motor works fine) and since it’s not stop working the driver is always running ( no fault) it only reverse its spin direction

How is the load connected to the shaft? In other words are you sure it's the motor and not the mechanicals? Have you tried with something needing lower torque? I'd also double-check the coil wires--don't just rely on wire color.


text:
Convert from raw data to float from DDSU666-H

Hi professers, i am trying to read the data from DDSU666-H ( Smart metter) CHINT using modbus RTU, i only get the raw data but i don't know how to convert it to float , in the code below is about Voltage , real data is 233,4V but in the serial is like this, can some one help me to convert this one to float 233,4V, thank you so much!

 Here is my code, i get it from modbusmaster library.
/*

  RS485_HalfDuplex.pde - example using ModbusMaster library to communicate
  with EPSolar LS2024B controller using a half-duplex RS485 transceiver.

  This example is tested against an EPSolar LS2024B solar charge controller.
  See here for protocol specs:
  http://www.solar-elektro.cz/data/dokumenty/1733_modbus_protocol.pdf

  Library:: ModbusMaster
  Author:: Marius Kintel <marius at kintel dot net>

  Copyright:: 2009-2016 Doc Walker

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

*/

#include <ModbusMaster.h>

/*!
  We're using a MAX485-compatible RS485 Transceiver.
  Rx/Tx is hooked up to the hardware serial port at 'Serial'.
  The Data Enable and Receiver Enable pins are hooked up as follows:
*/
#define MAX485_DE      50
#define MAX485_RE_NEG  52

// instantiate ModbusMaster object
ModbusMaster node;

void preTransmission()
{
  digitalWrite(MAX485_RE_NEG, 1);
  digitalWrite(MAX485_DE, 1);
}

void postTransmission()
{
  digitalWrite(MAX485_RE_NEG, 0);
  digitalWrite(MAX485_DE, 0);
}

void setup()
{
  pinMode(MAX485_RE_NEG, OUTPUT);
  pinMode(MAX485_DE, OUTPUT);
  // Init in receive mode
  digitalWrite(MAX485_RE_NEG, 0);
  digitalWrite(MAX485_DE, 0);

  // Modbus communication runs at 115200 baud
  Serial1.begin(9600);
  Serial.begin(9600);

  // Modbus slave ID 1
  node.begin(12, Serial1);
  // Callbacks allow us to configure the RS485 transceiver correctly
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);
}
void loop()
{
  uint8_t i, result;
  uint16_t data[2];
  union
  {
    uint32_t j;
    float f;
  } u;
  // Read 16 registers starting at 0x3100)
  Serial.println("-----------------------");
  result = node.readHoldingRegisters(0x2000, 2);
  if (result == node.ku8MBSuccess)
  {
    for (i = 0; i < 2; i++)
    {
      data[i] = node.getResponseBuffer(i);
    }
    Serial.println(data[0]);
    Serial.println(data[1]);
    u.j = ((unsigned long)data[1] << 16 | data[0]);
    Serial.println(u.f);
  }

not a question about Arduino ... it is a general programming question at best

please remove the picture of text and add the actusl text ... text in a picture cannot be copied for analysis

you mean " hi professer" text ?

no, the printout of the readings ... it should be text, not a picture

Could you share your wiring between rs485 module and ddsu please ?

Seems the data sheet does not specify the endianness. Or maybe it does,
but you are not showing it. From the numbers you get, it appears that
the floats come in big-endian order, whereas your code assumes
little-endian.
Change the assignment of u.j as follows:
u.j = ((unsigned long)data[0] << 16 | data[1]);

oh,, i actually read voltage register successfully, but with the frequentcy ( 0x200E), it doesn't work , haha

Hello expert, why i can't read the frequency and power active register while i can read voltage and current ?

@HẢIHỒ: No idea. Check the documentation of your device.


text:
My arduino gives me several avrdude erros
For school we program an arduino with visual studio and micro visio. Since a few days ago my arduino wont run the code of the arduino. At first it didnt give any errors until i tried to upload a code with arduino ide itself.
avrdude: ser_open(): can't set com-state for "\.\COM3"
Or saying that the acces is denied. I confirmed that my arduino is the COM3 port. The weird part is that on another pc it works fine. On the laptop where my arduino isnt working i did a loopback test following. https://support.arduino.cc/hc/en-us/articles/360020366520.
This went without a problem. I reinstalled the IDE and drivers but sadly this didnt help either. If i try a class mates his arduino it wont work either. If some one has information on how to fix this problem that would be nice. If there is some extra information needed that wont be a problem either.

The COM port can only be used by one program at a time. Typically, the above error happens if either program (Visual Studio or the Arduino IDE) have the serial console open and you try to program the Arduino using the other.

Thanks for the tip. I will admit at first i didn't do this but after a few times i did close the other and i still got the same problems.

If you connect and disconnect your Uno, the COM3 shows up and disappears, respectively? Also, when you are using Arduino IDE, the visual studio is not running? Check this link if you want to find out if some other process is using your COM port.


text:
Stepper motor with microstep driver
In my project I have to control a stepper motor using arduino and microstep driver, can I control the motor so that it can move 90 degrees then stop for like a second and then move again and repeat that sequence.
Can I do that please help I'm stuck in the code and I couldn't figure it out.

In what code are you stuck? You didn't provide any in your question. If you already have a code, then include it in the question. If not: Have you tried the examples with one of the Arduino stepper libraries (like Stepper or Accelstepper)? Have you tried to understand how they work? If you have problems understanding them: What exactly gives you problems here? We need more information to provide good answers.

Yes I tried with a bunch of code this one work the best for my stepper: https://drive.google.com/file/d/12Esu1wzS0HfXB_lRHbog6yM09OSJ5SSu/view

Of course you can! There are some excellent libraries to control steppers, e.g. Stepper or AccelStepper.
What you describe sounds like basic task that is covered in examples of these libraries. For example, this one: https://github.com/arduino-libraries/Stepper/blob/master/examples/stepper_oneRevolution/stepper_oneRevolution.ino. You only need to set correct pins and tweak delays and rotation angles (if your stepper has 200 steps per revolution, then 90 degrees is 50 steps).

This code is working well for me what could I change to get the motion needed https://drive.google.com/file/d/12Esu1wzS0HfXB_lRHbog6yM09OSJ5SSu/view

What to do with that particular code is a whole different question to what was initially asked. That said, your code looks fine, it probably does 2 revolutions continuously (depends on motor). To change that to 90 deg with pause, change 400 to 50 and add delay(1000); to loop. Also, as others noted, you need to understand your code to make it work, there is no other way.

Thanks I understand it now and It's working. I'm a beginner when it comes to programming, I tried a lot of codes from AccelStepper and other libraries none has worked for me so, I was frustrated and I wrote the question in a hurry. sorry for that and thank you again for the help.


text:
Digital Pins Question
I am new to the world of Arduino and need a little bit of help. I have an Arduino Uno and I am trying to supply 5V to an actuator using the digital pins. It is my understanding that the board I have is capable of doing that. But I can't seem to get 5V from my digital pins.
I would really prefer to not have to use the 5V power pin because I need to supply multiple sources with 5V in an alternating pattern, which I know I can do with the digital pins.
Could I use the analog pins to help with this? Could I supply more power using a battery? Etc.
Thank you in advance.

How much current?

Hi Edgar, I am not sure of the exact current. It is a shape memory alloy wire that I would like to actuate. It normally operates on 5V at 0.24 to 0.38 Amps. Thank you!

I can't seem to get 5V ... what does that mean? ... are you unsure if you get 5 V?

The digital pins of the Arduino are rated to reliably deliver up to
20 mA. Their absolute maximum rating is 40 mA. Anything
above that risks destroying the microcontroller.
If your device is supposed to pull from 0.24 to 0.38 A, that is too
much for your Arduino pins. With such a high current, you are seeing a
significant voltage drop caused by the internal resistance of the output
transistors. Or it could be that you already fried those transistors.

The most common solution is to use the digital output to turn on a MOSFET that supplies separate power to a high-current device that needs more current than the 20 mA that an ATmega328 microcontroller can safely supply.
The MOSFET is chosen based on the desired current and with the need for a logic-level input.
A typical circuit:

simulate this circuit – Schematic created using CircuitLab
D1 is needed for an inductive load like a motor. It protects other components.
You might get away without using the resistors (connecting D1 directly to the MOSFET's gate) but the 10 K "pull-down" resistor R1 ensures that the load is off when the Arduino is powering up. Resistor R2 is probably mainly useful for noisy or high-frequency applications..

Why an IRF530 instead of an IRL530?  Per Figures 1 of https://www.vishay.com/docs/91299/sihl530.pdf and https://www.vishay.com/docs/91019/irf530.pdf the IRL530 is more fully on at V_GS=5V and would do 10x the amps of the IRF530.

@DaveX: No reason other than that's what the diagram editor came up with and I forgot to remove :-)


text:
How to pre-design circuit before buying?
I am wanting to make a simple circuit that takes input from a movement sensor and plays a sound response.
To do this I think an ESP32 microcontroler would be optimal?
But how does one go about identifying parts and making sure they are compatible before buying?
For example I have no idea what sensor, speaker or battery sources to use. How does a total noob go about finding all this out in an efficient way?

Step one: read similar projects and tutorials. Step two: prototype using modules, breadboards, and wires.

Step #1: Steal! Search engines are your friend.
Step #2: (see step #1).

Look for published projects using parts that you want to use or to find out what parts someone else used, and how they connected them & coded for them.
Look up the datasheets for the parts you propose to use and read at least the introductions, to decide if they meet your needs. If you're project is for learning, not going into a bigger project (yet), you may not need this step if someone else's project has shown you the way. When you eventually come to designing your own, this step will be important.
As a beginner, copying from others is really the best/quickest way to 1) make stuff happen; and 2) not (or be less likely to...) blow up parts that cost money and take time to replace.
Once you've built a couple of projects you'll start to see common techniques of coding and of building circuits, that will lead you to more questions. (See step #1 above).
There's more, like learning some basic electrical and electronic theory and practice, if you haven't already, but that can come a little later and will make more sense when you have some hands-on experience.


text:
Does the compiler generate intermediate assembler?
My source files are *.ino, but after compilation there aren't any other files placed in the folder. Does the compiler generate intermediate assembler, and if so, where does it leave them? Or is the machine code available somewhere?

If you switch to a Makefile build or in some other way can customize arguments then you can ask avr-gcc to produce assembler ouput.  2) Alternately you can use avr-objdump to disassemble binary (or with the aid of objcopy, hex) ouput back to assembly mnemonics.  With an original unstripped elf binary objdump may be able to print many symbols (the usual way of producing a list file), but with a raw binary or hex file those are permanently lost.

@ChrisStratton: Thanks. Can you elaborate on 1)? I know makefiles are commonly used by software developers, but I don't have any experience with them.

There are various stock Makefiles you can find online to build an Arduino project with greater control of the details.  Not able to dig one up for you right now.  There may also be ways to customize the IDE's commands, but the IDE has so many other problems I'm not sure it's worth the bother.

You can find Arduino compatible makefiles in the embedxcode repository at http://embedxcode.weebly.com You will probably look at the arduino15avr.mk file in particular. You can change this file to have assembler output save and place where you want it to be.

My source files are *.ino, but after compilation there aren't any other files placed in the folder.

Correct. The Arduino IDE performs compilation in a separate temporary directory, whose location you can see if you enable verbose compilation in the IDE options.

Does the compiler generate intermediate assembler, and if so, where does it leave them?

By default GCC (which the Arduino IDE uses) does not leave intermediate assembly language files on disk. You must pass the --save-temps argument to have it leave them in the current directory, or --save-temps=obj to save them in the output directory.

Or is the machine code available somewhere?

The machine code is available in the .elf and .hex files generated in the temprary directory.

Yes.
Arduino compilation is set up with link-time optimization (LTO), and the assembly files created during C compilation don't contain any assembly code - just the intermediate representation used later in the LTO stage to generate actual assembly code. We want the latter.
It so happens, rather nicely, that the very last time assembler is invoked in the entire compilation process, is to take the output from the LTO stage, and turn it into a whole-application object file.
To get at this assembly file, do the following (on Windows):

Open %LOCALAPPDATA%\Arduino15\packages\arduino\hardware\avr\1.8.3\platform.local.txt (create it if it doesn't exist). Add the following line
compiler.c.elf.extra_flags=-save-temps=obj -fverbose-asm

If there already is such a line there, just add the above options (to the right of =).
Note: If you can't find the folder, look for the following files: boards.txt, platform.txt, programmers.txt. If you find these files in multiple locations, the one you want should be inside your home directory (i.e. not in Program Files or /Applications or /usr), and should be correlated at least partially to the version of Arduino you're using (should you have multiple versions installed).

Build the sketch again.

Look for a file named %TEMP%\cc*.ltrans.s. Each build will create a new such file. If you sort them by timestamp, the newest one is for the most recent build.

Note: The environment variables, enclosed by % signs, are valid in the Windows dialog boxes. You can directly paste such a path into e.g. an Open or Save As... dialog box, and it'll work. Paths with globs (*) will act as filters (IIRC).
To know which exact cc*.s file was generated, add the verbose option to the final binary generator pass:
compiler.c.elf.extra_flags=-save-temps=obj -fverbose-asm -v

Rebuild, and copy-paste all the output from the compilation status window in Arduino to e.g. Notepad++, and search for ar.exe. The sole line that contains ar.exe ends with the name of this cc file:
 c:/users/[...omitted...]/avr/bin/as.exe -mmcu=avr6 -mno-skip-bug
    -o C:\Users\[...]\AppData\Local\Temp\cc3XhU2F.ltrans0.ltrans.o
    C:\Users\[...]\AppData\Local\Temp\cc3XhU2F.ltrans0.ltrans.s

How does the file look? This is a short extract, just to show that both the C source and the assembly are intermingled - and this represents exactly the binary embedded in the .hex file and sent to the target.
.LBE33:
.LBE32:
.LBB34:
.LBB35:
 ;  C:\Users\[...]\Documents\Arduino\sketch_jul01a\sketch_jul01a.ino:29:   pinMode(ledPin, OUTPUT);
    .file 4 "C:\\Users\\[...]\\Documents\\Arduino\\sketch_jul01a\\sketch_jul01a.ino"
    .loc 4 29 0
    ldi r22,lo8(1)   ; ,
    ldi r24,lo8(13)  ; ,
    call pinMode     ;
.LVL55:
 ;  C:\Users\[...]\Documents\Arduino\sketch_jul01a\sketch_jul01a.ino:30:   pinMode(relayPin, OUTPUT);
    .loc 4 30 0
    ldi r22,lo8(1)   ; ,
    ldi r24,lo8(12)  ; ,
    call pinMode     ;
.LVL56:
 ;  C:\Users\[...]\Documents\Arduino\sketch_jul01a\sketch_jul01a.ino:31:   pinMode(ldrPin, INPUT);
    .loc 4 31 0
    ldi r22,0    ;
    ldi r24,lo8(54)  ; ,
    call pinMode     ;
.LVL57:
.LBE35:
.LBE34:
.LBB36:
.LBB37:

This approach also works on Linux and MacOS, except that the paths are slightly different, and path expansion uses different syntax. The two files of concern still are platform.local.txt - a file you must create, since it doesn't exist at first, and the ${TEMP}/cc*.ltrans.s files.

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


text:
Arduino Uno with crystal
Are there Arduino UNO R3s which use a crystal instead of a ceramic resonator?
(Frankly, I don't understand this cheapness: if you really want to save on component cost you can run both AVRs on the same crystal. The 16U2 always has a crystal.)

It would probably be an easy modification if you do it right at the ATmega pins.  Agree it's regrettable they didn't find a way to share the crystal between the two ATmegas.

Related (not duplicate): Does the Arduino Uno have two crystals?

Some of the Freeduino boards use crystals although the newer ones now use a cheaper USB to serial chip (the CH340) instead of the Atmel chip used on the Arduino Uno.
The diavolino is another build-it-yourself board that has a crystal. I am sure there are many others. The ruggeduino is another that uses a crystal and also markets itself as being practically indestructible. Their "How to Destroy an Arduino" is well worth a read for things to avoid doing to your Uno.

It appears that the Arduino Leonardo uses a crystal:

On the Sparkfun site it's the same price as the Uno R3, so I think I'll go for the Leonardo.

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


text:
What are possible issues when moving Arduino to another microcontroller?
When Arduino was conceived AVR was very much the best 8-bit controller available. But we're 10 years on now, and still using the AVR, despite lots of better microcontrollers available, notably ARMs. In particular M0 and M0+ cores are a lot cheaper, yet are a lot faster and have many more features than AVR.
For instance the NXP LPC824 has more serial buses, more A/D channels and higher A/D resolution, is almost twice as fast as the AVR, yet costs 30% less. (Granted, it doesn't have EEPROM, but you can have that for 20 cents.)
So I was wondering if there are particular issues which prevent the use of more modern microcontrollers on Arduino.
One difference may be Vcc, which is 5V for AVR and 3.3V for ARM. But given that more peripherals work at 3.3V this seems more to be an AVR issue than an ARM issue.
PS: I'm aware of Arduino Due, but that one costs twice as much as a Uno. I'm talking about controllers which price-wise can compete with AVR.

M0+ for the win. It seems like you have enough knowledge in the subject, why not just move your project to arm yourself?

There is NO best 8 bit or 16 or whatever bit uC (micro controller).
There always have been "better" ones and there always will be and better changes with your need as well as with time.
If you want or need a faster or more capable processor, use one.
For many tasks the existing AVR processors are very fine indeed.
A number of people are making Arduino-like uC's using ARM right now.
You can buy them 'off the shelf'.
Running "Arduino" code is where issues arise:
If you are willing to run 100% standard Arduino code applications will usually run well on the new uC.
If applications use precompiled libraries and you wish to use eg an ARM it will not run.
If you recompile the libraries and they are written in a compatible language flavor (C or whatever) then they MAY work for your new processor.
If they use assembler then they will not work in essentially all cases.
But, existing 'Arduino' hardware can use the high level language of your choice.
A new processor with a compatible compiler will compile eg C code that runs on Arduino hardware BUT port locations, register control methods etc need to be correctly allowed for.
It gets harder and harder as you try to fit the new giants into the old not-so-giant framework. Somewhere along the way it is easier to give up the attempt and use the Arduino for what it is good for and the 'new' processor where necessary.
Whatever the Arduino did well when new it still does well.
In most cases the speed, peripherals and memory capabilities are entirely fine for tasks that people who wish to use it wish to do.
The main issue is that an Arduino is not something it is not, just as a small family car is not a bus or a sportscar. Use the car where it is useful and use a bus or sportscar when necessary.


text:
Can I change the USB device name of Arduino?
I have several Arduinos connected to my Windows PC, and they appear as follows:

COM7 (Arduino Uno)
  COM11 (Arduino Uno)
  COM13 (Arduino Uno)

So there's no way to tell which is which, and when I want to upload a sketch to one, I have to unplug the others to make sure my code goes to the right one.
Is there a way to change the "Arduino Uno" description?
(I found a similar question but that was about Mac specifically).

You'll have to change the firmware on the usb to serial chip (atmega16u2)

And modify the driver to include the new name.

Here is the current link from @Gerben's Comment https://github.com/arduino/ArduinoCore-avr/blob/1.8.1/firmwares/atmegaxxu2/arduino-usbserial/Descriptors.c#L220

You'll have to change the software on the Arduino USB chip itself, and you may need to modify the drivers for the Arduino USB interface on the computer side.  It's not trivial, and probably not worth it.
However, Windows attempts to use the same serial port for the same devices in the same USB positions, so if you figure out which is which (blinking the LED at different frequencies) then you can mark the USB port itself with the com number that Windows uses when you plug an arduino into it.
If you use a hub, and you move that hub to a different port, the com numbers will change, but if you keep it in the same port, then it too will try to have them match what they have been in the past.
It's an annoyance, but it's a design decision by arduino.cc.  The old FTDI chips kept their assigned com port numbers because they have individual serial numbers and windows would attempt to reassign the same com port to the same chip each time it was plugged in, regardless of its location.  When Arduino.cc moved to a programmed MCU for the USB interface, they chose not to provide USB serial numbers, and thus windows has little option but to try to keep things straight by determining the location in the USB hierarchy that the device is connected, and try to keep com port assignments the same using that method.

"... they chose not to provide USB serial numbers ..." Oh wow. Was any rationale ever given for this?

@IgnacioVazquez-Abrams I've not seen any information from them on this issue.  They probably don't think it's important (the majority of users don't need it) and it does increase the cost as they not only have to program the chips individually, but track arduino serial numbers in some sort of coordinated fashion to avoid duplication. Given the number of knock-offs in addition to the licensed variants, it's a problem not worth tackling without good reason.


text:
Arduino at 20 MHz?
I wonder why Arduino doesn't run at 20 MHz, the frequency the AVR is specified for. Now, running at 16 MHz, we're wasting 20% performance for nothing.
I don't think there are any implications when you replace the 16 MHz resonator with a 20 MHz type, with probably the sole exception for the baudrate in the bootloader. Or is there?
Does anybody know why the Arduino designers chose 16 MHz?

Don't forget to set the fuses when you do this

@portforwardpodcast no need to change the fuses. They are already set to "Full-swing external oscillator".

There's no hardware reason (as far as I'm aware) that you couldn't run a suitable Arduino at 20 MHz. You'd run into minor timing inaccuracies in software though, as the standard Arduino configuration apparently works best if the clock speed is either 8 or 16MHz.
I suspect this is largely for historical reasons. Early Arduino boards were based on chips which only went up to 16 MHz, such as the ATmega8. Using the same configuration for all chips just keeps everything a bit simpler and more consistent.
There is more information here about the timing issues: http://forum.arduino.cc/index.php?topic=158223.0#msg_1186708

Thanks for your answer. Can you elaborate on "exact power of 2"? The 1 second period over which clock pulses are counted doesn't mean anything to a microcontroller, it only knows clock ticks. Overmore, 16 MHz isn't an exact power of 2, that would have to be 16.777216 MHz.

@JorisGroosman Sorry I didn't explain that properly. It's about the way the Arduino core calculates microseconds from clock ticks. This forum topic gives a much better explanation than I could.

You can, and I do.
It's not technically an Arduino anymore, I guess. I made my own board, replacing a resonator on a board will require some fine soldering, but it is definitely possible.
There are some gotchas: Anything time-related (e.g. millis() ) will be run faster than is should - 25% more millis() per second. Also, the bootloader expects 16mhz, so you won't be able to reprogram it at this speed. I purchased a USBASP programmer - it hooks into the 2x3 pin grid on one side of the board, and lets you reprogram it without the bootloader (this is how the bootloader is put on in the first place!). You will need at least 4.5 volts at 20mhz to avoid problems, compared to 3.78 volts for 16mhz - this means batteries will drain somewhat quicker (3x1.5v batteries will run down pretty quick), and if you have any motors or other draw on the batteries, 3 1.5v batteries will probably not work even if they are fresh.
Alternatively, going in the exact opposite direction, the lower the clock speed, the less voltage is required - for some projects, you might not need the clock speed - you can go down to 1.8v running at 4mhz.


text:
Empty message parse using ArduinoJSON from aedes MQTT server
I'm using aedes as my custom MQTT broker and PubSubClient at the ESP32 side, together with the ArduinoJSON package.
My server test code:
import Aedes from "aedes";
import net from "net";

let port = process.env.MQTT_PORT || 1883; // MQTT Port

const id = "MY_SERVER";

const aedes = new Aedes({
    id: id,
});

aedes.on("client", async (client) => {
    console.log("Client conntected...");
});

aedes.on("subscribe", async (subscriptions, client) => {

    let topic = "cmd/" + client.id;

    let msg = {
        topic: topic,
        type: "test",
        param: "p1"
    };

    console.log("Sending command...")
    console.log(msg);

    this.aedes.publish(msg);

});

let server = net.createServer(aedes.handle, options);

server.listen(port, () => {
    console.log(`Find the server at: mqtt://localhost:${port}/`);
});

When running I'm getting:
Client connected...
Sending command...
{ topic: 'cmd/4CA9A712B42A', type: 'test', param: 'p1' }

At the client (ESP32) side I have my PubSubClient callback as follows:
void callback(char *topic, byte *payload, unsigned int length)
{
    Serial.println("Message received.....");

    StaticJsonDocument<256> doc;
    deserializeJson(doc, payload, length);

    char *command = doc["type"];
    char *param = doc["param"];

    Serial.println(command);
    Serial.println(param);
}

The callback is being called property after subscription - but I'm not being able to parse the payload:
Message received.....
<empty line>
<empty line>

How can I fix the server or client to allow then to send/parse correctly the payload.

Could you Serial.write(payload, length); in the callback and show us what it prints?

Did it - payload has length zero, so nothing is coming from the server...

Do you have another way of testing the server? Maybe sniff the connection?

No way to sniff.... need to try different approach

Found the problem.... Needs to have a payload property when sending message:  let msg = {topic: topic, payload: JSON.stringify({type: "test", param: "p1"})} did the trick.


text:
Fast digital IO
I have a device programmable via an 8 bit digital parallel bus. I would like an Arduino to translate from a parallel 4 bit output of an existing device to 8 bit by intentionally reducing the resuloution. Unfortunately, I can't just use the most significant bits as I want to change the step size. The idea is to use an Arduino that ready the 4 digital input bits and then computs the necessary 8 bit output which it output to the 8 bit bus. However, this need to be as fast as 1 us. Is this possible with an Arduino? If so which board would you recommend? I guess I can't use the digitalWrite command as this will be too slow though. Any suggestions?

You can do this with an Uno, provided it has nothing else to do. I would
program it low-level, skipping the Arduino core since, as you said,
digitalWrite() would be too slow for this application.
Here is my proposed approach: read the 4-bit input from one port, use a
look-up table to translate it to an 8-bit output, and write that output
to another port. I would use PORTD (pins 0–7) for the output, as it is
the only full 8-bit port on the Uno, then the first bits of PORTB (pins
8–11) for the input:
/* Translation look-up table (dummy example). */
const uint8_t lut[16] = {
    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
    0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff
};

int main() {
    DDRB = 0x00;  // set port B as input
    DDRD = 0xff;  // set port D as output
    for (;;) {
        uint8_t input = PINB & 0x0f;  // grab the lowest 4 bits
        PORTD = lut[input];  // set the output
    }
}

I compiled and disassembled this code to count the CPU cycles: the main
loop takes 10 cycles per iteration. Given that the Uno is clocked
at 16 MHz, this is one update of the output every 0.625 µs.
Edit: This is a straightforward approach. At the cost of some extra
complexity, it could be optimized down to 7 cycles per iteration
(0.438 µs), or even 6 cycles (0.375 µs) in assembly.

nice answer ... upvote for the effort

Thank you very much for the detailed answer and testing. One further question out of curiosity: Does this mean that if I go for an Arduino Zero, it will be (48 MHz / 16 MHz) 3x faster and for a Due (84 MHz / 16 MHz) 5x faster?

@P.Egli: Re: “if I go for an Arduino Zero [...]”: No. These Arduinos use an ARM architecture, which is completely different from the AVR architecture of the Uno. The code above may not be trivially ported to them. AVR is simple enough that you can count the CPU cycles simply by looking at an assembly listing. I doubt the ARM cores of the Zero and the Due are at this level of simplicity.


text:
How to change between loops? IR Remote + led strip
#include <IRremote.h>
#include <Adafruit_NeoPixel.h>

#define LED_PIN 7 // define the LED strip data pin
#define LED_COUNT 150 // define the number of LEDs in the strip

Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

int RECV_PIN = 2; // define the IR receiver pin

IRrecv irrecv(RECV_PIN);

int brightness = 100;

void setup() {
 Serial.begin(9600); // initialize serial communication
strip.begin(); // initialize LED strip
strip.show(); // turn off all LEDs
irrecv.enableIRIn(); // start the receiver
}

void loop() {
case 0xE916FF00: // 0
    Serial.println("0");

      for (int i = 0; i<LED_COUNT; i++) {
      strip.setPixelColor(i, 0, 0, 0); // set all LEDs to off
      strip.show(); // turn off all LEDs
      Serial.println(irrecv.decodedIRData.decodedRawData);
      }

    break;
  case 0xF30CFF00: // 1
    Serial.println("1");

      for (int i = 0; i<LED_COUNT; i++) {
      strip.setPixelColor(i, 255, 255, 255); // set all LEDs to white
      strip.setBrightness(brightness); // set maximum brightness
      strip.show(); // display the color on the LED strip
      }

    break;
  case 0xE718FF00: // 2
    Serial.println("2");
    while (true) {

      for (int i = 0; i < LED_COUNT; i++) {
        strip.setPixelColor(i, random(256), random(256), random(256));
      }
      strip.show();
       delay(1000);
       if(irrecv.decode()){
         break;
       }

    }
    break;

  default:
    break;
}
irrecv.resume(); // receive the next code
  }
}

I have trouble to get out of the loop after i press button 3. When button 1 or 0 is pressed everything works perfectly but when i tried to add animation to my led strip (randomly changing colors) it stops to recieving. I dont know what to do.
I expect that after i press button 3 on my controller LED strip will be continously changing colors until another button is pressed (In my case button 0 or 1)
Can someone help me please?

you don't have any code for button 3 ... this is a question and answer site ... just ask a question that you would like answered ... Can someone help me please? is not a question about the problem ... besides, what is the point of asking a question that always has a yes answer

your code is missing parts... please read https://www.arduino.cc/reference/en/language/structure/control-structure/switchcase/

@jsotola so could you please help me? What is wrong in my code? Yeah i made a mistake it's button 2 not a button 3.

Basically I need to jump off the loop after I press another button on IR controller and I can't figure it out.

I told you what's wrong with your code on Mar 8 ... it's button 2 not a button 3 ... don't explain in a comment, edit your question and make the correction there ... When button 1 or 0 is pressed everything works perfectly ... how can it work perfectly when the code does not even compile without an error?


text:
'PinStatus' does not name a type
I bought an "off-brand" ESP32 board. I can upload blinky without a problem using platformio with the following platformio.ini file:
[env:humidious]
platform = espressif32
board = nodemcu-32s
framework = arduino

However, as soon as I add lib_deps = grafana/PrometheusArduino@^0.3.0 the compiler throws the following errors:
In file included from .pio/libdeps/humidious/WiFiNINA/src/WiFiStorage.h:23:0,
                 from .pio/libdeps/humidious/WiFiNINA/src/WiFi.h:38,
                 from .pio/libdeps/humidious/PromLokiTransport/src/clients/ESP32Client.h:7,
                 from .pio/libdeps/humidious/PromLokiTransport/src/PromLokiTransport.h:8,
                 from .pio/libdeps/humidious/PrometheusArduino/src/PromClient.h:4,
                 from .pio/libdeps/humidious/PrometheusArduino/src/PrometheusArduino.h:5,
                 from src/main.cpp:4:
.pio/libdeps/humidious/WiFiNINA/src/utility/wifi_drv.h:293:12: error: 'PinStatus' does not name a type
     static PinStatus digitalRead(uint8_t pin);

It was suggested on another thread that the board was out of date, but updating this didn't help.
Adding typedef int PinStatus before #include <PrometheusArduino.h> didn't help either.

What Majeko said was correct. PIO was using WifiNINA instead of the ESP32's WiFi library. To solve this, I added lib_ignore = WiFiNINA to platformio.ini and #include <WiFi.h> before including the prometheus libraries in main.ino.
I tested this by pointing PrometheusArduino at my desktop with this example:
$ ncat -l 9090
POST /api/prom/push HTTP/1.1
Host: 192.168.0.45
Content-Type: application/x-protobuf
Content-Encoding: snappy
User-Agent: prom-arduino/0.2.2
Content-Length: 209

F

%
__name__uptime_milliseconds_total

job
esp32-test

hostD   @/@%@<@@/

heap_free_bytes
0

foobar
        0xA6..(0xA/

The problem here is that PlatformIO is picking up the wrong WiFi library. It has decided that the WiFi.h provided by WiFiNINA is the correct one to use, rather than the WiFi.h provided by the ESP32's bundled WiFi library.
You could try removing all traces of the WiFiNINA library from your PlatformIO installation, or maybe you need to manually specify which WiFi library should be used to preempt the autoselection routine.
I don't know how you do that in PlatformIO.


text:
How to update root certificate(s) on Arduino MKR GSM 1400 (SARA-U201 basically) in order to be able to connect to GCP MQTT?
I wish to upload measurement data to Google Cloud Platform IoT Core with Arduino MKR GSM 1400. I have followed:
https://docs.arduino.cc/tutorials/mkr-gsm-1400/securely-connecting-a-mkr-gsm-1400-to-google-cloud-iot-core
and
https://create.arduino.cc/projecthub/Arduino_Genuino/securely-connecting-a-mkr-gsm-1400-to-google-cloud-iot-core-b8b628
but I did not succeed on connecting to Google's MQTT broker.
I have seen that I am not the only one with this problem, but I hope that someone has figured out the solution to this problem.
Reading this:
https://groups.google.com/a/arduino.cc/g/developers/c/EK7lmDK-jTA?pli=1
I came to the realization that I might need to update the root certificate in the "radio module", aka SARA-U201. I've tried to figure out how to do this, and stumbled upon the arduino-fwuploader, I have tried to run it like this:
/arduino-fwuploader firmware get-version -b arduino:samd:mkrgsm1400 -a /dev/ttyACM0
in order to succeed with this:
./arduino-fwuploader certificates flash -b arduino:samd:mkrgsm1400 -a /dev/ttyACM0 -u mqtt.googleapis.com:443
but the fwupdater does not even find the board despite "arduino:samd:mkrgsm1400" being correct. And yes, I am trying to do all this under Linux.
I was also trying to make the example: "SSLCertificateManagement_Example" working, but for this I would have needed the certificates to be converted to DET format and arrange it to be an array of unsigned chars.
https://www.sslshopper.com/ssl-converter.html
At this point I don't know what else I should/could try. I know for a fact that the hardware itself is working, I have tried as many examples regarding GSM as I could (sending SMS, GPRS ping, initiating a voice call, detecting GSM networks, etc.), and all worked. Following the tutorial, I have properly locked the ECC508 crypto chip, and generated a private/public key into slot 0. I have a GCP account, configured it properly, I have even tried to disable the HTTP protocol in the GCP project registry, but no use, I still think that it is about updating the root certificate in the SARA module.
Did anyone figure this out yet?
Thank you for the related tips and ideas!

Your question is "how to upgrade root cert", but your description is more like  "how to establish a SSL connection". Nobody will follow all the links you provided trying to guess how's your code looks like and what are you trying to do, it would be easier for you to post your code, and more importantly what shows on the Serial Monitor? So that it provides better understanding on whether it failed on establishing a SSL connection (which root CA will be used) or failed on authentication (which your public/private key) exchange mattered.

Hi Hcheung, thank you for the feedback, I may have been less specific at places where I should have been more specific. I wanted to demonstrate what I have done to try to solve the problem. The complete code can be found under my first link in the original question. Near the end of the "comments" section of the second link people begin to write about the same problem, what I am facing: The code gets stuck at an endless loop (writing ascii "."-s) trying to connect to mqtt.googleapis.com. That's the point where I begun my investigation.


text:
5v pin not outputting any voltage in Arduino Nano ble 33
I bought an Arduino Nano ble 33 but when I try to power my MQ-4 and MQ-8 sensors, these don't turn on at all, they do turn on if I switch to the 3.3V tho.
Is there anything special that I need to do to be able to use the 5V pin, or my board is faulty?

P.S: When I say 5V I mean the pin next to the green rectangle.

Did you set it up to use it? https://support.arduino.cc/hc/en-us/articles/360014779679-Why-doesn-t-the-5V-pin-work-in-the-Arduino-Nano-33-BLE-boards-

I haven't made a solder bridge on the two pads, however I am powering the board through the USB port (please note that this is not the BLE Sense board)

Oh I have just seen that as an OR when it is actually and AND, so both conditions need to be met

Says there it needs to be bridged. Also stated on https://www.arduino.cc/en/Guide/NANO33BLE.

To be honest, I couldn't find any information on my google search, but you are right, it says so.

I am new to this, and I am not sure how to bridge that as I don't have any soldering thingy

FWIW I searched for "Arduino Nano ble 33 5v pin" and it was the top two hits.

You are completely right I don't know what I was thinking of, the answer was on my first two results too, I think I read OR rather than AND and wrongly assumed my board was faulty, or something like that, sorry about that

No worries--it's only obvious after it's obvious ;)

i think you solder the two pads but i'll tell you something: use the 3.3v pin


text:
Arduino randomly stops sending data to python over serial
I want to send commands to Arduino over USB Serial from my python program and Arduino should send back received command to make sure data wasn't lost. However Arduino randomly stops sending data back. For debugging purposes I made builtin LED blink in the loop function. When Arduino stops sending data the LED slows down blinking (about 2-3 times).
I tried this on Arduino Uno and Arduino Nano to make sure it is not damaged board.
Here is my Python code responsible for communication:

class Communication(ABC):
    def __init__(self) -> None:
        self.history: list = []
        self.response_history: list = []
        self.last_responses: dict = dict()
        self.queue: collections.deque[str] = collections.deque()
        self.is_sending: bool = False
        self.command_recived_condition: threading.Condition = threading.Condition()

    def append_commands(self, commands: str) -> None:
        commands = map(lambda x: "c"+x, map(lambda x: x+";", filter(len, commands.split(";"))))
        for command in commands:
            self.queue.append(command)

    def append_and_send(self, commands: str) -> None:
        self.append_commands(commands)
        if not self.is_sending:
            self.sender: threading.Thread = threading.Thread(target=Communication.send_commands, args=(self, ))
            self.sender.start()

    @abstractmethod
    def send_command(self, command: str) -> bool:
        """ Sends command to the controller, waits for the response and tries again if command was not recived succesfully """
        pass

    @abstractmethod
    def listen(self) -> None:
        pass

    @abstractmethod
    def check_for_response(self, command: str) -> None:
        pass

    def send_commands(self):
        self.is_sending = True
        commands = self.queue
        while len(commands) > 0:
            command = commands.popleft()
            self.send_command(command)

        self.is_sending = False

class Serial_comunication(Communication):
    def __init__(self, port: str) -> None:
        super().__init__()
        self.serialcom = serial.Serial(port, 4800)

        self.listen()

        time.sleep(0.1)
        self.send_command("PING;")
        time.sleep(0.1)

    def listen(self) -> None:
        def listen_util() -> None:
            chars = []

            while True:
                if self.serialcom.inWaiting() > 0:
                    time.sleep(0.01)
                    try:
                        char: str = self.serialcom.read().decode()
                    except UnicodeDecodeError:
                        print("decoding err")
                        continue
                    print(char, end=" ")

                    if char[-1] == '#':
                        response_str = "".join(chars)
                        category, content = response_str.split("::")
                        self.last_responses[category] = content
                        self.response_history.append(response_str)
                        chars.clear()
                        print("\n", response_str)
                        if category == 'Info: recived':
                            with self.command_recived_condition:
                                self.command_recived_condition.notify()
                    else:
                        chars.append(char)

                time.sleep(0.01)

        self.listener = threading.Thread(target=listen_util)
        self.listener.start()

    def check_for_response(self, command: str) -> None:
        print("check")

        if self.last_responses.get('Info: recived') == command:
            print('possitive')
            return True

        return False

    def send_command(self, command: str) -> None:

        while True:
            time.sleep(0.1)
            self.serialcom.write(command.encode())
            print("sent", command)

            with self.command_recived_condition:
                self.command_recived_condition.wait()
                print("waited")

            if self.check_for_response(command.strip().strip(';')):
                break

And my Arduino Code responsible for communication:
#define INPUT_SIZE 50
char input[INPUT_SIZE + 1];

bool check_for_orders(Order& cmd, char *val, uint8_t& place)
{
    if (Serial.available() > 0)
    {
        // Read input from Serial until ; what means command has ended
        size_t size = Serial.readBytesUntil(';', input, INPUT_SIZE);
        input[size] = 0; // Add null terminator

        Serial.print(F("Info: recived::"));
        delay(10);
        Serial.print(input);
        Serial.print(F("#"));
        Serial.flush();

        // Check if command is not empty
        if (input[0] != 0)
        {
            // syntax is "order:pattern_place:value"
            cmd = static_cast<Order>(atoi(strtok(((char*)input)+1, ":"))); // Get order numer and convert to enum
            place = atoi(strtok(NULL, ":")); // Get place number from input (only 0 or 1 is allowed)
            char *value = strtok(NULL, ":"); // Get value from second part of string

            if (value == 0) // If value is empty then syntax is invalid
            {
                return false;
            }

            // Otherwise copy order name and value to c-strings from main function
            strcpy(val, value);
            free(value);

            return true;
        }
        else // Probably never gonna happen
        {
            return false;
        }
    }
    return false;
}

The check_for_orders function is run every time loop function is run.
Here is what python printed when I sent the following commands ["PING;", "c0:0:0;", "c0:1:0; c15:0:100,600,20,2,0,200,255,170,255,200;"]
sent PING;
I n f o :   r e c i v e d : : P I N G #
 Info: recived::PING
waited
check
possitive
sent c0:0:0;
I n f o :   r e c i v e d : : c 0 : 0 : 0 #
 Info: recived::c0:0:0
waited
check
possitive
sent c0:1:0;
I n f o :   r e c i v e d : : c 0 : 1 : 0 #
 Info: recived::c0:1:0
waited
check
possitive
sent c15:0:100,600,20,2,0,200,255,170,255,200;
I n f o :   r e c i v e d : : c 1 5 : 0 : 1 0 0 , 6 0 0 , 2 0 , 2 , 0 , 2 0 0 , 2 5 5 , 1 7 0 , 2 5 5 , 2 0 0 #
 Info: recived::c15:0:100,600,20,2,0,200,255,170,255,200
waited
check
possitive
sent c1:0:1;
/* and it got stuck */

Do someone know why something here is getting stuck and/or how to solve this problem?

4800 baud (I guess that is your baudrate) is pretty show. Depending on how often and how much you send you can easily overload the serial interface. Have you tried using a bigger baudrate? And can you provide a minimal working example, that shows your code? I mean a full working code, but without any non relevant code in it and that still shows your problem.

don't free(value)

I removed free(value) - rookie mistake - but that didn't completely solved the problem (but reduced frequency of occurrences).
Seems like declaring array like char val[50] and passing it to function as char* val was a bad idea. I changed array declaration to char *val = new char[50] and now seems like everything works fine.

Sending char* val is fine as long as: 1. you don't overflow the val; 2. you allow the last byte for NULL byte; 3. the val is always NULL terminated, no matter the size or you also send the size of it


text:
opencv reading the display and doesnot provide serial communication with arduino
I was creating a project where the following part of the code reads certain area of the display(which i screen shared from mobile)
import cv2 as cv
import numpy as np
from PIL import ImageGrab
import serial
arduinodata = serial.Serial('com5',9600)

def led_on():
    arduinodata.write(b'1')

def led_off():
    arduinodata.write(b'0')
i=1

while True:
    screen = np.array(ImageGrab.grab(bbox=(0,0,1920,1080)))
    #define the screen resulation
    screen_res = 1920, 1080
    scale_width = screen_res[0] / screen.shape[1]
    scale_height = screen_res[1] / screen.shape[0]
    scale = min(scale_width, scale_height)
    #resized window width and height
    window_width = int(screen.shape[1] * scale)
    window_height = int(screen.shape[0] * scale)
    #cv.namedWindow('Resized Window', cv.WINDOW_NORMAL)
    cv.resizeWindow('Resized Window', window_width, window_height)
    resized = screen.resize()
    health_bar = screen[262:268, 142:365]

    health_grayed = cv.cvtColor(health_bar, cv.COLOR_BGR2GRAY)
    count1 = cv.countNonZero(health_grayed)

if i==1:
    e =count1
    i=0

if e>count1:
    led_on()
    e=count1

if e<count1:

    e=count1

and whenever the value of the count1 variable decreases i want the Arduino led should be turned on
this was the arduino code
char serialData;

void setup() {
  // put your setup code here, to run once:
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
  Serial.begin(9600);

}

void loop()
  // put your main code here, to run repeatedly:
{
  if(Serial.available() >0)
  {
    digitalWrite(13,HIGH);
    delay(1000);
    digitalWrite(13,LOW);

   }

}

But the led is turning on but does not turns off . I don't know why
can anyone please help me

This happens because you are not reading from Serial.
When you send data to the Arduino, it gets placed in the Serial buffer. Serial.available() then returns the number of bytes in the buffer. The bytes are removed from the buffer by Serial.read()ing them, which you don't do. Since you don't remove any bytes from the buffer, Serial.available() will always return a number greater than zero from the moment on, that the first byte arrives. After the delay you turn the LED off via digitalWrite(13,LOW);, but in the next loop iteration the if statement is again executed (as described above). This happens so fast, that you think the LED just stays on. In reality it gets turned of for maybe a few microseconds and then turned on again.
You are sending a single byte for the LED to react. So it would be the simplest solution to just read a single byte from the buffer inside of the if statement. The result can be discarded.
void loop()
{
  if(Serial.available() >0)
  {
    digitalWrite(13,HIGH);
    delay(1000);
    digitalWrite(13,LOW);
    Serial.read();
   }
}

The Serial.read() removes one byte from the buffer and returns it (so it gets discarded here). This way the LED blinks for every byte, that the Arduino receives over Serial.

Note: Depending on how fast you are sending the data you might want to make more clear, that you have individual bytes. With the above code the LED will light up for 3 seconds straight if you send 3 bytes in (relatively) fast succession (meaning consecutive bytes less than a second apart). To make it more clear, that you have 3 individual bytes, you can add a delay() call after turning the LED off. That gives you the chance to actually see it turning off.


text:
Arduino Nano Ble Sense stopped working suddenly
My Arduino Nano 33 BLE Sense stopped working suddenly a while after uploading firmware for an ML project. I've used my board for several ML projects and it worked like a charm.
I can't find the board in the Arduino IDE's port section.
I've tried to reset the board by double-pressing the reset button, but that didn't make any response, not even flashing LEDs.
I've tried changing USB cables, connecting to different ports of the PC, also other PC's but the result was the same.
I've checked the board's outputs, luckily the 3v, 5v, and Vin pins have output and run without any abnormal heating. I'm not sure what's the problem with this board. Maybe the bootloader got corrupted?

it is possible to upload to Nano BLE with Nano IoT selected and vice versa. The result is a deleted bootloader. here I describe what to do for Nano IoT, but the same applies for Nano BLE: https://arduino.stackexchange.com/questions/72955/arduino-nano-33-iot-issue/72973#72973

Thanks for giving me light Juraj.


text:
ESP8266 - MAX3485 Modbus not getting data
I'm trying to connect a modbus meter to a nodeMcu LoLin v3
I'm using a MAX3485 module to transfer the TTL to a RS485 connection.
The modbus server has unitId 1, baud rate 9600 and no Parity
This is the scheme. A e B from the module go to the modbus server device

And this is my simple script
#define DIRECTION D3

#include <ModbusRTU.h>
#include <SoftwareSerial.h>

SoftwareSerial S(D2, D1);
ModbusRTU mb;

bool cb(Modbus::ResultCode event, uint16_t transactionId, void* data) { // Callback to monitor errors
  if (event != Modbus::EX_SUCCESS) {
    Serial.print("Error result: 0x");
    Serial.println(event, HEX);

  } else {
    Serial.print("No Error");
  }
  return true;
}

void setup() {
  Serial.begin(115200);
  pinMode(DIRECTION, OUTPUT);
  digitalWrite(DIRECTION, 0);
  S.begin(9600, SWSERIAL_8N1);

  mb.begin(&S);

  mb.client();
}

void loop() {
  uint16_t res[2];

  if (!mb.slave()) {    // Check if no transaction in progress
    mb.readHreg(1, 5, res, 1, cb); // Send Read Hreg from Modbus Server
    while (mb.slave()) { // Check if transaction is active
      mb.task();
      delay(10);

    }
    Serial.println("Res");
    Serial.println(res[0]);
    Serial.println(res[1]);

  }
  delay(1000);
}

I created a Software Serial on D1 and D2 and i'm trying to read from it but no matter what i do, i keep getting error 4 from the response and 2 values in my reg array i do not where they come from...
Error result: 0xE4
Res
59044
16382

Am I missing something?
The modbus server works because i connected it to another client and everything is ok

If you're using a MAX3485 then VCC should be connected to 3.3V, not VIN (which on some boards cannot provide power but instead can only be used to power the board itself).

You might find my answer to this question enlightening...

i do not know if it's 3.3V or 5V... i put it on 3.3V on the ESP8266, nothing changes, it's still powered on


text:
Cannot read values stored in bool* pointer
I'm trying to read values stored in a bool* pointer from a modbus coil call.
I'm using modbus-esp8266 library. it's all ok with Input Registers and Holding Registers but i cannot read the result of a coil read.
#include <ModbusRTU.h>
#include <SoftwareSerial.h>

SoftwareSerial S(D2, D1);
ModbusRTU mb;

bool cb(Modbus::ResultCode event, uint16_t transactionId, void* data) { // Callback to monitor errors
  if (event != Modbus::EX_SUCCESS) {
    Serial.print("Error result: 0x");
    Serial.print(event, HEX);
  }
  return true;
}

void setup() {
  Serial.begin(115200);
  S.begin(9600, SWSERIAL_8N1);
  mb.begin(&S);
  mb.master();
}

void loop() {
bool* coils;
  if (!mb.slave()) {    // Check if no transaction in progress
    mb.readCoil(1, 1, coils, 1, cb); // Send Read Hreg from Modbus Server
    while(mb.slave()) { // Check if transaction is active
      mb.task();
      delay(10);
    }
    Serial.println(*coils);

  }
  delay(1000);
}

I get this kind of error when trying to print *coils
Exception 28: LoadProhibited: A load referenced a page mapped with an attribute that does not permit loads

How to get the boolean result value from it?

please add the full error message text

The coils pointer points to some random place as you didn't bother to define any value for it (depends on what was in the memory where that pointer gets space).

bool coils; and mb.readCoil(1, 1, &coils, 1, cb);. this way the function can the value of the variable coil

When programming an Arduino you are actually writing in the language C.  As such you can search the internet for C programming answers of which there is likely 50 years of answers.
You have defined "coils" as a pointer.  This is done by preceding the name with an asterisk where it is defined.  In this line of code:
bool* coils;

This means you are using coils to store the memory location of where the actual value is to be stored.  However, in the case of the code in the posted question, the memory location of where the actual value is to be stored is never defined.
This is like going on a bad clue hut.  You receive instructions to obtain the next clue at a specific location.  But when you get there you find no further instructions.
Beginning programmers often find pointers confusing.  But later find pointers very useful tools that simplify many otherwise complex programs.
Consider dropping the asterisk in front of "coils" on the two lines of code where is exists and try running the program again.

Added later:
Guessing, it may be that the call to readCoil function assumed to be defined in ModbusRTU.h requires a pointer to be passed to in as the 3rd formal variable parameter.  This is more advanced C programming.  If true, then keep your original code but add a line of code setting the value of "coils" to the address of a new bool variable.  Perhaps something along these lines:
bool* coils;
bool coils_value;
coils = &coils_value;


text:
How to use ESP_LOGx?
I can't get the logging to work on the ESP32.
Here is my example:
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <esp_log.h>

void setup() {
  Serial.begin(115200);
  ESP_LOGE("Test", "This is a test!");
  delay(1000);
}

void loop() {
  ESP_LOGE("Test", "This is a repesting test!");
  delay(1000);
  Serial.println("Serial.print");
  delay(1000);
}

It only prints Serial.print every two seconds, but not the log messages.

Without any experience but after rushing through the documentation: Don't you need to call esp_log_level_set()?

You can set the log level from the Arduino IDE via Tools -> Core Debug Level. By default it is set to NONE.

I just had to add my thanks to hcheung! Changing the #defines and using esp_log_level_set() made no apparent difference. Setting Core Level Debug made all the difference, seeming to override the #defines mentioned above. -- John B

Thanks to hcheung! I had to set the Core Debug Level in the Tools menu.


text:
Reading/writing Ntag215 with RC522
I ordered Ntag215 from Aliexpress. The tags are identified just fine, yet I have issues writing/reading to them because of failed authentication. I am using Arduino Uno + RFID-RC522 module.
This is my code below:
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN 9  //
#define SS_PIN 10  //

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
  Serial.begin(9600);  // Initialize serial communications with the PC
  while (!Serial)
    ;                  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin();         // Init SPI bus
  mfrc522.PCD_Init();  // Init MFRC522
  Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
}

void loop() {
  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if (!mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if (!mfrc522.PICC_ReadCardSerial()) {
    return;
  }
  Serial.print(F("Card UID:"));
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println();
  Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
  Serial.println(mfrc522.PICC_GetTypeName(piccType));

  MFRC522::MIFARE_Key key = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
  MFRC522::StatusCode status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid));
  Serial.println(mfrc522.GetStatusCodeName(status));
}

void dump_byte_array(byte *buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
    }
}

And this is the output I get.
01:27:26.704 -> Scan PICC to see UID, type, and data blocks...
01:27:30.357 -> Card UID: 04 CB 4A 57 19 61 80
01:27:30.390 -> PICC type: MIFARE Ultralight or Ultralight C
01:27:30.422 -> Timeout in communication.

Always get Timeout in communication. With Mifare 1KB tags this is not an issue. Any idea?

it times out after 32 ms ... maybe the timeout setting is too short

Ok after more trial and error and research I have made it possible to Write and Read to Ntag215. Here are code snippets for writing and reading. It was not required to Authenticate to write the data the tag.
Writing: It is actually quite simple. The main rule is that the writing can start from the page 4. And the bufferSize has to be 4. Here is example just writing "A" character to the tag.
    char charToProgram = "A";
    byte data = charToProgram;       // Data to write (ASCII character "A")
    byte blockAddr = 4;  // Block address to write to

    // Write the data to the tag
    MFRC522::StatusCode status = reader.MIFARE_Ultralight_Write(4, &data, 4);

    if (status == MFRC522::StatusCode::STATUS_OK) {
      Serial.println("SUCCESS! Wrote to card!");
      reader.PICC_HaltA();
    }

Reading:
    int blockAddr = 4;  // Block address to read from
    byte data[18];
    byte size = 18;
    // Write the data to the tag
    MFRC522::StatusCode status = reader.MIFARE_Read(blockAddr, data, &size);

    if (status == MFRC522::StatusCode::STATUS_OK) {
      Serial.print("Read character: ");
      Serial.println((char) data[0]);
      reader.PICC_HaltA();
    }


text:
Arduino Motor Control at a Specific Time
Hello. Currently I'm working on creating an automatic dog food dispenser. I'm using a Arduino Uno R3, an L298N stepper driver, a DS1307 RTC breakout board, a Nema 17 stepper motor, and a breadboard to disperse the power to each board. I'm using a 9V battery to power it temporarily. I've tested motor control without it being determined by the current time and it works perfectly however when I have the motor run at a specific time (4:45 and 6:45 in the code) the motor doesn't move. How can I move the motor at these specific times?
#include <RTClib.h>
#include <Stepper.h>
#include <SoftwareSerial.h>

RTC_DS1307 rtc;

Stepper myStepper(200 , 9 , 10 , 11 , 12);

void setup() {
  Serial.begin(9600);
  rtc.adjust(DateTime(2021 , 7 , 14 , 4 , 44 , 0));
  myStepper.setSpeed(20);
}

void loop() {

  DateTime now = rtc.now();

  if ((now.hour() == 4 and now.minute() == 45) or (now.hour() == 6 and now.minute() == 45)) {
      Serial.println("testing");
      myStepper.step(10000);
      delay(1000);

}

}

You are pushing the limit of the L298N, probably will exceed it. A typical stepper motor like a NEMA 17 is probably rated at voltage of about 2.8 Volts and a maximum current of 1.68 Amps. This basically means if you hook it up to 2.8 Volts it will draw 1.68 Amps. If you try to run it at a higher voltage it will draw more current and get excessively hot. Driver Model: L298N has a Motor Supply Current (Maximum): 2A, Logic Voltage: 5V, Driver Voltage: 5-35V. The motor was rated at about 2.8V, powering it with more will very quickly exceed your bridge capacity. The Arduino will give you 5V and 3.3V but using either to power your motor will probably destroy the Arduino. The Arduino a power supply it is NOT! I suggest you use a seperate power supply for the motor. If you power the Arduino via Vin and use a buck converter from the 12V it should work fine.

Could I run a 9V battery into a breadboard and have both the motor and arduino using the same power supply?

@Carter If you mean those standard 9V block batteries, then no. They barely provide enough current for the Arduino itself, let alone any motor.

I’m new at this but looks to me like your rtc is uses i2c comms.  I don’t see that you’ve included wire.h or issued the wire.begin to initiate communication between the rtc and arduino.  See other rtc examples and good luck!

I'm new at this also and I found a few examples (all of which using an lcd screen) using wire.h but thought they were linked to the lcd. Its good to know that my guess was incorrect. Thanks for your help!

No problem.  Will be curious if that solves the issue.  Thanks.

The I2C communication is probalby already done by the RTC library. Thus there is no need for Wire in the main sketch

@chrisl. You would think, but RTClib shows wire as a dependency.

@Vince The point is that RTClib already #includes Wire.h. You only need to include libraries where they are used. Since Wire is not called in the main sketch, it doesn't need to be included there. Wire is called in the RTClib library, so that it included it at the start of its implementation.

Adding #include <Wire.h> and wire.begin(); worked

@Carter Glad it worked! Thanks for the update.


text:
Connecting an LCD when Pins A4 and A5 are Occupied
Recently I've been working on an automatic dog feeder dispenser (that dispenses by turning a screw attached to a stepper motor). Currently I have a Nema 17 connected to an L298N stepper driver which is connected to Arduino pins 9-12 and a DS1307 RTC connected to analog pins A4 and A5 (I would have a picture but the wiring is all over the place). I would like to connect a 16x2 LCD screen (with a potentiometer already on the back and 4 connecting pins) but from everything I've seen online, it also uses analog pins A4 and A5 which are occupied by the RTC. How would I go about connecting the LCD?
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <RTClib.h>
#include <SoftwareSerial.h>
#include <Stepper.h>

RTC_DS1307 rtc;
LiquidCrystal_I2C lcd(0x3F , 16 , 2);
Stepper myStepper(200 , 9 , 10 , 11 , 12);

void setup() {
  lcd.init();
  lcd.print("yes");
  Wire.begin();
  Serial.begin(9600);
  rtc.adjust(DateTime(2021 , 7 , 15 , 3 , 23 , 0));
  myStepper.setSpeed(100);
}

void loop() {
  DateTime now = rtc.now();
  Serial.print(now.hour());
  Serial.print(":");
  Serial.print(now.minute());
  Serial.print(":");
  Serial.print(now.second());
  Serial.println(" ");

  lcd.print(now.hour());
  lcd.print(":");
  lcd.print(now.minute());
  lcd.print(":");
  lcd.print(now.second());
  lcd.println(" ");

  if ((now.hour() == 7 and now.minute() == 0 and now.second() == 0)) {
    myStepper.step(1000);

}
  delay(1000);

}

I2C communication lines support more than one device on the same pins, so just connect
the LCD to the same pins... or you could just look under your Arduino to locate the 2 more I2C pins(Left of the Aref pin)

https://www.arduino.cc/en/Reference/Wire

I connected both the LCD and RTC to A4 and A5 via a breadboard and it works great. Thanks!

Here is one example where LCD and RTC both are conencted to same I2C pins. https://wokwi.com/arduino/projects/306828496357818944

As mentioned in the comments: Your LCD and the RTC both use the I2C bus for communication. That bus is designed to have many devices simultaneously connected. For this to work every slave device on the bus (the Arduino is the master device, which has no address) has to have a unique address. In your code you write, that the LCD is on address 0x3F. The RTC DS1307 is 0b1101000 or 0x68 (same value in binary or hexadecimal representation) (see the DS1307 datasheet, page 12).
So you can connect  both devices to the same pins, as the communication interface there already supports that. The pins A4 and A5 are the I2C pins of the Arduino, so you need to connect them there for using the Arduinos I2C hardware.

Here are my 2 cents.
As the other answer suggests, you can always use the same I2C lines for devices. The devices will be differentiated via an I2C address. I have compiled one example based on your code. Here is the link to the simulation
The code is below
#include <Wire.h>
#include "LiquidCrystal_I2C.h"
#include <RTClib.h>

RTC_DS1307 rtc;

LiquidCrystal_I2C lcd(0x27, 16, 2);

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

  if (! rtc.begin())
  {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    abort();
  }

  lcd.init();
  lcd.backlight();
  lcd.print("yes");
}

void loop() {
  DateTime now = rtc.now();
  Serial.print(now.hour());
  Serial.print(":");
  Serial.print(now.minute());
  Serial.print(":");
  Serial.print(now.second());
  Serial.println(" ");

  lcd.setCursor( 0,0);
  lcd.print(now.hour());
  lcd.print(":");
  lcd.print(now.minute());
  lcd.print(":");
  lcd.print(now.second());

  if ((now.hour() == 7 and now.minute() == 0 and now.second() == 0)) {
    // myStepper.step(1000);
  }

  delay(1000);
}

As you can see, I2C lines are shared between the RTC module and the LC display module.


text:
Does Leonardo need a separate power supply?
I'm currently using an Arduino Uno (R3), but want to switch to Leonardo for the USB-ability. The Uno can work from the USB's 5V. Looking at the Leonardo's schematic it seems the only input to the voltage regulator is from the power connector. This makes sense as it's a 5V regulator which needs > 5V in. But I don't see the MOSFET which connects the USB's 5V to the board's 5V, like there's one on the UNO.
So, does the Leonardo need the separate power input connected?

Power steering is performed by the assembly labelled "+5V AUTO SELECTOR" at the bottom of the page. The voltage at VIN is halved and then compared with the board's 3.3V output in order to determine whether or not to enable USB power via T1.

Ow! Didn't see that. It was close enough to the 1117 though. :-( Thanks a lot!