text:
Interrupts: use of the "volatile" keyword with a structure pointer for button debounce
I've written a small sketch targeted at the Arduino Uno (ATmega328P) to debounce a mechanical pushbutton using the summing/integration technique:
#include <IntegratingDebounce.h>
#define PIN_BTN 4

IntegratingDebounce *btn;

ISR (TIMER2_OVF_vect) {
  ideb_poll(btn);
} // end timer2 overflow ISR

void set_debounce_timer() {
  TCNT2 = 0;                                  // Clear timer
  TCCR2A &= ~( bit( WGM21 ) | bit( WGM20 ) ); // Set waveform generation mode to normal
  TCCR2B &= ~bit( WGM22 );
  TIMSK2 |= bit( TOIE2 );                     // Enable interrupt on overflow
  TCCR2B |= 7;                                // Start clocking the timer
} // set_debounce_timer()

void setup() {
  Serial.begin(9600);
  pinMode(PIN_BTN, INPUT_PULLUP);

  ideb_init(&btn, PIN_BTN, 4);
  set_debounce_timer();
} // setup()

void loop() {
  while (ideb_read(btn) == HIGH);  // wait until the button pin goes low
  Serial.println("Pressed!");
  delay(100);
} // loop()

An IntegratingDebounce structure stores the data needed to perform the debounce. I keep a pointer to the structure, btn, in the global memory space.
The timer2 overflow ISR periodically polls the state of the button pin, updates the internal integrator, and sets the (also internal) debounced output accordingly. The ideb_read() function reads the debounced output out of the structure.
I'm having trouble determining where the volatile keyword should be placed in the declaration for the btn structure pointer. First I declared it as:
volatile IntegratingDebounce *btn;
I thought this would make all of the fields in the structure pointed to by btn volatile, but button presses are not detected in loop(). Declaring btn as a volatile pointer rather than a pointer to a volatile structure generates the expected output:
IntegratingDebounce *volatile btn;
This seems backwards. Why does this work?
IntegratingDebounce.h
#ifndef __INTEGRATING_DEBOUNCE_H__
#define __INTEGRATING_DEBOUNCE_H__

#include <Arduino.h>
#include <stdint.h>

extern "C" {

typedef struct IntegratingDebounce_S IntegratingDebounce;
typedef uint8_t ideb_size_t;

// Create a debounce structure and initialize.
void ideb_init(
  IntegratingDebounce **ideb,
  uint8_t pin,                  // I/O pin to debounce
  ideb_size_t clamp             // debounce clamp; the maximum value the
                                //   internal sum is able to take on
);

// Poll the state of the pin, integrate, and update the debounced output.
void ideb_poll(IntegratingDebounce *ideb);

// Read the debounced state of the pin.
uint8_t ideb_read(IntegratingDebounce *ideb);

// Reset the internal integrator to either the LOW or HIGH state.
void ideb_reset(IntegratingDebounce *ideb, uint8_t state);

} // extern C

#endif

IntegratingDebounce.c
#include "IntegratingDebounce.h"

struct IntegratingDebounce_S {
  uint8_t pin;              // pin to debounce
  uint8_t output;           // debounced output
  ideb_size_t clamp;        // debounce clamp
  ideb_size_t integrator;   // clamped running sum
};

void ideb_init(IntegratingDebounce **ideb, uint8_t pin, uint8_t clamp) {
  *ideb = (IntegratingDebounce *)malloc(sizeof(IntegratingDebounce));
  (*ideb)->pin = pin;
  (*ideb)->clamp = clamp;
  (*ideb)->output = 0;
  (*ideb)->integrator = 0;
} // ideb_init()

void ideb_poll(IntegratingDebounce *ideb) {
  // update the integrator based on the present state of the pin:
  // - if LOW, decrement the integerator; if HIGH, increment the integrator
  // - constrain the integrator to values between 0 and 'clamp'
  if (digitalRead(ideb->pin) == LOW) {
    if (ideb->integrator > 0) ideb->integrator--;
  } // if
  else {
    if (ideb->integrator < ideb->clamp) ideb->integrator++;
  } // else

  // update the output based on the value of the integrator; the output
  // will not change until the integrator reaches a limiting value
  if (ideb->integrator == 0 && ideb->output == HIGH) {
    ideb->output = LOW;
  } // if
  else if (ideb->integrator == ideb->clamp && ideb->output == LOW) {
    ideb->output = HIGH;
  } // else if
} // ideb_poll()

uint8_t ideb_read(IntegratingDebounce *ideb) {
  return ideb->output;
} // ideb_read()

void ideb_reset(IntegratingDebounce *ideb, uint8_t state) {
  if (state == LOW) {
    ideb->integrator = 0;
    ideb->output = LOW;
  } // if
  else {
    ideb->integrator = ideb->clamp;
    ideb->output = HIGH;
  } // else
} // ideb_reset()

I think, that the problem is in ideb_read, which expects "a pointer to (non-volatile) structure" and so it does not care about re-reading ideb->output if it can it optimize out somehow (say putting it in free register).
IMHO the ideb_read should have parameter declared as (volatile IntegratingDebounce *ideb) (to know, that structure pointed by ideb is volatile) or use global variable btn (which is pointer to volatile structure) instead of pointer parametr to non-volatitle structure.

And why the second works would be because it forces re-read the parameter of ideb_read and so it cannot be saved out somewhere and the function is indirectly forced to expect changed pointer, so it have to use its 'new value' and read the structure (as it is simpler, than ensure, that the ideb have the same value as it had last call and so the whole structure there (which is declared as non-volatile in header of ideb_read) could be cached)

Another wording of the above:
Declaring volatile IntegratingDebounce *btn; the main program in loop simply takes the value of btn (which is non-volatile pointer to volatile structure) and copy that (non-volatile) value to ideb parametr od ideb_read, which is non-volatile pointer to non-volatile structure. ideb_read use it that way and compiler somehow was able to cache all of that and so not read ideb->output again, as it knows, that it is part of non-volatile struct. (So it does not work)
Declaring IntegratingDebounce *volatile btn; you made the btn volatile, so it gets read each time ideb_read is called and the 'new actual value' is passed to (non-volatile) ideb parametr (which is this way given 'new value' and so cannot be cached between calls) and it results to reading (non-volatile) date from "new" place pointed by ideb. So it works (by mistake).
Right solution would be declare correctly volatile IntegratingDebounce *btn; in main program AND declare correctly uint8_t ideb_read(volatile IntegratingDebounce *ideb) so the ideb_read function is forced read value pointed by ideb every time again (which is the right thing to do)
And it should be used for all other ideb_** functions too.
And I think, that it would be simpler to declare some typedef for this volatile structure (something like typedef struct { ... } volatile ideb_t; ) and use the new type everywhere.

That is making sense, and your solution works! Thanks. So passing a volatile IntegratingDebounce * as an argument to a function that expects an IntegratingDebounce * is an implicit type conversion to non-volatile, allowing the structure to be cached?

Yes, "pointer as pointer, it just points somewhere to memory" :) After all you can convert any pointer to void* and then convert it to any (other) pointer.

