text:
Code for ESP32 without Development Board
I'm very new to microcontrollers. I'd like to start developing for the esp32, as it has integrated wifi & bluetooth for quite cheap. This being said, i don't have a board yet. Is there a way i can emulate an esp32 board, so i can start programming and debugging my code?
As i'm very new, any advice is welcome.
Thanks

I don't think there are a lot of websites or software that allow you to emulate a microcontroller, to my knowledge I know a site called circuito.io that has a lot of options for components and code but does not actually emulate, or you could try tinkercad.com and it supports emulation of a few boards, but I'm not too sure about esp32

I see. I will make sure to check them out. Thanks for the hint :)

https://stackoverflow.com/questions/67330695/is-there-any-simulator-for-esp32-s2-or-esp32-chips similar question which can be merged

Welcome to Arduino Stack exchange. There are a lot of discussions and half-completed, or project-specific models available for the ESP32 simulator. My sincere advice is to go ahead and buy real hardware. By the time you take to set up the simulators (download the repo, set environment variables, connect GDB debugger or other), you would have received the ESP32 hardware itself.
Why you should go for real hardware?

An emulator can never match the timing of real ESP32 hardware. if you
have any timing-related issue, you cannot fix it using an ESP32 emulator
Real issues in hardware (bounce/debounce of switches, surge current and brownout voltages, rise time and reflections etc - won't appear in the ESP32 simulators
EMC issues due to floating inputs, Port pin current limits or even self-heating of components are not considered in most the simulators
A code running on the emulator can't always run on the real hardware without modifications, especially when it involved multiple threads and priorities

Still, other options are available online but it depends on your comfort

ESP32 Simulator by Wokwi - The ESP32 Simulator is currently in preview (affiliation disclosure)

ESP32 simulator from mireq - ESP-IDF contains a small amount of hardware-specific code, FreeRTOS and few multi-platform libraries. This project uses FreeRTOS port for POSIX, LWIP for TCP/IP layer and mbedtls for cryptography functions.
In addition, several useful APIs from esp-idf are implemented eg. logging. With this project, you can write a program, which will be runnable and testable on Linux.

ESP32 machine emulator - The purpose of this package is to enable you to test-drive (TDD) your MicroPython code in an IDE running on your computer. It seems a lot of people are test-driving python, but not many are test-driving MicroPython. That’s understandable, since many MicroPython projects are simple, and emulating real hardware in a test environment is difficult.

Bridges - Pretend your PC a Raspberry Pi or an ESP32 to connect I2C / SPI / GPIO / UART peripherals.

Note You should also check when is the last time the projects were updated. The latest ones and active ones are always a better choice as they are expected to have better usability, and stable simulations.

A few screenshots from Wokwi ESP32 Simulator

If you are new to microcontrollers then start with basic arduino code and components.  Since the esp chips can be coded with the Arduino framework it will be an almost seemless transition from Arduino board to ESP board.  Build some circuits on tinkercad.com, write some code, and simulate them. Once you have those basics down hopefully your esp board will have arrived and you can start building your project.


text:
FingerPrint Scanner wont detect any input (fingerprint image)
Hi good day to all I have a project that , it will lock the solenoid using the fingerprint then I have hook up a coinslot that will count the coins inside the vault its like a secured piggybank.
Project objective

it must display the coin total :
If fingerprint is access it will unlock the solenoid
then goes back to total of coins

The problem is its just showing total of coins inserte but the fingerprint wont detect any image id taken from enrrol code
#include <Adafruit_Fingerprint.h>    //Libraries needed
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

#include <EEPROM.h>
#define coinSlot 9 // different pin!!! untested!!!

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

int in2 = 4;

String Names[] = { "RAVEN", "Surtr", "Tech",}; //Those are the names affected to the fingertemplates IDs
                                                 //The first on which is Names[0] : Yassine has the ID 1 in the fingerprint sensor

SoftwareSerial mySerial(2, 3);                  //Fingerprint sensor wiring RX 3, TX 2
LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin); //LCD declaring

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);                    //Fingerprint sensor declaring

int coinCount = 0;
int coinSlotSignal;
int requiredCoins = 1;
boolean coinInserted = false;

void setup()
{
  pinMode(in2, OUTPUT);
  digitalWrite(in2, HIGH);
  pinMode(coinSlot, INPUT_PULLUP);
  lcd.write(EEPROM.read(5));

  Serial.begin(9600);               //Serial begin incase you need to see something on the serial monitor
  finger.begin(57600);              //Sensor baude rate
  lcd.begin (16,2);
  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.home();
  finger.getTemplateCount();        //Counts the number of templates stored in the sensor flash memory
  delay(2000);
}

void loop()
{
  int result = getFingerprintIDez();  //This function keeps looping and waiting for a fingerprint to be put on the sensor
    OpenDoor();

  // Coinslot
  while(!coinInserted){
    coinSlotSignal = digitalRead(coinSlot);

    if(coinSlotSignal < 1) {
      coinCount += 1;
      coinInserted = true;
      EEPROM.write(0,coinCount);
      Serial.println(EEPROM.read(0));

      lcd.setCursor(0,0);
      lcd.print("TOTAL:");
      lcd.setCursor(0,1);
      lcd.print(coinCount);
    } // if
  } // while

  while(coinInserted) {
   coinSlotSignal = digitalRead(coinSlot);
    if(coinSlotSignal >0) {
      coinInserted = false;
    }
  }

  if(coinCount >= requiredCoins) {
    delay(1500);
  }
}

//Main function taken from the "fingerprint" example and modified
//Only the modifications are commented
int getFingerprintIDez() {
  uint8_t p = finger.getImage();        //Image scanning
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.image2Tz();               //Converting
  if (p != FINGERPRINT_OK)  return -1;

  lcd.clear();                     //And here we write a message or take an action for the denied template
  p = finger.fingerFastSearch();     //Looking for matches in the internal memory
  if (p != FINGERPRINT_OK){          //if the searching fails it means that the template isn't registered
    lcd.print("Access denied");
    delay(2000);
    return -1;
  }
            //If we found a match we proceed in the function

  lcd.print("Welcome");                  //Printing a message for the recognized template
  lcd.setCursor(2,1);
  lcd.print(Names[finger.fingerID-1]); //Then print the name we gave it and the -1 is to remove the shift as the ID starts from "1" but the array from "0"
  return finger.fingerID;
}

/*The two following functions depends on your locking system
 *mine has a DC motor that should turn in both ways for opening and closing
 *that's why I'm using H bridge, you could have a solenoid with a transistor
 *then you'll need only opening sequence but controlling the transistor
 *as the closing is spring loaded...
 */

void OpenDoor(){
  digitalWrite(in2, LOW); // turn on motor
  delay(5000);
  digitalWrite(in2, HIGH); // turn off motor
}

what is your question?

I tried to test using enroll code it was working then If I try to upload the code it wont work in the serial monitor it sayst fingerprint not found

I cannot see, where "fingerprint not found" would be printed to Serial. Please explain, where this happens.and did you actually enroll fingerprint with a previous code? Otherwise the sensor cannot recognize any fingerprint.

hI sir thanks for the reply I already fixed the issue sir , I was having a bad balance on my Brackets , after formally formatting my code I found the issues. Thanks

source: Stack Exchange

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

sort: votes


text:
How can I use attached interrupt on my project?
Hi I have a coinslot project and connected with a fingerprint sensor it was stated in the ardiuno forum that it will work on pin 2 and 3 , but it is already used pins of the finger print sensor .
Coinslot signal is in pin 9 and the in2,3 is for the rx and tx of the fingerprint sensor.

So... change the RX and TX of the fingerprint sensor to some other pins...?

If you can't rearrange the pins like Majenko suggests in the their comment, something you can do is is use pin change interrupts rather than the regular "external" interrupts.  On the UNO, these are available on all of the "digital" capable pins, which also includes most of the "analog" pins if you have an SMT UNO, or all of them if you have a DIP model.
NiceHood's PinChangeInterrupt library is modeled after the regular attachInterrupt function, so it should be familiar looking to you.  It's in the library manager; you don't need to get it from github.
NOTE: The O.P. opened a another question which seems to be this same thing, only with different context and specific code.  There I've given more details on what's outlined above but in relation to that that specific code in an answer there.

Thank you sir for the help.

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


text:
Yellow LED got burned, green LED didn't

I'm not talking about the onboard LED at the Arduino board here.  What those LED's mean, is the LED's we usually plug at the breadboard.

I plugged in a yellow LED and a green LED onto a breadboard.  I wired it up, and noticed something.  Green LED lights up at its full brightness, while yellow LED didn't emit any light.  Tried in another yellow LED, and it seems like it's smoking, which means it's burned.
I'm not using a 220 Ohm resistor or any kind of resistor that time.  I also have no idea why the green LED didn't burn itself, when you plug it directly on 5V and GND.  I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.
When I plugged the green LED into a 220 Ohm resistor, it did as expected.  It lowered its brightness, of course, because the resistor is resisting some of the electricity to pass on the LED.

I don't see the Arduino connection here. Or a question.

The Arduino Uno can give 40mA shortcut current with a digital output pin. Maybe that was not enough to burn the led. I think that somewhere along the line from the computer via the usb cable, the Arduino board and the output pin, the current or voltage was lowered or the internal resistance of the led is higher or became higher during burning. Try a power supply of 5V 2A and connect all the leds to burn them all. What is the point of this? If you want to know about leds then measure the voltage and the current of the led. Can you get rid of that Arduino board, it might no longer be reliable.

@LookAlterno Oh, sorry.  I forgot to include the question. The question is, "Why is the yellow LED burning, while the green LED is not?"

@sempaiscuba I'm just new to the community.  If you like, then you can move this question / post to a different Q&A site.

@Jot I will burn all the LED's?  Why would I do that?

@LloydDominic You might find it helpful to review the site tour and Help Centre and, in particular, [ask].

You probably didn't have it connected to 5V for long enough. When I purposely applied too high a voltage to a led, it took around 10 seconds to fail. It changed color before that, which was funny.

I'm not using a 220 Ohm resistor or any kind of resistor that time.

Well, there you go then. If you abuse an LED you can expect it to die.

When I plugged the green LED into a 220 Ohm resistor, it did as expected. It lowered its brightness, of course, because the resistor is resisting some of the electricity to pass on the LED.

And the LED was so much happier when you weren't abusing it.

I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

It was probably tinged with yellow. And if you left it a while it would get yellower as it got hotter, and then started to fade out, and eventually die.
Different LEDs use different combinations of elements to make the different colours. Different types of the same colour also use different elements. Old fashioned green LEDs are more reliable, though dimmer, than newer ones. They withstand more abuse. But they will still complain after a while.

Majenko already mentioned the reason. Maybe it's good to add that different colored LEDs (and even each type/model) should have its 'calculated' resistor.
Find the forward voltage of the LED (differs per type/color), and use the following formula :
V - Vfv = I * R  <=> R = (V - Vfv) / I

E.g. if the forward voltage is 2V and you use a 5V Arduino and want 20 mA:
R = (5 - 2) / 0.02 = 150 ohm

The maximum mA you can find also in the data sheet of the LED.

