text:
How to re-construct audio from series of analog integer input?
I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it.   At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.
I'm new to working with these types of break out boards, so I found an online project that I'm using as a starting point:
Streaming audio from ESP8266 to pyaudio working in Arduino IDE
I figure I start troubleshooting my popping sound issue by inspecting the UDP packets my ESP8266 code.  Below is the source code I'm working from:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "change this";
const char* password = "change this";
int contconexion = 0;

WiFiUDP Udp;

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

  pinMode(5, OUTPUT);  //D1 Led de estado
  digitalWrite(15, LOW);

  WiFi.mode(WIFI_STA); //para que no inicie el SoftAP en el modo normal
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED and contconexion <50) { //Cuenta hasta 50 si no se puede conectar lo cancela
    ++contconexion;
    delay(250);
    Serial.print(".");
    digitalWrite(5, HIGH);
    delay(250);
    digitalWrite(5, LOW);
  }
  if (contconexion <50) {
      //para usar con ip fija
      IPAddress Ip(192,168,1,180);
      IPAddress Gateway(192,168,0,1);
      IPAddress Subnet(255,255,255,0);
      WiFi.config(Ip, Gateway, Subnet);

      Serial.println("");
      Serial.println("WiFi conectado");
      Serial.println(WiFi.localIP());
      //digitalWrite(5, HIGH);
  }
  else {
      Serial.println("");
      Serial.println("Error de conexion");
      //digitalWrite(15, LOW);
  }
}

void loop()
{
  Udp.beginPacket("192.168.0.26", 1234);

  for(int i=0; i<1024;i++){
    int old=micros();

    float analog = analogRead(A0);
    if (analog > 255) {
      analog = 255;
    }
    else if (analog < 0){
      analog = 0;
    }
    Udp.write(int(analog));
    Serial.print(int(analog));
    Serial.print(",");
    while(micros()-old<87); // 90uSec = 1Sec/11111Hz - 3uSec para los otros procesos
  }
  Serial.print(";;;;;");
  Udp.endPacket();
  delay(5);
}

Notice near the bottom of the file, I print out each analog value separated by a comma, and each data packet separated by five semicolons.
Can someone suggest a way for me to re-construct these series of integers into a sound file that I can inspect via listening with my own ears?  Then I can tell if the sound data being sent is complete?  Or let me know if there's a better way to test if all the data packets are being sent correctly.
UPDATE
I tried to create a wav file by doing this:

Take the list of all integers from Serial.print(int(analog)) and paste it into a file. I make sure all integers are space delimited (ie. no more commas or semicolons)
I copied the file over to a linux machine that had ffmpeg installed
I ran the command ffmpeg -f u8 -ar 11111 -ac 1 -i myfileofintegers -y test.wav

When I listen to the test.wav file, I just hear a series of rapid popping noises.  Not sure if I created the wav file properly?

You could convert it to the .wav file format. The simplest file format available.

I just updated my question to show my attempt at making a wav file.  Did I do it correctly?  I hear more popping noises.

convert what to wav? 2) prints take time 3) what is wired to A0? 4) range of analogRead is 10 bit. you cut the input to 255

@Juraj To answer you questions 1) I'd like to convert the list of integers given by Serial.print(int(analog)) to a wav file.  3) A0 receives the output voltage of a pre-amplified electret microphone.  The voltage amplitude seems to range between 0mv and 300mv.

I gather because I was following the same guide. Unfortunately I do not receive any quality sound but only small pulses, the microphone that uses in the video is made by him, I have used two different types of microphones: KY-038 and / or MAX4466 with the same result. My need is to receive audio, send it to UDP and save it in WAV. Can someone help us?

I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it.

You have described several problems; one needs to break big problems into small problems:

Sample the audio
Send it to another computer
Decode and playback the sound

At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.

This sounds like you have got your timebases messed up; it is likely that you aren't recording enough data or playing it back incorrectly. N.b. it looks like you are recording ~92ms of audio data each 'packet' and if you get a series of pops at 2hz you are likely playing less than 1/10 of a second of audio for ever 5/10 of time, so your speaker moves for 1/10th of a second then stays still for 4/10ths and repeats; this produces your 2hz popping noises.
Your code has some other problems as well:

Serial.print() is Slow! Don't use it where performance matters!
Intertwining sampling and sending
Incorrectly scaling the analog reading
11.1khz can only record signals up to 5.5khz

Lets start with the audio sampling. We have some sort of audio circuitry presenting a signal to an analog input, we need to sample it regularly and uniformly! The code presented is trying to sample at 11.1 kHz, but only does so for 1024 samples before hitting a discontinuity. We do not have circuitry dedicated to this so we will have to use the ADC circuitry on the Arduino.
First thing you will want to get you sampling regular and continuous. You will want to use an interrupt on the Arduino for this. The interrupt should take a single sample from the ADC and add it to a buffer or signal the main loop to read/buffer it.
This interrupt will need to fire regularly at the sample rate or the data will be ruined.
Second the audio circuitry should prepare the signal so that it is between 0-5v with a ~2.5v bias, this will use the ADC hardware to its fullest.
so in Pseudo code:
// include any libs etc.
// set up variables ect.
void interupt_sample();
// register and attach interrupt
void setup() {
//do your setup etc.
}
void loop() {
// if(new_sample) add_to_buffer(new_sample);
// if(buffer_full) send_and_flush_buffer();
}

Specific to converting a list of integers to an audio file, I found a solution here https://stackoverflow.com/questions/55286149/what-ffmpeg-command-to-use-to-convert-a-list-of-unsigned-integers-into-an-audio/55288084


text:
How do I set up a multi-file project in the Arduino IDE?
Suppose I have a project with several modules and a main program.  This works well by adding the modules to main_program.
module1.cpp
module1.h
module2.cpp
module2.h
...
main_program.ino

I'm having problems when I have test programs for each of the modules.  These allow the various devices to be tested in isolation.
module1.cpp
module1.h
module1.ino # test program
module2.cpp
module2.h
module2.ino # test program
...
main_program.ino

I'm required to have each ino file in a directory of the same name.  I can add the files to main_program by adding (e.g.) ../module1/module1.{cpp,h}.  But, I discover that it has actually copied module1.{cpp,h} to main_program/.
How do I set this up?  Is there any option other than making each module a library?  If possible I would like to keep these files more local than the library directory, since they're specific to this project and not general-purpose libraries.

Make each module a library.

You have two options with ArduinoIDE.
First Each module in a module directory
So the structure looks like
  main_routine
     main_routine.ino
  --module1
      module1.ino  #test routine
      module1.cpp
      module1.h
 --module2
  .....

included in main_routine.ino
   #include "module1/module1.h"
   #include "module2/module2.h"

So you have everything in your master dir and in module specific subdirs below - Nothing is or will be copied by the ArduinoIDE (v1.8.12)
The second (more hacky way) is to have everything in one dir and for development testing working with include guards in the main_routine.ino
 // for production comment all MODULEX_TEST and uncomment PRODUCTION
 //#define PRODUCTION
 #define MODULE1_TEST
 //#define MODULE2_TEST
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   #include "module1/module1.h"
#endif

#if defined (PRODUCTION) || defined (MODULE1_TEST )
   uint8_t myModule1Var = 0;
#endif

setup(){
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   myModule1setup someInit(1,2,3);
#endif
.....
 }

loop(){
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   void mymodule1Func(){....};
#endif
#ifdef MODULE1_TEST
   void mymodule1Test(){....};
#endif

Pros and cons

+This approach gives you the possibility to test two modules together.
-Its harder to read, but
+easier to document with tools like doxygen
~Only the active includes are compiled and so no overhead in the compiled code

Be aware that with some tool chains there are at the moment problems when using special templates (works if everything is in one module file - I use an "extended header" file as momentary work around) or arrays as initializer (open issue in esp8266)

source: Stack Exchange

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

sort: votes


text:
text section exceeds available space in board for esp32 + bluetooth + wifi + httpclient
I trying to learn how to write arduino code for an ESP32 WROOM 32.  I want my esp32 to make an http request to a RESTFUL API i've set up. Thus, my esp32 will need wifi access. I was planning to use Bluetooth to tell my esp32 what wifi connection details to use and the specific address of the RESTFUL API end point.  I read some documenation online and people suggested that I would need BluetoothSerial.h for bluetooth connection, <WiFi.h> for wifi connection and <HTTPClient.h> for make HTTP requests.
But the moment I include all 3 packages and initialize a few variables and try to compile, my Arduino IDE gives me the following error:
text section exceeds available space in boardSketch uses 1428393 bytes (108%) of program storage space. Maximum is 1310720 bytes.

Global variables use 55740 bytes (17%) of dynamic memory, leaving 271940 bytes for local variables. Maximum is 327680 bytes.
Sketch too big; see https://support.arduino.cc/hc/en-us/articles/360013825179 for tips on reducing it.
Error compiling for board ESP32-WROOM-DA Module.

This is the code that caused the error:
#include "BluetoothSerial.h"
#include <WiFi.h>
#include <HTTPClient.h>

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

BluetoothSerial SerialBT;
const char* ssid = "";
const char* pass = "";
String apiUrl = "";

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA); //Optional
  WiFi.begin(ssid, pass);

  while(WiFi.status() != WL_CONNECTED){
      delay(100);
  }
  SerialBT.begin("ESP32test"); //Bluetooth device name
}

void loop() {
  delay(20);
}

As you can see, I haven't even begun any real coding and I already get an error that suggest my ESP32 doesn't have necessary resources.
Did I do something wrong?  What else should I consider?

UPDATES
@jsotola
When I comment out the lines BluetoothSerial SerialBT; and SerialBT.begin("ESP32test");, then the program compiles and I see this message:
Wrote 726112 bytes (464336 compressed) at 0x00010000 in 7.0 seconds (effective 828.6 kbit/s)...
Hash of data verified.

So does that mean just those two lines of bluetooth related code takes up about 700kb?
@hcheung - If I change the Tools > Partition Scheme from Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS) to 8MB with spiffs (3MB APP/1.5MB SPIFFS), then Arduino IDE compiles and writes the code to my ESP32.  However, when I try to use my Android phones Serial Bluetooth app to try to connect to the ESP32, I get the error Connection failed: read failed, socket might closed or timeout, read ret:-1.  So it seems the partition scheme affects bluetooth functionality.
I also tried changing the Tools > Flash Size from 4MB to 8MB.  And I get the same behaviour - 4MB doesn't compile.  But 8MB does compile.  But after it compiles my phone can't connect via bluetooth.
And just to be sure, the following code below from File > Examples > BluetoothSerial > SerialtoSerialBT only works with Flash Size 4MB and Default Partition Scheme of Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)
#include "BluetoothSerial.h"

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

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32test"); //Bluetooth device name
  Serial.println("The device started, now you can pair it with bluetooth!");
}

