text:
How can I connect an Arduino / ESP8266 to an Azure MySQL database?
I am currently trying to connect an ESP8266 to my Azure MySQL database via WiFi, but have not yet been successful.
I have tried a bunch of guides, but no luck and I'm running out of ideas. I have made a connection to an IoT Hub in Azure but could not forward the messages to the MySQL database in the cloud. I managed to get it stored in a blob datatype but had so many issues with it that I kinda scratched that idea.
Last thing I tried was trying to implement the example from
https://github.com/ChuckBell/MySQL_Connector_Arduino
more specifically the 'connect_wifi' example. I was unable to find the ip of my azure server so i tried using some of the code from the 'connect_by_hostname' but no luck there.
I'm new to Arduino and cloud in general so any help is appreciated.

if you can get it stored at all, but not in sql, then it's not really an arduino question. typically you hit some http gateway that does all the fancy stuff like DBs for you.

How would I go about let's say getting the blob type files which are stored in a storage account in my Azure server sent to my SQL DB (also in the azure cloud) using http gateway?

usually a small snip of php or something like that, that listens on the URL then makes backend calls to the services mentioned once there's something for it to do.

Not sure how you would directly connect with an C++ embedded file. One way you could achieve this is by creating a computer application and connect to the machine via Bluetooth.
{Arduino}
* Intake information
* Process into commands
* Push through software serial ----(Blue Tooth-----> { PC or MAC}
                                                    *Create C# or Swift App
                                                    *Intake information via COM-PORT
                                                    *Prepare SQL command with serial data
                                                    *Push to database server

This may of not of been the method you were looking for, but it's a way I found around the issue when working with Azure Databases and Arduino Micro-Controllers. An alternative is going to Raspberry Pi which has a little more resources to deal with server functions.
Hope this helps.


text:
How does Peggy2 drive rows with 74HC154 Decoder?
Trying to program Evil Mad Scientist's Peggy 2 board without their Library.
The board drives a LED Matrix with

Source  74HC154 Decoder
Sink    STP16CPSO5  LED Sink Driver

Schematic
What has me confused is the 74HC154 Outputs can only have one output set to Low at at time. See table below. This means all but one row is "on". Isn't this backwards?  Shouldn't all outputs be low except one that is high?  Selecting what row you want on, rather than selecting what row you want off.  It looks more like the 74HC154 is a Sink.  Thanks.

Not sure how this relates to Arduino as written.  You might find this helpful: How to ask a good question for Arduino Stack Exchange

If you look into the datasheet of 74HC154, you can see that each output has an Active Low State. Also in the schematic, the leds row part use a pnp transistor (see page two). As so, they will be active if the input is low.

This means all but one row is "on". Isn't this backwards?

Since they are PNP, the only active row is the one with Low value and the current of that row is sink through the selected column(s) in the STP16CPS05

Ahh!!!    Makes perfect sense!  Low turns PNP on!   Thank you brtiberio!

source: Stack Exchange

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

sort: votes


text:
RTC and Time Library Problems
Want to use Arduino Time library and occasionally sync it with an external RTC (Maxim DS3231 chip).   I am turning LEDs on and off based on time and using a shift register (Nexperia 74HC154PW) and encoder (ST Micro STP16CPS05TTR).
It has all been working fine, until I decided to use libraries as shown in:
https://github.com/PaulStoffregen/DS1307RTC/commit/160fa0dbca29f6fb3c1465954f89ad7f1f0fbf67
//using libraries shown in examples/SetTime
What I cannot figure out is why using #include <DS1307RTC.h>  prevents the LEDs from lighting.
I have only included code below that lights the LED via a shift register to demonstrate that it runs without an error, but (have to take my word) does not light the LEDs.
If I comment out #include <DS1307RTC.h>  the LEDs light.
Note that in the code below time is not used for anything.
What is including  <DS1307RTC.h>  doing to break it?
Puzzled.
#include <Wire.h>
#include <Time.h>
#include <TimeLib.h>
#include <DS1307RTC.h>    //the problem:  Will not light LEDs if this is used

                          //RTC used is Maxim DS323`chip
                          //RTC connected to ATMEGA328 pin 27 PC4(ADC4/SDA) and pin 28 (PC5 (ADC5/SCL)
                          //RTC works great.

//Ouputs from Atemga and Inputs into 74HC154 pins
const int A0_Pin = 4; // Atmega328 pin  2 = Arduino pin 4
const int A1_Pin = 5; // Atmega328 pin  9 = Arduino pin 5
const int A2_Pin = 2; // Atmega328 pin 32 = Arduino pin 2
const int A3_Pin = 3; // Atmega328 pin  1 = Arduino pin 3

// Shift Register STP16CPS05 has 16 outputs.  Send two sets of 8 bits to turn on columns.  1 = on.
const int latchPin = 9;   // Aruino Pin 9 = ATMEGA328 DIP Pin15 = TQFP Pin 13. Connected to LE-DM1 of STP16CPS05 pin 4  Latch Pin
const int clockPin = 13;  // Arduino Pin 13 =  ATMEGA328 DIP Pin19 = TQFP 17. Connected to CLK of STP16CPS05 pin 3  Clock Pin
const int dataPin = 17;   // Arduino Pin17 = ATMEGA328 DIP Pin 26 = TQFD 26. Connected to SDI of   STP16CPS05 pin 2  Data Pin (SDI)

void setup() {

pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);

pinMode(A0_Pin, OUTPUT);
pinMode(A1_Pin, OUTPUT);
pinMode(A2_Pin, OUTPUT);
pinMode(A3_Pin, OUTPUT);
 }

void loop() {

  digitalWrite(latchPin, LOW);  //LOW through inverter = HIGH = OEDisabled for both Decoder and Shift Reg
                               //LOW Shift Reg New Data to Buffer
  digitalWrite(A0_Pin, 0);
  digitalWrite(A1_Pin, 1);
  digitalWrite(A2_Pin, 1);
  digitalWrite(A3_Pin, 0);

  shiftOut(dataPin, clockPin, LSBFIRST, B11000000);
  shiftOut(dataPin, clockPin, LSBFIRST, B11111111);

  digitalWrite(latchPin, HIGH);  //HIGH through inverter = LOW = OE Enabled for both Decoder and Shift Reg
                               //HIGH Shift Reg Move data to Output pins

}

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

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


text:
ESP8266 working as station while in AP mode
I'm programming an ESP8266 via the Arduino IDE with Arduino libraries.  I explicitly set the WiFi mode to WIFI_AP, but then, as described below, I'm still able to use it as both AP and station.  That leaves me unclear what's meant by the three modes available (WIFI_AP, WIFI_STA, and WIFI_AP_STA) since it seems that I've set to WIFI_AP explicitly but am getting behavior consistent with WIFI_AP_STA.
I have read various documents online about these modes. I think I'm clear on the conceptual difference between them.  What concerns / confuses me is that the actual behavior does not appear to match the specified behavior.
More detail:
Near the beginning of my setup function, I have this code
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, key);

server.begin();

where ssid and key are strings defined with appropriate values, and server is a global variable of type WiFiServer that has been initialized outside of setup.  When run, I see the network with the given name on my phone and can connect to it with the given password.  I can then browse to the IP address assigned by the ESP8266 and set the webpage sent by the server that's been defined in code.  So far so good.
At some point later, inside my loop, a condition triggers the ESP8266 to connect to my router.  Specifically, I have this sequence of code that runs once that trigger occurs:
WiFi.disconnect();
WiFi.begin(router_ssid, router_key);
auto status = WiFi.status();
while ( (status != WL_CONNECTED) && (status != WL_CONNECT_FAILED) ) {
    delay(500);
    status = WiFi.status();
}

As before, router_ssid and router_key are variables declared elsewhere with the proper values for my router.  I can verify from subsequent print statements, that the connection succeeds and get the IP address as assigned by my router. It is clear that the new IP is assigned by the router because it is on the subnet used by my router, which is different than the subnet the ESP8266 is defining in AP mode.
The ESP8266 is configured to serve a small webpage, as noted above. I can now reach that page using my phone, which is connected directly to the ESP8266 via the IP address assigned initially by the ESP8266 in AP mode, and I can also reach the same page from my laptop (connect to my router) using the IP address assigned by my router.  It would seem that I'm effectively in "AP+STA" mode now, despite having explicitly set to "AP" mode at the beginning.
So what's happening here?  Did I automatically switch to "AP+STA" mode when I called WiFi.begin?  If yes, what's the point (if any) of calling WiFi.mode?  If no, then why am I able to operate as if in "AP+STA" mode given the explicit setting of "AP" mode?

WiFi.begin() is a function of the ESP8266WiFiSTAClass. It changes the WiFi mode for you to STA or AP+STA based on the current mode.
begin functions are in ESP8266WiFiSTA
enableSTA function is in class ESP8266WiFiGeneric

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


text:
ESP8266 does not reconnect to WiFi on reboot
The ESP8266 is supposed to remember the WiFi credentials and reconnect to the network (if it is available) after each reboot.  That was the topic of this question: Does the ESP8266 somehow remember wifi access data?
I was observing that behavior and something has changed, I think when I updated via Board Manager in the Arduino IDE.  Now the credentials are lost each time that the device reboots. I've tried going back to earlier versions, but I have not been able to roll back to a version of the board definition that restores the old behavior.
Here's a sample sketch that I boiled down for testing:
#include <ESP8266WiFi.h>

char ssid[] = "ssid";
char pss[]  = "pass";

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

  Serial.println("Started");

  pinMode(0, OUTPUT);
  pinMode(2, OUTPUT);

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Not connected");
    WiFi.begin(ssid, pss);
    digitalWrite(0, LOW);
    digitalWrite(2, HIGH);
  } else {
    Serial.println("Connected");
    digitalWrite(0, HIGH);
    digitalWrite(2, LOW);
  }
}

void loop() {
  Serial.println("Loop");
  delay(500);
}

The first time through, of course, it hits the first case and prints "Not connected."  On reboot, however, I was expecting it to hit the second case and print "Connected".
I'm programming via the Arduino IDE.  The board is the Adafruit Feather HUZZAH ESP8266.  I've tried lwIP v1.4 and lwIP v2 in version 2.4.1 of the board.  I started rolling back versions from there got the same run-time results.
So, questions:

Is this a known bug of the ESP8266 modules in recent versions?
Is there some aspect of the WiFi configuration that's preserved on the board when I upload a new sketch? If so, how do I roll back?