Also keep in mind, that the IntegratedDebounce.* can be (and usually is) compiled (long) before the main.* and (as any library after all) does not know much, what would use/call it and how. (and the ideb_read is so small and easy, that compiler probably would it convert it into inline where possible, as the function body is lot smaller (in asm), than the preffix and suffix of the function and comparable with length of calling sequence.

Getting pointer declarations right can be anything but obvious, especially where const and volatile are concerned (which are syntactically equivalent). Your problem stemmed from the confusion between "volatile pointer to struct" and "pointer to volatile struct". See the difference? In words it's fairly clear. In C, it has you - and me - running to your C manual's Table of Precedence.
I keep a copy of Dan Saks' article, "Const T vs. T Const" on hand for just exactly this case - it seems I always need to look it up.
And while you're there, check out some of his other articles as well. I learn something every time I read one.

The article is very helpful, particularly in the suggestion to place const and volatile to the right of other type specifiers to improve the right-to-left reading. Thanks!

Also interesting and simple insight is here - http://unixwiz.net/techtips/reading-cdecl.html


text:
DS3231 OSF register changing without lost date
Dears, I have an logger prototype with arduino and ds3231 breadboard. My code check periodically OSF register to check if oscillator is/was stopped, as informed in datasheet. I turn on my logger, setting up date/hour, turn of and after some time, turn it on again to check if it's ok.
After that, the logger stay tuned off for a month. When I turned it on after this time, I note that OSF bit was changed, indicating that oscillator was stopped, but the data/time wasn't lost. I don't found possible process that can change the OSF bit in datasheet and Maxim recommendation. Maybe a negative voltage on VCC that force battery go to bellow threshold can changes the OSF bit (Maxim recommendation and this post).
Then, I test my logger connecting and disconnecting voltage (VCC) and checking the OSF bit, to simulate this possible begative voltage and not have problem with it.
My question is:

why the OSF bit changed, indicating lost of battery and consequently lost of date/time, and not lost date/time in my logger;
what could have happened with my turned off logger to change OSF bit and not lost date;

I'm using Adafruid RTCLib. Follow the simple code to check OSF bit:
#include <Wire.h>
#include <RTClib.h>

RTC_DS3231 rtc;

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

void loop()
{
  if(rtc.lostPower())
  {
     Serial.println("Date lost");
  }

  delay(1000);
}

Thank you!

excuse me @jsotola. I edited post to make myself clear. My question is why/how OSF bit changed, indicating lost of battery and data, and not lost data in my case (battery is ok)

How full is the battery? Is it a rechargable or not? The product page is a bit contradicting. As the schematic shows a crude charging circuit, while the photo and schematic show the use of a non-rechargeable CR2032. Is the resistor removed like shown in the second product picture?

The battery is a CR2032 non rechargeable and new (3.11V). I didn't remove resistor for this test, but I will. The question is that the OSF bit, for lost battery, change while the system was turned off for a month, only with CR2032 for keeping date/time. I'm using a Chinese breadboard as link in post.

the breadboard have a diode in positive of battery, then negative voltage will not affect battery.

source: Stack Exchange

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

sort: votes


text:
Arduino Mega: Interrupt not working? Use any pin for interrupt?
I am using an arduino mega. I'm trying to use interrupts in one of my programs.
I have 8 pins that I will need to make separate interrupts for.
The pins are 40 - 47. These pins are attached to limit switches, so when the limit switch is pressed or not it'll indicate that via digitalRead().
#define switch_1 43     // Pin 43 is connected to Switch 1 (1: X+)
#define switch_2 42     // Pin 42 is connected to Switch 2 (1: X-)
#define switch_3 41     // Pin 41 is connected to Switch 3 (1: Y+)
#define switch_4 40     // Pin 40 is connected to Switch 4 (1: Y-)
#define switch_5 46     // Pin 46 is connected to Switch 5 (2: FR)
#define switch_6 47     // Pin 47 is connected to Switch 6 (2: BL)
#define switch_7 45     // Pin 45 is connected to Switch 7 (2: BR)
#define switch_8 44     // Pin 44 is connected to Switch 8 (2: FL)
int interruptVar = 5;

In my set up function I have:
attachInterrupt(digitalPinToInterrupt(switch_6), tightenStrings1, CHANGE);

Then I have:
void tightenStrings1()
{
  interruptVar = 9;

}

When I change the status of the limit switches, by pressing them or unpressing them, this function never activates. The variable interruptVar is still 5.
What am I doing wrong?
Also, Serial isn't the problem in this case. I understand now not to use it though, but still doesn't solve the problem. Additionally I tried instead of CHANGE using RISING or FALLING and still no changes.
I have a feeling it's because the pins I'm using aren't technically interrupt pins...is there a way to make them usable as interrupt pins? I'm not allowed to change the pins being used, and using an interrupt is the best solution for the coding portion I'm working on.

Never use Serial in an interrupt.

I changed it as you were commenting lol. But Serial isn't the issue..do you have any other suggestions why this doesn't work?

your programming style is inconsistent .... you declare #define switch_6 47 and then you use attachInterrupt(digitalPinToInterrupt(47), tightenStrings1, CHANGE); ...... you should be using  attachInterrupt(digitalPinToInterrupt(switch_6), tightenStrings1, CHANGE);  ...... the pin name should really be something like switch_BL

Ok....thank you. I'll fix that. But again, this doesn't point out a solution. Do you guys have any idea how to fix the actual problem?

You are right when you say "technically they aren't interrupt pins".
The only pins you can use as interrupts are 2, 3, 18, 19, 20 and 21. There is no way of changing that. You can't magic more interrupts out of thin air.
However there is a different interrupt system that may help you out - the pin change interrupts.  These are harder to work with since they are grouped into sets of pins that share the same interrupt, but there are far more pins with this kind of interrupt available. Note that you still have to be careful which pins you choose.
There are a couple of libraries available to help you configure the PCINT registers should you need it.

Limit switch implies some mechanical thing is closing the switches, which hardly needs an interrupt as that will be pretty slow electronically. Simple polling is probably more than sufficient at the top of loop() or similar.
You can declare all the pins as INPUT_PULLUP, wire the switches to connect the pins to Gnd when pressed, then do digitalRead of each to determine its state, or put all 8 on one port and do a PORTx read
for example, and if the result is other than 0xFF, then one has been closed and you can act on it, or read it directly and act on like here for example:
switches = PORTL;
if (switches != 0xff){
switch(switches){
case 0b01111111:
//code for switch 7
break;
case 0b10111111:
// code for switch 6
break;
etc for 0b11011111, 11101111, 11110111, 111111011, 11111101, 111111110
}
}

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


text:
Motor driver shield l239D should be giving enough power but it doesn't
I am doing a line follower robot using motor driver shield l239D stacked with an Arduino uno to run 2 DC motors and two infrared sensors. I am supplying 12V to the motor driver shield trough three 18650 batteries.
The point is the car was working fine and it followed the line but  two days ago it stopped working after one week of working fine...
When the two DC motors and two sensors are connected the motors don't move they just buzz(the sound it makes when it's not getting enough power), it works sometimes a little bit...
Basically the car only works with no sensor connected. So I made measurements with the multimeter and I got this:
The three batteries:12.62V
The shield receives: 12.39V only with the two sensors connected and the motors disconnected.
The shield with the motors and two sensors connected:12.28V.
And when I measured how much the motors where receiving I got 0V! In both of them...
With just one motor and the sensors connected the motor started buzzing and I got 0.07V till the sound stopped and I got zero again.
Sometimes the motors work a little bit sometimes they just buzz and some times they don't buzz at all...
I see that the batteries are fine and they can deliver enough current for everything to work but the motors don't receive almost anything!!!
Can you help me and tell me suggestions of what I need to do please? I searched and asked a lot but haven't found anything that helps...
Here is my car and my circuit.

If you are working  with dupont plugs check each of them sounds like a problem with connection - check for loose/not fully connecting plugs and pins. Because if it worked the only other solution is you fried something by overheating/overpowering

If it is "only works with no sensor connected", then it is something to do with your code. Edit your post and add your code.

The cause is really the lack of power because with one sensor it works. But could it be because my wires for the batteries are thin? Wich doesn't make sense because they can passe the 12V to the shield... But could it be from it?

Does the motors work with the sensors disconnected? Do the sensors work with the motors disconnected? Did you measure the voltage at the output terminals of the shield as well as the input? If you can isolate the fault to one component it would be a lot easier to fix.


text:
Regarding Geared motor encoders
I wrote a simple code to count the number of pulses when the motor runs.
The code just counts the number of interrupts from the encoder, but the output is very weird.
Even when the motor is not running it outputs huge numbers of the range of 10000s as the number of pulses.
Same case with the other motor.
Is something wrong with the encoders or am i missing something?

what are you counting? ... i do not see any circuit diagram

Please edit your question to add the sketch you're using in text format. Highlight the sketch then click the {} button to give it the correct formatting.

You should use digitalPinToInterrupt(pin) instead of directly passing the interrupt number (0 should be correct, though). The reason for those readings you get when the motor isn‘t running could be that the interrupt pin is floating. Try pinMode(encoder_in, INPUT_PULLUP);.


text:
Power 5v from l298n to 5v pin arduino
im using the l298n module, and 3x 18650 batterys (near 12v total), and supplying 12v to the 12v pin of the l298 module. Can i use the 5v pin of the module to power the 5v pin of arduino? Or i need a second power supply just for the arduino? Any tips?

The L298 is a H-bridge driver, not a voltage regulator. It might be, that your L298 board has also a voltage rgulator on it. Please provide a link to that board. The datasheet mind say, how much current you can draw from it

https://www.alldatasheet.com/view.jsp?Searchword=L298N%20MODULE It has a 12v pin, ground and 5v pin

The chip has a Vss pin for the lpgic power supply. But that is not an output. The 12V will not be regulated down to 5V by this chip

I checked the 5v pin with a multimeter, and it is 5.23 volts and powered the arduino, the problem is that i dont know if it is safe or not, in my picture, the third screw withouta tire is the 5v output.

From the amazon link in the description of the linked video: "This module has a built-in 5v power supply, when the driving voltage is 7v-35v". The module has a voltage regulator. You won't get better answers, until we get a datasheet of that module with the information or at least the part number of the voltage regulator used on it.

That is something, that you can even do yourself. Look at the components on the board. Search for the voltage regulator. Look if there is a part number written onto it. Then google the datasheet. When you found it, you can look in there for the maximum output current. I would guess, the voltage regulator is the flat black IC in the middle, right besides the pins of the big L298 chip.

@JonathasMoreira 5.23V is perfectly safe

Power the arduino from your batteries via the Vin (barrel Jack) use the arduino to supply the 5V to the L298 module and connect all the grounds together. That should do it.

The L298N is a chip, and the link you provided in the comments is to the chip, not to a full H-bridge module with voltage regulator and other components. We don't have any way to answer your question about your particular set-up without more info.
If the module you have uses a voltage regulator to provide clean 5V to its solid state chips, but does not use it to drive the motors, and it provides enough extra current to drive your Arduino then you might be able to get away with using it to feed your Arduino. If the H-bridge module uses the output of it's 5V regulator to drive the motors then I would not recommend using it to power your Arduino, since as the motor is switched on and off it will cause the voltage from the regulator to bobble. At the very least you would need a reservoir capacitor across the 5V rails near the Arduino to smooth out the 5V supply.

Here is the module im using https://www.youtube.com/watch?v=-ikmDMW6tEw. I have a 1n4007 diode (https://www.alldatasheet.com/datasheet-pdf/pdf/872064/CHONGQING/1N4007.html) too, maybe it can help? Im afraid of inverse current, but im very noob at time to understand how things works better.

I'm not going to watch a 14 minute video to figure out what module you're using. What is the model number of the module? Do you have a data sheet?

No problem bro, you can do anything with your time, relax. I cant find the datasheet of the module, just know that use the chip l298n, and it is a very common module, but whatever, i will power my arduino with the 5v of the module. Thx

If you are going to ask questions about a specific module based on the L298n, you need to provide information about that specific module. We're trying to help you, but you need to post questions that provide enough information. Otherwise just delete your question and don't waste your time (or your readers'.)

It is simple, i have no idea how provide you the information about that specific module, the datasheet is somewhere so far away from me and i just cant find it, cause too dumb or noob to provide it. However, I endeavored to find a video that  has some information about the module, if that was not enough for you to help me, I ask you to simply ignore it and leave it to other people who can help. Thank you.


text:
POST image from Arduino Uno
I need to post an image to a website. Iam able to capture the image using OV7670 camera module. But don't know how to store and post the image to a website. I didn't get any idea to start this. Can anyone help me to do this.
I got the image capturing code and circuit from
 https://circuitdigest.com/microcontroller-projects/how-to-use-ov7670-camera-module-with-arduino
I have got the below components:
Arduino uno,
ESP 01 module,
OV7670

start by researching the different ways that pictures can be POSTed to a web server from a PC

@jsotola I cannot even post any data from arduino to a webpage using wifi module. Can you please give any idea to post any string data to webpage and the response back.


text:
Use of "static" with "RTClib"
I've got a question concerning the Arduino library "RTClib" by Adafruit and the use of the word "static".
Here you can see an excerpt from the example provided for the pcf8523 real-time clock:
#include "RTClib.h"

RTC_PCF8523 rtc;

void setup () {

  while (!Serial) {
    delay(1);  // for Leonardo/Micro/Zero
  }

  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.initialized()) {
    Serial.println("RTC is NOT running!");
  }
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    /*
    do some more stuff
    */
}

In the beginning of loop() they wrote:
DateTime now = rtc.now();