void loop() {
  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(20);
}

what is the program size if you remove all of the bluetooth program lines?

From Arduino IDE, click on menu "Tools -> Partition Scheme" to configure your board with larger flash memory size.

thanks @jsotola i updated my question with details to your question.  Seems like bluetooth lines use up half the memory/flash size?

thanks @hcheung, i updated my question with details to your suggestion. Seems like changing partition scheme or the flash size lets the program compile, but it disrupts the bluetooth connection

choose other options than 8MB unless you know for sure that your ESP32 came with 8MB flash memory. Changing the partition scheme has nothing to do with Bluetooth functionality.

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


text:
Is this a good way to filter noise due to vibration in limit switch?
I have a circuit connected as follows

my limit switches which are attached to my structure sometimes gets falsely triggered, so I wrote this code to address it. My motor is supposed to go down skip the up limit switch at first hit the down one then go back to the up one. is this a good way to implement it?
https://pastebin.com/qVU1Gp0q
//Switch pressed ->  reading HIGH
//Switch not pressed -> reading LOW
//Motor direction 0 is down, 1 is up

const int uplimit = 32;
const int downlimit = 34;
const int motorspeed = 9;
const int motordirection = 28;
//const int pumpspeed=5;
//const int pumpdirection=6;
const int motorenable = 26;
//const int pumpenable=;
int Finishedcleaning = 0;
int Reachedup = 0;
int Motorinitialsetup = 0;
int Motorsecondsetup = 0;
int downfiltered = 0;
int upfiltered = 0;
void setup() {
  // put your setup code here, to run once:

  pinMode(motorspeed, OUTPUT);
  pinMode(motordirection, OUTPUT);
  pinMode(motorenable, OUTPUT);
  //pinMode(pumpspeed, OUTPUT);
  //pinMode(pumpenable, OUTPUT);
  pinMode(uplimit, INPUT);
  pinMode(downlimit, INPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  int average1 = 0;
  int average2 = 0;
  if (Motorinitialsetup == 0 ) // to be run before hitting initial switch
  { digitalWrite(motorenable, HIGH);
    analogWrite(motorspeed, 190);
    digitalWrite(motordirection, 0); // Bring motor down
    //   digitalWrite(pumpenable,HIGH);
    //  digitalWrite(pumpdirection,1);
    // analogWrite(pumpspeed,240);
    Motorinitialsetup = 1; //so this if statement does not run again

  }

  for (int i = 1; i < 100; i++)
  { downfiltered = digitalRead(downlimit);
    average1 = average1 + downfiltered;
  }
  average1 = average1 / 100;

  if ((average1 > 0.9) && Finishedcleaning == 0 ) // Function after hitting down switch
  {
    delay(1000); // wait until motor cross switch
    analogWrite(motorspeed, 0); // stop motor
    Finishedcleaning = 1; //indicate cleaning is over for next loop
    delay(500); // wait until motor cross switch
  }

  if ( (Finishedcleaning == 1) &&   (Reachedup == 0)  && (Motorsecondsetup == 0))
  {
    digitalWrite(motordirection, 1); // reverse motor direction
    analogWrite(motorspeed, 190); // start motor again
    Motorsecondsetup = 1;
  }

  if ( Motorsecondsetup == 1) // only checks switch up switch after motors comes back
  {

    for (int i = 1; i < 300; i++)
    { upfiltered = digitalRead(downlimit);
      average2 = average2 + downfiltered;

    }
    average2 = average2 / 300;
    if ((average2 > 0.9) && (Finishedcleaning == 1)) // Stop Motor after returning
    { analogWrite(motorspeed, 0);
      delay(1000);
      Reachedup = 1; // indicate finished returning after cleaning cycle
    }
  }
}

Start by increasing consistancy and quality. Why does one switch have a pull down resistor of 220 ohm and the other of 4k7 ohm? In your sketch, the indents and brackets are all over the place. Try pressing ctrl+t in the arduino ide. Please describe in words how you want to filter the spikes before you put that in code. Put the sketch itself in your question please, instead of a link.

They both have 4k7
Also I used pastebin for the code because it has C formating I want to filter it by taking 100 points average of the digital reading to make sure it's actually high.

@Jot I added the code to the post.

It can also be the wiring. Noise from the motor can induce a signal on the limit switch wiring. A capacitor in parallel to each limit switch can help with this.

@sa_leinad I thought the capacitor should be in series with the resistor for an RC filter? then I could take the output from the capacitor? since a capacitor is a short circuit at high frequency thus would give me 0 volt?

I'm sorry to say that your wiring is wrong. Here is just one reference https://electronics.stackexchange.com/q/237938/104097. More if you Google  "switch debounce capacitor".

Hardware:
You have the switch at 5V with a pull down resistor.
When using longer wires or when everything is put into a box, it might be safer to have a GND wire to the switch (with a pull up resistor) instead of a 5V wire. When a switch or button is connected with a shielded cable, it can also be better to connect one pin of the switch to GND.
If you change the switch and connect one pin to GND with pullup resistor, then you have to change the sketch as well, because the pin will become LOW when the switch is pressed.
You may add a capacitor of 1 nF to 100 nF between the digital input and GND. That will help against spikes and noise.
The pull down resistors of 4k7 is a high value for a noisy environment. I suggest to use 470 Ω or 1k resistors.
The ground path is very important. You have the GND of the motor driver connected to the breadboard and that is also where the switches are connected. That means the input (switches) and the output (motor driver) share a piece of ground wire. Always avoid such situations.
Breadboards have often bad contacts. If the GND to the breadboard is not very solid, then you are injecting the input pins with noise from the output pins of the Arduino board.
Use two seperate breadboards for input and output. Or connect the GND of the motor driver directly to the Arduino board.
Software:
An integer can not be 0.9, therefor your filter does not work.
The function digitalRead() returns HIGH or LOW. You add those values, but I prefer to stick with HIGH or LOW.
Taking multiple samples and have a threshold is a good idea. Do you really need 100 or 300 samples? A button may bounce for 10 ms, so I suggest to use about 20 samples during 20 ms.
int digitalReadFiltered(int pin) {
  int result;
  const int n = 20;                // maximum 30
  int count = 0;                   // an integer can hold 30 analog samples

  for (int i = 0; i < n; i++) {
    if (digitalRead(pin) == HIGH) {
      count++;
    }
    delay(1);        // 1 ms for sampling during 20 ms with 20 samples
  }

  if (count > (n / 2)) {
    result = HIGH;   // counted enough HIGH values
  } else {
    result = LOW;
  }

  return(result);
}

In short, a pull down (or pull up) resistor with a low value makes the circuit low impedance, and the electrical noise will have less influence.
When a button is pressed, that connects the digital input pin of the Arduino board directly to 5V (or GND). Then it is almost impossible that electrical noise can get to that pin.
When a button is not pressed, then the resistor keeps the input pin low (or high). Then electrical noise can cause spikes.
A circuit with low impedance is less influenced by the electrical noise. The lower the value of the resistor, the less troubles with noise.
It is not something that can be calculated, see it as electrical/capacitive/electromagnetic/radio-noise combined with bad ground currents from a wrong ground path. What is the best way to receive that? With a high impedance circuit of course.
A pull down (or pull up) resistor with a value of 10k can be used when there are no wires connected to it that are going outside the circuit board. When there is a button with wires, then I would suggest a lower value, for example 2k2 or 4k7. Since you have troubles with noise, I suggest a value of 470 Ω or 1k.

Thank you, this is a very good and detailed answer. Would there be any apprehension about using a 47uF capacitor instead just to be safe? Also, I think my filter works just by changing int average to double average, or was that what you meant to say?

Also may I ask why would a higher resistance increase noise? I thought it would be the opposite if I have (V+v_n)/R = V/R +vn/R and vn/R goes to zero for high values of R  thus there is less noisy current with high resistance?

Using float (the arduino uno has no double) for the average should also work, but then you still add HIGH + HIGH + HIGH, I think that is weird. A capacitor of 47µF seems way much. I shall add a paragraph to my answer about the resistor.


text:
Activating a Relay with Wemos D1
I have a problem similar to these questions:
Wemos D1 doesnt drive Relay
Wemos D1 is not triggering Relay
I got this BC548B transistor from an old apparatus I scratched. The transistor saturation voltage is 0.6V  according to the datasheet:
https://alltransistors.com/pdfdatasheet_fairchild_semi/bc548_bc548a_bc548b_bc548c.pdf
When I set up my circuit the wemos d1 inboard leds dim and the board resets so I guess something is going really wrong. Can someone advise if my design makes sense?

UPDATE
I replaced the 12V relay with a 5V one but still can't get it to work. Basically, the 3.3V signal seems to be too low to activate the solenoid. How can I raise the 3V3 signal to 5V? What was wrong with my idea of using a transistor to do it?

so the relay doesn"t activate with 3.3 V as HIGH?

It makes no sense. Is that really the relay you are using? It has a transistor on there already. And did you see the voltage of the relay...?

@majenko 1. Yes, that's the relay, It looks like I need 12V to feed it. In the other hand, if I feed with 5V and the control signal is 5V it works,I have tested it so I though if I can use the 3.3V signal to control the transistor, it should saturate with that voltage and work as a switch for the 5V signal I need.

Without knowing the schematic of the relay we cannot predict what is going on. I would suggest that you don't want a transistor at all - just directly drive the IN pin.

That appears to be a 12 "solid state" relay. That means that it is designed to be both powered by and switched by 12V. You're trying to drive it with slightly more than 1/3 of its rated voltage. Don't do that.
Edit:
Note that none of the relays being discussed are true solid state relays. These are are all conventional coil relays that include cicuitry that allows them to be driven by CMOS logic signals. A true solid state relay does not have any moving parts, but uses solid state components to do the job of a relay. Those cost significantly more money however.)

It might be that you can get away with driving a 5V solid state relay with 3.3V, or 12V relay with 5V, but you shouldn't do those things either.
Also note that even if you are using the correct relay, your relay almost certainly takes more current than the 5V pin on an Arduino can provide (When driven from USB, the entire system is limited to 500 mA, including the power needed to the Arduino.)
Edit:
These solid state relays come in 12V, 5V, and 3V flavors. Get a 3V one: https://www.adafruit.com/product/3191?gclid=EAIaIQobChMIyY_dxM344gIVELbICh1ufwivEAQYBSABEgI3wPD_BwE

This answer is so wrong. This is not a SSR. And there is 5VDC on it. And the relay on link is not SSR either.