remove the if statement from the setup() block .... put serial.println(WiFi.status()) into the loop() block .... reduce the delay to 100mS ..... that should show you if it connects and how long it takes to connect

The esp8266 SDK libraries starts the STA connection, but it is handled by other thread then the Arduino sketch. You can wait for this connection in setup with waitForConnectResult. It returns status().
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Not connected");
    WiFi.begin(ssid, pss);
    digitalWrite(0, LOW);
    digitalWrite(2, HIGH);
  } else {
    Serial.println("Connected");
    digitalWrite(0, HIGH);
    digitalWrite(2, LOW);
  }

to connect with remembered STA mode, ssid and password, but with static IP address
  WiFi.setAutoConnect(false);
  IPAddress ip(192, 168, 1, 8);
  IPAddress gw(192, 168, 1, 1);
  IPAddress sn(255, 255, 255, 0);
  WiFi.config(ip, gw, sn, gw);
  WiFi.begin(); // uses remembered ssid and password
  WiFi.waitForConnectResult();

This fixed the issue in the sample sketch that I created for the question.  For anyone coming along later, to make it work in the real sketch, I had to use this and also coordinate it with other aspects of the WiFi set-up, especially the selection of the mode.  My original was changing the mode from AP to AP+STA over the course of the sketch, and I had to eliminate that part so that it is in AP+STA from the start.  Strange that this same sketch worked before and then suddenly stopped, but I'm happy to having working again now.

mode and AP settings are remembered too and initiated parallel to sketch

First, let's answer the OP's questions directly:

Is this a known bug?
Ans: There are and will continue to be '[issues][1],' but as
@Juraj's    answer points out it was not an issue, but a sketch that
wasn't    waiting for the quickest method to get wifi + IP ready on
an esp8266,    the SDK connect.

Is there ... WiFi configuration that's preserved on the board when I upload a new sketch? How to roll back?
Ans: There is no 'rolling back,' only erase & write new data to flash to recover. At the time of sketch upload, 'wifi settings' can only be erased. The user would choose in the Arduino IDE menu > Tools > Erase Flash: Sketch + Wifi Settings. Those 'wifi settings' are typically written to flash by calling

WiFi.begin(ssid,passphrase);  // or,
WiFi.begin(ssid,passphrase,channel,bssid,connect);  // about 2x quicker

The final arg can be false; we don't even need to connect to wifi to save the settings, eg.
begin("ssid", "passphrase", 1, {0xA4,0xB1,0xE9,0xBC,0x6A,0x28}, false);
ESP.restart();

Then wait for the SDK firmware to connect.
And now let's conclude with the 'newer' information, due to changes in the Arduino esp8266 core 3.0, circa mid-2020.
Beginning in core 3.0, the SDK connect feature was disabled by default. Since then, sketches wanting to take advantage of the quick SDK connect (about 220 ms, or twice as fast as any WiFi.begin), the following line must be included early in the setup() function
enableWiFiAtBootTime();                // prevents shutdown of sdk connect


text:
Need debug Software that can be used with Arduino IDE
Background: I have made a standalone Arduino board using Atmega328PB.  I have written code for a clock which lights LEDs based on the time.  After a day or so it locks up.  Sometimes it reboots.
I would like to get debug software that will tell me where in the code it is locking up or crashing.
It could be a memory issue - stack and heap crashing(?).
Compiler tells me sketch is using 62% of 32256 bytes storage space. Global variables use 34% of dynamic memory leaving 1332 bytes for local variables of 2048 bytes total.
Question:  Is there relatively cheap ( < $100) debugging software that is not very complex I could use to solve this issue?

serial.print() instructions placed in the program and serial monitor

did you use String?

@jsotola actually that's not really debugging (but afaik the only way on an Arduino)

Atmel Studio and a real hardware debugger. It's hardware you need, not software. Also remove String from your code.

I am not using String in my code.

What hardware would I use with Atmel Studio?

@MichelKeijzers, it is a sad state of affairs with debugging the arduino .... i have been using an array of integers ... various points in the program increment one of the integers ... a button press dumps the array to serial ... it avoids time delays due to multiple serial.print() statements within the program

you could use the watchdog interrupt to print some information about the state of the MCU and then let the watchdog reset the MCU

I did read about the watchdog interrupt.  Do you know of a good link I could learn about it and how to print the state of the MCU?

https://github.com/per1234/WatchdogLog

Thanks Juraj!  I will study that.

@jsotola that's approximately the same as I also did some debugging (except for the button which is a good idea). But also the lack of memory makes this hard to 'store' some data (as lack of SRAM is already an issue without this way of 'debugging'). Testing all non-Arduino related code via a separate PC program/unit tests is also a good idea, but of course you cannot test Arduino specific code this way.

If you suspect there is a memory leak, you may want to Serial.println the freeMemory in your loop.

@hcheung I will try printing free Memory.  I did not know of the MemoryFree Lib.  I just let it run for 14 hours with serial prints throughout and it went into a strange mode.  It went to a function from Loop and just kept going through the function like it was in a while loop.  Then every 7 seconds it would randomly go back to loop and go to a few other functions, and in one function went through if and else statements like they were both true, then back in the first function as if a while loop again....then repeat.  I reset the board and runs fine. Lets see what FreeMemory tells me.


text:
HM-10 Central mode starting a connection
I'm trying to issue a connection via HM-10 from arduino (rather than my phone).
However, I'm unable to start a connection from arduino using both AT+CON and AT+CONNL. When I try AT+CON I get OK+CONNA and when I use AT+CONNL I get OK+CONNE. Here's my code:
#include <SoftwareSerial.h>
SoftwareSerial bluetooth(8,9);

void setup() {
  Serial.begin(115200);
  Serial.setTimeout(50);
  bluetooth.begin(115200); //open BLE connection
  bluetooth.setTimeout(50); //set timeout
  bluetooth.write("AT+ROLE1");
  //bluetooth.write("AT+ROLE0");
  delay(50);
  bluetooth.write("AT+NOTI1");
  delay(50);
  bluetooth.write("AT+CONC40BCB403020");
  delay(50);
  //bluetooth.write("AT+CONNL");
}

void loop() {
    while (bluetooth.available() > 0) {
      String response = bluetooth.readString();
      Serial.println(response);
    }
}

The response that I get is:
OK+Set:1
OK+Set:1
OK+CONNA

Can you let us know what is the response to the commands AT+CON and AT+CONN after 10 seconds?

By now you've surely moved past this, but: I found that I had to try connecting multiple times in order to get a connection to complete.  Also, your timeout might need to be longer?


text:
Why this code for ESP8266 goes into STA+AP mode?
I'm using Arduino IDE 1.6 nightly with Generic ESP8266 Board.
Why this code runs in mesh mode instead of simply connecting to my wifi?
My goal is to test out MDNS, but so far I found this:

board connects to my wifi
but board also opens an ESP- access point
when connected to my wifi on my computer I cannot resolve http://esp8266-webupdate.local/update
when connected to the open ESP- wifi I can resolve http://esp8266-webupdate.local/update

To my understanding such code should just connect to my wifi and I would then be able to navigate to http://esp8266-webupdate.local/update, am I missing something?
output (note STA+AP)
Booting Sketch...
......
Connected, IP address: 192.168.1.20
Mode: STA+AP
PHY mode: N
Channel: 10
AP id: 0
Status: 5
Auto connect: 1

code
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>

const char* host = "esp8266-webupdate";
const char* ssid = "myhomeap";
const char* password = "blabla";

ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;

void setup(void){

  Serial.begin(115200);
  Serial.println();
  Serial.println("Booting Sketch...");
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  WiFi.printDiag(Serial);
  MDNS.begin(host);

  httpUpdater.setup(&httpServer);
  httpServer.begin();

  MDNS.addService("http", "tcp", 80);
  Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host);
}

void loop(void){
  httpServer.handleClient();
}

because of the WiFi.mode(WIFI_AP_STA); line?

the mdns propagation is not instant. wait some time

thanks, do you happen to know if is it necessary to go into this mode for mdns to work? this code was taken from examples

mdns works as expected in STA mode. only sometimes it takes time until the mdns name appears in IDE Port menu. (I use Eclipse and there I can type the address if it is still not found by mdns service)

yeah I mean, is this mode necessary (instead of going only pure station) for this example to work?

STA only yes. and it doesn't need mdns. you can use the IP address. for Upload from IDE use ArduinoOTA library

the code in question is example from the ESP8266HTTPUpdateServer library. it runs a web server and this web server enables to upload a new esp8266 code in binary form. after the code is uploaded the esp8266 restarts with the new code.

It goes into STA+AP mode because your code is telling it to do that.
If you want it to just go into STA mode then your line:

WiFi.mode(WIFI_AP_STA);

should be

WiFi.mode(WIFI_STA);

thanks, the code was taken from examples, do you know if going into AP mode is necessary for MDNS to work at all?

In theory MDNS should work in any mode, but of course would only be visible on networks that the ESP was actually connected to.
There are several issues filed on the MDNS code that show other people having trouble with STA+AP mode. There was a fix checked in but it's not clear that it really resolved the problem. So you're not the only one with problems with it; I wouldn't expect it to definitely work, unfortunately.


text:
Specified folder/zip file does not contain a valid library
I am trying to use this library.
But when I try to import the .zip file (of the directory) downloaded from GitHub, Arduino IDE says "Specified folder/zip file does not contain a valid library"

This problem really annoying. i can't add any library except from Arduino ide it self. even the most common library not even work, it seems to be a glitched or something.

That's because it contains two libraries, and the IDE doesn't know how to handle that.
Because of this repository structure, you will need to do a manual installation.
Extract the zip file manually and copy the libraries folder into your Arduino sketchbook folder. You can find the location of your sketchbook folder in the Arduino IDE at File > Preferences > Sketchbook location.

To be more exact: Copy the content of the libraries folder into the Arduino/libraries folder in your system

@chrisl Nah - just copy the folder. If it doesn't already exist it will do after copying it. If it does exist the OS will just merge the folders together, effectively copying the contents.


text:
Does delay() pause the counting of millis()?
If I add a delay for a few seconds, and then will the value given by millis () be equal just before and after delay?
Or to put it in other words, does the internal clock of Arduino stop during delay?