Would be much better if you give the meaning behind those acronyms.  (What is "V" ?, what is "Vfv" ?, etc. ...)

If someone does not know what V or Vfv (forward voltage) means, I think he should either google it or ask a new question.

I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

LEDs get burned from excessive heat that is the result of excessive current. Green LEDs have higher forward voltage than yellow LEDs so, if everything else is equal, the "excessive" current through the green LED is smaller than the one through the yellow LED, thus causing the yellow LED to warm up faster and thus burn out faster.
Other factors may still attribute to the yellow's burn-out.

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


text:
How can I use PWM in power saving mode (ATmega328)?
I fail to use PWM in power saving mode.  The output behaves erratically.  This should be possible, I guess.  The following is a minimal working example:
/* MWE: Cannot use PWM in any power saving mode.

   A minimal working example (MWE) demonstrating my trouble in using
   PWM while saving power.

   Intention: Control one load to be on or off for longer periods of
   time (hours, that is).  The brightness of the load is set by PWM.

   Wiring:

                                              +5V
                                               |
           +------------------+                |
     +5V---|Vin               |                |
           |     Arduino      |                C
           |     Pro Mini    9|-----/\/\/----B|<  PN2222
           |     compatible   |      1k        E
           |     (ATmega328)  |                |
     GND---|GND               |                | +
           +------------------+               LED
                                               | -
                                               |
                                               >
                                               < 1k
                                               >
                                               |
                                               |
                                              GND

   Implementation:

     * Set watchdog to cause an interrupt in regular intervals (in
       this MWE: 2s).  Count down `cycles` (MWE: 2 or 3) on each
       watchdog interrupt.

     * If `cycles` is 0, toggle the output, set new `cycles` value.
       The real program uses 7200 8s cycles for 16h before the next
       toggle.

     * Go to SLEEP_MODE_PWR_DOWN.

   Expected: attached load is on for 4s, dimmed at 32/256.  Then off
             for 6s.  Then repeat.

   Observed: In most cases, there's no output in sleep mode, the LED
             only blinks before sleeping.  But sometimes it is on, so
             PWM seems to be possible while sleeping!

   The real program (from which this MWE is derived) uses adjustable
   brightness, wakes up from sleep by external interrupts, stores
   brightnes to EEPROM, ...
*/

/* Setting the following to 0 uses `digitalWrite` instead of
   `analogWrite` to demonstrate that the watchdog and interrupt logic
   do actually work. */
#define USE_PWM 1

#include <avr/sleep.h>
#include <avr/wdt.h>

#define outputPin 9    // where the PWM load is connected
#define onCycles 2     // num of watchdog cycles to stay on
#define offCycles 3    // num of watchdog cycles to stay off

int brightness = 32;  // PWM duty cycle in 1/256, if the load is on
int toggle = 1; // current on/off state of PWM load

/* Number watchdog cycles until next toggle.  This will be modified in
   the watchdog interrupt handler. */
volatile unsigned long wdt_cycles = onCycles;

/* Watchdog interrupt handler called when watchdog expires, count down
   remaining cycles.  Does not underflow. */
ISR(WDT_vect) {
    if (wdt_cycles > 0)
        wdt_cycles--;
}

void setup(void) {

    /* Setup watchdog.  See [1] p54, [2] */
    cli(); // BEGIN disable interrupts

    MCUSR &= ~(1<<WDRF); // no system reset on watchdog timeout

    WDTCSR |= 1<<WDCE | 1<<WDE; // allow watchdog configuration

    WDTCSR
        = 1<<WDIE // enable interrupts
        | 1<<WDP2 | 1<<WDP1 | 1<<WDP0 // 2.0 seconds
        ;

    wdt_reset(); // reset timer

    sei(); // END disable interrupts

    /* Setup output pins */

    pinMode(outputPin, OUTPUT);

#if USE_PWM
    analogWrite(outputPin, brightness);
#else
    digitalWrite(outputPin, toggle ? HIGH : LOW);
#endif

}

void loop(void) {

    if (wdt_cycles < 1) {
        toggle = !toggle;
        wdt_cycles = toggle ? onCycles : offCycles;
#if USE_PWM
        analogWrite(outputPin, toggle ? brightness : 0);
#else
        digitalWrite(outputPin, toggle ? HIGH : LOW);
#endif
    }

    /* Heartbeat: Short blink of builtin led.  This verifies that we
       are actually sleeping and waking up. */
    digitalWrite(LED_BUILTIN, HIGH);
    delay(50);
    digitalWrite(LED_BUILTIN, LOW);

    /* Got to sleep, see [3].  I want `SLEEP_MODE_PWR_DOWN`, but also
       none of the others works. */
    set_sleep_mode(
                   //SLEEP_MODE_IDLE
                   //SLEEP_MODE_ADC
                   //SLEEP_MODE_PWR_SAVE
                   //SLEEP_MODE_STANDBY
                   SLEEP_MODE_PWR_DOWN
                   );
    sleep_mode();
}

/* References
   [1] https://cdn.sparkfun.com/datasheets/Kits/doc8161.pdf
   [2] https://forum.arduino.cc/index.php?topic=63651.0
   [3] https://playground.arduino.cc/Learning/ArduinoSleepCode
 */

The timers are disabled during SLEEP_MODE_PWR_DOWN, so PWM doesn't work during SLEEP_MODE_PWR_DOWN. You could instead use SLEEP_MODE_IDLE, but that only saves a bit of current.
When you put the MCU to sleep, the led will keep the state it was in during PWM. So around 12.5% if the time the leds will be on, and the other times it will be off (during those 2s PWM periods).

Your second comment explains why I have seen light-on in sleep mode, and also why this is difficult to reproduce.

Just as a complement to Gerben's answer:

You could use SLEEP_MODE_PWR_DOWN during the off period, but
SLEEP_MODE_IDLE is the only way to do PWM while sleeping.
When in SLEEP_MODE_IDLE, you can use the power_*_disable()
function defined in <avr/power.h> in order to further
reduce the power consumption.

Really good info: “SLEEP_MODE_IDLE is the only way to do PWM while sleeping”.  I failed to find this in the ATmega docs.  I'm using what you suggested, thanks!

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


text:
Input from two microphones to bluetooth
I am a complete noob at arduino, so I apologize if this is a stupid question.
I would like to take input from two microphones and send the output to a bluetooth headset using an Arduino processor? Is this something that can be done with these processors or do I need something more powerful, like a Raspberry Pi?
I don't really need to process the signal at all, simply add the 2 inputs together and divide by 2 to keep the output from clipping.

There are bluetooth audio modules, which have an audio input or output. You have to search for one of these. Keep in mind that you cannot use a bluetooth serial module like HC-05 or HC-06. The audio mixing can be done via electronic components. This should be easier, that first sampling both audio signals to an Arduino and then output the resulting analog voltage again.

Your comment on combining the two inputs before digitizing makes perfect sense. Thanks.

The point was, that the bluetooth audio module should do the digitizing. In this case the Arduino is only used to provide an interface for establishing Bluetooth connections.


text:
RaspberryPi Pico SPI and nrf24l01
I am programming a RaspberryPi Pico with the Arduino IDE. Works pretty well, but now I try to control an nrf24l01 module.
My code compiles but I do not know on which pins the SPI bus has to be hocked up. I tried to connect to different pins according the pinout
https://datasheets.raspberrypi.org/pico/Pico-R3-A4-Pinout.pdf
(for example 2 sck, 3 miso, 4 mosi), but nothing worked so far.
Does anybody know what the default pins are or how to control them? I also would like to control other SPI hardware, for example a display.
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

const uint64_t address = 0x1;
byte sendData[1];

#define CSN_PIN  5
#define CE_PIN   6
RF24 radio(CE_PIN, CSN_PIN);

byte counter = 0;

void setup()
{
  Serial.begin(115200);
  Serial.println(“radio starting");

  if (!radio.begin())
  {
    Serial.println("radio hardware is not responding!!");
    while (1) {}
  }
  radio.openWritingPipe(address);
}

void loop()
{
  Serial.print("Counter: ");
  Serial.println(counter);

  sendData[0] = counter;

  radio.write( sendData, sizeof(sendData));

  counter++;
}

Did you successfully run it both transmission and receiving? Any capacitor you use? My experience is that when using Raspberry Pi Pico + NRF24L01 and on Micropython, it works BUT fails when programmed on Arduino

For Arduino-pico core
** MISO - pin GP16
** MOSI - pin GP19
** CS   - pin GP17
** SCK  - pin GP18

Arduino-mbed core
** MISO - pin GP4
** MOSI - pin GP3
** CS   - pin GP5
** SCK  - pin GP2

Fantastic, it works!

Source, and other pins hard-coded on the pico: https://github.com/arduino/ArduinoCore-mbed/blob/8e0a044330e88bde781eb4c509875ce94980659f/variants/RASPBERRY_PI_PICO/pins_arduino.h


text:
Arduino Pro Micro - switch off LEDs
I am using a Arduino Pro Micro as a keyboard (USB HID device). Each time I press a key, the RX LED and TX LED light up. Can I switch them off in software?

Kind of.
You don't have to change pins_arduino.h.
Try the LED_BUILTIN_TX and the LED_BUILTIN_RX.
The pins are turned on and off by the code for the SerialUSB port. That can not be changed without changing the Arduino libraries. Setting that pin to INPUT in your sketch in the setup() function will turn them off:
pinMode(LED_BUILTIN_TX,INPUT);
pinMode(LED_BUILTIN_RX,INPUT);

If you have troubles with the LED_BUILTIN_TX and the LED_BUILTIN_RX, then you can use this as well:
bitClear(DDRD,5);
bitClear(DDRB,0);

The code for the SerialUSB port still writes to that pin, but once they are set as INPUT, that code will turn on and off the pullup resistor. That is no problem since those leds are connected to VCC.
To turn them on is also possible, but then those pins needs to be OUTPUT and LOW. They will not stay on when the SerialUSB port is used.

Kind of.
You would need to edit the pins_arduino.h file for the Pro Micro board to change the definitions of the TXLED0, TXLED1, RXLED0, RXLED1 and TX_RX_LED_INIT macros.
You want them to all be defined, but empty.
#undef TXLED0
#undef TXLED1
#undef RXLED0
#undef RXLED1
#undef TX_RX_LED_INIT

#define TXLED0
#define TXLED1
#define RXLED0
#define RXLED1
#define TX_RX_LED_INIT

That will remove the current definitions, and then create new empty definitions.  Without the empty definitions, you will get errors when compiling.


text:
Arduino ESP8266 direct/fast control of the digital pins
How does one control a digital pin directly avoiding the slow digitalWrite or digitalRead?

One reads the datasheet.

in what manner is it slow? you know the clock speed of an ESP right?

digitalWrite and digitalRead have a lot of overhead since the input pin is a variable. I just tried the following code
void loop() {
digitalWrite(D3,HIGH);
digitalWrite(D3,LOW);
}    and it runs with 160kHz on a Wemos D1 mini. This is very slow for a micro controller running at 80MHz

Your question needs more detail.

@sa_leinad - no, it really doesn't need more detail - it's perfectly clear as is.  This is a pretty basic, and ordinary question.  It's quite well known how to do the analogous thing on an ATmega, and it makes perfect sense to have a question about doing it on the ESP8266, if that chip is going to be considered on-topic as an Arduino target at all.

After a weekend of searching and trying, here is what I was looking for:
It is slightly different than for the AVR chips. There is one register for setting the pins to HIGH and another one to set the pins to low.
Setting the pin HIGH:
GPOS = (1 << PIN_OUT);

Setting the pin LOW:
GPOC = (1 << PIN_OUT);

using this, I managed to speed up my code by a factor of three. It is not as dramatic as for the AVR chips, since the digitalWrite function is much more simple for the ESP8266.
Edit Further experiments show it is 10x faster: 910nsec for digitalWrite vs. 88nsec using GPOC or GPOS!

Unfortunately, Ratchet Freak's answer is specific to AVR, and isn't how the ESP8266 works.
It looks like the ESP8266 does indeed have registers for doing exactly this, which would let you set all 16 GPIO pins (GPIO0 through GPIO15, 16 is a different thing entirely) with a single operation. There's also a SET register, which sets the pins corresponding to 1 bits, and ignores pins corresponding to 0 bits, and a CLEAR register, which is the other way around.
Something I found on a forum said a user went from ~800KHz to ~5.7MHz toggling pins using these direct registers, that sounds about right.
One version of this is found in eagle_soc.h. The relevant bits from the header to get you started:
#define GPIO_REG_READ(reg)                         READ_PERI_REG(PERIPHS_GPIO_BASEADDR + reg)
#define GPIO_REG_WRITE(reg, val)                 WRITE_PERI_REG(PERIPHS_GPIO_BASEADDR + reg, val)
#define GPIO_OUT_ADDRESS                         0x00
#define GPIO_OUT_W1TS_ADDRESS             0x04
#define GPIO_OUT_W1TC_ADDRESS             0x08

So, if I've understood this correctly (and I haven't done any real testing, just going off the spec sheet and the header and posts elsewhere):
GPIO_REG_WRITE(GPIO_OUT_ADDRESS, 0xF0F0);