Thus, with every iteration of loop() "new" gets defined anew (on the heap?!), right?
This appears inefficient to me.
I thought about rewriting it this way:
static DateTime now;    // static declaration, executed only once
now = rtc.now();    // assignment to "now" every time loop() starts over

In this case "new" should be allocated on the stack like a global variable, right?
I want to use "static" to increase overall performance by reducing work for the processor and the heap (thereby avoiding heap fragmentation). Does this make sense or will it cause more problems than it solves? Keep in mind that I want to learn both proper programming for Arduino and proper coding in general.
Link to the library:
https://github.com/adafruit/RTClib
Thank you! :-)
EDIT: For some reason I CAN NOT declare DateTime now; in global scope or else the program won't run. Don't know why though. This is why I want to use static in the first place.

Re “I CAN NOT declare DateTime now; in global scope”: what happens if you do so? A compilation error? Incorrect run-time behavior? I tried and it compiles just fine (but I have no RTC for testing).

Actually, DateTime now = rtc.now() might have utilize "copy elision", so it gets constructed directly into now variable and therefore it's faster than your approach (as you effectively blocked this possibility - so it has to create temporary object and copy it into now variable).

@EdgarBonet , it compiles and uploads but will not execute Setup(). Setup() starts with Serial.begin(9600); Serial.println("test"); Blinking the builtin-led doesn't work either.

@KIIV , concerning C++ I've read many times that separate declaration and definition can be part of "good practice". Your explanation was never mentioned but seems to make sense! Maybe it makes no difference with (aggressive) compiler optimization?

@blackdaw I'm pretty sure it's about declaration and definition of Class methods, not variables. And non rules/myths: Don't insist that all declarations shoudl be at the top of function and two rules Don't introduce a variable (or constant) before you need to use it

@KIIV You are right. I picked up many misconceptions through "beginner guides". The one you linked is a very helpful guide, thank you!

You wrote:

DateTime now = rtc.now();

Thus, with every iteration of loop() "now" gets defined anew (on the
  heap?!), right?

No. Local variables like this are usually allocated on the stack,
although the compiler may keep them in CPU registers if that helps
optimization.

static DateTime now;    // static declaration, executed only once

In this case "new" should be allocated on the stack like a global
  variable, right?

No. It is allocated statically, in the .bss section, like uninitialized
global variables.

I want to use "static" to increase overall performance by reducing
  work for the processor

Not sure it will make much difference. Static allocation may save you a
few CPU instructions compared to stack allocation (the instructions that
move the stack pointer). On the other hand, it will cost you a few
instructions compared to register allocation (the instructions to access
the RAM).

avoiding heap fragmentation

Stack allocation does not use the heap, and the stack never fragments.

Does this make sense or will it cause more problems than it solves?

If you really care about sub-microsecond differences in the execution
time, you should either look and the disassembly of the program, or do
some benchmarking. Otherwise just write whatever makes more sense from
the point of view of the program's logic: does the variable need to keep
its value across calls to loop()? If the answer is “no”, do not use
static.

You don't need to use the static keyword.
The cleanest solution is to define DateTime outside of the loop function:
DateTime now;

This will allocate the memory, and call the constructor of the class DateTime initializing it.
In case you would need a basic variable (like an int), you should initialize it, like:
int now = 0;

When you use it in setup or loop you use the created instance (without the class name to declare it):
void loop() {
   ...
   now = rtc.now();
}

Also, find a better name for now, because the variable is the same as the rtc's function now.
Update
after your comment, it cannot be used as a global variable:
I didn't try it myself, but I suspect, the constructor calls a function that uses variables or a function that is not initialized at that point. Actually, it's quite bad practice.
Anyway, one way to circumvent and stick as much to what I wrote above, is to use a pointer instead:
RTC_PCF8523* rtc = NULL;

Than you create an empty pointer, without calling the constructor. You will do this at the end of setup:
void setup() {
   ...
   rtc = new RTC_PCF8523();
}

This will cause the variable to be put on the stack.
Than when using it, you call:
now = rtc->now();

Note you have to use the -> notation, as rtc is a pointer.

Forgot to mention: Defining it outside of loop() in the global scope DOES NOT WORK! Don't ask me why, I spent hours just to find this problem. This is the reason why I wanted to use static in the first place. Will edit my post. And concerning the name "now": It's just what they used in the example, I won't use it, but good point!

I updated my answer, just try if it helps.

Re “I suspect, the constructor calls a function that uses variables or a function that is not initialized at that point”: I can't see anything wrong in this constructor.

@EdgarBonet ... me neither, I'm wondering why creating it as global variable wouldn't work.

See the comments above beneath @EdgarBonet 's solution. It compiles and uploads but doesn't execute.


text:
Arduino Nano and 0.96 i2c oled screen not working
When I try to scan the i2c address it stays stuck on "i2c Address Scanner" which is the first line of the code.
My screen is connected with VCC-5V, GND-GND, SCL- 4.7K resistor->A5, SDA- 4.7K resistor->A4.
Nothing displays on screen, and I even tried without the resistors. I also tried with some 10K resistors and same result.

Here in the picture you can see how I connected the screen to the nano. SDA-A4, SCL-A5, VCC-5V, GND-GND.

Did you put the resistors in line?  Or as pull-ups?   Show how you wired that.  It sounds like you did it wrong.

Take A look in the picture I hope it helps, I'm a noob

A 4 kOhm resistor in series is too big. Such resistors are normally used as pullup resistors, so connection from SDA/SCL to Vcc. Resistors in series are in I2C only used to limit current, when having different voltage levels (lower values must be used). Also your solding seems not clean enough. You have tons of burned flux there and the solder points look like they might not give you good contact.

that is a really horrible soldering job ... i would not bother to do any troubleshooting until the board is cleaned up and the soldering is properly done

Yeah those resistors are wrong.  They should go from the pin to Vcc.  Not in line with the signal.

Delta_G Could you please show me in a schematic what you mean?

chrisl what type of resistor would you recommend me to use?

I think those modules already have pull-up resistors on them, so pull-ups aren't needed. Connect the SDA and SCL pins directly to the Arduino pins. Also check continuity on your solder connections, because they look a bit crumby. Try holding you iron on the solder connection a bit longer. That is. Put the iron on the connection, trying to touch both the pad and the wire. Add a bit of solder. Keep the iron in the same position for a second or two, to make the solder flow. Then remove the iron.

@peterk Most likely the resistors aren't necessary, though I always add one 4.7kOhm standard  resistor (0.25W) as pullup resistor on each line, just to be sure

From what I am reading it is not properly connected.  You are getting what I would expect. ACL of the device goes directly to A5 and a pull up resistor to +5. Same thing with SCL, connected directly, both need pull ups. You did not state what it is connected to. If there is nothing connected you will get nothing. Also the old wire library did not support timeout so you could hang indefinitely.

As I said, I have two 4.7K ohm resistors, one with sda and one with scl. Both are connected with resistors(none directly connected).

As Delta_G asked, how did you connect the resistors? They should not be in line with the SCL and SDA signals. Could you show a (simple) schematic of how you built it?

Ok I just added a picture of how I wired everything hope it helps!

As stated earlier the resistors need to be pull ups, not in series as your photo shows. Also you need to clean up the solder splatter and flux, that could also cause shorts. Isopropyl alcohol 90% works great. I would suggest you get a temperature controlled soldering iron between 40 and 50 watts max,


text:
I'm trying to control a servo with a push of a button but its not working HELP
I'm new to Arduino and I'm following this tutorial: https://www.youtube.com/watch?v=T2HMJiy9b_I   but the problem is the servo just keeps moving back and forwards on it own and the button is doing nothing when pressed please help.
Code:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
#define servoPin 3 //~
#define pushButtonPin 2

int angle =90;    // initial angle  for servo
int angleStep =5;
const int minAngle = 50;
const int maxAngle = 110;

int buttonPushed =0;

void setup() {
  // Servo button demo by Robojax.com
  Serial.begin(9600);          //  setup serial
  myservo.attach(servoPin);  // attaches the servo on pin 3 to the servo object
  pinMode(pushButtonPin,INPUT_PULLUP);
   Serial.println("Robojax Servo Button ");
}

void loop() {
  if(digitalRead(pushButtonPin) == LOW){
    buttonPushed = 1;
  }
   if( buttonPushed ){
  // change the angle for next time through the loop:
  angle = angle + angleStep;

    // reverse the direction of the moving at the ends of the angle:
    if (angle <= minAngle || angle >= maxAngle) {
      angleStep = -angleStep;
       buttonPushed = 0;
    }
    myservo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
  delay(100); // waits for the servo to get there
   }

}

I posted the code:https://robojax.com/learn/arduino/?vid=robojax_Servo_PB2_move_one_direction. I need help with the code so when the button is pressed the servo will rotate 0 to 180 degrees and stop but the button is unresponsive and the servo just keeps moving back and forth

Edit your question. Select all of the code, and tap the {} code formatting button. Your code is unreadable as posted.

ok how about now

Once you push the button once and buttonPushed becomes 1 the servo will move forever because nothing ever sets buttonPushed back to 0.  You need an else there to set it back to 0.

sorry, but I don't really know how to do that. :(

Also you should use a pull down resistor if not already doing so.

Actually that code sets buttonPushed to 0 when the angle reaches one of the limits. From that code I would expect the servo to move to one of it's limits and stop if you pressed the button for a very short time. As long as you hold the button down I would expect the servo to keep moving back and forth.

The button appears to be wired through the pin to ground, and using INPUT_PULLUP mode on the pin. That should work. As long as you hold down the button, the servo should move back and forth. When you let go of the button it should stop almost immediately (within 1/10th of a second.)

i posted some code that shows how to detect the button being pressed at the moment that you press it, but it does not keep detecting a button press if you hold the button .... https://arduino.stackexchange.com/questions/74876/restart-sequence-of-neopixel-stick-with-a-push-button-at-any-time/74949#74949