No, I cannot check it (no Arduino at hand), but afaik the clock always keeps counting, so if you perform a delay of 1 second, and diff millis() just before and after, it will be (slightly over) 1,000 (ms).
Note however, that the use of delay is discouraged and it is better to check millis() to perform the next state/command instead of a delay which prevents doing other tasks meanwhile. But the (internal) timer always keeps running.
Only during some deep sleep mode it might stop, but than a delay will not work neither. And when interrupts are disbled (see remark of Chris Stratton below).

You are missing the more common exception: time also stops incrementing when interrupts are disabled.

@ChrisStratton Thanks ... I added it in my answer. Also, I didn't know this although is seems very logical.

Delay uses millis. It just waits examining millis until a certain time has passed.
Millis is driven by an interrupt. The only thing that stops it working is another interrupt (you can only have one interrupt executing at once), which is why you can't use delay in an interrupt.

(delay actually uses micros not millis (source). But both millis and micros do indeed use the timer interrupt for counting time.)

Delay, millis, micros, etc, it's all one and the same.

That's not quite right either - disabling interrupts outside of an ISR will also stop it.

Ok, Mr pedant. We all know you value your opinion.

It's not a question of opinion, but of the misleadingly false use of the word "only" for something that is not in fact the only possibility.  Normally an answer doesn't have to mention everything, but if it is going to use exclusive language, it does, otherwise readers can be mislead.  For that matter, "borrowing" the utilized timer for some other custom purpose would break it, too.

You create a lot of useless nose on here you know. The users here don't need to know such levels of detail most of the time. Tailor the answer to the audience.


text:
TLC5917 SPI Speeds
I am attempting to use 3 x TLC5917 chips to drive a row of LEDs in PWM. The LEDs share a common anode being powered through a transistor, with each LEDs cathode going to pins on the TLC5917 Chips.
There are obviously other chips specifically designed for PWM but my questions relate to the Arduino SPI Implementation.
The chips I am using are rated for 30MHz Max Speed.
The Arduino (Uno) I am using runs at 16MHz. SPI can only run at half speed which means the SPI Transfer Max Speed for this hardware is 8MHz.
With this in mind, before overhead it should take 1/8Million seconds per clock cycle, equivalent to 1/8th of a Microsecond.
This means that SPI should take 24 clock cycles to send out 24 bits. Clocking out all 3 bytes (24 bits) should take about 3 Microseconds before overhead.
Then a few more microseconds to flip the latch pin.
Instead I see it taking about 12 Microseconds to send the 24 bits and another 12 Microseconds to latch the pin low and high, 4 times what I expected. Obviously there is some overhead but 400% seems excessive.
I have looked at the Arduino SPI Library to see if there is any obvious overhead but I cant see anything that would quadruple the theoretical transfer time.
This is the sketch I used to time the data transfers
#include <SPI.h>

void SSHigh(){
  PORTB = PORTB | 10000000;
}

void SSLow(){
  PORTB = PORTB ^ 10000000;
}

void setup() {
   SPI.begin();
   Serial.begin(9600);
   pinMode(2, OUTPUT);
   digitalWrite(2, LOW);
}

void writeChips(byte red, byte green, byte blue){
    SPI.transfer(blue);
    SPI.transfer(green);
    SPI.transfer(red);

}

long start;
long end;
long delta;

void loop() {

  start = micros();
  writeChips(B11000110,B01110010,B00011110);
  end = micros();
  delta = end - start;
  Serial.println(delta);

}

There is always overhead, since the UNO doesn't have DMA. So it's waiting for the transfer the be completed, before it can send new data. This checking takes a few cycles, and doesn't always neatly align with the exact moment the transfer is done. There might also be overhead from the function call, and the return value, but the compiler might inline all the code. It might be useful to look at the compiled assembly code, to see what's going on.

Is there any way we can meaningfully reduce the overhead without having access to DMA?

You could not use the SPI library. But I'm not sure if this would help, as I wouldn't be surprised if the compiler already optimized the code. Also note that the calling micros and storing it's value takes some time, so your results are already off by a bit.

I'm also not sure how you are going to use this in driving the leds, as you'd need some additional code to do the pretty animations. Do you plan on updating the leds in a timer interrupt? What framerate are you striving for, and how many bit of PWM (how many different brightnesses)?

I have already achieved PWM using an interupt like you suggested. I was looking to gain further PWM bits, but at this point I am limited by SPI Speed (or the Arduino implementation of it).

Have you checked the default SPI clock frequency?

Crap, your right. Setting it to DIV_2 bring it down to about 8 Microseconds. The rest must be overhead.

You could try running the ISR at three times the speed, and only send out one byte at a time in the ISR. Then every third interrupt you set the latch pin. That way your main program can run while the SPI peripheral is sending out the data. Depending on the ISR overhead, you might be able to run the timer a bit faster, while still have enough time spend in your loop to do useful things. But I think it's better to start looking at another chip.

PS I've done some software PWM on shift registers in the past, using a timer to update all the shift registers. I used one of the PWM outputs of that same timer to connect to the enable pin on the shift registers. That way I could set a global brightness on all the leds, while at the same time having software-PWM on all the individual leds. I used that to change the brightness of the display depending on the ambient brightness, without sacrificing any resolution in individual PWM.


text:
How many times can I upload a program or sketch to my Arduino Uno Clone Board?
I'm about to work on my very first project using arduino (I'm just about to buy one next week), and one of our professor says that we can only upload a program or sketch in an Arduino Uno Board for approximately 8 times. He also added that if we're using a clone version, it'll can only last for 2 sketch uploads. Is this true or is he bluffing? Thank you in advance.

I've been flashing sketches to one particular Nano multiple times an hour as I build and test and I have been curious about this over the past few days myself. I knew it would be at least in the 100s of times but wasn't sure how many. Thanks for asking.

Time to question that professor's credibility. The program will be flashed into to the ATMega328P's internal flash memory, and flash will survive a few thousand write cycles. Even more for EEPROM. STMicro quotes "10K to 100K cycles" (http://www.st.com/resource/en/application_note/cd00165693.pdf)

Related: SPIFFS on the 8266 wear-levels, so if you're saving 3KB with 3MB free, you can save 1024X before the first overwrite (in theory, 512X on average w/o block overlap), which means millions of saves.

@jsotola unless Google shows you this question was already answered on SE, please don't tell users to Google (source: FAQ)

This is the ASE equivalent of fake news.

I think it’s all bluff, I’m using a clone and I’ve uploaded well over 100 sketches to mine. (Anyways, they are pretty darn cheap)

He's talking complete and utter gibberish.  To quote from the ATMega328P datasheet:

High Endurance Non-volatile Memory Segments

32KBytes of In-System Self-Programmable Flash program
  Memory
1KBytes EEPROM
2KBytes Internal SRAM
Write/Erase Cycles: 10,000 Flash/100,000 EEPROM
Data Retention: 20 years at 85°C/100 years at 25°C(1)
Optional Boot Code Section with Independent Lock Bits

In-System Programming by On-chip Boot Program
True Read-While-Write Operation

Programming Lock for Software Security

So you have at least 10,000 uses out of it before it starts to go flakey.

I would say he has at least 10K uses.

The way Flash memory works, as it ages it takes longer for a page to be erased. The 10,000 is the minimum expected number of erase operations on a page before the time taken to erase could start to exceed a pre-defined (manufacturer specified) threshold. So yes, you would expect to get more than that number (it's the minimum guaranteed), or it just take a little longer to erase pages.

In practice, I was reusing an Arduino Uno and constantly making small tweaks to the code.  Uploading again takes long enough that this is not even worth worrying about.  You are far more likely to goof up the board in some other manner if you are soldering or bending wires.  Also, when doing Arduino... the boards are so crazy cheap (particularly if you can move down to a MiniPro 5V) that the main thing you need to worry about is to just be careful when soldering the sensor/IO stuff.  The board is extremely reliable, and you can just replace cheaply if you ever have any doubts about the board.

whenever you get a talk about storage "wearing out", just keep in mind that it's generally this: 1) You have to "stressfully" blast whole areas full of zeroes and then write the ones over that.  2) Solid State storage usually has complex wear-levelling algorithms to minimize the impact of this.  3) It's a cheap Arduino.  4) The language is a subset of C++, so you can mock out a testing framework to fully test before it hits hardware; to limit unnecessary pushing of untested code into the hardware.

here is a simple example of mocking out the board so that you can just unit test it locally under Linux (compiled with GCC), rather than constantly pushing to
hardware to test.  The basic idea is to make a framework that looks like as much of the Arduino calls as you actually make from your code:  https://github.com/rfielding/octaveRounder/tree/master/test

@Rob generally you don't even bother with 4 (except for unrelated reasons) because of 3

I would suggest sending him anonymously a data sheet for the microcontroller with the pertinent parts highlighted the same section Majenko showed.  Since the clone units use the same micro and same other components why will it not last as long. I have one I have been flashing for over 6 years and no problems. I use it to test my code, it is connected to a USB and generally no other hardware. I do not think he is bluffing he took a SWAG and missed it badly. I suggest you continue to check his statements throughout the course.

I have firmware 94% flash - it took me a week to kill it. And this is a second device I killed this way. It's a Pro Micro clone. So I suggest solder a pcb with a reusablle port to change the card

it doesn't matter how much space of flash you use. it is only about the count of writes (erases really). and I doubt you did 10000 uploads, your Pro Micro has some other problem

Yes, you were right :)


text:
How can I change the speed of a stepper motor?
I am new to Arduino and am trying to implement different rotational speeds for a stepper motor. I am using a Nema 17 bipolar stepper motor, a Big Easy Driver, and an Arduino Uno.
I've been trying to modify a tutorial code such that it will run at variable speeds:
//Declare pin functions on Arduino
#define stp 2
#define dir 3
#define MS1 4
#define MS2 5
#define MS3 6
#define EN  7

//Declare variables for functions
char user_input;
int x;
int y;
int state;

#include <AccelStepper.h>
#include <Stepper.h>
Stepper stepper1 (1,stp,dir);

void setup() {

  pinMode(stp, OUTPUT);
  pinMode(dir, OUTPUT);
  pinMode(MS1, OUTPUT);
  pinMode(MS2, OUTPUT);
  pinMode(MS3, OUTPUT);
  pinMode(EN, OUTPUT);
  resetBEDPins(); //Set step, direction, microstep and enable pins to default states
  Serial.begin(9600); //Open Serial connection for debugging
  stepper1.setSpeed(1);
  Serial.println("Begin motor control");
  Serial.println();
  //Print function list for user selection
  Serial.println("Enter number for control option:");
  Serial.println("1. Turn at default microstep mode.");
  Serial.println("2. Reverse direction at default microstep mode.");
  Serial.println();

}