would set GPIO 4-7 and 12-15 to high, and 0-3 and 8-11 to low. In one operation. But there's more! Look at those W1TS and W1TC names. Those are set and clear registers. Which means you don't have to mask things. Instead of grabbing the current value, masking a bit in or out, and then writing it back, you can use those:
GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, 0x1);

This will set GPIO0 high, and not affect any other bits.
This is also offered in a cleaner/simpler (??) form in esp8266_peri.h, which simplifies it to:
GPOS = 0x1;

for setting a bit. This is what's actually called by the arduino library's digitalWrite (for pins other than GPIO16):
extern void ICACHE_RAM_ATTR __digitalWrite(uint8_t pin, uint8_t val) {
  pwm_stop_pin(pin);
  if(pin < 16){
    if(val) GPOS = (1 << pin);
    else GPOC = (1 << pin);
[...]

But definitely be aware of this if you're doing anything fast, because writing multiple pins with a single operation is going to be way faster than multiple function calls. Without this, this chip can't even toggle bits as fast as a 16MHz Arduino.

In the spec sheet you will find the details for your device but most of the time it's pretty simple.
There will be global variables to control them, each will control various aspects of the pins.
For example you will have a register to control whether it's input or output, a register to control the output state, ... Again read the spec for your device to know what is what.
After the pin has been set up the instruction to set a pin high is:
PORTA |= PINx_MASK;

where Pinx_MASK is a bit mask with a single bit set according to the pin it represents.
To set the pin low it's similar:
PORTA &= ~PINx_MASK;

To set multiple pins on the port to different values you can do the following:
PORTA = (PORTA & ~pinsMask) | pinValues;

where pinsMask is a bitmask where all the pins you want to change are set and pinValues is the bitmask of which pins should be set high.
It pays to know how to manipulate bits in bitmasks but that's out of scope for this answer.
The SDK will be doing direct port manipulation itself, if you follow the definitions you should be able to figure it out.

this looks like AVR code, did you test it on the ESP?

This works for a platform with Atmel AVR chips like the Arduino Uno, Nano,..., but it does not not work for ESP8266. I am fully aware of exactly this trick and want to know if it exists for the ESP8266.

"There will be global variables to control them". This are not global variables, these are registers. When you did this to a variable no pin will change.


text:
Ultrasonic distance module works without connecting to gnd
I have a (HCSR04) ultrasonic distance module connected to arduino , i have connected all the four pins of the module properly and its working fine , then when i pull off the wire which is connected to ground in arduino , the module works totally fine . How the module works without connecting its ground pin to arduino ground ?

It's not uncommon for part to "sort of" work when one of the supply rails is missing and an input signal of the some polarity somewhat substitutes for it, often through built-in ESD protection diodes.  In this case, the trigger input when idle is low, and there's probably some capacitance on the board that could hold it through the brief trigger pulse.
It's a bad idea to rely on this though, both as it typically means stressing parts by operating them outside of specified limits, and can also produce not-quite reliable behavior.
For example, I once wired an SPI flash chip on a small carrier stuck underneath an MCU eval board, in order to test some software for a board I was designing.  It worked great.  Or I should say, it did right up until I tried to write to it, which would always fail.  Eventually I discovered that I'd forgotten the ground connection when wiring it up.  It was able to return enough current through the I/Os to perform read operations, but not to support a write.


text:
Reduce PWM Frequency Arduino DUE
I'm newbie in arduino due. I need to reduce the default PWM frequency of arduino Due. Anyone have any tutorial to do this? (Frequencys like 25hz, 50Hz for example)
I read in some posts, if i change the PWM frequency, i make changes in internal timers of arduino and i loss functions like delay(), millis(), etc.
Exits any form to not lose these functions?
Thanks a lot!

25 and 50 hz square wave can be generated by software easily

The Palatis Softpwm library can generate PWM on any digital pin with (almost) any frequency. Example for 25Hz:
#include <SoftPWM.h>
SOFTPWM_DEFINE_CHANNEL(0, DDRB, PORTB, PORTB2);  //Arduino pin 10
void setup() {
  // begin with 25Hz pwm frequency
  Palatis::SoftPWM.begin(25);
  Palatis::SoftPWM.set(0, value); // value is 0 to 255 just like normal Arduino analogWrite
}


text:
Interference in readings
I have an project which control a heat exchanger.
I read 4 temperature sensors DS18B20, a distance with HC-SR04 Ultrasonic Sensor, and a flow with YF-S201 (with attach interrupt). I can turn on and off a monophasic motor with Arduino too.
I have many interference problems with i turn on my motor, the readings of temperature fail with big frequence and i have many errors with interrupt counter.
I read many posts about interferences, and one most important factors are high impedance of floatings pins.
I use Arduino Due, then many pins are floating. I have to put a pull-down resistors in all pins?
My project looks like the architeture in the image link bellow:
https://i.sstatic.net/glo5L.jpg
The code of my project can be found in :
https://github.com/felipefonsecabh/ArduinoCode/blob/ArduinoNoNavigation/ArduinoCode.ino
Any opinion?

The motors are connected directly to the Arduino? Or do they contain their own driver circuitry...?

I used SSr (Solid State Relay) to turn on and turn off my motor.

Why doesn't your diagram show the SSRs then?

Don't use the weak internal pullup, use external pullup resistors. For example with 4k7 for the 1-Wire bus, the buttons, and perhaps the flow meter as well. Check your grounding thoroughly, and after that check it once more. Don't let the returning current of the motors reach the GND of the Arduino Due board. A LM35 is never accurate, unless your voltage is perfectly accurate and stable. I'm sorry to say, but the usage of millis is totally wrong. Rewrite that. Use the blink without delay example: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay The temp[0...3] is used for different things.

I disagree about usage of millis ... i try to use the same way of this example (blinkwithout delay) ...what's wrong?

You can do the substraction of the millis at this moment minus a previous stored millis (millis() - previousMillis), but you may not add something to a stored value and compare that with millis.


text:
arduino loRa module search tutorial
I recently purchased a LoRa module (https://it.aliexpress.com/item/1005002116232826.html?spm=a2g0s.9042311.0.0.38c74c4dPnh2Gg) but I have not found any working tutorial for this model can you help me

this may help ... https://github.com/Lora-net/LoRaMac-node


text:
Why does my stepper motor run when I open the Serial port?
For some reason my motor moves a certain amount every time I open the serial port without giving it any other instructions. It will move further by the same amount if I close and reopen the serial port. Please could someone tell me how to avoid this? I haven't had this problem before.
I am using two stepper motors with a A4988 driver each.
Here is my code so far
#include <AccelStepper.h>
#include <MultiStepper.h>

// Define pin connections
const int dirPin1 = 2;
const int stepPin1 = 3;
const int dirPin2 = 4;
const int stepPin2 = 5;

String incomingByte; // for incoming serial data

// Define motor interface type
#define motorInterfaceType 1

// Creates an instance
AccelStepper stepper1(motorInterfaceType, stepPin1, dirPin1);
AccelStepper stepper2(motorInterfaceType, stepPin2, dirPin2);

MultiStepper steppers;

void setup() {
  Serial.begin(9600);
  String excess1 = Serial.readString();
  // Configure each stepper
  stepper1.setCurrentPosition(0);
  stepper2.setCurrentPosition(0);
  stepper1.setMaxSpeed(100);
  stepper2.setMaxSpeed(100);
  stepper1.setAcceleration(10);
  stepper2.setAcceleration(10);
  // Then give them to MultiStepper to manage
  steppers.addStepper(stepper1);
  steppers.addStepper(stepper2);
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {
    // read the incoming byte:
    incomingByte = Serial.readString();

    // say what you got:
    Serial.print("I received: ");
    //Serial.println(incomingByte, DEC);
    Serial.println(incomingByte);

    int x = incomingByte.toInt();

    long positions[2];

    positions[0] = x;
    positions[1] = 0;
    steppers.moveTo(positions);
    steppers.runSpeedToPosition();
  }
}

add serial.print() statements into your code so that you can determine how the program is progressing ... the Uno is probably resetting

That makes sense that the Uno would reset when the serial port is opened, but the motor shouldn't move if the current position is set to zero each time and there are no new instructions to move. I have included the line below to flush the serial buffer, so there shouldn't be any new instructions.
'''
String excess1 = Serial.readString();
'''

When you open or reopen the Serial port, the Arduino resets (depending on how you open it; some programs don't send the signal on DTR or RTS, which result in the reset).
My guess is, that the stepper driver reacts to the Arduino configuring its pins for the stepper. Difficult to say, what exactly happens there. To mitigate that, you can add an external pulldown resistor (assuming you have an active high stepper driver. For active low use a pullup resistor). That should keep the step line of the driver low even when its not actively driven by the Arduino.


text:
DC motor with slow speed to actuate mirrors
I am thinking to use Arduino to control a DC motor and apply a small torque to move the mirrors of my interferometer experiment. I have the components from the Arduino Starter Kit K000007, just to understand how it works because I am approaching it just now.
The mirror mount has a knob with a 2mm Hex hole and each revolution corresponds to a displacement of 50 microns: I would need a speed around 1/50 revolution/second, or even less. Is it possible to move the motor that slow?
Moreover, I should use a coupler to interface the motor with the knob, basically some joint to connect the shaft to a 2mm Hex bar or something: could you suggest a way to do so?

DC motors are made for spinning. Trying to spin it in sub full revolution steps is not really possible. But you can use a geared DC motor, where the rotor after the gear is slow enough for your purpose. Also this can give you enough torque for moving the knob (since small DC motors are often rather weak by their own). You can find geared DC motors with many different values (torque, voltage, speed, gear ratio, size...) at the typical online sellers. The small ones are rather cheap, so you might just buy some and test out, whats fitting for you. Otherwise you would need to set exact requirements for torque and speed (and maybe other parameters) and then search for a fitting one.
Also keep in mind, that you need something like a driver circuit for the motor. Since you will want to drive it in both directions, a H-bridge is needed. You can build those yourself with transistors, or buy a small chip, which incorporates the complete H-bridge (make sure to use one with MOSFETs in it, since they are more efficient). Also don't forget the flyback diode to avoid killing the electronics with the induction voltage from the motor.

I should use a coupler to interface the motor with the knob, basically some joint to connect the shaft to a 2mm Hex bar or something: could you suggest a way to do so?

Yes, you need some kind of coupler. But we cannot really suggest something here. It depends totally on your exact setup. This mechanical part will be something, that you have to design. There are different kinds of couplers available online, but I don't know, if they are good for your purpose.
Also maybe you should make sure to make the coupler flexible on the other axes than the rotation axis. That way the motor will not stall when a small disalignment happens, and the vibrations from the motor might not get transmitted to your mirror as much. I know this principle from my 3D printer, which uses a coupler like this one:

Thank you! As I need a ratio of severlal thousands to one, I have to use a gearbox for sure. For the H bridge yes, I saw it in one of the projects contained in the starter kit, thus I should be covered for that.Regarding the coupler, I think that I could ask the university workshop to manufacture one similar to the one you suggested very easily.


text:
ESP32S v1.1 NodeMcu vs ESP32 DevKitV1
I have two different ESP32 development boards labelled "ESP32S v1.1 NODEMCU" (A) and "ESP32 DEVKITV1" (B).  From what I can tell they have the same major components, but their pins and general layout are quite different. I assume they are both knock-offs.

When uploading from the Arduino IDE, both read the same revision number and features:
Chip is ESP32-D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
Crystal is 40MHz

From what I can tell NodeMcu has something to do with the firmware for the ESP8266 (wiki)?  Also, it seems my ESP32S NodeMcu board doesn't have the standard pin layout for ESP32 boards.
What exactly is this NodeMcu board and what are the differences between the two?

there's lots of wroom modules, all vary slightly in pinout, serial chip, component selection, etc; but they all do the same basic thing as far as arduino is concerned. I try to find ones with 36+ pins and pin labels on both sides of the board, and that are cheap.

The DevKit is a development board by ESP32 manufacturer Espressif to demonstrate ESP32 usage and to support prototyping.
The NodeMcu is a board by NodeMcu intended for the NodeMcu Lua language firmware.
There is no standard pinout. The labels on the DevKit are io pin numbers of the MCU.
You can use both development boards with the ESP32 "Arduino boards support package".

I wrote to Espressif asking about the ESP32 DEVKITV1 and they said they don't manufacture it. It appears to be made by this company: https://www.doit.am/#/mozu


text:
How to control 12v water pump by arduino?
I have arduino uno and I've bought 12 Volt/350 GPH Seaflo Electric Bilge Pump, how to control it directly from arduino?

Google for MOSFET and you should find the start of a solution to this problem.

It's not possible to control it directly. You need relay module (better one is with opto coupler).
Or you can use some N-Mosfet like IRF540 with antiparallel fast diode to supress induced high voltage from coil. However arduino output might be weak for fast charge/discharge mosfets gate and it gets hot.


text:
Webserver on Arduino: Refresh issues
I am using W5100 Ethernet Shield Network Module with arduino Uno as a webserver to trigger four relays connected to it.
The relays may be toggled through the four buttons attached to it physically, or through the four buttons on the hosted webpage. There is a counter how many times the relays are toggled which can be reset through a button on the webpage.
My issue is, whenever I toggle the relay through physical button, it does not update the counter on the webpage. And if I refresh the page, the last command from the page, such as togglerelay1 keeps echoing.
What solution do you propose to this problem:
#include <SPI.h>
#include <Ethernet.h>

int Relay1 = 2;
int Relay2 = 3;
int Relay3 = 4;
int Relay4 = 5;
int Button1 = 8;
int Button2 = 9;
int Button3 = 10;
int Button4 = 11;

String on = "On";
String off = "Off";

String Relay1Status = on;
String Relay2Status = on;
String Relay3Status = on;
String Relay4Status = on;

int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;

byte toggle1 = LOW;
byte toggle2 = LOW;
byte toggle3 = LOW;
byte toggle4 = LOW;

void toggleRelay1();
void toggleRelay2();
void toggleRelay3();
void toggleRelay4();

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //physical mac address
byte ip[] = { 172, 168, 1, 178 };                      // ip in lan (that's what you need to use in your browser. ("192.168.1.178")
byte gateway[] = { 172, 168, 1, 1 };                   // internet access via router
byte subnet[] = { 255, 255, 255, 0 };                  //subnet mask
EthernetServer server(80);                             //server port
String readString;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  pinMode(Relay1, OUTPUT);
  pinMode(Relay2, OUTPUT);
  pinMode(Relay3, OUTPUT);
  pinMode(Relay4, OUTPUT);
  pinMode(Button1, INPUT_PULLUP);
  pinMode(Button2, INPUT_PULLUP);
  pinMode(Button3, INPUT_PULLUP);
  pinMode(Button4, INPUT_PULLUP);
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {

  if (digitalRead(Button1) == LOW) {
    toggleRelay1();
    while (digitalRead(Button1) == LOW);
  }
  if (digitalRead(Button2) == LOW) {
    toggleRelay2();
    while (digitalRead(Button2) == LOW);
  }
  if (digitalRead(Button3) == LOW) {
    toggleRelay3();
    while (digitalRead(Button3) == LOW);
  }
  if (digitalRead(Button4) == LOW) {
    toggleRelay4();
    while (digitalRead(Button4) == LOW);
  }

  // Create a client connection
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += c;
          //Serial.print(c);
        }

        //if HTTP request has ended
        if (c == '\n') {
          Serial.println(readString); //print to serial monitor for debuging
          homepage();
          //controls the Arduino if you press the buttons
          if (readString.indexOf("?resetcount1") > 0) {
            count1 = 0;
          }
          if (readString.indexOf("?resetcount2") > 0) {
            count2 = 0;
          }
          if (readString.indexOf("?resetcount3") > 0) {
            count3 = 0;
          }
          if (readString.indexOf("?resetcount4") > 0) {
            count4 = 0;
          }
          if (readString.indexOf("?togglerelay1") > 0) {
            toggleRelay1();
          }
          if (readString.indexOf("?togglerelay2") > 0) {
            toggleRelay2();
          }
          if (readString.indexOf("?togglerelay3") > 0) {
            toggleRelay3();
          }
          if (readString.indexOf("?togglerelay4") > 0) {
            toggleRelay4();
          }
        }
      }
    }
  }
  //clearing string for next read
  readString = "";

}