this is a SSR module https://www.seeedstudio.com/Grove-Solid-State-Relay-V2-p-3128.html

Vendors use the term solid state relay when they really shouldn't. It's a relay module with circuitry that enables you to switch it with low current logic level signals. I was being lazy by using that term, and should not have.

i added a note to point out that these are not really solid state relays. (And the relay I link to is a 3V relay. Look at the picture.)


text:
buiReliable time in ISR
I'm using a Nano. The code below is a simplified workup of my problem code.
The point of it is asynchronous debounced button press detection. The actual code sets a volatile bool to tell the main loop it saw a press, but this simplified version toggles the state of the built-in LED. Another LED follows the state of the pushbutton to make it possible to see whether the ISR is firing appropriately.
#define SHORT_PRESS_MS 50
#define PUSHBUTTON_PIN 2
#define BUILTIN_LED_PIN 13
#define OTHER_LED_PIN 12
volatile unsigned long fallTime = 0;
volatile int builtinLedState = LOW;
void isr_change()
{
    unsigned long now = millis();
    int pushbuttonState = digitalRead(PUSHBUTTON_PIN);
    // show switch state with LED and 120 Ohms on D12
    digitalWrite(OTHER_LED_PIN, pushbuttonState);
    if ((pushbuttonState == LOW) || (fallTime == 0))
    { // change to low => falling edge
        fallTime = now;
    }
    if (pushbuttonState == HIGH)
    { // change to high => rising edge
        long pressMs = now - fallTime;
        if (pressMs > SHORT_PRESS_MS)
        {
            builtinLedState = !builtinLedState;
            digitalWrite(BUILTIN_LED_PIN, builtinLedState);
        }
    }
}
void setup()
{
    pinMode(PUSHBUTTON_PIN, INPUT_PULLUP);
    pinMode(BUILTIN_LED_PIN, OUTPUT);
    pinMode(OTHER_LED_PIN, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(PUSHBUTTON_PIN), isr_change, CHANGE);
}
void loop() {}

When this runs, OTHER_LED slavishly follows the button. There is no perceptible lag and it never gets out of synch no matter how machine-gun my antics with the button.
However, toggling of the built-in LED is not reliable. That OTHER_LED remains in sync with the button state implies that the event is always firing and the state is always what I expect, so it seems like there is a problem with my attempt to measure time.
What is the right way to measure time inside an ISR?

Applying suggested diagnostics confirmed the hypothesis of the accepted answer. Having determined the nature of the problem, I rewrote the ISR as follows.
void isr_change()
{
    static long fallTime = 0;
    static int lastPushbuttonState;
    int pushbuttonState = digitalRead(PUSHBUTTON_PIN);
    if (lastPushbuttonState != pushbuttonState)
    {
        long now = millis();
        if (pushbuttonState == LOW)
        { // change to low => falling edge
            fallTime = now;
        }
        if (pushbuttonState == HIGH)
        { // change to high => rising edge
            long pressMs = now - fallTime;
            if (pressMs > SHORT_PRESS_MS)
            {
                digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
            }
        }
    }
}

Testing reveals that the problem is resolved and the intended behaviour is occurring (reliably detect presses of minimum duration).
Also of interest is the use of static to carry values between ISR invocations with local scope, rather than using global volatile variables.

but you alternate the state of the LED. how should it be in sync with the other LED? and there could be more fast changes (bounce) which you can't see on other LED

The onboard LED toggles with every press. The other LED illuminates while the button is pressed and does not when it isn't. It's in sync with the button. To address your valid concern about bounce I will count both rising and falling edges and illuminate only when they are equal.

It's bound to CHANGE. It fires when it goes LOW (button press) and it fires again when it goes HIGH (release button). I read the button state and write it to the OTHER_LED.

I cannot make sense of this:
if ((pushbuttonState == LOW) || (fallTime == 0))

Why || (fallTime == 0)? Other than this, your ISR looks fine to me.
And your way of measuring the time is correct. The only scenario I can
imagine that can make the toggling unreliable is the ISR missing
transitions, which can happen if the input pin gives very short spikes.
Here is my scenario:
The button is pressed, fallTime holds the correct value, you release
the button. At this point, the bouncing button generates a very short
positive pulse: LOW → HIGH → LOW. The first transition triggers an
interrupt request. However, there is some latency in handling the
request. By the time the ISR starts running, the pin has already toggled
back to LOW, and the ISR then incorrectly updates fallTime.
A little bit later, the pin toggles back to HIGH for good. However,
now is very close to fallTime, and the rising edge gets ignored.
You can check whether you have missed transitions by toggling the LED
every time you see the same state as in the previous ISR run:
void isr_change()
{
    static uint8_t previous_pin_state;
    uint8_t pin_state = digitalRead(PUSHBUTTON_PIN);
    if (pin_state == previous_pin_state)
        digitalWrite(LED_BUILTIN, !digiatlRead(LED_BUILTIN));
    previous_pin_state = pin_state;
}

|| (fallTime == 0) is in case the first thing it sees is a rising edge. I'm about to try your diagnostic suggestion.

I took it out because in the larger program that needs this there is deferred initialisation anyway so I can discard any pending press at that stage.

I confirm your hypothesis. I guess I should skip handling when there's no change of direction.

you toggle the state of the main LED on CHANGE to HIGH. how should it be in sync with the other LED? and there could be more fast changes (bounce) which human eye can't see on LED
result of the sketch:

The LEDs are not intended to be in sync with each other. I never said they were. One toggles to indicate recognition of a pulse of the desired minimum duration, the other follows the button state to provide visual feedback showing that the ISR is responding to button activity.

@PeterWone, there are bounce toggles of LED, which you can't see on other LED. so you never know the right state of LED


text:
Risks when commanding multiple chips with same address via I2C
I know that I2C devices are supposed to have unique addresses when used. What if I still use multiple devices with the same address, what can go wrong? Let me describe the situation:
I have multiple digital capacitors (NCD2400M by IXYS) and I would be using them so, that I always send the same command to every chip. I have no need of reading anything from those, which is the reason I was thinking why should I bother multiplexing my I2C line. I have no reason to identify them, only commanding. For the commanding I use Arduino (Nano currently, might change to some other Arduino model).
I have already tried commanding them simultaneously and it works like a charm. I tried so that I connected SDA and SCL of four chips and used RC circuit and square wave to check the rise time to verify that every chip indeed changes their capacitance.

However, I'm new to I2C protocol and I'm not yet aware of every detail. I guess there could be issues when one of the chips fail? Can I assume in this case that nothing goes wrong with the ACK/NACK bit since the chips are "identical"?
-RautSa
EDIT:
After using correct keywords for searching I found this previously asked question. Based on that I now understand at least there would be a problem when only one of the chips tries to send NACK bit.

Please add a link to the sensor to your question. https://www.ixysiss.com/ncd2400

@Jot Thanks for the note, I added the link.

@Jaromanda X I guess you didn't bother reading my post? It does work, I have tested. The question is does it pose risks when used in a way it isn't intended to be used.

@Jaromanda X You really should elaborate your answers. If I expect it to not work correctly, it propably works correctly? Comments like "propably won't work" aren't helpful. If you had commented why it propably won't work, now that would have been helpful.

There is no risk for damaging something, but the risk is the reliability.
The NCD2400M operates at 3.3V and 5V, so that will work with every Arduino board.
Your question is very similar to the question that you already found: electronics.stackexchange.com/questions/417263/multiple-instances-of-same-device-on-i2c-bus.
There are a few specific Arduino things to mention.
During Arduino setup() a sensor is often checked if it is connected and if it is possible to communicate with a sensor. That would be impossible when the sensors share the I2C address.
The Arduino Wire library detects a bus error, for example when there are other I2C Masters on the bus, and returns with an error.
Since your NCD2400M are only Slaves, I think that they will not trigger a bus error.
You need some luck, and I can not guarantee that it will always work:

When the NCD2400M behaves like a normal I2C Slave and it is not too
smart, then it does not detect that another one pulls the SDA low
for an acknowledge.
Some sensors send a NACK when they are busy, I
can not find such a note in the datasheet. You could write to the
NCD2400M twice to be sure that they have received it.
When they have an
internal clock and respond with different timings on the I2C bus,
then you can set the SCL clock lower. For example
Wire.setClock(50000); after Wire.begin() for a 50kHz SCL clock.

When one of NCD2400M is blown, then you are not able to identify the bad one. However, when one of the NCD2400M is blown, perhaps the whole circuit is no longer reliable.
For a good design, you should know if you are actually communicating with a sensor or just talking into thin air. When you have made more Arduino projects, then you know that it is essential to know if a sensor is connected or not.
Trying this solution to make it "easy" for now, might cause a lot of troubles later.
Conclusion: It will work. You can use it for a test. When you use it in the final version, you take the risk that it can cause a lot of troubles.
More about the basics of the I2C bus: http://www.gammon.com.au/i2c

Thank you for your answer and the tips. With my current prototype I'll proceed with this configuration, and later on I'll add multiplexing to the more final design. Not getting the NACK information is a reason serious enough to implement the multiplexing. Too bad they only have two addresses available for the chip.

@RautSa with 4 chips and no multiplexer, you need 5 digital pins of the arduino nano. With a software i2c library and a single scl and four sda, you have four i2c busses. When each chip can have two addresses, then you need only two i2c busses, that is 3 pins with a software i2c library.

Could always add a switch like DG406, DG409, or equivalent to select which cap is connected to SDA so that only one is commanded at a time. Pullup SDA on the output side so it is not floating at the chip.

True, that's possible. Most likely I'll have to go with the implementation which takes the least amount of space on the final designs PCB, so I'll have to check the options.


text:
Which sensors to choose to detect movement direction
So I'm planning to build a sort of light switch for my Philips Hue bulbs with an Arduino. This project will be mounted on a shelf next to my door to the room, parallel to the walking direction. In order to detect the movement direction to either turn on or off the lights when a person is entering or leaving the room, I need one or two sensors. I've tried HC sr04 before but got inaccurate results which resulted in random changes of the lightstate.
So what sensors will be best for my application? I was thinking about the Sharp IR sensors (i.e. Sharp GP2Y0A60SZLF) but I'm not sure about any possible interference that comes with it when I mount to of these right next to each other. Any ideas?
Thanks in advance!

What "Sharp IR sensors"? Please provide a link or a part number

@chrisl yeah I forgot to add the part number, edited my question

Usually for "light" applications you use cheap PIR movement sensors. Two of them with some paper guards that limit their field of vision in two locations. You can check which is triggered first to deduce direction.