//Main loop
void loop() {
  while(Serial.available()){
      user_input = Serial.read(); //Read user input and trigger appropriate
function
      digitalWrite(EN, LOW); //Pull enable pin low to set FETs active and allow motor control
      if (user_input =='1')
      {
         StepForwardDefault();
      }
      else if(user_input =='2')
      {
        ReverseStepDefault();
      }
      else
      {
        Serial.println("Invalid option entered.");
      }
      resetBEDPins();
  }
}

//Reset Big Easy Driver pins to default states
void resetBEDPins()
{
  digitalWrite(stp, LOW);
  digitalWrite(dir, LOW);
  digitalWrite(MS1, LOW);
  digitalWrite(MS2, LOW);
  digitalWrite(MS3, LOW);
  digitalWrite(EN, HIGH);
}

//Default microstep mode function
void StepForwardDefault()
{
  Serial.println("Moving forward at default step mode.");
  digitalWrite(dir, LOW); //Pull direction pin low to move "forward"
  for(x= 1; x<4000; x++)  //Loop the forward stepping enough times for motion to be visible
  {
    digitalWrite(stp,HIGH); //Trigger one step forward
    delay(1);
    digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
    delay(1);
  }
  Serial.println("Enter new option");
  Serial.println();
}

//Reverse default microstep mode function
void ReverseStepDefault()
{
  Serial.println("Moving in reverse at default step mode.");
  digitalWrite(dir, HIGH); //Pull direction pin high to move in "reverse"
  for(x= 1; x<4000; x++)  //Loop the stepping enough times for motion to be visible
  {
    digitalWrite(stp,HIGH); //Trigger one step
    delay(1);
    digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
    delay(1);
  }
  Serial.println("Enter new option");
  Serial.println();
}

Adjusting the potentiometer on the Big Easy Driver will either stop the motor turning completely or run at a constant speed regardless of further adjustment.
Do you have any suggestions for debugging my code, or are there other functions I should be using in addition to/instead of those I have?

Do you understand how a stepper works?  You send it pulses and it steps for each pulse you send it.  The faster you send the pulses the faster it will run.  The slower you send the pulses the slower it will run.  You have lines in your code like this:
void StepForwardDefault()
{
  Serial.println("Moving forward at default step mode.");
  digitalWrite(dir, LOW); //Pull direction pin low to move "forward"
  for(x= 1; x<4000; x++)  //Loop the forward stepping enough times for motion to be visible
  {
    digitalWrite(stp,HIGH); //Trigger one step forward
    delay(1);
    digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
    delay(1);
  }
  Serial.println("Enter new option");
  Serial.println();
}

Can you see the part that is sending HIGH and LOW to your step pin?  See the delay that is determining how fast those pulses go out?  Can you imagine how you might change that delay so that the pulses go out faster or slower?  Here's a hint, delay works in milliseconds, but if you want to go faster than this then you'll need to work in microseconds.  Can you find the version of delay that works in microseconds in the Arduino reference?

Thank you, I found the delayMicroseconds() command which helped significantly!

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


text:
Hall effect sensor and water sensor
I'm working on a project based on the two sensor above but I keep getting this error:
'liquid_level does not name a type'
This is my sketch:
/*
YF‐ S201 Water Flow Sensor
Water Flow Sensor output processed to read in litres/hour
Adaptation Courtesy: www.hobbytronics.co.uk
*/
const int sensorPin= 0; //sensor pin connected to analog pin A0
int liquid_level;
volatile int flow_frequency; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor = 2; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;
void flow () // Interrupt function
{
   flow_frequency++;
}
void setup()
{

   pinMode(flowsensor, INPUT);
   pinMode(sensorPin, INPUT);
   digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
   Serial.begin(9600);
   attachInterrupt(0, flow, RISING); // Setup Interrupt
   sei(); // Enable interrupts
   currentTime = millis();
   cloopTime = currentTime;
}
void loop ()
{
   currentTime = millis();
   // Every second, calculate and print litres/hour
   if(currentTime >= (cloopTime + 1000))
   {
      cloopTime = currentTime; // Updates cloopTime
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency = 0; // Reset Counter
      Serial.print(l_hour, DEC); // Print litres/hour
      Serial.println(" L/hour");

   }
}

liquid_level= analogRead(sensorPin); //arduino reads the value from the liquid level sensor
Serial.println(liquid_level);//prints out liquid level sensor reading
delay(100);//delays 100ms
}

I suggest you to re-write your post in order to have more readable code. :)

The last 4 lines are outside any function. They aren’t in the loop() function. You can’t put plain statements outside of any function. Check your brackets.


text:
LGPL and Arduino in Commercial Products
I basically would like to ask this same question (in another context / more generically):
https://www.reddit.com/r/arduino/comments/25my2t/lgpl_and_arduino_in_commercial_products/
Stated differently:
What are the legal implications of LGPL licence in commercial products using Arduino boards (and or Arduino software/firmware)?
and about creating my own libraries for Arduino? (less or more permissive licenses cases for a derivative work)
and lastly, I'm also curious about this statically vs linked library conditions of LGPL (and how this would be applicable in this case)
thanks!

IANAL, but my understanding is:

Any LGPL code you modify you need to make available as source.
Using LGPL code in your project doesn't constitute modification of that code unless you actually modify that code (See above).
Any code you write that is not contained within LGPL code (see above) is yours to license as you wish. That means your libraries are your libraries. Your sketch is your sketch.

So in short, things that must be released as LGPL:

Modifications to the core code.
Modifications to other people's libraries

Things that are yours to license as you wish:

Your libraries
Your sketches

Things you should (if you're nice) provide attribution for:

Arduino API
Third party libraries

As far as hardware goes:

These files are licensed under a Creative Commons Attribution Share-Alike license, which allows for both personal and commercial derivative works, as long as they credit Arduino and release their designs under the same license. The Arduino software is also open-source.

Which means if you use their designs within your own design you should attribute it and make it open source under the CC-BY license. Otherwise, if you just use their hardware verbatim there's nothing to attribute - you haven't used their designs, but a commercial product as a component.

thanks a lot for your prompt answer! =]
"IANAL" always, but this helps a lot.
as it seems you're more used to this, would you think something like this wold be a "nice" (in that sense) and correct way to mention and clarify dependencies along a project?
https://github.com/marcosassis/gamepaduino/wiki/modules#gamepad_joystick_adapter-module

Yup, looks good to me.

This looks like a pretty good summary. I've added additional details in my answer on this other question here, and have tried to cover its various facets. I'm not sure if the question I posted my answer on is the best candidate, but it was good enough I suppose.


text:
How to get data from a device using ethernet connection with arduino
I have a question,
I know how to flush the result of a device(using PIN mode) / control a device with help of an Ethernet shield of arduino.
Now, the thing I want is I need to read a device which communicates only via Ethernet. so i have now connected the device with a router and I have the IP address of the device. I need to read the data from the device using arduino + Ethernet shield.
In fine: How to read data from a device connected to a arduino + Ethernet Sheild via lan cable and flash the result in web server or serial portal. Doesn't matter.
Please suggest a solution or help me with code.
regards,
J

The device is called "SCS EM Aware" - it sense  the electric field. The protocol can be HTTP.

http://staticcontrol.descoindustries.com/SCSCatalog/Monitors/ESD-Event-Monitors/EM-Aware-Monitor/770063/#.WnxIJKinGUk

That device communicates with their own custom server software (running in Windows) using their own custom protocol. You would need to spend a long time decoding their protocol using network sniffing software. Not a task for a beginner.


text:
Two Arduino boards - one IDE
Have been using UNO MEGA for small projects. Recently bought an UNO for other projects. Can I just go into the IDE an under Tools select UNO and a different port to do projects and rename sketches to keep track of sketches. Do not wish to use boards at the same time.


text:
Repairing Analogue Inputs on Uno?
After a long afternoon, chasing a fault on my project, I've come to find that I've damaged 2 out of the 6 Analogue Inputs. Their ADC reading doesn't display 0 when grounded, nor a known ADC value from a sensor.
I've identified the problem to the voltage divider sensors that were connected to these particular Analogue Inputs, I've since researched that topic and made some alterations.
I don't suppose by buying a replacement chip, will solve the problem of 2 bad Analogue Inputs? So I can save the hardware and reduce cost?
Thanks in advance for any help you can provide.
Stu

it is unclear what you are saying ... it seems that you are saying that replacing the atmega328 will not repair the problem ... if that is true, then why do you think so?

The analog inputs are wired directly to the ATMega MCU, so replacing it should fix the problem. Is it socketed or soldered to the board?

new 328s are only about a dollar, but is it worth your time and frustration?

If the Analog input of your Arduino Uno is damaged, then unfortunately you have damaged the pins on the ATMEAGA328P chip directly.
As per the schematic below of Arduino Uno R3, the pins A0 to A5 are connected directly on the Pins 23 to 28 of the ATMEGA328P chip.

Therefore if you say that the 2 out of 6 Analog pins have been damaged then the only way to fix that is to replace the ATMEGA328P chip with a new one.
More can be read here about the UNO's hardware design.
PS. When replacing the ATMEGA328P chip, be sure to program the new chip with the Arduino Bootloader so you can upload sketches to it, otherwise it won't work ;)
Cheers!


text:
How to replace the delay() function in my code?
I'm new to Arduino and I currently have a project that involves the control of an LED via ultrasonic sensor. Basically, if an object passes through the ultrasonic sensor, the LED will be ON for 5 seconds but adding another set of LED and ultrasonic sensor with the same function gives a problem because the other LED won't light up if the other one is ON and vice versa because of the delay whereas what I want is to be able to make them both light up and stay lit for 5 seconds after their respective ultrasonic sensors detect an object. I've tried using the "Blink without delay" example but I can't understand it nor make it work. Please help me guys and thanks for reading. Here is my current code:
int trigPin1=2;
int echoPin1=3;

int trigPin2=4;
int echoPin2=5;

int led1=10;
int led2=11;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
}