This condition below is never met because a boolean comparison is implied :
if( buttonPushed ){

and buttonPushed is declared as :
int buttonPushed =0;

A proper comparison should be OK :
if( buttonPushed == 1)
{
   // Do something
}

Also the buttons need proper debouncing or the push event will have undetectable results :
https://dduino.blogspot.com/2012/03/arduino-button-debouncing.html

C++ will treat any non-zero value as true and 0 as false.  It is perfectly legal to use an int inside an if statement in this way.   If you would like I can post demonstration code to prove it.  It not great coding style, but it won't cause any failure.

An if statement works with integers!

Mea culpa you are right :
https://www.arduino.cc/reference/en/language/variables/constants/constants/


text:
Stop VSCode/Arduino add-in from sending reset signal in the event of compile errors
This is more of an annoyance, but if I edit a program with the serial monitor open, click "upload",  and the compile fails, the IDE switches to the serial monitor pane, opens the serial port which triggers a reset, and the last successfully uploaded version begins execution. This can be really annoying if you don't notice there were errors in the compile because VSCode automatically switches to the monitor pane and you waste time wondering why your code changes had no effect.
Is there any way to tell VSCode/Arduino add-in not to switch to the monitor pane in the event of a failed compile?

This doesn't happen for me; it compiles and ends with [Error] Uploading sketch 'blink.ino': Exit with code=1. You may need to provide more details.

@DaveNewton - you're right, of course. I looked more closely at what's going on and revised the question to reflect what I think it happening.

See https://github.com/microsoft/vscode-arduino/issues/1061; switching to the CLI tools might resolve this, but a (very) cursory inspection of the plugin was unenlightening at best. I'll look in to this because the Arduino output/console output thing has been a pain point for me as well sometimes.

@DaveNewton - look at Arduino.ts line 701. It appears that the CLI will behave the same way, as it also records if the Serial Monitor was open. The monitor is restored after compile at line 723 without checking if the compile was a success.

@DaveNewton - see my issue at the github repot


text:
Value of uninitialized EEPROM in ESP8266?
In my limited testing it appears that the EEPROM in the Wemos D1 is not initialized to 255 like the specs say is the case for AtMega based Arduinos. In fact, the values look to be more-or-less random. Presumably this is because the ESP8266 doesn't actually contain EEPROM, but instead emulates it using flash. Is there a way to initialize the EEPROM region when flashing?
(This is pretty much the same question as here, which has not been answered.) Since I need only a few bytes of data, I'd prefer not to have to use the SPIFS.
Update:
Use case: I'm using the WiFiManager library to select the network to connect a Wemos D1 mini to the web to upload data to Thingspeak. I'd like to use WiFiManager to request the api-key and channel id from the user. However, once the user has entered these, I'd prefer not to make them enter the values again. (The api key is 16 random looking chars and difficult to enter correctly.) This means that the device has to store the values persistently between boots - the main use case for EEPROM. But how do you tell that the values in EEPROM (actually flash on an ESP device) are uninitialized crap, not the previous value? As suggested in the comments, setting flag values in a number of vars make it statistically unlikely to the random values from uninitialized memory. On an AtMega device, unless previously used, the values will be 255 in each byte.

You have to solve this in your sketch. That's how it should be in the first place. Even with an atmega it is dangerous to rely on the eeprom being all 0xff. When you use an atmega for testing, and forgot about it, the eeprom might no longer be 0xff. This question is the same, according to the rules of stackexchange, I think this question will be closed.

Just buy I2C EEPROM.. Much better solution

@Jot - Barring the use of persistent memory like EEPROM, a program (sketch) is the same every time you run it. How do you propose to "solve this in your sketch" if the goal is to determine if it has every been run since the device was flashed?

Have a separate sketch that clear the EEPROM. Upload that first, run it, then upload your own sketch.

Alternatively; write like 10 constant values to 10 unused locations in the flash. On boot check if those 10 locations contain those 10 constants. If they don't you know you have uninitialized flash. The chance that uninitialized flash contains those 10 constants is pretty slim.

@Gerben - the ESP8266 doesn't contain actual EEPROM, it simulates the behavior using flash. Clearing the "EEPROM" with a separate program would fail in this case as the flash memory would be over-written when a new program is flashed.

@Gerben - the idea of writing a number of values and checking is something I thought about and may try if nobody comes up with an actual solution. As you note, it's not guaranteed, but statistically it's pretty safe (unless the consequences of an error are large, which they are not in my application)

Flash and EEPROM are the same thing in the case of the ESP. I think they always use the same location of the Flash/EEPROM to store the "fake" EEPROM data.

You coud add an identifier and checksum to the data. When a sketch is compiled, it is possible to put the compilation date and time in the sketch with __ DATE __ and __ TIME __ if you check those and store them in eeprom, then you know if a new sketch was uploaded. Please tell us the reason for your question. What problem are you trying to solve?

The point is not to tell if a new sketch was uploaded. It's to persist data between reboots. What you suggest, for a different purpose, requires that data persist across a re-flash of the memory. I wrote a quick test program and can verify (that at least for my simple test) the simulated EEPROM does persist across a reflash. This suggests that the device could be "prepared" by running a program that initializes EEPROM to some known value, then the desired program is flashed after that and can depend on a known EEPROM state.

I sure hope so, or else calibration data or a wifi password has to be entered every time. Do they "guarantee" that the values stays there? When you use @Jot, then I get notified.

Calculate a checksum for the data and store as part of the data. Recalculate the checksum when you read the (questionable) data back again. If the checksum fails, it's invalid. If it passes, the data is valid to some statistical level of confidence.
A 16-bit checksum would make false acceptance highly unlikely, but  make it long enough for your own comfort level. What would be the worst consequence of a false acceptance: inconvenience (user has to re-enter a number)? Loss of money or property? Loss of life? Choose the complexity of your solution accordingly.

This is the best, most reasonable answer to this question. Other answers include "don't use EEPROM", and "rely on a magic value being there".  I definitely like your strategy the best, and as you can say it can be expanded on to increase confidence (a better type of hash maybe instead of just a checksum). I'd add that I would have some kind of ability to do "migrations", that is, store a version of the EEPROM and if values are added/changed, offer the ability to upgrade to the new format.

I've done this in the past by simply checking for a string (array of characters if you prefer) at a specific memory location. I used "INITIALIZED". It would be very unlikely for the ROM to have this sequence of characters by accident. If I find the string I read the variables from ROM. If I don't, I write the string and set default values for the variables.
I found a slightly different example that uses the same technique:
// EEPROM library.
#include <EEPROM.h>
// Persistent Shoe State.
byte shoeState = 0;
// Number of Shoe States.
#define SHOE_STATE_MAX 3

// setup() runs once at reset.
void setup() {
  // EEPROM Init Code Base Address
  #define EEPROM_INIT_CODE_ADDR 0x00
  // Check EEPROM Init Code
  byte shoeStateInit[] = {0xde, 0xad, 0xbe, 0xaf, 0xaa};
  for(int b = EEPROM_INIT_CODE_ADDR; b < EEPROM_INIT_CODE_ADDR + sizeof(shoeStateInit); b++) {
    // EEPROM = Init Code?
    if(EEPROM.read(b) != shoeStateInit[b]) {
      // No, Write Init Code to EEPROM.
      EEPROM.write(b, shoeStateInit[b]);
      // Set Not Initialized Flag.
      shoeState = -1;
    }
  }
  // EEPROM Init Code?
  if(shoeState == 0) {
    // Yes, Read Shoe State from EEPROM.
    shoeState = EEPROM.read(sizeof(shoeStateInit));
  }
}

The only variable being saved to ROM is shoeState.

While testing you'll want another sketch or some way to clear your flag memory.


text:
Compiling for Wemos D1 mini with Visual Studio Code
I'm giving Visual Studio Code (VSC) a try and am getting unexpected results. I have a program (sketch) that compiles fine in the Arduino IDE. I create a workspace in VSC, initialize the project, and after some more mucking about I get a compile there appears to succeed:
[Done] Finished verify sketch - RanchMonitor2.ino

But the console pane shows four "problems":

How can the compilation have succeeded if there are problems?
The same sort of thing is happening with one of the samples - HelloServer.ino
In this case the problems are an incomplete type and memcpy_P not defined.
I wouldn't think it should make a difference, but I'm working without a board physically attached to the USB port.
UPDATE:
I think "Problems" are issues identified by Intellisense. They appear even before a compilation is attempted. All I have to do is open the workspace and wait a few seconds, then the "problems" appear. Hence my conjecture they are Intellisense warnings, not compilation errors.
Adding "ESP8266" to the Defines section of c_cpp_properties.json got rid of the error "WiFiManager" is undefined.

If the compilation fails, it returns error code 1 and doesn't say "finished". I tested this by forcing a failure, removing a semi-colon at the end of a line. See edit to question.

Intellisense reports "Problems" - these are distinct from compile time errors. Just because Intellisense can't resolve a literal or something doesn't mean it won't be resolved in the compiler; thus it's possible to have the IDE report a problem but still be able to have a successful compile. In the case described above, two changes to the c_cpp_properties.json file provided Intellisense with the information it needed. A header file was added to the forcedInclude section to provide pin definitions. A literal "ESP8266" was added to the defines section to indicate the processor type. This define is used in lots of header files so it must be know to Intellisense when reading the headers. Here are the relevant sections of that .json file:
        "forcedInclude": [
            "C:\\Users\\David\\AppData\\Local\\Arduino15\\packages\\esp8266\\hardware\\esp8266\\2.7.1\\variants\\d1_mini\\pins_arduino.h"
        ],
        "defines": [
            "USBCON",
            "ESP8266"
        ],


text:
I2C and SPI at the same time?
I would like to ask a question relating to the following communication setup:
STM32 -- Arduino Pro Mini -- ADNS3080 sensor
The interface between STM32 -- Arduino is I2C and the interface between Arduino Pro Mini--ADNS3080 is SPI.
I have tested the communication between the STM32 and the Arduino Pro Mini, and between the Arduino Pro Mini and the ADNS3080 sensor. Both of them work fine; I can successfully send and receive data in both cases.
Now, I want to read the register of the ADNS3080 sensor using the STM32. First, I start an I2C communication between the STM32 and the Arduino Pro Mini, then I send the register address of the ADNS3080 to the Arduino Pro Mini. The Arduino Pro Mini reads the register address and in the same function starts a communication, using SPI, with the ADNS3080 sensor.
But I receive I2C errors in the STM32. Is it possible to use I2C and SPI at the same time? Do I have to introduce delays between the I2C and SPI commands?
Regards, Ali

I feel like their interrupts would be bumping into each other.

They are on separate busses, so yes you can do both in one program. However if one is being triggered by an interrupt from the other and it itself relies on interrupts there may be a problem there. You should have one interrupt telling your main program it's time to do the second operation rather than run it direct from inside an interrupt.

Are you expecting that the Arduino can execute the SPI transaction and return the data to the STM32 in the same I2C transaction? That isn't likely to work. You're going to need some sort of flow control or handshake mechanism that tells the STM32 when the data is actually available. This could be anything from clock stretching to splitting it into multiple I2C cycles in which the STM32 polls the Arduino for status.

You will get better answers if you post your code. You are asking about errors in unposted code, with no schematic. Any answers thus are general, and largely guesswork.

I feel like their interrupts would be bumping into each other - interrupts don't really "bump into each other". They are executed in priority order in an orderly way.

I would like to inform you all that, a few days back, I managed to solve my problem by following the suggestions made by @Majenko. Thanks everyone for the help.

is it possible to use I2C and SPI at the same time?

Yes it is. Both are implemented in hardware in the chip. They can operate "in the background" and raise an interrupt when there is something to do.

Do I have to introduce delays between the I2C and SPI commands?

No you don't.

Your Arduino code probably needs to implement clock stretching as an i2c slave. This tells the master to chill for a little while as the slave does some work to get an answer.

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


text:
How to execute commands on Arduino (via PC) without touching the current sketch?
I am working on my first Arduino project. It's a Reverse Geocache. Basically, it's a puzzle where a battery-powered Arduino is mounted inside a locked box, and is able to unlock the box if the user brings the box to the correct GPS coordinates and presses a push-button (that activates the Arduino, that runs a sketch, that checks the GPS, and operates a servo to release the lock).
It's all working, but I am trying to build in a backdoor, so I can unlock the box when I need to.
I have made the Arduino USB port accessible, and my hope is that I could connect a PC, and execute the appropriate command to operate the servo to unlock the box. The command is:
servo.write(OPEN_ANGLE);

The sketch that drives the whole puzzle depends on these libraries, but I am guessing the only one needed to operate the servo is PWMServo.h:
#include <PWMServo.h>
#include <SoftwareSerial.h>
#include <TinyGPS.h>
#include <EEPROM.h>
#include <LiquidCrystal.h>

I would like to be able to operate the servo without altering/replacing the uploaded sketch.
Is it possible to execute code "command prompt" style? Or can I somehow detect from within the sketch code that there is a USB connection, and have that trigger the unlock?
Finally (not the main question, but I would appreciate clarification), I have been told that the power to the Arduino should be disconnected before uploading new sketches (not sure why or if this is true). If forcing an unlock via the backdoor required uploading a new sketch, I seem to have a problem... For the puzzle to work within the locked box, the battery must be permanently connected, and also connecting to a PC via the USB seems to immediately power up the Arduino too. Does this mean uploading a new sketch would be impossible?

The simple thing would be for your sketch to read from the serial port continuously. If it finds something it stores it and when a newline arrives it sees if that happens to be a password known only to you. So, for example, all you would have to do is plug in the USB cable, activate the Serial Monitor on your PC, type swordfish and the servo opens the box.
You would need to allow for garbage arriving, so make sure that you discard input if it exceeds the size of the buffer you allocate for this purpose.

I have been told that the power to the Arduino should be disconnected before uploading new sketches (not sure why or if this is true).

I don't see how that can be true as you have to reapply power to upload the sketch. I never do that.

Is it possible to execute code "command prompt" style?

No, you upload compiled code.

Or can I somehow detect from within the sketch code that there is a USB connection, and have that trigger the unlock?

Then all the person you give the box to has to notice the USB port, plug something in, and it unlocks. I think not.

An even simpler solution would be to have two locations that unlock the box. For example, your kitchen could be one, so to unlock it you just take the box to your kitchen. The other location would be the "real" one that you want your friend to have to find. All the stuff about "you are 200 km from your destination" would of course refer to the real destination. You just make the code check that if it happens to find itself in your kitchen it unlocks the box.

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


text:
AREF pin on Arduino Uno R3
edit
So then, AREF can only output a voltage when used by the ADC, but not when used by the AC.
That is what I sense all your answers are pointing at, yet none has it black on white. My questions remains unmodified, below:

On the Uno R3, is the AREF pin supposed to present any voltage when default / bandgap voltage is set for the analog comparator?
With this code (analog comparator):
void initAC()
{
  ADCSRA = ADCSRB = ACSR = DIDR1 = 0; // also enables comparator
  ADCSRB |= (1 << ACME); // AIN1 from ADC mux
  ADMUX |= (1 << MUX0); // ADC1 input pin selected (PIN_VSENSE)
  ACSR |= (1 << ACBG); // AIN0 set to bandgap reference
                                          // voltage 1.1V
  //ACSR |= (1 << ACIS0) | (1 << ACIS1); // enable interrupr on rising edge;
  ACSR |= (1 << ACIE); // interrupts enable
  DIDR1 |= (1 << AIN0D) | (1 << AIN1D); // disable digital input buffers
                                          // for power saving
  PRR &= ~(1 << PRADC);                   // no power reduction ADC in order for
                                          // the AC to be able to use MUX input
  EEPROM.put(0x155, 0x5501);
}

When keeping the DMM probes on AREF / GND as the Arduino reboots I read some 10 mV steadily.
When touching the probes while the Arduino is running, I can read a decreasing voltage as through an RC group.
Tried with or without ACBG, same observation.
With this other code (analog digital converter):
{
 //power_adc_enable();          nah-uh!
 //power_usart0_enable();

 ADCSRA = ADCSRB = ADMUX = ACSR = DIDR0 = 0;
 ADCSRA |= (1 << ADEN);                  // power enable ADC
 ADCSRA |= (1 << ADIE);                  // enable interrupts
 ADCSRA |= (1 << ADPS2) | (1 << ADPS0);  // 250 kHz operation
 ADMUX |= (1 << REFS0);                  // 3.3V (AVCC) as voltage reference
 ADMUX |= (1 << ADLAR);                  // discard least significant 2 bits,
                                         // only read ADCH
 ADMUX |= (1 << MUX0);                   // ADC1 input pin selected (PIN_VSENSE)
 DIDR0 |= (1 << ADC1D) | (1 << ADC3D) | (1 << ADC5D);  // disable digital input
                                       // buffers for power saving, which is not
                                       // really needed given how the ADC is used
}

I was able to read a good 4.8V on the AREF pin. Swapped the Atmega328P chip on my Arduino board with another one - same behaviour.

After reading the answers I still don't understand why you try to read a voltage from an input.

On the ATmega328P (the microcontroller of the Arduino Uno), the AREF pin
is initially floating. If you try to read its voltage, you can get
basically anything.
As soon as you select an analog reference other than EXTERNAL, the
AREF pin gets internally connected to either the AVCC pin (if you select
DEFAULT) or the internal 1.1V reference (if you select INTERNAL).
This typically happens when you call analogRead() or, in your example
code, when you set the REFS0 bit of ADMUX.
Edit 1: As pointed out by JRobert in a comment, the section ADC
Voltage Reference of the ATmega328P datasheet is worth reading if
you consider using the AREF pin. Especially the warning in the third
paragraph.
Edit 2: Answering this new point:

AREF can only output a voltage when used by the ADC, but not when used
by the AC.

Whether or not it is being used by the ADC and/or the AC is irrelevant
to the behavior of the AREF pin. The only thing that matters is the
value of the REFS0 bit of ADMUX. The pin outputs a voltage if and
only if that bit is set. This can be clearly seen in this part of the
schematic of the ADC, from the datasheet:

When REFS0 is 1, the transistor circled in red connects the AREF pin
to either AVCC or the internal reference, as selected by the multiplexer
controlled by the REFS1 bit.
Note that you can change this bit without ever really using the ADC,
although that would probably be useless.

Also, see section 24.5 of the ATmega328 datasheet, "Changing Channel or Reference Selection" and especially 24.5.2 "ADC Voltage Reference". This subsection discusses the use of the AREF pin including a couple of warnings. Definitely worth a read!

@JRobert: Indeed! I added the relevant link to my answer.

You are supposed to supply an aref voltage to the aref pin. You supply your 5v reference to the aref pin, so that the ADC compares its input against the aref voltage.

As stated in the datasheet, section 1.1.8, the AREF pin is a reference voltage for the ADC. In other words it is an input.

AREF is the analog reference pin for the A/D converter.

From the datasheet:

23.5.2 ADC Voltage Reference
The reference voltage for the ADC (VREF) indicates the conversion range for the ADC. Single ended channels that exceed
VREF will result in codes close to 0x3FF. VREF can be selected as either AVCC, internal 1.1V reference, or external AREF pin.
AVCC is connected to the ADC through a passive switch. The internal 1.1V reference is generated from the internal bandgap
reference (VBG ) through an internal amplifier. In either case, the external AREF pin is directly connected to the ADC, and the
reference voltage can be made more immune to noise by connecting a capacitor between the AREF pin and ground. VREF
can also be measured at the AREF pin with a high impedance voltmeter. Note that VREF is a high impedance source, and
only a capacitive load should be connected in a system.
If the user has a fixed voltage source connected to the AREF pin, the user may not use the other reference voltage options
in the application, as they will be shorted to the external voltage. If no external voltage is applied to the AREF pin, the user
may switch between AV CC and 1.1V as reference selection.

As you can see from the above quote from the datasheet, once initialised, AREF is made available to you for measurement, and they recommend a capacitor to smooth out noise.


text:
Arduino OLED ssd1315 graphic print questions
I’ve tried to create a system that the rotary sensor as an input and use a 0.96 inch Oled as an output (first pic), try to show the voltage measurements and performance test using a small bar graphic.
And I use this code
#include <SPI.h>
#include <Wire.h>

#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 Display(OLED_RESET);

int r = 0;
int i = 0;

void setup()   {

  Display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3C (for the 128x32)

  // i'll follow the license agreement and display the Adafruit logo
  // and since they were nice enough to supply the libraries
  Display.clearDisplay();
  Display.display();
  delay (1000);

  DrawTitles();

}

void loop() {

  // get some dummy data to display

  r = rand() / 220;
  //r = analogRead(ADJ_PIN);
  //r = r / 7.98;

  Display.setTextSize(2);
  // note set the background color or the old text will still display
  Display.setTextColor(WHITE, BLACK);
  Display.setCursor(0, 33);
  Display.println(Format(r * 7.99 / 204.6, 3, 2));

  //draw the bar graph
  Display.fillRect(r, 50, 128 - r, 10, BLACK);
  Display.fillRect(3, 50, r, 10, WHITE);

  for (i = 1; i < 13; i++) {
    Display.fillRect(i * 10, 50, 2, 10, BLACK);
  }

  // now that the display is build, display it...
  Display.display();

}

void DrawTitles(void) {

  Display.setTextSize(2);
  Display.setTextColor(WHITE);
  Display.setCursor(0, 0);
  Display.println("Bar Graph");

  Display.setTextSize(1);
  Display.setTextColor(WHITE);
  Display.setCursor(0, 19);
  //Display.println("Measured Volts");
  Display.println("Random number");
  Display.display();

}

String Format(double val, int dec, int dig ) {

  // this is my simple way of formatting a number
  // data = Format(number, digits, decimals) when needed

  int addpad = 0;
  char sbuf[20];
  String fdata = (dtostrf(val, dec, dig, sbuf));
  int slen = fdata.length();
  for ( addpad = 1; addpad <= dec + dig - slen; addpad++) {
    fdata = " " + fdata;
  }
  return (fdata);

}

But it only showed the graphic bar and random number without an actual graphic bar at the end, so just wondered if I did something wrong or forgot to add something on my cold?
I'm new to this and I've tried so many things to fix it but seen not any of them working.
Thanks

please add a picture of the OLED output ... also add a drawing of the desired output

I've just add a picture

But it only showed the graphic bar and random number  ... where are those in the picture? ... all I see is text "Bar Graph" and "Random number"

we still do not know what you are trying to display

like the first picture, that's the one i trying to do.

What resolution does your display have? I think your display has a lower vertical resolution than the one in the first picture and assumed in your code. The value and bar graph are not displayed because they are drawn outside of the display's vertical boundary.


text:
1.54 e-ink without driver
i wan’t to know if is possible to use  this raw e-ink display  with arduino. if it’s possible to directly connect cables from this ribbon cable to arduino without any driver pcb and control it with 3 or 4 wire SPI.
the pinout of the display is on the 6th page

Please add more info, not just a  link to a picture!

i’ve just posted the datasheet

DONT CROSS POST!

See figure 7-5 in the datasheet you linked. There it shows you how to connect the board.

Kind of yes and kind of no.
It requires external circuitry, but that circuitry isn't a "driver board" in the traditional sense.
An e-Ink display requires high voltages to charge the electrostatic cells. Traditionally that would be provided using an external "driver" circuit - a boost voltage converter.
However this display has that boost converter built in - though it doesn't have all the components, because they just won't fit.
You need to provide the diodes, switching MOSFET, and inductor, etc as shown on page 18 of the datasheet.  Nothing less will do.

thanks. i was thinking that i just solder few wires to a ribbon cable but i understood that there must be a lot of other components


text:
Arduino Serial Writing Array Problem
I am trying to communicate Pc - Arduino Uno.
My Arduino code is here: (It is working as below)
int ndx = 0;
char pack[12];
void setup() {
Serial.begin(9600);
while(!Serial){;}
}

  void loop() {

   while(Serial.available() ){
    char rb = Serial.read();
    pack[ndx] = rb;
    ndx++;
    Serial.write(rb);
    if(ndx == 12){
        ndx=0;
      }
    }
    }

If I try in
Serial.write(rb);

Like that:
Serial.write(pack[ndx]);

Program is acting weird, I mean sending weird bytes. I do not know what is the reason. Can you help me, please? What is going on in code?
My python code:
https://github.com/mucahitkayadan/Python

A character is send as a ascii character, not the decimal value. Try to cast it to an int or try using DEC as second parameter. With such a low baudrate, should it be better to add a seperator? for example a comma between the values.

we do not see the definition of the array

@Juraj Sorry, There were some unnecessary definions. When I was posting,I deleted them, and array definion was out of sight. I fixed,edited it.

@Jot I can add comma in between every values in python list, but will it be easier? I have not understood the algorithm you are talking about.

Post the code that is not working

@Juraj What is the error? Working on me. It needs serial connection and I have. If you don't have, maybe thats why. I am not sure but it is working on me.

you replace Serial.write(rb); to Serial.write(pack[ndx]); and get?:
char rb = Serial.read();
pack[ndx] = rb;
ndx++;
Serial.write(pack[ndx]);

then you read an uninitialized array item on the next index

Actually, it is working without using array. I you use directly " Serial.write(inByte); " it is working normally.
But if you use " Serial.write(array[index]); " it is working weird. Sending 0-255 random numbers or maybe not random but I do not know reason or meaning of that weird numbers.

I changed the aswer

I have to process the data, so I need to process with array, namely 'pack[index]', thats why I don't want use Serial.write(rb); When I put "Serial.write(pack[ndx]);" program giving me different weird numbers.

do you have ndx++ before write(pack[ndx]);?

Yes, absolutely for this reason. Now it is working. So basic thing I can not believe myself, overlooked.

And, can I send data under for loop? Like that:
for(int i = 0 ; i < 12; i++){ Serial.write(pack[i]); }

yes you can do it in a for loop

The sequence:
pack[ndx] = rb;
ndx++;
Serial.write(rb);

modifies ndx before printing. So in your first case - printing 'rb' - you'll print the value you just stored in the array; in the second case printing 'pack[ndx]' - you'll print whatever happens to be in the following member of the array. Swapping the second and third statements in my excerpt will fix it.

My packs have 12 bytes and I have totally 7 pack.I tried to just send my index, namely 'ndx'. And it receives correctly. I mean, pc receives 0-11 numbers for every time for every pack. It is expected. That thing is what I could not understand, for every iteration rb and pack[rdx] are equal. Why write(rb) is working correctly but write(pack[ndx]) does not work?


text:
Arduino as Multiplexer
This is a kind of an experiment, I just have a question on how Arduino ports work. Consider this sample: there is this target device that I'm trying to control with Arduino. The device uses a typical scanned keyboard (8 output columns and 5 input rows which make contact whenever a user presses a key). I am trying to emulate that keyboard with Arduino. Of course, a standard way to do it would be to read 8 columns and produce appropriate output on the 5 rows. However, Arduino is not fast enough to make it work. So, I am going with multiplexer idea. 8 Arduino's digital pins are connected to columns and 5 Arduino digital pins are connected to rows. GND rail is NOT connected.
So the idea is this. By default all Arduino pins are set to INPUT in init() routine. Whenever I need to emulate a key press, I just set a corresponding row pin to OUTPUT and LOW, same for the column pin. So, that should work as some kind of a multiplexer, since Arduino pins are driven by Mosfets and input state is high impedance, and during output state both pins would be tied to Arduino's GND which makes a hardlink connection between them (setting to HIGH should work to, there's no difference).
Here is the test code which should make a keypress every 5 seconds:
pinMode(ROW0_PIN,OUTPUT);
digitalWrite(ROW0_PIN,LOW);
pinMode(COLUMN0_PIN,OUTPUT);
digitalWrite(COLUMN0_PIN,LOW);
Sleep(5000);