@FilipFranik wait, the PIR are based on infrared aren't they? So they won't detect a moving door when there is no human or ir emitting source nearby? Is it possible to mask the sensor in such a way that there is only a vertical line where the sensor detects a movement? Because that would be great to avoid any light changes when only the door moves but no person is nearby

The PIR sensors can work in your case. They are passive and detect only moving objects that emit IR radiation. So anything that's hotter than background like people, cats, dogs but not doors.
The raw sensor looks like this:

But it's usually available as a part of an IC that includes a plastic lens that focuses IR rays from broader area on the sensor.

Remove that lens (or not) and add something made of cardboard to limit the area that sensor sees and you have a directional sensor that detects moving hot things.
Technically you can completely hack the raw sensor and get info if the hot object is moving left or right. Read this article and look at the sensor response graph.

I guess you want to use 2 IR sensors with a little distance, so that you can check the direction by checking, which one detected an object first. You surely can do this with the mentioned sensor. To avoid interference, you can measure by one one, deactivating the other over it's enable pin during that time. It should be fast enough, so that you can do this sufficiently.
I would say using a distance sensor is overkill here. For checking, if someone comes in or out, you don't need distance information. Just 2 light barriers would be sufficient. For example a little laser pointer (could also be IR), a little mirror at the other side and a fitting photodiode. I think there are ready made modules to buy. Their output would only be digital, not analog.


text:
Help with code for changing motor speed depending on MPU6050 angles read
I have been trying to create code where my MPU6050 is constantly reading the angle it is at and based on that angle, increase or decrease the motor speed. For example the motor will be off when the sensor is level and maximum speed at 45 degrees, and 22 degrees is roughly half speed.
I have a 5065 200kv brushless motor going to a ESC with a bec which i can attach to the Arduino. I have tried to modify a self balancing drone code that used PID. I took out the PID and tried to do an if-then for if the angle is > 5 < 45 then servo write (anglex36) because the maximum angle is 45 and if i multiply 45 by 36 it will be 1620. It says in the code the maximum rpm is 2000, although mine can go faster, and I will change it later after testing.  It is recommended to have the max motor speed be at most 85% motor power to prevent damage so that is why I have it at 1620 for now and not 2000.
I am fairly new with Arduino and have no experience with the MPU6050 so I apologize for any misunderstanding of information or code.
Here is my code :
#include <Wire.h>
#include <Servo.h>

Servo right_prop;

int16_t Acc_rawX, Acc_rawY, Acc_rawZ,Gyr_rawX, Gyr_rawY, Gyr_rawZ;

float Acceleration_angle[2];
float Gyro_angle[2];
float Total_angle[2];

float elapsedTime, time, timePrev;
int i;
float rad_to_deg = 180/3.141592654;

double throttle=0; //initial value of throttle to the motors

void setup() {
  Wire.begin(); //begin the wire comunication
  Wire.beginTransmission(0x68);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(250000);
  right_prop.attach(3); //attatch the right motor to pin 3

  time = millis();

  right_prop.writeMicroseconds(1000);
  delay(7000);

void loop() {

/////////////////////////////I M U/////////////////////////////////////
    timePrev = time;
    time = millis();
    elapsedTime = (time - timePrev) / 1000;

     Wire.beginTransmission(0x68);
     Wire.write(0x3B);
     Wire.endTransmission(false);
     Wire.requestFrom(0x68,6,true);

     Acc_rawX=Wire.read()<<8|Wire.read();
     Acc_rawY=Wire.read()<<8|Wire.read();
     Acc_rawZ=Wire.read()<<8|Wire.read();

     Acceleration_angle[0] = atan((Acc_rawY/16384.0)/sqrt(pow((Acc_rawX/16384.0),2) + pow((Acc_rawZ/16384.0),2)))*rad_to_deg;
     /*---Y---*/
     Acceleration_angle[1] = atan(-1*(Acc_rawX/16384.0)/sqrt(pow((Acc_rawY/16384.0),2) + pow((Acc_rawZ/16384.0),2)))*rad_to_deg;

   Wire.beginTransmission(0x68);
   Wire.write(0x43); //Gyro data first adress
   Wire.endTransmission(false);
   Wire.requestFrom(0x68,4,true); //Just 4 registers

   Gyr_rawX=Wire.read()<<8|Wire.read();
   Gyr_rawY=Wire.read()<<8|Wire.read();

   /*---X---*/
   Gyro_angle[0] = Gyr_rawX/131.0;
   /*---Y---*/
   Gyro_angle[1] = Gyr_rawY/131.0;

   /*---X axis angle---*/
   Total_angle[0] = 0.98 *(Total_angle[0] + Gyro_angle[0]*elapsedTime) + 0.02*Acceleration_angle[0];
   /*---Y axis angle---*/
   Total_angle[1] = 0.98 *(Total_angle[1] + Gyro_angle[1]*elapsedTime) + 0.02*Acceleration_angle[1];

    Serial.println(Total_angle[1]);

if( Total_angle[1]> 5 && Total_angle[1]< 45)
{
right_prop.write(Total_angle[1]*37);
}
else{
right_prop.write(0);
}
}

//end of loop void


text:
avr_boot change LED pin
I would like to know how can I change LED pin for avr_boot bootloader.
I can see there is option in variants folder but in the manual it mention "if using USE_LED adapt LED-pins in asmfunc.S" which is not clear. I am using pin PC3 how do I write it.

Near the top of asmfunc.S, you have these lines:
; LED Pins
#define DDR_SS  _SFR_IO_ADDR(DDRD), 5   // SS pin (PIN, PORT)
#define PORT_SS _SFR_IO_ADDR(PORTD), 5

#define DDR_PW  _SFR_IO_ADDR(DDRD), 6   // Power pin (PIN, PORT)
#define PORT_PW _SFR_IO_ADDR(PORTD), 6

These define the “write” or “slave select” LED pin as PD5 (registers
DDRD and PORTD, bit 5), and the “power” LED as PD6 (registers DDRD
and PORTD, bit  6).
These are the lines you have to change if using different pins. For
example, pin PC3 is: registers DDRC and PORTC, bit 3.

Got it. I am using port PC3 so how do I write it. Also do I have to do anything else.

I do not know what each of these LEDs mean. Regarding PC3, see amended answer.


text:
Converting 16bit to float
I am trying to communicate with AT30TS75A-MA8M-T with below code, the problem is converting the 16 bit output to float so I can read temp:
Base on data sheet

I suppose to remove first 5 bit in order to read correctly but I am not converting it correctly.
Ex: (0b001001001100000 AND 0 b0111111111100000) = 0b1001001100000
0b1001001100000 >> 5 = 0b10010011 = 147
    void Atemp::begin()
{

    Wire.begin();

    // Check if sensor temp sensor is avilable

    // if (mySensor.beginI2C() == false)
    // {
    //     data[9] = 5; // Error Code
    // }
    // Set registor for two decimal
    Wire.beginTransmission(_i2cAddress);
    Wire.write(1);
    Wire.write(0b01100000);
    Wire.endTransmission();
}

void Atemp::read()
{
    Wire.beginTransmission(_i2cAddress);
    Wire.write(0);
    result = Wire.endTransmission();
    // result is 0-4
    if (result != 0)
    {
        data[9] = 5; // Error Code
    }

    result = Wire.requestFrom(_i2cAddress, (uint8_t)2);
    if (result != 2)
    {
        data[9] = 5; // Error Code
    }
    else
    {
        uint8_t part1 = Wire.read();
        uint8_t part2 = Wire.read();

        data[7] = part1;
         data[8] = part2;
        int16_t rawval = (part1 << 8 | part2) ;
        // rawval >>= 6;
        float temp = rawval / 256.0f;
        floatconv(temp);
    }
}

You need to do two things:

Right-shift the data to align it to the right of the variable, and
Multiply it by the value of one bit.

When right shifting be sure to do it in a signed data type so that C will sign extend the value and retain any negativeness to the value.
So taking the 12-bit examples from the datasheet you right shift 4 bits, so
SDDDDDDDDDDD0000

becomes
SSSSSDDDDDDDDDDD

(where S is the sign bit and D is a valid data bit, and 0 is padding)
Then simply multiply the value by 0.0625 to get the actual temperature.
In code that might look like:
int16_t rawval = part1 << 8 | part2;
rawval >>= 4; // Do this in the int16_t to preserve the sign
float temperature = rawval * 0.0625;

For different resolutions right shift by different amounts and multiply by the appropriate single-bit value for that resolution (hint: 11 bit is double the value of 12 bit, 10 bit is double the value of 11 bit, etc).

@Shahreza Page 10 of the datasheet. The resolution of the temperature measurement data can be configured to 9, 10, 11, or 12 bits which corresponds to temperature increments of 0.5̊C, 0.25̊C, 0.125̊C, and 0.0625̊C, respectively.

Just a complement to Majenko's answer. The temperature register is set
in such a way that you can interpret it in the same way irrespective of
the selected resolution:
int16_t rawval = part1 << 8 | part2;
float temperature = rawval * (1/256.0);

Good plan - didn't think of that ;)


text:
Convert float to int error
I am trying to convert 1.06 to 106 by multiplying by 100 but the answer comes 105, I do not know why. Variable ver can be any decimal in this format x.xx
float ver = 1.06;
int vers = ver * 100;
vm[0] = (vers / 100U) % 10;
vm[1] = (vers / 10U) % 10;
vm[2] = (vers / 1U) % 10;
Serial.println(vers);

Could  you let me know what I am doing wrong or maybe I have to do something else.

1.06 is not a float. The closest float is 1.059999942779541015625. If
you multiply that by 100 you get a number that, again, is not a float.
Rounding to the nearest float yields 105.99999237060546875, which is the
result of the expression ver * 100, and just one ULP short of 106.
Yes, floating point computations do quite usually involve rounding
steps.
Casting to an int implicitly rounds towards zero, and you get 105,
which is the correct result. Correct according to the rules of IEEE 754
arithmetics.
You may want to round() to the nearest integer before the cast.

Variable ver can be any decimal in this format x.xx

No, a float cannot be “any decimal” in this format. Floats are stored
in binary, and most decimal numbers (numbers that can be written with a
finite number of decimal digits) cannot be written in binary with a
finite number of bits.
Except for a few values (namely the multiples of 0.25), ver can only
store an approximation of the decimal number.

Thanks for the answer, now it make sense.


text:
Calculate pullup resistor, cat5e ftp
let me describe my schema, i got one arduino and one esp32 connected over i2c using 30m cat 5e ftp cable, I'm using 12v to power up both devices, each of them have dc-dc converter that convert to 5V, there is two P82B715P extenders, controllers i2c bus is wired with 10K pullups to P82B715P , i2c bus between P82B715P is wired with 1K pullups on master device side. On 30M cable it works only if I transmit SDA, SCL in twister pair with ground, no power voltage (+12V) is on the cable. When I place +12V on the cable, I2C bus stop working, tried to decrease pullups to 0.4K no effect, since I do not understand can only make try/fail tests. Question is do I need to adjust pullups beween P82B715P only,  or I need to change pullups between P82B715P and esp/arduino? Perhaps for calculation of pullups I must mention that i2c bus work on 10KHz

Can you post a schematic? Your question is a little hard to understand. Help us to help you. :)