void loop() {
  long duration1, distance1;
  digitalWrite(trigPin1, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

   if (distance1 >= 500 || distance1 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print ( "Sensor1  ");
    Serial.print ( distance1);
    Serial.println("cm");
       }

  long duration2, distance2;
  digitalWrite(trigPin2, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin2, LOW);
  duration2 = pulseIn(echoPin2, HIGH);
  distance2= (duration2/2) / 29.1;

  if (distance2 >= 500 || distance2 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor2  ");
    Serial.print(distance2);
    Serial.println("cm");
       }

  if(distance1>20 || distance2>20){
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
  }
  else if(distance1<20){
    digitalWrite(led1,HIGH);
    delay(5000);
  }

  else if(distance2<20){
    digitalWrite(led2,HIGH);
    delay(5000);
  }
}

The first set of delaymicroseconds for measuring is fine.
you'll want to replace the delay(5000) when switching the leds.
  if(distance1>20 || distance2>20){
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
  }
  else if(distance1<20){
    digitalWrite(led1,HIGH);
    delay(5000);
  }

  else if(distance2<20){
    digitalWrite(led2,HIGH);
    delay(5000);
  }

you can do that by using a timestamp of when the distance was last high:
  if(distance1<20){
    digitalWrite(led1,HIGH);
    timestamp1 = millis();
  }

  if(distance2<20){
    digitalWrite(led2,HIGH);
    timestamp2 = millis();
  }

if(millis() - timestamp1 > 5000){
  digitalWrite(led1,LOW);
}

if(millis() - timestamp2 > 5000){
  digitalWrite(led2,LOW);
}

timestamp1 and timestamp2 should be globals (or static locals). This code will delay turning off the led to 5 seconds after the sensor last detected something close.

Thank you very much! I managed to do it using your hints but I believe the code after if(millis()-timestamp1>5000) should be digitalWrite(led1,LOW);

@LelouchLamperouge indeed they should be set to low there. copy paste errors...


text:
ESP8266 only executes Sketch after switching on/off CH_PD pin
I started a new project with an ESP8266-01 module. I want to use it as stand-alone circuit to send an Email at the press of a button.
The wiring is:

VCC    -  3.3v VCC
CH_PD  -  3.3v VCC
GND    -  GND
GPIO_2 -  Push down button (internal pullup)

I've the sketch (Arduino IDE), I've upload it and it essentially works. However:

If I call the sendEmail(); method inside the void setup(){}, it works like a charm.
If I add an push down button on Pin #2 (GPIO_2) it only works if I previously have removed VCC from the CH_PD pin and reattached it again shortly after.

Now, I would bet I read something regarding (or similar) this situation a couple of days back, but I am unable to find it again, now that I need it.
Is there a solution for this or am I missing something?
Any help will be greatly appreciate it!
Thanks in advance!

The GPIO0 and GPIO2 determine what mode the module starts up. GPIO0 and GPIO2 need to have pull-up resistors connected to ensure the module starts up correctly. You can also use RX pin for the button.

Thanks @AltAir for your response. I've followed step #4 of this instructable http://www.instructables.com/id/How-to-use-the-ESP8266-01-pins/   but still doesn't work as I needed it to...

You can try a bulk capacitor between VCC and GND close to the module.

Well, after literally spending hours trying to figure out what the heck is going on, I decided to test the setup with a ESP8266-12 NodeMcu, which is essentially the same but more resembling to an Arduino in that it has more in/out pins and it's better for testing.
On this platform I got a different behavior. I was able to send an Email by the push of the button but... only once. So apparently, contrary to what I believed, something was wrong with the code.
In the code there is this method, which essentially initiates the WiFi connection:
void initializeWifi(){

  WiFi.begin(WIFI, PASSWORD);

  // allow time to make connection
 while (WiFi.status() != WL_CONNECTED)  delay(5000);

  }

Somehow the delay(5000); didn't seem right as delay usually freezes the whole thing. When I commented out the line, everything worked as expected. With the NodeMcu as well as with the ESP8266-01.
However, I still have to figure out how to give time to the WiFi to connect without freezing out all together. Probably it's the time for millis();
I hope this becomes useful to somebody else in the future.


text:
ToF VL53L1X sensor integrate with arduino
I have this latest version VL53L1X time of flight laser distance sensor: http://www.st.com/en/imaging-and-photonics-solutions/vl53l1x.html
I study about this sensor, It says that sensor only Access with API(Application program Interface) how do I Integrate that API code in arduino or
how do I use Wire library to Integrate this sensor.

I can see how to communicate with the device in the datasheet, but they don't seem to tell you what to communicate. Very helpful. And software for their boards is registration-walled. So stuff that.  I'd pick an easier to use sensor.

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

There's actually a library created by Pololu that is quite straightforward to use so you don't need to worry about any of that. I think it covers all available functionality.
https://github.com/pololu/vl53l0x-arduino
I was also a bit confused by the API comment and the datasheet.
I misread the device name so the above is not relevant.
In theory I think to use the API you can just #include the C code they provide into your sketch like a normal library. You can download the API code from the manufacturer ST here.
You'll need to give your name and email but it's free.
It's in C but you can probably understand it if you're familiar with Arduino/C++.
Before compiling you would also need to implement some I2C functions for which they provide prototypes (in the vl53l1_platform.c file). However, I think there are some additional steps when using C files that you will need to take to get this to compile, unfortunately I am not familiar with this so can't help - if anyone does then they can probably write a more complete answer.
The alternative is to write your own functions that replicate the functionality that is described in the API.
I would do this by looking at the basic process flow in the API User Manual, taking each function and working through the API files to see what it does.
The main thing you're looking for is the registers that you need to write (via I2C) in order to trigger a range measurement starting, and then the registers that you need to read to find out the result.
I would note that there are multiple levels of #defines for some of the register values and there is a lot of code that deals with managing the status of the device, so this might take a while.

Good find there. That should make life easier for them. I could find nothing to detail the registers on the ST site...

I try this VL53L0X library and change few functions but this library doesn't support in latest VL53L1X.


text:
How do I set a 25 kHz PWM signal on an ESP-WROOM-32?
I want to control a single pin of an ESP-WROOM-32 to have a 25 kHz PWM signal. How do I do that in Arduino Studio? I compiled a "hello world" program for such a device successfully in Arduino Studio, now what steps do I need to take? (Other libraries? Source Code?)
FYI: I'd like to do quite the same as provided in Set PWM frequency to 25 kHz but not on an AVM micro-controller but an ESP32. There are tons of explanations for original Arduinos and ESP8266s using bit banging in various forms. But how do I do that on an ESP-WROOM-32 using no bit banging but built in PWM?
Background: I'd like to control a standard 12V PWM fan with this signal. As far as I learned I just can connect a pin with the PWM input of the fan. I just don't seem to be able to figure out how to produce such high frequent PWM signals on an ESP32 :-/ Please help!

you said that you compiled a "hello world" program for the device .... you did not say if you were successful in loading the program into the device and running it ..... did you run the "hello world" program successfully on the device?

Sure I did. If that would be a problem, I would have asked a different question.

why do you use Arduino Studio? you were really successful in installing esp32 core package into that discontinued IDE?

It is discontinued??? Yes, in the meanwhile I downloaded the Espressif Toolchain. ledc seems to originate from there, I guess. My first I've to solve the issues with the circuit before I can attempt anything more with any software. (See below.) I'll get to that next weekend.

It is very simple to set up a PWM signal at any frequency you desire, with any resolution you desire, provided you don't exceed the maximum 'bandwidth': the frequency multplied by the resolution must be less than half the clock speed of the device.
The full explanation with relation to the ESP-IDF is available here. The article explains the intricacies of all the channels and their configurations. I must confess I have not read it all, because my application was very basic.
In setup(), the code required to instantiate a PWM signal on channel chan at frequency freq, with a resolution of bit_num bits is:
double ledcSetup(uint8_t chan, double freq, uint8_t bit_num)

The code to attach the channel chan to an output pin pin is:
void ledcAttachPin(uint8_t pin, uint8_t chan)

Within loop(), or otherwise, inflict a duty cycle duty to a given channel chan using:
void ledcWrite(uint8_t chan, uint32_t duty)

I recommend perusing esp32-hal-ledc.c in the core files you installed that enabled you to program the ESP32 in Arduino Studio. You don't need to include any files to get the above functionality, but it's always good to know a bit about what goes on behind the scenes.
A few things to note, if reading through the core code is too much:

chan can only be between 0 and 15, and the function will return 0 if you try an number outside these bounds;
you can't attach the PWM output to all of the GPIO pins, as some are input only and others might have secondary functions that you need;
duty is a 32-bit type but the maximum value is determined by the resolution you used for bit_num. For example, if bit_num is 8 then the range of duty is from 0 to 255. I don't know what happens if you put higher number: the duty may stay at 100%,  or the duty may be bitmasked such that writing 256 is the same as  0, 257 is 1, etc.

Once you have mastered this, the ESP32 includes 'fading' functionality, whereby the duty cycle changes from x% to y% in z milliseconds. There are a number of tutorials on the internet for such a thing.
FINAL NOTE:
If you haven't already, take a look at Intel's PWM fan specs. It states that you need an open-collector or open-drain source provided, in your case, by the ESP32. There's a chance that the PWM pin is pulled up to 5.25V within the fan; this will hurt the ESP32 if you just wire the two together. Likewise, the Tachometer output is pulled all the way up to 12V. This will kill the ESP32 if you wire it directly to the fan.

Thank you very much for the kindness of helping me. Looks good! I found documentation about LEDC but not for the Arduino platform. One question: I've seen many people connecting the output pin directly to the PWM input of the fan. Therefor I've done likewise. In order to be very careful I used a 220 Ohm resistor in between the fan and the ESP32 as I was wondering if that really is the way of doing it. Now I'm reading about this open-drain principle you're talking about. I don't understand that right now. I'm going to read more about it before it makes sense to ask a question.

BTW: The link to the fan specs doesn't work.

Edited for working link.

@RegisMay Have a look at the Wikipedia entry for Open Collector. It's the same as an Open Drain, but for a transistor rather than a MOSFET: transistors have collectors, emitters and bases while FETs have drains, sources and gates.

I have. I just don't (yet) understand the concept. I understand the physical principles, but not (yet) how and why these are used as I'm lacking sufficient knowledge about the use cases and what problems will be solved exactly. But I'm working on that.

open drain just means it connects and disconnects GND, instead of blinking a positive voltage.

Yes, I understand the basic principle, but the things are not clear enough to me to actually understand how to build the final circuit myself including selecting necessary resistors and their values. Thank you for now, I'll do some reading and then I will get back to this project next weekend.

@RegisMay Did you get this working?

I know it is an old topic, but at the moment I'm also busy with it.
To be sure the ESP32 doesn't get to much voltage from the pwm input, you have to measure on the PWM input if the signal is not above 3V3, otherwhise you need a resistor divider or work with a transistor in between to pull the signal down. Mine is around 3V3 so I can directly connect the ESP32 to the fan, but just like you I put a serie resistor (330) in between for a bit protection. If this input is around 5.25 V and you connect it to the ESP32, it will probably not directly go broke, but this depends on the input resistance of the fan and how much current the internal protection diode can take in the ESP32.
For the tacho signal, it is very simple, just connect it with a pullup resistor (10K) to the desired voltage you want. In my case I will connect it to 3V3 because the ESP32 is working on 3V3. The fan controller pulls it down if rotating.
I use this schematic as guide,
PWM Input:

Tacho open collector output:

website:
Fan controller
Hope this helps, just as reference.

As a matter of fact I still have not completed this project yet. I needed to focus on different things till now, but I will definitively continue on this in near future. Therefore thank you very much for this response!


text:
Custom (external) reference voltage for ADC: is there a lower limit?
I'm reading an analogue oxygen sensor (SGX-4OX) with a Nano Every (ATmega4809-based). We're seeing up to about 60mV* in ambient air (it will reduce as we purge with nitrogen), and the ADC is 10-bit.  We don't need very high precision but we'd like to make the best of what we've got without amplifying the sensor output.
The documentation on analogReference doesn't mention the Nano Every yet, but setting it to "Internal" we seem to saturate at around 600mV.  From other models I'd expect it to be 1V or 1.1V.  So we're using about 10% of our dynamic range, and get ~0.2%O2 resolution.  This is probably adequate, but I always try to fill my inputs' dynamic range a bit more, and relies on the internal reference being lower than expected.
Could I, either with a voltage reference IC, a voltage divider, or a combination of the 2, set a lower reference voltage - perhaps 100mV.

* The sensor is a current source, so choosing the sense resistor allows us to adjust the sensitivity.  We don't want to go too far from the manufacturer's recommended value (linearity and lifetime, which is finite anyway), and even to get 60mV is pushing it.

There are dev boards using the same sensor.  We may end up using one but want to try and make progress with what we've got.

Be mindful of the precision of the resistors used for the voltage divider. Any tolerance variation can affect the readings.

@liaifat85 indeed.  I'll probably measure V_ref rather than calculating it, and anyway it will come out in my calibration (at ambient and 0% O2, maybe an intermediate value as we have commercial O2 monitors that are far too big for our experiment).  By using the same type of resistor the ratio should at least stay constant with temperature.  We may well end up with precision greater than our accuracy, but can still spot trends from that, which will be useful

The Nano Every is based on the ATmega4809, the datasheet for which can be found at https://www.microchip.com/en-us/product/atmega4809
According to table 32-25 on p478 of version C of the datasheet, the reference voltage should be no lower than 1.1V if an external reference is used (VREF when REFSEL = External reference).
There is an internal 0.55V reference that allows operation down to 0.55V, which the lowest setting of the internal reference. Section 18 of the datasheet talks more about the internal reference.
So to answer the title question: Yes there is a limit and it is 1.1V for an external reference.

That's a much longer datasheet than the one I found (I don't have the link here but do in work).  It explains the unexpectedly low maximum value I found setting analogReferenceto internal