pinMode(ROW0_PIN,INPUT);
pinMode(COLUMN0_PIN,INPUT);
Sleep(5000);

Now, the thing IS working. However, it only works if one column pin is connected. When I connect any two pins, the target device stops responding. What I found is that actually, when I do
pinMode(COLUMN0_PIN,OUTPUT);digitalWrite(COLUMN0_PIN,LOW);,
the neighboring pins somehow get activated too, which results in all column outputs connected together and sending signal to row inputs.
If all pins are set to INPUT, it works fine, meaning, no connection between rows and columns.
My qustion is: why is it happening? Let me rephraze it: somehow setting a digital pin to OUTPUT makes other digital pins lose their high impedance state, although all of them are set to input. I haven't checked if this is happening within a hardware port or not, just consider schematics, please.

it is unclear what you are trying to do ... emulating a keyboard does not involve using a matrix ... are you trying to programmatically "press keys" on a real keyboard?

There is a vintage device that uses a typical keyboard matrix circuit. I am trying to emulate keypresses on that keyboard with Arduino. Usually you do this by following outputs and producing data on inputs. But Arduino is too slow in this case and that approach is not working. So, I'm looking for a simple way to do it. Of course, I can use add-on multiplexers, but the point is to keep it "Arduino only."

The Arduino is probably plenty fast enough - you just have to be more clevererer with your programming.