Well I do not have schematic, gonna try to draw one later

Check VCC and pullup calculation. http://www.ti.com/lit/ds/symlink/p82b715.pdf

Using the formula and the remark in the datasheet (8.1.1), I get between 330 and 660 Ohm for the 30m cable. Are you getting a stable 5V on the otherside of the cat5 cable; from the dc-dc converter?

yes voltage is stable, just I2c not working if +12V is on same cable where data is.

you run the 12 V twisted with SDA?

I tried all combination, with GND with 12V nothing make it work, and decide to stop trying and go to RS485

@user3503519 did you put adequate capacitors on the 12V line, on both sides? This looks like interference between the 12V noise and the data wires..

DC DC convertors include capacitors


text:
TMRpcm interferes with Wire.h
I'm using TMRpcm library for playing .wav files from my SD card. Everything works fine, but if I include Wire.h library the files aren't playing at all (there's no sound). I have only added this line of code above my program:
#include <Wire.h>
//code after

I suppose that this is because of the timer and interruption because TMRpcm documentation mentions that:

May interfere with other libraries that rely on interrupts. The isPlaying() disable() or noInterrupts()
   functions can be used to prevent parallel code execution.

I've tried to use those functions but maybe I do something wrong. Can somebody help me? How can I use those libraries at once?
UPDATE:
Here's my before code:
tmrpcm.play("neMode.wav");
delay(2000);

and after:
noInterrupts();
tmrpcm.play("neMode.wav");
delay(2000);
interrupts();

It doesn't change anything. I hear no sound at all.

How did you use disable() and noInterrupts()? Please show the code for a complete minimal example, that shows your problem.

@chrisl I updated my post with that information. Concerning disable() function I don't really know how to use it. I would appreciate if you could help me

It will not play something, when turning off interrupts. Please show a complete (!) example, that shows your problem.

Also posted at Arduino Forum. If you are doing this, you have to link to it, so that we don't spend time on searching for information, that you only gave on one site.

I cannot see an obvious reason, why it stops working, when including Wire.h. Have you tested, if the Arduino is stuck in some function? You can add simple LED blinks or Serial prints to slowly hunt the problematic code down.

Well, it stops working exactly after I add a line:
#include <Wire.h>
I'm a beginner in Arduino, that's why I may have some dummy questions. But I can't find a solution of how can I use isPlaying() disable() or noInterrupts() to prevent TMRcpm library from being interrupted. Could you show me please how is it used correctly?

Besides, the problem may be in timer that these libraries use. I have tried to change TMRpcm library to work with Timer2 in Config.h. But then I just hear noise&beep instead of my file that should be played.


text:
Code stuck on mag.getEvent(&event); in HMC5833L Compass
Last week I created some code in which I can run a Ublox GPS NEO-6 and a magnetometer HMC5883L together. Which at the time worked brilliantly.
Yesterday I have attempted to run the code again, with the same connections. No modifications to the code.
The GPS NEO-6 works as expected, the magnetometer not so much. After using serial commands as breakpoints, I am able to see that it gets to the line:
mag.getEvent(&event);

Then I bought two new HMC5883L modules and uploaded the example code, to see if the magnetometer will even run correctly.
The example code returned the basic stats on the breakout board but once again stopped at that line.
Out of curiosity, I removed the magnetometer and ran the program. It displayed exactly the same.
It's not picking up that the HMC5883L is even disconnected.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_HMC5883_U.h>
/* Assign a unique ID to this sensor at the same time */
Adafruit_HMC5883_Unified mag = Adafruit_HMC5883_Unified(12345);

void displaySensorDetails(void)
{
  sensor_t sensor;
  mag.getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" uT");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" uT");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" uT");
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

void setup(void)
{
  Serial.begin(9600);
  Serial.println("HMC5883 Magnetometer Test"); Serial.println("");

  /* Initialise the sensor */
  if(!mag.begin())
  {
    /* There was a problem detecting the HMC5883 ... check your connections */
    Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");
    while(1);
  }

  /* Display some basic information on this sensor */
  displaySensorDetails();
}

void loop(void)
{
  /* Get a new sensor event */
 sensors_event_t event;
 mag.getEvent(&event);

 /* Display the results (magnetic vector values are in micro-Tesla (uT)) */
 Serial.print("X: "); Serial.print(event.magnetic.x); Serial.print("  ");
 Serial.print("Y: "); Serial.print(event.magnetic.y); Serial.print("  ");
 Serial.print("Z: "); Serial.print(event.magnetic.z); Serial.print("  ");Serial.println("uT");

 // Hold the module so that Z is pointing 'up' and you can measure the heading with x&y
 // Calculate heading when the magnetometer is level, then correct for signs of axis.
 float heading = atan2(event.magnetic.y, event.magnetic.x);

 // Once you have your heading, you must then add your 'Declination Angle', which is the 'Error' of the magnetic field in your location.
 // Find yours here: http://www.magnetic-declination.com/
 // Mine is: -13* 2' W, which is ~13 Degrees, or (which we need) 0.22 radians
 // If you cannot find your Declination, comment out these two lines, your compass will be slightly off.
 float declinationAngle = 0.22;
 heading += declinationAngle;

 // Correct for when signs are reversed.
 if(heading < 0)
   heading += 2*PI;

 // Check for wrap due to addition of declination.
 if(heading > 2*PI)
   heading -= 2*PI;

 // Convert radians to degrees for readability.
 float headingDegrees = heading * 180/M_PI;

 Serial.print("Heading (degrees): "); Serial.println(headingDegrees);

 delay(500);
}

The wires i used are about 20cm long.

Please add more information to your question. Do you use the adafruit hmc5883 modules or other modules? Do those other modules have level shifters for sda and scl? How long are the wires of the i2c bus? Please also add a link to the used library: https://github.com/adafruit/Adafruit_HMC5883_Unified That library is not very good and contains a bug. It does not test if the hmc5883 is connected and the mag.getEvent function has a while loop that halts everything when the hmc5883 is not connected. That is what you found. I suggest to read the identification registers yourself after the mag.begin

i use 20 cm long jumper wires

and two another libraries i used for clearification are linked as: 1)..link and 2)..https://www.arduinolibraries.info/libraries/grove-3-axis-digital-compass-hmc5883-l

Were you able to solve this problem? @Jot would you specify more clearly what the alternative to _HMC5883_Unified is?

Denis G. Labrecque, sorry Dear, it's been 2 years ago and i haven't clearly remember its solution.


text:
Public variable in class not incrementing
I'm not sure what is wrong with my code, but whenever I call addNewLine, the linesInserted variable is not updating correctly. When I print the value of linesInserted inside of the addNewLine method, it shows as incrementing, but when I print the value inside of the draw method, it shows that it is 0.
I have tried different increment operators (linesInserted += 1 and linesInserted = linesInserted + 1). Oddly enough, when I do linesInserted = 99 instead of linesInserted++, it sets the value correctly. I'm wondering if I am possibly messing up a reference somewhere?
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1331.h>
#include <SPI.h>

class Character {
  public:
    char** lines; // using char for 8 bit integer
    int sizeOfLines;
    char symbol;
    Adafruit_SSD1331* display;
    int width;
    draw(int x, int y, int color);
    addNewLine(char startX, char startY, char endX, char endY);
    int linesInserted = 0;
};

Character::draw(int x, int y, int color) {
  if (linesInserted < sizeOfLines) {
    display->setCursor(0, 39);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "SYMBOL %c\nWASTED MEMORY", symbol);
    Serial.println(symbol);
    Serial.print(linesInserted);
    Serial.print(" ");
    Serial.println(sizeOfLines);
    display->print(buf);
  }
  for (int i = 0; i < sizeOfLines; i++) {
    char* line = lines[i];
    display->drawLine(line[0] + x, line[1] + y, line[2] + x, line[3] + y, color);
  }
};

Character::addNewLine(char startX, char startY, char endX, char endY)  {
  linesInserted++;
  if (linesInserted > sizeOfLines) {
    display->setCursor(0, 15);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "ERROR\nSYMBOL %c\nTOO MANY LINES", symbol);
    display->print(buf);
  } else {
    lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};
  }
};

EDIT: Git repo to the project is added - https://github.com/Pyrodron/charger-destination-board

Is char** lines; ever initialized?

@timemage - Yes, there's a method that sets lines to (char**) malloc(sizeof(char*) * Char.sizeOfLines);. I'm in the process of converting this from a struct to a class so I haven't gotten around to creating a constructor yet.

I suspect you'll eventually find this is a matter of corrupting memory.  Without the full code probably away to execute it, there's not much chance of me personally finding anything.  Generally to have a better chance of getting help with this, I'd say provide full code to a cut down example that still shows the problem.  If possible remove the display code entirely from the example, because that dependency will severely limit the set of people that can reproduce your problem.  That said, you're likely to find the answer in the process of doing that.

You should re-think your whole strategy. It looks like you're making a wrapper for some graphical symbols made out of straight line segments. It would be far better to store the data statically in flash and just provide a pointer to it to your class. Then use the pgm_read_* functions to access the data. No need for any dynamic RAM allocation. No limit on the number of lines in a symbol (that count could be static and part of the symbol data). No messing with malloc.

@timemage - I didn't want to make this question long by posting the entire code, but then realized that Git is a thing. I guess that's what I get for posting this at 11pm lol. I edited the question with the repo added.

@Majenko - To be completely honest, I was already thinking about that. Just trying to make some code as a proof of concept before I moved everything to flash.

It's difficult to pin down the exact details as to why the problem it's manifesting exactly the way it is. But, in short, it's fair to say you're running out of memory.
First, just a note:  The code I'm testing with (because it compiles) is the code out of your github repo, which used a char type variable for linesInserted and had a commented-out println(linesInserted);, so it kind of seems like at one point you'd been trying to print the count as character, specifically non-printable control characters.  So that might may have been confusing you.  I uncommented it and added a , DEC) parameter to it (rather than casting) to coerce println into treating it as an int.
I tested your code without the display library in a PC environment to allow me to run valgrind on it.  It didn't find anything; I wasn't necessarily expecting it to.  But, I did crudely instrument your code in this enviroment to see that you're calling malloc()/new 124 times, for a total of 500 bytes, but importantly this does not include the structure heap overhead, which is significant because you're new-ing tiny four-character chunks.
Then I ran your code as compiled for an AVR.  Because I don't have your display, and wanted to match your environment as closely as possible, I left the display code in but NOPed out a few function calls that would have screwed up my test rig.
The primary finding is that you're dangerously close to "running out" of memory:

000005e0 | 01 00 02 04  00 01 00 02 - 00 04 00 03  01 03 05 04 | ........ ........
000005f0 | 00 01 03 02  03 04 00 01 - 06 02 06 04  00 00 00 00 | ........ ........
00000600 | 00 04 00 02  00 02 00 04 - 00 01 01 01  01 04 00 00 | ........ ........
00000610 | 02 00 02 04  00 02 02 02 - 02 04 00 01  03 01 03 04 | ........ ........
00000620 | 00 00 04 00  04 04 00 02 - 04 02 04 04  00 01 05 01 | ........ ........
00000630 | 05 04 00 00  06 00 06 04 - 00 02 06 02  06 00 00 00 | ........ ........
                                                      ^^
                                                 [__brkval]

                          [SP]
                           VV
000006b0 | 00 00 00 00  00 00 b7 09 - 03 01 01 06  02 a5 02 00 | ........ ........
000006c0 | 00 00 00 01  00 57 05 06 - cc 00 03 8f  0f 01 00 00 | .....W.. ........
000006d0 | 00 01 00 00  03 00 03 00 - 00 00 07 02  a4 00 01 00 | ........ ........
000006e0 | 03 02 a4 00  05 f8 0d 06 - f6 00 03 00  00 08 c3 08 | ........ ........
000006f0 | de 00 01 00  01 80 1a ed - 02 04 00 41  a4 02 04 00 | ........ ...A....

There's 120 byte separation between the edge of the heap and the stack pointer.  The implementation of the malloc that I ran this under checks to see whether or the the stack pointer is within 128 (__malloc_margin) bytes.  As your code was building in my environment, without the counter-printing in, this managed to not-fail to allocate.  However adding a single additional call to addNewLine was enough to cause malloc() via new to fail.  So you are indeed right on the edge.  And you have no checks to see if malloc or new returning nullptr.
You're making one allocation after another without deallocation anything, which is resulting in a fairly simple pattern of the heap edge advancing by the requested size of your allocation plus 2 bytes each time.  So that's about 248 bytes waste in just heap structure.
I'm not sure on the exact cause of your counter being overwritten, assuming that's what's actually happening.  In fact I was having a hard time finding an case where it would overwrite anything in memory with the code as you have it, but here's a good candidate:
lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};

With generated code looking like:

0x24c6 [addNewLine+244] ldi    r25, 0x00       ; 0
0x24c8 [addNewLine+246] call   0x3830  ;  0x3830 [malloc]
0x24cc [addNewLine+250] movw   r30, r24
0x24ce [addNewLine+252] st     Z, r10
0x24d0 [addNewLine+254] std    Z+1, r11        ; 0x01
0x24d2 [addNewLine+256] std    Z+2, r17        ; 0x02
0x24d4 [addNewLine+258] std    Z+3, r16        ; 0x03

So, if malloc() fails, apparently the new statement will just assume that it didn't and goes ahead and writes into the memory at 0x0000 (nullptr) anyway, ugh.  I think this is because technically you're calling the normal new that is supposed to throw an exception on failure.  But there are no exceptions with the way avr-g++ is set up for Arduino.  As it exists in ArduinoCore-avr version 1.8.3, the new code just returns what malloc returns and the compiler thinks an exception will be in progress if it fails.  Normally you would call the std::nothrow version of new[] that returns nullptr on failure, as in:
lines[linesInserted - 1] = new(std::nothrow) char[4]{startX, startY, endX, endY};
// check lines[linesInserted - 1] against nullptr here

However, there's no facility to do that in 1.8.3.  The master as of writing appears to have addressed this, but that's not shipping yet.

The short answer to this is basically: Don't do that. That is:

Avoid dynamic allocation altogether where possible.

This was mentioned in the comments, but it's worth repeating, use flash where you can.  Besides getting your character data into PROGMEM, you also have some string literals that can be moved into flash by way of F().

To the extent that you're doing dynamic allocation requests:

Check to see that they're actually succeeding

Make as few requests as possible.

Do them up-front at the beginning of the code.  The "up-front" part you're more or less already doing, so that much is good.

It seems if you're going to dynamically allocate under core version 1.8.3 and you're at all in danger of having an allocation failure, it is important that you not use new, since doing so may cause it to overwrite memory for the initialization/construction part after the allocation proper has failed.  Alternately, seriously consider modifying your Arduino core's new.cpp file to do something like call abort() if malloc() returns nullptr, at a minimum, if not something more sensible.  Otherwise, this could drive you insane.

I probably should have pointed out that the register file is memory mapped into the start of data space.  So, when malloc() fails underneath new char[4]{...} the more immediate effect of it continuing to attempt initialization is that of screwing up the general purpose registers, which will do who-knows-what from there; nothing good or terribly predictable.

I didn't realize new called malloc underneath. That would explain a lot honestly. I always forget that you don't have a lot of memory to work with on Arduino, so I think I'm just going to move to using flash or an SD card to store the information for the symbols at this point. Seems like it would be less of a headache anyways.

Yeah, new (with the excepting the "placement" version) is dynamic allocation in any case.  That the it uses malloc is an implementation detail; it needn't strictly be done that way.  It typically that is what happens though.  So far, it doesn't seem like you need an SD card; just look into using PROGMEM and the rest of pgmspace.h.  You may find it a bit confusing at first.

Moving all the graphics data over to flash helped a lot! I'm no longer facing issues. Took a little getting used to PROGMEM but it was definitely worth it.

It would be good to see how this is used rather than just having a class with no context.
But I'd start by removing unnecessary parts, like the display pointer, and you could always use a simple program, like ideone.com to compile quickly and check for errors.
As I read through it I see 2 flaws with memory management.
This block is using the size of a char pointer instead of a character. I don't understand what you want this code to do.
(char**) malloc(sizeof(char*) * Char.sizeOfLines);

Try something more like:
(char**) malloc(sizeof(char) * <numberOfCharsPerLine> * Char.sizeOfLines);

But then even though you're allocating memory for a whole block of lines, then each time you add a new one, you're allocating memory for a new line.
lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};

Instead try something like:
lines[linesInserted - 1][0] = startX;
lines[linesInserted - 1][1] = startY;
...

what is wrong with assigning arrays to items in array of pointers?

Assignment isn't the problem. The problem is that he's using a malloc operation to alloc the entire set of lines, but then allocating again each line individually. It's like allocating an entire chessboard, and then ignoring your chessboard, and allocating each row independently as you fill it. You either allocate the board, or each row. Not both.

you say those are pointers what OP allocates and then you show how to allocate it at once. or am I reading it wrong?


text:
Arduino Pico doesn't work with ST7735 screen
I am attempting to get the graphicstest example bundled with the Adafruit ST7735 library for the 0.96 inch LCD screen.
The example runs fine and serial communication is up and running. However, nothing outputs on the screen. I verified that the code works with other Arduino boards and that I have it properly wired -> SCK to SCL, MOSI to SDA, etc.
I'm not sure if I am doing something wrong, or if this is a limitation of the board.
Edit: I added the modified graphicstest code to the Internet, it can be found here: https://drive.google.com/file/d/1cFOgQXhhH1vou0KUrFzBDMp0iiIp1Yuy/view?usp=sharing
I also added a crude diagram of how the screen is wired up to the Pico. Note that the LCD is powered externally since the Pico cannot handle the current draw of powering the LCD.
https://drive.google.com/file/d/1RmZSHBcelwC9caLoQC9iE5Lb4eHG9S2O/view?usp=sharing

Does your Arduino Pico have the chip atmega32u4? If yes, you could have issue with the library. Most of the standard arduino libraries are for atmega328 or atmega2560 (UNO and Mega). You will find that most of the libraries, that work for UNO or Mega, don't usually work for Arduino Leonardo (atmega32u4).

Show your wiring and any modifications you made to the graphicstest code.

@SimonVu14 I had a feeling that was the case. I'll try to see if there's another library out there other than the Adafruit one.

@timemage I only changed the pin outs to pins that were available on the Pico.
RST was 4, CS was 3, and DC was 2.

Until I can see everything you can see I'm unlikely to be of any help.

@timemage Apologies for it taking a long time to respond. I added the modified graphicstest along with a crude diagram to the question.

The diagram seems at odds with what is shown here where SCK is shown closest the diode.  In your diagram SCK is shown furthest from the diode.

@timemage I am going directly off of what's on their website. https://mellbell.cc/products/pico
What they show on the link you provided is a prototype. Additional research also shows that the SCK and MISO pins I'm connected to seem to be for programming only.

I found out the problem. I was trying to connect to the SCK and MOSI pins on the back of the Pico. Later research shows that these are meant for programming and burning a bootloader onto the microprocessor.
The Adafruit library allowed me to define my own pins for SCK and MOSI.
Once I switched to using the Adafruit_ST7735(int8_t cs, int8_t dc, int8_t mosi, int8_t sclk, int8_t rst) constructor, it worked after that.

Well, it's nice that you got it working, but there really isn't any reason why you shouldn't be able to use those pins.  As you say, they are used for ISP programming, the bootloader or whatever else.  But, they're also just SPI pins and beyond that just "digital" pins.

From a comment on the question:

I am going directly off of what's on their website.
mellbell.cc/products/pico What they show on the link you provided is a
prototype.

The "link you provided" refers to this, which despite being described as for a "prototype", shows correct information with regard to the SPI related pins.
As it turns out the documentation in the images you referenced at mellbell.cc/products/pico is incorrect, both under the product shots and in the pin-outs section under "Documentation".  You can tell this by looking right at their image of their board and their diagram, and comparing that with the pinout of the ATMega32U4 itself:

Interestingly, in the pinout on 8 of their PDF in the documentation section, they have it correct again and closer to the prototype:

Or at least it is with respect to the SPI signals.  The diode is in the wrong and orientation. In fact, the whole board seems to be left-right reversed.
Again, from the same comment:

Additional research also shows that the SCK and MISO pins
I'm connected to seem to be for programming only