For Microchip's 8-bit parts, that's about the size of datasheet I would expect to see, although some of the 16-bit or 32-bit parts have separate per-peripheral datasheets.

I agree, but I think there's a short form as well. Or I suppose something could have been going on with the in-browser PDF viewer failing to download or search everything

... it must have been the latter.  I'd seen §18 but my search for VREF wrapped round before the table loaded (I still had it open)


text:
ATtiny84 vs ATtiny85 consumption
I'm doing a comparative study between ATtiny84 and ATtiny85, and I found from the datasheet that ATtiny84 consumes less current, is that normal even if it is bigger in terms of size and number of pins? Am i wrong?

There are wide differences in power usage in AVR parts. Typically the "P" variants (for "picopower") are more optimized for low power usage, but there are also differences between different revs of the same part (for example the ATMEGA168PB uses slightly more power than the ATMEGA168PA during sleep) presumably becuase of different processes used to make the chips.
If you are looking for the lowest power possible, it will depend on how your application.  Do you spend most time running at full speed? Power down? Do you need a realtime-clock?
Don't forget about the ATXMEGA parts- they have some that have very low power when running a real-time clock from the internal "ultra-low power" oscillator.


text:
cannot resolve overloaded function... error
I started to learn Arduino and I want to get an input from user to blink LEDs. I wrote under the void loop() section input codes. After i compiled it and Arduino IDE gave me this: "Arduino:1.8.5 (Windows 10), Kart:"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"
C:\Users\Yunus Emre ERYILMAZ\Documents\Arduino\sketch_feb17a\sketch_feb19a\sketch_feb19a.ino: In function 'void loop()':

sketch_feb19a:27: error: cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

 numBlueBlink=Serial.parseInt;

             ^

sketch_feb19a:31: error: cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

 numYellowBlink=Serial.parseInt;

               ^

exit status 1
cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences."

What should i do, how can solve this problem? Thanks.
The code that i wrote:
int blueLEDPin=9;  // Declaring blue led's pin is 9.
int yellowLEDPin=10;  //Decllaring yellow led's pin is 10.
int blueOnTime=250;  // Bue led ontime
int blueOffTime=250; // Blue led offtime
int yellowOnTime=250; // Yellow led ontime
int yellowOffTime=250; // Yellow led offtime
int numBlueBlink=0;
int numYellowBlink=5;
String blueMessage="The blue LED is blinking...";
String yellowMessage="The yellow LED is blinking...";

void setup() {
  String wm1 = "Welcome to";
  String wm2 = " My Program";
  String wm3;
  wm3 = wm1+wm2;
  Serial.begin(115200);
  Serial.println (wm3);
  pinMode (blueLEDPin,OUTPUT);
  pinMode (yellowLEDPin, OUTPUT);

}

void loop() {
Serial.println ("How many times do you want the blue LED to blink? ");
while (Serial.available()==0){ }
numBlueBlink=Serial.parseInt;

Serial.println ("How many times do you want the yellow LED to blink? ");
while (Serial.available()==0){ }
numYellowBlink=Serial.parseInt;

Serial.println (blueMessage);
for (int j=1; j<=numBlueBlink; j=j+1) {
  Serial.print ("   You are on Blink #: ");
  Serial.println(j);
  digitalWrite (blueLEDPin,HIGH);  // Turn first led on
  delay (blueOnTime);  // Wait
  digitalWrite (blueLEDPin,LOW); // Turn first led off
  delay (blueOffTime); // Wait
}

Serial.println (" ");

Serial.println (yellowMessage);
for (int k=1; k<=numYellowBlink; k=k+1){
  Serial.print ("   You are on Blink #: ");
  Serial.println (k);
  digitalWrite (yellowLEDPin,HIGH); // Turn second led on
  delay (yellowOnTime); // Wait
  digitalWrite (yellowLEDPin,LOW);  // Turn second led off
  delay (yellowOffTime);  // Wait
}
Serial.println (" ");
}

The function parseInt is a function and you have to add parameters with ( and ), even when it has no parameters, thus instead of
 numBlueBlink = Serial.parseInt;

you have to write
 numBlueBlink = Serial.parseInt();

See Serial.parseInt for a reference.


text:
AtTiny85 and MMA8452Q accelerometer cannot connect using i2c
I am trying to connect the MMA8452Q with AtTiny85 using the TinyWireM library.
I made the proper hardware setup with  pull-ups on  SCL and SDA pins - tested it on Arduino
Uno and it works, however when i connect the Tiny I cannot even get the handshake.
The following code produces output 13 instead of 42 (0x2A)
HARDWARE SETUP
MMA8452 Breakout ------------AtTiny85
3.3V -------voltage regulator------ 5V
SDA -----------^^(330)^^----------- PB0 (on attiny programmer marked as 5)
SCL -----------^^(330)^^----------- PB3 (on attiny programmer marked as 2)
GND --------------------------------- GND
(I also tried different pins with no luck)
CODE
//---bluetooth console communication stuff---//
#include <SoftwareSerial.h>
#define rxPin 1 //not important - needed for initialization
#define txPin A2
SoftwareSerial blueTooth(rxPin, txPin);
//      ---     //

#include "TinyWireM.h" // Used for I2C

// The SparkFun breakout board defaults to 1, set to 0 if SA0 jumper on the bottom of the board is set
#define MMA8452_ADDRESS 0x1D  // 0x1D if SA0 is high, 0x1C if low

#define WHO_AM_I   0x0D

void setup() {

  blueTooth.begin(9600);
  delay(1000);
  TinyWireM.begin(); //Join the bus as a master
  delay(1000);
 }

void loop() {
   byte c =0;
   c = readRegister(WHO_AM_I);
   blueTooth.println(c);
   delay(1000);
  }

 // Read a single byte from addressToRead and return it as a byte
byte readRegister(byte addressToRead) {
  TinyWireM.beginTransmission(MMA8452_ADDRESS);
  TinyWireM.send(addressToRead);
  TinyWireM.endTransmission(); //endTransmission but keep the connection active

  TinyWireM.requestFrom(MMA8452_ADDRESS, 1); //Ask for 1 byte, once done, bus is released by default

  while(!TinyWireM.available()) ; //Wait for the data to come back
  return TinyWireM.receive(); //Return this one byte
}

Would anyone know how to get it right?

I2C pullup resistors are 4.7 kohm to Vcc (at 5V). SCL is PB2 (chip pin 7) and SDA is PB0 (chip pin 5).

changed the resistors. still getting the same output

On an ATtiny85 pin 5 (PB0) is SDA and pin 7 (PB2) is SCL for the I2C interface.  You're using the wrong pin for SCL.
Additionally, your pull-up resistors are too strong.  Somewhere between 4.7K Ohm and 10K Ohm are recommended for pull-up's on the SDA and SCL lines.

using the TinyWireM library.

Make sure the i2c actually works. Arduino libraries are generally of poor quality and just because someone wrote it doesn't mean it actually works. Get a logic analyzer or scope on the bus and see what's going on.
Once you can confirm that, get a datasheet for the 8452 and see how it works and code to it.