the device activates only one of the column lines at a time ... it reads the status of the row lines to determine if any of the keys are pressed in the selected column .... your code has to determine which of the column lines is being read and it has to activate only one of the row lines for the duration of the time the column is being addressed

I am not looking for advice or explanation on how keyboard matrix works or how to program it, it's textbook simple. I am trying to implement a crossbar-matrix multiplexer with Arduino. The keyboard matrix was just an example to illustrate the idea, forget the keyboard matrix. :) The actual quesion is about pinMode() behavior and why changing pin state to OUTPUT somehow affects other pins.

The difficulty is in the internal circuitry of the AVR, I don't think that your idea will work. So this is more an X-Y-problem.-- Would you mind to [edit] your question and add some timing information, please? Did you measure the times the device activates its scanning outputs? A diagram of a complete cycle would be optimal. And did you measure the times your program needs? Hint: the standard Arduino library's pin function are quite slow because of the "universal" pin numbers.

Thanks for elaborating, actually, I am talking about ZX Spectrum keyboard, the outputs are address lines of the Z80 CPU. Many people attempted doing it programmatically already, the Atmega 328 is not fast enough. It will work if Xtal is replaced by 24 Mhz, also using interrupt to read the IORQ line (which is active exactly when the CPU reads the keyaboard). What I'm trying to do here is achieve all this with bare Arduino. Just trying to find new simpler ways. Apparently the best way to do it is use a bunch of CD4051BE's.

How fast would be fast enough?   What do you mean by "the neighboring pins somehow get activated too"  Maybe they need some small physical pull-up resistors? You could speed things up by writing to your row pins in parallel with PORTC/DDRC/PINC and reading in parallel using PIND & PINB.  Changing the pinMode on A0-A4 to OUTPUT,  or not is just fiddling with bits in DDRC and PORTC -- see https://arduino.stackexchange.com/a/81338/6628 and https://arduino.stackexchange.com/a/22985/6628

I have no certainty about what is happening, but I suspect you are
seeing the effects of the input clamping diodes. Each digital pin has
clamping diodes that keep its potential between GND and Vcc, ±the diode
threshold.

As long as all pins are set to INPUT, they can freely float with
respect to one another, provided the potential differences stay within
Vcc+2×diode_threshold.

When you set one pin to OUPUT LOW, you are tying to to GND. The
other pins can still float above this one, but only very slightly
below it. The clamping diodes provide unidirectional current paths
from this pin (which is now GND) to every other pin.