It is true that these pins are used for ISP programming.  However, they also carry the data for the SPI bus peripheral when you're not doing ISP programming.  So they are "for programming" just not "only" for programming.  This is down to how the ATMega32U4 is, and not something tha the Pico makers have much control over.
This is also the case for UNO and basically all of the other popular AVR based Arduinos that can be programmed using the ISP method, as opposed to uPDI and others.  What slightly less common is to have these pins only available as unpopulated pads or only available on the ISP header.
I can see why you might want to not deal with those contacts because of the form factor of the Pico board.  However, because those pins are actually 32u4's SPI interface, and they should perform better than the bit-banging that Adafruit library would need to resort to in order to use other (non-SPI) pins.  So there is an incentive to use them.
So, your solution is a solution, but not for the reasons you think.  The pins you were previously trying to use will work when your efforts aren't being undermined by bad documentation, and you get them in the right order.


text:
How to increase the serial port's data throughput
I have an array of numbers that will be subtracted from the ADC readings
of a 50 Hz sine wave. Using Serial.begin(57600);, I can only
output 25 samples per sine wave cycle, or about 1,250 samples per
second. my questions are:

how fast the increent of array number moves with y++ in my int sinus[]? because when i see on serial monitor with 52700 baudrate it can only show about 25 numbers per cycle (50Hz)
how to increase the speed the increment of y++ in my array?

int sinus[] = {
    70, 72, 83, 92, 108, 132, 157, 182, 207, 230, 243, 255, 255,
    255, 250, 238, 217, 193, 169, 143, 118, 98, 88, 77, 72, 80
};
int dataSensor;
int hasil[26];
int datasensor2;
int dataBaru;
int x;
int y;
int intPin = 2;
int output;
int output2;
int toggle;
int toggle2;
int z;

void setup() {
    TCCR1A = 0b00000010;
    TCCR1B = 0b00011100;
    TCCR0A = 0;  //disable millis, delay and mciros
    TCCR0B = 0;
    ICR1 = 3200;

    Serial.begin(57600);

    pinMode(A1, INPUT);
    pinMode(A0, INPUT);
    pinMode(A2, INPUT);
    pinMode(intPin, INPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);

    attachInterrupt(0, genJeah, RISING);
}

void genJeah() {  //intrupsi rising
    y = 5;
}

void loop() {
    dataSensor = analogRead(A0);
    toggle     = digitalRead(A1);
    toggle2    = digitalRead(A2);
    dataBaru = map(dataSensor, 0, 1023, 0, 255);

    for (x = 0; x < 25; x++) {
        hasil[x] = sinus[x];
    }
    // for (x=0; x<100; x++){

    output = sinus[y] - dataBaru;
    Serial.println(output);
    y++;
    if (y > hasil[26]) {
        y = 0;
    }
}

what does move number mean?

would raising the serial speed to 230400 help? - 57600 outputs 5760 characters per second, so even if you output a single character as fast as possible, you wont make 5760 "data points" per second (the reason you only get about 2500 per second is that you output an average of 2.3 digits per "output"

Another possibility of raising speed is sending byte data instead of ASCII data. Would that be acceptable?

I edited the title and the body of your question to make it clearer. I believe my rewriting faithfully reflects what you intended to write, but feel free to re-edit if I misinterpreted something. Note that, for the purpose of your question, the fact that you are subtracting values from an array is completely irrelevant. Ideally you should remove this part (and the corresponding code) from the question in order to keep it focused on one single problem. Unless the question is about a compile error, you should also make sure, before posting some code, that it does at least compile.

Your code doesn't compile, therefore it cannot run at one speed or another speed. For example, where is y declared? And intPin? And toggle? We can't be expected to help speed up code that won't even compile.

Arduino @ 16Mhz with AVR MCU can at most perform 8.9 K ADC sample/s (10-bits, 112 us). This assumes the same channel (pin). Changing analog pin takes additional time. The upper limit for the sketch is approx. 1 K sample/s just for the ADC (10-bits). The conversion from integer to string to print takes additional time but ADC can be run in parallel. Also the ADC can be initiated for 8-bit conversion instead.

Don't use analogRead, as analogRead is blocking, while the conversion is taking place. Better to read the ADC result value, and then immediately start a new conversion (asynchronously), while run the rest of the code in the loop.

how to read adc without using analogread?  @Gerben

i have edited again my question @jsotola

i have edited again my question @EdgarBonet

i have edited again my question @NickGammon

how to read adc without using analogread? - this is another question, isn't it? However see this: http://www.gammon.com.au/adc

See Nick Gammons link; section "Read without blocking".

If you are looking for throughput then stop sending the ASCII conversion of numbers and just send the numbers.
In other words, use Serial.write() rather than Serial.print(): you can send ~25k integers per second with a 52k baudrate.
As you are actually remapping the ADC output to a single byte, that means you can easily achieve a 48k/s throughput with this simple change.
If you are also looking for low latency please consider the USB connection is actually packet based, not stream based, which means you will receive the data in chunks, no matter how frequently you write. You can speed it up a bit flushing the channel, at the cost of throughput.

will it work with Serial Plotter?

Do you mean the plotting view included in Sloeber?

Arduino IDE has Serial Plotter too

Sorry, wasn’t aware of that. For the Sloeber one I wrote a library (PlotPlus) which can probably achieve the 10k/s throughput considering the 2 additional protocol bytes used. I’m not sure it is compatible with the Arduino IDE one, never tried myself

doesn't Serial Plotter read numbers as text?

As I said, I cannot speak for the Arduino IDE implementation, but the Sloeber one uses a binary protocol

how fast the increment of array number moves with y++ in my int
  sinus[]?

Incrementing an int is fast enough. Even on a slowish Uno, y++ will
take less than one microsecond to execute, so you can do it a million
times per second if you want...

when i see on serial monitor with 52700 baudrate it can only show
  about 25 numbers per cycle (50Hz)

Your loop() is doing more than y++, no it's no wonder it takes
more time!
There are two slow functions there:

analogRead() takes about 110 µs
Serial.println() is initially fast, but once the output buffer is
full, it runs at the speed of the serial port.

The limiting factor here is Serial.println(). You are printing
4.6 bytes on average per sample (2.6 printable characters,
plus CR and LF). Each byte is worth 10 bits on the wire (one start
bit, 8 data bits and one stop bit). That is 46 bits per sample
at 57,600 bits per second. The ratio of these numbers gives the
1,250 samples per second you experienced.

how to increase the speed the increment of y++ in my array?

It's very hard to answer this question because you did not explain what
you are actually trying to achieve. If I naively take the question at
face value, the simplest option is to just repeat y++ several times
per loop iteration:
y++;
y++;
y++;
y++;

This can obviously be optimized into
y += 4;

and the compiler may even be able to figure out this optimization by
itself.
But maybe what you don't care so much about speeding up y++, and
instead you want to process more data samples per second? If this is the
case, then you can speed up the loop by speeding up the serial port:
Serial.begin(115200);

by printing only every other sample (or one sample every N):
static bool print_this_sample;
if (print_this_sample) {
    Serial.println(output);
}
print_this_sample = !print_this_sample;

by printing one sample every so often:
static uint32_t last_print_time;
if (millis() - last_print_time >= PRINT_PERIOD) {
    last_print_time += PRINT_PERIOD;
    Serial.println(output);
}

by printing the samples in binary (first make sure they fit in a byte):
Serial.write((byte) output);

Now, what I suspect, is that you actually want to get your processing
synchronized with the 50 Hz mains. If this is the case, you will
have to completely rethink your program, and reason about the timings:
at what specific time do you want to take each sample? The Arduino
timing functions (millis() and micros()) should help.
As you see, half of this answer is me making guesses about what you may
want to achieve. This is a sign of a very badly written question.
Normally it is your job to explain that in detail. Please, rewrite the
question and provide all the necessary background to help us understand
your project, and the difficulties you are facing.

Might want to add that the number conversion will take several hundred micro-seconds as it involves integer division.

thanks, again its very great explanation


text:
invalid type argument of unary '*' (have 'uint8_t {aka unsigned char}')
New to Arduino and was hoping to figure this out. I am working with a bill acceptor and getting the value once you insert the money. The code works fine with an older Arduino, but I am using Arduino Uno Wifi Rev2 and getting some major issues. I finally go it down to just this error and i cant figure this one out (Help Please!):
invalid type argument of unary '*' (have 'uint8_t {aka unsigned char}')

On line:
*digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));

Library that is giving the issue:
ReceiveOnlySoftwareSerial

You have to familiarise yourself with pointers if you want to use '*'. Also, edit your post and add more of your code.

What are you trying to do with this? Please provide more of your code and an explanation about your indents with it.

@chrisl this is code that already exists out there, i am just trying to use it on a newer board. The library ReceiveOnlySoftwareSerial is producing this error. I dont want to post the whole code in here but you can find the code here http://gammon.com.au/Arduino/ReceiveOnlySoftwareSerial.zip


text:
Are any Arduino boards especially suited for low-power operation?
The Arduino project has done an excellent job in providing a portable software interface to a number of different hardware systems.
Are there any Arduino-compatible systems which are especially applicable for very low power battery-based operation?  Specifically, in an application where a device wakes up periodically (e.g. for data collection) or activated by a user button press?

Related to your previous question: https://arduino.stackexchange.com/questions/55813/converting-a-standard-setup-loop-sketch-to-a-low-power-application

Technically you can use any arduino for that purpose with some modifications. I recommend to go with an arduino Pro Mini and remove the LED and the voltage regulator.
But if you don't need so much I/O you can go with a digispark Attiny board.

To program a pro-mini you need a separate usb-to-serial adapter for programming (or a spare Arduino UNO)


text:
"Hello World" program for nRF24L01+?
Where is a simple program that demonstrates unidirectional data transmission over a pair of nRF24L01+ radios?  It should have adequate output so that a beginner can determine that the transmission is working properly.

http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo

http://tmrh20.github.io/RF24 built in examples will do.

I found this site to have pretty strait forward instructions:
https://maniacbug.wordpress.com/2011/11/02/getting-started-rf24/
Main Library: https://github.com/maniacbug/RF24/
Example Sketch: https://github.com/maniacbug/RF24/blob/master/examples/pingpair/pingpair.pde

TMRh20 RF24 library examples work well.
Install TMRh20 RF24 library in the Arduino IDE Library Manager (“Sketch/Include Library/Manage Libraries...” and search for “RF24”). Then open the Getting Started example (“File/Examples/RF24/GettingStarted”).
You’ll need to change the “radioNumber” variable to 0 or 1 on the sending and receiving Arduino (line 13 of the code).
For the hardware I prefer to use pins 9 and 10 instead of 7 and 8 (line 16 of the code), so that all pins are connected to port B.
The nRF24 is supposed to be 5V tolerant on the data lines, but not for the power supply, so you need to connect VCC to 3.3 V. In my experience, it works best if you use it with a full 3.3 V board (ESP8266 or Arduino Pro Mini).
You absolutely need to add a strong capacitor between VCC and ground. I use a 2200 µF capacitor, but 10 µF may be enough (http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo).
I also wrote a small article about the nRF24L01+.