i tried doing  what you suggested and also tried pluging i2c  attiny as slave to uno as master. did not work either.
Generally what i get on oscillator is some mess different than what i get when plugging uno.  On uno i get nice square waves on clock and digital signals on sda. i ran some tests and used the pb0 and pb2 and pb3 pins on attiny for serial communication so the pins work (i guess?). Could it still be the chip problem? It seems that  many folks succeed with using TinyWireM as i2c library... i dont know where to go from here

i scanned for i2c devices and it detects an i2c device at each address it scans... so weird


text:
How to calculate the time it takes before the water valve stops dispensing water in an Automatic Water level controller?
I am making a project about an automated water level controller using ultrasonic, potentiometer and Arduino board. I need a mathematical calculation on how it works. So here's a simple scenario:
I have an open top cylindrical container with a radius of 7cm. The ultrasonic sensed that the half height of the container, which is 15cm, is filled with water. At the bottom part of it, a tube with a radius of 1cm is connected alongside with the water valve. How can I calculate the time needed for the water valve to stop dispensing water if I set the potentiometer to keep the level of water at 9cm only? Can you give me a mathematical formula??
I really need a help, please. Any answer will be highly appreciated. Thank you in advance.

Wouldn't it be easier to measure it?  Configure the system to stop at the desired point, run it, see where the water level actually ends up.  Build in a correction based on the difference, and try it again.   Modeling this is potentially academically interesting but requires information you have not presented about valve actuation time.  Most fill systems don't try to maintain an exact level, but have a deadband to avoid premature wearout of the valve.

One could use a peristaltic pump and skip the complications of using a sensor.  Or, using the keep it simple rule, I would use a float switch.  Or, simpler yet, a mechanical float as the one in your toilet. If you do use an electronic sensor be sure to add a bit of hysteresis so that your solenoid/valve will not prematurely fail.

This looks like a high school physics question wrappen in an Arduino question. But why would you need to calculate the time, if you can just continually measure the distance and turn of the valve if the distance is 6cm?

The concept you have is more complicated than you can imagine. But to answer your question (which is not so arduino-based), the mathematical formula you looking for is Torricelli's Law.
My suggestion for you is design a system which use a feedback concept instead

Sounds like it's the valve's time to close (t_vc) + half (statistically) the measurement interval (t_interval) + the software reaction time (t_sw). So
Add whatever measurement interval the software uses, if any, and the valve's time to close, once activated, and the software's time to react (from decision to actually making the valve-close signal) and you should have it. So:
T = t_sw + t_vc + 0.5*t_interval
Any software reaction time should be negilgible for practical purposes, so we're down to:
T = t_vc + 0.5*t_interval
If the software doesn't include sleeps or delays but loops continuously, measuring and deciding, then the half-interval reduces to negligibility leaving just the valve closure time:
T = t_vc


text:
RTClib now() within while loop does not update
I ran into this while trying to make a battery monitor and wondered where I went wrong. Using RTClib available in the Arduino IDE or from adafruit github, I ran into problems when trying to call now within a while loop inside of loop.  Here is a simple example:
#include "RTClib.h"

#define ledPIN 13

RTC_PCF8523 rtc;

void setup() {
  // put your setup code here, to run once:
  pinMode(ledPIN, OUTPUT);
  digitalWrite(ledPIN, LOW);
  Serial.begin(9600);
  while(!Serial) {/* wait for Serial */}
  rtc.begin();
  rtc.start();
  digitalWrite(ledPIN, HIGH);
 }

void loop() {
  // put your main code here, to run repeatedly:
  char fmt[] = "YYYY/MM/DD-hh:mm:ss\n";
  while (millis() < 60000){
    Serial.println((rtc.now()).toString(fmt));
    delay(5000);
  }
  Serial.println("Finished");
  digitalWrite(ledPIN, LOW);
  while(1) { /* do nothing forever */ }
}

The output of this little test will be the same time repeated every 5ish seconds.  If it matters I am using a Feather M0 with the FeatherLogger that has an RTC on it.  Changing this loop function to this:
void loop() {
  // put your main code here, to run repeatedly:
  char fmt[] = "YYYY/MM/DD-hh:mm:ss\n";
  if (millis() < 60000){
    Serial.println((rtc.now()).toString(fmt));
    delay(5000);
  } else {
    Serial.println("Finished");
    digitalWrite(ledPIN, LOW);
    while(1) { /* do nothing forever */ }
  }
}

shows that now does in fact update the time every 5ish seconds.  I looked at the code for now and it appears to do very basic i2c commands to get the time and report it back.  The only thing I can think of is that the compiler created a (not so) temporary DateTime object for me within the while loop and the RTC library does not provide a convenient constructor or operator to overwrite the existing object.
I tested my theory with this
void loop() {
  // put your main code here, to run repeatedly:
  char fmt[] = "YYYY/MM/DD-hh:mm:ss\n";
  while (millis() < 60000){
    DateTime t1 = rtc.now();
    Serial.println(t1.toString(fmt));
    delay(5000);
  }
  Serial.println("Finished");
  digitalWrite(ledPIN, LOW);
  while(1) { /* do nothing forever */ }
}

But again, the time did not change so clearly I don't understand what's happening here.  Why doesn't the rtc now function work as intended within a while loop inside the loop function?

if (! rtc.begin()) {     Serial.println("Couldn't find RTC");     Serial.flush();     abort();   } can you add this part to your code to check whether it is giving any error or not

You have also not added the date and time in your code. Before going forward can you check whether the example code is working or not

Try changing your loop to while (millis() < 60000){  volatile DateTime time = rtc.now(); Serial.println(time.toString(fmt)); delay(5000);   } If this works, your theory about a wrong compiler optimization is correct.

See the documentation of DateTime::toString():

The buffer parameter should be initialized by the caller with a
string specifying the requested format. This format string may contain
any of the following specifiers: [...] The specifiers within buffer
will be overwritten with the appropriate values from the DateTime.
Any characters not belonging to one of the above specifiers are left
as-is.

The important thing to realize is that the buffer parameter is used
both as input (for the format description) and as output (for the
formatted date and time). You initialize it with a format description
("YYYY/MM/DD-hh:mm:ss\n"). Then, after the first call to toString(),
the same buffer contains the formatted date and time. It does not
contain the format description anymore. On the second call to
toString(), as per the rule “Any characters not belonging to one of
the above specifiers are left as-is”, the buffer is not modified.
Solution: Put the buffer initialization within the same while loop
as the call to toString().

As usual, reading the documentation would have saved the OP a lot of time... ;-) +1


text:
Arduino Starter Kit - firmly wiring longer parts
I am getting started with project 01 on the Arduino starter kit. I'm facing an issue when wiring parts with long ends e.g. led & resistor. To make the simple circuit with led, resistor & switch work, I have to hold down the resistor & led, and then press the button. The parts don't connect well to the wires underneath the breadboard.
I want ask if someone could suggest how to better deal with such parts. On searching, I found people cut their parts short, but are there other approaches ?
Thanks.

In the good old days, 1/4 watt resistors had nice firm leads that may have been actually steel with plating (you could pick them up with a magnet!) and worked pretty well on halfway decent breadboards.  It seems today though that it's hard to buy resistors with anything but very thin soft leads, and meanwhile there are a lot of rather bad breadboards on the market.  Mainstream suppliers increasingly don't even carry "everyday" through hole resistors.

You could try folding the ends over (effectively doubling the width) if the wires are thin.

Cutting them short is proven solution, but there is sometimes still problem with legs too thin to fit good.
Other, even more reliable, is to solder them to pinheader https://commons.wikimedia.org/wiki/File:16_Pin_Header.jpg (just break away 2 or 3 pins depending on how many legs you need). Works even for SMD resistors and diodes https://divnoblog.files.wordpress.com/2015/10/005-odpor_1.jpg
Also you can use small piece of universal stripboard https://en.wikipedia.org/wiki/Stripboard / perfboard https://en.wikipedia.org/wiki/Perfboard, to solder anything on that and solder the pinheader under it. Works perfectly for switches etc.
(of course you can buy "modules" from any suplier, where is the part, maybe accompanied by one or two resistors or such, but the price is higher, than is you do it manually at home and there is not such wide range, as is in normal analog/digital parts, which you can solder to fit your needs)
The problem with https://en.wikipedia.org/wiki/Breadboard is, that usually the holes are good just for the pinheader-sized legs (a lot of IC have the right dimensions too), while nearly any pasive/simple parts are much thinner and do not fit reliably. But for some fast playing with and non-critical application it is usually usable enough.


text:
How can I connect H-Bridge motor driver (using four 2n222 transistors) to Arduino?
First of all I'm a noob.
I was trying to do the H-Bridge using 2N2222 controlled by an Arduino Uno.
This is the design--->

I joined A1 and A2 to form a common terminal (say A), similarly, I joined B1 and B2 to form B. Now I connected A and B to 2 pins of the arduino (say pin 9 & pin 10 respectively).
So, theoretically, when I should digitalWrite pin 9 HIGH, then current should flow via A1 and A2, i.e. left to right in the motor AND when I should digitalWrite pin 10 HIGH, then current should flow via B1 and B2, i.e. right to left in the motor.
Hence, I can control the direction of rotation of the motor.
BUT.....it wasn't working...!!!!
I need help...!!!
After much thinking I had a hunch...."Perhaps, I am not giving GROUND to the transistors". I thought about it, but was unable to figure out the way of doing it.
So, again, please help me...!!!

If Ground is the issue, connect it to the -ve of the battery. You can't just run one wire to the bridge, voltages are meaningless without a reference (commonly called Ground).

This circuit will not take advantage of your 9v supply when you only have 5v logic to drive the upper transistors, and designing a circuit that could is not really a question about Arduino.  If your goal is just to control something, look at an FET bridge like a TB6612FNG.  If you want to get into the details of designing a bridge from scratch, you are going to need to spend a lot more time understanding transistor circuits.

Make sure you have connect Arduino ground with -VE of battery. 2. If it still does not work, try to drive A1 A2 B1 B2 separately first.

Transistor needs like 0.7V from base to emitor to open. Arduino have 5V pins. So the voltage on motor can be max 4.3V to be able open A1. But if you open that, than you connect it to 9V of batery, the motor gets most voltage so there would be more then 8V on the side of motor and A1 closes, as B-E voltage is like 5-8=-3V enough to close it. You can drive the motor from 5V batery (and loss a lot of power), or you need more complicated schema of the H-bridge. I suggest reading http://scolton.blogspot.cz/p/motor-controllers.html  http://web.mit.edu/first/kart/controller_rev1.pdf to get some ideas