Yes, that must be it. Any idea how to get around it, please? Maybe add external diodes to create voltage offset?

@JimmyFalcon: Sorry, but no idea. Connecting nodes to GND of a floating IC is a very unconventional way of achieving electrical contact.


text:
Do I need to use resisters and ICes for specific sensors.What if I dont use it,Will it impact my arduino board some how like making it useless &faulty
So I was reading about Simple AutomaticLight Controller using LDR. or with the help of LDRSenso. But I have LM393 Photoresistor (LDR) Sensor I like to know are they same thing or somewhat different. So the way they work is detecting
light intensity and It is associated with both analog output pin and digital output pin labelled as AO and DO respectively on the board.When there is light, the resistance of LDR will become low according to the intensity of light. The greater the intensity of light, the lower the resistance of LDR.
And before that I was reading about Analog Piezoelectricity Ceramic Piezo Vibration Sensor For Arduino
So LDR sensor needs some kind of resister. And Analog Piezoelectricity Ceramic Vibration sensor needs some IC.
Can Anyone be specific to these specific resister and IC for each sensor types. I have them both as module for arduino Uno. I like to code in gcc avr. Thats how I am restricted. And will use C code to control but Can any please be briefly explain this type of resister for LDR sensor and Piezoelectric vibration sensor IC. Just few words to help me relate to some explanation and easily get poped in my mind when ever I hear about these two modules again. So Just some brief on this specific types of resister and IC related to these two modules why they needed how to code, and control through code
These are pictures of two sensors as Chrisl asked

https://www.daraz.pk/products/i140816069-s1300868385.html?urlFlag=true&mp=1
https://www.daraz.pk/products/i162290793-s1329534669.html?urlFlag=true&mp=1

If you need extra circuitry for a sensor depends on the exact sensor. Please provide a link to that exact product, that you have. Or - if there is no product link - then at least a few good photos of the used sensor/board and the part numbers, that might be printed on the boards or components.

@chrisl hi please check the sensor modules pictures I have posted

So you have a product page. Then please include the link to that product page in your question.

Both images, that you included, show breakout boards. They are circuit boards (PCB - Printed Circuit Board), which contain all the components, that are needed to connect the corresponding part (in your case a piezo and an Light Dependent Resistor (LDR)). They are called this way, because they are "breaking out" simple output pins from the sensor circuitry for directly connecting them to the Arduino. So instead of having to build the circuit with the pure components you have a simple board, which gives you standard pin headers for connecting to the your Arduino. They are also often called "modules".
That means, that you don't need any additional circuitry or ICs to connect these boards to the Arduino. For the piezo sensor the image even shows the wiring diagram. You can see there, that you don't need any additional parts besides the breakout board, piezo and the Arduino itself. The same applies for the LDR breakout board.
Connections:
For the piezo sensor you have an analog output. Thus you need to connect that to an analog input on the Arduino (A0 to A7) and read the signal with analogRead().
For the LDR breakout board I cannot be sure without a link to the product page, but it seems, that it has a digital output (DO). You can connect it to a digital input of the Arduino. It will switch between HIGH and LOW at a certain threshold brightness, which you can control by using a small screwdriver to rotate the little potentiometer on the board (the blue box with the hole in the middle).

can u please tell what is meant by breakout board. I have no clue. Are u refering breakout board to my sensor modules?

I have also posted product page link

@user786 I changed the description at the start of my answer to make it more clear.

Can u please tell last thing what is negative and positive electrodes on piezo sensor. Can I use screw driver for this too to control something?

@user786 The black wire of the piezo is ground. And no, you cannot set anything with a screwdriver here. You need to read the analog signal in your Arduino code. Then you can use your code to do a similar thing (doing something, when the read analog value is higher or lower than a specific threshold).

Can u also please tell what is ADC in analogRead that u mentioned. This function is not present in avr gcc. And I see the code from avr core it's very small function can u please add something on that too.

@user786 I'm not sure what you mean by that. The ADC is the Analog Digital Converter, the hardware that enables the Arduino to meaure analog voltages. When you don't want to use the Arduino framework (and thus analogRead()) you need to configure the ADC yourself directly by setting the corresponding registers. Refer to the datasheet of the Atmega328P (the microcontroller on the Arduino).


text:
Power requirements of a 7 Segment Display on Uno vs Nano
As part of a Simhub Dash set up I have been trying to get a 8 Digit 7 segment display working on an Arduino Nano. As part of my fault finding process I have gone back to basics and am using the 7CDemo7Segment example script included with the ledcontrol library . The 8x8Matrix Test is performed with the LCDemoMatrix example script. Both displays are powered by the 5v/Gnd pin combination.  No other devices are connected.
The following image shows the circuit.  Ignore pins (they are as described below) and Uno/Nano are interchangeable.

Completing the following tests I get the described results:

Uno and 7Seg with Pins 678 - OK - proof of library and display
Nano and 7Seg with Pins 678 - FAILS (nothing lights up and if it does it’s incoherent to what it should be going) - same code and display
Nano and 8x8 Matrix with Pins 678 - OK - proof of the Nano and Pins.

I feel the above combinations prove that: the script is correct; the display works; and that the pins are okay.
The only thing I can think is that this is a power/current issue via USB/5V pin?
Would someone be able to confirm.   I have looked at How much current can I draw from the Arduino's pins? and feel that there is not a clear answer for the Nano 5V pin.

With out a schematic we can only guess (or ask a lot of questions).  The Atmel328 processor can handle up to 40mA per pin.  But when you add all the current up you should stay below 200mA.  So, lets say your properly current limited LEDs are suppose to draw 5mA each.  Then, you should not turn on more than 40 on at the same time.  But I suspect you have other problems.  You might be trying to run multiple programs which use the same resources.  For example, you may have a limited number of timers and one program may overwrite the settings of another. Thereby ruining the other's LED control.

@st2000 I have tried to update the question without (hopefully) adding too much unnecessary detail.

So, there is only the 1 display?  Can you also identify the software library (or libraries) you are using?  From the wording in your question I though you had several different displays that worked independently but not together.

Honestly I don't think power is the issue. When powering via USB you should be able to draw the full 500mA, that the USB port gives you. Thats way enough for a normal 7 Seg display, even with 8 digits. Bit you can test this by connecting both Arduinos via USB and then connecting their ground and 5V. That doubles the available current

Please provide a link to the library that you are using

Power requirements of a 7 Segment Display on Uno vs Nano ... they would be the same

Does the voltage regulator on the Nano get hot?

What do you mean by "FAILS"? Please be more specific on the failure, what do you get instead of your expectation?

@st2000 Yes, eventually both should be connected but for the purposes of understanding this problem on a single display is connected

Thanks for answering.  Know this, loading up more than one library or loading up a library intended for a different processor can lead to difficulties.  For example, 2 libraries may try to configure the same timer, interrupt or processor pin.  Likely this will lead to unexpected results.  Can we assume you are loading up only the led control library?

Yes.  I’m using the built in library examples and just changing the pins as appropriate. In my mind it really could not be simpler.


text:
Is arduino a single board computer?
First excuse me if tags are not reflecting the content,
While watching a video about single board computer (SBC) I got confused that it doesn't mention arduino as SBC. I always considered it as SBC.
After digging around a bit I got more confused. It seems single board computer is where processor, memory, I/O this things are built on single circuit board rather than using expansion card attached on to a circuit board (motherboard).
According to that is not arduino a SBC? It's processor, memory,storage are on single ATMega32A (for uno) attached on a single board which provides some I/O port (I/O pin, USB, UART, I2C etc.).
From some digging I learned that arduino code runs on bare metal unlike SBC like Rpi and that's the reason for it not being SBC. This seems weird reason.
(1) Is Arduino a SBC?
If (1) is no then next questions are,
(2) Is Being less powerful is the cause? If yes where do you draw the line?
(3) Not having an OS hosted environment for execution is the cause?
If (3) is Yes then,
(4) Arduino has some bootloader code to load the program through USB. Isn't it  kinda like OS, I admit it's not giving some nice api for h/w usage but is it all?
This link comment section kind of started a debate but ended without giving clear answer about my question.

It may be impossible to draw a sharp line that separates single board
computers from microcontroller boards. There are, however, several
attributes that can help differentiate them and, in a sense, draw a
blurry line. If a specific board has most of the attributes of SBCs it's
probably safe to call it an SBC. Same for MCU boards.
Processing power may be one of those attributes. A typical SBC is many
orders of magnitude more powerful than your typical Arduino. A Raspberry
Pi, for example, has half a million times the RAM of an Arduino Uno.
Although you can find microcontrollers that are a thousand times more
powerful than the Uno, you are unlikely to find many SBCs that are one
hundred times less powerful than a Raspberry Pi.
The operating system may also be a factor. SBCs are typically meant to
run mainstream OSes: some flavor of Linux, Windows or Android.
Microcontrollers, on the other hand, will most often run some kind of
RTOS (real-time OS) specifically designed for the embedded world, if
they do run an OS at all.
A factor that has not been mentioned yet is the I/O capabilities. On an
SBC, you will typically find the kind of I/O ports that are common on
desktop or laptop computers, like HDMI, USB host or Ethernet. A
microcontroller, on the other hand, is more likely to have analog inputs
or outputs, as these are more useful in the “electronics” world than in
the “computer” world. Of course, the lines are blurry: you may find SPI,
I2C and GPIOs on both SBCs and MCUs.
Neither of those factors may be enough to tell an SBC apart from a MCU
board. But taken together, they can allow you to say that board A is
clearly an SBC, board B is clearly an MCU board, and board C is
somewhere in between and hard to classify.

The Arduino isn't a computer. It is a programmable microprocessor / microcontroller.
Generally a computer can run multiple applications where most programmed devices like the Arduino are running only one program. This is not an official definition but it is one way to differentiate.
It can be difficult to draw a line where it is one but not the other.

(4) Arduino has some bootloader code to load the program through USB.
  Isn't it kinda like OS, I admit it's not giving some nice api for h/w
  usage but is it all?

No that isn't like an operating system. The Arduino does not have a real operating system when compared to a computer system. And someone being able to load in a new program is just changing the current single program that is runnable.

An operating system (OS) is system software that manages computer
  hardware and software resources and provides common services for
computer programs.

I think the programs being plural is an important factor, but this is only my opinion.
There is no one definition so you will get a number of different opinions. And most will be reasonable.