Here are several "getting started" articles that contain simple programs.
http://tmrh20.github.io/RF24
https://groups.google.com/forum/#!topic/nrf24-arduino/VaC2U5D1o_s
http://arduino-for-beginners.blogspot.com/2013/02/setup-nordic-nrf24l01-rf-modules-to.html

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


text:
How do I upload an Arduino STM32 binary from the Mac command line?
I've compiled an Arduino program via a Makefile and have the resulting hex file.
From the Mac command line, how do I upload this hex file to my STM32 Cortex M3 board?  For an ATMEL processor I would use avrdude.

There are several different tools for uploading binaries to a Cortex M3.  Depending on the board (not chip) configuration, they include (ht: Majenko):

dfu-util through an FT232 adapter
stm32flash through serial
micronucleus through the Micronucleus bootloader
stlink through an STLink programmer

Many Arduino flavors use a board with some kind of USB or FT232 adapter.  In this case:
the STM32 line of processors include a DFU (device firmware update) bootloader in ROM.
The dfu-util project supports a Mac version of dfu-util, their command line DFU tool.
Note that this answer is identical for any binaries which run on the processor, be they Arduino sketches or programs developed with other frameworks.


text:
Converting a standard setup/loop sketch to a low power application?
Suppose I have a typical setup/loop style sketch, such as this one which turns on an LED when a button is pressed.
How do I modify this so that it enters low power mode, awakes on the button press, and puts itself back into low power mode when its logic has finished?
void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // desired: enter low power mode here
}
void loop() {
  int buttonState = digitalRead(buttonPin);
  // desired: awake from low power mode here
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
  }
  // desired: back to low power mode here
}

For which arduino board?

@Jot, I'm open to input about any of them.  If some are especially good for low power applications I would be interested in hearing about that.

Some are. For example a "bare bones" atmega328p. See: https://www.gammon.com.au/power Some Arduino MKR boards can be powered with Lipo battery. The ARM M0+ processor of the MKR boards can go into sleep mode, but I don't know if there is a library for that which supports all modes. I also don't know which MKR boards use very little current for the rest of the components of the board.

This sketch is almost identical to the powerDownWakeExternalInterrupt.ino sketch that comes with the LowPower Library. I'm using INPUT_PULLUP and a N.O. push button switch to trigger it to wake up and turn an LED on.
#include "LowPower.h"
const byte wakeUpPin = 2;

// Just a handler for the pin interrupt.
void wakeUp(){}

void setup(){

  // Configure wake up pin as input.
  // This will consumes few uA of current.
  pinMode(wakeUpPin, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  // Allow wake up pin to trigger interrupt on low.
  attachInterrupt(0, wakeUp, LOW);

  // Enter power down state with ADC and BOD module disabled.
  // Wake up when wake up pin is low.
  LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

  // Disable external pin interrupt on wake up pin.
  detachInterrupt(0);

  // Do something here.
  digitalWrite(LED_BUILTIN, HIGH);
  delay(2000);
  digitalWrite(LED_BUILTIN, LOW);

}


text:
How do I reset my libraries back to original condition?
How do I reset my arduino installation back to its original state? i.e., no extra downloaded libraries, etc.  If I delete Documents/Arduino/libraries is there any other state that needs to be cleaned up?

What operating system are you using? Did you use the installer or the portable zip?

Delete the Documents -> Arduino -> Libraries to remove all your libraries.
Delete the User -> AppData -> Local -> Arduino15 folder to remove all the preferences.
Uninstall Arduino IDE.
Install a fresh one.

Directory to suppress for reset config.

C:\Users\YourName\.arduinoIDE
C:\Users\YourName\AppData\Local\Arduino15
C:\Users\YourName\AppData\Local\Programs\Arduino IDE
C:\Users\YourName\AppData\Local\arduino-ide-updater
C:\Users\YourName\Documents\Arduino
C:\Users\YourName\AppData\AppData\Roaming\Arduino IDE
C:\Users\YourName\AppData\AppData\Roaming\arduino-ide


text:
Externally Powering a 3.3V device (nRL24L01+) with a 5V Arduino Pro Mini?
I have seen several references where the solution to interfacing a 5V Arduino with a 3.3V nRF24L01+ was to power the nRF24L01+ externally.
How do I do this?  The ground of the nRF24L01+ is connected to the Arduino; can I simply attach 3.3V power between the power and ground pins of the nRF24L01+?

"... power the nRF24L01+ externally." Not really sure what this has to do with interfacing with it...

If you have a 3.3v supply or regulator, yes.  Preferably the 3.3v and 5v would be available/absent at the same times.

To connect the nRF24L01+ to a 5V Pro Mini you will need external 3.3V power supply to power the nRF24L01+.  The ground for the Pro Mini and the ground for the nRF24L01+ should be tied together to ensure a common ground reference.
The inputs to the nRF24L01+ are 5V tolerant so you will not need a level shifter to convert the 5V Digital IO on the Pro Mini to 3.3V. Be aware the not all 3.3V devices have 5V tolerant inputs like nRF24L01+.
You might want to look into using a 3.3V Pro Mini with that you should be able to use the regulated 3.3V power on the Pro Mini to power the nRF24L01+. Be aware that the 3.3V Pro Mini only runs at 8MHz instead of 16MHz.

The second part is incorrect, in this case. The nRF24L01+ has 5v tolerant inputs. So, for this specific device, an level shifter isn't needed.

Yes, You can.
In any communication system, each module should have the same reference point of operation, or else the line is said to float. Here it is GND of arduino mini and GND of nRF24L01+.

you can download the references from this link: https://s3-ap-northeast-1.amazonaws.com/sain-amzn/20/20-019-102/NRF24L01.rar
Hope the information may be helpful. Cheers!

As far as I can tell, the file you're linking to only contains some source code. Can you explain how it's relevant to the power supply issue in this question? Thanks.

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


text:
How do I view Serial Output on an Android Device?
Within the Arduino IDE Serial.* output can be viewed with Tools / Serial Monitor.  How can I view Serial.* output on an Android?  As a concrete example, how can I view the output from Examples / Communication / ASCIITable?

This of course depends on the specific Arduino model generation or USB serial cable utilized.

These steps will allow your Android device to function as an Arduino Terminal.

Download a Serial Terminal app.  I'm using Android Hyperterminal, English version.
Attach an OTG ("On The Go") cable to your Android device.
Attach your Arduino to the OTG using your regular USB cable.
Make sure the terminal program is set to the same baud rate as your sketch.
Run the terminal App and select the USB port.

I didn't find that app, and ended up installing "Serial USB Terminal" by Kai Morich, it works well so far!


text:
HUZZAH ESP-8266 (by ADAFRUIT): How to use with the ARDUINO R3
I have recently purchased a ESP-8266 HUZZAH by adafruit. I'm kind of new to the whole arduino concept. I would like to know how I would be able to utilise this breakout board with my Arduino to do anything. I have searched on the internet and I know about flashing the board. However, I have no idea how to flash this device. Some help would be appreciated.
I also have no idea where to put my pins. I know that there are RX and TX pins on the UNO, but those are at 0 and 1. Most online guides are using something like 11/12 or 2/3.
Here is the link to the product website
Thanks,
Vraj

You wouldn't typically use it with an Uno. You program the ESP8266 directly with your own code and interface it to your devices of choice.

Oh ok. But would I still be able to use it with an arduino. I'm asking because I don't want to immediately go out and buy a new board if the old one works.

You can use it "with" an Arduino if you want to use it with an Arduino. You need some form of USB to UART device to program it, and the Arduino can do that. Just connect RESET to GND on the Arduino to disable the Arduino, then pins 0/1 can link your computer to the Huzzah.

Thanks, one other thing. I have a working MFRC522, I want to send the data from the RFID Card to the WiFi board to put it onto a website/server. If I connect it to the arduino and shut the arduino down. Would this still be possible?

No. You would connect the MFRC522 directly to the Huzzah. The Arudino is just the equivalent of an FT232 board. It's a dumb pipe. If you want to connect the MFRC522 to the Arduino then you will also have to write software for bothe the Arduino and the Huzzah to communicate between them (probably over serial).

Woah. That's weird. So I found this thing on the MFRC522 github post. It states that it is compatible with the ESP8266. So now that I have some info on that, what's the deal about the flashing thing. Would I still have to perform the flash? And how would I do that? Sorry, just very confused...

"Flashing" is the act of uploading your software to the ESP8266 from the Arduino IDE. It's how you get your code into the chip to make it do what you want it to do.

Oh yes. I see thank you. So that's what the posts meant. I think I have a deeper knowledge of the topic. Once I can fully get the solution, I'll post it as an answer. Thanks for the advice!

Ok, I'll keep this post open for anyone who got this board and the Arduino and wanted to use them together (it's probably only me, but who cares). Anyway, when looking at this board it's basically it's own controller. The front pins are what you need to communicate with the board itself. It's meant to be used with a FTDI cable to the computer. Anyway, looking further into it we see many pins behind the first 6 or so. To connect it to the computer using the Arduino you need to use this config.
Arduino | HUZZAH ESP8266
RX | RX (In the front)
TX | TX (In the front)
5V | V+ (In the front)
GND | GND (In the front)

Also, you need to create a thing where the Arduino won't be able to function, making it a communicator port for the HUZZAH itself. To do this simply take one of the GND pins on the Arduino and connect it to the RESET pin on the Arduino. After doing this you need to set up your ESP8266. This is a link to a basic guide on how to do this by ADAFRUIT. Instead of the USB cable, you are using your arduino as a cable essentially (a pretty expensive one). Anyway, the port number should be the port that your arduino is connected to (to the computer). This is if you want to use the ARDUINO IDE.
To use NODEMCU LUA which it comes preloaded with, you need to refer to this guide.
The other thing I wanted to mention was how to utilise a basic board with the controller. I had to use a MFRC522 RFID board with the Arduino, and I wanted to send the info to the internet. Sadly, it seemed as if I couldn't use the arduino itself. To use this board I used many sources. First, was the library github (this one).
The next step was to get the pin layout (from here). However, if you look at it it's in the pin format of a WESMOS D1 MINI board. The final source was to look at the product page (here) and convert the pin format to fit the HUZZAH Board (It's in the PIN section). That took a long time, but now you're done. That's a basic guide on how I used the HUZZAH Board with my arduino.