void toggleRelay1() {
  toggle1 = !toggle1;
  digitalWrite(Relay1, toggle1);
  if (toggle1 == HIGH) {
    count1++;
    Relay1Status = on;
  }
  else
    Relay1Status = off;
}

void toggleRelay2() {
  toggle2 = !toggle2;
  digitalWrite(Relay2, toggle2);
  if (toggle2 == HIGH) {
    count2++;
    Relay2Status = on;
  }
  else
    Relay2Status = off;
}

void toggleRelay3() {
  toggle3 = !toggle3;
  digitalWrite(Relay3, toggle3);
  if (toggle3 == HIGH) {
    count3++;
    Relay3Status = on;
  }
  else
    Relay3Status = off;
}

void toggleRelay4() {
  toggle4 = !toggle4;
  digitalWrite(Relay4, toggle4);
  if (toggle4 == HIGH) {
    count4++;
    Relay4Status = on;
  }
  else
    Relay4Status = off;
}

void homepage() {
  client.println("HTTP/1.1 200 OK"); //send new page
  client.println("Content-Type: text/html");
  client.println("Connection: Close");
  client.println();
  client.println("");
  client.println("");
  client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
  client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
  client.println("<link rel='stylesheet' type='text/css' href='http://randomnerdtutorials.com/ethernetcss.css' />");
  client.println("<TITLE>Relay Control System</TITLE>");

  client.println("");
  client.println("");
  client.println("
Relay Control System
");
  client.println("
");
  client.println("
");

  client.println("
Relays Status
");
  client.println("
");

  client.println("Relay 1 Status: ");
  client.println(Relay1Status);
  client.println("
");

  client.println("Relay 2 Status: ");
  client.println(Relay2Status);
  client.println("
");

  client.println("Relay 3 Status: ");
  client.println(Relay3Status);
  client.println("

");

  client.println("Relay 4 Status: ");
  client.println(Relay4Status);
  client.println("

");

  client.println("Number of times Relay1 has been activated: ");
  client.println(count1);
  client.println("Reset Counter");
  client.println("

");

  client.println("Number of times Relay2 has been activated: ");
  client.println(count2);
  client.println("Reset Counter");
  client.println("

");

  client.println("Number of times Relay3 has been activated: ");
  client.println(count3);
  client.println("Reset Counter");
  client.println("

");

  client.println("Number of times Relay4 has been activated: ");
  client.println(count4);
  client.println("Reset Counter");
  client.println("

");

  client.println("Toggle Relay1");

  client.println("Toggle Relay2");

  client.println("Toggle Relay3");

  client.println("Toggle Relay4");

  client.println("");
  client.println("");

  delay(1);
  //stopping client
  client.stop();
}

Instead of always responding with the homepage() for every request you should respond specially to the command requests with a 307 temporary redirect code to make the browser request the index page afresh
client.println("HTTP/1.1 307 Temporary Redirect");
client.println("Location: /");
client.println("Connection: Close");
client.println();
client.stop();

So the client gets /?togglerelay3, which happens, and then gets sent a reply telling it to make a new request to get / which it then does to get the new status. The URL in the browser will not have the ?togglerelay3 in it, so refreshing won't cause the command to be run again.
If you want live updating of the page with new count values as they happen you will have to be more cunning. Either use AJAX and JavaScript in the page to fetch new values to display, or periodically refresh the page (with a META Refresh).


text:
OSCOKIRQ failed to assert with USB HOST and SD card
I am having an issue using a MAX 3421 EE based Arduino USB Host shield and an SD card shield. From my understanding, they should both function as long as they are using different CS/SS pins and only one is active at a time. I have connected the SD card CS pin to pin 4. I am trying to write a program that reads an ACM terminal and writes that data to a file on the SD card (see code below). When the SD card is not powered the USB host shield reads the ACM and prints it to serial fine. However, immediately when I connect the SD card shield power, it starts printing "ACM not ready." On a reset, it prints "OSCOKIRQ failed to assert."
Troubleshooting steps I have already tried:

External power source.
Removing SD card from the reader.
Commenting out all SD Card code.
Disconnecting USB Device (to see if initialization still works)

None of these steps have helped solve the USB initialization issue.
My code:
//Lots of Code from https://github.com/felis/USB_Host_Shield_2.0/blob/master/examples/acm/acm_terminal/acm_terminal.ino
#include <cdcacm.h>
#include <usbhub.h>

#include "pgmstrings.h"

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif

#include <SPI.h>
//#include <SD.h>

//https://github.com/felis/USB_Host_Shield_2.0.git
class ACMAsyncOper : public CDCAsyncOper{
public:
    uint8_t OnInit(ACM *pacm);
};

uint8_t ACMAsyncOper::OnInit(ACM *pacm){
    uint8_t rcode;
    // Set DTR = 1 RTS=1
    rcode = pacm->SetControlLineState(3);

    if (rcode)
    {
        ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode);
        return rcode;
    }

    LINE_CODING lc;
    lc.dwDTERate    = 115200;
    lc.bCharFormat  = 0;
    lc.bParityType  = 0;
    lc.bDataBits    = 8;

    rcode = pacm->SetLineCoding(&lc);

    if (rcode)
        ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode);

    return rcode;
}

const int USBChipSelect = 10;
USB     Usb;
//USBHub     Hub(&Usb);
ACMAsyncOper  AsyncOper;
ACM           Acm(&Usb, &AsyncOper);

const int SDChipSelect = 4;
/*
const int maxLog = 10000;
volatile int logged = 0;
volatile long name = 0;
*/
void setup()
{
    Serial.begin(115200);
    Serial.println("Start");

    pinMode(USBChipSelect, OUTPUT); // Sets USB CS pin output
    pinMode(SDChipSelect, OUTPUT); //Sets SD CS pin output
    digitalWrite(SDChipSelect,HIGH);
    digitalWrite(USBChipSelect,HIGH);

    USBActive();

    if (Usb.Init() == -1){
    Serial.println("OSCOKIRQ failed to assert");
  }

    delay(500);
}

void loop(){
    String toWrite = "Error";

    toWrite = readACM();
    Serial.println(toWrite);

    if(logged>=maxLog){
        logged = 0;
        name++;
    }
    /*
    SD.begin(SDChipSelect);
    File dataFile = SD.open(String(name), FILE_WRITE);
    if(dataFile){
        dataFile.println(toWrite);
        dataFile.close();
    }*/
    delay(100);
}

//Activates USB and Deactivates SD
void USBActive(){
    digitalWrite(SDChipSelect,HIGH);
    digitalWrite(USBChipSelect,LOW);
}

//Activates SD and Deactiavates USB
void SDActive(){
    digitalWrite(USBChipSelect,true);
    digitalWrite(SDChipSelect,false);
}

String readACM(){
  Usb.Task();

  if( Acm.isReady()) {
       uint8_t rcode;

        /* reading the phone */
        /* buffer size must be greater or equal to max.packet size */
        /* it it set to 64 (largest possible max.packet size) here, can be tuned down
        for particular endpoint */
        uint8_t  buf[64];
        uint16_t rcvd = 64;
        rcode = Acm.RcvData(&rcvd, buf);
         if (rcode && rcode != hrNAK)
            ErrorMessage<uint8_t>(PSTR("Ret"), rcode);

        if( rcvd ) { //more than zero bytes received
            char rcvdData[rcvd];
            for(uint16_t i=0; i < rcvd; i++ ) {
                rcvdData[i] = (char)buf[i]; //printing on the screen
            }
            return String(rcvdData);
        }
    }
    return String("ACM Not Ready");
}

Thanks in Advance.

As I remember SD cards don't behave well on the SPI bus. They are blocking all other devices.

If they block all other SPI devices why do they still have a CS line? Isn't the CS line to select which device on the SPI bus to use.

Found this question, which suggests, that the problem lies with the cheap sd card modules, not with the cards themselves. I guess you use one of these modules, since you have to convert the 5V level of the Arduino to the 3.3V of the SD card.

Ok, I thought the SD card module was a bit too cheap but it worked fine on its own. Any suggestions for an SD card module (preferably MicroSD) that does this properly?

the Adafruit SD adapter is good


text:
SEN0114 moisture sensor low max reading?
I am using the following SEN0114 moisture sensor with an ESP32:  https://datasheetspdf.com/datasheet/SEN0114.html
How come when submerged in water I only get a reading of ~2500?  Should this not read ~4095 as the ESP32 analog pins are 12-bit?

What voltage is it producing when submerged?

I can't measure that directly but I would assume 2V based on the 2500 analog reading?  Would I need to check this with a volt meter?

Well, if you measure it, you can know.  And then your question really has nothing to do with the sensor, and only to do with analogRead with a given input voltage, which is a better question, IMO.  Either that or you're going to discover your understanding about the sensor is wrong, and that will have some value.

This is a resistive sensor and "plain" water is not infinitely conductive. In fact, pure or distilled water is a very poor conductor. Also, "plain" water - tap water, I assume - will vary in its dissolved solids, not only from source to source, but likely over time, too, for some sources and it is these solutes that are responsible for increased conductivity. That goes double for plant-moisture sensing because it is really measuring the resistance of damp dirt, which again, varies in composition.
So the sensor can give you a range from dry to very moist, per plant, but the absolute measurements won't be very meaningful.


text:
Arduino recieve sensor data from other arduino SPI
I have Arduino Uno (sender) and Arduino Uno Wifi rev 2 (receiver). I want to send the ping value to the other one via serial - jumper wires.
Arduino Uno is using the newping example, and I want the Uno Wifi to receive the sensor value and print it to serial.
I am using SoftwareSerial.h
jumper wires go TX<->RX , RX <->TX, GRD-GRD according to the pins in the sketch below.
The problem is the sketch code for the Uno WiFi (receiver), it keeps printing garbage and seems like no carriage return sometimes.
13
⸮10
⸮52
⸮5LC⸮1⸮H⸮10
5⸮H⸮51
13C⸮10
⸮5⸮H⸮5LC⸮13
10
⸮52
51C⸮13
10
⸮52
5LC⸮13
⸮10C⸮52
⸮51
13
10
⸮52
50

Code on Uno (sender):
// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------
#include <SoftwareSerial.h>
#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
SoftwareSerial mySerial(9, 10); // RX, TX

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

 Serial.println("Hello World Serial");
 mySerial.begin(4800);
 mySerial.println("Hello World, mySerial");
}
void loop() {
  delay(500);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
  mySerial.print(sonar.ping_cm());
  mySerial.println();
  }

code on uno wifi (reciever):
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);

}

void loop() { // run over and over

    Serial.println(mySerial.read());
    delay(1000);

}

I can see the Uno (sender) with NewPing is printing the correct data to it's serial but I can't get the Uno wifi (listener) to get the same value. Its just garbage. I am new to this, what am I doing wrong?

reduce the sender code ... only send fixed values ... remove all code that is not associated with sending mySerial data ... no Serial, no sonar

Try replacing the receiving Serial line with if(mySerial.available()) Serial.write(mySerial.read());

Well I have gotten a bit farther. I used Serial.write and on the recieving Arduino I get values just not the correct one. The serial on the sender is sending value- 32, on the recieving arduino with - SonarReading=(mySerial.read()); I get numbers like 240, 241, ...

Well had a bit of luck after spending all day on this.
Arduino UNO (sender): Like mentioned by chrisl, use Serial.write and not Serial.print
mySerial.write(sonar.ping_cm());

UNO Wifi (receiver):
Serial.println(mySerial.readString());

So, instead of mySerial.read I used mySerial.readString.
This is most likely a obvious mistake to almost everybody here; took me two days. Sigh.


text:
Arduino buzzer code sequence not triggering
I have a problem with my arduino buzzer:
the code should be doing the following:
I have a security system where in order to open the door you have to enter a 4 digit code from the remote. If the code is correct the door opens. if not you can try again.
You have 3 chances to try to enter the pin before an alarm goes on. here comes the problem: the alarms code triggers but the buzzer isn't making any sound.
here is the code for the alarm sound:
if (tryCount>=3) { // if the pin is wrong 3 times we sound an alarm
    Serial.println("got in alarm");
    while(true) {
        Serial.println("got in while");
        noTone(buzzer);
        tone(buzzer,100,300);
        delay(300);
        noTone(buzzer);
        tone(buzzer,1000,300);
        delay(300);
    }
}

here is the proof the alarm code triggers:

here is the full code:
https://create.arduino.cc/editor/mihimbc/8ec2fe30-d812-45cc-b0ae-850b437eb05b/preview
and here is the hardware schematics:

Is the buzzer an active or a passive one? Only passive buzzers can be driven via tone(). Active buzzers can only switched on or off via digitalWrite()

it's an active one.
to mention: when i move the instruction for the buzzer inside the loop it works, but in that specific part of the program doesn't.
and it's strange that accordingly to the Serial.println that i've put inside the while it seems that its getting there but but no sound is coming from the buzzer

The problem was with the buzzer, somehow was a faulty buzzer, I've managed to replace it and the problem was solved.
Thanks everybody for your time trying to help me!


text:
I2C Packet ocasionally send a garbage data
I have a project with Arduino working as I2C slave.
The master request data each 300ms.
The code of Arduino is:
/*
  Name:     SimpleClass_Applcation.ino
  Created:  5/26/2017 4:18:28 PM
  Author:   Felipe Fonseca
  Description: Versão de Código para o Trocador de Calor de forma a simplificar
  a operçãoo para tornar possível a utilização em aulas
*/

//includes

//Libs dos sensores
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Ultrasonic.h>

//display lcd
#include <LiquidCrystal.h>

//timed action
//#include <Utility.h>
//#include <TimedAction.h>

//lib i2c
#include <Wire.h>

//gerar sinais
#include <waveforms.h>

//Pinos de entrada e sa�da

#define but1 A1  //no programa de testes 42; no original, trocar por A1  //
#define but2 A2  //no programa de testes 44; no original trocar por A2
#define pot A0 //no programa de testes A7; no original trocar por A0

#define mode_switch 42  //no programa de testes 43; no original trocar por 42
#define emergency_button 43 //no programa de testes 51; no original  trocar por 43

#define ultrassonico_echo   50      //no original trocar para 50
#define ultrassonico_trigger 48     //no original trocar para 48
#define ONE_WIRE_BUS 52             //no original trocar para 52  - terminal do conjunto de sensores
#define hf_sensor 9                //no original trocar para 9 -> pino de interrup��o para calculo da vaz�o agua fria
#define TEMPERATURE_PRECISION 12

#define led1 44                  // utilizado para sinalização geral
#define led2 45                  // utilizado para sinalização geral
#define led_heater 47            // no programa de testes 37; no original trocar para 47

#define inversor_rele 49        //no programa de teste 47;no original trocar para 49
#define heater_rele 10          //no programa de testes 49;no original trocar para 10

#define MAX_MENU_ITENS 2         //numero de telas no menu

//testes em prototipo
#define LDR_PIN A3
#define LM35_PIN A4
#define RXLED 3
#define oneHzSample 1000000/maxSamplesNum //gerador de sinais
#define SIMULATORSAMPLETIME 500

float LM35_value;
float LDR_value;

//vari�veis internas

//armazenar valores de entrada
bool switch_state;
int pot_value;
bool emergency_status;

volatile int pump_onoff;
volatile int heater_onoff;
volatile float remote_pumpspeed;

float temp[4];
double vazao_quente;
float vazao_fria;
volatile int flow_frequency;

//estrutura de dados para envio i2c
typedef struct processData {
  float temp1;
  float temp2;
  float temp3;
  float temp4;
  float hotflow;
  float coldflow;
  float pump_speed;
  byte bstatus;
  byte chksum;
};

typedef union I2C_Send { //compartilha a mesma área de memória
  processData data;
  byte I2C_packet[sizeof(processData)];
};

I2C_Send send_info;
int command; //processar o indice de comando enviado pelo Rpi

//array de bytes auxilar para receber a velocidade da bomba
byte data[4];

//estrutura para receber um float para alterar velocidade
typedef union PumpDataSpeed {
  float fspeed;
  byte bspeed[4];
};

//variáveis utilizadas no calculo de vazao de agua fria/quente
unsigned long currentTime;
unsigned long cloopTime;
long microsec;
float cmMsec;
float nivel;
//float vazao1_sf;   //se for necessário para a função de vazao quente, descomentar

//variáveis auxiliares para operação local
char flag_button1 = 0x00;
char flag_button2 = 0x00;
char flag_emergency = 0x00;
String mode = "";

//variáveis auxiliares para comando
float pot_value_mapped;

//variáveis para o simulador
unsigned long current_sim_time;
unsigned long simulator_time_elapsed;
int indexwave;

//inicialização de objetos
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DeviceAddress deviceID[] =
{
  { 0x28, 0xFF, 0x46, 0x02, 0x54, 0x16, 0x04, 0xF8 },
  { 0x28, 0xFF, 0xD3, 0xE6, 0x53, 0x16, 0x04, 0xA0 },
  { 0x28, 0xFF, 0xE8, 0xF0, 0x53, 0x16, 0x04, 0x65 },
  { 0x28, 0x1D, 0x9D, 0x27, 0x00, 0x00, 0x80, 0x2E }
};
//delay necessário para leitura dos sensores. Depende da resolução
int delayTempRead = 0;
int lastTempRequest = millis();

Ultrasonic ultrasonic(ultrassonico_trigger, ultrassonico_echo);

LiquidCrystal lcd(41, 11, 12, 40, 13, 38);  //no original deve-se utilizar  LiquidCrystal lcd(41, 11, 12, 40, 13, 38);

//funções
void ReadPotentiometer();
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max);

//funções de navegação  - Display LCD
void Menu(int op);
void EmergencyStatus();

//funções de leitura de grandezes
void flow();                //função de interrupção para o calculo de vazao de água fria
void PumpSpeed(float ref);  //função para alterar a velocidade da bomba
void VazaoAguaFria();       //função para calcular a vazão de água fria
void VazaoAguaQuente();     //função para calcular a vazão de água quente
void Temperaturas();        //função para calcular as temperaturas dos sensores
void new_Temperaturas();

//funções do estado do arduino
void LocalState();
void RemoteState();
void emergencia();

//funções para fazerem a leitura periodica dos valores analógicos
void runReads();
void refresh_I2C_Packet();

//função para receber o valor em bytes via i2c e retornar a velocidade em float
void parseSpeed(byte data[]);

//testes em prototipo
void Temperaturas2();
void Simulator();

// the setup function runs once when you press reset or power the board
void setup() {
  //painel
  pinMode(but1, INPUT_PULLUP);
  pinMode(but2, INPUT_PULLUP);
  pinMode(pot, INPUT);
  pinMode(mode_switch, INPUT);
  pinMode(emergency_button, INPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led_heater, OUTPUT);

  //sensores
  pinMode(ultrassonico_echo, INPUT);
  pinMode(ultrassonico_trigger, OUTPUT);
  pinMode(hf_sensor, INPUT_PULLUP);
  pinMode(ONE_WIRE_BUS, INPUT_PULLUP);

  //reles
  pinMode(heater_rele, OUTPUT);
  pinMode(inversor_rele, OUTPUT);

  //começar inversor desligado
  digitalWrite(inversor_rele, HIGH);

  //habilitar a interrupção para medição de vazão fria
  //attachInterrupt(hf_sensor, flow, RISING);

  //iniciar sensores de temperatura
  sensors.begin();
  for (byte i = 0; i <= 4; i++) {
    sensors.setResolution(deviceID[i], TEMPERATURE_PRECISION);
  }
  //modo de leitura assincrona
  //sensors.setWaitForConversion(false);
  delayTempRead = 750 / (1 << (12 - TEMPERATURE_PRECISION));

  //iniciar lcd
  lcd.begin(20, 4); //no original utilizar 20,4

  //resolução de escrita do DAC
  analogWriteResolution(10);

  //variáveis que guarda o status da bomba e do aquecedor
  pump_onoff = 0;
  heater_onoff = 0;

  //inicialização da serial
  Serial.begin(115200);

  //inicialização de variáveis
  vazao_fria = 0;
  vazao_quente = 0;

  //inicialização da estrutura i2c
  send_info.data.chksum = 27;
  Wire.begin(12); //arduino iniciado no endereço 12
  Wire.onReceive(receiveEvent); //callback para recebimento de comandos
  Wire.onRequest(requestEvent); //callback para responder à requisições

  //semente para o simulador
  randomSeed(analogRead(LM35_PIN));
  indexwave = 0;
}

// the loop function runs over and over again until power down or reset
void loop() {

  // le o estado da chave
  switch_state = digitalRead(mode_switch);

  /* lê se o botão de emergencia está acionado ou não
      cobre os casos de pressionar o botão e despressionar o botão
  */
  if (digitalRead(emergency_button) == LOW) { //presisonado botão
    emergencia();
  }
  else if (!digitalRead(emergency_button) == LOW && flag_emergency) { //despressionado o botão
    flag_emergency = 0x00;
    emergency_status = 0;
    lcd.clear();
    if (switch_state) {
      RemoteState();
    }
    else {
      LocalState();
    }
  }
  else { //tudo normal
    if (switch_state) {
      RemoteState();
    }
    else {
      LocalState();
    }
  }
}

//função de interrupção para calcular a vazão
/*void flow() {
  flow_frequency++;
}*/

//funções que gerenciam o estado do arduino

void LocalState() {

  //efetua a leitura das grandezas
  runReads();

  //atualiza o lcd com os novos valores
  Menu(0);

  if (!digitalRead(but1)) flag_button1 = 0x01;
  if (!digitalRead(but2)) flag_button2 = 0x01;

  if (digitalRead(but1) && flag_button1) {
    flag_button1 = 0x00;
    //troca o estado da bomba
    digitalWrite(inversor_rele, pump_onoff);  //o estado da bomba � invertido
    //digitalWrite(led_pump, !pump_onoff);  -> N�o � para utilizar o led
    pump_onoff = !pump_onoff;
  }

  if (digitalRead(but2) && flag_button2) {
    flag_button2 = 0x00;
    //troca o estado do aquecedor
    digitalWrite(heater_rele, !heater_onoff);
    digitalWrite(led_heater, !heater_onoff);
    heater_onoff = !heater_onoff;
  }

  //controlar a velocidade da bomba
  ReadPotentiometer();
  PumpSpeed(pot_value_mapped);

  //enquanto modo local, a variável remote_pumpspeed deve ser atualizada para quando
  //ocorrer a mudança para o modo remoto, por exemplo, as informações sejam corretas
  remote_pumpspeed = pot_value_mapped;

  //atualiza a estrutura de envio de dados via i2c
  refresh_I2C_Packet();
}

void RemoteState() {
  //faz a leitura das variáveis
  runReads();

  //atualiza o lcd com os novos valores
  Menu(1);

  //atualiza a estrutura de envio de dados via i2c
  refresh_I2C_Packet();
}

void emergencia() {
  //digitalWrite(led_flow_mode, LOW);//Apaga LED 1
  digitalWrite(led_heater, LOW);//Apaga LED 2
  digitalWrite(inversor_rele, HIGH);//Desliga a bomba
  digitalWrite(heater_rele, LOW);//Desliga o aquecedor

  //atualiza variável de emergência
  emergency_status = 1;

  //vari�veis auxiliares
  pump_onoff = 0x00;
  heater_onoff = 0x00;
  remote_pumpspeed = 0.0;

  //para evitar blinkar o lcd
  if (!flag_emergency) {
    lcd.clear();
    EmergencyStatus();
  }
  flag_emergency = 0x01;
}

//funções para gerenciar a exibição do lcd

void EmergencyStatus() {
  lcd.setCursor(0, 0);
  lcd.print("Emergencia");
  lcd.setCursor(0, 1);
  lcd.print("Comandos");
  lcd.setCursor(0, 2);
  lcd.print("Bloqueados");
}

void Menu(int op) {

  mode = (op == 1) ? "Remote Mode" : "Local  Mode";

  lcd.setCursor(0, 0);
  lcd.print(mode);

  lcd.setCursor(0, 1);
  lcd.print("TA: ");
  lcd.print(temp[0]);
  lcd.print("  ");
  lcd.print("TB: ");
  lcd.print(temp[1]);

  lcd.setCursor(0, 2);
  lcd.print("TC: ");
  lcd.print(temp[2]);
  lcd.print("  ");
  lcd.print("TD: ");
  lcd.print(temp[3]);

  lcd.setCursor(0, 3);
  lcd.print("V1: ");
  lcd.print(vazao_quente);
  lcd.print("  ");
  lcd.print("V2: ");
  lcd.print(vazao_fria);

}

//funções de leitura (e escrita) das grandezas

void Temperaturas() {

  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus

  sensors.requestTemperatures();

  // print the device information
  for (byte i = 0; i <= 4; i++)
  {
    temp[i] = sensors.getTempC(deviceID[i]);
  }
}

void new_Temperaturas(){
  if(millis() - lastTempRequest > delayTempRead){
    for (byte i = 0; i <= 4; i++)
    {
      temp[i] = sensors.getTempC(deviceID[i]);
    }
  }
  lastTempRequest = millis();
  sensors.requestTemperatures();
}

void VazaoAguaFria() {
  currentTime = millis();
  // Every second, calculate litres/hour
  if (currentTime >= (cloopTime + 1000))
  {
    cloopTime = currentTime; // Updates cloopTime
    // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
    vazao_fria = (flow_frequency / 7.5); // (Pulse frequency) / 7.5Q = flowrate in L/min
    flow_frequency = 0; // Reset Counter
  }
}

void VazaoAguaQuente() {

  float vazao1_sf; //descobrir o porquê do nome da variavel

  microsec = ultrasonic.timing();
  cmMsec = ultrasonic.convert(microsec, Ultrasonic::CM);
  nivel = 11.46 - cmMsec;
  vazao1_sf = (0.0537) * pow((nivel * 10), 1.4727);
  if (vazao1_sf > 1) {
    vazao_quente = 0.75 * vazao_quente + 0.25 * vazao1_sf;
  }
}

void Temperaturas2() {
  LM35_value = analogRead(LM35_PIN) * 0.48875855;
  LDR_value = analogRead(LDR_PIN) / 10.0;
  temp[0] = LM35_value;
  temp[1] = LDR_value;
}

void Simulator() {
  current_sim_time = millis();
  if (current_sim_time >= simulator_time_elapsed + SIMULATORSAMPLETIME) {

    simulator_time_elapsed = current_sim_time;

    for (int i = 0; i < 3; ++i) {
      temp[i] = mapfloat(random(1024), 0, 1023, 10, 50);
    }

    //ultima temperatura com valor senoidal
    temp[3] = mapfloat(waveformsTable[0][indexwave], 0, 4095, 0, 100);
    indexwave++;
    if (indexwave == maxSamplesNum) {
      indexwave = 0;// Reset the counter to repeat the wave
    }

    vazao_quente = mapfloat(random(1024), 0, 1023, 0, 30);
    vazao_fria = mapfloat(random(1024), 0, 1023, 0, 30);
  }
}

void PumpSpeed(float ref) {
  if (ref > 100)
    ref = 100;
  else if (ref < 0)
    ref = 0;
  analogWrite(DAC0, ref * 9.43 + 80);
}

void ReadPotentiometer() {
  pot_value = analogRead(pot);
  pot_value_mapped = mapfloat(pot_value, 0, 1023, 0, 100);
}

void runReads() {

    //Temperaturas();
    //VazaoAguaFria();
    //VazaoAguaQuente();
    //new_Temperaturas();

  //Temperaturas2();
  Simulator();
}

//funções callback do i2c
void receiveEvent(int Nbytes) {
  command = Wire.read();

  switch (command) {
    case 49: //comando de teste
      //comando liga bomba
      digitalWrite(inversor_rele, LOW); //o estado da bomba é invertido
      pump_onoff = 1;
      break;

    case 50:
      //comando desliga bomba
      digitalWrite(inversor_rele, HIGH);
      pump_onoff = 0;
      break;

    case 51:
      //comando liga aquecedor
      digitalWrite(heater_rele, HIGH);
      digitalWrite(led_heater, HIGH);
      heater_onoff = 1;
      break;

    case 52:
      //comando desliga aquecedor
      digitalWrite(heater_rele, LOW);
      digitalWrite(led_heater, LOW);
      heater_onoff = 0;
      break;

    case 53:
      //comando alterar velocidade da bomba
      int i = 0;
      while (Wire.available()) {
        data[i] = Wire.read();
        i = i + 1;
      }
      parseSpeed(data);
      break;
  }
}

void requestEvent() {
  if (command == 54) {
    Wire.write(send_info.I2C_packet, sizeof(processData));
  }
}

void parseSpeed(byte data[]) {
  //o primeiro byte é o número de bytes do envio; deve-se ignorar
  PumpDataSpeed speed;
  speed.bspeed[0] = data[1];
  speed.bspeed[1] = data[2];
  speed.bspeed[2] = data[3];
  speed.bspeed[3] = data[4];
  //Serial.println(speed.fspeed);
  remote_pumpspeed = speed.fspeed;
  PumpSpeed(remote_pumpspeed); //envia o comando de velocidade para a bomba fisicamente
}

void refresh_I2C_Packet() {
  send_info.data.temp1 = temp[0];
  send_info.data.temp2 = temp[1];
  send_info.data.temp3 = temp[2];
  send_info.data.temp4 = temp[3];

  //se a bomba estiver desligada, ignorar o valor do potenciometro
  if (pump_onoff) {
    if (switch_state) {
      send_info.data.pump_speed = remote_pumpspeed;
    }
    else {
      send_info.data.pump_speed = pot_value_mapped;
    }
  }
  else {
    send_info.data.pump_speed = 0.0;
  }

  send_info.data.hotflow = vazao_quente;
  send_info.data.coldflow = vazao_fria;
  bitWrite(send_info.data.bstatus, 0, pump_onoff);
  bitWrite(send_info.data.bstatus, 1, heater_onoff);
  bitWrite(send_info.data.bstatus, 2, switch_state);
  bitWrite(send_info.data.bstatus, 3, emergency_status);
}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

https://github.com/felipefonsecabh/ArduinoCode/blob/ArduinoNoNavigation/ArduinoCode.ino
My problem is ocasionally i'm receiving in master a crazy data.
For example:
Normal block data
[0, 0, 9, 66, 0, 192, 6, 66, 0, 128, 207, 65, 0, 0, 208, 65, 52, 171, 33, 64, 102, 102, 166, 64, 0, 0, 0, 0, 4, 27]

Crazy data
[120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120]

Any ideas?
Thanks a lot!

You have already a open question about that same code: https://arduino.stackexchange.com/questions/46637/interference-in-readings There are a number of problems with your code and I have not even mentioned them all.

The interference measurement os a diferent problem. I want to know , whats could be happening with my i2c packet, because doesn't make Sense ALL bytes with same value.

That could be a mismatch of command 54 between the master and the slave. It could be a bug in the master. You don't tell us who is showing the data of those 120's. In my opinion your sketch needs to be build up from the ground, step by step.

I have seen this exact same problem, and it took me quite a while to track down the answer.
The I2C protocol is a very raw protocol that is inexpensive to implement, but is very susceptible to noise on the bus.  When I put the SCL and SDA lines on my oscilloscope, I saw that occasionally there were spikes of high frequency noise on both lines. These turned out to be EMF noise. Most of the spikes were rejected by glitch filters on the master and slave chips, but occasionally the spikes lasted too long for the glitch filters, and were then read as data or as clock pulses.
When this happens, the master and the slave get out of sync, often resulting in the slave holding SDA low while awaiting a clock pulse, while the master is waiting for the slave to release SDA so it can send a final NAK.
I2C has no concept of a timeout, so this state will last forever unless you detect it and force a resolution.
In the meantime, your sensor library does not check for Wire errors (it has no way of doing so) so it is returning invalid data.
When you see the invalid data, you can try to recover by temporarily taking control of the SCL and SDA pins yourself and toggling them as follows:

Pulse the clock 9 times to force any slave that was sending data to
finish sending the current byte, at which point it will release the
SDA line. When SDA goes high, the slave will see the next clock pulse
as a NAK, so it will stop sending any more bytes.  Any leftover clock
pulses won't have any START marker, so will be ignored by the slaves.
Then send a STOP condition (take CLK low, then take SDA low, then
take CLK high, and finally allow SDA to transition low-> high while
CLK is high. All masters and slaves on the bus should now be OK
again.

Another failure mode can occur in which the slave believes it has received a WRITE command, and it may write to addresses that can put it into an unknown state. To recover from that state, first do the pulsing as above, and then just stop and restart that sensor using library calls.
Finally, there is a failure mode in which the master thinks another master has control of the bus. To recover from that state, first issue the pulses as above, then stop and restart Wire, and then stop and restart any frozen sensors.
It would be nice if all this functionality were in the Wire library, but as of today that's not the case so you'll have to do it yourself. Fortunately that's not too difficult -- it's only a dozen lines of code.
Good luck!


text:
Leonardo soft bricked
I was uploading a sketch to my Arduino Leonardo and I pressed the reset button accidentally while it was still uploading. Now the board does not get recognized by my computer. Is there something that can be done to save it or should I get a new one?

activate the bootloader with reset or double reset and upload a working sketch while the bootloader is active

There's no COM port to send the sketch to, even after double reset. How can I upload a sketch when there's no board recognized?

If you can no longer activate the bootloader, even with the double reset method, then it looks like you will have to reinstall the bootloader.

You'll need to program it trough the ISP port with an AVR programmer if you can't program it through a reset or double reset anymore. This can be done using another arduino. A tutorial is on the arduino.cc website.

Thank you I will try that.


text:
How to dynamically allocate arrays
Question given in the title. I'm trying to dynamically allocate the size of an array on runtime on an arduino pro micro. I've tried realloc, malloc and the c++ variant delete and new without success. This is my current test code:
int* test = 0;

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

void loop() {
  Serial.println("test");
  if(test != 0){ //c++ delete and new attempt
    delete [] test;
  }
  test = new int[2];
  //test = (int*) realloc(test, 2 * sizeof(int)); //realloc attempt
  //test = (int*) malloc(2*sizeof(int));          //malloc attempt
  test[0] = 1;
  test[1] = 2;
  int answer = test[0] + test[1];
  Serial.println(" " + answer);
  Serial.print(" " + test[0]);
  Serial.println(" " + test[1]);
  Serial.println("test");
  delay(100000000000);
}

All of my attempts result in either some garbage in the serial or in most cases:
test

test

Does anyone know what I'm doing wrong?

serial.println doesn't work that way. Or more precisely + with string literal and an int does not create a concatenated string. Instead it treats the string literal as a char* and then does pointer arithmetic on it.
  Serial.print(" ");
  Serial.println(answer);
  Serial.print(" ");
  Serial.print(test[0]);
  Serial.print(" ");
  Serial.println(test[1]);
  Serial.println("test");
  delay(100000000000);


text:
How to do with fzz file
I have a file YunConfig.fzz file for arduino yun for map maker project with ultrasonic sensor.
How can I open or do with that file?
please answer me.

That's a fritzing drawing.

Have a look at Fritzing.org.  With most unknown files you can use a text editor (Notepad) to look at the file.  Sometimes the file will be text and you might be able to read it.  The rest of the time it will be binary and it will look like garbage, however there might be some strings in there that give you a clue as to what application the file is for.

BTY, the Fritzing CAD software is not free. it is 9$ US.

Download and install the open-source, Fritzing CAD software for electronics hobbyist and open the .fzz file with that.
Versions are available for Linux, Mac, and Windows.
Installation instructions are on the downloads page.

Fritzing does no longer seem to be free (as in beer) and it's quite hard to compile the sources, IMHO

You can get the latest version here:
fritzing(dot)org/download/api/1.0/update/344
or find a version on softpedia

The Fritzing download is no longer available. Softpedia Link: https://www.softpedia.com/get/Science-CAD/Fritzing.shtml


text:
Water flow sensor unable to get readings
I connected my "arduino(nano)" to "water flow sensor" and wrote a code which simply prints the readings like 0-1023 and tested it. First i got the readings but now i'm not getting it.

My code looks something like this.
void setup(){
 Serial.begin(115200);
}

void loop(){
 int vla=analogRead(2);
 Serial.println(vla);
 delay(1500);
}

and my connection.

Sensor to Supply module
  Vcc -->  5v
  Gnd -->  Gnd
Sensor to Arduino(Nano)
  Sig --> D2

Also asked at http://forum.arduino.cc/index.php?topic=501527

posting details about your exact flow sensor and library being used along with your schematic and full code may get you better answers; I have used water flow sensors to a good extent for some prototypes but cant answer your question without better details since many people around simply down vote answers without understanding the question and the intent of the person who answered :-)

Sensor to Arduino(Nano)
  Sig --> D2

Your connections are wrong.
int vla=analogRead(2);

is reading from analog channel 2, which is pin A2 on your Nano, not D2
D2 is not an analog pin and thus you can't use it with analogRead().

I tried it but i'm getting only junk value, i even tried adding a pullup.

i think its 16 for a2 and 2 for d2

Use A0, A1, A2 and so on for analog pins. To avoid any confusion. For example: int vla=analogRead(A2);

"i think its 16 for a2 and 2 for d2". analogRead(A2), analogRead(2), and analogRead(16) all do the same thing. See the source code: https://github.com/arduino/Arduino/blob/1.8.4/hardware/arduino/avr/cores/arduino/wiring_analog.c#L38-L55

But @Jot is right, analogRead(A2) makes the intent of the code the most clear.

Okay. Now it's clear.


text:
WS2812 (?) RGB LED matrix turns on white
I have an RGB LED 8x8 matrix which is claimed to consist of WS2812. When turning it on, it automatically lights up all LEDs white with full brightness. The LEDs even light up without DIN being connected. I remember reading something about this behaviour and I think it was related to the LEDs being SK6812 or similar rather than WS2812, but I can't find this page anymore, nor anything else describing this behaviour.
My question is, how can I disable the LEDs lighting up when turning power on? Of course I could add some kind of relay to switch them on right before the signal is sent by the Arduino, but is there something simpler?

that's a feature of most led strips so you can test the leds without having to connect them to a control box, or be able to use them as leds until you can install the controller

I see, but is there a way to disable it?When I connect everything all 64 LEDs are lit up on full brightness white for about a second until the Arduino executes my program. Problem is I need to run on batteries and therefore lowered brightness to around 25%, so the initial flash not only looks bad, but also drains my battery.

I don't think that initial flash will drain that much Ah

If you had the Arduino "controlling" the lights and it had turned them off and then you disconnect and reconnect the power do they still flash?  (Arduino still running and DIN left connected)  The reason I am asking is because if they do still flash what different would a relay/switch on the power line make?  When you turn the power on, they will flash for a second. (I appreciate that the 'switch' is not the preferred solution, but...)

Just tried that, and unfortunately the LEDs still flash. My idea was that maybe it took the Arduino around a second to boot up and initialise everything (I'm using FastLED), and set the pin to output mode. So if I first initialised everything, then just flipped the switch to power on the LEDs and immediately set them to the correct brightness, the problem would not be notable.

Use a MOSFET to control the matrix power line and activate the MOSFET only a few milliseconds before turning off your LEDs: this way the few millis intercurring between power on and off control signal will not be noticeable and will reduce the current bootstrap consumption.

simulate this circuit – Schematic created using CircuitLab

That is the alternative approach I had in my mind. Thank you for the nice schematics :)

If that solves your problem please mark the answer as accepted, otherwise, this question will remain listed among those without an accepted answer.

@RobertoLoGiacco Why do we need R1?

The MOSFET has a capacitance you need to charge up to activate it: R1 is there to limit the current spike produced when you charge up that capacitance.


text:
Arduino Timer 0 in fast PWM mode and micros()
I have the same problem as described on this topic
I needed to set my prescale factor for Timer0 to 1 so I can get a 62.5Khz PWM out of pin 4
My issue is that now the delays() function on my sketches doesn't work correctly.
As mentioned also in the above topic, I've changed the MICROSECONDS_PER_TIMER0_OVERFLOW macro on the wiring.c library, but this doesn't fix the delay() function.
I understand I need to fix the micros() function as well, however I'm confused on how to address the problem.
Isn't the Timer0 Interrupt overflowing 64 times faster now?
So dividing the micros by 64 shouldn't address the problem

if the timer is counting 64 times faster, then you need to delay for 64 times longer.

Modifying standard libraries is a bad idea. The answers in your linked question tell you everything you need to know - "The best workaround is to only use millis() for your timing critical functions." If that isn't good enough then write your own delay() and micros() equivalents.


text:
Getting error ets jan 8 2013,rst cause:4,boot mode(1,6) wdt reset
I'm working on a project to send ultrasonic sensor data to my webserver. For that I'm using ESP8266  WiFi module, 3.3V regulator IC by giving input volt of 5v from aduino uno.
I successfully uploaded a code but in serial monitor I got an error
ets jan 8 2013,rst cause:4,boot mode(1,6) wdt reset.

Please, tell what does it mean?
Here is my code. Guide me if I made something wrong. Thanks in  advance.
Note:
Before sending sensor values I successfully send a raw data  manually to webserver, i.e string data, but when I try to send sensor values, I got an error.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "VENTURE 11";
const char* pass = "12345678";

WiFiClient clientx;
const int trigPin = 8;  //Digital port D5
const int echoPin = 9;  //Digital port D6

long duration;
float distance;
float Mdistance;
float MAX_HEIGHT = 0;

void setup() {

  Serial.begin(115200);                                  //Serial connection
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT);

  WiFi.begin("VENTURE 11", "12345678");   //WiFi connection
  Serial.println("Setup iniated");
  while (WiFi.status() != 3) {  //Wait for the WiFI connection completion
    delay(500);
    Serial.println("Waiting for connection");
    Serial.print("WIFI STATUS : ");
    Serial.println(String(WiFi.status()));
  }
  Serial.println(String(WiFi.status()));
}

void loop() {
  Serial.println(String(WiFi.status()));
  if (WiFi.status() != 3)
  {
    WiFi.begin("VENTURE", "12345678");   //WiFi connection
    while (WiFi.status() != 3)
    {
      Serial.println("Waiting for connection");
    }
  }
  else
  {
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);

    // Calculating the distance
    distance = (duration * 0.034) / 2;

    if (MAX_HEIGHT == 0) {
      //MAX_HEIGHT = distance;
      Serial.print("Max height has been set to ");
      //Serial.print(distance);
      Serial.println(" cm");
      Serial.println("Waiting for 5 seconds...");
      delay(5000);
    } else {
      Serial.print("Distance:\n");
      Serial.print(distance);
      Serial.print("cm\n");
      Serial.print("Distance:\n");
      Serial.print(distance / 100);
      Serial.print("m\n");
      delay(1000);

    }

    HTTPClient http;
    String Data = "x=" + (String)distance + "&y=" + (String)MAX_HEIGHT + "&z=0";
    //String Data = "x=Finally&y=Did&z=it;)";
    http.begin("http://testingblahblah.000webhostapp.com/IOTCON.php");
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    int sent = http.POST(Data);
    Serial.println(sent);
    String httpPayload = http.getString();
    Serial.println(httpPayload);
    if (sent > 0)
    {
      Serial.println("Message has been sent");
    } else {
      Serial.println("unable to send data");
    }
    delay(20000);

  }
}`

Do you see the serial prints on your serial monitor? where do they stop?

also in String Data, you should type String(distance) and String(MAX_HEIGHT) (paranthesis around the argument not the func)

Please check SSID name of the WiFi in the code.

port D6 doesn't exist on most of esp8266 board, change it to another pin

@Erez.Electronic.can, D6 is a label and constant on NodeMcu and Wemos boards and is mapped to io 12. but you are right about wrong pin. io 6 to io 10 are used for communication with the flash memory

Found a possible solution.
I was facing with the same problem.
Apparently this is a hardware stack overflow watch dog preventing malfunction. This may not apply to every possible scenario but I discovered that the allocated pin number on the board itself is incorrect.
What is numbered 03 is in fact D15 for example. So assigning the pin to D15 worked but 3 created this error.
I hope this helps others.

Your loop():
void loop() {
  Serial.println(String(WiFi.status()));
  if (WiFi.status() != 3)
  {
    WiFi.begin("VENTURE", "12345678");   //WiFi connection
    while (WiFi.status() != 3)
    {
      Serial.println("Waiting for connection");
    }
  }
  else
  {
    // Other code...
  }
}

While waiting for the connection, you are creating String objects at a very high rate, since your delay(20000) is in the else clause.
This means you are possibly running out of memory, as you are creating the String objects with every iteration, which is in the Megahertz range.
You likely don't need the String(...) wrappers, as the Serial.println() function can work with C-style strings returned by the WiFi library. Then, your program won't be allocating memory to hold the result of WiFi.status() millions of times per second, which you don't use later on in your program.

the answer is not valid anymore. begin with const char* parameters exists. but this answer was never the right answer


text:
Powering a Nano with a 5v mini USB adaptor
I have made a simple temp sensing circuit that lights an LED when it reaches a certain point. It works perfectly when powered by a USB plugged in to the laptop but when I connect it to a 5V supply with a mini-USB connection nothing happens.
Is this correct and do I need to send power directly to the board on the 5V pin?
Many thanks,
Jack

You can use the computer or a 5V USB charger to power the Arduino via the USB connector. If it does not work, then something else is the problem. What kind of 5V supply is that ? Is there something weird with it ? Is it from a well known brand or a cheap unreliable power supply. Try another USB 5V charger, it should work.

Is that with a TMP36 ? And the 5V as reference ? That will never be accurate. The temperature could be 10 degrees wrong. Do you have a multimeter to measure the 5V ?

And how exactly are you connecting that mini-USB to your circuit?

@gre_gor the Arduino Nano board has a mini USB jack on one end, most likely the poster's is a workalike but they usually preserve this even if they use a CH340 rather than an FTDI.

@Jot The datasheet for the TMP36 states the accuracy as +/- 1C at 25C and +/- 2C over the full range, and that the power supply can be 2.7V to 5.5V.

@Mike the sensor outputs a voltage. That has to be measured (as if using a multimeter to measure the voltage). The Arduino used default the 5V as voltage reference. If the 5V changes, so will the resulating calculated temperature change. When the Arduino is powered via the USB cable, the 5V could change a lot. In such situations, I always use the internal analog reference of the Arduino, which is reasonably accurate. Even better is to avoid all this analog reference hassle and use a DS18B20 with a digital interface.

Thanks all. I found a different power source with a mini-usb connector and it works fine. I think when plugging it in to the PC the Nano makes some faint clicking noises but when direct to  5v plug it does not? I'm not sure so I'll re-test. It was the lack of clicking that lead me to believe it wasn't working as I can't see the on board LEDs using my enclosure.
I don't know about the accuracy but it seems to work for my situation - it is to be placed in a fridge that recently turned itself in to a freezer but has since fixed itself. This project is an early warning system in case it decides to do it again.
Thanks again.
Jack

"I think when plugging it in to the PC the Nano makes some faint clicking noises but when direct to 5v plug it does not?" ... more probably, the PC makes this noise when recognising the Nano's USB<->Serial converter chip as additional USB device.

I found that the noise may be from the little piezo speaker that I added in series with the USB. If it is this then it is gently chirps whilst the red LED on the Nano is flashing when connecting it to the USB. The red LED only flashes once and no sound from the piezo when connecting to an AC 5v adaptor.

This sounds like the 5v PSU didn't have enough amps to run the Nano and the few attachments.  The USB power doesn't generally have many amps, so that PSU mush have been dead/a dud or seriously under powered.