I am not an electronics guru yet either so others might give you a better answer, but this is one circuit I have messed with a lot because I keep trying to build robots, so I will take a shot at an answer.
Normally you need both NPN and PNP transistors for an H-bridge:

The 2N222 is NPN so you'd want to pair two of them with two equivalent PNPs such as the 2N2907.
I've see diagrams that have all NPNs but I have never gotten a circuit to work that way. There is a distinction about where the load goes, before or after the transistor, that makes you chose to use an NPN or a PNP in order to make it all flow properly.

This circuit won't work for the question's power supply, either, as the supply voltage is more than a diode drop above the logic voltage.  The maximum voltage at "Forward Input" is 5v, but the emitter of your PNP transistors is at 9v, so they will always be "on" with no way for the Arduino to turn them off.  Designing a working H-bridge is not trivial.


text:
ESP32 doesnt save every string to SD Card
My code initializes, the header (the ID; Value string) for the .csv file gets saved, but the dataString which is the most important part doesnt save to the .csv file.
I get an arraypointer to the start of the array. I dont have much experience with pointers but i dont get any errors.
The best solution would be if i could put everything into the "write matrix to SD"-function. Anyone has an idea? I am just dumbfounded because everything works perfectly without the arraypointer and i dont know what to try.
My setup()
  Serial.begin(115200);

  p_EKG_state_1 = &EKG_state_1;

  pinMode(CS_Pin, OUTPUT);
  if(!SD.begin(CS_Pin))
    {
      Serial.println("Card failed or not present");
    }

  EKG_data_transmision.matrixData = SD.open("/data.csv", FILE_APPEND);  //erstelle data.csv datei

  if(EKG_data_transmision.matrixData)
    {
    String header = "ID; Value;";
    EKG_data_transmision.matrixData.println(header);
    EKG_data_transmision.matrixData.close();
    Serial.println(header);
    Serial.println("card init sucess");
    }
  else
    {
    Serial.println("Couldnt open vector data file");
    }

  //Serial.println(ESP.getFreeHeap());
  pinMode(LED_BUILTIN, OUTPUT); // TEST OUTPUT LED PIN

  pinMode(btn_modus.PIN, INPUT_PULLUP); // MODUSAUSWAHL TASTER
  attachInterrupt(btn_modus.PIN, isr, FALLING); // MODUS TASTER hört auf fallende Flanke und führt dann Funktion isr aus
  WiFi.begin(ssid, password); // Verbinde mit WLAN

  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); // initialisiere Zeit variablen
  EKG_state_1.set_state(1);

}

My function that writes the matrix/arraypointer to the SD
bool  EKG_data_transmision::write_matrix_to_SD(unsigned short *array_pointer) // Übertrage , unsigned short id
{

   if(!SD.begin(CS_Pin))
  {
    Serial.println("Card failed or not present");
    return 1;
  }
  matrixData = SD.open("/data.csv", FILE_APPEND);  //erstelle data.csv datei

  if(matrixData)
  {
    //look if data.csv exists

    while(matrix_coloum < 3071)
    {
      if(matrix_coloum == 1024 || matrix_coloum == 2048)
      {
          header = "ID; Value;\n";
          matrixData.println(header);
      }
      dataString = String(matrix_coloum) + ";" + String(*array_pointer) + "\n";
      matrixData.println(dataString);
      Serial.println("This is datastring:");
      Serial.println(dataString);
      array_pointer++;
      matrix_coloum++;
    }

  }

  else{
    Serial.println("Error writing to file !");
}
  matrixData.close(); // close the file

  return 0;
}

My class with all the inits

class EKG_data_transmision
{
  private:

    String dataString;
    String header;
    unsigned short matrix_coloum = 0;

  public:
    EKG_data_transmision();

    File matrixData;

    //Definiere Funktionen:
    bool write_matrix_to_SD(unsigned short *array_pointer);
    bool delete_matrix_from_SD(unsigned int record);

How is write_matrix_to_SD() called? From the string String(matrix_coloum) + ";" + String(*array_pointer) + "\n"; you do see the matrix column number but not the value? Is it an empty value or some random invalid value?

the write matrix to SD is called from the loop. Like this EKG_data_transmision.write_matrix_to_SD(EKG_recording.array_pointer);
If i serial.print the strings i can see them. They just dont get saved to the .csv file like the header with "ID; Value"


text:
How to build an µC controlled power regulator?
The idea: Use an Arduino-like µC to control a set of CPU fans by control the voltage the CPU fans receive. My question: How can I do this in an easy way?
Yes, I know, there is PWM but this is not very suitable for this purpose: I did some tests with it but it turns out that the characteristics of PWM fans don't suite my purpose: PWM fans are designed to be controlled between not audible and full speed, not between nearly not rotating and full speed. Even very special fans with a wide range of PWM speed control don't work as well as powering a regular 12V fan with just 5 or 6V.
Which brings me to an alternative idea: It should be possible to send an I2C or SPI signal to some kind of IC that then provides a voltage as required.
Alternatively to that there seem to be PWM controlled voltage regulators available. But that doesn't seem to be a very elegant solution, isn't it?
Or is there an even better way of controlling the voltage output to the fans I'm not aware of?
I'm aiming for a solution that works well and can be build with little effort. Unfortunately I don't know how to do that: I can't find any breakouts I could use right away for that purpose. Probably there are some and I just have not been able to find them? Any help is appreciated!

It's actually very simple, and it indeed does involve using PWM.
PWM is just a signal being on for a percentage of a predefined period.  That percentage is also, when the PWM signal is averaged out, equivalent to a percentage of the peak voltage of the PWM signal.
So if you take a PWM signal and use it to switch a higher power source (say, through a P-channel MOSFET that's being itself switched by an N-channel MOSFET), then add smoothing to that switched output, and you have a variable voltage.
If you want to know what that voltage is you can add a resistor network to the output (assuming it's higher than the voltage the MCU can handle) and read the divided voltage using an ADC.  You can then use that as a feedback loop to adjust the PWM duty cycle to get your desired voltage.

simulate this circuit – Schematic created using CircuitLab
That is precisely* how switch-mode power supplies work. Use PWM to switch a FET that controls an incoming voltage, then smooth it out, adding a feedback network for control.

*Apart from the PWM bit: they often use other methods of switching the signal to get better efficiency at different loads, such as PFM.


text:
What is the maximum size of Static Json Document in Arduino JSON?
I'm trying to do serial communication between Arduino mega and a esp8266, and having issues with determining the size of the JSON document. I have read that the receiver buffer size should be greater than the sender buffer, but what's the maximum buffer size we can use for the JSON document?

The Arduino Mega has 8 KB of RAM, all of which you could use in a StaticJsonDocument.
The ESP8266 has 80 KB of RAM, but the core limits the stack to 4 KB. If you need something bigger, switch to a DynamicJsonDocument.
In both cases, you need to leave a lot of room for other variables and libraries. As an example, I wouldn't create a StaticJsonDocument bigger than 6 KB on the Mega, and 2 KB on the ESP8266.
By the way, I heard this library is very well documented, did you have a look?
Do you know you can use the ArduinoJson Assistant to help you decide the capacity of the JsonDocument?

so you heard? :-)

Thanks and I checked the links earlier, but I have an issue, is the size we give when creating the static json document is in bytes? ex StaticJsonDocument<450> doc; is it 450 bytes?

Yes, it's the capacity of the memory pool, in bytes.


text:
Stacks on arrays on arrays
I am trying to find a "vanilla" way of writing several arrays into one. I spent a lot of time searching for how to do this but everything that comes up is either a tutorial that doesn't cover concatenation or someones question that ended up being an unrelated syntax problem.
I put several strands of WS2812B LEDs wired in series so the Arduino sees them as one continuous strand. I have been able to run some very cool patterns as one strand using the Pololu library but I would like to program the strands separately. The number of lights I have is very resource intensive and I like to keep things simple so I'm looking for advice on the best way to go about combining arrays without importing more libraries.
Because the patterns I have used so far write to an array and the output is an array, my first thought was that I could write one pattern to an array made up of sections 1, 4, and 5, and another pattern that would be mapped to sections 2, 3, and 6 and then concatenate it all together in order. However, adding arrays seems to be somewhat complicated without worrying about this or that persons favorite library or looping through one value at a time and I am trying to work on my C skills. Is there a simple way to concatenate arrays or a better way for me to think about this? Any best practice or organizational advice is welcome. I want to write clean code.
Bonus Round: I use several different languages at work and I cant figure out why I have it in my head that this would work...
array1 = [a, b, c]
array2 = [x, y]
array3 = array1 + array2

// array3 = [a, b, c, x, y]

Any idea if that is possible or what language I am thinking of?

A 2 dimensional array is technically saved serialized as a long 1 dimensional array. It should be possible to read/write each subarray and also the whole array with 1 dimension using pointer. Maybe I have time to write a whole answer to this later this day.

C(++) does not natively let you "add" arrays like that.  Your code looks like maybe Python.
There are several ways to do what you want to do.  You could make your code which writes the pattern to the array accept an offset - so rather than always starting at position 0, you could tell it where to start.
You could write a function to "concatenate" arrays, or use one someone else has written, if you can find one.  It's pretty trivial to do.
However the method I'd use in your situation, probably just a matter of preference really, is this:
Let's say (for example) you have 6 strips of 10 LEDs each.  You need 60 elements to represent them all.  (I'm assuming each element is an int; I can't remember if it is.)  Create one big array for the whole lot:
int allElements[60];

You might think of the variable allElements as an array, but it is really an int* (a pointer to an int), with that memory address happening to have 59 other memory addresses after it reserved.  C knows that when you say allElements[7] it needs to looks 7 ints on from the address pointed to by allElements.  What this means is that you can create new variables which point to parts of that array, and use those variables as if they were their own arrays.  For example:
int *firstStrip = &(allElements[0]);
int *secondStrip = &(allElements[10]);
int *thirdStrip = &(allElements[20]);
/* ... and so on */

(There is a more idiomatic way to write this which is exactly equivalent, but I think the above is more explicit if you're new to it.)
As an extra improvement you might now notice that you have a load of similarly-named variables with similar functions -- and you might want to put them into an array.
int* strips[] = { &(allElements[0]), &(allElements[1]), &(allElements[2]) /* and so on */};

Now you can use strips[3] to give you the fourth strip.
There are several other ways too, but I think this will get you going.