It all depends on your definition of "computer".  From the point of view that the Arduino is a "Turing complete" architecture, with CPU, memory, storage, IO, etc, then yes, it is a computer. But it's not a "computer" as in what you have on your desk.
Is a mobile phone a "computer"?
We can shift the definition elsewhere if you like:
In general an SBC is taken to be a SoC mounted on a board with the support components.  A SoC is a "System on Chip".  But now we just move the definition to "What is a SoC?" - a question that has been asked many times before.
There is no one specific thing that divides a SoC from a Microcontroller. For instance:

"A SoC runs an operating system, but a Microcontroller doesn't" - except that there are microcontrollers that can and do run operating systems, and you don't have to run an operating system on a SoC.
"A SoC relies on external memory, but Microcontrollers have it built in" - except that there are SoCs with built in memory, and Microcontrollers than need external memory to function

The list goes on.
My definition of what constitutes a "computer" as opposed to an "embedded system" has nothing to do with what the device is, it's what you do with it.
If the board is being used with a keyboard, mouse, screen, etc for generic operation then it's a computer. If it's being programmed for one specific task then it's an embedded system.  The same hardware could be used in both ways, and I would call it a computer if it were running "general" software (operating system, web browser, server software, etc), but I'd call it an "embedded system" if it were running one program only (with or without an OS) gathering data, reporting it back to a central system, etc.
For something to be termed a "Single Board Computer" I would say it has to be capable of running general software designed to run on a "traditional" computer.  Things like Linux with Apache etc, or a desktop environment.
Mind, this is only my opinion, and as such it will differ from other peoples' opinions.


text:
Interfacing with SPI
I am attempting to program an Arduino to interface with a DAC, specifically the AD7390 made by Analog Devices.
I have tried using the SPI library as a means of realising the interface but am confused by the PIN layout of the DAC. It provides me with SCK, SDI, CLR and LD pins.
The LD (Load Strobe) PIN is used to transfer buffers from the chip's on-board shift register to its DAC register.
The CLR PIN is used to forcibly clear the DAC register.
The documentation claims that the device is SPI compatible but, using these PINs with the Arduino Mega2560 as a micro-controller, only partially works and I am concerned that the circuit requirements of the SPI library are not being satisfied. In SPI documentation, a SS (slave select) PIN is universally mentioned but is not present with my device.
As I have managed to get the CLR PIN working, consistently and as expected, I wonder if a manual approach - i.e. using shiftIn() instead of the SPI library - is the way to go.
Any suggestions or advice would be appreciated.

The AD7390 data sheet timing diagrams show that /LD is in effect a slave select, but an active high one.
Specifically, it says that while /LD is high, each rising clock edge causes "Shift-Register-Data Advanced One-Bit", while when it is low, the shift register data is transferred to the DAC.
So basically you would need to use SPI in a mode where the slave select is controlled by software and asserted with the opposite of the usual polarity, but the actual shifting of the data can be accomplished with the hardware SPI engine.
It does not seem that you are always required to use the /CLR input - if you don't want to use it, wire it high.  Otherwise, you can connect it to a GPIO, take it low, and then raise it so that the rising edge causes an asynchronous clear.


text:
Can't read JSON data from client (webpage) with Arduino Leonardo ETH
I'm reading a digital pin and count how many times that pin is enable, after that the data is sent in JSON format. All is working well till here. But I want to introduce a value from webpage to arduino, so the arduino will know from what number it should count. I modified the webpage, I'm converting the value in JSON format, everything. But I can't get it on arduino. I see the value on Serial Monitor right before client disconnect. But I just cannot figure what I'm doing wrong, maybe you guys have a suggestion ?
Here is my Arduino code ( is a bit messy, and I haven't did the part were I tell to arduino the number where it should start to count, I will do that after i can get my numbers from webpage ). If needed i can also add the webpage code.
#include <SD.h>
#include <SPI.h>
#include <Ethernet2.h>
#include <ArduinoJson.h>

int pin = 3;
int state = 0;
//==========================
int push = 0;
//==========================
int laststate = 0;
const int chipS = 4;

byte mac[] = {0x00, 0x08, 0xDC, 0x1C, 0xB8, 0x4C}; // Enter the MAC address that is on your Ethernet shield (sticker) - eg. 00-08-DC-1C-B8-4C  (but use hexidecimal format eg. 0x00)
IPAddress ip(192, 168, 0, 88);                     // The IP address that you will give the Server - will depend on your local network range
EthernetServer server(8880);                       // The port to listen for Web Browsers - the default is 80, but some routers will block this port.. so change to 8081.

//*************************************************************************************************
// setup function
//=================================================================================================
void setup()
{
    Serial.begin(9600); // Begin Serial communication (baud rate = 9600).
    while (!Serial)
    {
        ; // wait for serial port to connect. Needed for Leonardo only
    }

    Ethernet.begin(mac, ip); // Initialise the ethernet library and network settings: https://www.arduino.cc/en/Reference/EthernetBegin
    server.begin();          // Tell the server to begin listening for incoming connections (on port 8081 in this example)
    Serial.print("Server IP address : ");
    Serial.println(Ethernet.localIP()); // If you see the IP address within the Serial monitor - you know that the server started successfully
    Serial.println(" ");

    // cardlaif  -  SD CARD INITALIZATION
    Serial.println("Initializare card...");
    if (!SD.begin(chipS))
    {
        Serial.println(" Initializarea cardului a esuat sau cardul lipseste ");
        while (1)
            ;
    }
    Serial.println(" Card initializat ");
    Serial.println(" ");
    pinMode(3, INPUT);
}

//*************************************************************************************************
// loop function
//=================================================================================================
void loop()
{
    //=====================================================================================================
    // contor  PIN 3 COUNTER
    //======================================================================================================
    state = digitalRead(pin);

    if (state != laststate)
    {
        if (state == HIGH)
        {
            push++;
        }
        delay(50);
    }
    laststate = state;

    Serial.print(" nr. citiri: ");
    Serial.println(push);
    //====================================================================================================
    // card SD CARD WRITE CODE
    //====================================================================================================
    String dataString = " ";
    dataString += String("nr. citiri: ");
    dataString += String(push);

    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile)
    {
        dataFile.println(dataString);
        dataFile.close();
    }
    else
    {
        Serial.println("error opening datalog.txt");
    }
    //========================================================================================================
    //    net
    //========================================================================================================
    EthernetClient client = server.available(); // assign any newly connected Web Browsers to the "client" variable.

    if (client.connected())
    {
        Serial.println("Client Connected");
        // char c = client.read();
        // Serial.print(c);
        while (client.available())
        {
            Serial.write(client.read()); // Uncomment if you want to write the request from the Browser (CLIENT) to the SERIAL MONITOR (and comment out the next line)
            // client.read();                               // This line will clear the communication buffer between the client and the server.
        }

        // Send the Server response header back to the browser.
        client.println(F("HTTP/1.1 200 OK"));                                                                                // This tells the browser that the request to provide data was accepted
                                                                                //    client.println("GET");
        client.println(F("Access-Control-Allow-Origin: *"));                                                                            // Tells the browser it has accepted its request for data from a different domain (origin).
        client.println(F("Access-Control-Allow-Methods:  GET,POST,PUT,DELETE,OPTIONS"));                                                // The arduino will accept JSON format data using this
        client.println(F("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")); // The arduino will accept JSON format data using this
        client.println(F("Content-Type: application/json;charset=utf-8"));                                                              // Lets the browser know that the data will be in a JSON format
        client.println(F("Server: Arduino"));                                                                                // The data is coming from an Arduino Web Server (this line can be omitted)
        client.println(F("Connection: close"));                                                                                // Will close the connection at the end of data transmission.
        client.println();                                                                                // You need to include this blank line - it tells the browser that it has reached the end of the Server reponse header.

        // Example Transmission: [{"key":0, "value":300},{"key":1, "value":320},{"key":2, "value":143},{"key":3, "value":24},{"key":4, "value":760},{"key":5, "value":470}]
        client.print("[");            // This is tha starting bracket of the JSON data
        client.print("{\"value\": "); // The value I read on pin 3 and send in JSON format to webpage
        client.print(push);           //  The value I read on pin 3 and send in JSON format to webpage
        client.print("}");            //  JSON things
        client.println("]");          // This is the final bracket of the JSON data
    }

    //=================================================================================================
    // trying to print on serial json data
    //=================================================================================================
    char json[] = "{\"index\" }";
    StaticJsonBuffer<300> jsonBuffer;
    JsonObject &root = jsonBuffer.createObject();
    if (!root.success())
    {
        Serial.println("Parsing failed");
    }
    int index = root["index"];
    Serial.print(" index: ");
    Serial.print(index);
    Serial.println(" ");

    client.stop();                       // This method terminates the connection to the client
    Serial.println("Client has closed"); // Print the message to the Serial monitor to indicate that the client connection has closed.
} // VOID LOOP END

And this is what I get on serial monitor:
Client Connected
POST / HTTP/1.1
Host: 192.168.0.88:8880
Connection: keep-alive
Content-Length: 1
Accept: application/json, text/javascript, */*; q=0.01
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
Content-Type: application/json; charset=UTF-8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,ro;q=0.8,es;q=0.7

5 index: 0

At the end, that 5 before the " index " word should be where the 0 is.
The 5 it's my JSON data. The reason why I see it it's because I enabled to see the reqest from the browser.
Someone have any idea ?
P.S Sorry for my bad english ^_^

Below, you create a static string, which is never used again.
char json[] = "{\"index\" }";

Here you create a buffer and instantiate an empty JsonObject.
StaticJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();

Here you check if root (your newly created JsonObject) is valid. Because it's empty and fresh, it is valid.
if (!root.success())
{
  Serial.println("Parsing failed");
}

Here, you try to ask for the value of index from your empty object.
int index = root["index"];
Serial.print(" index: ");
Serial.print(index);

If you never provide the JsonObject with any structure or content to parse, how can it give you anything back besides nothing?
The examples from the ArduinoJSON library prove to be helpful:
Documentation on parseObject

char json[] = "{\"hello\":\"world\"}";
StaticJsonBuffer<200> jsonBuffer;
JsonObject& object = jsonBuffer.parseObject(json);
const char* world = object["hello"];

Note the differences from what you are doing:

The initial JSON string to parse has both a key and a value.
The StaticJsonBuffer declaration includes a buffer size
The JsonObject declaration uses parseObject and passes in the json string, instead of creating a blank/empty object.